<commit_before>/**
 * Created by nuintun on 2015/4/27.
 */

'use strict';

var path = require('path');
var util = require('util');
var cmd = require('cmd-deps');
var css = require('@nuintun/css-deps');
var debug = require('debug')('gulp-cmd');
var plugins = require('./plugins/index');
var gutil = require('@nuintun/gulp-util');

var join = path.join;
var extname = path.extname;
var dirname = path.dirname;
var basename = path.basename;
var relative = path.relative;
var write = process.stdout.write;

// regexp
var OUTBOUNDRE = /(?:^[\\\/]?)\.\.(?:[\\\/]|$)/;
var SPLITRE = /\/((?:\d+\.){2}\d+)(?:\/|$)/;
var PATHSRE = /^([^/:]+)(\/.+)$/;
var VARSRE = /{([^{]+)}/g;

// set debug color use 6
debug.color = 6;

/**
 * rename
 *
 * @param {any} path
 * @param {any} transform
 * @returns {String}
 */
function rename(path, transform) {
  return gutil.rename(path, transform, debug);
}

/**
 * transport
 *
 * @param {any} vinyl
 * @param {any} options
 * @param {any} done
 * @returns {void}
 */
function transport(vinyl, options, done) {
  return gutil.transport(vinyl, options, done, debug);
}

/**
 * resolve
 *
 * @param {any} relative
 * @param {any} vinyl
 * @param {any} wwwroot
 * @returns {String}
 */
function resolve(relative, vinyl, wwwroot) {
  return gutil.resolve(relative, vinyl, wwwroot, debug);
}

/**
 * pring
 *
 * @returns {void}
 */
function print() {
  var message = gutil.apply(util.format, null, gutil.slice.call(arguments));

  write(gutil.colors.cyan.bold('  gulp-cmd ') + message + '\n');
}

/**
 * get rename options
 *
 * @param transform
 * @returns {Object}
 */
function initRenameOptions(transform) {
  if (gutil.isFunction(transform)) {
    return transform;
  }

  transform = transform || {};

  if (transform.min) {
    transform.suffix = '-min';
  }

  if (transform.debug) {
    transform.suffix = '-debug';
  }

  return transform;
}

/**
 * init options
 *
 * @param options
 * @returns {Object}
 */
function initOptions(options) {
  // mix
  options = gutil.extend(true, {
    css: {}, // { prefix: null, onpath: null }
    map: {}, // the map
    vars: {}, // the vars
    paths: {}, // the paths
    alias: {}, // the alias
    cache: true, // use memory file cahe
    ignore: [], // omit the given dependencies when include
    wwwroot: '', // web root
    rename: null, // { debug: boolean, min: boolean }
    plugins: null, // file trnasport plugins
    include: 'relative', // include model: self, relative, all
    idleading: '{{name}}/{{version}}/{{file}}' // the id prefix template
  }, options);

  // wwwroot must be string
  if (!gutil.isString(options.wwwroot)) {
    gutil.throwError('options.wwwroot\'s value should be string.');
  }

  // init wwwroot
  options.wwwroot = join(gutil.cwd, options.wwwroot);
  // init plugins
  options.plugins = gutil.plugins(options.plugins, plugins);
  // init css settings
  options.css = options.css || {};
  // init rename
  options.rename = initRenameOptions(options.rename);
  // init ignore
  options.ignore = gutil.isArray(options.ignore) ? options.ignore : [];
  // init js settings
  options.js = options.js || {};
  // init js flags
  if (!options.js.hasOwnProperty('flags')) {
    options.js.flags = ['async'];
  }

  return options;
}

/**
 * resolve id leading
 *
 * @param idleading
 * @param path
 * @param pkg
 * @returns {String}
 */
function resolveIdleading(idleading, path, pkg) {
  return gutil.isFunction(idleading) ? idleading(path, pkg) : idleading;
}

/**
 * transport vinyl id
 *
 * @param vinyl
 * @param options
 * @returns {String}
 */
function transportId(vinyl, options) {
  var id;
  var pkg = parsePackage(vinyl, options.wwwroot);
  var idleading = resolveIdleading(options.idleading, vinyl.path, pkg);

  // get id
  id = template(idleading, pkg);
  // rename id
  id = addExt(id);
  id = rename(id, options.rename);
  id = hideExt(id);

  // seajs has hacked css before 3.0.0
  // https://github.com/seajs/seajs/blob/2.2.1/src/util-path.js#L49
  // demo https://github.com/popomore/seajs-test/tree/master/css-deps
  if (extname(id) === '.css') {
    id += '.js';
  }

  // normalize id
  id = gutil.normalize(id);
  id = id.replace(/^\.\//, '');
  id = id.replace(/^\/\//, '/');

  // debug
  debug('transport id: %s', gutil.colors.magenta(id));

  // rewrite vinyl path
  if (isAbsolute(id)) {
    vinyl.path = join(options.wwwroot, addExt(id));
  } else {
    vinyl.path = join(vinyl.cwd, vinyl.base, addExt(id));
  }

  // parse map
  id = parseMap(id, options.map);

  // set vinyl package info
  vinyl.package = gutil.extend(pkg, { id: id });

  return id;
}

/**
 * transport cmd dependencies.
 * @param vinyl
 * @param options
 * @returns {object}
 */
function transportDeps(vinyl, options) {
  var deps = [];
  var include = [];
  var vars = options.vars;
  var alias = options.alias;
  var paths = options.paths;
  var pkg = vinyl.package || {};

  // replace require and collect dependencies
  vinyl.contents = new Buffer(cmd(vinyl.contents.toString(), function(id, flag) {
    // parse id form alias, paths, vars
    id = parseAlias(id, alias);
    id = parsePaths(id, paths);
    id = parseAlias(id, alias);
    id = parseVars(id, vars);
    id = parseAlias(id, alias);

    // id is not a local file
    if (!isLocal(id)) {
      // cache dependencie id
      deps.push(id);
    } else {
      var path;

      // normalize id
      id = gutil.normalize(id);

      // if end with /, find index file
      if (id.substring(id.length - 1) === '/') {
        id += 'index';
      }

      // debug
      debug('transport%s deps: %s', flag ? ' ' + flag : '', gutil.colors.magenta(id));

      // add extname
      path = addExt(id);
      // rename id
      id = rename(path, options.rename);
      // hide extname
      id = hideExt(id);

      // seajs has hacked css before 3.0.0
      // https://github.com/seajs/seajs/blob/2.2.1/src/util-path.js#L49
      // demo https://github.com/popomore/seajs-test/tree/master/css-deps
      if (extname(id) === '.css') {
        id += '.js';
      }

      // normalize id
      id = gutil.normalize(id);
      // parse map
      id = parseMap(id, options.map);

      // cache dependencie id and path
      if (flag === null) {
        // cache dependencie id
        deps.push(id);

        // get absolute path
        path = resolve(path, vinyl, options.wwwroot);

        // cache dependencie absolute path
        include.push({
          id: id,
          path: path
        });
      }
    }

    return id;
  }, options.js.flags));

  // cache file dependencies
  vinyl.package = gutil.extend(pkg, {
    include: include,
    dependencies: deps
  });

  return deps;
}

/**
 * transport css dependencies.
 *
 * @param vinyl
 * @param options
 * @returns {Array}
 */
function transportCssDeps(vinyl, options) {
  var deps = [];
  var include = [];
  var pkg = vinyl.package || {};
  var onpath = options.css.onpath;
  var prefix = options.css.prefix;

  // init css settings
  onpath = gutil.isFunction(onpath) ? function(path, property) {
    return options.css.onpath(path, property, vinyl.path, options.wwwroot);
  } : null;
  prefix = gutil.isFunction(prefix) ? prefix(vinyl.path, options.wwwroot) : prefix;

  // replace imports and collect dependencies
  vinyl.contents = new Buffer(css(vinyl.contents, function(id) {
    var path;

    // id is not a local file
    if (!isLocal(id)) {
      // cache dependencie id
      deps.push(id);
    } else {
      // normalize id
      id = gutil.normalize(id);

      var isRelative = gutil.isRelative(id);
      var isAbsolute = gutil.isAbsolute(id);

      // css import parsing rules using html
      if (!isAbsolute && !isRelative) {
        id = './' + id;
      }

      // if end with /, find index file
      if (id.substring(id.length - 1) === '/') {
        id += 'index.css';
      }

      // debug
      debug('transport deps: %s', gutil.colors.magenta(id));

      // add extname
      path = addExt(id);
      // rename id
      id = rename(path, options.rename);
      // hide extname
      id = hideExt(id);

      // seajs has hacked css before 3.0.0
      // https://github.com/seajs/seajs/blob/2.2.1/src/util-path.js#L49
      // demo https://github.com/popomore/seajs-test/tree/master/css-deps
      if (extname(id) === '.css') {
        id += '.js';
      }

      // normalize id
      id = gutil.normalize(id);
      // parse map
      id = parseMap(id, options.map);

      // get absolute path
      path = resolve(path, vinyl, options.wwwroot);

      // cache dependencie id
      deps.push(id);
      // cache dependencie absolute path
      include.push({
        id: id,
        path: path
      });
    }

    // delete all import
    return false;
  }, { prefix: prefix, onpath: onpath }));

  // Cache file dependencies
  vinyl.package = gutil.extend(pkg, {
    include: include,
    dependencies: deps
  });

  return deps;
}

/**
 * parse package form vinyl
 * @param vinyl
 * @param wwwroot
 * @returns {object}
 */
function parsePackage(vinyl, wwwroot) {
  var relative = vinyl.relative;

  // vinyl not in base dir, user wwwroot
  if (OUTBOUNDRE.test(relative)) {
    relative = path.relative(wwwroot, vinyl.path);
    // vinyl not in wwwroot, throw error
    if (OUTBOUNDRE.test(relative)) {
      throwError('file: %s is out of bound of wwwroot: %s.', normalize(vinyl.path), normalize(wwwroot));
    }

    // reset relative
    relative = path.join('/', relative);
  }

  var dir = gutil.normalize(dirname(relative));
  var filename = basename(relative);
  var match = dir.split(SPLITRE);

  return {
    name: match[0] || '',
    version: match[1] || '',
    file: match[2] ? match[2] + '/' + filename : filename
  }
}

/**
 * simple template
 * @param format
 * @param data
 * @returns {string}
 * ```
 * var tpl = '{{name}}/{{version}}';
 * util.template(tpl, {name:'base', version: '1.0.0'});
 * ```
 */
function template(format, data) {
  if (!gutil.isString(format)) return '';

  return format.replace(/{{([a-z]*)}}/gi, function(all, match) {
    return data[match] || '';
  });
}

/**
 * parse alias
 * @param id
 * @param alias
 * @returns {String}
 */
function parseAlias(id, alias) {
  alias = alias || {};

  return alias && gutil.isString(alias[id]) ? alias[id] : id;
}

/**
 * parse paths
 * @param id
 * @param paths
 * @returns {String}
 */
function parsePaths(id, paths) {
  var match;

  paths = paths || {};

  if (paths && (match = id.match(PATHSRE)) && gutil.isString(paths[match[1]])) {
    id = paths[match[1]] + match[2];
  }

  return id;
}

/**
 * parse vars
 * @param id
 * @param vars
 * @returns {String}
 */
function parseVars(id, vars) {
  vars = vars || {};

  if (vars && id.indexOf('{') !== -1) {
    id = id.replace(VARSRE, function(match, key) {
      return gutil.isString(vars[key]) ? vars[key] : match;
    });
  }

  return id;
}

/**
 * parse map
 * @param id
 * @param map
 * @returns {String}
 */
function parseMap(id, map) {
  var ret = id;

  if (Array.isArray(map)) {
    for (var i = 0, len = map.length; i < len; i++) {
      var rule = map[i];

      // parse map
      if (gutil.isFunction(rule)) {
        ret = rule(id);
      } else if (Array.isArray(rule)) {
        ret = id.replace(rule[0], rule[1]);
      }

      // must be string
      if (!ret || !gutil.isString(ret)) {
        ret = id;
      }

      // only apply the first matched rule
      if (ret !== id) break;
    }
  }

  return ret;
}

/**
 * add .js if not exists
 * @param path
 * @returns {*}
 */
function addExt(path) {
  return extname(path) === '.js' ? path : (path + '.js');
}

/**
 * hide .js if exists
 * @param path
 * @returns {*}
 */
function hideExt(path) {
  return extname(path) === '.js' ? path.replace(/\.js$/, '') : path;
}

/**
 * wrap module
 * @param id
 * @param deps
 * @param code
 * @returns {string}
 */
function wrapModule(id, deps, code) {
  // header and footer template string
  var header = 'define({{id}}, {{deps}}, function(require, exports, module){';
  var footer = '});\n';

  if (Buffer.isBuffer(code)) code = code.toString();

  // debug
  debug('compile module: %s', colors.magenta(id));

  id = JSON.stringify(id);
  deps = JSON.stringify(deps);

  return template(header, { id: id, deps: deps })
    + '\n' + code + '\n' + footer;
}

/**
 * print message
 */
function print() {
  var slice = [].slice;
  var message = util.format
    .apply(null, slice.call(arguments));

  process.stdout.write(gutil.colors.cyan.bold('  gulp-cmd ') + message + '\n');
}

/**
 * exports module
 */
module.exports = {
  debug: debug,
  rename: rename,
  transport: transport,
  resolve: resolve,
  print: print,
  initOptions: initOptions,
  transportId: transportId,
  transportDeps: transportDeps,
  transportCssDeps: transportCssDeps,
  parsePackage: parsePackage,
  template: template,
  parseAlias: parseAlias,
  parsePaths: parsePaths,
  parseVars: parseVars,
  parseMap: parseMap,
  addExt: addExt,
  hideExt: hideExt,
  wrapModule: wrapModule
};
<commit_msg>update files<commit_after>/**
 * Created by nuintun on 2015/4/27.
 */

'use strict';

var path = require('path');
var util = require('util');
var cmd = require('cmd-deps');
var css = require('@nuintun/css-deps');
var debug = require('debug')('gulp-cmd');
var gutil = require('@nuintun/gulp-util');

var join = path.join;
var extname = path.extname;
var dirname = path.dirname;
var basename = path.basename;
var relative = path.relative;
var write = process.stdout.write;

// regexp
var OUTBOUNDRE = /(?:^[\\\/]?)\.\.(?:[\\\/]|$)/;
var SPLITRE = /\/((?:\d+\.){2}\d+)(?:\/|$)/;
var PATHSRE = /^([^/:]+)(\/.+)$/;
var VARSRE = /{([^{]+)}/g;

// set debug color use 6
debug.color = 6;

/**
 * rename
 *
 * @param {any} path
 * @param {any} transform
 * @returns {String}
 */
function rename(path, transform) {
  return gutil.rename(path, transform, debug);
}

/**
 * transport
 *
 * @param {any} vinyl
 * @param {any} options
 * @param {any} done
 * @returns {void}
 */
function transport(vinyl, options, done) {
  return gutil.transport(vinyl, options, done, debug);
}

/**
 * resolve
 *
 * @param {any} relative
 * @param {any} vinyl
 * @param {any} wwwroot
 * @returns {String}
 */
function resolve(relative, vinyl, wwwroot) {
  return gutil.resolve(relative, vinyl, wwwroot, debug);
}

/**
 * pring
 *
 * @returns {void}
 */
function print() {
  var message = gutil.apply(util.format, null, gutil.slice.call(arguments));

  write(gutil.colors.cyan.bold('  gulp-cmd ') + message + '\n');
}

/**
 * get rename options
 *
 * @param transform
 * @returns {Object}
 */
function initRenameOptions(transform) {
  if (gutil.isFunction(transform)) {
    return transform;
  }

  transform = transform || {};

  if (transform.min) {
    transform.suffix = '-min';
  }

  if (transform.debug) {
    transform.suffix = '-debug';
  }

  return transform;
}

/**
 * init options
 *
 * @param options
 * @returns {Object}
 */
function initOptions(options) {
  // mix
  options = gutil.extend(true, {
    css: {}, // { prefix: null, onpath: null }
    map: {}, // the map
    vars: {}, // the vars
    paths: {}, // the paths
    alias: {}, // the alias
    cache: true, // use memory file cahe
    ignore: [], // omit the given dependencies when include
    wwwroot: '', // web root
    rename: null, // { debug: boolean, min: boolean }
    plugins: null, // file trnasport plugins
    include: 'relative', // include model: self, relative, all
    idleading: '{{name}}/{{version}}/{{file}}' // the id prefix template
  }, options);

  // wwwroot must be string
  if (!gutil.isString(options.wwwroot)) {
    gutil.throwError('options.wwwroot\'s value should be string.');
  }

  // init wwwroot
  options.wwwroot = join(gutil.cwd, options.wwwroot);
  // init plugins
  options.plugins = gutil.plugins(options.plugins, require('./plugins/index'));
  // init css settings
  options.css = options.css || {};
  // init rename
  options.rename = initRenameOptions(options.rename);
  // init ignore
  options.ignore = gutil.isArray(options.ignore) ? options.ignore : [];
  // init js settings
  options.js = options.js || {};
  // init js flags
  if (!options.js.hasOwnProperty('flags')) {
    options.js.flags = ['async'];
  }

  return options;
}

/**
 * resolve id leading
 *
 * @param idleading
 * @param path
 * @param pkg
 * @returns {String}
 */
function resolveIdleading(idleading, path, pkg) {
  return gutil.isFunction(idleading) ? idleading(path, pkg) : idleading;
}

/**
 * transport vinyl id
 *
 * @param vinyl
 * @param options
 * @returns {String}
 */
function transportId(vinyl, options) {
  var id;
  var pkg = parsePackage(vinyl, options.wwwroot);
  var idleading = resolveIdleading(options.idleading, vinyl.path, pkg);

  // get id
  id = template(idleading, pkg);
  // rename id
  id = addExt(id);
  id = rename(id, options.rename);
  id = hideExt(id);

  // seajs has hacked css before 3.0.0
  // https://github.com/seajs/seajs/blob/2.2.1/src/util-path.js#L49
  // demo https://github.com/popomore/seajs-test/tree/master/css-deps
  if (extname(id) === '.css') {
    id += '.js';
  }

  // normalize id
  id = gutil.normalize(id);
  id = id.replace(/^\.\//, '');
  id = id.replace(/^\/\//, '/');

  // debug
  debug('transport id: %s', gutil.colors.magenta(id));

  // rewrite vinyl path
  if (isAbsolute(id)) {
    vinyl.path = join(options.wwwroot, addExt(id));
  } else {
    vinyl.path = join(vinyl.cwd, vinyl.base, addExt(id));
  }

  // parse map
  id = parseMap(id, options.map);

  // set vinyl package info
  vinyl.package = gutil.extend(pkg, { id: id });

  return id;
}

/**
 * transport cmd dependencies.
 * @param vinyl
 * @param options
 * @returns {object}
 */
function transportDeps(vinyl, options) {
  var deps = [];
  var include = [];
  var vars = options.vars;
  var alias = options.alias;
  var paths = options.paths;
  var pkg = vinyl.package || {};

  // replace require and collect dependencies
  vinyl.contents = new Buffer(cmd(vinyl.contents.toString(), function(id, flag) {
    // parse id form alias, paths, vars
    id = parseAlias(id, alias);
    id = parsePaths(id, paths);
    id = parseAlias(id, alias);
    id = parseVars(id, vars);
    id = parseAlias(id, alias);

    // id is not a local file
    if (!isLocal(id)) {
      // cache dependencie id
      deps.push(id);
    } else {
      var path;

      // normalize id
      id = gutil.normalize(id);

      // if end with /, find index file
      if (id.substring(id.length - 1) === '/') {
        id += 'index';
      }

      // debug
      debug('transport%s deps: %s', flag ? ' ' + flag : '', gutil.colors.magenta(id));

      // add extname
      path = addExt(id);
      // rename id
      id = rename(path, options.rename);
      // hide extname
      id = hideExt(id);

      // seajs has hacked css before 3.0.0
      // https://github.com/seajs/seajs/blob/2.2.1/src/util-path.js#L49
      // demo https://github.com/popomore/seajs-test/tree/master/css-deps
      if (extname(id) === '.css') {
        id += '.js';
      }

      // normalize id
      id = gutil.normalize(id);
      // parse map
      id = parseMap(id, options.map);

      // cache dependencie id and path
      if (flag === null) {
        // cache dependencie id
        deps.push(id);

        // get absolute path
        path = resolve(path, vinyl, options.wwwroot);

        // cache dependencie absolute path
        include.push({
          id: id,
          path: path
        });
      }
    }

    return id;
  }, options.js.flags));

  // cache file dependencies
  vinyl.package = gutil.extend(pkg, {
    include: include,
    dependencies: deps
  });

  return deps;
}

/**
 * transport css dependencies.
 *
 * @param vinyl
 * @param options
 * @returns {Array}
 */
function transportCssDeps(vinyl, options) {
  var deps = [];
  var include = [];
  var pkg = vinyl.package || {};
  var onpath = options.css.onpath;
  var prefix = options.css.prefix;

  // init css settings
  onpath = gutil.isFunction(onpath) ? function(path, property) {
    return options.css.onpath(path, property, vinyl.path, options.wwwroot);
  } : null;
  prefix = gutil.isFunction(prefix) ? prefix(vinyl.path, options.wwwroot) : prefix;

  // replace imports and collect dependencies
  vinyl.contents = new Buffer(css(vinyl.contents, function(id) {
    var path;

    // id is not a local file
    if (!isLocal(id)) {
      // cache dependencie id
      deps.push(id);
    } else {
      // normalize id
      id = gutil.normalize(id);

      var isRelative = gutil.isRelative(id);
      var isAbsolute = gutil.isAbsolute(id);

      // css import parsing rules using html
      if (!isAbsolute && !isRelative) {
        id = './' + id;
      }

      // if end with /, find index file
      if (id.substring(id.length - 1) === '/') {
        id += 'index.css';
      }

      // debug
      debug('transport deps: %s', gutil.colors.magenta(id));

      // add extname
      path = addExt(id);
      // rename id
      id = rename(path, options.rename);
      // hide extname
      id = hideExt(id);

      // seajs has hacked css before 3.0.0
      // https://github.com/seajs/seajs/blob/2.2.1/src/util-path.js#L49
      // demo https://github.com/popomore/seajs-test/tree/master/css-deps
      if (extname(id) === '.css') {
        id += '.js';
      }

      // normalize id
      id = gutil.normalize(id);
      // parse map
      id = parseMap(id, options.map);

      // get absolute path
      path = resolve(path, vinyl, options.wwwroot);

      // cache dependencie id
      deps.push(id);
      // cache dependencie absolute path
      include.push({
        id: id,
        path: path
      });
    }

    // delete all import
    return false;
  }, { prefix: prefix, onpath: onpath }));

  // Cache file dependencies
  vinyl.package = gutil.extend(pkg, {
    include: include,
    dependencies: deps
  });

  return deps;
}

/**
 * parse package form vinyl
 * @param vinyl
 * @param wwwroot
 * @returns {object}
 */
function parsePackage(vinyl, wwwroot) {
  var relative = vinyl.relative;

  // vinyl not in base dir, user wwwroot
  if (OUTBOUNDRE.test(relative)) {
    relative = path.relative(wwwroot, vinyl.path);
    // vinyl not in wwwroot, throw error
    if (OUTBOUNDRE.test(relative)) {
      throwError('file: %s is out of bound of wwwroot: %s.', normalize(vinyl.path), normalize(wwwroot));
    }

    // reset relative
    relative = path.join('/', relative);
  }

  var dir = gutil.normalize(dirname(relative));
  var filename = basename(relative);
  var match = dir.split(SPLITRE);

  return {
    name: match[0] || '',
    version: match[1] || '',
    file: match[2] ? match[2] + '/' + filename : filename
  }
}

/**
 * simple template
 * @param format
 * @param data
 * @returns {string}
 * ```
 * var tpl = '{{name}}/{{version}}';
 * util.template(tpl, {name:'base', version: '1.0.0'});
 * ```
 */
function template(format, data) {
  if (!gutil.isString(format)) return '';

  return format.replace(/{{([a-z]*)}}/gi, function(all, match) {
    return data[match] || '';
  });
}

/**
 * parse alias
 * @param id
 * @param alias
 * @returns {String}
 */
function parseAlias(id, alias) {
  alias = alias || {};

  return alias && gutil.isString(alias[id]) ? alias[id] : id;
}

/**
 * parse paths
 * @param id
 * @param paths
 * @returns {String}
 */
function parsePaths(id, paths) {
  var match;

  paths = paths || {};

  if (paths && (match = id.match(PATHSRE)) && gutil.isString(paths[match[1]])) {
    id = paths[match[1]] + match[2];
  }

  return id;
}

/**
 * parse vars
 * @param id
 * @param vars
 * @returns {String}
 */
function parseVars(id, vars) {
  vars = vars || {};

  if (vars && id.indexOf('{') !== -1) {
    id = id.replace(VARSRE, function(match, key) {
      return gutil.isString(vars[key]) ? vars[key] : match;
    });
  }

  return id;
}

/**
 * parse map
 * @param id
 * @param map
 * @returns {String}
 */
function parseMap(id, map) {
  var ret = id;

  if (Array.isArray(map)) {
    for (var i = 0, len = map.length; i < len; i++) {
      var rule = map[i];

      // parse map
      if (gutil.isFunction(rule)) {
        ret = rule(id);
      } else if (Array.isArray(rule)) {
        ret = id.replace(rule[0], rule[1]);
      }

      // must be string
      if (!ret || !gutil.isString(ret)) {
        ret = id;
      }

      // only apply the first matched rule
      if (ret !== id) break;
    }
  }

  return ret;
}

/**
 * add .js if not exists
 * @param path
 * @returns {*}
 */
function addExt(path) {
  return extname(path) === '.js' ? path : (path + '.js');
}

/**
 * hide .js if exists
 * @param path
 * @returns {*}
 */
function hideExt(path) {
  return extname(path) === '.js' ? path.replace(/\.js$/, '') : path;
}

/**
 * wrap module
 * @param id
 * @param deps
 * @param code
 * @returns {string}
 */
function wrapModule(id, deps, code) {
  // header and footer template string
  var header = 'define({{id}}, {{deps}}, function(require, exports, module){';
  var footer = '});\n';

  if (Buffer.isBuffer(code)) code = code.toString();

  // debug
  debug('compile module: %s', colors.magenta(id));

  id = JSON.stringify(id);
  deps = JSON.stringify(deps);

  return template(header, { id: id, deps: deps })
    + '\n' + code + '\n' + footer;
}

/**
 * print message
 */
function print() {
  var slice = [].slice;
  var message = util.format
    .apply(null, slice.call(arguments));

  process.stdout.write(gutil.colors.cyan.bold('  gulp-cmd ') + message + '\n');
}

/**
 * exports module
 */
module.exports = {
  debug: debug,
  rename: rename,
  transport: transport,
  resolve: resolve,
  print: print,
  initOptions: initOptions,
  transportId: transportId,
  transportDeps: transportDeps,
  transportCssDeps: transportCssDeps,
  parsePackage: parsePackage,
  template: template,
  parseAlias: parseAlias,
  parsePaths: parsePaths,
  parseVars: parseVars,
  parseMap: parseMap,
  addExt: addExt,
  hideExt: hideExt,
  wrapModule: wrapModule
};
<|endoftext|>


<commit_before>let fs = require('fs');
let path = require('path');
let yaml = require('js-yaml');
let log = require('./logger');
let theme = require('./theme').default;

/**
 * See both `pre` and `post`.
 *
 * @param {String} file
 * @param {Logger} logger
 * @return {Object}
 */
export default function (file, logger = log.empty) {
  return post(pre(file, logger));
}

/**
 * Get the configuration object from given file of `.sassdocrc` if not
 * found.
 *
 * The `dir` property will be the directory of the given file or the CWD
 * if no file is given. The configuration paths should be relative to
 * it.
 *
 * The given logger will be injected in the configuration object for
 * further usage.
 *
 * @param {String} file
 * @param {Logger} logger
 * @return {Object}
 */
export function pre(file, logger = log.empty) {
  file = resolve(process.cwd(), file);

  let config = maybe(file, () => {
    if (file !== undefined) {
      logger.error(`Config file "${file}" not found.`);
      logger.warn('Falling back to ".sassdocrc".');
    }

    return maybe('.sassdocrc', () => {
      return {logger};
    });
  });

  config.logger = logger;

  if (file === undefined) {
    config.dir = process.cwd();
  } else {
    config.dir = path.resolve(path.dirname(file));
  }

  return config;
}

/**
 * Post process given configuration object to ensure `package` and
 * `theme` are uniform values.
 *
 * The `package` key is ensured to be an object. If it's a string, it's
 * required as JSON, relative to the configuration file directory.
 *
 * The `theme` key, if present and not already a function, will be resolved to
 * the actual theme function.
 *
 * @param {Object} config
 * @return {Object}
 */
export function post(config) {
  if (typeof config.package !== 'object') {
    let file = resolve(config.dir, config.package);

    config.package = maybe(file, () => {
      if (config.package !== undefined) {
        config.logger.error(`Package file "${file}" not found.`);
        config.logger.warn('Falling back to "package.json".');
      }

      let file = path.resolve(config.dir, 'package.json');

      return maybe(file, () => {
        config.logger.warn('No package information.');
      });
    });
  }

  if (typeof config.theme !== 'function') {
    config.themeName = config.theme || 'default';
    config.theme = theme(config.theme, config.dir, config.logger);
  }
}

/**
 * If given file is not undefined, resolve it to given directory.
 *
 * @param {String} dir
 * @param {String} file
 * @return {String}
 */
function resolve(dir, file) {
  if (file !== undefined) {
    return path.resolve(dir, file);
  }
}

/**
 * Try `load` for given file but call given fallback if an exception
 * with `ENOENT` code is thrown, or if the file is undefined.
 *
 * Other exceptions are not muted.
 *
 * @param {Function} loader
 * @param {String} file
 * @param {Function} fallback
 * @return {Object}
 */
function maybe(file, fallback = () => {}) {
  if (file === undefined) {
    return fallback();
  }

  try {
    return load(file);
  } catch (e) {
    if (e.code !== 'ENOENT') {
      throw e;
    }
  }

  return fallback();
}

/**
 * Load YAML or JSON from given file path.
 *
 * @param {String} path
 * @return {Object}
 */
function load(path) {
  return yaml.safeLoad(fs.readFileSync(path, 'utf-8'));
}
<commit_msg>Name cfg default export<commit_after>let fs = require('fs');
let path = require('path');
let yaml = require('js-yaml');
let log = require('./logger');
let theme = require('./theme').default;

/**
 * See both `pre` and `post`.
 *
 * @param {String} file
 * @param {Logger} logger
 * @return {Object}
 */
export default function cfg(file, logger = log.empty) {
  return post(pre(file, logger));
}

/**
 * Get the configuration object from given file of `.sassdocrc` if not
 * found.
 *
 * The `dir` property will be the directory of the given file or the CWD
 * if no file is given. The configuration paths should be relative to
 * it.
 *
 * The given logger will be injected in the configuration object for
 * further usage.
 *
 * @param {String} file
 * @param {Logger} logger
 * @return {Object}
 */
export function pre(file, logger = log.empty) {
  file = resolve(process.cwd(), file);

  let config = maybe(file, () => {
    if (file !== undefined) {
      logger.error(`Config file "${file}" not found.`);
      logger.warn('Falling back to ".sassdocrc".');
    }

    return maybe('.sassdocrc', () => {
      return {logger};
    });
  });

  config.logger = logger;

  if (file === undefined) {
    config.dir = process.cwd();
  } else {
    config.dir = path.resolve(path.dirname(file));
  }

  return config;
}

/**
 * Post process given configuration object to ensure `package` and
 * `theme` are uniform values.
 *
 * The `package` key is ensured to be an object. If it's a string, it's
 * required as JSON, relative to the configuration file directory.
 *
 * The `theme` key, if present and not already a function, will be resolved to
 * the actual theme function.
 *
 * @param {Object} config
 * @return {Object}
 */
export function post(config) {
  if (typeof config.package !== 'object') {
    let file = resolve(config.dir, config.package);

    config.package = maybe(file, () => {
      if (config.package !== undefined) {
        config.logger.error(`Package file "${file}" not found.`);
        config.logger.warn('Falling back to "package.json".');
      }

      let file = path.resolve(config.dir, 'package.json');

      return maybe(file, () => {
        config.logger.warn('No package information.');
      });
    });
  }

  if (typeof config.theme !== 'function') {
    config.themeName = config.theme || 'default';
    config.theme = theme(config.theme, config.dir, config.logger);
  }
}

/**
 * If given file is not undefined, resolve it to given directory.
 *
 * @param {String} dir
 * @param {String} file
 * @return {String}
 */
function resolve(dir, file) {
  if (file !== undefined) {
    return path.resolve(dir, file);
  }
}

/**
 * Try `load` for given file but call given fallback if an exception
 * with `ENOENT` code is thrown, or if the file is undefined.
 *
 * Other exceptions are not muted.
 *
 * @param {Function} loader
 * @param {String} file
 * @param {Function} fallback
 * @return {Object}
 */
function maybe(file, fallback = () => {}) {
  if (file === undefined) {
    return fallback();
  }

  try {
    return load(file);
  } catch (e) {
    if (e.code !== 'ENOENT') {
      throw e;
    }
  }

  return fallback();
}

/**
 * Load YAML or JSON from given file path.
 *
 * @param {String} path
 * @return {Object}
 */
function load(path) {
  return yaml.safeLoad(fs.readFileSync(path, 'utf-8'));
}
<|endoftext|>


<commit_before>/**
 * @author Gilles Coomans <gilles.coomans@gmail.com>
 * View means something special in yamvish. there is no view instance as you could find in other MV* lib.
 * View here is just a __Template__ that will always produce a container that will be mounted in parent node.
 * (in dom output case of course, but it's transparent for string or twopass output)
 *
 * Additionnaly, it will produce and hold its own context in produced container.
 *
 * Exactly as what a classic view's instance would encapsulate (some nodes and a local context).
 *
 * But here finally, we just have simple nodes that could be mounted/unmounted and that refer to a local context. And nothing more.
 *
 * In place of View's class instanciation, you have View's template execution.
 *
 * As a Template descendant, you could use it exactly as a normal template and everywhere a template do the job.
 *
 * As such descendant :
 * You could add some methods in View api that will not be accessible to Template's instances.
 * But every methods added to Template prototype will be accessible in View's instance.
 *
 * It's interesting when you want to benefit from the container produced when View's template is executed.
 * As yamvish-route do by implementing .route method in View api.
 *
 * All that sounds much more complex than when you use it... less is more... ;)
 */

var Template = require('./template');

function View(data, parent, path) {
	this.__yView__ = true;
	Template.call(this);
	this.context(data, parent, path)
		.exec(function(context) {
			context.viewData = {};
		}, null, true)
		.exec(function(context, container) {
			context.viewData.container = container;
		});
};

View.prototype = new Template();

// kill all attributes related metods
['attr', 'css', 'setClass', 'cl', 'visible', 'disabled', 'val']
.forEach(function(method) {
	View.prototype[method] = null;
});

module.exports = View;
<commit_msg>adapt view to exec refactpring<commit_after>/**
 * @author Gilles Coomans <gilles.coomans@gmail.com>
 * View means something special in yamvish. there is no view instance as you could find in other MV* lib.
 * View here is just a __Template__ that will always produce a container that will be mounted in parent node.
 * (in dom output case of course, but it's transparent for string or twopass output)
 *
 * Additionnaly, it will produce and hold its own context in produced container.
 *
 * Exactly as what a classic view's instance would encapsulate (some nodes and a local context).
 *
 * But here finally, we just have simple nodes that could be mounted/unmounted and that refer to a local context. And nothing more.
 *
 * In place of View's class instanciation, you have View's template execution.
 *
 * As a Template descendant, you could use it exactly as a normal template and everywhere a template do the job.
 *
 * As such descendant :
 * You could add some methods in View api that will not be accessible to Template's instances.
 * But every methods added to Template prototype will be accessible in View's instance.
 *
 * It's interesting when you want to benefit from the container produced when View's template is executed.
 * As yamvish-route do by implementing .route method in View api.
 *
 * All that sounds much more complex than when you use it... less is more... ;)
 */

var Template = require('./template');

function setContainer(context, container) {
	context.viewData.container = container;
}

function View(data, parent, path) {
	this.__yView__ = true;
	Template.call(this);
	this.newContext(data, parent, path)
		.context(function(context) {
			context.viewData = {};
		})
		.dom(setContainer)
		.secondPass(setContainer);
};

View.prototype = new Template();

// kill all attributes related metods
['attr', 'css', 'setClass', 'cl', 'visible', 'disabled', 'val']
.forEach(function(method) {
	View.prototype[method] = null;
});

module.exports = View;
<|endoftext|>


<commit_before>/**
 * @author Gilles Coomans <gilles.coomans@gmail.com>
 * Views controller using deepjs tools and methods
 */
if (typeof define !== 'function') {
	var define = require('amdefine')(module);
}
define(["require", "deepjs/deep", "deepjs/lib/errors", "./directives"], function(require, deep, errors) {
	"use strict";

	/**
	 * view refresh sequence : arg = route params
	 * 	if(!initialised)
	 * 		init()
	 * 	then
	 * 		load(params);
	 * 			deepLoad what, how, where
	 * 		render(loaded);
	 * 			how(context);
	 * 		 	where(context);
	 * 		  	enhance(context);
	 * 		   	done(context);
	 *
	 * View remove sequence :
	 * 		remove each subs
	 * 		remove each dp-controlled
	 * 		remove html node
	 * 		clean();
	 */

	 var applyRender = function(self, loaded, routeMatch, params) {
		// console.log("view render : ", loaded)
		if (!loaded)
			return;
		var config = self.config || {},
			isServer = deep.context("isServer");
		if (self._deep_controlled_) {
			for (var i in self._deep_controlled_)
				self._deep_controlled_[i].remove();
			self._deep_controlled_ = null;
		}
		var what = null,
			how = null,
			where = null,
			rendered = null,
			placed = null;
		if (loaded.what)
			what = loaded.what;
		if (loaded.how)
			how = loaded.how;
		if (loaded.where)
			where = loaded.where;
		what = (what && what._deep_query_node_) ? what.value : what;
		how = (how && how._deep_query_node_) ? how.value : how;
		where = (where && where._deep_query_node_) ? where.value : where;

		if (what && what._deep_ocm_)
			what = what();
		if (how && how._deep_ocm_)
			how = how();
		if (where && where._deep_ocm_)
			where = where();

		loaded.what = what;
		loaded.how = how;
		loaded.where = where;
		loaded.params = params;

		placed = self.placed ? self.placed() : null;

		loaded.placed = placed;
		loaded.ctrl = self;
		// console.log("render with : how : ", how, what)
			//console.log("WHAT : ", what);
			// console.log("HOW : ", how);
			if (routeMatch) {
				loaded.route = routeMatch;
			}
			if (typeof how === 'function')
				rendered = loaded.rendered = how.call(self, loaded);
			else if (how)
				rendered = loaded.rendered = how;
			else if (what)
				rendered = loaded.rendered = what;
			if (where && typeof where === 'function')
				placed = loaded.placed = where.call(self, loaded.rendered, loaded.placed);
			else if (typeof jQuery !== 'undefined' && where instanceof jQuery)
				placed = loaded.placed = where;
			else if (typeof where === 'string' && deep.Promise.context.$)
				placed = loaded.placed = deep.Promise.context.$(where);
			/*else
				placed = loaded.placed = null;*/

		if (placed && !isServer)
			self.placed = function() {
				// console.log("store placed : ", placed)
				return placed;
			};

		var promise = null;
		if (config.enhance !== false && placed && deep.Promise.context.$) {
			//console.log("view placed : placed = ", placed);
			if (placed._deep_html_merged_) {
				var subprom = [];
				for (var i in placed) {
					if (i === '_deep_html_merged_')
						continue;
					subprom.push(deep.ui.enhance(self, placed[i], loaded))
				}
				promise = deep.all(subprom);
			} else
				promise = deep.ui.enhance(self, placed, loaded);
		}

		//console.log("rendered : ", loaded);
		if (promise)
			return promise
				.done(function() {
					if (config.relink !== false && !isServer && placed && self.relink)
						self.relink(placed);
					if (typeof self.done === "function") {
						var done = self.done;
						if (done._deep_ocm_)
							done = done();
						return done.call(self, loaded) || loaded;
					}
					return loaded;
				})
				.fail(function(e) {
					if (typeof self.fail === 'function')
						return self.fail(e) || e;
					return e;
				});

		//if(config.relink == false)
		//	console.log("skip relink on : ", self);
		if (config.relink !== false && !isServer && placed && self.relink)
			self.relink(placed);
		if (typeof self.done === "function") {
			var done = self.done;
			if (done._deep_ocm_)
				done = done();
			return done.call(self, loaded) || loaded;
		}
		return loaded;
	};

	deep.errors.View = function(msg, report, fileName, lineNum) {
		if (typeof msg === 'object')
			report = msg;
		if (!msg)
			msg = "UIError";
		return errors.Error(1500, msg, report, fileName, lineNum);
	};

	deep.View = deep.Classes(function(layer) {
		if (layer)
			deep.aup(layer, this);
	}, {
		_deep_view_: true,
		fail: function(e) {
			deep.utils.dumpError(e);
			if (!this.where)
				return e;
			if (typeof this.where === 'string')
				return deep.nodes(this.where).done(function(s) {
					if (typeof s === 'function')
						s(e.toString());
					else
						$(s).replaceWith(e.toString());
					return e;
				});
			else if (typeof this.where === 'function')
				this.where(e.toString());
			else if (typeof jQuery !== 'undefined' && this.where instanceof jQuery) // WARNING : cheerio case not managed
				$(this.where).html(e.toString());
		},
		addSubControlled: function(ctrl) {
			var label = "view" + Date.now().valueOf();
			this._deep_controlled_ = this._deep_controlled_ || {};
			this._deep_controlled_[label] = ctrl;
		},
		remove: function() {
			//console.log("VIEW REMOVE : ", this.placed);
			if (this.subs)
				for (var i in this.subs)
					this.subs[i].remove();
			if (this._deep_controlled_) {
				for (var i in this._deep_controlled_)
					this._deep_controlled_[i].remove();
				this._deep_controlled_ = null;
			}
			if (this.placed) {
				// console.log("remove node : ", this, this.placed())
				deep.$(this.placed()).remove();
			}
			if (this.clean)
				this.clean();
			this.prepared = false;
			this.placed = null;
		},
		load: function(opt) {
			opt = opt || {};
			var params = opt.params,
				config = this.config || {},
				isServer = deep.context("isServer");
			//if (params && Object.keys(params).length === 0)
			//	params = null;
			if (config.scope && config.scope != "both")
				if (isServer) {
					if (config.scope != "server")
						return;
				} else if (config.scope != "browser")
				return;
			var self = this;
			if (this.init && !this.initialised)
				return deep.when(this.init())
					.done(function(success) {
						self.initialised = true;
						return self.load({
							params: params
						});
					});
			if (this.prepare && (!this.prepared || isServer))
				return deep.when(this.prepare())
					.done(function(success) {
						self.prepared = true;
						return self.load({
							params: params
						});
					});
			if (this.condition === false)
				return null;
			var promises = [],
				ctx = {
					params: params,
					context: deep.context(),
					ctrl: self
				};
			if (this.condition)
				if (typeof this.condition === "function" && !this.condition.apply(ctx))
					return null;
			if (this.what)
				promises.push(deep.nodes(this).query("./what").deepLoad(ctx, false));
			else
				promises.push(null);

			if (typeof this.how === 'string')
				promises.push(deep.nodes(this).query("./how").deepLoad(ctx, false, true));
			else
				promises.push(this.how);

			if (this.where)
				if (typeof this.where === 'string')
					promises.push(deep.nodes(this).query("./where").deepLoad(ctx, false, true));
				else
					promises.push(this.where);

				// console.log("launch deep load");
			return deep.all(promises)
				.done(function(res) {
					//console.log("view deep load : res  : ", res);
					var result = {
						_deep_render_node_: true,
						what: res[0],
						how: res[1],
						where: res[2],
						params: params
					};
					// console.log("view deep load done : ", self.how);
					return result;
				})
				.fail(function(e) {
					if (typeof self.fail === 'function')
						return self.fail(e) || e;
					return e;
				});
		},
		render : function(loaded, routeMatch, params){
			try{
				return applyRender(this, loaded, routeMatch, params);
			}
			catch(e){
				deep.error("error catched while view.render : ", e);
				if (this.fail)
					return this.fail(e) || e;
				return e;
			}
		},
		refresh: function(arg /* params, loaded, routeMatch */ ) {
			var config = this.config || {},
				isServer = deep.context("isServer");
			if (config.scope && config.scope != "both")
				if (!isServer) {
					if (config.scope != "browser")
						return;
				} else
			if (config.scope != "server")
				return;
			// console.log("view refresh : params : ", params, " - loaded : ", loaded);
			var self = this;
			if (this.init && !this.initialised)
				return deep.when(this.init())
					.done(function(success) {
						self.initialised = true;
						return self.refresh(arg);
					});
			if (this.prepare && (isServer || !this.prepared))
				return deep.when(this.prepare())
					.done(function(success) {
						self.prepared = true;
						return self.refresh(arg);
					});
			var loaded, params, routeMatch;
			if (arg)
				if (arg._deep_render_node_) {
					loaded = arg;
					params = loaded.params;
				} else
			if (arg._deep_matched_node_) {
				loaded = arg.loaded;
				params = arg.output;

				routeMatch = arg;
			} else
				params = arg;
			params = params || this.params;
			if (params && !isServer)
				this.params = params;

			var p;
			if (loaded)
				p = deep.when(this.render(loaded, routeMatch, params))
				.fail(function(e) {
					if (typeof self.fail === 'function') {
						var fail = self.fail;
						if (fail._deep_ocm_)
							fail = fail();
						return fail.call(self, e) || e;
					}
				});
			else
				p = deep.when(this.load({
					params: params
				}))
				.done(function(loaded) {
					return self.render(loaded, routeMatch, params);
				})
				.fail(function(e) {
					if (typeof self.fail === 'function') {
						var fail = self.fail;
						if (fail._deep_ocm_)
							fail = fail();
						return fail.call(self, e) || e;
					}
				});
			return p;
		},
		relink: function(selector) {
			if(deep.context("isServer"))
				return;
			var app = deep.currentApp(),
				$ = deep.$();
			if($)
				$(selector)
					.find(this.relinkSelector || "a")
					.each(function() {
						if (this._deep_rerouted_)
							return;
						this._deep_rerouted_ = true;

						var uri = $(this).attr("href");
						if (!uri)
							return;
						if (uri.substring(0, 4) === 'http')
							return;
						if (uri[0] == '/' && uri[1] == '/') // file
							return;
						// console.log("RELINK : ", uri, this);
						$(this).click(function(e) {
							if (e && e.preventDefault)
								e.preventDefault();
							if(window.history && window.history.pushState)
							{
								// history.pushState( data, title, href);
								window.history.pushState({
			                        some: "datas"
			                    },
			                    this.title || ("hello world"),
			                    this.href);
							}
							deep.app(app).get(uri).elog();
							return false;
						});
					});
		}
	});

	deep.View.relink = function(selector, relinkSelector) {
		// console.log("relink : ", selector);
		return deep.View.prototype.relink.call({
			relinkSelector: relinkSelector
		}, selector);
	};
	deep.coreUnits = deep.coreUnits || [];
	deep.coreUnits.push("js::deep-views/units/views");
	return deep.View;
});<commit_msg>work on relink in view<commit_after>/**
 * @author Gilles Coomans <gilles.coomans@gmail.com>
 * Views controller using deepjs tools and methods
 */
if (typeof define !== 'function') {
	var define = require('amdefine')(module);
}
define(["require", "deepjs/deep", "deepjs/lib/errors", "./directives"], function(require, deep, errors) {
	"use strict";

	/**
	 * view refresh sequence : arg = route params
	 * 	if(!initialised)
	 * 		init()
	 * 	then
	 * 		load(params);
	 * 			deepLoad what, how, where
	 * 		render(loaded);
	 * 			how(context);
	 * 		 	where(context);
	 * 		  	enhance(context);
	 * 		   	done(context);
	 *
	 * View remove sequence :
	 * 		remove each subs
	 * 		remove each dp-controlled
	 * 		remove html node
	 * 		clean();
	 */

	 var applyRender = function(self, loaded, routeMatch, params) {
		// console.log("view render : ", loaded)
		if (!loaded)
			return;
		var config = self.config || {},
			isServer = deep.context("isServer");
		if (self._deep_controlled_) {
			for (var i in self._deep_controlled_)
				self._deep_controlled_[i].remove();
			self._deep_controlled_ = null;
		}
		var what = null,
			how = null,
			where = null,
			rendered = null,
			placed = null;
		if (loaded.what)
			what = loaded.what;
		if (loaded.how)
			how = loaded.how;
		if (loaded.where)
			where = loaded.where;
		what = (what && what._deep_query_node_) ? what.value : what;
		how = (how && how._deep_query_node_) ? how.value : how;
		where = (where && where._deep_query_node_) ? where.value : where;

		if (what && what._deep_ocm_)
			what = what();
		if (how && how._deep_ocm_)
			how = how();
		if (where && where._deep_ocm_)
			where = where();

		loaded.what = what;
		loaded.how = how;
		loaded.where = where;
		loaded.params = params;

		placed = self.placed ? self.placed() : null;

		loaded.placed = placed;
		loaded.ctrl = self;
		// console.log("render with : how : ", how, what)
			//console.log("WHAT : ", what);
			// console.log("HOW : ", how);
			if (routeMatch) {
				loaded.route = routeMatch;
			}
			if (typeof how === 'function')
				rendered = loaded.rendered = how.call(self, loaded);
			else if (how)
				rendered = loaded.rendered = how;
			else if (what)
				rendered = loaded.rendered = what;
			if (where && typeof where === 'function')
				placed = loaded.placed = where.call(self, loaded.rendered, loaded.placed);
			else if (typeof jQuery !== 'undefined' && where instanceof jQuery)
				placed = loaded.placed = where;
			else if (typeof where === 'string' && deep.Promise.context.$)
				placed = loaded.placed = deep.Promise.context.$(where);
			/*else
				placed = loaded.placed = null;*/

		if (placed && !isServer)
			self.placed = function() {
				// console.log("store placed : ", placed)
				return placed;
			};

		var promise = null;
		if (config.enhance !== false && placed && deep.Promise.context.$) {
			//console.log("view placed : placed = ", placed);
			if (placed._deep_html_merged_) {
				var subprom = [];
				for (var i in placed) {
					if (i === '_deep_html_merged_')
						continue;
					subprom.push(deep.ui.enhance(self, placed[i], loaded))
				}
				promise = deep.all(subprom);
			} else
				promise = deep.ui.enhance(self, placed, loaded);
		}

		//console.log("rendered : ", loaded);
		if (promise)
			return promise
				.done(function() {
					if (config.relink !== false && !isServer && placed && self.relink)
						self.relink(placed);
					if (typeof self.done === "function") {
						var done = self.done;
						if (done._deep_ocm_)
							done = done();
						return done.call(self, loaded) || loaded;
					}
					return loaded;
				})
				.fail(function(e) {
					if (typeof self.fail === 'function')
						return self.fail(e) || e;
					return e;
				});

		//if(config.relink == false)
		//	console.log("skip relink on : ", self);
		if (config.relink !== false && !isServer && placed && self.relink)
			self.relink(placed);
		if (typeof self.done === "function") {
			var done = self.done;
			if (done._deep_ocm_)
				done = done();
			return done.call(self, loaded) || loaded;
		}
		return loaded;
	};

	deep.errors.View = function(msg, report, fileName, lineNum) {
		if (typeof msg === 'object')
			report = msg;
		if (!msg)
			msg = "UIError";
		return errors.Error(1500, msg, report, fileName, lineNum);
	};

	deep.View = deep.Classes(function(layer) {
		if (layer)
			deep.aup(layer, this);
	}, {
		_deep_view_: true,
		fail: function(e) {
			deep.utils.dumpError(e);
			if (!this.where)
				return e;
			if (typeof this.where === 'string')
				return deep.nodes(this.where).done(function(s) {
					if (typeof s === 'function')
						s(e.toString());
					else
						$(s).replaceWith(e.toString());
					return e;
				});
			else if (typeof this.where === 'function')
				this.where(e.toString());
			else if (typeof jQuery !== 'undefined' && this.where instanceof jQuery) // WARNING : cheerio case not managed
				$(this.where).html(e.toString());
		},
		addSubControlled: function(ctrl) {
			var label = "view" + Date.now().valueOf();
			this._deep_controlled_ = this._deep_controlled_ || {};
			this._deep_controlled_[label] = ctrl;
		},
		remove: function() {
			//console.log("VIEW REMOVE : ", this.placed);
			if (this.subs)
				for (var i in this.subs)
					this.subs[i].remove();
			if (this._deep_controlled_) {
				for (var i in this._deep_controlled_)
					this._deep_controlled_[i].remove();
				this._deep_controlled_ = null;
			}
			if (this.placed) {
				// console.log("remove node : ", this, this.placed())
				deep.$(this.placed()).remove();
			}
			if (this.clean)
				this.clean();
			this.prepared = false;
			this.placed = null;
		},
		load: function(opt) {
			opt = opt || {};
			var params = opt.params,
				config = this.config || {},
				isServer = deep.context("isServer");
			//if (params && Object.keys(params).length === 0)
			//	params = null;
			if (config.scope && config.scope != "both")
				if (isServer) {
					if (config.scope != "server")
						return;
				} else if (config.scope != "browser")
				return;
			var self = this;
			if (this.init && !this.initialised)
				return deep.when(this.init())
					.done(function(success) {
						self.initialised = true;
						return self.load({
							params: params
						});
					});
			if (this.prepare && (!this.prepared || isServer))
				return deep.when(this.prepare())
					.done(function(success) {
						self.prepared = true;
						return self.load({
							params: params
						});
					});
			if (this.condition === false)
				return null;
			var promises = [],
				ctx = {
					params: params,
					context: deep.context(),
					ctrl: self
				};
			if (this.condition)
				if (typeof this.condition === "function" && !this.condition.apply(ctx))
					return null;
			if (this.what)
				promises.push(deep.nodes(this).query("./what").deepLoad(ctx, false));
			else
				promises.push(null);

			if (typeof this.how === 'string')
				promises.push(deep.nodes(this).query("./how").deepLoad(ctx, false, true));
			else
				promises.push(this.how);

			if (this.where)
				if (typeof this.where === 'string')
					promises.push(deep.nodes(this).query("./where").deepLoad(ctx, false, true));
				else
					promises.push(this.where);

				// console.log("launch deep load");
			return deep.all(promises)
				.done(function(res) {
					//console.log("view deep load : res  : ", res);
					var result = {
						_deep_render_node_: true,
						what: res[0],
						how: res[1],
						where: res[2],
						params: params
					};
					// console.log("view deep load done : ", self.how);
					return result;
				})
				.fail(function(e) {
					if (typeof self.fail === 'function')
						return self.fail(e) || e;
					return e;
				});
		},
		render : function(loaded, routeMatch, params){
			try{
				return applyRender(this, loaded, routeMatch, params);
			}
			catch(e){
				deep.error("error catched while view.render : ", e);
				if (this.fail)
					return this.fail(e) || e;
				return e;
			}
		},
		refresh: function(arg /* params, loaded, routeMatch */ ) {
			var config = this.config || {},
				isServer = deep.context("isServer");
			if (config.scope && config.scope != "both")
				if (!isServer) {
					if (config.scope != "browser")
						return;
				} else
			if (config.scope != "server")
				return;
			// console.log("view refresh : params : ", params, " - loaded : ", loaded);
			var self = this;
			if (this.init && !this.initialised)
				return deep.when(this.init())
					.done(function(success) {
						self.initialised = true;
						return self.refresh(arg);
					});
			if (this.prepare && (isServer || !this.prepared))
				return deep.when(this.prepare())
					.done(function(success) {
						self.prepared = true;
						return self.refresh(arg);
					});
			var loaded, params, routeMatch;
			if (arg)
				if (arg._deep_render_node_) {
					loaded = arg;
					params = loaded.params;
				} else
			if (arg._deep_matched_node_) {
				loaded = arg.loaded;
				params = arg.output;

				routeMatch = arg;
			} else
				params = arg;
			params = params || this.params;
			if (params && !isServer)
				this.params = params;

			var p;
			if (loaded)
				p = deep.when(this.render(loaded, routeMatch, params))
				.fail(function(e) {
					if (typeof self.fail === 'function') {
						var fail = self.fail;
						if (fail._deep_ocm_)
							fail = fail();
						return fail.call(self, e) || e;
					}
				});
			else
				p = deep.when(this.load({
					params: params
				}))
				.done(function(loaded) {
					return self.render(loaded, routeMatch, params);
				})
				.fail(function(e) {
					if (typeof self.fail === 'function') {
						var fail = self.fail;
						if (fail._deep_ocm_)
							fail = fail();
						return fail.call(self, e) || e;
					}
				});
			return p;
		},
		relink: function(selector) {
			if(deep.context("isServer"))
				return;
			var app = deep.currentApp(),
				$ = deep.$();
			if(!$)
				return;
			$(selector)
				.find(this.relinkSelector || "a")
				.each(function() {
					if (this._deep_rerouted_)
						return;
					this._deep_rerouted_ = true;

					var uri = $(this).attr("href");
					if (!uri)
						return;
					if (uri.substring(0, 4) === 'http')
						return;
					if (uri[0] == '/' && uri[1] == '/') // file
						return;
					// console.log("RELINK : ", uri, this);
					$(this).click(function(e) {
						if (e && e.preventDefault)
							e.preventDefault();
						if(window.history && window.history.pushState)
						{
							// history.pushState( data, title, href);
							window.history.pushState({
		                        some: "datas"
		                    },
		                    this.title || ("hello world"),
		                    this.href);
						}
						deep.app(app).get(uri).elog();
						return false;
					});
				});
		}
	});

	deep.View.relink = function(selector, relinkSelector) {
		// console.log("relink : ", selector);
		return deep.View.prototype.relink.call({
			relinkSelector: relinkSelector
		}, selector);
	};
	deep.coreUnits = deep.coreUnits || [];
	deep.coreUnits.push("js::deep-views/units/views");
	return deep.View;
});<|endoftext|>


<commit_before>
  // returns how much "power" a user's votes have
  var getVotePower = function(user){
    // return (user && user.isAdmin) ? 5 : 1;
    return 1; // for now, leave everybody at 1 including admins; 5 is too unbalanced
  };

  var modifyKarma = function(userId, karma){
    Meteor.users.update({_id: userId}, {$inc: {karma: karma}});
  };

  var hasUpvotedItem= function(item, user){
    return item.upvoters && item.upvoters.indexOf(user._id) != -1;
  };

  var hasDownvotedItem= function(item, user){
    return item.downvoters && item.downvoters.indexOf(user._id) != -1;
  };

  var upvoteItem = function(collection, item) {
    var user = Meteor.user(),
        votePower = getVotePower(user);

    // make sure user has rights to upvote first
    if (!user || !canUpvote(user, collection, true)  || hasUpvotedItem(item, user))
      return false;

    // if user is upvoting a previously downvoted item, cancel downvote first
    if (hasDownvotedItem(item, user))
      cancelDownvote(collection, item, user);

    // Votes & Score
    var result = collection.update({_id: item && item._id},{
      $addToSet: {upvoters: user._id},
      $pull: {downvoters: user._id},
      $inc: {votes: 1, baseScore: votePower},
      $set: {inactive: false}
    });

    // extend item with baseScore to help calculate newScore
    item = _.extend(item, {baseScore: (item.baseScore + votePower)});
    updateScore({collection: collection, item: item, forceUpdate: true});

    // if the item is being upvoted by its own author, don't give karma
    if (item.userId != user._id){
      modifyKarma(item.userId, votePower);

      // if karma redistribution is enabled, give karma to all previous upvoters of the post
      // (but not to the person doing the upvoting)
      if(getSetting('redistributeKarma', false)){
        _.each(item.upvoters, function(upvoterId){
          // share the karma equally among all upvoters, but cap the value at 0.1
          var karmaIncrease = Math.min(0.1, votePower/item.upvoters.length);
          modifyKarma(upvoterId, 0.1);
        });
      }
    }
    return true;
  };

  var downvoteItem = function(collection, item) {
    var user = Meteor.user(),
        votePower = getVotePower(user);

    // make sure user has rights to downvote first
    if (!user || !canDownvote(user, collection, true)  || hasDownvotedItem(item, user))
      return false;

    // if user is downvoting a previously upvoted item, cancel upvote first
    if (hasUpvotedItem(item, user))
      cancelUpvote(collection, item, user);

    // Votes & Score
    collection.update({_id: item && item._id},{
      $addToSet: {downvoters: user._id},
      $pull: {upvoters: user._id},
      $inc: {votes: -1, baseScore: -votePower},
      $set: {inactive: false}
    });

    // extend item with baseScore to help calculate newScore
    item = _.extend(item, {baseScore: (item.baseScore + votePower)});
    updateScore({collection: collection, item: item, forceUpdate: true});

    // if the item is being upvoted by its own author, don't give karma
    if (item.userId != user._id)
      modifyKarma(item.userId, votePower);

    return true;
  };

  var cancelUpvote = function(collection, item) {
    var user = Meteor.user();
        votePower = getVotePower(user);

    // if user isn't among the upvoters, abort
    if(!hasUpvotedItem(item, user))
      return false;

    // Votes & Score
    collection.update({_id: item && item._id},{
      $pull: {upvoters: user._id},
      $inc: {votes: -1, baseScore: -votePower},
      $set: {inactive: false}
    });

    // extend item with baseScore to help calculate newScore
    item = _.extend(item, {baseScore: (item.baseScore + votePower)});
    updateScore({collection: collection, item: item, forceUpdate: true});

    // if the item is being upvoted by its own author, don't give karma
    if (item.userId != user._id)
      modifyKarma(item.userId, votePower);

    return true;
  };

  var cancelDownvote = function(collection, item) {
    var user = Meteor.user(),
      votePower = getVotePower(user);

    // if user isn't among the downvoters, abort
    if(!hasUpvotedItem(item, user))
      return false;

    // Votes & Score
    collection.update({_id: item && item._id},{
      $pull: {downvoters: user._id},
      $inc: {votes: 1, baseScore: votePower},
      $set: {inactive: false}
    });

    // extend item with baseScore to help calculate newScore
    item = _.extend(item, {baseScore: (item.baseScore + votePower)});
    updateScore({collection: collection, item: item, forceUpdate: true});

    // if the item is being upvoted by its own author, don't give karma
    if (item.userId != user._id)
      modifyKarma(item.userId, votePower);

    return true;
  };

  // note: doesn't actually seem very useful to enable admins to vote for other users. Remove this?
  var getUser = function(user){
    // only let admins specify different users for voting
    // if no user is specified, use current user by default
    return (isAdmin(Meteor.user()) && typeof user !== 'undefined') ? user : Meteor.user();
  };

  Meteor.methods({
    upvotePost: function(post, user){
      return upvoteItem.call(this, Posts, post);
    },
    downvotePost: function(post, user){
      return downvoteItem.call(this, Posts, post);
    },
    cancelUpvotePost: function(post, user){
      return cancelUpvote.call(this, Posts, post);
    },
    cancelDownvotePost: function(post, user){
      return cancelDownvote.call(this, Posts, post);
    },
    upvoteComment: function(comment, user){
      return upvoteItem.call(this, Comments, comment);
    },
    downvoteComment: function(comment, user){
      return downvoteItem.call(this, Comments, comment);
    },
    cancelUpvoteComment: function(comment, user){
      return cancelUpvote.call(this, Comments, comment);
    },
    cancelDownvoteComment: function(comment, user){
      return cancelDownvote.call(this, Comments, comment);
    }
  });
<commit_msg>fixed - upvote/downvote<commit_after>
  // returns how much "power" a user's votes have
  var getVotePower = function(user){
    // return (user && user.isAdmin) ? 5 : 1;
    return 1; // for now, leave everybody at 1 including admins; 5 is too unbalanced
  };

  var modifyKarma = function(userId, karma){
    Meteor.users.update({_id: userId}, {$inc: {karma: karma}});
  };

  var hasUpvotedItem= function(item, user){
    return item.upvoters && item.upvoters.indexOf(user._id) != -1;
  };

  var hasDownvotedItem= function(item, user){
    return item.downvoters && item.downvoters.indexOf(user._id) != -1;
  };

  var upvoteItem = function(collection, item) {
    var user = Meteor.user(),
        votePower = getVotePower(user);

    // make sure user has rights to upvote first
    if (!user || !canUpvote(user, collection, true)  || hasUpvotedItem(item, user))
      return false;

    // if user is upvoting a previously downvoted item, cancel downvote first
    if (hasDownvotedItem(item, user))
      cancelDownvote(collection, item, user);

    // Votes & Score
    var result = collection.update({_id: item && item._id},{
      $addToSet: {upvoters: user._id},
      $pull: {downvoters: user._id},
      $inc: {votes: 1, baseScore: votePower},
      $set: {inactive: false}
    });

    // extend item with baseScore to help calculate newScore
    item = _.extend(item, {baseScore: (item.baseScore + votePower)});
    updateScore({collection: collection, item: item, forceUpdate: true});

    // if the item is being upvoted by its own author, don't give karma
    if (item.userId != user._id){
      modifyKarma(item.userId, votePower);

      // if karma redistribution is enabled, give karma to all previous upvoters of the post
      // (but not to the person doing the upvoting)
      if(getSetting('redistributeKarma', false)){
        _.each(item.upvoters, function(upvoterId){
          // share the karma equally among all upvoters, but cap the value at 0.1
          var karmaIncrease = Math.min(0.1, votePower/item.upvoters.length);
          modifyKarma(upvoterId, 0.1);
        });
      }
    }
    return true;
  };

  var downvoteItem = function(collection, item) {
    var user = Meteor.user(),
        votePower = getVotePower(user);

    // make sure user has rights to downvote first
    if (!user || !canDownvote(user, collection, true)  || hasDownvotedItem(item, user))
      return false;

    // if user is downvoting a previously upvoted item, cancel upvote first
    if (hasUpvotedItem(item, user))
      cancelUpvote(collection, item, user);

    // Votes & Score
    collection.update({_id: item && item._id},{
      $addToSet: {downvoters: user._id},
      $pull: {upvoters: user._id},
      $inc: {votes: -1, baseScore: -votePower},
      $set: {inactive: false}
    });

    // extend item with baseScore to help calculate newScore
    item = _.extend(item, {baseScore: (item.baseScore + votePower)});
    updateScore({collection: collection, item: item, forceUpdate: true});

    // if the item is being upvoted by its own author, don't give karma
    if (item.userId != user._id)
      modifyKarma(item.userId, votePower);

    return true;
  };

  var cancelUpvote = function(collection, item) {
    var user = Meteor.user();
        votePower = getVotePower(user);

    // if user isn't among the upvoters, abort
    if(!hasUpvotedItem(item, user))
      return false;

    // Votes & Score
    collection.update({_id: item && item._id},{
      $pull: {upvoters: user._id},
      $inc: {votes: -1, baseScore: -votePower},
      $set: {inactive: false}
    });

    // extend item with baseScore to help calculate newScore
    item = _.extend(item, {baseScore: (item.baseScore + votePower)});
    updateScore({collection: collection, item: item, forceUpdate: true});

    // if the item is being upvoted by its own author, don't give karma
    if (item.userId != user._id)
      modifyKarma(item.userId, votePower);

    return true;
  };

  var cancelDownvote = function(collection, item) {
    var user = Meteor.user(),
      votePower = getVotePower(user);

    // if user isn't among the downvoters, abort
    if(!hasDownvotedItem(item, user))
      return false;

    // Votes & Score
    collection.update({_id: item && item._id},{
      $pull: {downvoters: user._id},
      $inc: {votes: 1, baseScore: votePower},
      $set: {inactive: false}
    });

    // extend item with baseScore to help calculate newScore
    item = _.extend(item, {baseScore: (item.baseScore + votePower)});
    updateScore({collection: collection, item: item, forceUpdate: true});

    // if the item is being upvoted by its own author, don't give karma
    if (item.userId != user._id)
      modifyKarma(item.userId, votePower);

    return true;
  };

  // note: doesn't actually seem very useful to enable admins to vote for other users. Remove this?
  var getUser = function(user){
    // only let admins specify different users for voting
    // if no user is specified, use current user by default
    return (isAdmin(Meteor.user()) && typeof user !== 'undefined') ? user : Meteor.user();
  };

  Meteor.methods({
    upvotePost: function(post, user){
      return upvoteItem.call(this, Posts, post);
    },
    downvotePost: function(post, user){
      return downvoteItem.call(this, Posts, post);
    },
    cancelUpvotePost: function(post, user){
      return cancelUpvote.call(this, Posts, post);
    },
    cancelDownvotePost: function(post, user){
      return cancelDownvote.call(this, Posts, post);
    },
    upvoteComment: function(comment, user){
      return upvoteItem.call(this, Comments, comment);
    },
    downvoteComment: function(comment, user){
      return downvoteItem.call(this, Comments, comment);
    },
    cancelUpvoteComment: function(comment, user){
      return cancelUpvote.call(this, Comments, comment);
    },
    cancelDownvoteComment: function(comment, user){
      return cancelDownvote.call(this, Comments, comment);
    }
  });
<|endoftext|>


<commit_before>/*
 * Wifi Support
 *
 * Copyright(c) 2012 Fred Chien <fred@mandice.com>
 *
 */

module.exports = function(connman) {
	var self = this;
	var dbus = connman.dbus;
	var updaterID = null;

	this.service = null;
	this.serviceChangedCallback = null;
	this._internalServiceChangedCallback = null;
	this._enableServiceChanged = function() {
		if (self.service) {
			self.service.PropertyChanged.onemit = _serviceChangedCallback;
			self.service.PropertyChanged.enabled = true;
		}

		/* Timer for pulling strength */
		if (!updaterID) {
			updaterID = setInterval(function() {
				if (self.service) {

					var serviceProp = self.service.GetProperties();

					if ('Strength' in serviceProp) {
						_serviceChangedCallback('Strength', serviceProp.Strength);
					}
				}
			}, 30000);
		}
	};

	this._disableServiceChanged = function() {
		/* ServiceChanged signal is being using */
		if (self.serviceChangedCallback)
			return;

		if (self.service) {
			self.service.ServiceChanged.onemit = null;
			self.service.ServiceChanged.enabled = false;
		}

		if (updaterID)
			clearInterval(updaterID);
	};

	var _serviceChangedCallback = function() {
		if (self._internalServiceChangedCallback)
			self._internalServiceChangedCallback.apply(self, Array.prototype.slice.call(arguments));

		if (self.serviceChangedCallback)
			self.serviceChangedCallback.apply(self, Array.prototype.slice.call(arguments));
	};

	/* Create connection for Wifi Technology */
	this.technology = connman.Technology.Find('wifi');

	this.ListAPs = function(callback) {
		process.nextTick(function() {
			var origList = connman.manager.GetServices();
			var list = [];

			/* We only get services of wifi */
			for (var index in origList) {
				if (origList[index][1].Type != 'wifi')
					continue;

				origList[index][1].dbusObject = origList[index][0];

				list.push(origList[index][1]);
			}

			delete origList;

			callback(list);
		});
	};

	this.Scan = function(callback) {
		if (self.technology) {
			process.nextTick(function() {
				self.technology.Scan['finish'] = function() {
					callback();
				};
				self.technology.Scan['timeout'] = 30000;
				self.technology.Scan();
			});
		}
	};

	this.FindAccessPoint = function(ssid, callback) {
		process.nextTick(function() {
			var List = connman.manager.GetServices();
			var ap;

			for (var index in List) {
				ap = List[index];
				if (ap[1].Name == ssid) {
					callback(null, ap);

					delete List;

					return;
				}
			}

			delete List;

			callback(new Error('Cannot find such access point'));
		});
	};

	this.Connect = function(ssid, passphrase, security) {
		if (self.technology) {
			self.FindAccessPoint(ssid, function(err, ap) {
				if (err)
					return;

				/* Get service interface */
				self.service = dbus.get_interface(connman.systemBus, 'net.connman', ap[0], 'net.connman.Service');

				/* Connect to Agent to make connection with access point */
				self.service.Connect();
			});
		}
	};

	this.GetStatus = function(callback) {
		process.nextTick(function() {
			var List = connman.manager.GetServices();
			var service;

			for (var index in List) {
				service = List[index];
				if (service[1].Type == 'wifi' && (service[1].State == 'online' || service[1].State == 'ready')) {

					/* Get service interface */
					self.service = dbus.get_interface(connman.systemBus, 'net.connman', service[0], 'net.connman.Service');

					callback(null, service);

					return;
				}
			}

			callback(new Error('Cannot get Wifi status'));
		});
	};

	/* Signal */
	this.onPropertyChanged = function(callback) {
		self.technology.PropertyChanged.onemit = callback;
		self.technology.PropertyChanged.enabled = true;
	};

	this.onServiceChanged = function(callback) {
		self.serviceChangedCallback = callback;

		self._enableServiceChanged();
	};

	/* Properties */
	this.__defineGetter__('Connected', function() {
		return self.technology.GetProperties().Connected;
	});

	this.__defineGetter__('Powered', function() {
		return self.technology.GetProperties().Powered;
	});

	this.__defineSetter__('Powered', function(value) {
		self.technology.SetProperty('Powered', value);
	});

	this.__defineGetter__('Tethering', function() {
		return self.technology.GetProperties().Tethering;
	});

	this.__defineSetter__('Tethering', function(value) {
		self.technology.SetProperty('Tethering', value);
	});
};
<commit_msg>remove uneccessary parameter and add a new method to connect specific service<commit_after>/*
 * Wifi Support
 *
 * Copyright(c) 2012 Fred Chien <fred@mandice.com>
 *
 */

module.exports = function(connman) {
	var self = this;
	var dbus = connman.dbus;
	var updaterID = null;

	this.service = null;
	this.serviceChangedCallback = null;
	this._internalServiceChangedCallback = null;
	this._enableServiceChanged = function() {
		if (self.service) {
			self.service.PropertyChanged.onemit = _serviceChangedCallback;
			self.service.PropertyChanged.enabled = true;
		}

		/* Timer for pulling strength */
		if (!updaterID) {
			updaterID = setInterval(function() {
				if (self.service) {

					var serviceProp = self.service.GetProperties();

					if ('Strength' in serviceProp) {
						_serviceChangedCallback('Strength', serviceProp.Strength);
					}
				}
			}, 30000);
		}
	};

	this._disableServiceChanged = function() {
		/* ServiceChanged signal is being using */
		if (self.serviceChangedCallback)
			return;

		if (self.service) {
			self.service.ServiceChanged.onemit = null;
			self.service.ServiceChanged.enabled = false;
		}

		if (updaterID)
			clearInterval(updaterID);
	};

	var _serviceChangedCallback = function() {
		if (self._internalServiceChangedCallback)
			self._internalServiceChangedCallback.apply(self, Array.prototype.slice.call(arguments));

		if (self.serviceChangedCallback)
			self.serviceChangedCallback.apply(self, Array.prototype.slice.call(arguments));
	};

	/* Create connection for Wifi Technology */
	this.technology = connman.Technology.Find('wifi');

	this.ListAPs = function(callback) {
		process.nextTick(function() {
			var origList = connman.manager.GetServices();
			var list = [];

			/* We only get services of wifi */
			for (var index in origList) {
				if (origList[index][1].Type != 'wifi')
					continue;

				origList[index][1].dbusObject = origList[index][0];

				list.push(origList[index][1]);
			}

			delete origList;

			callback(list);
		});
	};

	this.Scan = function(callback) {
		if (self.technology) {
			process.nextTick(function() {
				self.technology.Scan['finish'] = function() {
					callback();
				};
				self.technology.Scan['timeout'] = 30000;
				self.technology.Scan();
			});
		}
	};

	this.FindAccessPoint = function(ssid, callback) {
		process.nextTick(function() {
			var List = connman.manager.GetServices();
			var ap;

			for (var index in List) {
				ap = List[index];
				if (ap[1].Name == ssid) {
					callback(null, ap);

					delete List;

					return;
				}
			}

			delete List;

			callback(new Error('Cannot find such access point'));
		});
	};

	this.ConnectService = function(service) {
		/* Get service interface */
		self.service = dbus.get_interface(connman.systemBus, 'net.connman', service, 'net.connman.Service');

		/* Connect to Agent to make connection with access point */
		self.service.Connect();
	};

	this.Connect = function(ssid) {
		if (self.technology) {
			self.FindAccessPoint(ssid, function(err, ap) {
				if (err)
					return;

				self.ConnectService(ap[0]);
			});
		}
	};

	this.GetStatus = function(callback) {
		process.nextTick(function() {
			var List = connman.manager.GetServices();
			var service;

			for (var index in List) {
				service = List[index];
				if (service[1].Type == 'wifi' && (service[1].State == 'online' || service[1].State == 'ready')) {

					/* Get service interface */
					self.service = dbus.get_interface(connman.systemBus, 'net.connman', service[0], 'net.connman.Service');

					callback(null, service);

					return;
				}
			}

			callback(new Error('Cannot get Wifi status'));
		});
	};

	/* Signal */
	this.onPropertyChanged = function(callback) {
		self.technology.PropertyChanged.onemit = callback;
		self.technology.PropertyChanged.enabled = true;
	};

	this.onServiceChanged = function(callback) {
		self.serviceChangedCallback = callback;

		self._enableServiceChanged();
	};

	/* Properties */
	this.__defineGetter__('Connected', function() {
		return self.technology.GetProperties().Connected;
	});

	this.__defineGetter__('Powered', function() {
		return self.technology.GetProperties().Powered;
	});

	this.__defineSetter__('Powered', function(value) {
		self.technology.SetProperty('Powered', value);
	});

	this.__defineGetter__('Tethering', function() {
		return self.technology.GetProperties().Tethering;
	});

	this.__defineSetter__('Tethering', function(value) {
		self.technology.SetProperty('Tethering', value);
	});
};
<|endoftext|>


<commit_before>var path = require('path')
var child_process = require('child_process')
var fork = child_process.fork
var resolve = require('resolve').sync
var hook = require('./hook')
var ipc = require('./ipc')
var cfg = require('./cfg')
var cli = require('./cli')

// Remove wrap.js from the argv array
process.argv.splice(1, 1)

// Resolve the location of the main script relative to cwd
var main = cli.resolveMain(process.argv[1])

var cfg = require('./cfg')(main)

// Set NODE_ENV to 'development' unless already set
if (!process.env.NODE_ENV) process.env.NODE_ENV = 'development'

if (process.env.NODE_DEV_PRELOAD) {
  require(process.env.NODE_DEV_PRELOAD)
}

// Listen SIGTERM and exit unless there is another listener
process.on('SIGTERM', function() {
  if (process.listeners('SIGTERM').length == 1) process.exit(0)
})

if (cfg.fork) {
  // Overwrite child_process.fork() so that we can hook into forked processes
  // too. We also need to relay messages about required files to the parent.
  child_process.fork = function(modulePath, args, options) {
    var child = fork(__filename, [modulePath].concat(args), options)
    ipc.relay(child)
    return child
  }
}

// Error handler that displays a notification and logs the stack to stderr:
process.on('uncaughtException', function(err) {
 ipc.send({error: err.name, message: err.message})
 console.error(err.stack || err)
})

// Hook into require() and notify the parent process about required files
hook(cfg, module, function(file) {
  ipc.send({required: file})
})

// Check if a module is registered for this extension
var ext = path.extname(main).slice(1)
  , mod = cfg.extensions[ext]

if (mod) require(resolve(mod, { basedir: path.dirname(main) }))

// Execute the wrapped script
require(main)
<commit_msg>log error before signalling parent<commit_after>var path = require('path')
var child_process = require('child_process')
var fork = child_process.fork
var resolve = require('resolve').sync
var hook = require('./hook')
var ipc = require('./ipc')
var cfg = require('./cfg')
var cli = require('./cli')

// Remove wrap.js from the argv array
process.argv.splice(1, 1)

// Resolve the location of the main script relative to cwd
var main = cli.resolveMain(process.argv[1])

var cfg = require('./cfg')(main)

// Set NODE_ENV to 'development' unless already set
if (!process.env.NODE_ENV) process.env.NODE_ENV = 'development'

if (process.env.NODE_DEV_PRELOAD) {
  require(process.env.NODE_DEV_PRELOAD)
}

// Listen SIGTERM and exit unless there is another listener
process.on('SIGTERM', function() {
  if (process.listeners('SIGTERM').length == 1) process.exit(0)
})

if (cfg.fork) {
  // Overwrite child_process.fork() so that we can hook into forked processes
  // too. We also need to relay messages about required files to the parent.
  child_process.fork = function(modulePath, args, options) {
    var child = fork(__filename, [modulePath].concat(args), options)
    ipc.relay(child)
    return child
  }
}

// Error handler that displays a notification and logs the stack to stderr:
process.on('uncaughtException', function(err) {
 console.error(err.stack || err)
 ipc.send({ error: err.name || 'Error' , message: err.message })
})

// Hook into require() and notify the parent process about required files
hook(cfg, module, function(file) {
  ipc.send({required: file})
})

// Check if a module is registered for this extension
var ext = path.extname(main).slice(1)
  , mod = cfg.extensions[ext]

if (mod) require(resolve(mod, { basedir: path.dirname(main) }))

// Execute the wrapped script
require(main)
<|endoftext|>


<commit_before>/*
 * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
$(function () {
    var conf;
    var schema;
    var providerData;
    var init = function () {
        var CHART_CONF = 'chart-conf';
        var GADGET_NAME = 'gadget-name';
        $.ajax({
            url: '/portal/store/carbon.super/fs/gadget/my_gadget/conf.json',
            method: "GET",
            contentType: "application/json",
            async: false,
            success: function (data) {
                conf = JSON.parse(data);
                console.log(JSON.stringify(conf));
                console.log(conf[CHART_CONF][GADGET_NAME]);
                $.ajax({
                    url: '/portal/store/carbon.super/fs/gadget/' + conf[CHART_CONF][GADGET_NAME] + '/gadget-controller.jag?action=getSchema',
                    method: "POST",
                    data: JSON.stringify(conf),
                    contentType: "application/json",
                    async: false,
                    success: function (data) {
                        console.log(JSON.stringify(data));
                        schema = data;
                    }
                });
                $.ajax({
                    url: '/portal/store/carbon.super/fs/gadget/'  + conf[CHART_CONF][GADGET_NAME] +'/gadget-controller.jag?action=getData',
                    method: "POST",
                    data: JSON.stringify(conf),
                    contentType: "application/json",
                    async: false,
                    success: function (data) {
                        providerData = data;
                    }
                });
            }
        });

        draw('#canvas', conf[CHART_CONF], schema, providerData);
    }
    init();
});
<commit_msg>deriving gadgetLocation from top level variable<commit_after>/*
 * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
$(function () {
    var conf;
    var schema;
    var providerData;
    // gadgetLocation will be dynamically injected
    var gadgetLocation = '/portal/store/carbon.super/fs/gadget/my_gadget/';
    var init = function () {

        var CHART_CONF = 'chart-conf';
        var GADGET_NAME = 'gadget-name';
        $.ajax({
            url: gadgetLocation + 'conf.json',
            method: "GET",
            contentType: "application/json",
            async: false,
            success: function (data) {
                conf = JSON.parse(data);
                console.log(JSON.stringify(conf));
                console.log(conf[CHART_CONF][GADGET_NAME]);
                $.ajax({
                    url: gadgetLocation +  '/gadget-controller.jag?action=getSchema',
                    method: "POST",
                    data: JSON.stringify(conf),
                    contentType: "application/json",
                    async: false,
                    success: function (data) {
                        console.log(JSON.stringify(data));
                        schema = data;
                    }
                });
                $.ajax({
                    url: gadgetLocation +'/gadget-controller.jag?action=getData',
                    method: "POST",
                    data: JSON.stringify(conf),
                    contentType: "application/json",
                    async: false,
                    success: function (data) {
                        providerData = data;
                    }
                });
            }
        });

        draw('#canvas', conf[CHART_CONF], schema, providerData);
    }
    init();
});
<|endoftext|>


<commit_before>//Event
$(document).ready(function()
{
    document.loadSidebar();
});
//Account
document.popLogin = function()
{

    $("#cover").fadeIn(function ()
    {
        $("#form-signin-container").fadeIn();
    });
};
document.hideLogin = function ()
{
    $("#form-signin-container").fadeOut(function ()
    {
       $("#cover").fadeOut();
    });

};
document.login = function ()
{

    $.ajax({
        url: "Login.exec",
        cache: false,
        type: "POST",
        dataType :"json",
        data: {
            name: $("#form-signin-username").val(),
            password: $("#form-signin-password").val()
        },
        success: function (data)
        {
            $("#form-signin-notice").show();
            $("#form-signin-notice").removeClass();
            switch (data.status)
            {
                case 0:

                    $("#form-signin-notice").addClass("alert alert-success");
                    $("#form-signin-notice").text(data.text);
                    document.receiveUserData();
                    document.hideLogin();
                    break;
                case 1:

                    $("#form-signin-notice").addClass("alert alert-info");
                    $("#form-signin-notice").text(data.text);
                    break;

                case 2:

                    $("#form-signin-notice").addClass("alert alert-warning");
                    $("#form-signin-notice").text(data.text);
                    break;

                default:
                    $("#form-signin-notice").addClass("alert alert-danger");
                    $("#form-signin-notice").text(data.text);
                    break;
            }
            document.loadSidebar();
        }

    });
};

document.logout = function()
{
    $.removeCookie('identification');
    $.removeCookie('varify');
    $("#signin-block").show();
    $("#signed-block").hide();
};

document.receiveUserData = function ()
{
    $.ajax({
        url: "ReceiveUserData.exec",
        success: function (data)
        {
            $("#signin-block").hide();
            $("#signed-block").show();
        }

    });
};
//Content Loader
document.loadContent = function (url)
{
    $.ajax({
        url: url,
        success: function (data)
        {
            $("#content").html(data);
          //  document.contentInit();
        }

    });
};

document.loadSidebar = function ()
{
    $.ajax({
        url: "Sidebar.exec",
        dataType: "json",
        cache:false,
        success: function (data)
        {

            $("#sidebar-content").empty();
            $(data).each(function ()
            {
                var li = $("

");
                li.addClass("sidebar-child");
                var a = $("");
                a.attr("href", "#");
                var i = $("");
                i.addClass("icon");
                i.addClass(this.iconName);
                var span = $("");
                span.text(this.title);
                li.append(a);
                a.append(i);
                a.append(span);
                li.attr("onclick", "document.loadContent('" + this.url + "');");

                $("#sidebar-content").append(li);
            });
            $(".sidebar-child")[0].click();
        }

    });
}<commit_msg>Change parameter name<commit_after>//Event
$(document).ready(function()
{
    document.loadSidebar();
});
//Account
document.popLogin = function()
{

    $("#cover").fadeIn(function ()
    {
        $("#form-signin-container").fadeIn();
    });
};
document.hideLogin = function ()
{
    $("#form-signin-container").fadeOut(function ()
    {
       $("#cover").fadeOut();
    });

};
document.login = function ()
{

    $.ajax({
        url: "Login.exec",
        cache: false,
        type: "POST",
        dataType :"json",
        data: {
            username: $("#form-signin-username").val(),
            password: $("#form-signin-password").val()
        },
        success: function (data)
        {
            $("#form-signin-notice").show();
            $("#form-signin-notice").removeClass();
            switch (data.status)
            {
                case 0:

                    $("#form-signin-notice").addClass("alert alert-success");
                    $("#form-signin-notice").text(data.text);
                    document.receiveUserData();
                    document.hideLogin();
                    document.loadSidebar();
                    break;
                case 1:

                    $("#form-signin-notice").addClass("alert alert-info");
                    $("#form-signin-notice").text(data.text);
                    break;

                case 2:

                    $("#form-signin-notice").addClass("alert alert-warning");
                    $("#form-signin-notice").text(data.text);
                    break;

                default:
                    $("#form-signin-notice").addClass("alert alert-danger");
                    $("#form-signin-notice").text(data.text);
                    break;
            }

        }

    });
};

document.logout = function()
{
    $.removeCookie('identification');
    $("#signin-block").show();
    $("#signed-block").hide();
};

document.receiveUserData = function ()
{
    $.ajax({
        url: "ReceiveUserData.exec",
        success: function (data)
        {
            $("#signin-block").hide();
            $("#signed-block").show();
        }

    });
};
//Content Loader
document.loadContent = function (url)
{
    $.ajax({
        url: url,
        success: function (data)
        {
            $("#content").html(data);
          //  document.contentInit();
        }

    });
};

document.loadSidebar = function ()
{
    $.ajax({
        url: "Sidebar.exec",
        dataType: "json",
        cache:false,
        success: function (data)
        {

            $("#sidebar-content").empty();
            $(data).each(function ()
            {
                var li = $("

");
                li.addClass("sidebar-child");
                var a = $("");
                a.attr("href", "#");
                var i = $("");
                i.addClass("icon");
                i.addClass(this.iconName);
                var span = $("");
                span.text(this.title);
                li.append(a);
                a.append(i);
                a.append(span);
                li.attr("onclick", "document.loadContent('" + this.url + "');");

                $("#sidebar-content").append(li);
            });
            $(".sidebar-child")[0].click();
        }

    });
}<|endoftext|>