<commit_before>/**
 * @todo: recursively send requests until all contacts are fetched
 *
 * @see https://developers.google.com/google-apps/contacts/v3/reference#ContactsFeed
 *
 * To API test requests:
 *
 * @see https://developers.google.com/oauthplayground/
 *
 * To format JSON nicely:
 *
 * @see http://jsonviewer.stack.hu/
 *
 * Note: The Contacts API has a hard limit to the number of results it can return at a
 * time even if you explicitly request all possible results. If the requested feed has
 * more fields than can be returned in a single response, the API truncates the feed and adds
 * a "Next" link that allows you to request the rest of the response.
 */
var EventEmitter = require('events').EventEmitter,
  _ = require('underscore'),
  qs = require('querystring'),
  util = require('util'),
  url = require('url'),
  https = require('https'),
  querystring = require('querystring');

var GoogleContacts = function (opts) {
  if (typeof opts === 'string') {
    opts = { token: opts }
  }
  if (!opts) {
    opts = {};
  }

  this.contacts = [];
  this.consumerKey = opts.consumerKey ? opts.consumerKey : null;
  this.consumerSecret = opts.consumerSecret ? opts.consumerSecret : null;
  this.token = opts.token ? opts.token : null;
  this.refreshToken = opts.refreshToken ? opts.refreshToken : null;
};

GoogleContacts.prototype = {};

util.inherits(GoogleContacts, EventEmitter);

GoogleContacts.prototype._get = function (params, cb) {
  var self = this;

  if (typeof params === 'function') {
    cb = params;
    params = {};
  }

  var req = {
    host: 'www.google.com',
    port: 443,
    path: this._buildPath(params),
    method: 'GET',
    headers: {
      'Authorization': 'OAuth ' + this.token
    }
  };

  console.log(req);

  https.request(req, function (res) {
    var data = '';

    res.on('end', function () {
      if (res.statusCode < 200 || res.statusCode >= 300) {
        var error = new Error('Bad client request status: ' + res.statusCode);
        return cb(error);
      }
      try {
        data = JSON.parse(data);
        cb(null, data);
      }
      catch (err) {
        cb(err);
      }
    });

    res.on('data', function (chunk) {
      //console.log(chunk.toString());
      data += chunk;
    });

    res.on('error', function (err) {
      cb(err);
    });

    //res.on('close', onFinish);
  }).on('error', function (err) {
    cb(err);
  }).end();
};

GoogleContacts.prototype.getContacts = function (cb, contacts) {
  var self = this;

  this._get({ type: 'contacts' }, receivedContacts);
  function receivedContacts(err, data) {
    if (err) return cb(err);

    self._saveContactsFromFeed(data.feed);

    var next = false;
    data.feed.link.forEach(function (link) {
      if (link.rel === 'next') {
        next = true;
        var path = url.parse(link.href).path;
        self._get({ path: path }, receivedContacts);
      }
    });
    if (!next) {
      cb(null, self.contacts);
    }
  };
};

GoogleContacts.prototype._saveContactsFromFeed = function (feed) {
  var self = this;
  //console.log(feed);
  feed.entry.forEach(function (entry) {
    try {
      var name = entry.title['$t'];
      var email = entry['gd$email'][0].address; // only save first email
      self.contacts.push({ name: name, email: email });
    }
    catch (e) {
      // property not available...
    }
  });
  console.log(self.contacts);
  console.log(self.contacts.length);
}

GoogleContacts.prototype._buildPath = function (params) {
  if (params.path) return params.path;

  params = params || {};
  params.type = params.type || 'contacts';
  params.alt = params.alt || 'json';
  params.projection = params.projection || 'thin';
  params.email = params.email || 'default';
  params['max-results'] = params['max-results'] || 2000;

  var query = {
    alt: params.alt,
    'max-results': params['max-results']
  };

  var path = '/m8/feeds/';
  path += params.type + '/';
  path += params.email + '/';
  path += params.projection;
  path += '?' + qs.stringify(query);

  return path;
};

GoogleContacts.prototype.refreshAccessToken = function (refreshToken, cb) {
  if (typeof params === 'function') {
    cb = params;
    params = {};
  }

  var data = {
    refresh_token: refreshToken,
    client_id: this.consumerKey,
    client_secret: this.consumerSecret,
    grant_type: 'refresh_token'

  }

  var body = qs.stringify(data);

  var opts = {
    host: 'accounts.google.com',
    port: 443,
    path: '/o/oauth2/token',
    method: 'POST',
    headers: {
      'Content-Type': 'application/x-www-form-urlencoded',
      'Content-Length': body.length
    }
  };

  //console.log(opts);
  //console.log(data);

  var req = https.request(opts, function (res) {
    var data = '';
    res.on('end', function () {
      if (res.statusCode < 200 || res.statusCode >= 300) {
        var error = new Error('Bad client request status: ' + res.statusCode);
        return cb(error);
      }
      try {
        data = JSON.parse(data);
        //console.log(data);
        cb(null, data.access_token);
      }
      catch (err) {
        cb(err);
      }
    });

    res.on('data', function (chunk) {
      //console.log(chunk.toString());
      data += chunk;
    });

    res.on('error', function (err) {
      cb(err);
    });

    //res.on('close', onFinish);
  }).on('error', function (err) {
    cb(err);
  });

  req.write(body);
  req.end();
}

exports.GoogleContacts = GoogleContacts;
<commit_msg>changing from 'OAuth' to 'Bearer' for Authorization header<commit_after>/**
 * @todo: recursively send requests until all contacts are fetched
 *
 * @see https://developers.google.com/google-apps/contacts/v3/reference#ContactsFeed
 *
 * To API test requests:
 *
 * @see https://developers.google.com/oauthplayground/
 *
 * To format JSON nicely:
 *
 * @see http://jsonviewer.stack.hu/
 *
 * Note: The Contacts API has a hard limit to the number of results it can return at a
 * time even if you explicitly request all possible results. If the requested feed has
 * more fields than can be returned in a single response, the API truncates the feed and adds
 * a "Next" link that allows you to request the rest of the response.
 */
var EventEmitter = require('events').EventEmitter,
  _ = require('underscore'),
  qs = require('querystring'),
  util = require('util'),
  url = require('url'),
  https = require('https'),
  querystring = require('querystring');

var GoogleContacts = function (opts) {
  if (typeof opts === 'string') {
    opts = { token: opts }
  }
  if (!opts) {
    opts = {};
  }

  this.contacts = [];
  this.consumerKey = opts.consumerKey ? opts.consumerKey : null;
  this.consumerSecret = opts.consumerSecret ? opts.consumerSecret : null;
  this.token = opts.token ? opts.token : null;
  this.refreshToken = opts.refreshToken ? opts.refreshToken : null;
};

GoogleContacts.prototype = {};

util.inherits(GoogleContacts, EventEmitter);

GoogleContacts.prototype._get = function (params, cb) {
  var self = this;

  if (typeof params === 'function') {
    cb = params;
    params = {};
  }

  var req = {
    host: 'www.google.com',
    port: 443,
    path: this._buildPath(params),
    method: 'GET',
    headers: {
      'Authorization': 'Bearer ' + this.token
    }
  };

  console.log(req);

  https.request(req, function (res) {
    var data = '';

    res.on('end', function () {
      if (res.statusCode < 200 || res.statusCode >= 300) {
        var error = new Error('Bad client request status: ' + res.statusCode);
        return cb(error);
      }
      try {
        data = JSON.parse(data);
        cb(null, data);
      }
      catch (err) {
        cb(err);
      }
    });

    res.on('data', function (chunk) {
      //console.log(chunk.toString());
      data += chunk;
    });

    res.on('error', function (err) {
      cb(err);
    });

    //res.on('close', onFinish);
  }).on('error', function (err) {
    cb(err);
  }).end();
};

GoogleContacts.prototype.getContacts = function (cb, contacts) {
  var self = this;

  this._get({ type: 'contacts' }, receivedContacts);
  function receivedContacts(err, data) {
    if (err) return cb(err);

    self._saveContactsFromFeed(data.feed);

    var next = false;
    data.feed.link.forEach(function (link) {
      if (link.rel === 'next') {
        next = true;
        var path = url.parse(link.href).path;
        self._get({ path: path }, receivedContacts);
      }
    });
    if (!next) {
      cb(null, self.contacts);
    }
  };
};

GoogleContacts.prototype._saveContactsFromFeed = function (feed) {
  var self = this;
  //console.log(feed);
  feed.entry.forEach(function (entry) {
    try {
      var name = entry.title['$t'];
      var email = entry['gd$email'][0].address; // only save first email
      self.contacts.push({ name: name, email: email });
    }
    catch (e) {
      // property not available...
    }
  });
  console.log(self.contacts);
  console.log(self.contacts.length);
}

GoogleContacts.prototype._buildPath = function (params) {
  if (params.path) return params.path;

  params = params || {};
  params.type = params.type || 'contacts';
  params.alt = params.alt || 'json';
  params.projection = params.projection || 'thin';
  params.email = params.email || 'default';
  params['max-results'] = params['max-results'] || 2000;

  var query = {
    alt: params.alt,
    'max-results': params['max-results']
  };

  var path = '/m8/feeds/';
  path += params.type + '/';
  path += params.email + '/';
  path += params.projection;
  path += '?' + qs.stringify(query);

  return path;
};

GoogleContacts.prototype.refreshAccessToken = function (refreshToken, cb) {
  if (typeof params === 'function') {
    cb = params;
    params = {};
  }

  var data = {
    refresh_token: refreshToken,
    client_id: this.consumerKey,
    client_secret: this.consumerSecret,
    grant_type: 'refresh_token'

  }

  var body = qs.stringify(data);

  var opts = {
    host: 'accounts.google.com',
    port: 443,
    path: '/o/oauth2/token',
    method: 'POST',
    headers: {
      'Content-Type': 'application/x-www-form-urlencoded',
      'Content-Length': body.length
    }
  };

  //console.log(opts);
  //console.log(data);

  var req = https.request(opts, function (res) {
    var data = '';
    res.on('end', function () {
      if (res.statusCode < 200 || res.statusCode >= 300) {
        var error = new Error('Bad client request status: ' + res.statusCode);
        return cb(error);
      }
      try {
        data = JSON.parse(data);
        //console.log(data);
        cb(null, data.access_token);
      }
      catch (err) {
        cb(err);
      }
    });

    res.on('data', function (chunk) {
      //console.log(chunk.toString());
      data += chunk;
    });

    res.on('error', function (err) {
      cb(err);
    });

    //res.on('close', onFinish);
  }).on('error', function (err) {
    cb(err);
  });

  req.write(body);
  req.end();
}

exports.GoogleContacts = GoogleContacts;
<|endoftext|>


<commit_before>module.exports =  (def, separator=' ') => {
  let classes = ''
  for (const cls in def) {
    if (def[cls]) {
      classes = classes ? cls : classes + separator + cls
    }
  }
  return classes
}<commit_msg>Fix empty check<commit_after>module.exports =  (def, separator=' ') => {
  let classes = ''
  for (const cls in def) {
    if (def[cls]) {
      classes = classes ? classes + separator + cls : cls
    }
  }
  return classes
}<|endoftext|>


<commit_before>
/**
 * Module dependencies.
 */

var Emitter = require('emitter')
  , classes = require('classes')
  , Upload = require('upload')
  , events = require('events')

/**
 * Expose `Dropload`.
 */

module.exports = Dropload;

/**
 * Types.
 */

var typeMap = {
  'text/plain': 'text',
  'text/uri-list': 'url',
  'text/html': 'html'
};

/**
 * Initialize a drop point
 * on the given `el`.
 *
 * Emits:
 *
 *   - `error` on validation error
 *   - `upload` passing an `Upload`
 *
 * @param {Element} el
 * @api public
 */

function Dropload(el) {
  if (!(this instanceof Dropload)) return new Dropload(el);
  Emitter.call(this);
  this.el = el;
  this.classes = classes(el);
  this.events = events(el, this);
  this.events.bind('drop');
  this.events.bind('dragenter');
  this.events.bind('dragleave');
  this.events.bind('dragover');
  this.ignored = {};
}

/**
 * Mixin emitter.
 */

Emitter(Dropload.prototype);

/**
 * Ignore `name`.
 *
 * @param {String} name
 * @api private
 */

Dropload.prototype.ignore = function(name){
  this.ignored[name] = true;
};

/**
 * Check if `name` is ignored.
 *
 * @param {String} name
 * @return {Boolean}
 * @api private
 */

Dropload.prototype.ignoring = function(name){
  return !! this.ignored[name];
};

/**
 * Unbind event handlers.
 *
 * @api public
 */

Dropload.prototype.unbind = function(){
  this.events.unbind();
};

/**
 * Dragenter handler.
 */

Dropload.prototype.ondragenter = function(e){
  this.classes.add('over');
};

/**
 * Dragover handler.
 */

Dropload.prototype.ondragover = function(e){
  e.preventDefault();
};

/**
 * Dragleave handler.
 */

Dropload.prototype.ondragleave = function(e){
  this.classes.remove('over');
};

/**
 * Drop handler.
 */

Dropload.prototype.ondrop = function(e){
  e.stopPropagation();
  e.preventDefault();
  this.classes.remove('over');
  var items = e.dataTransfer.items;
  var files = e.dataTransfer.files;
  if (items) this.directories(items);
  if (items) this.items(items);
  if (files) this.upload(files);
};

/**
 * Walk directories and upload files.
 *
 * Directories are considered "files",
 * non-files return null for .webkitGetAsEntry()
 * for example when dragging urls.
 *
 * @param {DataTransferItemList} items
 * @api private
 */

Dropload.prototype.directories = function(items){
  for (var i = 0; i < items.length; i++) {
    var item = items[i];

    if ('file' != item.kind) continue;

    if (!item.webkitGetAsEntry) continue;
    var entry = item.webkitGetAsEntry();

    if (entry.isDirectory) {
      this.ignore(entry.name);
      this.walkEntry(entry);
    }
  }
};

/**
 * Handle the given `items`.
 *
 * @param {DataTransferItemList}
 * @api private
 */

Dropload.prototype.items = function(items){
  for (var i = 0; i < items.length; i++) {
    var item = items[i];
    this.item(item);
  }
};

/**
 * Walk file entry recursively.
 *
 * @param {FileEntry} item
 * @api private
 */

Dropload.prototype.walkEntry = function(item){
  var self = this;

  if (item.isFile) {
    return item.file(function(file){
      file.entry = item;
      self.upload([file]);
    });
  }

  if (item.isDirectory) {
    var dir = item.createReader();
    dir.readEntries(function(entries){
      for (var i = 0; i < entries.length; i++) {
        var name = entries[i].name;
        if ('.' == name[0]) continue;
        self.walkEntry(entries[i]);
      }
    })
  }
};

/**
 * Handle `item`.
 *
 * @param {Object} item
 * @api private
 */

Dropload.prototype.item = function(item){
  var self = this;
  var type = typeMap[item.type];
  item.getAsString(function(str){
    self.emit(type, str, item);
  });
};

/**
 * Upload the given `files`.
 *
 * Presents each `file` in the FileList
 * as an `Upload` via the "upload" event
 * after it has been validated.
 *
 * @param {FileList} files
 * @api public
 */

Dropload.prototype.upload = function(files){
  for (var i = 0; i < files.length; i++) {
    var file = files[i];
    if (this.ignoring(file.name)) continue;
    this.emit('upload', new Upload(file));
  }
};
<commit_msg>reset ignored state after drop<commit_after>
/**
 * Module dependencies.
 */

var Emitter = require('emitter')
  , classes = require('classes')
  , Upload = require('upload')
  , events = require('events')

/**
 * Expose `Dropload`.
 */

module.exports = Dropload;

/**
 * Types.
 */

var typeMap = {
  'text/plain': 'text',
  'text/uri-list': 'url',
  'text/html': 'html'
};

/**
 * Initialize a drop point
 * on the given `el`.
 *
 * Emits:
 *
 *   - `error` on validation error
 *   - `upload` passing an `Upload`
 *
 * @param {Element} el
 * @api public
 */

function Dropload(el) {
  if (!(this instanceof Dropload)) return new Dropload(el);
  Emitter.call(this);
  this.el = el;
  this.classes = classes(el);
  this.events = events(el, this);
  this.events.bind('drop');
  this.events.bind('dragenter');
  this.events.bind('dragleave');
  this.events.bind('dragover');
  this.ignored = {};
}

/**
 * Mixin emitter.
 */

Emitter(Dropload.prototype);

/**
 * Ignore `name`.
 *
 * @param {String} name
 * @api private
 */

Dropload.prototype.ignore = function(name){
  this.ignored[name] = true;
};

/**
 * Check if `name` is ignored.
 *
 * @param {String} name
 * @return {Boolean}
 * @api private
 */

Dropload.prototype.ignoring = function(name){
  return !! this.ignored[name];
};

/**
 * Unbind event handlers.
 *
 * @api public
 */

Dropload.prototype.unbind = function(){
  this.events.unbind();
};

/**
 * Dragenter handler.
 */

Dropload.prototype.ondragenter = function(e){
  this.classes.add('over');
};

/**
 * Dragover handler.
 */

Dropload.prototype.ondragover = function(e){
  e.preventDefault();
};

/**
 * Dragleave handler.
 */

Dropload.prototype.ondragleave = function(e){
  this.classes.remove('over');
};

/**
 * Drop handler.
 */

Dropload.prototype.ondrop = function(e){
  e.stopPropagation();
  e.preventDefault();
  this.classes.remove('over');
  var items = e.dataTransfer.items;
  var files = e.dataTransfer.files;
  if (items) this.directories(items);
  if (items) this.items(items);
  if (files) this.upload(files);
  this.ignored = {};
};

/**
 * Walk directories and upload files.
 *
 * Directories are considered "files",
 * non-files return null for .webkitGetAsEntry()
 * for example when dragging urls.
 *
 * @param {DataTransferItemList} items
 * @api private
 */

Dropload.prototype.directories = function(items){
  for (var i = 0; i < items.length; i++) {
    var item = items[i];

    if ('file' != item.kind) continue;

    if (!item.webkitGetAsEntry) continue;
    var entry = item.webkitGetAsEntry();

    if (entry.isDirectory) {
      this.ignore(entry.name);
      this.walkEntry(entry);
    }
  }
};

/**
 * Handle the given `items`.
 *
 * @param {DataTransferItemList}
 * @api private
 */

Dropload.prototype.items = function(items){
  for (var i = 0; i < items.length; i++) {
    var item = items[i];
    this.item(item);
  }
};

/**
 * Walk file entry recursively.
 *
 * @param {FileEntry} item
 * @api private
 */

Dropload.prototype.walkEntry = function(item){
  var self = this;

  if (item.isFile) {
    return item.file(function(file){
      file.entry = item;
      self.upload([file]);
    });
  }

  if (item.isDirectory) {
    var dir = item.createReader();
    dir.readEntries(function(entries){
      for (var i = 0; i < entries.length; i++) {
        var name = entries[i].name;
        if ('.' == name[0]) continue;
        self.walkEntry(entries[i]);
      }
    })
  }
};

/**
 * Handle `item`.
 *
 * @param {Object} item
 * @api private
 */

Dropload.prototype.item = function(item){
  var self = this;
  var type = typeMap[item.type];
  item.getAsString(function(str){
    self.emit(type, str, item);
  });
};

/**
 * Upload the given `files`.
 *
 * Presents each `file` in the FileList
 * as an `Upload` via the "upload" event
 * after it has been validated.
 *
 * @param {FileList} files
 * @api public
 */

Dropload.prototype.upload = function(files){
  for (var i = 0; i < files.length; i++) {
    var file = files[i];
    if (this.ignoring(file.name)) continue;
    this.emit('upload', new Upload(file));
  }
};
<|endoftext|>


<commit_before>var denodeify = require('es6-denodeify')(Promise)
var tough = require('tough-cookie')

module.exports = function fetchCookieDecorator (fetch, jar) {
  fetch = fetch || window.fetch
  jar = jar || new tough.CookieJar()

  var getCookieString = denodeify(jar.getCookieString.bind(jar))
  var setCookie = denodeify(jar.setCookie.bind(jar))

  async function fetchCookie (url, opts) {
    opts = opts || {}

    // Prepare request
    const cookie = await getCookieString(typeof url === 'string' ? url : url.url)

    if (url.headers && typeof url.headers.append === 'function') {
      url.headers.append('cookie', cookie)
    } else if (opts.headers && typeof opts.headers.append === 'function') {
      opts.headers.append('cookie', cookie)
    } else {
      opts.headers = Object.assign(
        opts.headers || {},
        cookie ? { cookie: cookie } : {}
      )
    }

    // Actual request
    const res = await fetch(url, opts)

    // Get cookie header
    var cookies = []
    if (res.headers.getAll) {
      // node-fetch v1
      cookies = res.headers.getAll('set-cookie')
      // console.warn("You are using a fetch version that supports 'Headers.getAll' which is deprecated!")
      // console.warn("In the future 'fetch-cookie-v2' may discontinue supporting that fetch implementation.")
      // console.warn('Details: https://developer.mozilla.org/en-US/docs/Web/API/Headers/getAll')
    } else {
      // node-fetch v2
      const headers = res.headers.raw()
      if (headers['set-cookie'] !== undefined) {
        cookies = headers['set-cookie']
      }
    }

    // Store all present cookies
    await Promise.all(cookies.map(cookie => setCookie(cookie, res.url)))

    return res
  }
  fetchCookie.toughCookie = tough // Export for making you own CookieJars
  return fetchCookie
}

module.exports.toughCookie = tough // Export for making you own CookieJars
<commit_msg>formatting<commit_after>var denodeify = require('es6-denodeify')(Promise)
var tough = require('tough-cookie')

module.exports = function fetchCookieDecorator (fetch, jar) {
  fetch = fetch || window.fetch
  jar = jar || new tough.CookieJar()

  var getCookieString = denodeify(jar.getCookieString.bind(jar))
  var setCookie = denodeify(jar.setCookie.bind(jar))

  async function fetchCookie (url, opts) {
    opts = opts || {}

    // Prepare request
    const cookie = await getCookieString(typeof url === 'string' ? url : url.url)

    if (url.headers && typeof url.headers.append === 'function') {
      url.headers.append('cookie', cookie)
    } else if (opts.headers && typeof opts.headers.append === 'function') {
      opts.headers.append('cookie', cookie)
    } else {
      opts.headers = Object.assign(
        opts.headers || {},
        cookie ? { cookie: cookie } : {}
      )
    }

    // Actual request
    const res = await fetch(url, opts)

    // Get cookie header
    var cookies = []
    if (res.headers.getAll) {
      // node-fetch v1
      cookies = res.headers.getAll('set-cookie')
      // console.warn("You are using a fetch version that supports 'Headers.getAll' which is deprecated!")
      // console.warn("In the future 'fetch-cookie-v2' may discontinue supporting that fetch implementation.")
      // console.warn('Details: https://developer.mozilla.org/en-US/docs/Web/API/Headers/getAll')
    } else {
      // node-fetch v2
      const headers = res.headers.raw()
      if (headers['set-cookie'] !== undefined) {
        cookies = headers['set-cookie']
      }
    }

    // Store all present cookies
    await Promise.all(cookies.map((cookie) => setCookie(cookie, res.url)))

    return res
  }
  fetchCookie.toughCookie = tough // Export for making you own CookieJars
  return fetchCookie
}

module.exports.toughCookie = tough // Export for making you own CookieJars
<|endoftext|>


<commit_before>var request = new XMLHttpRequest();
var widget = document.getElementById('speakerdeck-widget');
var username, pathname = location.pathname.split('/');
if(location.hostname=='http://ezefranca.com/speakerdeck-widget/' && !!pathname[1])
  username = pathname[1];
else if(widget.dataset.username)
  username = widget.dataset.username;

request.overrideMimeType("application/json");
request.open("GET", "https://gist.github.com.ru/ezefranca/0f33a0baec388f665bdfb88a6aa77725?username=" + username);
request.onload = function () {
  if (request.status != 200) return;
  var response = JSON.parse(request.response.replace(/href=\\"\//g, 'href=\\"https://speakerdeck.com/'));
  console.log(response.result);
  if (response['error']) {
    widget.innerHTML = 'Please make sure your name in "username" is a real person on speakerdeck';
    return;
  }
  // If you want a more quality version replace the thumbnail and use the  high qualityimagens
  //  widget.innerHTML = response.result.talks.replace("thumb_slide_0.jpg","slide_1.jpg");
  widget.innerHTML = response.result.talks;
};
request.send();

function appendCSS(name){
  var stylesheet = document.createElement("link")
  stylesheet.setAttribute("rel", "stylesheet")
  stylesheet.setAttribute("href", name)
  document.getElementsByTagName("head")[0].appendChild(stylesheet)
}

appendCSS('//ezefranca.com/speakerdeck-widget/main.css');
appendCSS('//maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css')
<commit_msg>rename variable<commit_after>var request = new XMLHttpRequest();
var widget = document.getElementById('speakerdeck-widget');
var username, pathname = location.pathname.split('/');
if(location.hostname=='http://ezefranca.com/speakerdeck-widget/' && !!pathname[1])
  username = pathname[1];
else if(widget.dataset.sp_username)
  username = widget.dataset.sp_username;

request.overrideMimeType("application/json");
request.open("GET", "https://gist.github.com.ru/ezefranca/0f33a0baec388f665bdfb88a6aa77725?username=" + username);
request.onload = function () {
  if (request.status != 200) return;
  var response = JSON.parse(request.response.replace(/href=\\"\//g, 'href=\\"https://speakerdeck.com/'));
  console.log(response.result);
  if (response['error']) {
    widget.innerHTML = 'Please make sure your name in "username" is a real person on speakerdeck';
    return;
  }
  // If you want a more quality version replace the thumbnail and use the  high qualityimagens
  //  widget.innerHTML = response.result.talks.replace("thumb_slide_0.jpg","slide_1.jpg");
  widget.innerHTML = response.result.talks;
};
request.send();

function appendCSS(name){
  var stylesheet = document.createElement("link")
  stylesheet.setAttribute("rel", "stylesheet")
  stylesheet.setAttribute("href", name)
  document.getElementsByTagName("head")[0].appendChild(stylesheet)
}

appendCSS('//ezefranca.com/speakerdeck-widget/main.css');
appendCSS('//maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css')
<|endoftext|>


<commit_before>var path = require('path');
var util = require('util');

var merge = require('cli-util').merge;
var types = require('./lib/types');
var clierr = require('cli-error');
var conflict = require('./lib/conflict');
var middlewares = require('./lib/middleware');
var cname = require('./lib/util/name');
var logger = require('cli-logger');
var syslog = require('./lib/syslog').log;
var circular = require('circular');
var debug = !!process.env.CLI_TOOLKIT_DEBUG;

var cli = require('cli-define');
var define = cli.define;
var key = cli.key;
var Program = cli.Program;
var Option = cli.Option;
var Command = cli.Command;

var errors = clierr.errors;
var ErrorDefinition = clierr.ErrorDefinition;
var CliError = clierr.CliError;

var __middleware__;

var defaults = {
  load: {
    file: null,
    options: null
  },
  substitute: {
    escaping: true,
    enabled: false
  },
  command: {
    exec: false,
    dir: null
  },
  exit: true,
  stash: null,
  bin: null,
  env: null,
  help: {
    indent: 1,
    exit: false,
    pedantic: true,
    vanilla: false,
    sort: false,
    maximum: 80,
    width: 20,
    align: 'column',
    collapse: false,
    messages: {
      summary: 'Command should be one of: %s',
      usage: {
        command: 'command',
        option: 'option',
        args: 'args'
      },
      bugs: 'Report bugs to %s.'
    }
  },
  trace: undefined,
  unknown: true,
  strict: false,
  middleware: null,
  error: null,
  manual: null
}

var all = [
  middlewares.error,
  middlewares.boot,
  middlewares.load,
  middlewares.substitute,
  middlewares.parser,
  middlewares.unparsed,
  middlewares.defaults,
  middlewares.events,
  middlewares.action,
  middlewares.eunknown,
  middlewares.emultiple,
  middlewares.erequired,
  middlewares.env,
  middlewares.rc,
  middlewares.multiple,
  middlewares.merge,
  middlewares.convert,
  middlewares.exec,
  middlewares.command,
  middlewares.empty,
  middlewares.run];

var CommandProgram = function() {
  Program.apply(this, arguments);
  __middleware__ = [];

  // not that merge maintains object references so defaults
  // would get polluted with this merge, for most programs this
  // is not an issue however it breaks the unit tests so that
  // quick fix is the stringify/parse clone
  // really merge() should be able to create new object and merge them
  // both
  var conf = merge(JSON.parse(JSON.stringify(defaults)), {});
  // private
  define(this, '_middleware', undefined, true);
  define(this, '_conf', conf, true);
  define(this, '_request', undefined, true);

  //
  this._conf.stash = this;

  // public
  define(this, 'errors', errors, false);

  //this.use(middlewares.error);
}

util.inherits(CommandProgram, Program);

/**
 *  Get or set the middleware request object.
 *
 *  @param req The request object.
 */
function request(req) {
  if(!arguments.length) return this._request;
  this._request = req;
  return this;
}
define(CommandProgram.prototype, 'request', request, false);

/**
 *  Wrap an error from an error definition, string
 *  or Error instance.
 *
 *  @param err The error definition, string or Error.
 *  @param parameters The message replacement parameters.
 *  @param source A source error to wrap.
 */
function wrap(err, parameters, source) {
  var msg = 'Cannot wrap invalid error \'' + err + '\'';
  if(!err) {
    throw new TypeError(msg);
  }
  var e, code = err.code || errors.EGENERIC.code;
  if(err instanceof CliError) {
    e = err;
  }else if(err instanceof ErrorDefinition) {
    e = err.toError(source);
    if(!source) e.shift();
    e.parameters = parameters || [];
    e.key = err.key;
  }else if(err instanceof Error) {
    e = new CliError(err, code, parameters);
    e.key = err.key || errors.EGENERIC.key;
  }else if(typeof err === 'string') {
    e = new CliError(source || err, code, parameters);
  }else{
    throw new TypeError(msg);
  }
  return e;
}
define(CommandProgram.prototype, 'wrap', wrap, false);

/**
 *  Raise an error from an error definition or error
 *  instance.
 *
 *  @param err The error definition.
 *  @param parameters The message replacement parameters.
 *  @param source A source error to wrap.
 */
function raise(err, parameters, source) {
  var e = this.wrap(err, parameters, source);
  this.emit('error', e, errors);
}
define(CommandProgram.prototype, 'raise', raise, false);

/**
 *  Define program middleware.
 */
function use(middleware) {
  var i, nm, closure, conf = this.configure();
  var ind = -1, args = [].slice.call(arguments, 1);
  if(middleware === false) {
    __middleware__ = [];
    this._middleware = [];
    return this;
  }
  if(typeof middleware === 'number') {
    ind = middleware;
    middleware = arguments[1];
    args = [].slice.call(arguments, 2);
  }
  if(!arguments.length && this._middleware === undefined) {
    for(i = 0;i < all.length;i++) {
      if(conf && conf.middleware) {
        closure = all[i].call(this);
        if(typeof closure !== 'function') {
          continue;
        }
        nm = cname(closure);
        //console.log('got name %s', nm);
        if(nm && conf.middleware[nm] === false) {
          continue;
        }
      }
      this.use(all[i]);
    }
    return this;
  }
  if(typeof middleware != 'function') {
    throw new Error('Invalid middleware, must be a function');
  }
  closure = middleware.apply(this, args);
  if(~__middleware__.indexOf(middleware)) {
    //console.dir(__middleware__);
    throw new Error('Invalid middleware, duplicate detected');
  }
  if(typeof(closure) == 'function') {
    if(this._middleware === undefined) this._middleware = [];
    if(ind < 0 || ind >= __middleware__.length) {
      this._middleware.push(closure);
    }else{
      this._middleware.splice(ind, 0, closure);
    }
  }else{
    // mark the middleware as in use
    middleware.use = true;
  }

  __middleware__.push(middleware);

  return this;
}
define(CommandProgram.prototype, 'use', use, false);

/**
 *  Default error handler for the error event.
 *
 *  @param e The error instance.
 */
function error(e) {
  var conf = this.configure();
  if(!(e instanceof CliError)) {
    e = this.wrap(e);
  }
  var trace =
    (conf.trace !== undefined)
      ? conf.trace : (e.code === errors.EUNCAUGHT.code);
  //console.log('conf.trace %s', conf.trace);
  //console.log('trace %s', trace);
  //console.log('code %s', e.code);
  var logger = this.log && typeof(this.log.error) === 'function';
  if(logger) {
    var args = e.parameters.slice(0);
    args.unshift(e.message);
    this.log.error.apply(this.log, args);
    if(trace) {
      // NOTE: prefer the stack of a source error
      // TODO: make this configurable
      var stack = e._source && e._source.stack ?
        e._source.stack : e.stack;
      if(stack) {
        this.log.error(stack.split('\n').slice(1).join('\n'));
      }
    }
  }else{
    e.error(trace)
  }
  if(conf.exit) e.exit();
}
define(CommandProgram.prototype, 'error', error, false);

/**
 *  Assigns configuration information to the program.
 *
 *  @param conf The program configuration.
 */
function configure(conf) {
  if(!arguments.length) return this._conf;
  conf = conf || {};
  this._conf = merge(conf, this._conf);
  if(conf.stash) {
    this._conf.stash = conf.stash;
  }

  // load custom error definitions
  if(conf && conf.error && typeof conf.error === 'object') {
    clierr.file(conf.error, function(err) {
      if(err) throw err;
    })
  }
  return this;
}
define(CommandProgram.prototype, 'configure', configure, false);

/**
 *  Adds a version flag to the program.
 *
 *  @param semver A specific version number.
 *  @param name The argument name.
 *  @param description The argument description.
 *  @param action A function to invoke.
 */
function version(semver, name, description, action) {
  if(!arguments.length && this._options.versionopt) return this._version;
  return this.use(middlewares.version, semver, name, description, action);
}
define(CommandProgram.prototype, 'version', version, false);

/**
 *  Adds a help flag to the program.
 *
 *  @param name The argument name.
 *  @param description The argument description.
 *  @param action A function to invoke.
 */
function help(name, description, action) {
  return this.use(middlewares.help, name, description, action);
}
define(CommandProgram.prototype, 'help', help, false);

/**
 *  Parse the supplied arguments and execute any commands
 *  found in the arguments, preferring the built in commands
 *  for help and version.
 *
 *  @param args The arguments to parse, default is process.argv.slice(2).
 */
function parse(args) {
  if(debug) syslog.trace(circular.stringify(this, 2));
  args = args || process.argv.slice(2);
  conflict.call(this);
  if(this._middleware === undefined) {
    this.use();
  }
  middleware.call(this, args);
  return this;
}
define(CommandProgram.prototype, 'parse', parse, false);

/**
 *  Execute middleware.
 *
 *  @param args The arguments passed to parse.
 */
function middleware(args) {
  var i = 0, list = this._middleware, scope = this;
  var req = {argv: args}, name;
  function exec() {
    var func = list[i];
    name = cname(func);
    if(debug) {
      syslog.trace('middleware/start: %s', name);
      syslog.trace(circular.stringify(req, 2));
    }
    //console.dir(func);
    //console.log('' + func);
    func.call(scope, req, next);
    //console.log('' + func);
    //console.log('file %s', scope.file);
  }
  function next(err, parameters, e) {
    if(debug) {
      syslog.trace('middleware/end: %s', name);
    }
    //console.log('next being called ... with %s', err);
    //console.log(new Error().stack);
    if(err === null) {
      // halt processing, complete never fires
      return;
    }else if(err === true) {
      return scope.emit('complete', req);
    }else if(err) {
      req.error = scope.wrap(err, parameters, e);
      scope.raise(err, parameters, e);
    }
    i++;
    if(i < list.length) {
      exec();
    }else{
      scope.emit('complete', req);
    }
  }
  if(list.length) exec();
}

module.exports = function(package, name, description, options) {
  options = options || {};
  var locales = path.join(__dirname, 'lib', 'error', 'locales');
  clierr.file({locales: locales});
  var program = cli(package, name, description, CommandProgram);
  var listeners = process.listeners('uncaughtException');
  if(!listeners.length) {
    process.on('uncaughtException', function(err) {
      err.code = errors.EUNCAUGHT.code;
      program.raise(err);
    })
  }
  if(debug) {
    syslog.level(logger.TRACE);
  }
  if(options.log === false) {
    syslog.level(logger.NONE);
  }
  // TODO: allow setting error configuration on the program configuration
  clierr({name: program.name()});
  return program;
}

module.exports.defaults = defaults;
module.exports.middleware = middlewares;
module.exports.doc = require('./lib/help');
module.exports.help = middlewares.help.action;
module.exports.version = middlewares.version.action;
module.exports.types = types;
module.exports.error = require('./lib/error');
module.exports.CommandProgram = CommandProgram;
module.exports.log = syslog;
<commit_msg>Use env middleware after rc middleware by default.<commit_after>var path = require('path');
var util = require('util');

var merge = require('cli-util').merge;
var types = require('./lib/types');
var clierr = require('cli-error');
var conflict = require('./lib/conflict');
var middlewares = require('./lib/middleware');
var cname = require('./lib/util/name');
var logger = require('cli-logger');
var syslog = require('./lib/syslog').log;
var circular = require('circular');
var debug = !!process.env.CLI_TOOLKIT_DEBUG;

var cli = require('cli-define');
var define = cli.define;
var key = cli.key;
var Program = cli.Program;
var Option = cli.Option;
var Command = cli.Command;

var errors = clierr.errors;
var ErrorDefinition = clierr.ErrorDefinition;
var CliError = clierr.CliError;

var __middleware__;

var defaults = {
  load: {
    file: null,
    options: null
  },
  substitute: {
    escaping: true,
    enabled: false
  },
  command: {
    exec: false,
    dir: null
  },
  exit: true,
  stash: null,
  bin: null,
  env: null,
  help: {
    indent: 1,
    exit: false,
    pedantic: true,
    vanilla: false,
    sort: false,
    maximum: 80,
    width: 20,
    align: 'column',
    collapse: false,
    messages: {
      summary: 'Command should be one of: %s',
      usage: {
        command: 'command',
        option: 'option',
        args: 'args'
      },
      bugs: 'Report bugs to %s.'
    }
  },
  trace: undefined,
  unknown: true,
  strict: false,
  middleware: null,
  error: null,
  manual: null
}

var all = [
  middlewares.error,
  middlewares.boot,
  middlewares.load,
  middlewares.substitute,
  middlewares.parser,
  middlewares.unparsed,
  middlewares.defaults,
  middlewares.events,
  middlewares.action,
  middlewares.eunknown,
  middlewares.emultiple,
  middlewares.erequired,
  middlewares.rc,
  middlewares.env,
  middlewares.multiple,
  middlewares.merge,
  middlewares.convert,
  middlewares.exec,
  middlewares.command,
  middlewares.empty,
  middlewares.run];

var CommandProgram = function() {
  Program.apply(this, arguments);
  __middleware__ = [];

  // not that merge maintains object references so defaults
  // would get polluted with this merge, for most programs this
  // is not an issue however it breaks the unit tests so that
  // quick fix is the stringify/parse clone
  // really merge() should be able to create new object and merge them
  // both
  var conf = merge(JSON.parse(JSON.stringify(defaults)), {});
  // private
  define(this, '_middleware', undefined, true);
  define(this, '_conf', conf, true);
  define(this, '_request', undefined, true);

  //
  this._conf.stash = this;

  // public
  define(this, 'errors', errors, false);

  //this.use(middlewares.error);
}

util.inherits(CommandProgram, Program);

/**
 *  Get or set the middleware request object.
 *
 *  @param req The request object.
 */
function request(req) {
  if(!arguments.length) return this._request;
  this._request = req;
  return this;
}
define(CommandProgram.prototype, 'request', request, false);

/**
 *  Wrap an error from an error definition, string
 *  or Error instance.
 *
 *  @param err The error definition, string or Error.
 *  @param parameters The message replacement parameters.
 *  @param source A source error to wrap.
 */
function wrap(err, parameters, source) {
  var msg = 'Cannot wrap invalid error \'' + err + '\'';
  if(!err) {
    throw new TypeError(msg);
  }
  var e, code = err.code || errors.EGENERIC.code;
  if(err instanceof CliError) {
    e = err;
  }else if(err instanceof ErrorDefinition) {
    e = err.toError(source);
    if(!source) e.shift();
    e.parameters = parameters || [];
    e.key = err.key;
  }else if(err instanceof Error) {
    e = new CliError(err, code, parameters);
    e.key = err.key || errors.EGENERIC.key;
  }else if(typeof err === 'string') {
    e = new CliError(source || err, code, parameters);
  }else{
    throw new TypeError(msg);
  }
  return e;
}
define(CommandProgram.prototype, 'wrap', wrap, false);

/**
 *  Raise an error from an error definition or error
 *  instance.
 *
 *  @param err The error definition.
 *  @param parameters The message replacement parameters.
 *  @param source A source error to wrap.
 */
function raise(err, parameters, source) {
  var e = this.wrap(err, parameters, source);
  this.emit('error', e, errors);
}
define(CommandProgram.prototype, 'raise', raise, false);

/**
 *  Define program middleware.
 */
function use(middleware) {
  var i, nm, closure, conf = this.configure();
  var ind = -1, args = [].slice.call(arguments, 1);
  if(middleware === false) {
    __middleware__ = [];
    this._middleware = [];
    return this;
  }
  if(typeof middleware === 'number') {
    ind = middleware;
    middleware = arguments[1];
    args = [].slice.call(arguments, 2);
  }
  if(!arguments.length && this._middleware === undefined) {
    for(i = 0;i < all.length;i++) {
      if(conf && conf.middleware) {
        closure = all[i].call(this);
        if(typeof closure !== 'function') {
          continue;
        }
        nm = cname(closure);
        //console.log('got name %s', nm);
        if(nm && conf.middleware[nm] === false) {
          continue;
        }
      }
      this.use(all[i]);
    }
    return this;
  }
  if(typeof middleware != 'function') {
    throw new Error('Invalid middleware, must be a function');
  }
  closure = middleware.apply(this, args);
  if(~__middleware__.indexOf(middleware)) {
    //console.dir(__middleware__);
    throw new Error('Invalid middleware, duplicate detected');
  }
  if(typeof(closure) == 'function') {
    if(this._middleware === undefined) this._middleware = [];
    if(ind < 0 || ind >= __middleware__.length) {
      this._middleware.push(closure);
    }else{
      this._middleware.splice(ind, 0, closure);
    }
  }else{
    // mark the middleware as in use
    middleware.use = true;
  }

  __middleware__.push(middleware);

  return this;
}
define(CommandProgram.prototype, 'use', use, false);

/**
 *  Default error handler for the error event.
 *
 *  @param e The error instance.
 */
function error(e) {
  var conf = this.configure();
  if(!(e instanceof CliError)) {
    e = this.wrap(e);
  }
  var trace =
    (conf.trace !== undefined)
      ? conf.trace : (e.code === errors.EUNCAUGHT.code);
  //console.log('conf.trace %s', conf.trace);
  //console.log('trace %s', trace);
  //console.log('code %s', e.code);
  var logger = this.log && typeof(this.log.error) === 'function';
  if(logger) {
    var args = e.parameters.slice(0);
    args.unshift(e.message);
    this.log.error.apply(this.log, args);
    if(trace) {
      // NOTE: prefer the stack of a source error
      // TODO: make this configurable
      var stack = e._source && e._source.stack ?
        e._source.stack : e.stack;
      if(stack) {
        this.log.error(stack.split('\n').slice(1).join('\n'));
      }
    }
  }else{
    e.error(trace)
  }
  if(conf.exit) e.exit();
}
define(CommandProgram.prototype, 'error', error, false);

/**
 *  Assigns configuration information to the program.
 *
 *  @param conf The program configuration.
 */
function configure(conf) {
  if(!arguments.length) return this._conf;
  conf = conf || {};
  this._conf = merge(conf, this._conf);
  if(conf.stash) {
    this._conf.stash = conf.stash;
  }

  // load custom error definitions
  if(conf && conf.error && typeof conf.error === 'object') {
    clierr.file(conf.error, function(err) {
      if(err) throw err;
    })
  }
  return this;
}
define(CommandProgram.prototype, 'configure', configure, false);

/**
 *  Adds a version flag to the program.
 *
 *  @param semver A specific version number.
 *  @param name The argument name.
 *  @param description The argument description.
 *  @param action A function to invoke.
 */
function version(semver, name, description, action) {
  if(!arguments.length && this._options.versionopt) return this._version;
  return this.use(middlewares.version, semver, name, description, action);
}
define(CommandProgram.prototype, 'version', version, false);

/**
 *  Adds a help flag to the program.
 *
 *  @param name The argument name.
 *  @param description The argument description.
 *  @param action A function to invoke.
 */
function help(name, description, action) {
  return this.use(middlewares.help, name, description, action);
}
define(CommandProgram.prototype, 'help', help, false);

/**
 *  Parse the supplied arguments and execute any commands
 *  found in the arguments, preferring the built in commands
 *  for help and version.
 *
 *  @param args The arguments to parse, default is process.argv.slice(2).
 */
function parse(args) {
  if(debug) syslog.trace(circular.stringify(this, 2));
  args = args || process.argv.slice(2);
  conflict.call(this);
  if(this._middleware === undefined) {
    this.use();
  }
  middleware.call(this, args);
  return this;
}
define(CommandProgram.prototype, 'parse', parse, false);

/**
 *  Execute middleware.
 *
 *  @param args The arguments passed to parse.
 */
function middleware(args) {
  var i = 0, list = this._middleware, scope = this;
  var req = {argv: args}, name;
  function exec() {
    var func = list[i];
    name = cname(func);
    if(debug) {
      syslog.trace('middleware/start: %s', name);
      syslog.trace(circular.stringify(req, 2));
    }
    //console.dir(func);
    //console.log('' + func);
    func.call(scope, req, next);
    //console.log('' + func);
    //console.log('file %s', scope.file);
  }
  function next(err, parameters, e) {
    if(debug) {
      syslog.trace('middleware/end: %s', name);
    }
    //console.log('next being called ... with %s', err);
    //console.log(new Error().stack);
    if(err === null) {
      // halt processing, complete never fires
      return;
    }else if(err === true) {
      return scope.emit('complete', req);
    }else if(err) {
      req.error = scope.wrap(err, parameters, e);
      scope.raise(err, parameters, e);
    }
    i++;
    if(i < list.length) {
      exec();
    }else{
      scope.emit('complete', req);
    }
  }
  if(list.length) exec();
}

module.exports = function(package, name, description, options) {
  options = options || {};
  var locales = path.join(__dirname, 'lib', 'error', 'locales');
  clierr.file({locales: locales});
  var program = cli(package, name, description, CommandProgram);
  var listeners = process.listeners('uncaughtException');
  if(!listeners.length) {
    process.on('uncaughtException', function(err) {
      err.code = errors.EUNCAUGHT.code;
      program.raise(err);
    })
  }
  if(debug) {
    syslog.level(logger.TRACE);
  }
  if(options.log === false) {
    syslog.level(logger.NONE);
  }
  // TODO: allow setting error configuration on the program configuration
  clierr({name: program.name()});
  return program;
}

module.exports.defaults = defaults;
module.exports.middleware = middlewares;
module.exports.doc = require('./lib/help');
module.exports.help = middlewares.help.action;
module.exports.version = middlewares.version.action;
module.exports.types = types;
module.exports.error = require('./lib/error');
module.exports.CommandProgram = CommandProgram;
module.exports.log = syslog;
<|endoftext|>


<commit_before>var reader = require('./lib/reader'),
    initializer = require('./lib/initializer'),
    formatter = require('./lib/formatter'),
    absorb = require('absorb'),
    widget = require('./lib/widget'),
    server = require('./lib/http-server'),
    colors = require('colors'),
    shell = require('shelljs'),
    path = require('./lib/path'),
    yaml = require('js-yaml'),
    Hexo = require('hexo'),
    glob = require('glob'),
    json = require('jsonfile'),
    fs = require('fs');

var fromModule = function(targetPath) {
    return __dirname + '/' + path.trimLeft(targetPath);
};

var fromProcess = function(targetPath) {
    return process.cwd() + '/' + path.trimRight(path.trimLeft(targetPath));
};

var conf, defaultConf;
var packageJSON = json.readFileSync(fromModule('package.json'));
var hexoConfig, mergedConfig;
var widgetFiles;

var checkPath = function(path, configVarName, canSkip) {
    var skip = canSkip || false;
    if (shell.test('-e', path)) {
        return true;
    } else {
        if (skip) {
            return false;
        }
        var varName = configVarName || false;
        if (varName) {
            console.error(' ERROR: '.red + ' the file ' + (path).red + ' in ' + (varName).yellow + ' property from your ' + 'a-pollo.yml'.yellow + ' config not found.');
        } else {
            console.error(' ERROR: '.red + ' file ' + (path).red + ' in your ' + 'a-pollo.yml'.yellow + ' config not found.');
        }
        return false;
    }
};

var checkPageFile = function(filter, defaultFileName) {
    var filesToFind, filesFound, defaultFile, pages, destinationFile;

    pages = path.trimRight(process.cwd() + '/' + path.trimLeft(conf.pages));
    filesToFind = pages + filter;
    filesFound = glob.sync(filesToFind);
    defaultFile = fromModule('/hexo/_default_source/' + defaultFileName);
    destinationFile = pages + '/' + defaultFileName;

    if (filesFound.length === 0) {
        if (!shell.test('-e', destinationFile)) {
            console.log('Default index file not found, ' + 'a-pollo'.yellow + ' will create it for you');
            shell.cp('-f', defaultFile, destinationFile);
        }
    }
};

var hexoModule = function() {
    if (!shell.test('-e', fromModule('/hexo/node_modules'))) {
        console.log('Preparing modules...');
        fs.symlinkSync(fromModule('node_modules'), fromModule('/hexo/node_modules'));
        console.log('Done.');
    }
};

var addThemeImage = function(imageName) {
    var defaultLogoSource, defaultLogoTarget, defaultLogoTargetPath;
    defaultLogoTarget = fromModule('/hexo/source/css/theme/assets/' + imageName);
    defaultLogoTargetPath = path.trimRight(fromModule('/hexo/source/css/theme/assets/'));
    if (!shell.test('-e', defaultLogoTarget)) {
        defaultLogoSource = fromModule('/frontsize/themes/a-pollo/img/' + imageName);
        shell.cp('-f', defaultLogoSource, defaultLogoTargetPath);
    }
};

var prepareFiles = function() {

    if (shell.test('-e', fromProcess(conf.public_dir))) {
        shell.rm('-Rf', fromProcess(conf.public_dir));
    }

    shell.mkdir('-p', fromModule('/hexo/source'));
    shell.mkdir('-p', fromModule('/hexo/source/_posts'));
    shell.mkdir('-p', fromModule('/source'));

    if (conf.pages !== undefined || conf.pages) {
        if (checkPath(fromProcess(conf.pages), 'pages')) {
            //checkPageFile('index.{md,html}', 'index.md');
            shell.cp('-R', path.inside(fromProcess(conf.pages)), fromModule('/hexo/source'));
        }
    } else {
        shell.cp('-R', fromModule('/hexo/_default_source/*'), fromModule('/hexo/source'));
    }

    shell.mkdir('-p', fromModule('/hexo/source/css/theme'));
    shell.mkdir('-p', fromModule('/hexo/source/css/theme/img'));
    shell.mkdir('-p', fromModule('/hexo/source/css/theme/fonts'));

    console.log('Copying CSS theme images and fonts');

    if (checkPath(fromProcess(conf.style.images), 'style.images')) {
        shell.cp('-R', path.inside(fromProcess(conf.style.images)), fromModule('/hexo/source/css/theme/assets'));
        addThemeImage('apollo-logo__icon.svg');
        addThemeImage('apollo-logo__icon-grey.svg');
        addThemeImage('apollo-logo__icon-black.svg');
    }
    if (checkPath(fromProcess(conf.style.fonts), 'style.fonts')) {
        shell.cp('-R', path.inside(fromProcess(conf.style.fonts)), fromModule('/hexo/source/css/theme/assets'));
    }
};

var checkTheme = function() {
    var defaultTheme = 'a-pollo';
    if (conf.theme !== undefined) {
        if (!shell.test('-e', fromModule('/hexo/themes/' + conf.theme))) {
            console.log('Theme ' + (' ' + conf.theme + ' ').yellow.bgBlack + ' not installed, searching on project folder');
            if (!shell.test('-e', fromProcess(conf.theme))) {
                console.log('Theme ' + (' ' + conf.theme + ' ').yellow.bgBlack + ' not found, it will be used ' + (' ' + defaultTheme + ' ').yellow.bgBlack + ' as default theme');
                conf.theme = defaultTheme;
            } else {
                console.log('Installing found theme ' + (' ' + conf.theme + ' ').yellow.bgBlack);
                shell.cp('-R', path.inside(fromProcess(conf.theme)), fromModule('/hexo/themes/' + conf.theme));
            }
        } else {
            console.log('Using selected theme ' + (' ' + conf.theme + ' ').yellow.bgBlack);
        }
    } else {
        console.log('Theme not set, it will be used ' + (' ' + defaultTheme + ' ').yellow.bgBlack + ' as default theme');
        conf.theme = defaultTheme;
    }
};

var generateDocs = function () {
    shell.mv('-f', fromProcess('/source/_posts'), fromModule('/hexo/source'));
    shell.exec('cd ' + fromModule('/hexo') + ' && ../node_modules/.bin/hexo generate');
    shell.mv('-f', fromModule('/hexo/' + path.trimLeft(conf.public_dir)), fromProcess(conf.public_dir));
};

var removeFiles = function() {
    if (shell.test('-e', fromModule('/hexo/source'))) { shell.rm('-Rf', fromModule('/hexo/source')); }
    if (shell.test('-e', fromModule('/source'))) { shell.rm('-Rf', fromModule('/source')); }
    if (shell.test('-e', fromModule('/hexo/_config.yml'))) { shell.rm('-f', fromModule('/hexo/_config.yml')); }
};

var prepareHTTP = function() {

    setTimeout(function(){
        removeFiles();
    }, 500);

    console.log('Build finished successfully.'.green);

    if (conf.http_server !== undefined && conf.http_server !== false) {
        server.start(conf.public_dir, conf.url);
    } else {
        console.log('The style guide was generated here: ' + conf.public_dir.toString().yellow);
    }
};

var postCreated = function(widgetFilesLength) {
    var posts = glob.sync(fromProcess('/source/_posts/**/*.md'));
    if (posts.length === widgetFilesLength) {
        generateDocs();
        setTimeout(function(){
            prepareHTTP();
        }, 1000);
    } else {
        setTimeout(function(){
            postCreated(widgetFilesLength);
        }, 500);
    }
};

var copyThemeAssets = function() {
    var cssFileData;
    if (checkPath(fromProcess(conf.style.css), 'style.css')) {
        console.log('Copying style CSS to display');
        cssFileData = fs.readFileSync(fromProcess(conf.style.css), 'utf8');
        cssFileData = cssFileData.replace(/url\(('|"){1,}(.*\/)(.*)('|"){1,}\)/g, 'url($1/css/theme/assets/$3$4)');
        fs.writeFileSync(fromModule('/hexo/source/css/theme/theme.css'), cssFileData);
    } else {
        return false;
    }
};

var runBuild = function() {
    var hexo;
    checkTheme();
    hexoModule();
    prepareFiles();

    copyThemeAssets();

    console.log('Initializing ' + 'Hexo'.blue);

    if (checkPath(fromModule('/hexo/_config.yml'))) {
        console.log('Loading ' + 'Hexo'.blue + ' configuration');
    }

    hexo = new Hexo(process.cwd(), {
        debug: false,
        config: fromModule('/hexo/_config.yml')
    });

    hexo.init().then(function(){
        var postData;
        console.log('Crunching ' + 'a-pollo'.yellow + ' doc annotations to ' + 'Hexo'.blue + ' posts...');
        for (var i = 0; i < widgetFiles.length; i += 1) {
            console.log('Creating post for ' + (' ' + widgetFiles[i][0].file + ' ').yellow.bgBlack);
            postData = formatter.toHexo(widgetFiles[i]);
            postData.content = widget.toMarkdown(widgetFiles[i], conf);
            // console.log(postData.docs[0].htmlSnippet)
            hexo.post.create(postData, true);
        }
        console.log('Waiting for ' + 'Hexo'.blue + ' to finish...');
        postCreated(widgetFiles.length);
    });
};

var runProcess = function() {

    console.log('Starting ' + 'a-pollo '.rainbow + packageJSON.version);

    removeFiles();

    var initializerStarted = false;

    process.argv.forEach(function(val) {
        if (val === 'init') {
            initializer.start();
            return;
        }
    });

    if (initializerStarted) {
        return;
    }

    var filename = process.cwd() + '/a-pollo.yml';
    process.argv.forEach(function(val) {
        if (val.indexOf('config=') === 0) {
            filename = process.cwd() + val.replace('config=', '/');
        }
    });

    if (shell.test('-e', filename)) {
        var confToMerge = yaml.safeLoad(fs.readFileSync(filename, 'utf-8'));
        confToMerge.apollo = {
            version: packageJSON.version,
            homepage: packageJSON.homepage
        };
        defaultConf = yaml.safeLoad(fs.readFileSync(fromModule('/a-pollo.yml'), 'utf-8'));

        delete defaultConf.pages;
        delete defaultConf.libs;

        conf = absorb(confToMerge, defaultConf, false, true);
        hexoConfig   = yaml.safeLoad(fs.readFileSync(fromModule('/hexo/_default_config.yml'), 'utf-8'));

        if (conf.libs !== undefined) {
            if (conf.libs.node !== undefined) {
                if (checkPath(fromProcess(conf.libs.node), 'libs.node')) {
                    conf.libs.nodeDependencies = yaml.safeLoad(fs.readFileSync(fromProcess(conf.libs.node))).dependencies;
                }
            }
            if (conf.libs.bower !== undefined) {
                if (checkPath(fromProcess(conf.libs.bower), 'libs.bower')) {
                    conf.libs.bowerDependencies = yaml.safeLoad(fs.readFileSync(fromProcess(conf.libs.bower))).dependencies;
                }
            }
        }

        console.log('Loading doc annotations data from ' + (' ' + conf.style.docs + ' ').yellow.bgBlack + ' folder');
        widgetFiles = reader.load(fromProcess(conf.style.docs));

        conf = formatter.setProjectStats(conf, widgetFiles);
        mergedConfig = absorb(conf, hexoConfig, false, true);

        fs.writeFileSync(fromModule('/hexo/_config.yml'), yaml.safeDump(mergedConfig));

        runBuild();
    } else {
        var isInitProcess = false;
        process.argv.forEach(function(val) {
            if (val.indexOf('init') === 0) {
                isInitProcess = true;
            }
        });
        if (!isInitProcess) {
            console.log('ERROR: '.red + 'file ' + filename.toString().red + ' not found, please run ' + 'a-pollo init'.yellow + ' or ' + './node_modules/.bin/a-pollo init'.yellow + ' to create one.');
        }
    }
};

runProcess();
<commit_msg>Fix some css wrong path<commit_after>var reader = require('./lib/reader'),
    initializer = require('./lib/initializer'),
    formatter = require('./lib/formatter'),
    absorb = require('absorb'),
    widget = require('./lib/widget'),
    server = require('./lib/http-server'),
    colors = require('colors'),
    shell = require('shelljs'),
    path = require('./lib/path'),
    yaml = require('js-yaml'),
    Hexo = require('hexo'),
    glob = require('glob'),
    json = require('jsonfile'),
    fs = require('fs');

var fromModule = function(targetPath) {
    return __dirname + '/' + path.trimLeft(targetPath);
};

var fromProcess = function(targetPath) {
    return process.cwd() + '/' + path.trimRight(path.trimLeft(targetPath));
};

var conf, defaultConf;
var packageJSON = json.readFileSync(fromModule('package.json'));
var hexoConfig, mergedConfig;
var widgetFiles;

var checkPath = function(path, configVarName, canSkip) {
    var skip = canSkip || false;
    if (shell.test('-e', path)) {
        return true;
    } else {
        if (skip) {
            return false;
        }
        var varName = configVarName || false;
        if (varName) {
            console.error(' ERROR: '.red + ' the file ' + (path).red + ' in ' + (varName).yellow + ' property from your ' + 'a-pollo.yml'.yellow + ' config not found.');
        } else {
            console.error(' ERROR: '.red + ' file ' + (path).red + ' in your ' + 'a-pollo.yml'.yellow + ' config not found.');
        }
        return false;
    }
};

var checkPageFile = function(filter, defaultFileName) {
    var filesToFind, filesFound, defaultFile, pages, destinationFile;

    pages = path.trimRight(process.cwd() + '/' + path.trimLeft(conf.pages));
    filesToFind = pages + filter;
    filesFound = glob.sync(filesToFind);
    defaultFile = fromModule('/hexo/_default_source/' + defaultFileName);
    destinationFile = pages + '/' + defaultFileName;

    if (filesFound.length === 0) {
        if (!shell.test('-e', destinationFile)) {
            console.log('Default index file not found, ' + 'a-pollo'.yellow + ' will create it for you');
            shell.cp('-f', defaultFile, destinationFile);
        }
    }
};

var hexoModule = function() {
    if (!shell.test('-e', fromModule('/hexo/node_modules'))) {
        console.log('Preparing modules...');
        fs.symlinkSync(fromModule('node_modules'), fromModule('/hexo/node_modules'));
        console.log('Done.');
    }
};

var addThemeImage = function(imageName) {
    var defaultLogoSource, defaultLogoTarget, defaultLogoTargetPath;
    defaultLogoTarget = fromModule('/hexo/source/css/theme/assets/' + imageName);
    defaultLogoTargetPath = path.trimRight(fromModule('/hexo/source/css/theme/assets/'));
    if (!shell.test('-e', defaultLogoTarget)) {
        defaultLogoSource = fromModule('/frontsize/themes/a-pollo/img/' + imageName);
        shell.cp('-f', defaultLogoSource, defaultLogoTargetPath);
    }
};

var prepareFiles = function() {

    if (shell.test('-e', fromProcess(conf.public_dir))) {
        shell.rm('-Rf', fromProcess(conf.public_dir));
    }

    shell.mkdir('-p', fromModule('/hexo/source'));
    shell.mkdir('-p', fromModule('/hexo/source/_posts'));
    shell.mkdir('-p', fromModule('/source'));

    if (conf.pages !== undefined || conf.pages) {
        if (checkPath(fromProcess(conf.pages), 'pages')) {
            //checkPageFile('index.{md,html}', 'index.md');
            shell.cp('-R', path.inside(fromProcess(conf.pages)), fromModule('/hexo/source'));
        }
    } else {
        shell.cp('-R', fromModule('/hexo/_default_source/*'), fromModule('/hexo/source'));
    }

    shell.mkdir('-p', fromModule('/hexo/source/css/theme'));
    shell.mkdir('-p', fromModule('/hexo/source/css/theme/img'));
    shell.mkdir('-p', fromModule('/hexo/source/css/theme/fonts'));

    console.log('Copying CSS theme images and fonts');

    if (checkPath(fromProcess(conf.style.images), 'style.images')) {
        shell.cp('-R', path.inside(fromProcess(conf.style.images)), fromModule('/hexo/source/css/theme/assets'));
        addThemeImage('apollo-logo__icon.svg');
        addThemeImage('apollo-logo__icon-grey.svg');
        addThemeImage('apollo-logo__icon-black.svg');
    }
    if (checkPath(fromProcess(conf.style.fonts), 'style.fonts')) {
        shell.cp('-R', path.inside(fromProcess(conf.style.fonts)), fromModule('/hexo/source/css/theme/assets'));
    }
};

var checkTheme = function() {
    var defaultTheme = 'a-pollo';
    if (conf.theme !== undefined) {
        if (!shell.test('-e', fromModule('/hexo/themes/' + conf.theme))) {
            console.log('Theme ' + (' ' + conf.theme + ' ').yellow.bgBlack + ' not installed, searching on project folder');
            if (!shell.test('-e', fromProcess(conf.theme))) {
                console.log('Theme ' + (' ' + conf.theme + ' ').yellow.bgBlack + ' not found, it will be used ' + (' ' + defaultTheme + ' ').yellow.bgBlack + ' as default theme');
                conf.theme = defaultTheme;
            } else {
                console.log('Installing found theme ' + (' ' + conf.theme + ' ').yellow.bgBlack);
                shell.cp('-R', path.inside(fromProcess(conf.theme)), fromModule('/hexo/themes/' + conf.theme));
            }
        } else {
            console.log('Using selected theme ' + (' ' + conf.theme + ' ').yellow.bgBlack);
        }
    } else {
        console.log('Theme not set, it will be used ' + (' ' + defaultTheme + ' ').yellow.bgBlack + ' as default theme');
        conf.theme = defaultTheme;
    }
};

var generateDocs = function () {
    shell.mv('-f', fromProcess('/source/_posts'), fromModule('/hexo/source'));
    shell.exec('cd ' + fromModule('/hexo') + ' && ../node_modules/.bin/hexo generate');
    shell.mv('-f', fromModule('/hexo/' + path.trimLeft(conf.public_dir)), fromProcess(conf.public_dir));
};

var removeFiles = function() {
    if (shell.test('-e', fromModule('/hexo/source'))) { shell.rm('-Rf', fromModule('/hexo/source')); }
    if (shell.test('-e', fromModule('/source'))) { shell.rm('-Rf', fromModule('/source')); }
    if (shell.test('-e', fromModule('/hexo/_config.yml'))) { shell.rm('-f', fromModule('/hexo/_config.yml')); }
};

var prepareHTTP = function() {

    setTimeout(function(){
        removeFiles();
    }, 500);

    console.log('Build finished successfully.'.green);

    if (conf.http_server !== undefined && conf.http_server !== false) {
        server.start(conf.public_dir, conf.url);
    } else {
        console.log('The style guide was generated here: ' + conf.public_dir.toString().yellow);
    }
};

var postCreated = function(widgetFilesLength) {
    var posts = glob.sync(fromProcess('/source/_posts/**/*.md'));
    if (posts.length === widgetFilesLength) {
        generateDocs();
        setTimeout(function(){
            prepareHTTP();
        }, 1000);
    } else {
        setTimeout(function(){
            postCreated(widgetFilesLength);
        }, 500);
    }
};

var copyThemeAssets = function() {
    var cssFileData, url;
    if (checkPath(fromProcess(conf.style.css), 'style.css')) {
        console.log('Copying style CSS to display');
        url = path.trimRight(conf.url);
        cssFileData = fs.readFileSync(fromProcess(conf.style.css), 'utf8');
        cssFileData = cssFileData.replace(/url\(('|"){1,}(.*\/)(.*)('|"){1,}\)/g, 'url($1' + url + '/css/theme/assets/$3$4)');
        fs.writeFileSync(fromModule('/hexo/source/css/theme/theme.css'), cssFileData);
    } else {
        return false;
    }
};

var runBuild = function() {
    var hexo;
    checkTheme();
    hexoModule();
    prepareFiles();

    copyThemeAssets();

    console.log('Initializing ' + 'Hexo'.blue);

    if (checkPath(fromModule('/hexo/_config.yml'))) {
        console.log('Loading ' + 'Hexo'.blue + ' configuration');
    }

    hexo = new Hexo(process.cwd(), {
        debug: false,
        config: fromModule('/hexo/_config.yml')
    });

    hexo.init().then(function(){
        var postData;
        console.log('Crunching ' + 'a-pollo'.yellow + ' doc annotations to ' + 'Hexo'.blue + ' posts...');
        for (var i = 0; i < widgetFiles.length; i += 1) {
            console.log('Creating post for ' + (' ' + widgetFiles[i][0].file + ' ').yellow.bgBlack);
            postData = formatter.toHexo(widgetFiles[i]);
            postData.content = widget.toMarkdown(widgetFiles[i], conf);
            // console.log(postData.docs[0].htmlSnippet)
            hexo.post.create(postData, true);
        }
        console.log('Waiting for ' + 'Hexo'.blue + ' to finish...');
        postCreated(widgetFiles.length);
    });
};

var runProcess = function() {

    console.log('Starting ' + 'a-pollo '.rainbow + packageJSON.version);

    removeFiles();

    var initializerStarted = false;

    process.argv.forEach(function(val) {
        if (val === 'init') {
            initializer.start();
            return;
        }
    });

    if (initializerStarted) {
        return;
    }

    var filename = process.cwd() + '/a-pollo.yml';
    process.argv.forEach(function(val) {
        if (val.indexOf('config=') === 0) {
            filename = process.cwd() + val.replace('config=', '/');
        }
    });

    if (shell.test('-e', filename)) {
        var confToMerge = yaml.safeLoad(fs.readFileSync(filename, 'utf-8'));
        confToMerge.apollo = {
            version: packageJSON.version,
            homepage: packageJSON.homepage
        };
        defaultConf = yaml.safeLoad(fs.readFileSync(fromModule('/a-pollo.yml'), 'utf-8'));

        delete defaultConf.pages;
        delete defaultConf.libs;

        conf = absorb(confToMerge, defaultConf, false, true);
        hexoConfig   = yaml.safeLoad(fs.readFileSync(fromModule('/hexo/_default_config.yml'), 'utf-8'));

        if (conf.libs !== undefined) {
            if (conf.libs.node !== undefined) {
                if (checkPath(fromProcess(conf.libs.node), 'libs.node')) {
                    conf.libs.nodeDependencies = yaml.safeLoad(fs.readFileSync(fromProcess(conf.libs.node))).dependencies;
                }
            }
            if (conf.libs.bower !== undefined) {
                if (checkPath(fromProcess(conf.libs.bower), 'libs.bower')) {
                    conf.libs.bowerDependencies = yaml.safeLoad(fs.readFileSync(fromProcess(conf.libs.bower))).dependencies;
                }
            }
        }

        console.log('Loading doc annotations data from ' + (' ' + conf.style.docs + ' ').yellow.bgBlack + ' folder');
        widgetFiles = reader.load(fromProcess(conf.style.docs));

        conf = formatter.setProjectStats(conf, widgetFiles);
        mergedConfig = absorb(conf, hexoConfig, false, true);

        fs.writeFileSync(fromModule('/hexo/_config.yml'), yaml.safeDump(mergedConfig));

        runBuild();
    } else {
        var isInitProcess = false;
        process.argv.forEach(function(val) {
            if (val.indexOf('init') === 0) {
                isInitProcess = true;
            }
        });
        if (!isInitProcess) {
            console.log('ERROR: '.red + 'file ' + filename.toString().red + ' not found, please run ' + 'a-pollo init'.yellow + ' or ' + './node_modules/.bin/a-pollo init'.yellow + ' to create one.');
        }
    }
};

runProcess();
<|endoftext|>


<commit_before>/* jshint node: true */
'use strict';

module.exports = {
  name: 'ember-plaid',

  contentFor: function(type) {
    if (type === 'body') {
      return '<script src="https://cdn.plaid.com/link/stable/link-initialize.js"></script>';
    }
  },
};
<commit_msg>upgrade to plaid v2 library<commit_after>/* jshint node: true */
'use strict';

module.exports = {
  name: 'ember-plaid',

  contentFor: function(type) {
    if (type === 'body') {
      return '<script src="https://cdn.plaid.com/link/v2/stable/link-initialize.js"></script>';
    }
  },
};
<|endoftext|>


<commit_before>'use strict'

const chalk =   require('chalk')
const figures = require('figures')
const output =  require('log-update')
const escapes = require('ansi-escapes')

const styles = {
	default:   (input) => input,
	password:  (input) => '*'.repeat(input.length),
	invisible: (input) => ''
}

const symbols = {
	aborted: chalk.red(figures.cross),
	done:    chalk.green(figures.tick),
	default: chalk.cyan('?')
}

const defaults = {
	symbol:    (ctx) => ctx.aborted ? symbols.aborted : (ctx.done ? symbols.done : symbols.default),
	text:      '',
	delimiter: chalk.gray('>'),
	replace:   styles.default,
	suggest:   (input) => []
}

const render = function (ctx) {
	// todo: `output` appends a line break :/
	output(escapes.eraseLine + (!ctx.done ? escapes.cursorShow : '') + [
		ctx._.symbol(ctx),
		ctx._.text,
		ctx._.delimiter,
		ctx._.replace(ctx.input)
	].join(' '))
}

const onKey = (ctx) => function (input, enc) {
	input = input.toString(enc)
	let code = input.charCodeAt(0); // see https://en.wikipedia.org/wiki/GNU_Readline#Keyboard_shortcuts
	// if (code === 1)    return first(); // ctrl + A
	if (code === 3)    return abort(ctx) // ctrl + C
	if (code === 13)   return submit(ctx) // return key
	if (code === 127)  return remove(ctx) // backspace
	// if (code === 4)    return process.exit(); // ctrl + D
	// if (code === 5)    return last(); // ctrl + E
	// if (code === 7)    return reset(); // ctrl + G
	// if (code === 9)    return right(); // ctrl + I / tab
	// if (code === 10)   return submit(); // ctrl + J
	// if (code === 27)   return abort(); // escape
	// if (code === 8747) return left(); // alt + B
	// if (code === 402)  return right(); // alt + F
	onInput(ctx, input)
}

const onInput = function (ctx, input) {
	ctx.input += input
	ctx.suggestions = ctx._.suggest(ctx.input)
	render(ctx)
}

const abort = function (ctx) {
	process.stdin.destroy()
	ctx.aborted = ctx.done = true
	render(ctx)

	output.done()
	process.stdout.write(escapes.cursorHide)
	ctx.reject(null)
}

const submit = function (ctx) {
	process.stdin.destroy()
	ctx.done = true
	render(ctx)

	output.done()
	process.stdout.write(escapes.cursorHide)
	ctx.resolve(ctx.input)
}

const remove = function (ctx) {
	if (ctx.input.length === 0) output(escapes.beep)
	ctx.input = ctx.input.slice(0, -1)
	ctx.suggestions = ctx._.suggest(ctx.input)
	render(ctx)
}

const prompt = function (text, opt) {
	if ('string' !== typeof text) throw new Error('text must be a string.')
	if (arguments.length < 2 || 'object' !== typeof opt) opt = {}
	opt = Object.assign({}, defaults, opt, {text})
	let ctx = {
		_:           opt,
		done:        false,
		aborted:     false,
		input:       '',
		suggestions: []
	}

	process.stdin.setRawMode(true)
	process.stdin.on('data', onKey(ctx))
	// todo: on 'end'
	onInput(ctx, ctx.input)
	render(ctx)

	return new Promise(function (resolve, reject) {
		ctx.resolve = resolve
		ctx.reject =  reject
	})
}

module.exports = Object.assign(prompt, {styles, symbols, defaults})
<commit_msg>better cursor handling<commit_after>'use strict'

const chalk =     require('chalk')
const figures =   require('figures')
const escapes =   require('ansi-escapes')
const stripAnsi = require('strip-ansi')

const styles = {
	default:   (input) => input,
	password:  (input) => '*'.repeat(input.length),
	invisible: (input) => ''
}

const symbols = {
	aborted: chalk.red(figures.cross),
	done:    chalk.green(figures.tick),
	default: chalk.cyan('?')
}

const defaults = {
	symbol:    (ctx) => ctx.aborted ? symbols.aborted : (ctx.done ? symbols.done : symbols.default),
	text:      '',
	delimiter: chalk.gray('>'),
	replace:   styles.default,
	suggest:   (input) => []
}

const renderPrompt = (ctx) =>
	escapes.eraseLine
	+ (!ctx.done ? escapes.cursorShow : '')
	+ [
		ctx._.symbol(ctx),
		ctx._.text,
		ctx._.delimiter,
		ctx._.replace(ctx.input)
	].join(' ')

const render = function (ctx) {
	let lines = [renderPrompt(ctx)]
		.concat(ctx.suggestions
			.map((suggestion) => chalk.yellow(suggestion)))

	let linesRendered = lines.length
	let lengthOfFistLine = stripAnsi(lines[0]).length
	process.stdout.write(lines.join('\n')
		+ escapes.cursorTo(0)
		+ escapes.cursorMove(lengthOfFistLine, -linesRendered + 1))
}

const onKey = (ctx) => function (input, enc) {
	input = input.toString(enc)
	let code = input.charCodeAt(0); // see https://en.wikipedia.org/wiki/GNU_Readline#Keyboard_shortcuts
	// if (code === 1)    return first(); // ctrl + A
	if (code === 3)    return abort(ctx) // ctrl + C
	if (code === 13)   return submit(ctx) // return key
	if (code === 127)  return remove(ctx) // backspace
	// if (code === 4)    return process.exit(); // ctrl + D
	// if (code === 5)    return last(); // ctrl + E
	// if (code === 7)    return reset(); // ctrl + G
	// if (code === 9)    return right(); // ctrl + I / tab
	// if (code === 10)   return submit(); // ctrl + J
	// if (code === 27)   return abort(); // escape
	// if (code === 8747) return left(); // alt + B
	// if (code === 402)  return right(); // alt + F
	onInput(ctx, input)
}

const onInput = function (ctx, input) {
	ctx.input += input
	ctx.suggestions = ctx._.suggest(ctx.input)
	render(ctx)
}

const abort = function (ctx) {
	process.stdin.destroy()
	ctx.aborted = ctx.done = true
	render(ctx)

	process.stdout.write(escapes.cursorHide)
	ctx.reject(null)
}

const submit = function (ctx) {
	process.stdin.destroy()
	ctx.done = true
	render(ctx)

	process.stdout.write(escapes.cursorHide)
	ctx.resolve(ctx.input)
}

const remove = function (ctx) {
	if (ctx.input.length === 0) process.stdout.write(escapes.beep)
	ctx.input = ctx.input.slice(0, -1)
	ctx.suggestions = ctx._.suggest(ctx.input)
	render(ctx)
}

const prompt = function (text, opt) {
	if ('string' !== typeof text) throw new Error('text must be a string.')
	if (arguments.length < 2 || 'object' !== typeof opt) opt = {}
	opt = Object.assign({}, defaults, opt, {text})
	let ctx = {
		_:           opt,
		done:        false,
		aborted:     false,
		input:       '',
		suggestions: []
	}

	process.stdin.setRawMode(true)
	process.stdin.on('data', onKey(ctx))
	// todo: on 'end'
	onInput(ctx, ctx.input)
	render(ctx)

	return new Promise(function (resolve, reject) {
		ctx.resolve = resolve
		ctx.reject =  reject
	})
}

module.exports = Object.assign(prompt, {styles, symbols, defaults})
<|endoftext|>


<commit_before>'use strict'
var emojiNamedCharacters = require('emoji-named-characters')
var marked = require('ssb-marked')
var ssbref = require('ssb-ref')
var mlib   = require('ssb-msgs')

var blockRenderer = new marked.Renderer()
var inlineRenderer = new marked.Renderer()

// override to only allow external links or hashes, and correctly link to ssb objects
blockRenderer.urltransform = function (url) {
  var c = url.charAt(0)
  var hasSigil = (c == '@' || c == '&' || c == '%')

  if (this.options.sanitize && !hasSigil) {
    try {
      var prot = decodeURIComponent(unescape(url))
        .replace(/[^\w:]/g, '')
        .toLowerCase();
    } catch (e) {
      return false;
    }
    if (prot.indexOf('javascript:') === 0) {
      return false;
    }
  }

  var islink = ssbref.isLink(url)
  if (hasSigil && !islink && this.options.mentionNames) {
    // do a name lookup
    url = this.options.mentionNames[url.slice(1)]
    if (!url)
      return false
    islink = true
  }

  if (islink) {
    if (ssbref.isFeedId(url))
      return '#/profile/'+encodeURIComponent(url)
    else if (ssbref.isMsgId(url))
      return '#/msg/'+encodeURIComponent(url)
    else if (ssbref.isBlobId(url))
      return '#/webview/'+encodeURIComponent(url)
  }
  else if (url.indexOf('http') !== 0) {
    return false;
  }
  return url
}

// override to make http/s links external
blockRenderer.link = function(href, title, text) {
  href = this.urltransform(href)
  var out
  if (href !== false) {
    if (href.indexOf('#/webview/') === 0 && (title || text)) // add ?name param if this is a link to a blob
      href += '?name='+encodeURIComponent(title || text)
    out = '<a href="' + href + '"';
  } else
    out = '' + text + '';
  return out;
};

blockRenderer.image  = function (href, title, text) {
  href = href.replace(/^&/, '&')
  if (ssbref.isLink(href)) {
    var out = ''
    return out
  }
  return text
}

// inline renderer just spits out the text of links and images
inlineRenderer.urltransform = function (url) { return false }
inlineRenderer.link = function (href, title, text) { return unquote(text) }
inlineRenderer.image  = function (href, title, text) { return unquote(text) }
inlineRenderer.code = function(code, lang, escaped) { return escaped ? code : quote(code) }
inlineRenderer.blockquote = function(quote) { return unquote(quote) }
inlineRenderer.html = function(html) { return false }
inlineRenderer.heading = function(text, level, raw) { return ''+unquote(text)+' ' }
inlineRenderer.hr = function() { return ' --- ' }
inlineRenderer.br = function() { return ' ' }
inlineRenderer.list = function(body, ordered) { return unquote(body) }
inlineRenderer.listitem = function(text) { return '- '+unquote(text) }
inlineRenderer.paragraph = function(text) { return unquote(text)+' ' }
inlineRenderer.table = function(header, body) { return unquote(header + ' ' + body) }
inlineRenderer.tablerow = function(content) { return unquote(content) }
inlineRenderer.tablecell = function(content, flags) { return unquote(content) }
inlineRenderer.strong = function(text) { return ''+unquote(text)+'' }
inlineRenderer.em = function(text) { return unquote(text) }
inlineRenderer.codespan = function(text) { return unquote(text) }
inlineRenderer.del = function(text) { return unquote(text) }
inlineRenderer.mention = function(preceding, id) { return unquote((preceding||'') + id) }
function unquote (text) {
  return text.replace(/&/g, '&').replace(/"/g, '"').replace(/'/g, '\'')
}
function quote (text) {
  return text
    .replace(/&/g, '&')
    .replace(/</g, '<')
    .replace(/>/g, '>')
    .replace(/"/g, '"')
    .replace(/\n+/g, ' ')
}

marked.setOptions({
  gfm: true,
  mentions: true,
  tables: true,
  breaks: true,
  pedantic: false,
  sanitize: true,
  smartLists: true,
  smartypants: false,
  emoji: renderEmoji(16),
  renderer: blockRenderer
})

exports.block = function(text, mentionNames) {
  if (mentionNames && mentionNames.key && mentionNames.value) {
    // is a message, get the mentions links
    mentionNames = mlib.links(mentionNames.value.content.mentions, 'feed')
  }
  if (Array.isArray(mentionNames)) {
    // is an array of links, turn into an object map
    var n = {}
    mentionNames.forEach(function (link) {
      n[link.name] = link.link
    })
    mentionNames = n
  }

  return marked(''+(text||''), { mentionNames: mentionNames })
}

exports.inline = function(text) {
  return marked(''+(text||''), { renderer: inlineRenderer, emoji: renderEmoji(12) })
}

var emojiRegex = /(\s|>|^)?:([A-z0-9_]+):(\s|<|$)/g;
exports.emojis = function (str) {
  return str.replace(emojiRegex, function(full, $1, $2, $3) {
    return ($1||'') + renderEmoji(16)($2) + ($3||'')
  })
}

function renderEmoji (size) {
  size = size||20
  return function (emoji) {
    return emoji in emojiNamedCharacters ?
        ''
      : ':' + emoji + ':'
    }
}

<commit_msg>extract refs from http urls when found in markdown content<commit_after>'use strict'
var emojiNamedCharacters = require('emoji-named-characters')
var marked = require('ssb-marked')
var ssbref = require('ssb-ref')
var mlib   = require('ssb-msgs')

var blockRenderer = new marked.Renderer()
var inlineRenderer = new marked.Renderer()

// override to only allow external links or hashes, and correctly link to ssb objects
blockRenderer.urltransform = function (url) {
  var c = url.charAt(0)
  var hasSigil = (c == '@' || c == '&' || c == '%')

  if (this.options.sanitize && !hasSigil) {
    // sanitize - only allow ssb refs or http/s links
    try {
      var prot = decodeURIComponent(unescape(url.replace(/[^\w:]/g, ''))).toLowerCase();
    } catch (e) {
      return false;
    }
    if (prot.indexOf('http:') !== 0 && prot.indexOf('https:') !== 0 && prot.indexOf('data:') !== 0) {
      return false;
    }
  }

  // is this an ssb ref, or perhaps a ref within an HTTP url?
  var isSsbRef = ssbref.isLink(url)
  if (!isSsbRef) {
    // check if there's a ref inside somewhere
    var ref = ssbref.extract(url)
    if (ref) {
      url = ref
      isSsbRef = true
    }
  }

  // is this an @username mention?
  if (hasSigil && !isSsbRef && this.options.mentionNames) {
    // try a name lookup
    url = this.options.mentionNames[url.slice(1)]
    if (!url)
      return false
    isSsbRef = true
  }

  // use our own link if this is an ssb ref
  if (isSsbRef) {
    if (ssbref.isFeedId(url))
      return '#/profile/'+encodeURIComponent(url)
    else if (ssbref.isMsgId(url))
      return '#/msg/'+encodeURIComponent(url)
    else if (ssbref.isBlobId(url))
      return '/'+encodeURIComponent(url)
  }
  return url
}

// override to make http/s links external
blockRenderer.link = function(href, title, text) {
  href = this.urltransform(href)
  var out
  if (href !== false) {
    if ((href.indexOf('/%26') === 0 || href.indexOf('/&') === 0) && (title || text)) // add ?name param if this is a link to a blob
      href += '?name='+encodeURIComponent(title || text)
    out = '<a href="' + href + '"';
  } else
    out = '' + text + '';
  return out;
};

blockRenderer.image  = function (href, title, text) {
  href = href.replace(/^&/, '&')
  if (ssbref.isLink(href)) {
    var out = ''
    return out
  }
  return text
}

// inline renderer just spits out the text of links and images
inlineRenderer.urltransform = function (url) { return false }
inlineRenderer.link = function (href, title, text) { return unquote(text) }
inlineRenderer.image  = function (href, title, text) { return unquote(text) }
inlineRenderer.code = function(code, lang, escaped) { return escaped ? code : escape(code) }
inlineRenderer.blockquote = function(quote) { return unquote(quote) }
inlineRenderer.html = function(html) { return false }
inlineRenderer.heading = function(text, level, raw) { return ''+unquote(text)+' ' }
inlineRenderer.hr = function() { return ' --- ' }
inlineRenderer.br = function() { return ' ' }
inlineRenderer.list = function(body, ordered) { return unquote(body) }
inlineRenderer.listitem = function(text) { return '- '+unquote(text) }
inlineRenderer.paragraph = function(text) { return unquote(text)+' ' }
inlineRenderer.table = function(header, body) { return unquote(header + ' ' + body) }
inlineRenderer.tablerow = function(content) { return unquote(content) }
inlineRenderer.tablecell = function(content, flags) { return unquote(content) }
inlineRenderer.strong = function(text) { return ''+unquote(text)+'' }
inlineRenderer.em = function(text) { return unquote(text) }
inlineRenderer.codespan = function(text) { return unquote(text) }
inlineRenderer.del = function(text) { return unquote(text) }
inlineRenderer.mention = function(preceding, id) { return unquote((preceding||'') + id) }
function unquote (text) {
  return text.replace(/&/g, '&').replace(/"/g, '"').replace(/'/g, '\'')
}
function escape (text) {
  return text
    .replace(/&/g, '&')
    .replace(/</g, '<')
    .replace(/>/g, '>')
    .replace(/"/g, '"')
    .replace(/\n+/g, ' ')
}

marked.setOptions({
  gfm: true,
  mentions: true,
  tables: true,
  breaks: true,
  pedantic: false,
  sanitize: true,
  smartLists: true,
  smartypants: false,
  emoji: renderEmoji(16),
  renderer: blockRenderer
})

exports.block = function(text, mentionNames) {
  if (mentionNames && mentionNames.key && mentionNames.value) {
    // is a message, get the mentions links
    mentionNames = mlib.links(mentionNames.value.content.mentions, 'feed')
  }
  if (Array.isArray(mentionNames)) {
    // is an array of links, turn into an object map
    var n = {}
    mentionNames.forEach(function (link) {
      n[link.name] = link.link
    })
    mentionNames = n
  }

  return marked(''+(text||''), { mentionNames: mentionNames })
}

exports.inline = function(text) {
  return marked(''+(text||''), { renderer: inlineRenderer, emoji: renderEmoji(12) })
}

var emojiRegex = /(\s|>|^)?:([A-z0-9_]+):(\s|<|$)/g;
exports.emojis = function (str) {
  return str.replace(emojiRegex, function(full, $1, $2, $3) {
    return ($1||'') + renderEmoji(16)($2) + ($3||'')
  })
}

function renderEmoji (size) {
  size = size||20
  return function (emoji) {
    return emoji in emojiNamedCharacters ?
        ''
      : ':' + emoji + ':'
    }
}

<|endoftext|>