<commit_before>'use strict';

const path = require('path');

const postcss = require('postcss');

function init({
    processorConfig,
    processorCommonConfig,
    commonConfig,
}) {
  const config = Object.assign({}, commonConfig, processorCommonConfig, processorConfig);

  function read(basePath, { readers }) {
    const stylePaths = readers.dir(`${basePath}`);
    const styles = stylePaths.map((stylePath) => {
      return {
        id: path.basename(stylePath),
        name: path.basename(stylePath),
        isBundle: false,
        contents: readers.fileToString(stylePath),
      };
    });
    const bundles = config.bundles ? config.bundles.map((bundle) => {
      return {
        id: bundle.name,
        name: bundle.name,
        isBundle: true,
        files: bundle.files,
      };
    }) : [];
    return [...styles, ...bundles];
  }

  function preprocess(styles) {
    return styles.map((style) => {
      const next = Object.assign({}, style);
      next.writePath = `styles/${style.name}`;
      return next;
    });
  }

  function templateVariables(styles) {
    return styles.map((style) => {
      const next = Object.assign({}, style);
      next.url = `/styles/${style.name}`;
      return next;
    });
  }

  function normalizePostcssPluginPath(basePath, pluginName) {
    return path.resolve(basePath, 'node_modules', pluginName);
  }

  function normalizePostcssPluginPaths(basePath, plugins) {
    return plugins.map((plugin) => {
      if (plugin.name === 'cssnano') {
        return plugin;
      }
      return Object.assign({}, plugin, { name: normalizePostcssPluginPath(basePath, plugin.name) });
    });
  }

  function loadPostcssPlugins(plugins) {
    return plugins.map((plugin) => {
      const loadedPlugin = require(plugin.name);
      if (plugin.opts) {
        return loadedPlugin(plugin.opts);
      }
      return loadedPlugin;
    });
  }

  function preparePostcssOptions(opts = {}, basePath) {
    const postcssOptions = {};

    if (opts.parser) {
      postcssOptions.parser = require(normalizePostcssPluginPath(basePath, opts.parser));
    }

    if (opts.syntax) {
      postcssOptions.syntax = require(normalizePostcssPluginPath(basePath, opts.syntax));
    }

    if (opts.stringifier) {
      postcssOptions.stringifier = require(normalizePostcssPluginPaths(basePath, opts.stringifier));
    }

    return postcssOptions;
  }

  function postprocess(styles, helperFunctions, db) {
    const postcssPlugins = config.productionMode ? config.postcss.plugins.prod : config.postcss.plugins.dev;
    const postcssNormalizedPlugins = normalizePostcssPluginPaths(db.get('basePath'), postcssPlugins);
    const postcssLoadedPlugins = loadPostcssPlugins(postcssNormalizedPlugins);

    const postcssOptions = preparePostcssOptions(config.postcss.opts, db.get('basePath'));

    return Promise.all(styles.map((style) => {
      if (style.isBundle) {
        style.contents = style.files.reduce((s, fileName) => {
          return s + styles.object[fileName].contents;
        }, '');
      }

      return postcss(postcssLoadedPlugins)
          .process(style.contents, postcssOptions)
          .then((result) => {
            result.writePath = style.writePath;
            return result;
          });
    }));
  }

  function write(styles, { writers }) {
    styles.forEach((style) => {
      writers.file(`${config.outputDir}/${style.writePath}`, style.css);
    });
  }

  return {
    read,
    preprocess,
    templateVariables,
    postprocess,
    write,
  };
}

const type = 'asset';
const name = 'styles';
function registration(register) {
  register(type, name, init);
}

module.exports = registration;
<commit_msg>Don't use PostCSS to process bundles<commit_after>'use strict';

const path = require('path');

const postcss = require('postcss');

function init({
    processorConfig,
    processorCommonConfig,
    commonConfig,
}) {
  const config = Object.assign({}, commonConfig, processorCommonConfig, processorConfig);

  function read(basePath, { readers }) {
    const stylePaths = readers.dir(`${basePath}`);
    const styles = stylePaths.map((stylePath) => {
      return {
        id: path.basename(stylePath),
        name: path.basename(stylePath),
        isBundle: false,
        contents: readers.fileToString(stylePath),
        stylePath,
      };
    });
    const bundles = config.bundles ? config.bundles.map((bundle) => {
      return {
        id: bundle.name,
        name: bundle.name,
        isBundle: true,
        files: bundle.files,
      };
    }) : [];
    return [...styles, ...bundles];
  }

  function preprocess(styles) {
    return styles.map((style) => {
      const next = Object.assign({}, style);
      next.writePath = `styles/${style.name}`;
      return next;
    });
  }

  function templateVariables(styles) {
    return styles.map((style) => {
      const next = Object.assign({}, style);
      next.url = `/styles/${style.name}`;
      return next;
    });
  }

  function normalizePostcssPluginPath(basePath, pluginName) {
    return path.resolve(basePath, 'node_modules', pluginName);
  }

  function normalizePostcssPluginPaths(basePath, plugins) {
    return plugins.map((plugin) => {
      if (plugin.name === 'cssnano') {
        return plugin;
      }
      return Object.assign({}, plugin, { name: normalizePostcssPluginPath(basePath, plugin.name) });
    });
  }

  function loadPostcssPlugins(plugins) {
    return plugins.map((plugin) => {
      const loadedPlugin = require(plugin.name);
      if (plugin.opts) {
        return loadedPlugin(plugin.opts);
      }
      return loadedPlugin;
    });
  }

  function preparePostcssOptions(opts = {}, basePath) {
    const postcssOptions = {};

    if (opts.parser) {
      postcssOptions.parser = require(normalizePostcssPluginPath(basePath, opts.parser));
    }

    if (opts.syntax) {
      postcssOptions.syntax = require(normalizePostcssPluginPath(basePath, opts.syntax));
    }

    if (opts.stringifier) {
      postcssOptions.stringifier = require(normalizePostcssPluginPaths(basePath, opts.stringifier));
    }

    return postcssOptions;
  }

  function postprocess(styles, helperFunctions, db) {
    const postcssPlugins = config.productionMode ? config.postcss.plugins.prod : config.postcss.plugins.dev;
    const postcssNormalizedPlugins = normalizePostcssPluginPaths(db.get('basePath'), postcssPlugins);
    const postcssLoadedPlugins = loadPostcssPlugins(postcssNormalizedPlugins);

    const postcssOptions = preparePostcssOptions(config.postcss.opts, db.get('basePath'));

    const bundles = [];
    const postprocessResults = {};

    const promises = styles // Ignore bundles for now
      .filter((style) => {
        if (style.isBundle) {
          bundles.push(style);
          return false;
        }
        return true;
      }) // postprocess all real files
      .map((style) => {
        return postcss(postcssLoadedPlugins)
          .process(style.contents, Object.assign(postcssOptions, { from: style.stylePath }))
          .then((result) => {
            result.writePath = style.writePath;
            postprocessResults[style.name] = result;
            return result;
          });
      });
    return Promise
      .all(promises)
      .then((results) => { // Now get bundle contents from the postprocess results
        const postprocessedBundles = bundles.map((bundle) => {
          bundle.css = bundle.files.reduce((s, fileName) => {
            return s + postprocessResults[fileName].css;
          }, '');
          return bundle;
        });
        return [...results, ...postprocessedBundles];
      });
  }

  function write(styles, { writers }) {
    styles.forEach((style) => {
      writers.file(`${config.outputDir}/${style.writePath}`, style.css);
    });
  }

  return {
    read,
    preprocess,
    templateVariables,
    postprocess,
    write,
  };
}

const type = 'asset';
const name = 'styles';
function registration(register) {
  register(type, name, init);
}

module.exports = registration;
<|endoftext|>


<commit_before>const consoleLogger = require('../../util/logger.js')
const http = require('http')
const extractTokenRegEx = /([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})/
const tokenFormatRegEx = /[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/
const TokenBlacklist = require('../../util/token-blacklist.js')

function jsonParse (text) {
  try {
    return JSON.parse(text)
  } catch (err) {
    return null
  }
}

function extractJson (line, source) {
  var parsed = {}
  if (/^\[{0,1}\{.*\}]{0,1}$/.test(line)) {
    parsed = jsonParse(line)
    if (!parsed) {
      return null
    }
    return parsed
  }
}

function InputHeroku (config, eventEmitter) {
  this.config = config
  this.eventEmitter = eventEmitter
  this.tokenBlackList = new TokenBlacklist(eventEmitter)
  this.config.port = this.config.heroku || config.port
  if (config.workers) {
    this.config.herokuWorkers = config.workers
  } else {
    this.config.herokuWorkers = undefined
  }
}
InputHeroku.prototype.start = function () {
  if (this.config.port) {
    this.throng = require('throng')
    this.throng({
      workers: this.config.herokuWorkers || this.WORKERS || 2,
      lifetime: Infinity
    }, this.startHerokuServer.bind(this))
  }
}

InputHeroku.prototype.stop = function (cb) {
  if (this.server) {
    this.server.close(cb)
  }
}

InputHeroku.prototype.getHttpServer = function (aport, handler) {
  var _port = aport || process.env.PORT
  if (aport === true) { // a command line flag was set but no port given
    _port = process.env.PORT
  }
  var server = http.createServer(handler)
  this.server = server
  try {
    server = server.listen(_port)
    consoleLogger.log('Logagent listening (http): ' + _port + ', process id: ' + process.pid)
    return server
  } catch (err) {
    consoleLogger.log('Port in use (' + _port + '): ' + err)
  }
}

function filterHerokuMessage (data, context) {
  if (data) {
    data._type = context.sourceName.replace('_' + context.index, '')
    data.logSource = ('' + data.logSource).replace('_' + context.index, '')
    var msg = {
      message: data.message,
      app: data.app,
      host: data.host,
      process_type: data.process_type,
      originalLine: data.originalLine,
      severity: data.severity,
      facility: data.facility
    }
    msg.json = extractJson(msg.message)
    var optionalFields = ['method', 'path', 'host', 'request_id', 'fwd', 'dyno', 'connect', 'service', 'status', 'bytes']
    optionalFields.forEach(function (f) {
      if (data[f]) {
        msg[f] = data[f]
      }
    })
    if (!data['@timestamp']) {
      msg['@timestamp'] = new Date()
    }
    return msg
  }
}

InputHeroku.prototype.herokuHandler = function (req, res) {
  try {
    var self = this
    var path = req.url.split('/')
    var token = null
    if (path.length > 1) {
      if (path[1] && path[1].length > 31 && tokenFormatRegEx.test(path[1])) {
        const match = path[1].match(extractTokenRegEx)
        if (match && match.length > 1) {
          token = match[1]
        }
      } else if (path[1] === 'health' || path[1] === 'ping') {
        res.statusCode = 200
        res.end('ok\n')
        return
      }
    }

    if (!token) {
      res.end('<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css"
Error: Missing Logsene Token ' +
        req.url + '. Please use /LOGSENE_TOKEN. More info:

Heroku Log Drain for Logsene

Logsene Log Management by Sematext

')
      return
    }

    if ((self.config.useIndexFromUrlPath === true && !token) || self.tokenBlackList.isTokenInvalid(token)) {
      res.statusCode = 404
      res.end(`invalid logs token in url ${req.url}\n`)
      return
    }

    var body = ''
    req.on('data', function (data) {
      body += data
    })
    req.on('end', function endHandler () {
      var lines = body.split('\n')
      lines.forEach(function (line) {
        if (!line) {
          return
        }
        self.eventEmitter.emit('data.raw', line, { sourceName: 'heroku_' + token, index: token, filter: filterHerokuMessage })
      })
      res.end('ok\n')
    })
  } catch (err) {
    consoleLogger.error('Error in Heroku (http): ' + err)
  }
}
// heroku start function for WEB_CONCURENCY
InputHeroku.prototype.startHerokuServer = function (id) {
  consoleLogger.log('start heroku worker: ' + id + ', pid:' + process.pid)
  this.getHttpServer(Number(this.config.port), this.herokuHandler.bind(this))
  var exitInProgress = false
  var terminate = function (reason) {
    return function () {
      if (exitInProgress) {
        return
      }
      exitInProgress = true
      consoleLogger.log('stop heroku worker: ' + id + ', pid:' + process.pid + ', terminate reason: ' + reason + ' memory rss: ' + (process.memoryUsage().rss / (1024 * 1024)).toFixed(2) + ' MB')
      setTimeout(process.exit, 250)
    }
  }
  process.once('SIGTERM', terminate('SIGTERM'))
  process.once('SIGINT', terminate('SIGINT'))
  process.once('exit', terminate('exit'))
}

module.exports = InputHeroku
<commit_msg>apply standard format<commit_after>const consoleLogger = require('../../util/logger.js')
const http = require('http')
const extractTokenRegEx = /([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})/
const tokenFormatRegEx = /[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/
const TokenBlacklist = require('../../util/token-blacklist.js')

function jsonParse (text) {
  try {
    return JSON.parse(text)
  } catch (err) {
    return null
  }
}

function extractJson (line, source) {
  var parsed = {}
  if (/^\[{0,1}\{.*\}]{0,1}$/.test(line)) {
    parsed = jsonParse(line)
    if (!parsed) {
      return null
    }
    return parsed
  }
}

function InputHeroku (config, eventEmitter) {
  this.config = config
  this.eventEmitter = eventEmitter
  this.tokenBlackList = new TokenBlacklist(eventEmitter)
  this.config.port = this.config.heroku || config.port
  if (config.workers) {
    this.config.herokuWorkers = config.workers
  } else {
    this.config.herokuWorkers = undefined
  }
}
InputHeroku.prototype.start = function () {
  if (this.config.port) {
    this.throng = require('throng')
    this.throng({
      workers: this.config.herokuWorkers || this.WORKERS || 2,
      lifetime: Infinity
    }, this.startHerokuServer.bind(this))
  }
}

InputHeroku.prototype.stop = function (cb) {
  if (this.server) {
    this.server.close(cb)
  }
}

InputHeroku.prototype.getHttpServer = function (aport, handler) {
  var _port = aport || process.env.PORT
  if (aport === true) { // a command line flag was set but no port given
    _port = process.env.PORT
  }
  var server = http.createServer(handler)
  this.server = server
  try {
    server = server.listen(_port)
    consoleLogger.log('Logagent listening (http): ' + _port + ', process id: ' + process.pid)
    return server
  } catch (err) {
    consoleLogger.log('Port in use (' + _port + '): ' + err)
  }
}

function filterHerokuMessage (data, context) {
  if (data) {
    data._type = context.sourceName.replace('_' + context.index, '')
    data.logSource = ('' + data.logSource).replace('_' + context.index, '')
    var msg = {
      message: data.message,
      app: data.app,
      host: data.host,
      process_type: data.process_type,
      originalLine: data.originalLine,
      severity: data.severity,
      facility: data.facility
    }
    msg.json = extractJson(msg.message)
    var optionalFields = ['method', 'path', 'host', 'request_id', 'fwd', 'dyno', 'connect', 'service', 'status', 'bytes']
    optionalFields.forEach(function (f) {
      if (data[f]) {
        msg[f] = data[f]
      }
    })
    if (!data['@timestamp']) {
      msg['@timestamp'] = new Date()
    }
    return msg
  }
}

InputHeroku.prototype.herokuHandler = function (req, res) {
  try {
    var self = this
    var path = req.url.split('/')
    var token = null
    if (path.length > 1) {
      if (path[1] && path[1].length > 31 && tokenFormatRegEx.test(path[1])) {
        const match = path[1].match(extractTokenRegEx)
        if (match && match.length > 1) {
          token = match[1]
        }
      } else if (path[1] === 'health' || path[1] === 'ping') {
        res.statusCode = 200
        res.end('ok\n')
        return
      }
    }

    if (!token) {
      res.end('<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css"
Error: Missing Logsene Token ' +
        req.url + '. Please use /LOGSENE_TOKEN. More info:

Heroku Log Drain for Logsene

Logsene Log Management by Sematext

')
      return
    }

    if ((self.config.useIndexFromUrlPath === true && !token) || self.tokenBlackList.isTokenInvalid(token)) {
      res.statusCode = 404
      res.end(`invalid logs token in url ${req.url}\n`)
      return
    }

    var body = ''
    req.on('data', function (data) {
      body += data
    })
    req.on('end', function endHandler () {
      var lines = body.split('\n')
      lines.forEach(function (line) {
        if (!line) {
          return
        }
        self.eventEmitter.emit('data.raw', line, { sourceName: 'heroku_' + token, index: token, filter: filterHerokuMessage })
      })
      res.end('ok\n')
    })
  } catch (err) {
    consoleLogger.error('Error in Heroku (http): ' + err)
  }
}
// heroku start function for WEB_CONCURENCY
InputHeroku.prototype.startHerokuServer = function (id) {
  consoleLogger.log('start heroku worker: ' + id + ', pid:' + process.pid)
  this.getHttpServer(Number(this.config.port), this.herokuHandler.bind(this))
  var exitInProgress = false
  var terminate = function (reason) {
    return function () {
      if (exitInProgress) {
        return
      }
      exitInProgress = true
      consoleLogger.log('stop heroku worker: ' + id + ', pid:' + process.pid + ', terminate reason: ' + reason + ' memory rss: ' + (process.memoryUsage().rss / (1024 * 1024)).toFixed(2) + ' MB')
      setTimeout(process.exit, 250)
    }
  }
  process.once('SIGTERM', terminate('SIGTERM'))
  process.once('SIGINT', terminate('SIGINT'))
  process.once('exit', terminate('exit'))
}

module.exports = InputHeroku
<|endoftext|>


<commit_before>var fs = require('fs'), // @todo: remove once HTML report contents have been verified
    path = require('path'),
    handlebars = require('handlebars'),

    PostmanHTMLReporter;

PostmanHTMLReporter = function (emitter, options) {
    // @todo load reporter template here so that we can give early warning if it fails
    // @todo throw error here or simply don't catch them and it will show up as warning on newman
    var exportPath = options.output; // @todo maybe validate writeable?

    emitter.on('beforeDone', function () {
        var HTML,
            compiler,
            templateContent = fs.readFileSync(path.join(__dirname, 'template-default.hbs'), { encoding: 'utf8' });

        compiler = handlebars.compile(templateContent);
        HTML = compiler(this);
        fs.writeFileSync(exportPath, HTML); // @todo: remove when validated

        this.summary.exports.push({
            path: exportPath,
            content: HTML
        });
    });
};

module.exports = PostmanHTMLReporter;
<commit_msg>Removed file writing code from HTML report compiler<commit_after>var fs = require('fs'), // @todo: remove once HTML report contents have been verified
    path = require('path'),
    handlebars = require('handlebars'),

    PostmanHTMLReporter;

PostmanHTMLReporter = function (emitter, options) {
    // @todo load reporter template here so that we can give early warning if it fails
    // @todo throw error here or simply don't catch them and it will show up as warning on newman
    var exportPath = options.output; // @todo maybe validate writeable?

    emitter.on('beforeDone', function () {
        var HTML,
            compiler,
            templateContent = fs.readFileSync(path.join(__dirname, 'template-default.hbs'), { encoding: 'utf8' });

        compiler = handlebars.compile(templateContent);
        HTML = compiler(this);

        this.summary.exports.push({
            path: exportPath,
            content: HTML
        });
    });
};

module.exports = PostmanHTMLReporter;
<|endoftext|>


<commit_before>
exports.name = "sotd.ac-review";
exports.check = function (sr, done) {
    var $sotd = sr.getSotDSection();
    if (!$sotd || !$sotd.length) {
        sr.error(exports.name, "no-sotd");
        return done();
    }
    var found = false;
    $sotd.find("a[href*='www.w3.org/2002/09/wbs/']").each(function() {
        var href = sr.$(this).attr("href");
        found = true;
        // XXX use an <a href> to display the link
        sr.warning(exports.name, "found", { link : href });
        return;
    });
    if (!found) sr.error(exports.name, "not-found");
    done();
};
<commit_msg>use info message instead of warning<commit_after>
exports.name = "sotd.ac-review";
exports.check = function (sr, done) {
    var $sotd = sr.getSotDSection();
    if (!$sotd || !$sotd.length) {
        sr.error(exports.name, "no-sotd");
        return done();
    }
    var found = false;
    $sotd.find("a[href*='www.w3.org/2002/09/wbs/']").each(function() {
        var href = sr.$(this).attr("href");
        found = true;
        // XXX use an <a href> to display the link
        sr.info(exports.name, "found", { link : href });
        return;
    });
    if (!found) sr.error(exports.name, "not-found");
    done();
};
<|endoftext|>


<commit_before>/**********************************************************\
|                                                          |
|                          hprose                          |
|                                                          |
| Official WebSite: http://www.hprose.com/                 |
|                   http://www.hprose.org/                 |
|                                                          |
\**********************************************************/

/**********************************************************\
 *                                                        *
 * HproseService.js                                       *
 *                                                        *
 * HproseService for Node.js.                             *
 *                                                        *
 * LastModified: Oct 19, 2014                             *
 * Author: Ma Bingyao <andot@hprose.com>                  *
 *                                                        *
\**********************************************************/

/*jshint node:true, eqeqeq:true */
'use strict';

var util = require('util');
var EventEmitter = require('events').EventEmitter;
var HproseResultMode = require('../common/HproseResultMode.js');
var HproseException = require('../common/HproseException.js');
var HproseTags = require('../io/HproseTags.js');
var HproseBufferInputStream = require('../io/HproseBufferInputStream.js');
var HproseBufferOutputStream = require('../io/HproseBufferOutputStream.js');
var HproseReader = require('../io/HproseReader.js');
var HproseWriter = require('../io/HproseWriter.js');

function callService(method, obj, execontext, args) {
    var result;
    if (typeof(method) === 'function') {
        result = method.apply(execontext, args);
    }
    else if (obj && typeof(obj[method]) === 'function') {
        result = obj[method].apply(execontext, args);
    }
    return result;
}

function arrayValues(obj) {
    var result = [];
    for (var key in obj) result.push(obj[key]);
    return result;
}

function getFuncName(func, obj) {
    var f = func.toString();
    var funcname = f.substr(0, f.indexOf('(')).replace(/(^\s*function\s*)|(\s*$)/ig, '');
    if ((funcname === '') && obj) {
        for (var name in obj) {
            if (obj[name] === func) return name;
        }
    }
    return funcname;
}

function responseEnd(ostream, context, filters) {
    var data = ostream.toBuffer();
    for (var i = 0, n = filters.length; i < n; i++) {
        data = filters[i].outputFilter(data, context);
    }
    context.__send__(data);
}

function getCallback(service, functionName, functionArgs, byref, resultMode, async, writer, context, filters) {
    return function(result) {
        service.emit('afterInvoke', functionName, functionArgs, byref, result, context);
        var ostream = writer.stream;
        if (resultMode === HproseResultMode.RawWithEndTag) {
            ostream.write(result);
            responseEnd(ostream, context, filters);
            return true;
        }
        else if (resultMode === HproseResultMode.Raw) {
            ostream.write(result);
        }
        else {
            ostream.write(HproseTags.TagResult);
            if (resultMode === HproseResultMode.Serialized) {
                ostream.write(result);
            }
            else {
                writer.reset();
                writer.serialize(result);
            }
            if (byref) {
                ostream.write(HproseTags.TagArgument);
                writer.reset();
                writer.writeList(functionArgs);
            }
        }
        if (async) {
            ostream.write(HproseTags.TagEnd);
            responseEnd(ostream, context, filters);
        }
        return false;
    };
}

function HproseService() {
    var m_functions = {};
    var m_funcNames = {};
    var m_debug = false;
    var m_simple = false;
    var m_filters = [];

    EventEmitter.call(this);

    // private methods
    function doInvoke(service, istream, context) {
        var async = false;
        var ostream = new HproseBufferOutputStream();
        var simpleReader = new HproseReader(istream, true);
        var tag;
        do {
            var functionName = simpleReader.readString();
            var aliasName = functionName.toLowerCase();
            var func = m_functions[aliasName] || m_functions['*'];
            var simple, writer;
            if (func) {
                simple = (func.simple === undefined ? m_simple : func.simple);
                writer = new HproseWriter(ostream, simple);
            }
            else {
                throw new HproseException('Can NOT find this function ' + functionName + '().');
            }
            var functionArgs = [];
            var byref = false;
            tag = simpleReader.checkTags([HproseTags.TagList,
                                              HproseTags.TagEnd,
                                              HproseTags.TagCall]);
            if (tag === HproseTags.TagList) {
                var reader = new HproseReader(istream, false, func.useHarmonyMap);
                functionArgs = reader.readListWithoutTag();
                tag = reader.checkTags([HproseTags.TagTrue,
                                        HproseTags.TagEnd,
                                        HproseTags.TagCall]);
                if (tag === HproseTags.TagTrue) {
                    byref = true;
                    tag = reader.checkTags([HproseTags.TagEnd,
                                            HproseTags.TagCall]);
                }
            }
            service.emit('beforeInvoke', functionName, functionArgs, byref, context);
            var callback = getCallback(service, functionName, functionArgs, byref, func.resultMode, func.async, writer, context, m_filters);
            if (func === m_functions['*']) {
                functionArgs = [functionName, functionArgs];
            }
            if (func.async) {
                async = true;
                callService(func.method, func.obj, func.execontext, functionArgs.concat([callback]));
            }
            else {
                if (callback(callService(func.method, func.obj, func.execontext, functionArgs))) return;
            }
        } while (tag === HproseTags.TagCall);
        if (!async) {
            ostream.write(HproseTags.TagEnd);
            responseEnd(ostream, context, m_filters);
        }
    }

    // protected methods

    this._doFunctionList = function(context) {
        var ostream = new HproseBufferOutputStream();
        var writer = new HproseWriter(ostream, true);
        var functions = arrayValues(m_funcNames);
        ostream.write(HproseTags.TagFunctions);
        writer.writeList(functions);
        ostream.write(HproseTags.TagEnd);
        responseEnd(ostream, context, m_filters);
    };

    this._handle = function(data, context) {
        for (var i = m_filters.length - 1; i >= 0; i--) {
            data = m_filters[i].inputFilter(data, context);
        }
        var istream = new HproseBufferInputStream(data);
        try {
            switch (istream.getc()) {
                case HproseTags.TagCall: return doInvoke(this, istream, context);
                case HproseTags.TagEnd: return this._doFunctionList(context);
                default: throw new HproseException('Wrong Request: \r\n' + data.toString());
            }
        }
        catch (e) {
            this.emit('sendError', e, context);
            var ostream = new HproseBufferOutputStream();
            var writer = new HproseWriter(ostream, true);
            ostream.write(HproseTags.TagError);
            writer.writeString(e.message);
            ostream.write(HproseTags.TagEnd);
            responseEnd(ostream, context, m_filters);
        }
    };

    // public methods
    this.isDebugEnabled = function() {
        return m_debug;
    };

    this.setDebugEnabled = function(enable) {
        if (enable === undefined) enable = true;
        m_debug = enable;
    };

    this.getSimpleMode = function() {
        return m_simple;
    };

    this.setSimpleMode = function(value) {
        if (value === undefined) value = true;
        m_simple = value;
    };

    this.addMissingFunction = function(func, resultMode, async, simple, useHarmonyMap) {
        this.addFunction(func, '*', resultMode, async, simple, useHarmonyMap);
    };

    this.addAsyncMissingFunction = function(func, resultMode, simple, useHarmonyMap) {
        this.addMissingFunction(func, resultMode, true, simple, useHarmonyMap);
    };

    this.addMissingMethod = function(method, obj, execontext, resultMode, async, simple, useHarmonyMap) {
        this.addMethod(method, obj, '*', execontext, resultMode, async, simple, useHarmonyMap);
    };

    this.addAsyncMissingMethod = function(method, obj, execontext, resultMode, simple, useHarmonyMap) {
        this.addMissingMethod(method, obj, execontext, resultMode, true, simple, useHarmonyMap);
    };

    this.addFunction = function(func, alias, resultMode, async, simple, useHarmonyMap) {
        if (resultMode === undefined) {
            resultMode = HproseResultMode.Normal;
        }
        if (alias === undefined || alias === null) {
            switch(typeof(func)) {
                case 'string':
                    alias = func;
                    break;
                case 'function':
                    alias = getFuncName(func);
                    if (alias === '') {
                        throw new HproseException('Need an alias');
                    }
                    break;
                default:
                    throw new HproseException('Need an alias');
            }
        }
        if (typeof(alias) === 'string') {
            var aliasName = alias.toLowerCase();
            m_functions[aliasName] = {method: func, obj: null, execontext: null, resultMode: resultMode, async: async, simple: simple, useHarmonyMap: useHarmonyMap};
            m_funcNames[aliasName] = alias;
        }
        else {
            throw new HproseException('Argument alias is not a string');
        }
    };

    this.addAsyncFunction = function(func, alias, resultMode, simple, useHarmonyMap) {
        this.addFunction(func, alias, resultMode, true, simple, useHarmonyMap);
    };

    this.addFunctions = function(functions, aliases, resultMode, async, simple, useHarmonyMap) {
        var count = functions.length;
        var i;
        if (aliases === undefined || aliases === null) {
            for (i = 0; i < count; i++) this.addFunction(functions[i], null, resultMode, async, simple, useHarmonyMap);
        }
        else {
            if (count !== aliases.length) {
                throw new HproseException('The count of functions is not matched with aliases');
            }
            for (i = 0; i < count; i++) this.addFunction(functions[i], aliases[i], resultMode, async, simple, useHarmonyMap);
        }
    };

    this.addAsyncFunctions = function(functions, aliases, resultMode, simple, useHarmonyMap) {
        this.addFunctions(functions, aliases, resultMode, true, simple, useHarmonyMap);
    };

    this.addMethod = function(method, obj, alias, execontext, resultMode, async, simple, useHarmonyMap) {
        if (obj === undefined || obj === null) {
            this.addFunction(method, alias, resultMode, async, simple, useHarmonyMap);
            return;
        }
        if (execontext === undefined) {
            execontext = obj;
        }
        if (resultMode === undefined) {
            resultMode = HproseResultMode.Normal;
        }
        if (alias === undefined || alias === null) {
            switch(typeof(method)) {
                case 'string':
                    alias = method;
                    break;
                case 'function':
                    alias = getFuncName(method, obj);
                    if (alias === '') {
                        throw new HproseException('Need an alias');
                    }
                    break;
                default:
                    throw new HproseException('Need an alias');
            }
        }
        if (typeof(alias) === 'string') {
            var aliasName = alias.toLowerCase();
            m_functions[aliasName] = {method: method, obj: obj, execontext: execontext, resultMode: resultMode, async: async, simple: simple, useHarmonyMap: useHarmonyMap};
            m_funcNames[aliasName] = alias;
        }
        else {
            throw new HproseException('Argument alias is not a string');
        }
    };

    this.addAsyncMethod = function(method, obj, alias, execontext, resultMode, simple, useHarmonyMap) {
        this.addMethod(method, obj, alias, execontext, resultMode, true, simple, useHarmonyMap);
    };

    this.addMethods = function(methods, obj, aliases, execontext, resultMode, async, simple, useHarmonyMap) {
        var count = methods.length;
        var i;
        if (aliases === undefined || aliases === null) {
            for (i = 0; i < count; i++) {
                this.addMethod(methods[i], obj, null, execontext, resultMode, async, simple, useHarmonyMap);
            }
        }
        else {
            if (count !== aliases.length) {
                throw new HproseException('The count of methods is not matched with aliases');
            }
            for (i = 0; i < count; i++) {
                this.addMethod(methods[i], obj, aliases[i], execontext, resultMode, async, simple, useHarmonyMap);
            }
        }
    };

    this.addAsyncMethods = function(methods, obj, aliases, execontext, resultMode, simple, useHarmonyMap) {
        this.addMethods(methods, obj, aliases, execontext, resultMode, true, simple, useHarmonyMap);
    };

    this.addInstanceMethods = function(obj, aliasPrefix, execontext, resultMode, async, simple, useHarmonyMap) {
        var alias;
        for (var name in obj) {
            alias = (aliasPrefix ? aliasPrefix + '_' + name : name);
            if (typeof(obj[name]) === 'function') {
                this.addMethod(obj[name], obj, alias, execontext, resultMode, async, simple, useHarmonyMap);
            }
        }
    };

    this.addAsyncInstanceMethods = function(obj, aliasPrefix, execontext, resultMode, async, simple, useHarmonyMap) {
        this.addInstanceMethods(obj, aliasPrefix, execontext, resultMode, true, simple, useHarmonyMap);
    };

    this.getFilter = function () {
        if (m_filters.length === 0) {
            return null;
        }
        return m_filters[0];
    };

    this.setFilter = function (filter) {
        m_filters.length = 0;
        if (filter !== undefined && filter !== null) {
            m_filters.push(filter);
        }
    };

    this.addFilter = function (filter) {
        m_filters.push(filter);
    };

    this.removeFilter = function (filter) {
        var i = m_filters.indexOf(filter);
        if (i === -1) {
            return false;
        }
        m_filters.splice(i, 1);
        return true;
    };
}

util.inherits(HproseService, EventEmitter);

module.exports = HproseService;<commit_msg>Changed the parameters' order of the add*.<commit_after>/**********************************************************\
|                                                          |
|                          hprose                          |
|                                                          |
| Official WebSite: http://www.hprose.com/                 |
|                   http://www.hprose.org/                 |
|                                                          |
\**********************************************************/

/**********************************************************\
 *                                                        *
 * HproseService.js                                       *
 *                                                        *
 * HproseService for Node.js.                             *
 *                                                        *
 * LastModified: Apr 26, 2015                             *
 * Author: Ma Bingyao <andot@hprose.com>                  *
 *                                                        *
\**********************************************************/

/*jshint node:true, eqeqeq:true */
'use strict';

var util = require('util');
var EventEmitter = require('events').EventEmitter;
var HproseResultMode = require('../common/HproseResultMode.js');
var HproseException = require('../common/HproseException.js');
var HproseTags = require('../io/HproseTags.js');
var HproseBufferInputStream = require('../io/HproseBufferInputStream.js');
var HproseBufferOutputStream = require('../io/HproseBufferOutputStream.js');
var HproseReader = require('../io/HproseReader.js');
var HproseWriter = require('../io/HproseWriter.js');

function callService(method, obj, execontext, args) {
    var result;
    if (typeof(method) === 'function') {
        result = method.apply(execontext, args);
    }
    else if (obj && typeof(obj[method]) === 'function') {
        result = obj[method].apply(execontext, args);
    }
    return result;
}

function arrayValues(obj) {
    var result = [];
    for (var key in obj) result.push(obj[key]);
    return result;
}

function getFuncName(func, obj) {
    var f = func.toString();
    var funcname = f.substr(0, f.indexOf('(')).replace(/(^\s*function\s*)|(\s*$)/ig, '');
    if ((funcname === '') && obj) {
        for (var name in obj) {
            if (obj[name] === func) return name;
        }
    }
    return funcname;
}

function responseEnd(ostream, context, filters) {
    var data = ostream.toBuffer();
    for (var i = 0, n = filters.length; i < n; i++) {
        data = filters[i].outputFilter(data, context);
    }
    context.__send__(data);
}

function getCallback(service, functionName, functionArgs, byref, resultMode, async, writer, context, filters) {
    return function(result) {
        service.emit('afterInvoke', functionName, functionArgs, byref, result, context);
        var ostream = writer.stream;
        if (resultMode === HproseResultMode.RawWithEndTag) {
            ostream.write(result);
            responseEnd(ostream, context, filters);
            return true;
        }
        else if (resultMode === HproseResultMode.Raw) {
            ostream.write(result);
        }
        else {
            ostream.write(HproseTags.TagResult);
            if (resultMode === HproseResultMode.Serialized) {
                ostream.write(result);
            }
            else {
                writer.reset();
                writer.serialize(result);
            }
            if (byref) {
                ostream.write(HproseTags.TagArgument);
                writer.reset();
                writer.writeList(functionArgs);
            }
        }
        if (async) {
            ostream.write(HproseTags.TagEnd);
            responseEnd(ostream, context, filters);
        }
        return false;
    };
}

function HproseService() {
    var m_functions = {};
    var m_funcNames = {};
    var m_debug = false;
    var m_simple = false;
    var m_filters = [];

    EventEmitter.call(this);

    // private methods
    function doInvoke(service, istream, context) {
        var async = false;
        var ostream = new HproseBufferOutputStream();
        var simpleReader = new HproseReader(istream, true);
        var tag;
        do {
            var functionName = simpleReader.readString();
            var aliasName = functionName.toLowerCase();
            var func = m_functions[aliasName] || m_functions['*'];
            var simple, writer;
            if (func) {
                simple = (func.simple === undefined ? m_simple : func.simple);
                writer = new HproseWriter(ostream, simple);
            }
            else {
                throw new HproseException('Can NOT find this function ' + functionName + '().');
            }
            var functionArgs = [];
            var byref = false;
            tag = simpleReader.checkTags([HproseTags.TagList,
                                              HproseTags.TagEnd,
                                              HproseTags.TagCall]);
            if (tag === HproseTags.TagList) {
                var reader = new HproseReader(istream, false, func.useHarmonyMap);
                functionArgs = reader.readListWithoutTag();
                tag = reader.checkTags([HproseTags.TagTrue,
                                        HproseTags.TagEnd,
                                        HproseTags.TagCall]);
                if (tag === HproseTags.TagTrue) {
                    byref = true;
                    tag = reader.checkTags([HproseTags.TagEnd,
                                            HproseTags.TagCall]);
                }
            }
            service.emit('beforeInvoke', functionName, functionArgs, byref, context);
            var callback = getCallback(service, functionName, functionArgs, byref, func.resultMode, func.async, writer, context, m_filters);
            if (func === m_functions['*']) {
                functionArgs = [functionName, functionArgs];
            }
            if (func.async) {
                async = true;
                callService(func.method, func.obj, func.execontext, functionArgs.concat([callback]));
            }
            else {
                if (callback(callService(func.method, func.obj, func.execontext, functionArgs))) return;
            }
        } while (tag === HproseTags.TagCall);
        if (!async) {
            ostream.write(HproseTags.TagEnd);
            responseEnd(ostream, context, m_filters);
        }
    }

    // protected methods

    this._doFunctionList = function(context) {
        var ostream = new HproseBufferOutputStream();
        var writer = new HproseWriter(ostream, true);
        var functions = arrayValues(m_funcNames);
        ostream.write(HproseTags.TagFunctions);
        writer.writeList(functions);
        ostream.write(HproseTags.TagEnd);
        responseEnd(ostream, context, m_filters);
    };

    this._handle = function(data, context) {
        for (var i = m_filters.length - 1; i >= 0; i--) {
            data = m_filters[i].inputFilter(data, context);
        }
        var istream = new HproseBufferInputStream(data);
        try {
            switch (istream.getc()) {
                case HproseTags.TagCall: return doInvoke(this, istream, context);
                case HproseTags.TagEnd: return this._doFunctionList(context);
                default: throw new HproseException('Wrong Request: \r\n' + data.toString());
            }
        }
        catch (e) {
            this.emit('sendError', e, context);
            var ostream = new HproseBufferOutputStream();
            var writer = new HproseWriter(ostream, true);
            ostream.write(HproseTags.TagError);
            writer.writeString(e.message);
            ostream.write(HproseTags.TagEnd);
            responseEnd(ostream, context, m_filters);
        }
    };

    // public methods
    this.isDebugEnabled = function() {
        return m_debug;
    };

    this.setDebugEnabled = function(enable) {
        if (enable === undefined) enable = true;
        m_debug = enable;
    };

    this.getSimpleMode = function() {
        return m_simple;
    };

    this.setSimpleMode = function(value) {
        if (value === undefined) value = true;
        m_simple = value;
    };

    this.addMissingFunction = function(func, resultMode, simple, useHarmonyMap, async) {
        this.addFunction(func, '*', resultMode, simple, useHarmonyMap, async);
    };

    this.addAsyncMissingFunction = function(func, resultMode, simple, useHarmonyMap) {
        this.addMissingFunction(func, resultMode, simple, useHarmonyMap, true);
    };

    this.addMissingMethod = function(method, obj, execontext, resultMode, simple, useHarmonyMap, async) {
        this.addMethod(method, obj, '*', execontext, resultMode, simple, useHarmonyMap, async);
    };

    this.addAsyncMissingMethod = function(method, obj, execontext, resultMode, simple, useHarmonyMap) {
        this.addMissingMethod(method, obj, execontext, resultMode, simple, useHarmonyMap, true);
    };

    this.addFunction = function(func, alias, resultMode, simple, useHarmonyMap, async) {
        if (resultMode === undefined) {
            resultMode = HproseResultMode.Normal;
        }
        if (alias === undefined || alias === null) {
            switch(typeof(func)) {
                case 'string':
                    alias = func;
                    break;
                case 'function':
                    alias = getFuncName(func);
                    if (alias === '') {
                        throw new HproseException('Need an alias');
                    }
                    break;
                default:
                    throw new HproseException('Need an alias');
            }
        }
        if (typeof(alias) === 'string') {
            var aliasName = alias.toLowerCase();
            m_functions[aliasName] = {method: func,
                                      obj: null,
                                      execontext: null,
                                      resultMode: resultMode,
                                      useHarmonyMap: useHarmonyMap,
                                      simple: simple,
                                      async: async};
            m_funcNames[aliasName] = alias;
        }
        else {
            throw new HproseException('Argument alias is not a string');
        }
    };

    this.addAsyncFunction = function(func, alias, resultMode, simple, useHarmonyMap) {
        this.addFunction(func, alias, resultMode, simple, useHarmonyMap, true);
    };

    this.addFunctions = function(functions, aliases, resultMode, simple, useHarmonyMap, async) {
        var count = functions.length;
        var i;
        if (aliases === undefined || aliases === null) {
            for (i = 0; i < count; i++) this.addFunction(functions[i], null, resultMode, simple, useHarmonyMap, async);
        }
        else {
            if (count !== aliases.length) {
                throw new HproseException('The count of functions is not matched with aliases');
            }
            for (i = 0; i < count; i++) this.addFunction(functions[i], aliases[i], resultMode, simple, useHarmonyMap, async);
        }
    };

    this.addAsyncFunctions = function(functions, aliases, resultMode, simple, useHarmonyMap) {
        this.addFunctions(functions, aliases, resultMode, simple, useHarmonyMap, true);
    };

    this.addMethod = function(method, obj, alias, execontext, resultMode, simple, useHarmonyMap, async) {
        if (obj === undefined || obj === null) {
            this.addFunction(method, alias, resultMode, simple, useHarmonyMap, async);
            return;
        }
        if (execontext === undefined) {
            execontext = obj;
        }
        if (resultMode === undefined) {
            resultMode = HproseResultMode.Normal;
        }
        if (alias === undefined || alias === null) {
            switch(typeof(method)) {
                case 'string':
                    alias = method;
                    break;
                case 'function':
                    alias = getFuncName(method, obj);
                    if (alias === '') {
                        throw new HproseException('Need an alias');
                    }
                    break;
                default:
                    throw new HproseException('Need an alias');
            }
        }
        if (typeof(alias) === 'string') {
            var aliasName = alias.toLowerCase();
            m_functions[aliasName] = {method: method,
                                      obj: obj,
                                      execontext: execontext,
                                      resultMode: resultMode,
                                      simple: simple,
                                      useHarmonyMap: useHarmonyMap,
                                      async: async};
            m_funcNames[aliasName] = alias;
        }
        else {
            throw new HproseException('Argument alias is not a string');
        }
    };

    this.addAsyncMethod = function(method, obj, alias, execontext, resultMode, simple, useHarmonyMap) {
        this.addMethod(method, obj, alias, execontext, resultMode, simple, useHarmonyMap, true);
    };

    this.addMethods = function(methods, obj, aliases, execontext, resultMode, simple, useHarmonyMap, async) {
        var count = methods.length;
        var i;
        if (aliases === undefined || aliases === null) {
            for (i = 0; i < count; i++) {
                this.addMethod(methods[i], obj, null, execontext, resultMode, simple, useHarmonyMap, async);
            }
        }
        else {
            if (count !== aliases.length) {
                throw new HproseException('The count of methods is not matched with aliases');
            }
            for (i = 0; i < count; i++) {
                this.addMethod(methods[i], obj, aliases[i], execontext, resultMode, simple, useHarmonyMap, async);
            }
        }
    };

    this.addAsyncMethods = function(methods, obj, aliases, execontext, resultMode, simple, useHarmonyMap) {
        this.addMethods(methods, obj, aliases, execontext, resultMode, simple, useHarmonyMap, true);
    };

    this.addInstanceMethods = function(obj, aliasPrefix, execontext, resultMode, simple, useHarmonyMap, async) {
        var alias;
        for (var name in obj) {
            alias = (aliasPrefix ? aliasPrefix + '_' + name : name);
            if (typeof(obj[name]) === 'function') {
                this.addMethod(obj[name], obj, alias, execontext, resultMode, simple, useHarmonyMap, async);
            }
        }
    };

    this.addAsyncInstanceMethods = function(obj, aliasPrefix, execontext, resultMode, simple, useHarmonyMap) {
        this.addInstanceMethods(obj, aliasPrefix, execontext, resultMode, simple, useHarmonyMap, true);
    };

    this.getFilter = function () {
        if (m_filters.length === 0) {
            return null;
        }
        return m_filters[0];
    };

    this.setFilter = function (filter) {
        m_filters.length = 0;
        if (filter !== undefined && filter !== null) {
            m_filters.push(filter);
        }
    };

    this.addFilter = function (filter) {
        m_filters.push(filter);
    };

    this.removeFilter = function (filter) {
        var i = m_filters.indexOf(filter);
        if (i === -1) {
            return false;
        }
        m_filters.splice(i, 1);
        return true;
    };
}

util.inherits(HproseService, EventEmitter);

module.exports = HproseService;<|endoftext|>


<commit_before>;(function(global){

  if (typeof basis == 'undefined' || !basis.data)
    return;

  //
  // import names
  //

  var DataObject = basis.data.DataObject;
  var Dataset = basis.data.Dataset;
  var STATE = basis.data.STATE;

  var console = global.console;
  if (typeof console == 'undefined')
    console = {
      log: function(){},
      warn: function(){}
    };

  //
  // local vars
  //

  var sendToServer = function(){
    console.warn('basisjs-tools: Server backend is not available');
  };

  var serverState = new DataObject({
    data: {
      isReady: false,
      isOnline: false,
      connectionState: 'offline'
    }
  });

  //
  // Files
  //

  var files = new Dataset();
  var fileMap = {};

  var File = DataObject.subclass({
    read: function(){
      this.setState(STATE.PROCESSING);

      var file = this;
      sendToServer('readFile', this.data.filename, function(data){
        file.update(data);
      });
    },
    save: function(content){
      this.update({
        content: content
      });
      this.setState(STATE.PROCESSING);

      var self = this;
      sendToServer('saveFile', this.data.filename, content, true, function(err){
        if (err)
        {
          self.setState(STATE.ERROR, err);
          console.log('basisjs-tools: File `' + self.data.filename + '` saving error: ', err);
        }
        else
        {
          self.setState(STATE.READY);
          console.log('basisjs-tools: File `' + self.data.filename + '` successfuly saved');
        }
      });
    },
    event_update: function(delta){
      DataObject.prototype.event_update.call(this, delta);

      if ('filename' in delta || 'content' in delta)
        basis.resource(this.data.filename).update(this.data.content);
    }
  });

  function loadFiles(filelist){
    var files_ = [];
    for (var i = 0, fileData; fileData = filelist[i]; i++)
    {
      if (fileData.type == 'file')
      {
        var file = new File(basis.data({
          filename: fileData.filename
        }));

        fileMap[fileData.filename] = file;
        files_.push(file);
      }
    }
    files.set(files_);
  }

  function createFile(data){
    // check for file existence
    var filename = data.filename;
    var file = fileMap[filename];

    if (!file){
      // create new file
      file = new File(basis.data({
        filename: filename,
        content: data.content
      }));

      fileMap[filename] = file;
      files.add([file]);
    }

    return file;
  }

  function updateFile(data){
    var file = getFile(data.filename);
    if (file)
    {
      file.update(data);
      file.setState(STATE.READY);
    }
  }

  function removeFile(filename){
    var file = fileMap[filename];

    if (file)
    {
      delete fileMap[filename];
      file.destroy();
    }
  }

  function getFile(filename, autocreate){
    var file = fileMap[filename];

    if (!file && autocreate)
    {
      file = createFile({
        filename: filename
      });
      file.setState(STATE.UNDEFINED);
    }

    return file;
  }

  //
  // script event handlers
  //

  function onError(){
    if (this.parentNode)
      this.parentNode.removeChild(this);

    console.warn('basisjs-tools: Error on loading ' + this.src);
  }

  function onLoad(){
    if (this.parentNode)
      this.parentNode.removeChild(this);

    if (typeof io == 'undefined')
      return;

    //appcp.init();

    console.log('basisjs-tools: Connecting to server via socket.io');

    var socket = io.connect('/');
    serverState.update({ isReady: true });

    var sendToServerOffline = function(){
      console.warn('basisjs-tools: No connection with server :( Trying to send:', arguments);
    };

    var sendToServerOnline = function(){
      console.log('basisjs-tools: Send to server: ', arguments[0], arguments[1]);
      socket.emit.apply(socket, arguments);
    };

    //
    // add callbacks on events
    //
    basis.object.iterate({
      //
      // connection events
      //
      connect: function(){
        socket.emit('observe');
        sendToServer = sendToServerOnline;

        serverState.update({ isOnline: true });
      },
      disconnect: function(){
        sendToServer = sendToServerOffline;

        serverState.update({ isOnline: false });
      },
      observeReady: function(filelist){
        loadFiles(filelist);
      },
      //
      // file events
      //
      newFile: function(data){
        createFile(data);
        console.log('basisjs-tools: New file', data);
      },
      updateFile: function(data){
        updateFile(data);
        console.log('basisjs-tools: File updated', data);
      },
      deleteFile: function(data){
        removeFile(data.filename);
        console.log('basisjs-tools: File deleted', data);
      },

      //
      // common events
      //
      error: function(data){
        console.log('basisjs-tools: Error:', data.operation, data.message);
      }
    }, socket.on, socket);
  }

  //
  // App Control Panel
  //
  var appcp = (function(){
    var socket;
    var transportInited = false;
    var deferredCalls = [];

    function init(){
      socket = io.connect('http://localhost:8001');
      socket.on('connect', function(){
        sendMessage('clientConnected');
      });
      socket.on('message', function(message){
        if (message.action == 'appcpReady')
        {
          initTransport();
          deferredCalls.splice(0).forEach(processCall);
        }

        if (message.action == 'call' && basis.appCP)
        {
          if (basis.appCP)
            processCall(message);
          else
            deferredCalls.push(message);
        }
      });
    }

    function processCall(message){
      var fn = basis.appCP[message.data.method];
      if (typeof fn == 'function')
        basis.appCP[message.data.method].apply(null, message.data.args);
      else
        console.warn('basisjs-tools: Unknown ACP method:', message.data.method);
    }

    function initTransport(){
      if (transportInited)
      {
        sendMessage('ready');
        return;
      }

      var transferDiv = document.getElementById('transferDiv');
      if (transferDiv)
      {
        transferDiv.addEventListener('transferData', function(){
          var action = transferDiv.getAttribute('action');
          var data = transferDiv.innerText;

          console.log('basisjs-tools: transfer data action:', action);
          //console.log('transfer data:', data);

          sendMessage(action, data);
        });

        transportInited = true;
        sendMessage('ready');
      }
      else
      {
        console.warn('basisjs-tools: basis devpanel not found');
      }
    }

    function sendMessage(action, data){
      socket.emit('message', {
        action: action,
        data: data
      });
    }

    return {
      init: init
    };
  })();

  //
  // init part
  //

  basis.ready(function(){
    var scriptEl = document.createElement('script');

    scriptEl.src = "/socket.io/socket.io.js";
    scriptEl.onload = onLoad;
    scriptEl.onerror = onError;

    document.getElementsByTagName('head')[0].appendChild(scriptEl);
  });

  //
  // export names
  //

  basis.devtools = {
    serverState: serverState,
    files: files,

    getFileGraph: function(callback){
      sendToServer('getFileGraph', location.href, callback);
    },

    getFile: getFile,
    createFile: function(filename){
      sendToServer('createFile', filename);
    }
  };

})(this);<commit_msg>fix live update for new basis.js<commit_after>;(function(global){

  if (typeof basis == 'undefined' || !basis.data)
    return;

  //
  // import names
  //

  var DataObject = basis.data.Object;
  var Dataset = basis.data.Dataset;
  var STATE = basis.data.STATE;

  var console = global.console;
  if (typeof console == 'undefined')
    console = {
      log: function(){},
      warn: function(){}
    };

  //
  // local vars
  //

  var sendToServer = function(){
    console.warn('basisjs-tools: Server backend is not available');
  };

  var serverState = new DataObject({
    data: {
      isReady: false,
      isOnline: false,
      connectionState: 'offline'
    }
  });

  //
  // Files
  //

  var files = new Dataset();
  var fileMap = {};

  var File = DataObject.subclass({
    read: function(){
      this.setState(STATE.PROCESSING);

      var file = this;
      sendToServer('readFile', this.data.filename, function(data){
        file.update(data);
      });
    },
    save: function(content){
      this.update({
        content: content
      });
      this.setState(STATE.PROCESSING);

      var self = this;
      sendToServer('saveFile', this.data.filename, content, true, function(err){
        if (err)
        {
          self.setState(STATE.ERROR, err);
          console.log('basisjs-tools: File `' + self.data.filename + '` saving error: ', err);
        }
        else
        {
          self.setState(STATE.READY);
          console.log('basisjs-tools: File `' + self.data.filename + '` successfuly saved');
        }
      });
    },
    // for new basis
    dispatch_update: function(delta){
      DataObject.prototype.dispatch_update.call(this, delta);

      if ('filename' in delta || 'content' in delta)
        basis.resource(this.data.filename).update(this.data.content);
    },
    // for previous basis version
    event_update: function(delta){
      DataObject.prototype.event_update.call(this, delta);

      if ('filename' in delta || 'content' in delta)
        basis.resource(this.data.filename).update(this.data.content);
    }
  });

  function loadFiles(filelist){
    var files_ = [];
    for (var i = 0, fileData; fileData = filelist[i]; i++)
    {
      if (fileData.type == 'file')
      {
        var file = new File(basis.data({
          filename: fileData.filename
        }));

        fileMap[fileData.filename] = file;
        files_.push(file);
      }
    }
    files.set(files_);
  }

  function createFile(data){
    // check for file existence
    var filename = data.filename;
    var file = fileMap[filename];

    if (!file){
      // create new file
      file = new File(basis.data({
        filename: filename,
        content: data.content
      }));

      fileMap[filename] = file;
      files.add([file]);
    }

    return file;
  }

  function updateFile(data){
    var file = getFile(data.filename);
    if (file)
    {
      file.update(data);
      file.setState(STATE.READY);
    }
  }

  function removeFile(filename){
    var file = fileMap[filename];

    if (file)
    {
      delete fileMap[filename];
      file.destroy();
    }
  }

  function getFile(filename, autocreate){
    var file = fileMap[filename];

    if (!file && autocreate)
    {
      file = createFile({
        filename: filename
      });
      file.setState(STATE.UNDEFINED);
    }

    return file;
  }

  //
  // script event handlers
  //

  function onError(){
    if (this.parentNode)
      this.parentNode.removeChild(this);

    console.warn('basisjs-tools: Error on loading ' + this.src);
  }

  function onLoad(){
    if (this.parentNode)
      this.parentNode.removeChild(this);

    if (typeof io == 'undefined')
      return;

    //appcp.init();

    console.log('basisjs-tools: Connecting to server via socket.io');

    var socket = io.connect('/');
    serverState.update({ isReady: true });

    var sendToServerOffline = function(){
      console.warn('basisjs-tools: No connection with server :( Trying to send:', arguments);
    };

    var sendToServerOnline = function(){
      console.log('basisjs-tools: Send to server: ', arguments[0], arguments[1]);
      socket.emit.apply(socket, arguments);
    };

    //
    // add callbacks on events
    //
    basis.object.iterate({
      //
      // connection events
      //
      connect: function(){
        socket.emit('observe');
        sendToServer = sendToServerOnline;

        serverState.update({ isOnline: true });
      },
      disconnect: function(){
        sendToServer = sendToServerOffline;

        serverState.update({ isOnline: false });
      },
      observeReady: function(filelist){
        loadFiles(filelist);
      },
      //
      // file events
      //
      newFile: function(data){
        createFile(data);
        console.log('basisjs-tools: New file', data);
      },
      updateFile: function(data){
        updateFile(data);
        console.log('basisjs-tools: File updated', data);
      },
      deleteFile: function(data){
        removeFile(data.filename);
        console.log('basisjs-tools: File deleted', data);
      },

      //
      // common events
      //
      error: function(data){
        console.log('basisjs-tools: Error:', data.operation, data.message);
      }
    }, socket.on, socket);
  }

  //
  // App Control Panel
  //
  var appcp = (function(){
    var socket;
    var transportInited = false;
    var deferredCalls = [];

    function init(){
      socket = io.connect('http://localhost:8001');
      socket.on('connect', function(){
        sendMessage('clientConnected');
      });
      socket.on('message', function(message){
        if (message.action == 'appcpReady')
        {
          initTransport();
          deferredCalls.splice(0).forEach(processCall);
        }

        if (message.action == 'call' && basis.appCP)
        {
          if (basis.appCP)
            processCall(message);
          else
            deferredCalls.push(message);
        }
      });
    }

    function processCall(message){
      var fn = basis.appCP[message.data.method];
      if (typeof fn == 'function')
        basis.appCP[message.data.method].apply(null, message.data.args);
      else
        console.warn('basisjs-tools: Unknown ACP method:', message.data.method);
    }

    function initTransport(){
      if (transportInited)
      {
        sendMessage('ready');
        return;
      }

      var transferDiv = document.getElementById('transferDiv');
      if (transferDiv)
      {
        transferDiv.addEventListener('transferData', function(){
          var action = transferDiv.getAttribute('action');
          var data = transferDiv.innerText;

          console.log('basisjs-tools: transfer data action:', action);
          //console.log('transfer data:', data);

          sendMessage(action, data);
        });

        transportInited = true;
        sendMessage('ready');
      }
      else
      {
        console.warn('basisjs-tools: basis devpanel not found');
      }
    }

    function sendMessage(action, data){
      socket.emit('message', {
        action: action,
        data: data
      });
    }

    return {
      init: init
    };
  })();

  //
  // init part
  //

  basis.ready(function(){
    var scriptEl = document.createElement('script');

    scriptEl.src = "/socket.io/socket.io.js";
    scriptEl.onload = onLoad;
    scriptEl.onerror = onError;

    document.getElementsByTagName('head')[0].appendChild(scriptEl);
  });

  //
  // export names
  //

  basis.devtools = {
    serverState: serverState,
    files: files,

    getFileGraph: function(callback){
      sendToServer('getFileGraph', location.href, callback);
    },

    getFile: getFile,
    createFile: function(filename){
      sendToServer('createFile', filename);
    }
  };

})(this);<|endoftext|>


<commit_before>var OAuth2 = require("./oauth2")

function NinjaBlocks(options) {
  ["code", "token", "user"].forEach(function(name) {
    this[name] = Object.create(this[name])
  }, this)

  this.code.query = {
    client_id: options.id,
    response_type: "code",
    scope: options.scope || []
  }

  this.token.query = {
    client_id: options.id,
    client_secret: options.secret,
    grant_type: "authorization_code"
  }

  this.user.query = {}

  this.on("request", this.onRequest.bind(this))
}

NinjaBlocks.prototype = new OAuth2

NinjaBlocks.prototype.code = {
  protocol: "https",
  host: "api.ninja.is",
  pathname: "/oauth/authorize"
}

NinjaBlocks.prototype.token = {
  method: "POST",
  host: "api.ninja.is",
  path: "/oauth/access_token"
}

NinjaBlocks.prototype.user = {
  host: "api.ninja.is",
  path: "/rest/v1/user"
}

module.exports = NinjaBlocks<commit_msg>Inherit from the OAuth2 class correctly<commit_after>var OAuth2 = require("./oauth2")

function NinjaBlocks(options) {

  this.code.query = {
    client_id: options.id,
    response_type: "code",
    scope: options.scope || []
  }

  this.token.query = {
    client_id: options.id,
    client_secret: options.secret,
    grant_type: "authorization_code"
  }

  this.user.query = {}
  console.log(this)
  this.on("request", this.onRequest.bind(this))
}

require('util').inherits(NinjaBlocks, OAuth2)

NinjaBlocks.prototype.code = {
  protocol: "https",
  host: "api.ninja.is",
  pathname: "/oauth/authorize"
}

NinjaBlocks.prototype.token = {
  method: "POST",
  host: "api.ninja.is",
  path: "/oauth/access_token"
}

NinjaBlocks.prototype.user = {
  host: "api.ninja.is",
  path: "/rest/v1/user"
}

module.exports = NinjaBlocks<|endoftext|>


<commit_before>'use strict';

module.exports = function(config, specificOptions) {
  config.set({
    frameworks: ['jasmine'],
    autoWatch: true,
    logLevel: config.LOG_INFO,
    logColors: true,
    browsers: ['Chrome'],
    browserDisconnectTimeout: 10000,
    browserDisconnectTolerance: 2,
    browserNoActivityTimeout: 20000,

    // SauceLabs config for local development.
    sauceLabs: {
      testName: specificOptions.testName || 'AngularJS',
      startConnect: true,
      options: {
        'selenium-version': '2.41.0'
      }
    },

    // BrowserStack config for local development.
    browserStack: {
      project: 'AngularJS',
      name: specificOptions.testName,
      startTunnel: true,
      timeout: 600 // 10min
    },

    // For more browsers on Sauce Labs see:
    // https://saucelabs.com/docs/platforms/webdriver
    customLaunchers: {
      'SL_Chrome': {
        base: 'SauceLabs',
        browserName: 'chrome',
        version: '34'
      },
      'SL_Firefox': {
        base: 'SauceLabs',
        browserName: 'firefox',
        version: '26'
      },
      'SL_Safari': {
        base: 'SauceLabs',
        browserName: 'safari',
        platform: 'OS X 10.9',
        version: '7'
      },
      'SL_IE_9': {
        base: 'SauceLabs',
        browserName: 'internet explorer',
        platform: 'Windows 2008',
        version: '9'
      },
      'SL_IE_10': {
        base: 'SauceLabs',
        browserName: 'internet explorer',
        platform: 'Windows 2012',
        version: '10'
      },
      'SL_IE_11': {
        base: 'SauceLabs',
        browserName: 'internet explorer',
        platform: 'Windows 8.1',
        version: '11'
      },

      'BS_Chrome': {
        base: 'BrowserStack',
        browser: 'chrome',
        os: 'OS X',
        os_version: 'Mountain Lion'
      },
      'BS_Safari': {
        base: 'BrowserStack',
        browser: 'safari',
        os: 'OS X',
        os_version: 'Mountain Lion'
      },
      'BS_Firefox': {
        base: 'BrowserStack',
        browser: 'firefox',
        os: 'Windows',
        os_version: '8'
      },
      'BS_IE_9': {
        base: 'BrowserStack',
        browser: 'ie',
        browser_version: '9.0',
        os: 'Windows',
        os_version: '7'
      },
      'BS_IE_10': {
        base: 'BrowserStack',
        browser: 'ie',
        browser_version: '10.0',
        os: 'Windows',
        os_version: '8'
      },
      'BS_IE_11': {
        base: 'BrowserStack',
        browser: 'ie',
        browser_version: '11.0',
        os: 'Windows',
        os_version: '8.1'
      }
    }
  });

  if (process.env.TRAVIS) {
    var buildLabel = 'TRAVIS #' + process.env.TRAVIS_BUILD_NUMBER + ' (' + process.env.TRAVIS_BUILD_ID + ')';

    config.logLevel = config.LOG_DEBUG;
    config.transports = ['websocket', 'xhr-polling'];
    config.captureTimeout = 0; // rely on SL timeout

    config.browserStack.build = buildLabel;
    config.browserStack.startTunnel = false;

    config.sauceLabs.build = buildLabel;
    config.sauceLabs.startConnect = false;
    config.sauceLabs.tunnelIdentifier = process.env.TRAVIS_JOB_NUMBER;
    config.sauceLabs.recordScreenshots = true;

    // TODO(vojta): remove once SauceLabs supports websockets.
    // This speeds up the capturing a bit, as browsers don't even try to use websocket.
    config.transports = ['xhr-polling'];

    // Debug logging into a file, that we print out at the end of the build.
    config.loggers.push({
      type: 'file',
      filename: process.env.LOGS_DIR + '/' + (specificOptions.logFile || 'karma.log')
    });
  }

  // Terrible hack to workaround inflexibility of log4js:
  // - ignore web-server's 404 warnings,
  // - ignore DEBUG logs (on Travis), we log them into a file instead.
  var IGNORED_404 = [
    '/favicon.ico',
    '/%7B%7BtestUrl%7D%7D',
    '/someSanitizedUrl',
    '/{{testUrl}}'
  ];
  var log4js = require('./node_modules/karma/node_modules/log4js');
  var layouts = require('./node_modules/karma/node_modules/log4js/lib/layouts');
  var originalConfigure = log4js.configure;
  log4js.configure = function(log4jsConfig) {
    var consoleAppender = log4jsConfig.appenders.shift();
    var originalResult = originalConfigure.call(log4js, log4jsConfig);
    var layout = layouts.layout(consoleAppender.layout.type, consoleAppender.layout);

    log4js.addAppender(function(log) {
      var msg = log.data[0];

      // ignore web-server's 404s
      if (log.categoryName === 'web-server' && log.level.levelStr === config.LOG_WARN &&
          IGNORED_404.some(function(ignoredLog) {return msg.indexOf(ignoredLog) !== -1;})) {
        return;
      }

      // on Travis, ignore DEBUG statements
      if (process.env.TRAVIS && log.level.levelStr === config.LOG_DEBUG) {
        return;
      }

      console.log(layout(log));
    });

    return originalResult;
  };
};
<commit_msg>chore(travis): increase browserNoActivityTimeout<commit_after>'use strict';

module.exports = function(config, specificOptions) {
  config.set({
    frameworks: ['jasmine'],
    autoWatch: true,
    logLevel: config.LOG_INFO,
    logColors: true,
    browsers: ['Chrome'],
    browserDisconnectTimeout: 10000,
    browserDisconnectTolerance: 2,
    browserNoActivityTimeout: 30000,

    // SauceLabs config for local development.
    sauceLabs: {
      testName: specificOptions.testName || 'AngularJS',
      startConnect: true,
      options: {
        'selenium-version': '2.41.0'
      }
    },

    // BrowserStack config for local development.
    browserStack: {
      project: 'AngularJS',
      name: specificOptions.testName,
      startTunnel: true,
      timeout: 600 // 10min
    },

    // For more browsers on Sauce Labs see:
    // https://saucelabs.com/docs/platforms/webdriver
    customLaunchers: {
      'SL_Chrome': {
        base: 'SauceLabs',
        browserName: 'chrome',
        version: '34'
      },
      'SL_Firefox': {
        base: 'SauceLabs',
        browserName: 'firefox',
        version: '26'
      },
      'SL_Safari': {
        base: 'SauceLabs',
        browserName: 'safari',
        platform: 'OS X 10.9',
        version: '7'
      },
      'SL_IE_9': {
        base: 'SauceLabs',
        browserName: 'internet explorer',
        platform: 'Windows 2008',
        version: '9'
      },
      'SL_IE_10': {
        base: 'SauceLabs',
        browserName: 'internet explorer',
        platform: 'Windows 2012',
        version: '10'
      },
      'SL_IE_11': {
        base: 'SauceLabs',
        browserName: 'internet explorer',
        platform: 'Windows 8.1',
        version: '11'
      },

      'BS_Chrome': {
        base: 'BrowserStack',
        browser: 'chrome',
        os: 'OS X',
        os_version: 'Mountain Lion'
      },
      'BS_Safari': {
        base: 'BrowserStack',
        browser: 'safari',
        os: 'OS X',
        os_version: 'Mountain Lion'
      },
      'BS_Firefox': {
        base: 'BrowserStack',
        browser: 'firefox',
        os: 'Windows',
        os_version: '8'
      },
      'BS_IE_9': {
        base: 'BrowserStack',
        browser: 'ie',
        browser_version: '9.0',
        os: 'Windows',
        os_version: '7'
      },
      'BS_IE_10': {
        base: 'BrowserStack',
        browser: 'ie',
        browser_version: '10.0',
        os: 'Windows',
        os_version: '8'
      },
      'BS_IE_11': {
        base: 'BrowserStack',
        browser: 'ie',
        browser_version: '11.0',
        os: 'Windows',
        os_version: '8.1'
      }
    }
  });

  if (process.env.TRAVIS) {
    var buildLabel = 'TRAVIS #' + process.env.TRAVIS_BUILD_NUMBER + ' (' + process.env.TRAVIS_BUILD_ID + ')';

    config.logLevel = config.LOG_DEBUG;
    config.transports = ['websocket', 'xhr-polling'];
    config.captureTimeout = 0; // rely on SL timeout

    config.browserStack.build = buildLabel;
    config.browserStack.startTunnel = false;

    config.sauceLabs.build = buildLabel;
    config.sauceLabs.startConnect = false;
    config.sauceLabs.tunnelIdentifier = process.env.TRAVIS_JOB_NUMBER;
    config.sauceLabs.recordScreenshots = true;

    // TODO(vojta): remove once SauceLabs supports websockets.
    // This speeds up the capturing a bit, as browsers don't even try to use websocket.
    config.transports = ['xhr-polling'];

    // Debug logging into a file, that we print out at the end of the build.
    config.loggers.push({
      type: 'file',
      filename: process.env.LOGS_DIR + '/' + (specificOptions.logFile || 'karma.log')
    });
  }

  // Terrible hack to workaround inflexibility of log4js:
  // - ignore web-server's 404 warnings,
  // - ignore DEBUG logs (on Travis), we log them into a file instead.
  var IGNORED_404 = [
    '/favicon.ico',
    '/%7B%7BtestUrl%7D%7D',
    '/someSanitizedUrl',
    '/{{testUrl}}'
  ];
  var log4js = require('./node_modules/karma/node_modules/log4js');
  var layouts = require('./node_modules/karma/node_modules/log4js/lib/layouts');
  var originalConfigure = log4js.configure;
  log4js.configure = function(log4jsConfig) {
    var consoleAppender = log4jsConfig.appenders.shift();
    var originalResult = originalConfigure.call(log4js, log4jsConfig);
    var layout = layouts.layout(consoleAppender.layout.type, consoleAppender.layout);

    log4js.addAppender(function(log) {
      var msg = log.data[0];

      // ignore web-server's 404s
      if (log.categoryName === 'web-server' && log.level.levelStr === config.LOG_WARN &&
          IGNORED_404.some(function(ignoredLog) {return msg.indexOf(ignoredLog) !== -1;})) {
        return;
      }

      // on Travis, ignore DEBUG statements
      if (process.env.TRAVIS && log.level.levelStr === config.LOG_DEBUG) {
        return;
      }

      console.log(layout(log));
    });

    return originalResult;
  };
};
<|endoftext|>


<commit_before>module.exports = function(config, specificOptions) {
  config.set({
    frameworks: ['jasmine'],
    autoWatch: true,
    logLevel: config.LOG_INFO,
    logColors: true,
    browsers: ['Chrome'],
    browserDisconnectTimeout: 10000,

    // config for Travis CI
    sauceLabs: {
      testName: specificOptions.testName || 'AngularJS',
      startConnect: false,
      tunnelIdentifier: process.env.TRAVIS_JOB_NUMBER
    },

    // BrowserStack config for Travis CI
    browserStack: {
      startTunnel: false
    },

    // For more browsers on Sauce Labs see:
    // https://saucelabs.com/docs/platforms/webdriver
    customLaunchers: {
      'SL_Chrome': {
        base: 'SauceLabs',
        browserName: 'chrome'
      },
      'SL_Firefox': {
        base: 'SauceLabs',
        browserName: 'firefox'
      },
      'SL_Safari': {
        base: 'SauceLabs',
        browserName: 'safari',
        platform: 'Mac 10.8',
        version: '6'
      },
      'SL_IE_8': {
        base: 'SauceLabs',
        browserName: 'internet explorer',
        platform: 'Windows 7',
        version: '8'
      },
      'SL_IE_9': {
        base: 'SauceLabs',
        browserName: 'internet explorer',
        platform: 'Windows 2008',
        version: '9'
      },
      'SL_IE_10': {
        base: 'SauceLabs',
        browserName: 'internet explorer',
        platform: 'Windows 2012',
        version: '10'
      },

      'BS_Chrome': {
        base: 'BrowserStack',
        browser: 'chrome',
        os: 'OS X',
        os_version: 'Mountain Lion'
      },
      'BS_Safari': {
        base: 'BrowserStack',
        browser: 'safari',
        os: 'OS X',
        os_version: 'Mountain Lion'
      },
      'BS_Firefox': {
        base: 'BrowserStack',
        browser: 'firefox',
        os: 'Windows',
        os_version: '8'
      },
      'BS_IE_8': {
        base: 'BrowserStack',
        browser: 'ie',
        browser_version: '8.0',
        os: 'Windows',
        os_version: '7'
      },
      'BS_IE_9': {
        base: 'BrowserStack',
        browser: 'ie',
        browser_version: '9.0',
        os: 'Windows',
        os_version: '7'
      },
      'BS_IE_10': {
        base: 'BrowserStack',
        browser: 'ie',
        browser_version: '10.0',
        os: 'Windows',
        os_version: '8'
      },
      'BS_IE_11': {
        base: 'BrowserStack',
        browser: 'ie',
        browser_version: '11.0',
        os: 'Windows',
        os_version: '8.1'
      }
    }
  });

  if (process.env.TRAVIS) {
    // Debug logging into a file, that we print out at the end of the build.
    config.loggers.push({
      type: 'file',
      filename: process.env.LOGS_DIR + '/' + (specificOptions.logFile || 'karma.log'),
      level: config.LOG_DEBUG
    });
  }
};
<commit_msg>chore(travis): add some more info for BrowserStack sessions<commit_after>module.exports = function(config, specificOptions) {
  config.set({
    frameworks: ['jasmine'],
    autoWatch: true,
    logLevel: config.LOG_INFO,
    logColors: true,
    browsers: ['Chrome'],
    browserDisconnectTimeout: 10000,

    // config for Travis CI
    sauceLabs: {
      testName: specificOptions.testName || 'AngularJS',
      startConnect: false,
      tunnelIdentifier: process.env.TRAVIS_JOB_NUMBER
    },

    // BrowserStack config for Travis CI
    browserStack: {
      startTunnel: false,
      project: 'AngularJS',
      name: specificOptions.testName,
      build: process.env.TRAVIS_BUILD_NUMBER
    },

    // For more browsers on Sauce Labs see:
    // https://saucelabs.com/docs/platforms/webdriver
    customLaunchers: {
      'SL_Chrome': {
        base: 'SauceLabs',
        browserName: 'chrome'
      },
      'SL_Firefox': {
        base: 'SauceLabs',
        browserName: 'firefox'
      },
      'SL_Safari': {
        base: 'SauceLabs',
        browserName: 'safari',
        platform: 'Mac 10.8',
        version: '6'
      },
      'SL_IE_8': {
        base: 'SauceLabs',
        browserName: 'internet explorer',
        platform: 'Windows 7',
        version: '8'
      },
      'SL_IE_9': {
        base: 'SauceLabs',
        browserName: 'internet explorer',
        platform: 'Windows 2008',
        version: '9'
      },
      'SL_IE_10': {
        base: 'SauceLabs',
        browserName: 'internet explorer',
        platform: 'Windows 2012',
        version: '10'
      },

      'BS_Chrome': {
        base: 'BrowserStack',
        browser: 'chrome',
        os: 'OS X',
        os_version: 'Mountain Lion'
      },
      'BS_Safari': {
        base: 'BrowserStack',
        browser: 'safari',
        os: 'OS X',
        os_version: 'Mountain Lion'
      },
      'BS_Firefox': {
        base: 'BrowserStack',
        browser: 'firefox',
        os: 'Windows',
        os_version: '8'
      },
      'BS_IE_8': {
        base: 'BrowserStack',
        browser: 'ie',
        browser_version: '8.0',
        os: 'Windows',
        os_version: '7'
      },
      'BS_IE_9': {
        base: 'BrowserStack',
        browser: 'ie',
        browser_version: '9.0',
        os: 'Windows',
        os_version: '7'
      },
      'BS_IE_10': {
        base: 'BrowserStack',
        browser: 'ie',
        browser_version: '10.0',
        os: 'Windows',
        os_version: '8'
      },
      'BS_IE_11': {
        base: 'BrowserStack',
        browser: 'ie',
        browser_version: '11.0',
        os: 'Windows',
        os_version: '8.1'
      }
    }
  });

  if (process.env.TRAVIS) {
    // Debug logging into a file, that we print out at the end of the build.
    config.loggers.push({
      type: 'file',
      filename: process.env.LOGS_DIR + '/' + (specificOptions.logFile || 'karma.log'),
      level: config.LOG_DEBUG
    });
  }
};
<|endoftext|>


<commit_before>//
// Implementations of primitive methods
// This is loaded at the very end, everything is already available
// If this gets too long, split it in multiple files
//

ProtoObject._addClassMethods({
	basicNew: function() { return this._newInstance(); },
	_new: function() { return this.basicNew().initialize(); },
	name: function() { return this._classname; }
});
ProtoObject._addInstanceMethods({
	_equals_equals: function(anObject) { return bool(this === anObject); },
	identityHash: function() { return number(this.instanceNumber$); }
});

_Object._addInstanceMethods({
	_class: function() { return this.__class; },
	halt: function() { debugger; },
});

Exception._addInstanceMethods({
	signal: function(){ throw this }
});

String._addInstanceMethods({
	// This is not actually a primitive function, but behaves in the same way the #, method does
	_comma: function(anotherString) { return string(this.string$ + anotherString.string$) },
	_equals: function(anotherString) { return bool(this.string$ == anotherString.string$) },
	isEmpty: function() { return bool(this.string$.length == 0) },
	size: function() { return number(this.string$.length); },
	at_: function(num) { return character(this.string$[num.num$ - 1]); }
});

ByteString._addInstanceMethods({
	at_: function(num) { return character(this.string$[num.num$ - 1]); }
});

/*
at_ should also be defined in:
ByteSymbol
WideString
WideSymbol
*/

_Number._addInstanceMethods({
	printString: function() { return string(this.num$.toString()); }
});

Float._addInstanceMethods({
	_plus: function(other) { return number(this.num$ + other.num$); },
	_minus: function(other) { return number(this.num$ - other.num$); },
	_times: function(other) { return number(this.num$ * other.num$); },
	_slash: function(other) { return number(this.num$ / other.num$); },
	floor: function() { return number(Math.floor(this.num$)); },
	_less: function(other) {
		return bool(this.num$ < other.num$);
	},
	_greater: function(other) {
		return bool(this.num$ > other.num$);
	},
	_less_equals: function(other) {
		return bool(this.num$ <= other.num$);
	},
	_greater_equals: function(other) {
		return bool(this.num$ >= other.num$);
	},
	_equals: function(other) {
		return bool(this.num$ == other.num$);
	},
	timesRepeat_: function(aBlock){
		for (var i = 0; i < this.num$; i++) {
			aBlock.value();
		}
		return this;
	},
	truncated: function() {
		return number(Math.floor(this.num$));
	}
});

Point._addInstanceMethods({
	_times: function(aNumber){
		return (this.x()._times(aNumber))._at(this.y()._times(aNumber));
	}
});

var _blockValueFunction_ = function(){ return this.func$.apply(this, arguments); };
BlockClosure._addInstanceMethods({
	value: _blockValueFunction_,
	value_: _blockValueFunction_,
	value_value_: _blockValueFunction_,
	value_value_value_: _blockValueFunction_,
	value_value_value_value_: _blockValueFunction_,

	whileTrue_: function(anotherBlock) {
		while (this.value() === _true) {
			anotherBlock.value();
		}
		return nil;
	},
	whileTrue: function(anotherBlock) {
		// TODO implement whileTrue: for real
		while (this.value() === _true) ;
		return nil;
	},
	whileFalse_: function() {
		while (this.value() === _false) {
			anotherBlock.value();
		}
		return nil;
	},
	whileFalse: function() {
		while (this.value() === _false) ;
		return nil;
	}
});

_Array._addInstanceMethods({
	size: function(){
		return number(this.arr$.length);
	},
	at_put_: function(idx, val){
		this.arr$[idx.num$ - 1] = val;
		return val;
	},
	at_: function(idx){
		return this.arr$[idx.num$ - 1];
	},
	isEmpty: function(){
		return bool(this.arr$.length == 0);
	}
});
_Array._addClassMethods({
	new_: function(size){
		var arr = new Array(size.num$);
		for (var i = 0; i < size.num$; i++) {
			arr[i] = nil;
		}
		return array(arr);
	}
});

// Defined in bootstrap.js. Must be called after primitives-initialization.
AddJsFunctionToAllObjects();
<commit_msg>added _tilde_equals primitive to Float<commit_after>//
// Implementations of primitive methods
// This is loaded at the very end, everything is already available
// If this gets too long, split it in multiple files
//

ProtoObject._addClassMethods({
	basicNew: function() { return this._newInstance(); },
	_new: function() { return this.basicNew().initialize(); },
	name: function() { return this._classname; }
});
ProtoObject._addInstanceMethods({
	_equals_equals: function(anObject) { return bool(this === anObject); },
	identityHash: function() { return number(this.instanceNumber$); }
});

_Object._addInstanceMethods({
	_class: function() { return this.__class; },
	halt: function() { debugger; },
});

Exception._addInstanceMethods({
	signal: function(){ throw this }
});

String._addInstanceMethods({
	// This is not actually a primitive function, but behaves in the same way the #, method does
	_comma: function(anotherString) { return string(this.string$ + anotherString.string$) },
	_equals: function(anotherString) { return bool(this.string$ == anotherString.string$) },
	isEmpty: function() { return bool(this.string$.length == 0) },
	size: function() { return number(this.string$.length); },
	at_: function(num) { return character(this.string$[num.num$ - 1]); }
});

ByteString._addInstanceMethods({
	at_: function(num) { return character(this.string$[num.num$ - 1]); }
});

/*
at_ should also be defined in:
ByteSymbol
WideString
WideSymbol
*/

_Number._addInstanceMethods({
	printString: function() { return string(this.num$.toString()); }
});

Float._addInstanceMethods({
	_plus: function(other) { return number(this.num$ + other.num$); },
	_minus: function(other) { return number(this.num$ - other.num$); },
	_times: function(other) { return number(this.num$ * other.num$); },
	_slash: function(other) { return number(this.num$ / other.num$); },
	floor: function() { return number(Math.floor(this.num$)); },
	_less: function(other) {
		return bool(this.num$ < other.num$);
	},
	_greater: function(other) {
		return bool(this.num$ > other.num$);
	},
	_less_equals: function(other) {
		return bool(this.num$ <= other.num$);
	},
	_greater_equals: function(other) {
		return bool(this.num$ >= other.num$);
	},
	_equals: function(other) {
		return bool(this.num$ == other.num$);
	},
	_tilde_equals: function(other) {
	  return bool(this.num$ != other.num$);
	},
	timesRepeat_: function(aBlock){
		for (var i = 0; i < this.num$; i++) {
			aBlock.value();
		}
		return this;
	},
	truncated: function() {
		return number(Math.floor(this.num$));
	}
});

Point._addInstanceMethods({
	_times: function(aNumber){
		return (this.x()._times(aNumber))._at(this.y()._times(aNumber));
	}
});

var _blockValueFunction_ = function(){ return this.func$.apply(this, arguments); };
BlockClosure._addInstanceMethods({
	value: _blockValueFunction_,
	value_: _blockValueFunction_,
	value_value_: _blockValueFunction_,
	value_value_value_: _blockValueFunction_,
	value_value_value_value_: _blockValueFunction_,

	whileTrue_: function(anotherBlock) {
		while (this.value() === _true) {
			anotherBlock.value();
		}
		return nil;
	},
	whileTrue: function(anotherBlock) {
		// TODO implement whileTrue: for real
		while (this.value() === _true) ;
		return nil;
	},
	whileFalse_: function() {
		while (this.value() === _false) {
			anotherBlock.value();
		}
		return nil;
	},
	whileFalse: function() {
		while (this.value() === _false) ;
		return nil;
	}
});

_Array._addInstanceMethods({
	size: function(){
		return number(this.arr$.length);
	},
	at_put_: function(idx, val){
		this.arr$[idx.num$ - 1] = val;
		return val;
	},
	at_: function(idx){
		return this.arr$[idx.num$ - 1];
	},
	isEmpty: function(){
		return bool(this.arr$.length == 0);
	}
});
_Array._addClassMethods({
	new_: function(size){
		var arr = new Array(size.num$);
		for (var i = 0; i < size.num$; i++) {
			arr[i] = nil;
		}
		return array(arr);
	}
});

// Defined in bootstrap.js. Must be called after primitives-initialization.
AddJsFunctionToAllObjects();
<|endoftext|>