<commit_before>/* tasks uber example */

var fs = require('fs');
var http = require('http');
var querystring = require('querystring');

var g = {};
g.host = '0.0.0.0';
g.port = (process.env.PORT ? process.env.PORT : 8484);

/* internal test data */
g.list = [];
g.list[0] = {id:0,text:'this is some item'};
g.list[1] = {id:1,text:'this is another item'};
g.list[2] = {id:2,text:'this is one more item'};
g.list[3] = {id:3,text:'this is possibly an item'};

// main entry point
function handler(req, res) {

  var m = {};
  m.item = {};
  m.filter = '';

  // internal urls
  m.homeUrl = '/';
  m.listUrl = '/tasks/';
  m.scriptUrl = '/tasks.js';
  m.filterUrl = '/tasks/search';
  m.completeUrl = '/tasks/complete/';
  m.profileUrl = '/tasks-alps.xml';

  // media-type identifiers
  m.uberXml  = {'content-type':'application/xml'};
  m.textHtml = {'content-type':'text/html'};
  m.appJS = {'content-type':'application/javascript'};
  m.appXml = {'content-type':'application/xml'};

  // add support for CORS
  var headers = {
    'Content-Type' : 'application/xml',
    'Access-Control-Allow-Origin' : '*',
    'Access-Control-Allow-Methods' : '*',
    'Access-Control-Allow-Headers' : '*'
  };

  // hypermedia controls
  m.errorMessage = '<uber version="1.0"><error><data id="status">{status}</data><data id="message">{msg}</data></error></uber>';
  m.addControl = '<data id="add" rel="add" name="links" url="/tasks/" action="append" model="text={text}" />';
  m.filterControl = '<data id="search" rel="search" name="links" url="/tasks/search" action="read" model="?text={text}" />';
  m.listControl = '<data id="list" rel="collection" name="links" url="/tasks/" action="read" />';
  m.completeControl = '<data rel="complete" url="/tasks/complete/" model="id={id}" action="append" />';
  m.itemControl = '<data id="task{id}" rel="item" name="tasks">{complete}<data name="text">{text}</data></data>';
  m.profileControl = '<data id="alps" rel="profile" url="/tasks-alps.xml" action="read" />';

  // add support for CORS
  var headers = {
    'Content-Type' : 'application/json',
    'Access-Control-Allow-Origin' : '*',
    'Access-Control-Allow-Methods' : '*',
    'Access-Control-Allow-Headers' : '*'
  };

  main();

  /* process requests */
  function main() {
    var url;

    // check for a search query
    if(req.url.indexOf(m.filterUrl)!==-1) {
      url = m.filterUrl;
      m.filter = req.url.substring(m.filterUrl.length,255).replace('?text=','');
    }
    else {
      url = req.url;
    }

    // handle CORS OPTIONS call
    if(req.method==='OPTIONS') {
        var body = JSON.stringify(headers);
        showResponse(req, res, body, 200);
    }

    // process request
    switch(url) {
      case m.homeUrl:
        switch(req.method) {
          case 'GET':
            showHtml();
            break;
          default:
            showError(405, 'Method not allowed');
            break;
        }
        break;
      case m.scriptUrl:
        switch(req.method) {
          case 'GET':
            showScript();
            break;
          default:
            showError(405, 'Method not allowed');
            break;
        }
        break;
      case m.profileUrl:
        switch(req.method) {
          case 'GET':
            showProfile();
            break;
          default:
            showError(405, 'Method not allowed');
            break;
        }
        break;
      case m.listUrl:
        switch(req.method) {
          case 'GET':
            sendList();
            break;
          case 'POST':
            addToList();
            break;
          default:
            showError(405, 'Method not allowed');
            break;
        }
        break;
      case m.filterUrl:
        switch(req.method) {
          case 'GET':
            searchList();
            break;
          default:
            showError(405, 'Method not allowed');
            break;
        }
        break;
      case m.completeUrl:
        switch(req.method) {
          case 'POST':
            completeItem();
            break;
          default:
            showError(405, 'Method not allowed');
            break;
        }
        break;
      default:
        showError(404, 'Page not found');
        break;
    }
  }

  /*
    show list of items

    /tasks/

  */
  function sendList() {
    var msg, i, x;

    msg = makeUber(g.list,false);
    res.writeHead(200, 'OK', m.uberXml);
    res.end(msg);
  }

  /*
     search the list

     /tasks/search?text={text}

  */
  function searchList() {
    var coll, i, x, msg;

    coll = [];
    for(i=0,x=g.list.length;i<x;i++) {
      if(g.list[i].text.indexOf(m.filter)!==-1) {
        coll.push(g.list[i]);
      }
    }

    msg = makeUber(coll,true);
    res.writeHead(200, 'OK', m.uberXml);
    res.end(msg);
  }

  /*
     add item to list

     /tasks/
     text={text}

  */
  function addToList() {
    var body = '';

    req.on('data', function(chunk) {
      body += chunk.toString();
    });

    req.on('end', function() {
      m.item = querystring.parse(body);
      sendAdd();
    });
  }
  function sendAdd() {
    var item;

    item = {};
    item.id = g.list.length;
    item.text = m.item.text;
    g.list.push(item);

    res.writeHead(204, "No content");
    res.end();
  }

  /*
     complete single item

     /tasks/complete/
     id={id}

  */
  function completeItem() {
    var body = '';

    req.on('data', function(chunk) {
      body += chunk.toString();
    });

    req.on('end', function() {
      m.item = querystring.parse(body);
      sendComplete();
    });
  }
  function sendComplete() {
    var tlist, i, x;

    //build new list
    tlist = [];
    for(i=0,x=g.list.length;i<x;i++) {
      if(g.list[i].id!=m.item.id) {
        tlist.push(g.list[i]);
      }
    }
    g.list = tlist.slice(0);

    res.writeHead(204, "No content");
    res.end();
  }

  /* generate uber representation */
  function makeUber(list, showControls) {
    var i, x, msg;

    msg  = '<uber version="1.0">';
    msg += '<data id="links">';
    msg += m.profileControl
    if(list.length>0 || showControls===true) {
      msg += m.listControl;
      msg += m.filterControl;
    }
    msg += m.addControl;
    msg += '</data>';

    msg += '<data id="tasks">';
    for(i=0,x=list.length;i<x;i++) {
      msg += m.itemControl.replace("{complete}",m.completeControl).replace(/{id}/gi,list[i].id).replace(/{text}/gi,list[i].text);
    }
    msg += '</data>';
    msg += '</uber>';

    return msg;
  }

  /* show html page */
  function showHtml() {
    fs.readFile('index.html', 'ascii', sendHtml);
  }
  function sendHtml(err, data) {
    if (err) {
      showError(500, err.message);
    }
    else {
      res.writeHead(200, "OK",m.textHtml);
      res.end(data);
    }
  }

  /* show script file */
  function showScript() {
    fs.readFile('tasks.js', 'ascii', sendScript);
  }
  function sendScript(err, data) {
    if (err) {
      showError(500, err.message);
    }
    else {
      res.writeHead(200, "OK",m.appJS);
      res.end(data);
    }
  }

  /* show profile document */
  function showProfile() {
    fs.readFile('tasks-alps.xml', 'ascii', sendProfile);
  }
  function sendProfile(err, data) {
    if (err) {
      showError(500, err.message);
    }
    else {
      res.writeHead(200, "OK",m.appXml);
      res.end(data);
    }
  }

  /* show error page */
  function showError(status, msg) {
    res.writeHead(status, msg, m.uberXml);
    res.end(m.errorMessage.replace('{status}', status).replace('{msg}', msg));
  }
}

// return response to caller
function showResponse(req, res, body, code) {
    res.writeHead(code,headers);
    res.end(body);
}

// listen for requests
http.createServer(handler).listen(g.port, g.host);

// ***** END OF FILE *****

<commit_msg>Use proper UBER XML Content-Type for responses.<commit_after>/* tasks uber example */

var fs = require('fs');
var http = require('http');
var querystring = require('querystring');

var g = {};
g.host = '0.0.0.0';
g.port = (process.env.PORT ? process.env.PORT : 8484);

/* internal test data */
g.list = [];
g.list[0] = {id:0,text:'this is some item'};
g.list[1] = {id:1,text:'this is another item'};
g.list[2] = {id:2,text:'this is one more item'};
g.list[3] = {id:3,text:'this is possibly an item'};

// main entry point
function handler(req, res) {

  var m = {};
  m.item = {};
  m.filter = '';

  // internal urls
  m.homeUrl = '/';
  m.listUrl = '/tasks/';
  m.scriptUrl = '/tasks.js';
  m.filterUrl = '/tasks/search';
  m.completeUrl = '/tasks/complete/';
  m.profileUrl = '/tasks-alps.xml';

  // media-type identifiers
  m.uberXml  = {'content-type':'application/vnd.uber+xml'};
  m.textHtml = {'content-type':'text/html'};
  m.appJS = {'content-type':'application/javascript'};
  m.appXml = {'content-type':'application/xml'};

  // add support for CORS
  var headers = {
    'Content-Type' : 'application/xml',
    'Access-Control-Allow-Origin' : '*',
    'Access-Control-Allow-Methods' : '*',
    'Access-Control-Allow-Headers' : '*'
  };

  // hypermedia controls
  m.errorMessage = '<uber version="1.0"><error><data id="status">{status}</data><data id="message">{msg}</data></error></uber>';
  m.addControl = '<data id="add" rel="add" name="links" url="/tasks/" action="append" model="text={text}" />';
  m.filterControl = '<data id="search" rel="search" name="links" url="/tasks/search" action="read" model="?text={text}" />';
  m.listControl = '<data id="list" rel="collection" name="links" url="/tasks/" action="read" />';
  m.completeControl = '<data rel="complete" url="/tasks/complete/" model="id={id}" action="append" />';
  m.itemControl = '<data id="task{id}" rel="item" name="tasks">{complete}<data name="text">{text}</data></data>';
  m.profileControl = '<data id="alps" rel="profile" url="/tasks-alps.xml" action="read" />';

  // add support for CORS
  var headers = {
    'Content-Type' : 'application/json',
    'Access-Control-Allow-Origin' : '*',
    'Access-Control-Allow-Methods' : '*',
    'Access-Control-Allow-Headers' : '*'
  };

  main();

  /* process requests */
  function main() {
    var url;

    // check for a search query
    if(req.url.indexOf(m.filterUrl)!==-1) {
      url = m.filterUrl;
      m.filter = req.url.substring(m.filterUrl.length,255).replace('?text=','');
    }
    else {
      url = req.url;
    }

    // handle CORS OPTIONS call
    if(req.method==='OPTIONS') {
        var body = JSON.stringify(headers);
        showResponse(req, res, body, 200);
    }

    // process request
    switch(url) {
      case m.homeUrl:
        switch(req.method) {
          case 'GET':
            showHtml();
            break;
          default:
            showError(405, 'Method not allowed');
            break;
        }
        break;
      case m.scriptUrl:
        switch(req.method) {
          case 'GET':
            showScript();
            break;
          default:
            showError(405, 'Method not allowed');
            break;
        }
        break;
      case m.profileUrl:
        switch(req.method) {
          case 'GET':
            showProfile();
            break;
          default:
            showError(405, 'Method not allowed');
            break;
        }
        break;
      case m.listUrl:
        switch(req.method) {
          case 'GET':
            sendList();
            break;
          case 'POST':
            addToList();
            break;
          default:
            showError(405, 'Method not allowed');
            break;
        }
        break;
      case m.filterUrl:
        switch(req.method) {
          case 'GET':
            searchList();
            break;
          default:
            showError(405, 'Method not allowed');
            break;
        }
        break;
      case m.completeUrl:
        switch(req.method) {
          case 'POST':
            completeItem();
            break;
          default:
            showError(405, 'Method not allowed');
            break;
        }
        break;
      default:
        showError(404, 'Page not found');
        break;
    }
  }

  /*
    show list of items

    /tasks/

  */
  function sendList() {
    var msg, i, x;

    msg = makeUber(g.list,false);
    res.writeHead(200, 'OK', m.uberXml);
    res.end(msg);
  }

  /*
     search the list

     /tasks/search?text={text}

  */
  function searchList() {
    var coll, i, x, msg;

    coll = [];
    for(i=0,x=g.list.length;i<x;i++) {
      if(g.list[i].text.indexOf(m.filter)!==-1) {
        coll.push(g.list[i]);
      }
    }

    msg = makeUber(coll,true);
    res.writeHead(200, 'OK', m.uberXml);
    res.end(msg);
  }

  /*
     add item to list

     /tasks/
     text={text}

  */
  function addToList() {
    var body = '';

    req.on('data', function(chunk) {
      body += chunk.toString();
    });

    req.on('end', function() {
      m.item = querystring.parse(body);
      sendAdd();
    });
  }
  function sendAdd() {
    var item;

    item = {};
    item.id = g.list.length;
    item.text = m.item.text;
    g.list.push(item);

    res.writeHead(204, "No content");
    res.end();
  }

  /*
     complete single item

     /tasks/complete/
     id={id}

  */
  function completeItem() {
    var body = '';

    req.on('data', function(chunk) {
      body += chunk.toString();
    });

    req.on('end', function() {
      m.item = querystring.parse(body);
      sendComplete();
    });
  }
  function sendComplete() {
    var tlist, i, x;

    //build new list
    tlist = [];
    for(i=0,x=g.list.length;i<x;i++) {
      if(g.list[i].id!=m.item.id) {
        tlist.push(g.list[i]);
      }
    }
    g.list = tlist.slice(0);

    res.writeHead(204, "No content");
    res.end();
  }

  /* generate uber representation */
  function makeUber(list, showControls) {
    var i, x, msg;

    msg  = '<uber version="1.0">';
    msg += '<data id="links">';
    msg += m.profileControl
    if(list.length>0 || showControls===true) {
      msg += m.listControl;
      msg += m.filterControl;
    }
    msg += m.addControl;
    msg += '</data>';

    msg += '<data id="tasks">';
    for(i=0,x=list.length;i<x;i++) {
      msg += m.itemControl.replace("{complete}",m.completeControl).replace(/{id}/gi,list[i].id).replace(/{text}/gi,list[i].text);
    }
    msg += '</data>';
    msg += '</uber>';

    return msg;
  }

  /* show html page */
  function showHtml() {
    fs.readFile('index.html', 'ascii', sendHtml);
  }
  function sendHtml(err, data) {
    if (err) {
      showError(500, err.message);
    }
    else {
      res.writeHead(200, "OK",m.textHtml);
      res.end(data);
    }
  }

  /* show script file */
  function showScript() {
    fs.readFile('tasks.js', 'ascii', sendScript);
  }
  function sendScript(err, data) {
    if (err) {
      showError(500, err.message);
    }
    else {
      res.writeHead(200, "OK",m.appJS);
      res.end(data);
    }
  }

  /* show profile document */
  function showProfile() {
    fs.readFile('tasks-alps.xml', 'ascii', sendProfile);
  }
  function sendProfile(err, data) {
    if (err) {
      showError(500, err.message);
    }
    else {
      res.writeHead(200, "OK",m.appXml);
      res.end(data);
    }
  }

  /* show error page */
  function showError(status, msg) {
    res.writeHead(status, msg, m.uberXml);
    res.end(m.errorMessage.replace('{status}', status).replace('{msg}', msg));
  }
}

// return response to caller
function showResponse(req, res, body, code) {
    res.writeHead(code,headers);
    res.end(body);
}

// listen for requests
http.createServer(handler).listen(g.port, g.host);

// ***** END OF FILE *****

<|endoftext|>


<commit_before>/*
 * grunt-kmc
 * https://github.com/daxingplay/grunt-kmc
 *
 * Copyright (c) 2013 daxingplay
 * Licensed under the MIT license.
 */

'use strict';

var kmc = require('kmc'),
	fs = require('fs'),
    path = require('path'),
    os = require('os');

module.exports = function (grunt) {

    // Please see the Grunt documentation for more information regarding task
    // creation: http://gruntjs.com/creating-tasks

    grunt.registerMultiTask('kmc', 'Build KISSY modules.', function () {
        // Merge task-specific and/or target-specific options with these defaults.
        var options = this.options(),
            depExt = options.depExt,
            depFilePath = options.depFilePath,
            comboOnly = options.comboOnly,
            depFileCharset = options.depFileCharset || options.charset,
            fixModuleName = options.fixModuleName === true,
            fixModuleNameOnDest = options.copyAssets === true,
			// 当 comboOnly 为 false（需要静态合并）时，将被合并入主文件的kmd文件删除
			cleanUp = options.cleanUp === true,
            traverse = options.traverse,
			// 如果comboOnly为false并且执行清理无用文件，则css也执行静态合并
			/* //a.js
			 * add({
			 * 		'a.css'
			 * });
			 * //b.js
			 * add({
			 *		'b.css'
			 * });
			 * 构建后
			 * //a.js
			 * add('a',{
			 *		'a.css' //a.css执行了合并
			 * });
			 * add('b',{ //b.css在依赖中被清空
			 * });
			 * */
			comboCss = ((comboOnly === false) && (cleanUp === true)),
            wrap = options.wrap || 'KISSY.config';

		// 被合并入主文件的kmd文件列表
		var combinedFiles = [];
		// src中指定的需要合并的入口文件列表
		var retainFiles = [];
		// 模块依赖全表
		var astMods = {};

		// added by jayli 2014-10-2
		// 从依赖的文件目录数组得到绝对地址数组
		var getResolvedFiles = function(a,dest){
			var result = [];
			//console.log(a);
			var moduleName;
			var outputFile= path.resolve(String(dest));
			var destRoot;
			a.forEach(function(item){
				for(var i in kmc._config.pkgs){
					if(item.indexOf(i) === 0){
						moduleName = i;
						break;
					}
				}
				// h5-test/widgets/calendar/index => /widgets/calendar/index
				var tname = item.replace(new RegExp('^'+moduleName,'i'),'');
				if(outputFile.indexOf(item)){
					destRoot = outputFile.replace(tname,'').replace(/\.js$/i,'');
					return false;
				}
			});
			a.forEach(function(item){
				for(var i in kmc._config.pkgs){
					if(item.indexOf(i) === 0){
						moduleName = i;
						break;
					}
				}
				// h5-test/widgets/calendar/index => ./widgets/calendar/index
				var rpath = item.replace(new RegExp('^'+moduleName,'i'),'.');
				if(!/\.(js|css)$/.test(rpath)){
					// 没有后缀，默认是js文件
					rpath += '.js';
				}
				//console.log('xxxx'+dest);
				result.push(path.resolve(destRoot,rpath));
			});
			return result;
		};

        kmc.config(options);

        // Iterate over all specified file groups.
        var results = [];
        this.files.forEach(function (f) {
            f.src.forEach(function(src){
                var depFile = '',
                    inputSrc = path.resolve(src),
                    outputSrc = path.resolve(String(f.dest));
                if(depExt || depFilePath){
                    depExt = depExt || '.dep';
                    var outputIsDir = grunt.file.isDir(outputSrc) || !/\.js$/.test(outputSrc);
                    if(depFilePath){
                        if(grunt.file.isDir(depFilePath) || !/.js$/.test(depFilePath)){
                            depFile = path.resolve(depFilePath, path.basename(outputIsDir ? path.basename(inputSrc, '.js') :outputSrc) + depExt + '.js');
                        }else{
                            depFile = depFilePath;
                        }
                    }else{
                        var dir = outputIsDir ? outputSrc : path.dirname(outputSrc);
                        depFile = path.resolve(dir, path.basename(inputSrc, '.js') + depExt + '.js');
                    }
                }
                var result = '';
                if(comboOnly === true){
                    var outputDir = grunt.file.isDir(outputSrc) ? outputSrc : path.dirname(outputSrc);
					var r = kmc.combo(inputSrc, options.comboMap !== true ? depFile : undefined, depFileCharset, fixModuleName, true, fixModuleNameOnDest ? outputDir : null,comboOnly === true);
					results.push(r);
                    options.comboMap !== true && grunt.log.ok('Dep File "' + depFile + '" created.');
                }else{
					console.log(inputSrc);
                    result = kmc.build(inputSrc, outputSrc, null, depFile, traverse);
                    results.push(result);
					combinedFiles = combinedFiles.concat(getResolvedFiles(result.files[0].combined,f.dest));
					retainFiles.push(outputSrc);
					try{
						mix(astMods,result.files[0].modules);
					}catch(e){}
                    grunt.log.ok('File "' + result.files[0].outputFile + '" created.');
                }

            });
        });

		// added by jayli 2014-10-2
		if(options.comboOnly === false && options.cleanUp === true){
			// 清理js无用的依赖文件
			combinedFiles.forEach(function(item){
				if(retainFiles.indexOf(item) < 0){
					try {
						fs.unlinkSync(item);
					} catch(e){
					}
					grunt.log.ok('clean Up files: '+ item);
				}
			});
			// 合并并清理css无用的依赖文件
			console.log('-----------------------'.blue);
			kmcCssParser(astMods,combinedFiles,retainFiles);
		}

        if(options.comboMap === true){
            var content = [];
            var writed = [];
            results.forEach(function(result){
                if(result.modules){
                    for(var modName in result.modules){
                        if(writed.indexOf(modName) === -1){
                            var mod = result.modules[modName];
                            var requires = [];
                            if(mod && mod.dependencies && mod.dependencies.length){
                                mod.dependencies.forEach(function(subMod){
                                    requires.push("'" + subMod.name + "'");
                                });
                                content.push("'" + modName + "': { requires: [" + requires.join(', ') + "]}");
                            }
                            writed.push(modName);
                        }
                    }
                }
            });
            var r = '/*generated by KMC*/' + os.EOL;
            if(content.length){
                r += wrap + "('modules', {" + os.EOL + " " + content.join("," + os.EOL + " ") + " " + os.EOL + "});";
            }
            grunt.file.write(options.depFilePath, r, {'encoding':'utf8'});
            grunt.log.ok('combined dependency file ' + options.depFilePath + ' created.');
		}
    });

};

function mix(r,o){
	for(var i in o){
		r[i] = o[i];
	}
}

function kmcCssParser(astMods,combinedFiles,retainFiles){

	for(var i in astMods){
		console.log(i.blue);
	}

	retainFiles.forEach(function(item){
		var modName = getTempModuleName(item);
		var mod = {};// 得到当前mod
		var subCssMods = {}; // 得到当前mod下辖的css文件
		var hasCss = false; // flag
		for(var i in astMods){
			if(getTempModuleName(i) === modName){
				mod = astMods[i];
				break;
			}
		}
		if(mod.modules === null){
			return true;
		}
		for(var j in mod.modules){
			if(/\.css$/i.test(j)){
				subCssMods[j] = getTempModuleName(j);
				hasCss = true;
			}
		}
		if(hasCss === false){
			return true;
		}
		console.log('---------------------'.red);
		console.log(item);
		console.log(subCssMods);
	});

}

// 只支持pages和widgets里的css合并
// /User/bachi/ttt/h5-car/src/pages/search/index.js  => pages/search/index
// /User/bachi/ttt/h5-car/src/widgets/pad/index  => pages/search/index
function getTempModuleName(str){
	var modName = str.match(/(pages|mods|widgets)\/[^\/]+\/[^\/]+$/i);
	if(modName !==  null && modName.length >=0){
		modName = modName[0].replace(/\.js$/i,'');
	} else {
		return false;
	}
	return modName;
}
<commit_msg>临时提交文件<commit_after>/*
 * grunt-kmc
 * https://github.com/daxingplay/grunt-kmc
 *
 * Copyright (c) 2013 daxingplay
 * Licensed under the MIT license.
 */

'use strict';

var kmc = require('kmc'),
	fs = require('fs'),
    path = require('path'),
    os = require('os');

module.exports = function (grunt) {

    // Please see the Grunt documentation for more information regarding task
    // creation: http://gruntjs.com/creating-tasks

    grunt.registerMultiTask('kmc', 'Build KISSY modules.', function () {
        // Merge task-specific and/or target-specific options with these defaults.
        var options = this.options(),
            depExt = options.depExt,
            depFilePath = options.depFilePath,
            comboOnly = options.comboOnly,
            depFileCharset = options.depFileCharset || options.charset,
            fixModuleName = options.fixModuleName === true,
            fixModuleNameOnDest = options.copyAssets === true,
			// 当 comboOnly 为 false（需要静态合并）时，将被合并入主文件的kmd文件删除
			cleanUp = options.cleanUp === true,
            traverse = options.traverse,
			// 如果comboOnly为false并且执行清理无用文件，则css也执行静态合并
			/* //a.js
			 * add({
			 * 		'a.css'
			 * });
			 * //b.js
			 * add({
			 *		'b.css'
			 * });
			 * 构建后
			 * //a.js
			 * add('a',{
			 *		'a.css' //a.css执行了合并
			 * });
			 * add('b',{ //b.css在依赖中被清空
			 * });
			 * */
			comboCss = ((comboOnly === false) && (cleanUp === true)),
            wrap = options.wrap || 'KISSY.config';

		// 被合并入主文件的kmd文件列表
		var combinedFiles = [];
		// src中指定的需要合并的入口文件列表
		var retainFiles = [];
		// 模块依赖全表
		var astMods = {};

		// added by jayli 2014-10-2
		// 从依赖的文件目录数组得到绝对地址数组
		var getResolvedFiles = function(a,dest){
			var result = [];
			//console.log(a);
			var moduleName;
			var outputFile= path.resolve(String(dest));
			var destRoot;
			a.forEach(function(item){
				for(var i in kmc._config.pkgs){
					if(item.indexOf(i) === 0){
						moduleName = i;
						break;
					}
				}
				// h5-test/widgets/calendar/index => /widgets/calendar/index
				var tname = item.replace(new RegExp('^'+moduleName,'i'),'');
				if(outputFile.indexOf(item)){
					destRoot = outputFile.replace(tname,'').replace(/\.js$/i,'');
					return false;
				}
			});
			a.forEach(function(item){
				for(var i in kmc._config.pkgs){
					if(item.indexOf(i) === 0){
						moduleName = i;
						break;
					}
				}
				// h5-test/widgets/calendar/index => ./widgets/calendar/index
				var rpath = item.replace(new RegExp('^'+moduleName,'i'),'.');
				if(!/\.(js|css)$/.test(rpath)){
					// 没有后缀，默认是js文件
					rpath += '.js';
				}
				//console.log('xxxx'+dest);
				result.push(path.resolve(destRoot,rpath));
			});
			return result;
		};

        kmc.config(options);

        // Iterate over all specified file groups.
        var results = [];
        this.files.forEach(function (f) {
            f.src.forEach(function(src){
                var depFile = '',
                    inputSrc = path.resolve(src),
                    outputSrc = path.resolve(String(f.dest));
                if(depExt || depFilePath){
                    depExt = depExt || '.dep';
                    var outputIsDir = grunt.file.isDir(outputSrc) || !/\.js$/.test(outputSrc);
                    if(depFilePath){
                        if(grunt.file.isDir(depFilePath) || !/.js$/.test(depFilePath)){
                            depFile = path.resolve(depFilePath, path.basename(outputIsDir ? path.basename(inputSrc, '.js') :outputSrc) + depExt + '.js');
                        }else{
                            depFile = depFilePath;
                        }
                    }else{
                        var dir = outputIsDir ? outputSrc : path.dirname(outputSrc);
                        depFile = path.resolve(dir, path.basename(inputSrc, '.js') + depExt + '.js');
                    }
                }
                var result = '';
                if(comboOnly === true){
                    var outputDir = grunt.file.isDir(outputSrc) ? outputSrc : path.dirname(outputSrc);
					var r = kmc.combo(inputSrc, options.comboMap !== true ? depFile : undefined, depFileCharset, fixModuleName, true, fixModuleNameOnDest ? outputDir : null,comboOnly === true);
					results.push(r);
                    options.comboMap !== true && grunt.log.ok('Dep File "' + depFile + '" created.');
                }else{
					console.log(inputSrc);
                    result = kmc.build(inputSrc, outputSrc, null, depFile, traverse);
                    results.push(result);
					combinedFiles = combinedFiles.concat(getResolvedFiles(result.files[0].combined,f.dest));
					retainFiles.push(outputSrc);
					try{
						mix(astMods,result.files[0].modules);
					}catch(e){}
                    grunt.log.ok('File "' + result.files[0].outputFile + '" created.');
                }

            });
        });

		// added by jayli 2014-10-2
		if(options.comboOnly === false && options.cleanUp === true){
			// 清理js无用的依赖文件
			combinedFiles.forEach(function(item){
				if(retainFiles.indexOf(item) < 0){
					try {
						fs.unlinkSync(item);
					} catch(e){
					}
					grunt.log.ok('clean Up files: '+ item);
				}
			});
			// 合并并清理css无用的依赖文件
			console.log('-----------------------'.blue);
			kmcCssParser(astMods,combinedFiles,retainFiles);
		}

        if(options.comboMap === true){
            var content = [];
            var writed = [];
            results.forEach(function(result){
                if(result.modules){
                    for(var modName in result.modules){
                        if(writed.indexOf(modName) === -1){
                            var mod = result.modules[modName];
                            var requires = [];
                            if(mod && mod.dependencies && mod.dependencies.length){
                                mod.dependencies.forEach(function(subMod){
                                    requires.push("'" + subMod.name + "'");
                                });
                                content.push("'" + modName + "': { requires: [" + requires.join(', ') + "]}");
                            }
                            writed.push(modName);
                        }
                    }
                }
            });
            var r = '/*generated by KMC*/' + os.EOL;
            if(content.length){
                r += wrap + "('modules', {" + os.EOL + " " + content.join("," + os.EOL + " ") + " " + os.EOL + "});";
            }
            grunt.file.write(options.depFilePath, r, {'encoding':'utf8'});
            grunt.log.ok('combined dependency file ' + options.depFilePath + ' created.');
		}
    });

};

function mix(r,o){
	for(var i in o){
		r[i] = o[i];
	}
}

function kmcCssParser(astMods,combinedFiles,retainFiles){

	for(var i in astMods){
		console.log(i.blue);
	}

	retainFiles.forEach(function(item){
		var modName = getTempModuleName(item);
		var mod = {};// 得到当前mod
		var subCssMods = {}; // 得到当前mod下辖的css文件
		var hasCss = false; // flag
		var combinedFileContent = '';//合并后的css文件内容
		var pickOneCss = '';// 要合并的cssfile地址
		for(var i in astMods){
			if(getTempModuleName(i) === modName){
				mod = astMods[i];
				break;
			}
		}
		if(mod.modules === null){
			return true;
		}
		for(var j in mod.modules){
			if(/\.css$/i.test(j)){
				subCssMods[j] = getCssFullPath(mod,j);
				hasCss = true;
			}
		}
		if(hasCss === false){
			return true;
		}
		console.log('---------------------'.red);
		for(var f in subCssMods){
			pickOneCss = subCssMods[f];
			combinedFileContent += fs.readFileSync(subCssMods[f],{
				encoding:'utf8'
			});
		}
		kmcCss(pickOneCss,combinedFileContent,item);
		// console.log(mod);
	});

}

// 只支持pages和widgets里的css合并
// /User/bachi/ttt/h5-car/src/pages/search/index.js  => pages/search/index
// /User/bachi/ttt/h5-car/src/widgets/pad/index  => pages/search/index
function getTempModuleName(str){
	var modName = str.match(/(pages|mods|widgets)\/[^\/]+\/[^\/]+$/i);
	if(modName !==  null && modName.length >=0){
		modName = modName[0].replace(/\.js$/i,'');
	} else {
		return false;
	}
	return modName;
}

function getCssFullPath(mod,k){
	return mod.modules[k].path;
}

// 将cssFile之外的css引用从combinedJsFile中删除
// cssFile写入content的内容
function kmcCss(cssFile,cssContent,combinedJSFile){
	console.log(combinedJSFile);
	var jsContent = fs.readFileSync(combinedJSFile,{encoding:'utf8'});
	// TODO:把jsContent里的requires里的对css的引用删除只剩下一个

}
<|endoftext|>


<commit_before>var React = require('react');
var ReactNative = require('react-native');
var {
  StyleSheet,
} = ReactNative;

var Style = StyleSheet.create({
  radioForm: {
  },

  radioWrap: {
    flexDirection: 'row',
    alignItems: 'center',
    alignSelf: 'center',
    marginBottom: 5,
  },
  radio: {
    justifyContent: 'center',
    alignItems: 'center',

    width: 30,
    height: 30,

    alignSelf: 'center',

    borderColor: '#2196f3',
    borderRadius: 30,
  },

  radioLabel: {
    paddingLeft: 10,
    lineHeight: 20,
  },

  radioNormal: {
    borderRadius: 10,
  },

  radioActive: {
    width: 20,
    height: 20,
    backgroundColor: '#2196f3',
  },

  labelWrapStyle: {
    flexGrow: 1,
    flexDirection: 'row',
    alignItems: 'center',
    alignSelf: 'center'
  },

  labelVerticalWrap: {
    flexDirection: 'column',
    paddingLeft: 10,
  },

  labelVertical: {
    paddingLeft: 0,
  },

  formHorizontal: {
    flexDirection: 'row',
  },
});

module.exports = Style;
<commit_msg>add compatibility for 0.42.x<commit_after>var React = require('react');
var ReactNative = require('react-native');
var {
  StyleSheet,
} = ReactNative;

var Style = StyleSheet.create({
  radioForm: {
  },

  radioWrap: {
    flexDirection: 'row',
    alignItems: 'center',
    alignSelf: 'center',
    marginBottom: 5,
  },
  radio: {
    justifyContent: 'center',
    alignItems: 'center',

    width: 30,
    height: 30,

    alignSelf: 'center',

    borderColor: '#2196f3',
    borderRadius: 30,
  },

  radioLabel: {
    paddingLeft: 10,
    lineHeight: 20,
  },

  radioNormal: {
    borderRadius: 10,
  },

  radioActive: {
    width: 20,
    height: 20,
    backgroundColor: '#2196f3',
  },

  labelWrapStyle: {
    flexDirection: 'row',
    alignItems: 'center',
    alignSelf: 'center'
  },

  labelVerticalWrap: {
    flexDirection: 'column',
    paddingLeft: 10,
  },

  labelVertical: {
    paddingLeft: 0,
  },

  formHorizontal: {
    flexDirection: 'row',
  },
});

module.exports = Style;
<|endoftext|>


<commit_before>var Botkit = require(__dirname + '/CoreBot.js');
var express = require('express');
var bodyParser = require('body-parser');
var querystring = require('querystring');
var request = require('requestretry');
var clone = require('clone');
var TeamsAPI = require(__dirname + '/TeamsAPI.js');

function TeamsBot(configuration) {
    var controller = Botkit(configuration || {});

    controller.api = TeamsAPI(configuration || {});

    controller.api.getToken(function(err) {
        if (err) {
            // this is a fatal error - could not create a Teams API client
            throw new Error(err);
        }
    });

    controller.defineBot(function(botkit, config) {
        var bot = {
            type: 'teams',
            botkit: botkit,
            config: config || {},
            utterances: botkit.utterances
        };

        bot.startConversation = function(message, cb) {
            botkit.startConversation(this, message, cb);
        };

        bot.createConversation = function(message, cb) {
            botkit.createConversation(this, message, cb);
        };

        bot.channelLink = function(channel_info) {
            return '' + channel_info.name + '';
        };

        bot.startPrivateConversation = function(message, cb) {

            bot.createPrivateConversation(message, function(err, new_convo) {

                if (err) {
                    cb(err);
                } else {
                    new_convo.activate();
                    cb(null, new_convo);
                }

            });

        };

        bot.createPrivateConversation = function(message, cb) {

            bot.openPrivateConvo(message, function(err, new_convo) {
                if (err) {
                    cb(err);
                } else {
                    message.raw_message.conversation = new_convo;
                    bot.createConversation(message, cb);
                }
            });

        };

        bot.openPrivateConvo = function(src, cb) {

            var data = {
                bot: src.recipient,
                members: [src.raw_message.from],
                channelData: src.channelData,
            };

            bot.api.createConversation(data, cb);

        };

        bot.openConvo = function(src, members, cb) {

            var data = {
                isGroup: true,
                bot: src.recipient,
                members: members,
                channelData: src.channelData,
            };

            bot.api.createConveration(data, cb);
        };

        bot.send = function(message, cb) {

            bot.api.addMessageToConversation(message.conversation.id, message, cb);

        };

        bot.replyWithActivity = function(src, message, cb) {

            var data = {
                type: 'message',
                recipient: src.raw_message.from,
                from: src.raw_message.recipient,
                conversation: src.conversation,
                channelData: {
                    notification: {
                      alert: true
                    }
                },
                text: message.text,
                summary: message.summary,
                attachments: message.attachments || null,
                attachmentLayout: message.attachmentLayout || 'list',
            };

            bot.api.addMessageToConversation(src.conversation.id, data, cb);
        };

        bot.replyToComposeExtension = function(src, resp, cb) {
            // console.log('src: ', src);
            src.http_res.send(resp);
            if (cb) {
                cb();
            }
        };

        bot.replyInThread = function(src, resp, cb) {

            // can't clone theis, not needed for this type of messages.
            delete(src.http_res);
            var copy = clone(src);

            // make sure this does NOT include the activity id
            copy.raw_message.conversation = src.raw_message.channelData.channel;

            bot.reply(copy, resp, cb);

        };

        bot.reply = function(src, resp, cb) {
            if (src.type === 'composeExtension') {
                bot.replyToComposeExtension(src, resp, cb);
            }
            if (typeof resp == 'string') {
                resp = {
                    text: resp
                };
            }

            resp.serviceUrl = src.raw_message.serviceUrl;
            resp.from = src.raw_message.recipient;
            resp.recipient = src.raw_message.from;
            resp.to = src.user;
            resp.channel = src.channel;
            resp.conversation = src.raw_message.conversation;

            bot.say(resp, cb);
        };

        bot.findConversation = function(message, cb) {
            botkit.debug('CUSTOM FIND CONVO', message.user, message.channel);
            for (var t = 0; t < botkit.tasks.length; t++) {
                for (var c = 0; c < botkit.tasks[t].convos.length; c++) {
                    if (
                      botkit.tasks[t].convos[c].isActive() &&
                      botkit.tasks[t].convos[c].source_message.user == message.user
                    ) {
                      botkit.debug('FOUND EXISTING CONVO!');
                      cb(botkit.tasks[t].convos[c]);
                      return;
                    }
                }
            }

            cb();
        };
        return bot;
    });

    controller.configureIncomingWebhook = function() {
        controller.webserver.post('/teams/receive', function(req, res) {

            var bot = controller.spawn({
                serviceUrl: message.serviceUrl,
            });

            var message = req.body;

            controller.ingest(bot, message, res);

        });
    };

    controller.middleware.spawn.use(function(bot, next) {

        if (!bot.config.serviceUrl) {
            throw new Error('Cannot spawn a bot without a serviceUrl in the configuration');
        }

        // set up the teams api client
        bot.api = TeamsAPI({
            client_id: controller.config.client_id,
            client_secret: controller.config.client_secret,
            token: controller.config.token,
            serviceUrl: bot.config.serviceUrl,
            team: bot.config.team,
        });

        next();

    });

    controller.middleware.ingest.use(function(bot, message, res, next) {

        res.status(200);
        if (message.name != 'composeExtension/query') {
            // send a result back immediately
            res.send('');
        }

        message.http_res = res;
        next();

    });

    controller.middleware.normalize.use(function(bot, message, next) {

        message.user = message.raw_message.from.id;
        message.channel = message.raw_message.conversation.id;

        next();

    });

    controller.middleware.categorize.use(function(bot, message, next) {

        if (message.type === 'invoke' && message.name === 'composeExtension/query') {
            message.type = 'composeExtension';

            // teams only supports a single parameter, it either exists or doesn't!
            message.text = message.value.parameters[0].value;

        }

        next();

    });

    controller.middleware.categorize.use(function(bot, message, next) {

        if (message.type == 'conversationUpdate') {

            console.log('got a conversation update event', JSON.stringify(message.channelData));
            if (message.raw_message.membersAdded) {
                // replies to these end up in the right place
                for (var m = 0; m < message.raw_message.membersAdded.length; m++) {

                    // clone the message
                    // and copy this member into the from list
                    delete(message.http_res); // <-- that can't be cloned safely
                    var copy = clone(message);
                    copy.from = message.raw_message.membersAdded[m];
                    copy.user = copy.from.id;

                    if (copy.user == message.raw_message.recipient.id) {
                        copy.type = 'bot_channel_join';
                    } else {
                        copy.type = 'user_channel_join';
                    }

                    // restart the categorize process for the newly cloned messages
                    controller.categorize(bot, copy);

                }

            } else if (message.raw_message.membersRemoved) {

                // replies to these end up in the right place
                for (var m = 0; m < message.raw_message.membersRemoved.length; m++) {

                    // clone the message
                    // and copy this member into the from list
                    delete(message.http_res); // <-- that can't be cloned safely
                    var copy = clone(message);
                    copy.from = message.raw_message.membersRemoved[m];
                    copy.user = copy.from.id;

                    if (copy.user == message.raw_message.recipient.id) {
                        copy.type = 'bot_channel_leave';
                    } else {
                        copy.type = 'user_channel_leave';
                    }

                    // restart the categorize process for the newly cloned messages
                    controller.categorize(bot, copy);
                }

                next();
            } else if (message.raw_message.channelData && message.raw_message.channelData.eventType) {
                // channelCreated
                // channelDeleted
                // channelRenamed
                // teamRenamed
                message.type = message.raw_message.channelData.eventType;

                // replies to these end up in general
                next();
            }

        } else {
            next();
        }
    });

    controller.middleware.categorize.use(function(bot, message, next) {

        if (message.type == 'message') message.type = 'message_received';

        if (!message.conversation.isGroup && message.type == 'message_received') {
            message.type = 'direct_message';
        } else if (message.conversation.isGroup && message.type == 'message_received') {

            // start by setting this to a mention, meaning that the bot's name was _somewhere_ in the string
            message.type = 'mention';

            // check to see if this is a direct mention ,meaning bot was mentioned at start of string
            for (var e = 0; e < message.entities.length; e++) {
                var entity = message.entities[0];
                if (entity.type == 'mention' && message.text) {
                    var pattern = new RegExp(message.recipient.id);
                    if (entity.mentioned.id.match(pattern)) {
                        var clean = new RegExp('^' + entity.text + '\\s+');

                        if (message.text.match(clean)) {

                          message.text = message.text.replace(clean, '');
                          message.type = 'direct_mention';
                        }
                    }
                }
            }
        }

        next();
    });

    controller.middleware.format.use(function(bot, message, platform_message, next) {

       platform_message = {
            type: 'message',
            recipient: message.recipient,
            from: message.from,
            text: message.text,
            textFormat: 'markdown',
            entities: message.entities,
            attachments: message.attachments || null,
            attachmentLayout: message.attachmentLayout || 'list',
            conversation: message.conversation,
        };

        next();
    });

    controller.startTicking();
    return controller;
}

module.exports = TeamsBot;
<commit_msg>facebook formatter<commit_after>var Botkit = require(__dirname + '/CoreBot.js');
var express = require('express');
var bodyParser = require('body-parser');
var querystring = require('querystring');
var request = require('requestretry');
var clone = require('clone');
var TeamsAPI = require(__dirname + '/TeamsAPI.js');

function TeamsBot(configuration) {
    var controller = Botkit(configuration || {});

    controller.api = TeamsAPI(configuration || {});

    controller.api.getToken(function(err) {
        if (err) {
            // this is a fatal error - could not create a Teams API client
            throw new Error(err);
        }
    });

    controller.defineBot(function(botkit, config) {
        var bot = {
            type: 'teams',
            botkit: botkit,
            config: config || {},
            utterances: botkit.utterances
        };

        bot.startConversation = function(message, cb) {
            botkit.startConversation(this, message, cb);
        };

        bot.createConversation = function(message, cb) {
            botkit.createConversation(this, message, cb);
        };

        bot.channelLink = function(channel_info) {
            return '' + channel_info.name + '';
        };

        bot.startPrivateConversation = function(message, cb) {

            bot.createPrivateConversation(message, function(err, new_convo) {

                if (err) {
                    cb(err);
                } else {
                    new_convo.activate();
                    cb(null, new_convo);
                }

            });

        };

        bot.createPrivateConversation = function(message, cb) {

            bot.openPrivateConvo(message, function(err, new_convo) {
                if (err) {
                    cb(err);
                } else {
                    message.raw_message.conversation = new_convo;
                    bot.createConversation(message, cb);
                }
            });

        };

        bot.openPrivateConvo = function(src, cb) {

            var data = {
                bot: src.recipient,
                members: [src.raw_message.from],
                channelData: src.channelData,
            };

            bot.api.createConversation(data, cb);

        };

        bot.openConvo = function(src, members, cb) {

            var data = {
                isGroup: true,
                bot: src.recipient,
                members: members,
                channelData: src.channelData,
            };

            bot.api.createConveration(data, cb);
        };

        bot.send = function(message, cb) {

            bot.api.addMessageToConversation(message.conversation.id, message, cb);

        };

        bot.replyWithActivity = function(src, message, cb) {

            var data = {
                type: 'message',
                recipient: src.raw_message.from,
                from: src.raw_message.recipient,
                conversation: src.conversation,
                channelData: {
                    notification: {
                      alert: true
                    }
                },
                text: message.text,
                summary: message.summary,
                attachments: message.attachments || null,
                attachmentLayout: message.attachmentLayout || 'list',
            };

            bot.api.addMessageToConversation(src.conversation.id, data, cb);
        };

        bot.replyToComposeExtension = function(src, resp, cb) {
            // console.log('src: ', src);
            src.http_res.send(resp);
            if (cb) {
                cb();
            }
        };

        bot.replyInThread = function(src, resp, cb) {

            // can't clone theis, not needed for this type of messages.
            delete(src.http_res);
            var copy = clone(src);

            // make sure this does NOT include the activity id
            copy.raw_message.conversation = src.raw_message.channelData.channel;

            bot.reply(copy, resp, cb);

        };

        bot.reply = function(src, resp, cb) {
            if (src.type === 'composeExtension') {
                bot.replyToComposeExtension(src, resp, cb);
            }
            if (typeof resp == 'string') {
                resp = {
                    text: resp
                };
            }

            resp.serviceUrl = src.raw_message.serviceUrl;
            resp.from = src.raw_message.recipient;
            resp.recipient = src.raw_message.from;
            resp.to = src.user;
            resp.channel = src.channel;
            resp.conversation = src.raw_message.conversation;

            bot.say(resp, cb);
        };

        bot.findConversation = function(message, cb) {
            botkit.debug('CUSTOM FIND CONVO', message.user, message.channel);
            for (var t = 0; t < botkit.tasks.length; t++) {
                for (var c = 0; c < botkit.tasks[t].convos.length; c++) {
                    if (
                      botkit.tasks[t].convos[c].isActive() &&
                      botkit.tasks[t].convos[c].source_message.user == message.user
                    ) {
                      botkit.debug('FOUND EXISTING CONVO!');
                      cb(botkit.tasks[t].convos[c]);
                      return;
                    }
                }
            }

            cb();
        };
        return bot;
    });

    controller.configureIncomingWebhook = function() {
        controller.webserver.post('/teams/receive', function(req, res) {

            var bot = controller.spawn({
                serviceUrl: message.serviceUrl,
            });

            var message = req.body;

            controller.ingest(bot, message, res);

        });
    };

    controller.middleware.spawn.use(function(bot, next) {

        if (!bot.config.serviceUrl) {
            throw new Error('Cannot spawn a bot without a serviceUrl in the configuration');
        }

        // set up the teams api client
        bot.api = TeamsAPI({
            client_id: controller.config.client_id,
            client_secret: controller.config.client_secret,
            token: controller.config.token,
            serviceUrl: bot.config.serviceUrl,
            team: bot.config.team,
        });

        next();

    });

    controller.middleware.ingest.use(function(bot, message, res, next) {

        res.status(200);
        if (message.name != 'composeExtension/query') {
            // send a result back immediately
            res.send('');
        }

        message.http_res = res;
        next();

    });

    controller.middleware.normalize.use(function(bot, message, next) {

        message.user = message.raw_message.from.id;
        message.channel = message.raw_message.conversation.id;

        next();

    });

    controller.middleware.categorize.use(function(bot, message, next) {

        if (message.type === 'invoke' && message.name === 'composeExtension/query') {
            message.type = 'composeExtension';

            // teams only supports a single parameter, it either exists or doesn't!
            message.text = message.value.parameters[0].value;

        }

        next();

    });

    controller.middleware.categorize.use(function(bot, message, next) {

        if (message.type == 'conversationUpdate') {

            console.log('got a conversation update event', JSON.stringify(message.channelData));
            if (message.raw_message.membersAdded) {
                // replies to these end up in the right place
                for (var m = 0; m < message.raw_message.membersAdded.length; m++) {

                    // clone the message
                    // and copy this member into the from list
                    delete(message.http_res); // <-- that can't be cloned safely
                    var copy = clone(message);
                    copy.from = message.raw_message.membersAdded[m];
                    copy.user = copy.from.id;

                    if (copy.user == message.raw_message.recipient.id) {
                        copy.type = 'bot_channel_join';
                    } else {
                        copy.type = 'user_channel_join';
                    }

                    // restart the categorize process for the newly cloned messages
                    controller.categorize(bot, copy);

                }

            } else if (message.raw_message.membersRemoved) {

                // replies to these end up in the right place
                for (var m = 0; m < message.raw_message.membersRemoved.length; m++) {

                    // clone the message
                    // and copy this member into the from list
                    delete(message.http_res); // <-- that can't be cloned safely
                    var copy = clone(message);
                    copy.from = message.raw_message.membersRemoved[m];
                    copy.user = copy.from.id;

                    if (copy.user == message.raw_message.recipient.id) {
                        copy.type = 'bot_channel_leave';
                    } else {
                        copy.type = 'user_channel_leave';
                    }

                    // restart the categorize process for the newly cloned messages
                    controller.categorize(bot, copy);
                }

                next();
            } else if (message.raw_message.channelData && message.raw_message.channelData.eventType) {
                // channelCreated
                // channelDeleted
                // channelRenamed
                // teamRenamed
                message.type = message.raw_message.channelData.eventType;

                // replies to these end up in general
                next();
            }

        } else {
            next();
        }
    });

    controller.middleware.categorize.use(function(bot, message, next) {

        if (message.type == 'message') message.type = 'message_received';

        if (!message.conversation.isGroup && message.type == 'message_received') {
            message.type = 'direct_message';
        } else if (message.conversation.isGroup && message.type == 'message_received') {

            // start by setting this to a mention, meaning that the bot's name was _somewhere_ in the string
            message.type = 'mention';

            // check to see if this is a direct mention ,meaning bot was mentioned at start of string
            for (var e = 0; e < message.entities.length; e++) {
                var entity = message.entities[0];
                if (entity.type == 'mention' && message.text) {
                    var pattern = new RegExp(message.recipient.id);
                    if (entity.mentioned.id.match(pattern)) {
                        var clean = new RegExp('^' + entity.text + '\\s+');

                        if (message.text.match(clean)) {

                          message.text = message.text.replace(clean, '');
                          message.type = 'direct_mention';
                        }
                    }
                }
            }
        }

        next();
    });

    controller.middleware.format.use(function(bot, message, platform_message, next) {

      platform_message.type = 'message';
      platform_message.recipient =  message.recipient;
      platform_message.from =  message.from;
      platform_message.text =  message.text;
      platform_message.textFormat =  'markdown';
      platform_message.entities =  message.entities;
      platform_message.attachments =  message.attachments || null;
      platform_message.attachmentLayout =  message.attachmentLayout || 'list';
      platform_message.conversation =  message.conversation;

        next();
    });

    controller.startTicking();
    return controller;
}

module.exports = TeamsBot;
<|endoftext|>


<commit_before>/**
 * @file RaisedButton component
 * @author liangxiaojun(liangxiaojun@derbysoft.com)
 */

import React, {Component} from 'react';
import PropTypes from 'prop-types';

import BaseButton from '../_BaseButton';
import Theme from '../Theme';
import TipProvider from '../TipProvider';

import Util from '../_vendors/Util';

export default class RaisedButton extends Component {

    constructor(props, ...restArgs) {

        super(props, ...restArgs);

        this.startRipple = ::this.startRipple;
        this.endRipple = ::this.endRipple;

    }

    startRipple(e) {
        this.refs.baseButton.startRipple(e);
    }

    endRipple() {
        this.refs.baseButton.endRipple();
    }

    render() {

        const {children, className} = this.props;

        return (
            <BaseButton {...this.props}
                        ref="baseButton"
                        className={`raised-button ${className}`}>
                {children}
            </BaseButton>
        );

    }
};

RaisedButton.propTypes = {

    /**
     * The CSS class name of the root element.
     */
    className: PropTypes.string,

    /**
     * Override the styles of the root element.
     */
    style: PropTypes.object,

    /**
     * The button theme.Can be primary,highlight,success,warning,error.
     */
    theme: PropTypes.oneOf(Util.enumerateValue(Theme)),

    /**
     * If true,the button will have rounded corners.
     */
    isRounded: PropTypes.bool,

    /**
     * If true,the button will be round.
     */
    isCircular: PropTypes.bool,

    /**
     * The text of the button.Type can be string or number.
     */
    value: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),

    /**
     * The type of button.Can be reset,submit or button.
     */
    type: PropTypes.string,

    /**
     * Disables the button if set to true.
     */
    disabled: PropTypes.bool,

    /**
     * If true,the button will be have loading effect.
     */
    isLoading: PropTypes.bool,

    /**
     * If true,the element's ripple effect will be disabled.
     */
    disableTouchRipple: PropTypes.bool,

    /**
     * Use this property to display an icon.It will display on the left.
     */
    iconCls: PropTypes.string,

    /**
     * Use this property to display an icon.It will display on the right.
     */
    rightIconCls: PropTypes.string,

    /**
     * If true,the ripple effect will be display centered.
     */
    rippleDisplayCenter: PropTypes.bool,

    tip: PropTypes.string,
    tipPosition: PropTypes.oneOf(Util.enumerateValue(TipProvider.Position)),

    /**
     * You can create a complicated renderer callback instead of value prop.
     */
    renderer: PropTypes.func,

    /**
     * Callback function fired when the button is touch-tapped.
     */
    onTouchTap: PropTypes.func

};

RaisedButton.defaultProps = {

    className: '',
    style: null,
    theme: Theme.DEFAULT,

    isRounded: false,
    isCircular: false,

    value: '',
    disabled: false,
    type: 'button',
    isLoading: false,
    disableTouchRipple: false,

    rippleDisplayCenter: false,

    iconCls: '',
    rightIconCls: '',

    tip: null,
    tipPosition: TipProvider.Position.BOTTOM

};<commit_msg>update RaisedButton<commit_after>/**
 * @file RaisedButton component
 * @author liangxiaojun(liangxiaojun@derbysoft.com)
 */

import React, {Component} from 'react';
import PropTypes from 'prop-types';

import BaseButton from '../_BaseButton';
import TipProvider from '../TipProvider';
import Theme from '../Theme';

import Util from '../_vendors/Util';

export default class RaisedButton extends Component {

    constructor(props, ...restArgs) {

        super(props, ...restArgs);

        this.startRipple = ::this.startRipple;
        this.endRipple = ::this.endRipple;

    }

    startRipple(e) {
        this.refs.baseButton.startRipple(e);
    }

    endRipple() {
        this.refs.baseButton.endRipple();
    }

    render() {

        const {children, className} = this.props;

        return (
            <BaseButton {...this.props}
                        ref="baseButton"
                        className={`raised-button ${className}`}>
                {children}
            </BaseButton>
        );

    }
};

RaisedButton.propTypes = {

    /**
     * The CSS class name of the root element.
     */
    className: PropTypes.string,

    /**
     * Override the styles of the root element.
     */
    style: PropTypes.object,

    /**
     * The button theme.Can be primary,highlight,success,warning,error.
     */
    theme: PropTypes.oneOf(Util.enumerateValue(Theme)),

    /**
     * If true,the button will have rounded corners.
     */
    isRounded: PropTypes.bool,

    /**
     * If true,the button will be round.
     */
    isCircular: PropTypes.bool,

    /**
     * The text of the button.Type can be string or number.
     */
    value: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),

    /**
     * The type of button.Can be reset,submit or button.
     */
    type: PropTypes.string,

    /**
     * Disables the button if set to true.
     */
    disabled: PropTypes.bool,

    /**
     * If true,the button will be have loading effect.
     */
    isLoading: PropTypes.bool,

    /**
     * If true,the element's ripple effect will be disabled.
     */
    disableTouchRipple: PropTypes.bool,

    /**
     * Use this property to display an icon.It will display on the left.
     */
    iconCls: PropTypes.string,

    /**
     * Use this property to display an icon.It will display on the right.
     */
    rightIconCls: PropTypes.string,

    /**
     * If true,the ripple effect will be display centered.
     */
    rippleDisplayCenter: PropTypes.bool,

    tip: PropTypes.string,
    tipPosition: PropTypes.oneOf(Util.enumerateValue(TipProvider.Position)),

    /**
     * You can create a complicated renderer callback instead of value prop.
     */
    renderer: PropTypes.func,

    /**
     * Callback function fired when the button is touch-tapped.
     */
    onTouchTap: PropTypes.func

};

RaisedButton.defaultProps = {

    className: '',
    style: null,
    theme: Theme.DEFAULT,

    isRounded: false,
    isCircular: false,

    value: '',
    disabled: false,
    type: 'button',
    isLoading: false,
    disableTouchRipple: false,

    rippleDisplayCenter: false,

    iconCls: '',
    rightIconCls: '',

    tip: null,
    tipPosition: TipProvider.Position.BOTTOM

};<|endoftext|>


<commit_before>var core = require('./core');
var fs = require('fs');
var path = require('path');
var caller = require('./caller.js');
var nodeModulesPaths = require('./node-modules-paths.js');
var splitRe = process.platform === 'win32' ? /[\/\\]/ : /\//;

module.exports = function resolve (x, opts, cb) {
    if (typeof opts === 'function') {
        cb = opts;
        opts = {};
    }
    if (!opts) opts = {};
    if (typeof x !== 'string') {
        return process.nextTick(function () {
            cb(new Error('path must be a string'));
        });
    }

    var isFile = opts.isFile || function (file, cb) {
        fs.stat(file, function (err, stat) {
            if (err && err.code === 'ENOENT') cb(null, false)
            else if (err) cb(err)
            else cb(null, stat.isFile() || stat.isFIFO())
        });
    };
    var readFile = opts.readFile || fs.readFile;

    var extensions = opts.extensions || [ '.js' ];
    var y = opts.basedir || path.dirname(caller());

    opts.paths = opts.paths || [];

    if (/^(?:\.\.?(?:\/|$)|\/|([A-Za-z]:)?[\\\/])/.test(x)) {
        var res = path.resolve(y, x);
        if (x === '..') res += '/';
        loadAsFile(res, opts.package, function (err, m, pkg) {
            if (err) cb(err)
            else if (m) cb(null, m, pkg)
            else loadAsDirectory(res, function (err, d, pkg) {
                if (err) cb(err)
                else if (d) cb(null, d, pkg)
                else cb(new Error("Cannot find module '" + x + "' from '" + y + "'"))
            })
        });
    }
    else loadNodeModules(x, y, function (err, n, pkg) {
        if (err) cb(err)
        else if (n) cb(null, n, pkg)
        else if (core[x]) return cb(null, x);
        else cb(new Error("Cannot find module '" + x + "' from '" + y + "'"))
    });

    function loadAsFile (x, pkg, cb, again) {
        if (typeof pkg === 'function') {
            cb = pkg;
            pkg = undefined;
        }

        var exts = [''].concat(extensions);

        if (x === y && !again) {
            loadAsDirectory(y, pkg, function (err, d, pkg) {
                if (d) cb(err, d, pkg)
                else loadAsFile(x, pkg, cb, true)
            });
        }
        else load(exts, x, pkg)

		function load (exts, x, pkg) {
            if (exts.length === 0) return cb(null, undefined, pkg);
            var file = x + exts[0];

            isFile(file, function (err, ex) {
                if (err) return cb(err)
                if (!ex) return load(exts.slice(1), x, pkg)
                if (pkg) return cb(null, file, pkg)

                loadpkg(path.dirname(file), function (err, pkg, dir) {
                    if (err) return cb(err)
                    if (pkg && opts.pathFilter) {
                        var rel = path.relative(dir, file)
                            .slice(0, -exts[0].length)
                        ;
                        var r = opts.pathFilter(pkg, x, rel);
                        if (r) return load(
                            extensions.slice(),
                            path.resolve(dir, r),
                            pkg
                        );
                    }
                    cb(null, file, pkg)
                });
            });
        }
    }

    function loadpkg (dir, cb) {
        if (dir === '' || dir === '/') return cb(null);
        if (process.platform === 'win32' && /^\w:[\\\/]*$/.test(dir)) {
            return cb(null);
        }
        if (/[\\\/]node_modules[\\\/]*$/.test(dir)) return cb(null);

        var pkgfile = path.join(dir, 'package.json');
        isFile(pkgfile, function (err, ex) {
            if (err) return cb(err);
            if (!ex) return loadpkg(
                dir.replace(/[\\\/]*[^\\\/]+[\\\/]*/, ''), cb
            );

            readFile(pkgfile, function (err, body) {
                if (err) cb(err);
                try { var pkg = JSON.parse(body) }
                catch (err) {}

                if (pkg && opts.packageFilter) {
                    pkg = opts.packageFilter(pkg, pkgfile);
                }
                cb(null, pkg, dir);
            });
        });
    }

    function loadAsDirectory (x, fpkg, cb) {
        if (typeof fpkg === 'function') {
            cb = fpkg;
            fpkg = opts.package;
        }

        var pkgfile = path.join(x, '/package.json');
        isFile(pkgfile, function (err, ex) {
            if (err) return cb(err);
            if (!ex) return loadAsFile(path.join(x, '/index'), fpkg, cb);

            readFile(pkgfile, function (err, body) {
                if (err) return cb(err);
                try {
                    var pkg = JSON.parse(body);
                }
                catch (err) {}

                if (opts.packageFilter) {
                    pkg = opts.packageFilter(pkg, pkgfile);
                }

                if (pkg.main) {
                    if (pkg.main === '.' || pkg.main === './'){
                        pkg.main = 'index'
                    }
                    loadAsFile(path.resolve(x, pkg.main), pkg, function (err, m, pkg) {
                        if (err) return cb(err);
                        if (m) return cb(null, m, pkg);
                        if (!pkg) return loadAsFile(path.join(x, '/index'), pkg, cb);

                        var dir = path.resolve(x, pkg.main);
                        loadAsDirectory(dir, pkg, function (err, n, pkg) {
                            if (err) return cb(err);
                            if (n) return cb(null, n, pkg);
                            loadAsFile(path.join(x, '/index'), pkg, cb);
                        });
                    });
                    return;
                }

                loadAsFile(path.join(x, '/index'), pkg, cb);
            });
        });
    }

    function loadNodeModules (x, start, cb) {
        (function process (dirs) {
            if (dirs.length === 0) return cb(null, undefined);
            var dir = dirs[0];

            loadAsFile(path.join(dir, '/', x), undefined, function (err, m, pkg) {
                if (err) return cb(err);
                if (m) return cb(null, m, pkg);
                loadAsDirectory(path.join(dir, '/', x), undefined, function (err, n, pkg) {
                    if (err) return cb(err);
                    if (n) return cb(null, n, pkg);
                    process(dirs.slice(1));
                });
            });
        })(nodeModulesPaths(start, opts));
    }
};
<commit_msg>path logic fix that seems to handle all the cases across this package and browserify<commit_after>var core = require('./core');
var fs = require('fs');
var path = require('path');
var caller = require('./caller.js');
var nodeModulesPaths = require('./node-modules-paths.js');
var splitRe = process.platform === 'win32' ? /[\/\\]/ : /\//;

module.exports = function resolve (x, opts, cb) {
    if (typeof opts === 'function') {
        cb = opts;
        opts = {};
    }
    if (!opts) opts = {};
    if (typeof x !== 'string') {
        return process.nextTick(function () {
            cb(new Error('path must be a string'));
        });
    }

    var isFile = opts.isFile || function (file, cb) {
        fs.stat(file, function (err, stat) {
            if (err && err.code === 'ENOENT') cb(null, false)
            else if (err) cb(err)
            else cb(null, stat.isFile() || stat.isFIFO())
        });
    };
    var readFile = opts.readFile || fs.readFile;

    var extensions = opts.extensions || [ '.js' ];
    var y = opts.basedir || path.dirname(caller());

    opts.paths = opts.paths || [];

    if (/^(?:\.\.?(?:\/|$)|\/|([A-Za-z]:)?[\\\/])/.test(x)) {
        var res = path.resolve(y, x);
        if (x === '..') res += '/';
        if (/\/$/.test(x) && res === y) {
            loadAsDirectory(res, opts.package, onfile);
        }
        else loadAsFile(res, opts.package, onfile);
    }
    else loadNodeModules(x, y, function (err, n, pkg) {
        if (err) cb(err)
        else if (n) cb(null, n, pkg)
        else if (core[x]) return cb(null, x);
        else cb(new Error("Cannot find module '" + x + "' from '" + y + "'"))
    });

    function onfile (err, m, pkg) {
        if (err) cb(err)
        else if (m) cb(null, m, pkg)
        else loadAsDirectory(res, function (err, d, pkg) {
            if (err) cb(err)
            else if (d) cb(null, d, pkg)
            else cb(new Error("Cannot find module '" + x + "' from '" + y + "'"))
        })
    }

    function loadAsFile (x, pkg, cb) {
        if (typeof pkg === 'function') {
            cb = pkg;
            pkg = undefined;
        }

        var exts = [''].concat(extensions);
        load(exts, x, pkg)

		function load (exts, x, pkg) {
            if (exts.length === 0) return cb(null, undefined, pkg);
            var file = x + exts[0];

            isFile(file, function (err, ex) {
                if (err) return cb(err)
                if (!ex) return load(exts.slice(1), x, pkg)
                if (pkg) return cb(null, file, pkg)

                loadpkg(path.dirname(file), function (err, pkg, dir) {
                    if (err) return cb(err)
                    if (pkg && opts.pathFilter) {
                        var rel = path.relative(dir, file)
                            .slice(0, -exts[0].length)
                        ;
                        var r = opts.pathFilter(pkg, x, rel);
                        if (r) return load(
                            extensions.slice(),
                            path.resolve(dir, r),
                            pkg
                        );
                    }
                    cb(null, file, pkg)
                });
            });
        }
    }

    function loadpkg (dir, cb) {
        if (dir === '' || dir === '/') return cb(null);
        if (process.platform === 'win32' && /^\w:[\\\/]*$/.test(dir)) {
            return cb(null);
        }
        if (/[\\\/]node_modules[\\\/]*$/.test(dir)) return cb(null);

        var pkgfile = path.join(dir, 'package.json');
        isFile(pkgfile, function (err, ex) {
            if (err) return cb(err);
            if (!ex) return loadpkg(
                dir.replace(/[\\\/]*[^\\\/]+[\\\/]*/, ''), cb
            );

            readFile(pkgfile, function (err, body) {
                if (err) cb(err);
                try { var pkg = JSON.parse(body) }
                catch (err) {}

                if (pkg && opts.packageFilter) {
                    pkg = opts.packageFilter(pkg, pkgfile);
                }
                cb(null, pkg, dir);
            });
        });
    }

    function loadAsDirectory (x, fpkg, cb) {
        if (typeof fpkg === 'function') {
            cb = fpkg;
            fpkg = opts.package;
        }

        var pkgfile = path.join(x, '/package.json');
        isFile(pkgfile, function (err, ex) {
            if (err) return cb(err);
            if (!ex) return loadAsFile(path.join(x, '/index'), fpkg, cb);

            readFile(pkgfile, function (err, body) {
                if (err) return cb(err);
                try {
                    var pkg = JSON.parse(body);
                }
                catch (err) {}

                if (opts.packageFilter) {
                    pkg = opts.packageFilter(pkg, pkgfile);
                }

                if (pkg.main) {
                    if (pkg.main === '.' || pkg.main === './'){
                        pkg.main = 'index'
                    }
                    loadAsFile(path.resolve(x, pkg.main), pkg, function (err, m, pkg) {
                        if (err) return cb(err);
                        if (m) return cb(null, m, pkg);
                        if (!pkg) return loadAsFile(path.join(x, '/index'), pkg, cb);

                        var dir = path.resolve(x, pkg.main);
                        loadAsDirectory(dir, pkg, function (err, n, pkg) {
                            if (err) return cb(err);
                            if (n) return cb(null, n, pkg);
                            loadAsFile(path.join(x, '/index'), pkg, cb);
                        });
                    });
                    return;
                }

                loadAsFile(path.join(x, '/index'), pkg, cb);
            });
        });
    }

    function loadNodeModules (x, start, cb) {
        (function process (dirs) {
            if (dirs.length === 0) return cb(null, undefined);
            var dir = dirs[0];

            loadAsFile(path.join(dir, '/', x), undefined, function (err, m, pkg) {
                if (err) return cb(err);
                if (m) return cb(null, m, pkg);
                loadAsDirectory(path.join(dir, '/', x), undefined, function (err, n, pkg) {
                    if (err) return cb(err);
                    if (n) return cb(null, n, pkg);
                    process(dirs.slice(1));
                });
            });
        })(nodeModulesPaths(start, opts));
    }
};
<|endoftext|>


<commit_before>"use strict";

var package_json = require('./../package.json');
var Sendgrid = require('sendgrid');

var Barke = function(api_user, api_key, options) {
	if( !(this instanceof Barke) ) {
	  return new Barke(api_user, api_key, options);
	}

	var options = options || {};

	options.protocol = options.protocol || "https";
	options.host = options.host || "esp.embarkemail.com";
	options.port = options.port || "";
	options.endpoint = options.endpoint || "/sendgrid/api/mail.send.json";

	var sendgrid = Sendgrid(api_user, api_key, options);

	/*
	 * Expose public API calls
	 */
	this.version         = package_json.version;
	this.sendgrid        = sendgrid;
	this.Email           = sendgrid.Email;
	this.api_user        = api_user;
	this.api_key         = api_key;
	this.send            = sendgrid.send;
	this.options         = this.options;
	return this;

}

module.exports = Barke;<commit_msg>added embarkeapi object<commit_after>"use strict";

var package_json = require('./../package.json');
var Sendgrid = require('sendgrid');

var Barke = function(api_user, api_key, options) {
	if( !(this instanceof Barke) ) {
	  return new Barke(api_user, api_key, options);
	}

	var options = options || {};

	options.protocol = options.protocol || "https";
	options.host = options.host || "esp.embarkemail.com";
	options.port = options.port || "";
	options.endpoint = options.endpoint || "/sendgrid/api/mail.send.json";

	var sendgrid = Sendgrid(api_user, api_key, options);

	sendgrid.Email.prototype.setSendDate = function(date) {
		if(typeof this.embarkeapi == "undefined") {
			this.embarkeapi = {};
		}
		var dateObj;

		if (typeof date == "undefined") {
			dateObj = new Date();
		}

		if (typeof date == "string") {
			dateObj = new Date(date);
		}

		if (typeof date == "object") {
			dateObj = date;
		}

		this.embarkeapi.sendDate = dateObj;
	};

	sendgrid.Email.prototype.setMaxSendHours = function(hours) {
		if(typeof this.embarkeapi == "undefined") {
			this.embarkeapi = {};
		}
		this.embarkeapi.maxSendHours = hours;
	};

	sendgrid.Email.prototype.setCampaignId = function(id) {
		if(typeof this.embarkeapi == "undefined") {
			this.embarkeapi = {};
		}
		this.embarkeapi.campaignId = id;
	};

	sendgrid.Email.prototype.setMailAccount = function(account) {
		if(typeof this.embarkeapi == "undefined") {
			this.embarkeapi = {};
		}
		this.embarkeapi.mailAccount = account;
	};

	sendgrid.Email.prototype.addTag = function(tag) {
		if(typeof this.embarkeapi == "undefined") {
			this.embarkeapi = {};
		}

		if(typeof this.embarkeapi.tags == "undefined") {
			this.embarkeapi.tags = [];
		}

		this.embarkeapi.tags.push(tag);
	};

	sendgrid.Email.prototype.setTags = function(tags) {
		if(typeof this.embarkeapi == "undefined") {
			this.embarkeapi = {};
		}

		if(typeof tags == "string"){
			tags = [tags];
		}

		this.embarkeapi.tags = tags;
	};

	var send = function (email, cb) {

		if(typeof email !== "object") {
			if(typeof cb === "function") {
				cb(new Error("send requires the first argument be an Email object or javascript object"));
			}
			return false;
		}

		if (email.constructor !== sendgrid.Email) {
			email = new sendgrid.Email(email);
		}

		if(typeof email.embarkeapi == "undefined" || typeof email.embarkeapi.sendDate == "undefined"){
			email.setSendDate();
		}

		if(email.embarkeapi.sendDate.constructor !== Date) {
			email.setSendDate(email.embarkeapi.sendDate);
		}

		email.embarkeapi.sendDate = email.embarkeapi.sendDate.toISOString();

		email.addHeader("x-embarkeapi", JSON.stringify(email.embarkeapi));

		sendgrid.send(email, cb);
	}

	/*
	 * Expose public API calls
	 */
	this.version         = package_json.version;
	this.sendgrid        = sendgrid;
	this.Email           = sendgrid.Email;
	this.api_user        = api_user;
	this.api_key         = api_key;
	this.send            = send;
	this.options         = this.sendgrid.options;
	return this;

}

module.exports = Barke;<|endoftext|>


<commit_before>import React from 'react';

const Single =  React.createClass({
  render(){
    return(

        Single nigga

     )
  }
})

export default Single;
<commit_msg>Modified single component<commit_after>import React from 'react';
import Photo from './Photo';
// import comments

const Single =  React.createClass({
  render(){
    // index of post
    const i = this.props.posts.findIndex((post) => post.code ===
    this.props.params.postId);
    const post = this.props.posts[i];

    return(

          <Photo i={i} post={post} {...this.props}/>

     )
  }
})

export default Single;
<|endoftext|>


<commit_before>/* global _ */

Template.editor.helpers({
  fileId: function () {
    return Session.get('fileId')
  },
  filename: function () {
    return Files.findOne({ _id: Session.get('fileId') }).filename
  },
  config: function () {
    return function (cm) {
      const file = Files.findOne({ _id: Session.get('fileId') })

      cm.setOption('lineNumbers', true)

      // set content of the editor to the latest content from file object
      cm.doc.setValue(file.content)

      // periodically update file object when there is a change in the editor
      cm.doc.on('change', _.debounce(function (editor) {
        Meteor.call('updateFile', file._id, editor.getValue())
      }, 500))
    }
  },
  setContent: function () {
    return function (cm) {
      const file = Files.findOne({ _id: Session.get('fileId') })
      cm.doc.setValue(file.content)
    }
  }
})
//
// Template.editingUsers.helpers({
//   users: function () {
//     var doc, eusers, users
//     doc = Documents.findOne()
//     if (!doc) {
//       return
//     }
//     eusers = EditingUsers.findOne()
//     if (!eusers) {
//       return
//     }
//
//     users = []
//     var i = 0
//     for (var user_id in eusers.users) {
//       users[i] = eusers.users[user_id]
//       i++
//     }
//     return users
//   }
// })
<commit_msg>remove redundant code<commit_after>/* global _ */

Template.editor.helpers({
  fileId: function () {
    return Session.get('fileId')
  },
  filename: function () {
    return Files.findOne({ _id: Session.get('fileId') }).filename
  },
  config: function () {
    return function (cm) {
      const file = Files.findOne({ _id: Session.get('fileId') })

      cm.setOption('lineNumbers', true)

      // periodically update file object when there is a change in the editor
      cm.doc.on('change', _.debounce(function (editor) {
        Meteor.call('updateFile', file._id, editor.getValue())
      }, 500))
    }
  },
  setContent: function () {
    return function (cm) {
      const file = Files.findOne({ _id: Session.get('fileId') })
      cm.doc.setValue(file.content)
    }
  }
})
//
// Template.editingUsers.helpers({
//   users: function () {
//     var doc, eusers, users
//     doc = Documents.findOne()
//     if (!doc) {
//       return
//     }
//     eusers = EditingUsers.findOne()
//     if (!eusers) {
//       return
//     }
//
//     users = []
//     var i = 0
//     for (var user_id in eusers.users) {
//       users[i] = eusers.users[user_id]
//       i++
//     }
//     return users
//   }
// })
<|endoftext|>


<commit_before>var $module = (function($B){

_b_ = $B.builtins

var ELEMENT_NODE = 1,
    TEXT_NODE = 3,
    COMMENT_NODE =	8,
    DOCUMENT_TYPE_NODE =	10

var HTMLNode = $B.make_class("HTMLNode",
    function(){
        return {
            __class__: HTMLNode,
            nodeType: TEXT_NODE,
            text: ""
        }
    }
)

HTMLNode.__str__ = function(self){
    return self.text
}

$B.set_func_names(HTMLNode, "_html_parser")

function* tokenize(src){
    var node = HTMLNode.$factory(),
        pos = 0,
        tag = "",
        type = "text"
    while(pos < src.length){
        var char = src[pos]
        switch(type){
            case "text":
                if(char == "<"){
                    // starts a tag if immediately followed by a letter or by /
                    var tag_mo = /^(\/?)[a-zA-Z]+/.exec(src.substr(pos + 1))
                    if(tag_mo){
                        yield node
                        node = HTMLNode.$factory()
                        type = "tag"
                        node.tagName = ""
                        node.nodeType = ELEMENT_NODE
                        node.closing = tag_mo[1] != ""
                        node.attrs = []
                    }else{
                        // doctype declaration
                        var decl_mo = /^<!doctype\s+(.*?)>/i.exec(src.substr(pos))
                        if(decl_mo){
                            yield node
                            node = HTMLNode.$factory()
                            node.text = decl_mo[0]
                            node.doctype = decl_mo[1]
                            node.nodeType = DOCUMENT_TYPE_NODE
                            yield node
                            node = HTMLNode.$factory()
                            type = "text"
                            pos += decl_mo[0].length
                            break
                        }else{
                            // comment
                            var comment_mo = /^\<!(.*?)>/.exec(src.substr(pos))
                            if(comment_mo){
                                yield node
                                node = HTMLNode.$factory()
                                node.text = comment_mo[0]
                                node.comment = comment_mo[1]
                                node.nodeType = COMMENT_NODE
                                yield node
                                node = HTMLNode.$factory()
                                type = "text"
                                pos += comment_mo[0].length
                                break
                            }
                        }
                    }
                }
                pos++
                node.text += char
                break
            case "tag":
                if(char.search(/[_a-zA-Z]/) > -1){
                    var mo = /\w+/.exec(src.substr(pos))
                    if(mo !== null){
                        pos += mo[0].length
                        if(node.tagName == ""){
                            node.tagName = mo[0].toUpperCase()
                        }
                        node.text += mo[0]
                    }else{
                        pos++
                    }
                }else if(char == ">"){
                    node.text += char
                    yield node
                    node = HTMLNode.$factory()
                    type = "text"
                    pos++
                }else if(char == "="){
                    node.text += char
                    pos++
                }else if(char == "'" || char == '"'){
                    var i = pos + 1
                    while(i < src.length){
                        if(src[i] == char){
                            var nb_escape = 0
                            while(src[i - 1 - nb_escape] == '/'){
                                nb_escape++
                            }
                            if(nb_escape % 2 == 0){
                                node.text += src.substr(pos, i + 1 - pos)
                                pos = i + 1
                                break
                            }else{
                                i++
                            }
                        }else{
                            i++
                        }
                    }
                }else{
                    node.text += char
                    pos++
                }
                break
            default:
                pos++
        }
    }
    yield node
}
return  {
    ELEMENT_NODE: 1,
    TEXT_NODE: 3,
    COMMENT_NODE:	8,
    DOCUMENT_TYPE_NODE:	10,
    tokenize: tokenize
}

})(__BRYTHON__)
<commit_msg>html_parser supports unterminated strings inside tags.<commit_after>var $module = (function($B){

_b_ = $B.builtins

var ELEMENT_NODE = 1,
    TEXT_NODE = 3,
    COMMENT_NODE =    8,
    DOCUMENT_TYPE_NODE =    10

var HTMLNode = $B.make_class("HTMLNode",
    function(){
        return {
            __class__: HTMLNode,
            nodeType: TEXT_NODE,
            text: ""
        }
    }
)

HTMLNode.__str__ = function(self){
    return self.text
}

$B.set_func_names(HTMLNode, "_html_parser")

function* tokenize(src){
    var node = HTMLNode.$factory(),
        pos = 0,
        tag = "",
        type = "text"
    while(pos < src.length){
        var char = src[pos]
        switch(type){
            case "text":
                if(char == "<"){
                    // starts a tag if immediately followed by a letter or by /
                    var tag_mo = /^(\/?)[a-zA-Z]+/.exec(src.substr(pos + 1))
                    if(tag_mo){
                        yield node
                        node = HTMLNode.$factory()
                        type = "tag"
                        node.tagName = ""
                        node.nodeType = ELEMENT_NODE
                        node.closing = tag_mo[1] != ""
                        node.attrs = []
                    }else{
                        // doctype declaration
                        var decl_mo = /^<!doctype\s+(.*?)>/i.exec(src.substr(pos))
                        if(decl_mo){
                            yield node
                            node = HTMLNode.$factory()
                            node.text = decl_mo[0]
                            node.doctype = decl_mo[1]
                            node.nodeType = DOCUMENT_TYPE_NODE
                            yield node
                            node = HTMLNode.$factory()
                            type = "text"
                            pos += decl_mo[0].length
                            break
                        }else{
                            // comment
                            var comment_mo = /^\<!(.*?)>/.exec(src.substr(pos))
                            if(comment_mo){
                                yield node
                                node = HTMLNode.$factory()
                                node.text = comment_mo[0]
                                node.comment = comment_mo[1]
                                node.nodeType = COMMENT_NODE
                                yield node
                                node = HTMLNode.$factory()
                                type = "text"
                                pos += comment_mo[0].length
                                break
                            }
                        }
                    }
                }
                pos++
                node.text += char
                break
            case "tag":
                if(char.search(/[_a-zA-Z]/) > -1){
                    var mo = /\w+/.exec(src.substr(pos))
                    if(mo !== null){
                        pos += mo[0].length
                        if(node.tagName == ""){
                            node.tagName = mo[0].toUpperCase()
                        }
                        node.text += mo[0]
                    }else{
                        pos++
                    }
                }else if(char == ">"){
                    node.text += char
                    yield node
                    node = HTMLNode.$factory()
                    type = "text"
                    pos++
                }else if(char == "="){
                    node.text += char
                    pos++
                }else if(char == "'" || char == '"'){
                    var i = pos + 1,
                        found_string_end = false
                    while(i < src.length){
                        if(src[i] == char){
                            var nb_escape = 0
                            while(src[i - 1 - nb_escape] == '/'){
                                nb_escape++
                            }
                            if(nb_escape % 2 == 0){
                                node.text += src.substr(pos, i + 1 - pos)
                                pos = i + 1
                                found_string_end = true
                                break
                            }else{
                                i++
                            }
                        }else if(src[i] == '>'){
                            break
                        }else{
                            i++
                        }
                    }
                    if(! found_string_end){
                        // unterminated string: ignore
                        pos++
                    }
                }else{
                    node.text += char
                    pos++
                }
                break
            default:
                pos++
        }
    }
    yield node
}
return  {
    ELEMENT_NODE: 1,
    TEXT_NODE: 3,
    COMMENT_NODE:    8,
    DOCUMENT_TYPE_NODE:    10,
    tokenize: tokenize
}

})(__BRYTHON__)
<|endoftext|>


<commit_before><commit_msg>Disable ligatures for code blocks (#10646)<commit_after><|endoftext|>


<commit_before>const chalk = require('chalk');
const fs = require('fs');
const inquirer = require('inquirer');

module.exports = () => {
  require('./greeter')(`What projects do you want to update?`);

  const choices = fs.readdirSync('.')
    .filter(folder => fs.lstatSync(folder).isDirectory())
    .map(folder => ({ name: folder }));

  inquirer.prompt([{
    choices,
    type: 'checkbox',
    message: 'Select projects',
    name: 'projects',
    pageSize: 30,
  }]).then(projects => {
    if (!projects.length) {
      console.error(chalk.red('ERROR: You have selected no projects to update.'));
    }
  });
}
<commit_msg>:sparkles: Auto-update version constraints in Composer<commit_after>const chalk = require('chalk');
const composer = require('./updaters/composer');
const fs = require('fs');
const inquirer = require('inquirer');
const shelljs = require('shelljs');

module.exports = () => {
  require('./greeter')(`What projects do you want to update?`);

  const choices = fs.readdirSync('.')
    .filter(folder => fs.lstatSync(folder).isDirectory())
    .map(folder => ({ name: folder }));

  inquirer.prompt([{
    choices,
    type: 'checkbox',
    message: 'Select projects',
    name: 'projects',
    pageSize: 30,
  }]).then(({ projects }) => {
    if (!projects.length) {
      console.error(chalk.red('ERROR: You have selected no projects to update.'));
      return;
    }

    projects.forEach(project => {
      if (fs.existsSync(`${project}/composer.json`)) {
        shelljs.cd(project);

        const packageUpdates = composer.getOutdatedAfterUpdate()
          .split('\n')
          .map(composerPackage => {
            const [name, currentVersion, availableVersion] = composerPackage.split(/\s+/);

            return `${name} ${availableVersion}`;
          })
          .join(' ');

        shelljs.exec(`composer require ${packageUpdates} --no-update`, { silent: true });
        shelljs.exec('composer update', { silent: true });

        shelljs.cd('..');
      }
    });
  });
}
<|endoftext|>