<commit_before>var chownr = require('chownr')
var tar = require('tar-stream')
var pump = require('pump')
var mkdirp = require('mkdirp')
var fs = require('fs')
var path = require('path')
var os = require('os')

var win32 = os.platform() === 'win32'

var noop = function () {}

var echo = function (name) {
  return name
}

var normalize = !win32 ? echo : function (name) {
  return name.replace(/\\/g, '/').replace(/[:?<>|]/g, '_')
}

var statAll = function (fs, stat, cwd, ignore, entries, sort) {
  var queue = entries || ['.']

  return function loop (callback) {
    if (!queue.length) return callback()
    var next = queue.shift()
    var nextAbs = path.join(cwd, next)

    stat(nextAbs, function (err, stat) {
      if (err) return callback(err)

      if (!stat.isDirectory()) return callback(null, next, stat)

      fs.readdir(nextAbs, function (err, files) {
        if (err) return callback(err)

        if (sort) files.sort()
        for (var i = 0; i < files.length; i++) {
          if (!ignore(path.join(cwd, next, files[i]))) queue.push(path.join(next, files[i]))
        }

        callback(null, next, stat)
      })
    })
  }
}

var strip = function (map, level) {
  return function (header) {
    header.name = header.name.split('/').slice(level).join('/')

    var linkname = header.linkname
    if (linkname && (header.type === 'link' || path.isAbsolute(linkname))) {
      header.linkname = linkname.split('/').slice(level).join('/')
    }

    return map(header)
  }
}

exports.pack = function (cwd, opts) {
  if (!cwd) cwd = '.'
  if (!opts) opts = {}

  var xfs = opts.fs || fs
  var ignore = opts.ignore || opts.filter || noop
  var map = opts.map || noop
  var mapStream = opts.mapStream || echo
  var statNext = statAll(xfs, opts.dereference ? xfs.stat : xfs.lstat, cwd, ignore, opts.entries, opts.sort)
  var strict = opts.strict !== false
  var umask = typeof opts.umask === 'number' ? ~opts.umask : ~processUmask()
  var dmode = typeof opts.dmode === 'number' ? opts.dmode : 0
  var fmode = typeof opts.fmode === 'number' ? opts.fmode : 0
  var pack = opts.pack || tar.pack()
  var finish = opts.finish || noop

  if (opts.strip) map = strip(map, opts.strip)

  if (opts.readable) {
    dmode |= parseInt(555, 8)
    fmode |= parseInt(444, 8)
  }
  if (opts.writable) {
    dmode |= parseInt(333, 8)
    fmode |= parseInt(222, 8)
  }

  var onsymlink = function (filename, header) {
    xfs.readlink(path.join(cwd, filename), function (err, linkname) {
      if (err) return pack.destroy(err)
      header.linkname = normalize(linkname)
      pack.entry(header, onnextentry)
    })
  }

  var onstat = function (err, filename, stat) {
    if (err) return pack.destroy(err)
    if (!filename) {
      if (opts.finalize !== false) pack.finalize()
      return finish(pack)
    }

    if (stat.isSocket()) return onnextentry() // tar does not support sockets...

    var header = {
      name: normalize(filename),
      mode: (stat.mode | (stat.isDirectory() ? dmode : fmode)) & umask,
      mtime: stat.mtime,
      size: stat.size,
      type: 'file',
      uid: stat.uid,
      gid: stat.gid
    }

    if (stat.isDirectory()) {
      header.size = 0
      header.type = 'directory'
      header = map(header) || header
      return pack.entry(header, onnextentry)
    }

    if (stat.isSymbolicLink()) {
      header.size = 0
      header.type = 'symlink'
      header = map(header) || header
      return onsymlink(filename, header)
    }

    // TODO: add fifo etc...

    header = map(header) || header

    if (!stat.isFile()) {
      if (strict) return pack.destroy(new Error('unsupported type for ' + filename))
      return onnextentry()
    }

    var entry = pack.entry(header, onnextentry)
    if (!entry) return

    var rs = mapStream(xfs.createReadStream(path.join(cwd, filename)), header)

    rs.on('error', function (err) { // always forward errors on destroy
      entry.destroy(err)
    })

    pump(rs, entry)
  }

  var onnextentry = function (err) {
    if (err) return pack.destroy(err)
    statNext(onstat)
  }

  onnextentry()

  return pack
}

var head = function (list) {
  return list.length ? list[list.length - 1] : null
}

var processGetuid = function () {
  return process.getuid ? process.getuid() : -1
}

var processUmask = function () {
  return process.umask ? process.umask() : 0
}

exports.extract = function (cwd, opts) {
  if (!cwd) cwd = '.'
  if (!opts) opts = {}

  var xfs = opts.fs || fs
  var ignore = opts.ignore || opts.filter || noop
  var map = opts.map || noop
  var mapStream = opts.mapStream || echo
  var own = opts.chown !== false && !win32 && processGetuid() === 0
  var extract = opts.extract || tar.extract()
  var stack = []
  var now = new Date()
  var umask = typeof opts.umask === 'number' ? ~opts.umask : ~processUmask()
  var dmode = typeof opts.dmode === 'number' ? opts.dmode : 0
  var fmode = typeof opts.fmode === 'number' ? opts.fmode : 0
  var strict = opts.strict !== false

  if (opts.strip) map = strip(map, opts.strip)

  if (opts.readable) {
    dmode |= parseInt(555, 8)
    fmode |= parseInt(444, 8)
  }
  if (opts.writable) {
    dmode |= parseInt(333, 8)
    fmode |= parseInt(222, 8)
  }

  var utimesParent = function (name, cb) { // we just set the mtime on the parent dir again everytime we write an entry
    var top
    while ((top = head(stack)) && name.slice(0, top[0].length) !== top[0]) stack.pop()
    if (!top) return cb()
    xfs.utimes(top[0], now, top[1], cb)
  }

  var utimes = function (name, header, cb) {
    if (opts.utimes === false) return cb()

    if (header.type === 'directory') return xfs.utimes(name, now, header.mtime, cb)
    if (header.type === 'symlink') return utimesParent(name, cb) // TODO: how to set mtime on link?

    xfs.utimes(name, now, header.mtime, function (err) {
      if (err) return cb(err)
      utimesParent(name, cb)
    })
  }

  var chperm = function (name, header, cb) {
    var link = header.type === 'symlink'
    var chmod = link ? xfs.lchmod : xfs.chmod
    var chown = link ? xfs.lchown : xfs.chown

    if (!chmod) return cb()

    var mode = (header.mode | (header.type === 'directory' ? dmode : fmode)) & umask
    chmod(name, mode, function (err) {
      if (err) return cb(err)
      if (!own) return cb()
      if (!chown) return cb()
      chown(name, header.uid, header.gid, cb)
    })
  }

  extract.on('entry', function (header, stream, next) {
    header = map(header) || header
    header.name = normalize(header.name)
    var name = path.join(cwd, path.join('/', header.name))

    if (ignore(name, header)) {
      stream.resume()
      return next()
    }

    var stat = function (err) {
      if (err) return next(err)
      utimes(name, header, function (err) {
        if (err) return next(err)
        if (win32) return next()
        chperm(name, header, next)
      })
    }

    var onsymlink = function () {
      if (win32) return next() // skip symlinks on win for now before it can be tested
      xfs.unlink(name, function () {
        xfs.symlink(header.linkname, name, stat)
      })
    }

    var onlink = function () {
      if (win32) return next() // skip links on win for now before it can be tested
      xfs.unlink(name, function () {
        var srcpath = path.resolve(cwd, header.linkname)

        xfs.link(srcpath, name, function (err) {
          if (err && err.code === 'EPERM' && opts.hardlinkAsFilesFallback) {
            stream = xfs.createReadStream(srcpath)
            return onfile()
          }

          stat(err)
        })
      })
    }

    var onfile = function () {
      var ws = xfs.createWriteStream(name)
      var rs = mapStream(stream, header)

      ws.on('error', function (err) { // always forward errors on destroy
        rs.destroy(err)
      })

      pump(rs, ws, function (err) {
        if (err) return next(err)
        ws.on('close', stat)
      })
    }

    if (header.type === 'directory') {
      stack.push([name, header.mtime])
      return mkdirfix(name, {
        fs: xfs, own: own, uid: header.uid, gid: header.gid
      }, stat)
    }

    var dir = path.dirname(name)

    validate(xfs, dir, path.join(cwd, '.'), function (err, valid) {
      if (err) return next(err)
      if (!valid) return next(new Error(dir + ' is not a valid path'))

      mkdirfix(dir, {
        fs: xfs, own: own, uid: header.uid, gid: header.gid
      }, function (err) {
        if (err) return next(err)

        switch (header.type) {
          case 'file': return onfile()
          case 'link': return onlink()
          case 'symlink': return onsymlink()
        }

        if (strict) return next(new Error('unsupported type for ' + name + ' (' + header.type + ')'))

        stream.resume()
        next()
      })
    })
  })

  if (opts.finish) extract.on('finish', opts.finish)

  return extract
}

function validate (fs, name, root, cb) {
  if (name === root) return cb(null, true)
  fs.lstat(name, function (err, st) {
    if (err && err.code !== 'ENOENT') return cb(err)
    if (err || st.isDirectory()) return validate(fs, path.join(name, '..'), root, cb)
    cb(null, false)
  })
}

function mkdirfix (name, opts, cb) {
  mkdirp(name, {fs: opts.xfs}, function (err, made) {
    if (!err && made && opts.own) {
      chownr(made, opts.uid, opts.gid, cb)
    } else {
      cb(err)
    }
  })
}
<commit_msg>force hardlink targets to be in the tar<commit_after>var chownr = require('chownr')
var tar = require('tar-stream')
var pump = require('pump')
var mkdirp = require('mkdirp')
var fs = require('fs')
var path = require('path')
var os = require('os')

var win32 = os.platform() === 'win32'

var noop = function () {}

var echo = function (name) {
  return name
}

var normalize = !win32 ? echo : function (name) {
  return name.replace(/\\/g, '/').replace(/[:?<>|]/g, '_')
}

var statAll = function (fs, stat, cwd, ignore, entries, sort) {
  var queue = entries || ['.']

  return function loop (callback) {
    if (!queue.length) return callback()
    var next = queue.shift()
    var nextAbs = path.join(cwd, next)

    stat(nextAbs, function (err, stat) {
      if (err) return callback(err)

      if (!stat.isDirectory()) return callback(null, next, stat)

      fs.readdir(nextAbs, function (err, files) {
        if (err) return callback(err)

        if (sort) files.sort()
        for (var i = 0; i < files.length; i++) {
          if (!ignore(path.join(cwd, next, files[i]))) queue.push(path.join(next, files[i]))
        }

        callback(null, next, stat)
      })
    })
  }
}

var strip = function (map, level) {
  return function (header) {
    header.name = header.name.split('/').slice(level).join('/')

    var linkname = header.linkname
    if (linkname && (header.type === 'link' || path.isAbsolute(linkname))) {
      header.linkname = linkname.split('/').slice(level).join('/')
    }

    return map(header)
  }
}

exports.pack = function (cwd, opts) {
  if (!cwd) cwd = '.'
  if (!opts) opts = {}

  var xfs = opts.fs || fs
  var ignore = opts.ignore || opts.filter || noop
  var map = opts.map || noop
  var mapStream = opts.mapStream || echo
  var statNext = statAll(xfs, opts.dereference ? xfs.stat : xfs.lstat, cwd, ignore, opts.entries, opts.sort)
  var strict = opts.strict !== false
  var umask = typeof opts.umask === 'number' ? ~opts.umask : ~processUmask()
  var dmode = typeof opts.dmode === 'number' ? opts.dmode : 0
  var fmode = typeof opts.fmode === 'number' ? opts.fmode : 0
  var pack = opts.pack || tar.pack()
  var finish = opts.finish || noop

  if (opts.strip) map = strip(map, opts.strip)

  if (opts.readable) {
    dmode |= parseInt(555, 8)
    fmode |= parseInt(444, 8)
  }
  if (opts.writable) {
    dmode |= parseInt(333, 8)
    fmode |= parseInt(222, 8)
  }

  var onsymlink = function (filename, header) {
    xfs.readlink(path.join(cwd, filename), function (err, linkname) {
      if (err) return pack.destroy(err)
      header.linkname = normalize(linkname)
      pack.entry(header, onnextentry)
    })
  }

  var onstat = function (err, filename, stat) {
    if (err) return pack.destroy(err)
    if (!filename) {
      if (opts.finalize !== false) pack.finalize()
      return finish(pack)
    }

    if (stat.isSocket()) return onnextentry() // tar does not support sockets...

    var header = {
      name: normalize(filename),
      mode: (stat.mode | (stat.isDirectory() ? dmode : fmode)) & umask,
      mtime: stat.mtime,
      size: stat.size,
      type: 'file',
      uid: stat.uid,
      gid: stat.gid
    }

    if (stat.isDirectory()) {
      header.size = 0
      header.type = 'directory'
      header = map(header) || header
      return pack.entry(header, onnextentry)
    }

    if (stat.isSymbolicLink()) {
      header.size = 0
      header.type = 'symlink'
      header = map(header) || header
      return onsymlink(filename, header)
    }

    // TODO: add fifo etc...

    header = map(header) || header

    if (!stat.isFile()) {
      if (strict) return pack.destroy(new Error('unsupported type for ' + filename))
      return onnextentry()
    }

    var entry = pack.entry(header, onnextentry)
    if (!entry) return

    var rs = mapStream(xfs.createReadStream(path.join(cwd, filename)), header)

    rs.on('error', function (err) { // always forward errors on destroy
      entry.destroy(err)
    })

    pump(rs, entry)
  }

  var onnextentry = function (err) {
    if (err) return pack.destroy(err)
    statNext(onstat)
  }

  onnextentry()

  return pack
}

var head = function (list) {
  return list.length ? list[list.length - 1] : null
}

var processGetuid = function () {
  return process.getuid ? process.getuid() : -1
}

var processUmask = function () {
  return process.umask ? process.umask() : 0
}

exports.extract = function (cwd, opts) {
  if (!cwd) cwd = '.'
  if (!opts) opts = {}

  var xfs = opts.fs || fs
  var ignore = opts.ignore || opts.filter || noop
  var map = opts.map || noop
  var mapStream = opts.mapStream || echo
  var own = opts.chown !== false && !win32 && processGetuid() === 0
  var extract = opts.extract || tar.extract()
  var stack = []
  var now = new Date()
  var umask = typeof opts.umask === 'number' ? ~opts.umask : ~processUmask()
  var dmode = typeof opts.dmode === 'number' ? opts.dmode : 0
  var fmode = typeof opts.fmode === 'number' ? opts.fmode : 0
  var strict = opts.strict !== false

  if (opts.strip) map = strip(map, opts.strip)

  if (opts.readable) {
    dmode |= parseInt(555, 8)
    fmode |= parseInt(444, 8)
  }
  if (opts.writable) {
    dmode |= parseInt(333, 8)
    fmode |= parseInt(222, 8)
  }

  var utimesParent = function (name, cb) { // we just set the mtime on the parent dir again everytime we write an entry
    var top
    while ((top = head(stack)) && name.slice(0, top[0].length) !== top[0]) stack.pop()
    if (!top) return cb()
    xfs.utimes(top[0], now, top[1], cb)
  }

  var utimes = function (name, header, cb) {
    if (opts.utimes === false) return cb()

    if (header.type === 'directory') return xfs.utimes(name, now, header.mtime, cb)
    if (header.type === 'symlink') return utimesParent(name, cb) // TODO: how to set mtime on link?

    xfs.utimes(name, now, header.mtime, function (err) {
      if (err) return cb(err)
      utimesParent(name, cb)
    })
  }

  var chperm = function (name, header, cb) {
    var link = header.type === 'symlink'
    var chmod = link ? xfs.lchmod : xfs.chmod
    var chown = link ? xfs.lchown : xfs.chown

    if (!chmod) return cb()

    var mode = (header.mode | (header.type === 'directory' ? dmode : fmode)) & umask
    chmod(name, mode, function (err) {
      if (err) return cb(err)
      if (!own) return cb()
      if (!chown) return cb()
      chown(name, header.uid, header.gid, cb)
    })
  }

  extract.on('entry', function (header, stream, next) {
    header = map(header) || header
    header.name = normalize(header.name)
    var name = path.join(cwd, path.join('/', header.name))

    if (ignore(name, header)) {
      stream.resume()
      return next()
    }

    var stat = function (err) {
      if (err) return next(err)
      utimes(name, header, function (err) {
        if (err) return next(err)
        if (win32) return next()
        chperm(name, header, next)
      })
    }

    var onsymlink = function () {
      if (win32) return next() // skip symlinks on win for now before it can be tested
      xfs.unlink(name, function () {
        xfs.symlink(header.linkname, name, stat)
      })
    }

    var onlink = function () {
      if (win32) return next() // skip links on win for now before it can be tested
      xfs.unlink(name, function () {
        var srcpath = path.join(cwd, path.join('/', header.linkname))

        xfs.link(srcpath, name, function (err) {
          if (err && err.code === 'EPERM' && opts.hardlinkAsFilesFallback) {
            stream = xfs.createReadStream(srcpath)
            return onfile()
          }

          stat(err)
        })
      })
    }

    var onfile = function () {
      var ws = xfs.createWriteStream(name)
      var rs = mapStream(stream, header)

      ws.on('error', function (err) { // always forward errors on destroy
        rs.destroy(err)
      })

      pump(rs, ws, function (err) {
        if (err) return next(err)
        ws.on('close', stat)
      })
    }

    if (header.type === 'directory') {
      stack.push([name, header.mtime])
      return mkdirfix(name, {
        fs: xfs, own: own, uid: header.uid, gid: header.gid
      }, stat)
    }

    var dir = path.dirname(name)

    validate(xfs, dir, path.join(cwd, '.'), function (err, valid) {
      if (err) return next(err)
      if (!valid) return next(new Error(dir + ' is not a valid path'))

      mkdirfix(dir, {
        fs: xfs, own: own, uid: header.uid, gid: header.gid
      }, function (err) {
        if (err) return next(err)

        switch (header.type) {
          case 'file': return onfile()
          case 'link': return onlink()
          case 'symlink': return onsymlink()
        }

        if (strict) return next(new Error('unsupported type for ' + name + ' (' + header.type + ')'))

        stream.resume()
        next()
      })
    })
  })

  if (opts.finish) extract.on('finish', opts.finish)

  return extract
}

function validate (fs, name, root, cb) {
  if (name === root) return cb(null, true)
  fs.lstat(name, function (err, st) {
    if (err && err.code !== 'ENOENT') return cb(err)
    if (err || st.isDirectory()) return validate(fs, path.join(name, '..'), root, cb)
    cb(null, false)
  })
}

function mkdirfix (name, opts, cb) {
  mkdirp(name, {fs: opts.xfs}, function (err, made) {
    if (!err && made && opts.own) {
      chownr(made, opts.uid, opts.gid, cb)
    } else {
      cb(err)
    }
  })
}
<|endoftext|>


<commit_before>module.exports = {
  AdNotExistError:                              'ad not exist',
  AlreadyActivatedError:                        'already activated',
  AppNotExistError:                             'app not exist',
  AppPlatformSettingsNotExistError:             'app platform settings not exist',
  AttachmentNotExistError:                      'attachment not exist',
  ClientNotExistError:                          'client not exist',
  CubePointAggregationFailedError:              'failed to aggregate cube point',
  CubePointNotExistError:                       'cube point not exist',
  FailedToCreateAdClickError:                   'failed to create ad click',
  FailedToCreateAdError:                        'failed to create ad',
  FailedToCreateAppPlatformSettingsError:       'failed to create app platform settings',
  FailedToCreateAttachmentError:                'failed to create attachment',
  FailedToCreateDeviceError:                    'failed to create device, contact us',
  FailedToCreateDeviceDataBlobError:            'failed to create device data blob',
  FailedToCreateMPoiWifiRuleError:              'failed to create poi wifi rule',
  FailedToCreatePoiError:                       'failed to create poi',
  FailedToCreateScenarioError:                  'failed to create scenario',
  FailedToCreateSubscriptionError:              'failed to create subscription',
  FailedToCreateUserError:                      'failed to create user',
  FailedToDeleteFileError:                      'failed to delete file',
  FailedToDestroyAdError:                       'failed to destroy ad',
  FailedToDestroyAppPlatformSettingsError:      'failed to destroy app platform settings',
  FailedToDestroyAttachmentError:               'failed to destroy attachment',
  FailedToDestroyMPoiWifiRuleError:             'failed to destroy poi wifi rule',
  FailedToDestroyScenarioError:                 'failed to destroy scenario',
  FailedToDestroySubscriptionError:             'failed to destroy subscription',
  FailedToEnsureDeviceError:                    'rpc error, failed to ensure device',
  FailedToExportPoiError:                       'failed to export poi',
  FailedToFindAdError:                          'failed to find ad',
  FailedToFindAppError:                         'failed to get app, check if appKey is valid',
  FailedToFindAppPlatformSettingsError:         'failed to find app platform settings',
  FailedToFindAttachmentError:                  'failed to find attachment',
  FailedToFindCubePointError:                   'failed to find cube point',
  FailedToFindFileError:                        'failed to find file',
  FailedToFindJobError:                         'failed to find job',
  FailedToFindPoiPullRequestError:              'failed to find poi pull request, contact us',
  FailedToFindPoisError:                        'failed to find pois',
  FailedToFindRegionsError:                     'failed to find regions',
  FailedToFindResourceError:                    'failed to find specified resource',
  FailedToFindScenarioError:                    'failed to find scenario',
  FailedToFindSubscriptionError:                'failed to find subscription',
  FailedToFindUserBehaviorsError:               'failed to find user behaviors',
  FailedToFindUsersError:                       'failed to find users',
  FailedToGenerateTokenError:                   'failed to generate token, contact us',
  FailedToGetAppError:                          'rpc error, failed to Get App',
  FailedToGetDeviceError:                       'failed to get device, contact us',
  FailedToGetJobError:                          'failed to get job status',
  FailedToGetPoiError:                          'rpc error, failed to get poi',
  FailedToHashPasswordError:                    'failed to hash password',
  FailedToImportPoiError:                       'failed to import error',
  FailedToQueueDeviceDataCollectJobError:       'failed to queue device data collect job',
  FailedToQueuePoiExportJobError:               'failed to queue poi export job',
  FailedToQueuePoiImportJobError:               'failed to queue poi import job',
  FailedToQueuePoiRemoveJobError:               'failed to queue poi remove job',
  FailedToQueuePoiRevertJobError:               'failed to queue poi revert job',
  FailedToReadCertificateError:                 'failed to read certificate, please check the password is correct',
  FailedToReadFileError:                        'error when read file',
  FailedToSaveDeviceError:                      'failed to create/update device, contact us',
  FailedToSaveFileError:                        'failed to save file',
  FailedToSaveUserError:                        'failed to save user, please check if required field is correct',
  FailedToSendMailError:                        'failed to send mail',
  FailedToUpdateAdError:                        'failed to update ad',
  FailedToUpdateAdLastOperationError:           'failed to update ad last operation',
  FailedToUpdateAppError:                       'failed to update app',
  FailedToUpdateAppLastOperationError:          'failed to update app last operation',
  FailedToUpdateAppPlatformSettingsError:       'failed to update app platform settings',
  FailedToUpdateAttachmentError:                'failed to update attachment',
  FailedToUpdateDeviceError:                    'failed to update device, contact us',
  FailedToUpdateMPoiWifiRuleError:              'failed to update poi wifi rule',
  FailedToUpdatePoiError:                       'failed to update poi',
  FailedToUpdatePoiPullRequestError:            'failed to update poi pull request',
  FailedToUpdateScenarioError:                  'failed to update scenario',
  FailedToUpdateScenarioLastOperationError:     'failed to update scenario last operation',
  FailedToUpdateSubscriptionError:              'failed to update subscription',
  FailedToUploadDeviceDataError:                'failed to upload data',
  FailedToValidateEmailError:                   'failed to validate email',
  FileNotExistError:                            'file not exist',
  InternalError:                                'internal error, contact us',
  InvalidActivationCodeError:                   'invalid activation code',
  InvalidAdSignatureError:                      'invalid ad signature',
  InvalidAppKeyError:                           'invalid appKey',
  InvalidAppSecretError:                        'invalid appSecret',
  InvalidClientKeyError:                        'invalid clientKey',
  InvalidClientSecretError:                     'invalid clientSecret',
  InvalidLocationError:                         'invalid location',
  InvalidPasswordResetCodeError:                'invalid password reset code',
  InvalidTokenError:                            'invalid token',
  MPoiWifiRuleNotExistError:                    'poi wifi rule not exist',
  NotYourAppError:                              'app is not yours',
  PasswordNotMatchError:                        'password not match',
  PendingPoiPullRequestExistsError:             'pending poi pull request exists',
  PoiNotExistError:                             'poi not exist',
  PoiNotReadyError:                             'poi not ready',
  PoiPullRequestNotActiveError:                 'poi pull request not active',
  PoiPullRequestNotExistError:                  'poi pull request not exist',
  RequireAdClickError:                          'require ad click',
  RequireAdError:                               'require ad',
  RequireAdIdError:                             'require ad id',
  RequireAppBundleError:                        'require appBundle',
  RequireAppError:                              'require app',
  RequireAppIdError:                            'require app id',
  RequireAppKeyError:                           'require appKey',
  RequireAppPlatformSettingsIdError:            'require app platform settings id',
  RequireAppSecretError:                        'require appSecret',
  RequireAttachmentError:                       'require attachment',
  RequireAttachmentIdError:                     'require attachment id',
  RequireBeaconsOrWifisOrLocationError:         'require beacon or wifi or location',
  RequireBssidError:                            'require wifi bssid',
  RequireClientKeyError:                        'require clientKey',
  RequireClientSecretError:                     'require clientSecret',
  RequireDeviceDataBlobError:                   'require device data blob',
  RequireDataFileError:                         'require uploaded data file',
  RequireDeviceError:                           'require device',
  RequireDeviceUdidError:                       'require deviceUdid',
  RequireFileBucketError:                       'require file bucket',
  RequireFilePathError:                         'require file path',
  RequireJobIdError:                            'require job id',
  RequireMPoiWifiRuleError:                     'require poi wifi rule',
  RequireMPoiWifiRuleIdError:                   'require poi wifi rule id',
  RequireOwnerError:                            'require owner',
  RequirePasswordError:                         'require password',
  RequirePoiError:                              'require poi',
  RequirePoiIdError:                            'require poi id',
  RequirePoiIdOrUmmError:                       'require poi id or umm',
  RequirePoiPullRequestError:                   'require poi pull request info',
  RequirePoiPullRequestIdError:                 'require poi pull request id',
  RequirePoisError:                             'require pois',
  RequireScenarioError:                         'require scenario',
  RequireScenarioIdError:                       'require scenario id',
  RequireSsidError:                             'require wifi ssid',
  RequireSubscriptionError:                     'require subscription',
  RequireSubscriptionIdError:                   'require subscription id',
  RequireTokenError:                            'require token',
  RequireUmmError:                              'require beacon umm',
  RequireUsernameError:                         'require username',
  RequireUserOrCodeToResetPasswordError:        'require user or code to reset password',
  ScenarioNotExistError:                        'scenario not exist',
  SubscriptionNotExistError:                    'subscription not exist',
  Success:                                      'success',
  SystemBusyError:                              'system busy, retry later',
  TokenExpiredError:                            'token is expired',
  UserAlreadySignupError:                       'failed to signup, user already signup',
  UserNotExistError:                            'user not exist',
  WrongParameterError:                          'wrong parameter'
};
<commit_msg>add genre error messages.<commit_after>module.exports = {
  AdNotExistError:                              'ad not exist',
  AlreadyActivatedError:                        'already activated',
  AppNotExistError:                             'app not exist',
  AppPlatformSettingsNotExistError:             'app platform settings not exist',
  AttachmentNotExistError:                      'attachment not exist',
  ClientNotExistError:                          'client not exist',
  CubePointAggregationFailedError:              'failed to aggregate cube point',
  CubePointNotExistError:                       'cube point not exist',
  FailedToCreateAdClickError:                   'failed to create ad click',
  FailedToCreateAdError:                        'failed to create ad',
  FailedToCreateAppPlatformSettingsError:       'failed to create app platform settings',
  FailedToCreateAttachmentError:                'failed to create attachment',
  FailedToCreateDeviceError:                    'failed to create device, contact us',
  FailedToCreateDeviceDataBlobError:            'failed to create device data blob',
  FailedToCreateGenreError:                     'failed to create genre',
  FailedToCreateMPoiWifiRuleError:              'failed to create poi wifi rule',
  FailedToCreatePoiError:                       'failed to create poi',
  FailedToCreateScenarioError:                  'failed to create scenario',
  FailedToCreateSubscriptionError:              'failed to create subscription',
  FailedToCreateUserError:                      'failed to create user',
  FailedToDeleteFileError:                      'failed to delete file',
  FailedToDestroyAdError:                       'failed to destroy ad',
  FailedToDestroyAppPlatformSettingsError:      'failed to destroy app platform settings',
  FailedToDestroyAttachmentError:               'failed to destroy attachment',
  FailedToDestroyGenreError:                    'failed to destroy genre',
  FailedToDestroyMPoiWifiRuleError:             'failed to destroy poi wifi rule',
  FailedToDestroyScenarioError:                 'failed to destroy scenario',
  FailedToDestroySubscriptionError:             'failed to destroy subscription',
  FailedToEnsureDeviceError:                    'rpc error, failed to ensure device',
  FailedToExportPoiError:                       'failed to export poi',
  FailedToFindAdError:                          'failed to find ad',
  FailedToFindAppError:                         'failed to get app, check if appKey is valid',
  FailedToFindAppPlatformSettingsError:         'failed to find app platform settings',
  FailedToFindAttachmentError:                  'failed to find attachment',
  FailedToFindCubePointError:                   'failed to find cube point',
  FailedToFindFileError:                        'failed to find file',
  FailedToFindGenreError:                       'failed to find genre',
  FailedToFindJobError:                         'failed to find job',
  FailedToFindPoiPullRequestError:              'failed to find poi pull request, contact us',
  FailedToFindPoisError:                        'failed to find pois',
  FailedToFindRegionsError:                     'failed to find regions',
  FailedToFindResourceError:                    'failed to find specified resource',
  FailedToFindScenarioError:                    'failed to find scenario',
  FailedToFindSubscriptionError:                'failed to find subscription',
  FailedToFindUserBehaviorsError:               'failed to find user behaviors',
  FailedToFindUsersError:                       'failed to find users',
  FailedToGenerateTokenError:                   'failed to generate token, contact us',
  FailedToGetAppError:                          'rpc error, failed to Get App',
  FailedToGetDeviceError:                       'failed to get device, contact us',
  FailedToGetJobError:                          'failed to get job status',
  FailedToGetPoiError:                          'rpc error, failed to get poi',
  FailedToHashPasswordError:                    'failed to hash password',
  FailedToImportPoiError:                       'failed to import error',
  FailedToQueueDeviceDataCollectJobError:       'failed to queue device data collect job',
  FailedToQueuePoiExportJobError:               'failed to queue poi export job',
  FailedToQueuePoiImportJobError:               'failed to queue poi import job',
  FailedToQueuePoiRemoveJobError:               'failed to queue poi remove job',
  FailedToQueuePoiRevertJobError:               'failed to queue poi revert job',
  FailedToReadCertificateError:                 'failed to read certificate, please check the password is correct',
  FailedToReadFileError:                        'error when read file',
  FailedToSaveDeviceError:                      'failed to create/update device, contact us',
  FailedToSaveFileError:                        'failed to save file',
  FailedToSaveUserError:                        'failed to save user, please check if required field is correct',
  FailedToSendMailError:                        'failed to send mail',
  FailedToUpdateAdError:                        'failed to update ad',
  FailedToUpdateAdLastOperationError:           'failed to update ad last operation',
  FailedToUpdateAppError:                       'failed to update app',
  FailedToUpdateAppLastOperationError:          'failed to update app last operation',
  FailedToUpdateAppPlatformSettingsError:       'failed to update app platform settings',
  FailedToUpdateAttachmentError:                'failed to update attachment',
  FailedToUpdateDeviceError:                    'failed to update device, contact us',
  FailedToUpdateGenreError:                     'failed to update genre',
  FailedToUpdateMPoiWifiRuleError:              'failed to update poi wifi rule',
  FailedToUpdatePoiError:                       'failed to update poi',
  FailedToUpdatePoiPullRequestError:            'failed to update poi pull request',
  FailedToUpdateScenarioError:                  'failed to update scenario',
  FailedToUpdateScenarioLastOperationError:     'failed to update scenario last operation',
  FailedToUpdateSubscriptionError:              'failed to update subscription',
  FailedToUploadDeviceDataError:                'failed to upload data',
  FailedToValidateEmailError:                   'failed to validate email',
  FileNotExistError:                            'file not exist',
  GenreNotExistError:                           'genre not exist',
  InternalError:                                'internal error, contact us',
  InvalidActivationCodeError:                   'invalid activation code',
  InvalidAdSignatureError:                      'invalid ad signature',
  InvalidAppKeyError:                           'invalid appKey',
  InvalidAppSecretError:                        'invalid appSecret',
  InvalidClientKeyError:                        'invalid clientKey',
  InvalidClientSecretError:                     'invalid clientSecret',
  InvalidLocationError:                         'invalid location',
  InvalidPasswordResetCodeError:                'invalid password reset code',
  InvalidTokenError:                            'invalid token',
  MPoiWifiRuleNotExistError:                    'poi wifi rule not exist',
  NotYourAppError:                              'app is not yours',
  PasswordNotMatchError:                        'password not match',
  PendingPoiPullRequestExistsError:             'pending poi pull request exists',
  PoiNotExistError:                             'poi not exist',
  PoiNotReadyError:                             'poi not ready',
  PoiPullRequestNotActiveError:                 'poi pull request not active',
  PoiPullRequestNotExistError:                  'poi pull request not exist',
  RequireAdClickError:                          'require ad click',
  RequireAdError:                               'require ad',
  RequireAdIdError:                             'require ad id',
  RequireAppBundleError:                        'require appBundle',
  RequireAppError:                              'require app',
  RequireAppIdError:                            'require app id',
  RequireAppKeyError:                           'require appKey',
  RequireAppPlatformSettingsIdError:            'require app platform settings id',
  RequireAppSecretError:                        'require appSecret',
  RequireAttachmentError:                       'require attachment',
  RequireAttachmentIdError:                     'require attachment id',
  RequireBeaconsOrWifisOrLocationError:         'require beacon or wifi or location',
  RequireBssidError:                            'require wifi bssid',
  RequireClientKeyError:                        'require clientKey',
  RequireClientSecretError:                     'require clientSecret',
  RequireDeviceDataBlobError:                   'require device data blob',
  RequireDataFileError:                         'require uploaded data file',
  RequireDeviceError:                           'require device',
  RequireDeviceUdidError:                       'require deviceUdid',
  RequireFileBucketError:                       'require file bucket',
  RequireFilePathError:                         'require file path',
  RequireGenreError:                            'require genre',
  RequireGenreIdError:                          'require genre id',
  RequireJobIdError:                            'require job id',
  RequireMPoiWifiRuleError:                     'require poi wifi rule',
  RequireMPoiWifiRuleIdError:                   'require poi wifi rule id',
  RequireOwnerError:                            'require owner',
  RequirePasswordError:                         'require password',
  RequirePoiError:                              'require poi',
  RequirePoiIdError:                            'require poi id',
  RequirePoiIdOrUmmError:                       'require poi id or umm',
  RequirePoiPullRequestError:                   'require poi pull request info',
  RequirePoiPullRequestIdError:                 'require poi pull request id',
  RequirePoisError:                             'require pois',
  RequireScenarioError:                         'require scenario',
  RequireScenarioIdError:                       'require scenario id',
  RequireSsidError:                             'require wifi ssid',
  RequireSubscriptionError:                     'require subscription',
  RequireSubscriptionIdError:                   'require subscription id',
  RequireTokenError:                            'require token',
  RequireUmmError:                              'require beacon umm',
  RequireUsernameError:                         'require username',
  RequireUserOrCodeToResetPasswordError:        'require user or code to reset password',
  ScenarioNotExistError:                        'scenario not exist',
  SubscriptionNotExistError:                    'subscription not exist',
  Success:                                      'success',
  SystemBusyError:                              'system busy, retry later',
  TokenExpiredError:                            'token is expired',
  UserAlreadySignupError:                       'failed to signup, user already signup',
  UserNotExistError:                            'user not exist',
  WrongParameterError:                          'wrong parameter'
};
<|endoftext|>


<commit_before>var trumpet = require('trumpet');
var Transform = require('readable-stream/transform');
var hyperglue = require('hyperglue');
var encode = require('ent').encode;
var through = require('through');

module.exports = function (html, opts, cb) {
    if (typeof opts === 'function') {
        cb = opts;
        opts = {};
    }
    if (!opts) opts = {};

    var tf = new Transform({ objectMode: true });
    tf._transform = function (line, _, next) {
        var row;
        if (typeof line === 'string' || Buffer.isBuffer(line)) {
            try { row = JSON.parse(line) }
            catch (err) { this.emit('error', err) }
        }
        else row = line;
        var res = cb(row);
        if (!res) return next();

        var tr = trumpet();
        if (opts.key && row.key) {
            tr.select('*').setAttribute(opts.key, row.key);
        }

        tr.on('data', function (buf) { tf.push(buf) });
        tr.on('end', function () { next() });

        Object.keys(res).forEach(function (key) {
            if (key === ':first') {
                each(key, tr.select('*'));
            }
            else if (/:first$/.test(key)) {
                each(key, tr.select(key.replace(/:first$/, '')));
            }
            else tr.selectAll(key, function (elem) { each(key, elem) })
        });

        function each (key, elem) {
            if (isStream(res[key])) {
                tf.emit('stream', res[key]);
                res[key].pipe(elem.createWriteStream());
            }
            else if (Array.isArray(res[key])) {
                var bufs = [];
                var write = function (buf) { bufs.push(buf) };
                var end = function (next) {
                    var html = Buffer.concat(bufs).toString('utf8');
                    if (html.length) {
                        res[key].forEach(function (m) {
                            var mm = {}; mm[key] = m;
                            trf.queue(hyperglue(html, mm).outerHTML);
                        });
                    }
                    trf.queue(null);
                };
                var trf = through(write, end);
                trf.pipe(elem.createStream({ outer: true })).pipe(trf);
            }
            else if (typeof res[key] === 'object') {
                Object.keys(res[key]).forEach(function (k) {
                    var v = res[key][k];
                    if (k === '_html') {
                        if (isStream(v)) {
                            v.pipe(elem.createWriteStream());
                        }
                        else if (typeof v === 'string' || Buffer.isBuffer(v)) {
                            elem.createWriteStream().end(v);
                        }
                        else {
                            elem.createWriteStream().end(String(v));
                        }
                    }
                    else if (k === '_text') {
                        if (Buffer.isBuffer(v)) v = v.toString('utf8')
                        else if (typeof v !== 'string') v = String(v);
                        elem.createWriteStream().end(encode(v));
                    }
                    else {
                        if (Buffer.isBuffer(v)) v = v.toString('utf8')
                        else if (typeof v !== 'string') v = String(v);
                        elem.setAttribute(k, v);
                    }
                });
            }
            else {
                var v = res[key];
                if (Buffer.isBuffer(v)) v = v.toString('utf8')
                else if (typeof v !== 'string') v = String(v);
                elem.createWriteStream().end(encode(v));
            }
        }
        tr.end(html);
    };
    return tf;
};

function encode (s) {
    var res = '';
    for (var i = 0; i < s.length; i++) {
        var c = s.charCodeAt(i);
        if (c >= 128) {
            res += '&#' + c + ';';
        }
        else res += s.charAt(i);
    }
    return res;
}

function isStream (x) {
    return x && typeof x.pipe === 'function';
}
<commit_msg>convert row.key to a string if it isn't one already<commit_after>var trumpet = require('trumpet');
var Transform = require('readable-stream/transform');
var hyperglue = require('hyperglue');
var encode = require('ent').encode;
var through = require('through');

module.exports = function (html, opts, cb) {
    if (typeof opts === 'function') {
        cb = opts;
        opts = {};
    }
    if (!opts) opts = {};

    var tf = new Transform({ objectMode: true });
    tf._transform = function (line, _, next) {
        var row;
        if (typeof line === 'string' || Buffer.isBuffer(line)) {
            try { row = JSON.parse(line) }
            catch (err) { this.emit('error', err) }
        }
        else row = line;
        var res = cb(row);
        if (!res) return next();

        var tr = trumpet();
        if (opts.key && row.key) {
            var rk = typeof row.key === 'string' ? row.key : String(row.key);
            tr.select('*').setAttribute(opts.key, rk);
        }

        tr.on('data', function (buf) { tf.push(buf) });
        tr.on('end', function () { next() });

        Object.keys(res).forEach(function (key) {
            if (key === ':first') {
                each(key, tr.select('*'));
            }
            else if (/:first$/.test(key)) {
                each(key, tr.select(key.replace(/:first$/, '')));
            }
            else tr.selectAll(key, function (elem) { each(key, elem) })
        });

        function each (key, elem) {
            if (isStream(res[key])) {
                tf.emit('stream', res[key]);
                res[key].pipe(elem.createWriteStream());
            }
            else if (Array.isArray(res[key])) {
                var bufs = [];
                var write = function (buf) { bufs.push(buf) };
                var end = function (next) {
                    var html = Buffer.concat(bufs).toString('utf8');
                    if (html.length) {
                        res[key].forEach(function (m) {
                            var mm = {}; mm[key] = m;
                            trf.queue(hyperglue(html, mm).outerHTML);
                        });
                    }
                    trf.queue(null);
                };
                var trf = through(write, end);
                trf.pipe(elem.createStream({ outer: true })).pipe(trf);
            }
            else if (typeof res[key] === 'object') {
                Object.keys(res[key]).forEach(function (k) {
                    var v = res[key][k];
                    if (k === '_html') {
                        if (isStream(v)) {
                            v.pipe(elem.createWriteStream());
                        }
                        else if (typeof v === 'string' || Buffer.isBuffer(v)) {
                            elem.createWriteStream().end(v);
                        }
                        else {
                            elem.createWriteStream().end(String(v));
                        }
                    }
                    else if (k === '_text') {
                        if (Buffer.isBuffer(v)) v = v.toString('utf8')
                        else if (typeof v !== 'string') v = String(v);
                        elem.createWriteStream().end(encode(v));
                    }
                    else {
                        if (Buffer.isBuffer(v)) v = v.toString('utf8')
                        else if (typeof v !== 'string') v = String(v);
                        elem.setAttribute(k, v);
                    }
                });
            }
            else {
                var v = res[key];
                if (Buffer.isBuffer(v)) v = v.toString('utf8')
                else if (typeof v !== 'string') v = String(v);
                elem.createWriteStream().end(encode(v));
            }
        }
        tr.end(html);
    };
    return tf;
};

function encode (s) {
    var res = '';
    for (var i = 0; i < s.length; i++) {
        var c = s.charCodeAt(i);
        if (c >= 128) {
            res += '&#' + c + ';';
        }
        else res += s.charAt(i);
    }
    return res;
}

function isStream (x) {
    return x && typeof x.pipe === 'function';
}
<|endoftext|>


<commit_before>var gulp 	= require('gulp'),
	plugins = require('gulp-load-plugins')();
var runSequence = require('run-sequence');

/**
 * doScss - Compile Scss
 * @param  Array src 		Globs of src path.
 * @param  Array paths 		Paths to include for Scss @import.
 * @param  String dest 		Path of stream destination.
 * @return Object
 */
exports.doScss = function(src, paths, dest) {
	return gulp.src(src)
		.pipe(plugins.sourcemaps.init())
			.pipe(plugins.sass({
				includePaths: paths,
				outputStyle: 'compressed'
			}))
		.pipe(plugins.sourcemaps.write('./maps'))
		.pipe(gulp.dest(dest));
};

/**
 * doJs - Compile Javascript
 * @param  Array src		Globs of src paths.
 * @param  String name 		Name of output file.
 * @param  String dest 		Path of stream destination.
 * @return Object
 */
exports.doJs = function(src, name, dest) {
	return gulp.src(src)
		.pipe(plugins.sourcemaps.init())
			.pipe(plugins.concat( name + '.js', {newLine: ';'}))
			.pipe(plugins.rename({ basename: name, suffix: '.min'}))
			.pipe(plugins.uglify())
		.pipe(plugins.sourcemaps.write('./maps'))
		.pipe(gulp.dest(dest));
};<commit_msg>create doImages task<commit_after>var gulp 	= require('gulp'),
	plugins = require('gulp-load-plugins')();
var runSequence = require('run-sequence');

/**
 * doScss - Compile Scss
 * @param  Array src 		Globs of src file patterns.
 * @param  Array paths 		Paths to include for Scss @import.
 * @param  String dest 		Path of stream destination.
 * @return Object
 */
exports.doScss = function(src, paths, dest) {
	return gulp.src(src)
		.pipe(plugins.sourcemaps.init())
			.pipe(plugins.sass({
				includePaths: paths,
				outputStyle: 'compressed'
			}))
		.pipe(plugins.sourcemaps.write('./maps'))
		.pipe(gulp.dest(dest));
};

/**
 * doJs - Compile Javascript
 * @param  Array src		Globs of src file patterns.
 * @param  String name 		Name of output file.
 * @param  String dest 		Path of stream destination.
 * @return Object
 */
exports.doJs = function(src, name, dest) {
	return gulp.src(src)
		.pipe(plugins.sourcemaps.init())
			.pipe(plugins.concat( name + '.js', {newLine: ';'}))
			.pipe(plugins.rename({ basename: name, suffix: '.min'}))
			.pipe(plugins.uglify())
		.pipe(plugins.sourcemaps.write('./maps'))
		.pipe(gulp.dest(dest));
};

/**
 * doImages - Optimize Images
 * @param  Array src 		Globs of src file patterns.
 * @param  String dest 		Path of stream destination.
 * @param  Object options 	Imagemin Options.
 * @return Object
 */
exports.doImages = function(src, dest, options) {
	options = typeof options !== 'undefined' ? options : {
		optimizationLevel: 5,
		progressive: true,
		interlaced: true
	};

	return gulp.src(src)
		.pipe(plugins.imagemin(options))
		.pipe(gulp.dest(dest));
}<|endoftext|>


<commit_before>var cheerio = require('cheerio')
var map = require('map-limit')
var request = require('request')
var assign = require('object-assign')
var url = require('url')

var limit = 25

function scripts(body) {
  var $ = cheerio.load(body)
  var tags = []
  $('script').each(function(idx, el) {
    el = $(el)
    tags.push({
      type: el.attr('type'),
      src: el.attr('src'),
      body: el.html() || ''
    })
  })
  return tags
}

function fetch(uri, script, cb) {
  request.get({ uri: uri }, function(err, resp, body) {
    if (err) return cb(err)
    cb(null, assign({}, script, { body: body }))
  })
}

module.exports = function(opt, done) {
  if (typeof opt === 'string')
    opt = { uri: opt }
  else
    opt = opt||{}

  if (typeof done !== 'function')
    throw new TypeError('expected callback function')

  //first grab site body
  request.get(opt, function(err, resp, body) {
    if (err) return done(err)

    //parse script tags
    var tags = scripts(body)
    var base = opt.uri || opt.url

    //map script resources
    map(tags, limit, function(item, next) {
      if (item.src) { //request and replace body
        var uri = url.resolve(base, item.src)
        fetch(uri, item, next)
      } else {
        next(null, item)
      }
    }, done)
  })
}<commit_msg>temp fix for base bath<commit_after>var cheerio = require('cheerio')
var map = require('map-limit')
var request = require('request')
var assign = require('object-assign')
var url = require('url')
var path = require('path')

var limit = 25

function scripts(body) {
  var $ = cheerio.load(body)
  var tags = []
  $('script').each(function(idx, el) {
    el = $(el)
    tags.push({
      type: el.attr('type'),
      src: el.attr('src'),
      body: el.html() || ''
    })
  })
  return tags
}

function fetch(base, script, cb) {
  request.get({ uri: script.src, baseUrl: base }, function(err, resp, body) {
    if (err) return cb(err)
    cb(null, assign({}, script, { body: body }))
  })
}

module.exports = function(opt, done) {
  if (typeof opt === 'string')
    opt = { uri: opt }
  else
    opt = opt||{}

  if (typeof done !== 'function')
    throw new TypeError('expected callback function')

  //first grab site body
  request.get(opt, function(err, resp, body) {
    if (err) return done(err)

    //parse script tags
    var tags = scripts(body)
    var baseUrl = url.parse(opt.uri || opt.url)
    var base = baseUrl.href
    if (path.extname(base)) {
      base = path.dirname(base)
    }

    //map script resources
    map(tags, limit, function(item, next) {
      if (item.src) { //request and replace body
        fetch(base, item, next)
      } else {
        next(null, item)
      }
    }, done)
  })
}<|endoftext|>


<commit_before>#!/usr/bin/env node

var fs = require('fs')
  , spawn = require('child_process').spawn
  , path = require('path');

var choices = require('choices')
  , colors = require('colors')
  , jssc = require('jssc');

if (process.argv.length < 3) {
  console.error('Usage: ss [-i] [filename]');
  process.exit(1);
}

function compile (file, next) {
  var bufs = [];
  var colony = spawn('colony', ['-cb', path.relative(process.cwd(), file)])
  colony.stderr.on('data', function (data) {
    console.error(String(data).red);
  })
  colony.stdout.on('data', function (data) {
    bufs.push(data);
  })
  colony.on('close', function (code) {
    if (code > 0) {
      console.error('Invalid colony output code', code + ', aborting.');
      process.exit(1);
    }

    var output = Buffer.concat(bufs);
    next(output);
  })
}

var firstNoDevicesFound = false;

console.log('hey its scripstick'.grey);

detectDevice(function (modem) {
  handshake(modem, function (serial) {
    if (process.argv[2] == '-i') {
      console.log('[connected]'.grey);
    } else {
      compile(process.argv[2], function (luacode) {
        upload(serial, luacode);
      });
    }
  });
});

function detectDevice (next) {
  var modems = fs.readdirSync('/dev').filter(function (file) {
    return file.match(/^cu.usbmodem.*$/);
  });

  if (modems.length == 0) {
    if (!firstNoDevicesFound) {
      console.error('No ScriptStick connected, waiting for device to connect...'.grey);
      firstNoDevicesFound = true;
    }
    return setTimeout(detectDevice, 10, next);
  }

  if (modems.length > 1) {
    choices('Select a device: ', modems, function (i) {
      next(modems[i]);
    });
  } else {
    next(modems[0]);
  }
}

function handshake (modem, next) {
  modem = '/dev/' + modem;
  process.stdout.write('Connecting to '.grey + modem.green + '... '.grey);

  var serial = jssc.listen(modem);
  serial.stderr.pipe(process.stderr);
  serial.on('close', function (code) {
    console.log('jssc exited with code', code);
    process.exit(1);
  })

  // Wait for initial "!\n"
  serial.stdout.once('data', function onhandshake (data) {
    serial.stdout.pipe(process.stdout);
    serial.stdin.write("!\n", function () {
      console.log('done.');
      next(serial);
    });
  })
}

function upload (serial, luacode) {
  var sizebuf = new Buffer(4);
  sizebuf.writeInt32LE(luacode.length, 0);
  serial.stdin.write(Buffer.concat([sizebuf, luacode]), function () {
    console.log(String('[it is written]').grey);
  });
}<commit_msg>Handshaking<commit_after>#!/usr/bin/env node

var fs = require('fs')
  , spawn = require('child_process').spawn
  , path = require('path');

var choices = require('choices')
  , colors = require('colors')
  , jssc = require('jssc');

if (process.argv.length < 3) {
  console.error('ScriptStick CLI\nUsage: ss [-i] [filename]');
  process.exit(1);
}

function compile (file, next) {
  var bufs = [];
  var colony = spawn('colony', ['-cb', path.relative(process.cwd(), file)])
  colony.stderr.on('data', function (data) {
    console.error(String(data).red);
  })
  colony.stdout.on('data', function (data) {
    bufs.push(data);
  })
  colony.on('close', function (code) {
    if (code > 0) {
      console.error('Invalid colony output code', code + ', aborting.');
      process.exit(1);
    }

    var output = Buffer.concat(bufs);
    next(output);
  })
}

var firstNoDevicesFound = false;

console.log('hey its scripstick'.grey);

detectDevice(function (modem) {
  handshake(modem, function (serial) {
    if (process.argv[2] == '-i') {
      console.log('[connected]'.grey);

      // console.log('Beat.');
      // setTimeout(function () {
      //   serial.send('B', '', function () {
      //     console.log('BREAK');
      //   })
      // }, 5000);
    } else {
      compile(process.argv[2], function (luacode) {
        upload(serial, luacode);
      });
    }
  });
});

function detectDevice (next) {
  var modems = fs.readdirSync('/dev').filter(function (file) {
    return file.match(/^cu.usbmodem.*$/);
  });

  if (modems.length == 0) {
    if (!firstNoDevicesFound) {
      console.error('No ScriptStick connected, waiting for device to connect...'.grey);
      firstNoDevicesFound = true;
    }
    return setTimeout(detectDevice, 10, next);
  }

  if (modems.length > 1) {
    choices('Select a device: ', modems, function (i) {
      next(modems[i]);
    });
  } else {
    next(modems[0]);
  }
}

function handshake (modem, next) {
  modem = '/dev/' + modem;
  process.stdout.write('Connecting to '.grey + modem.green + '... '.grey);

  var serial = jssc.listen(modem);
  serial.stderr.pipe(process.stderr);

  serial.on('close', function (code) {
    console.log('jssc exited with code', code);
    process.exit(1);
  })
  serial.on('cts', function (cts) {
    if (!cts) {
      process.exit(1);
    }
  })

  // Wait for initial "!\n"
  var shake = '';
  serial.on('data', function onhandshake (data) {
    shake += String(data);
    if (shake == '!\n') {
      serial.removeListener('data', onhandshake);
      serial.on('data', function (data) {
        process.stdout.write(data);
      });
      serial.on('error', function (err) {
        console.error(err);
      });
      serial.write("!\n", function () {
        console.log('done.');
        next(serial);
      });
    } else if (shake.length > 2) {
      console.error('ERROR'.red, 'Please restart device.');
      process.exit(1);
    }
  })
}

function upload (serial, luacode) {
  var sizebuf = new Buffer(4);
  sizebuf.writeInt32LE(luacode.length, 0);
  serial.write(Buffer.concat([sizebuf, luacode]), function () {
    console.log(String('[it is written]').grey);
  });
}<|endoftext|>


<commit_before>var Botkit = require('botkit')

var token = process.env.SLACK_TOKEN

var races_original = [
	"The Barony of Letnev",
	"The Clan of Saar",
	"The Emirates of Hacan",
	"The Federation of Sol",
	"The Mentak Coalition",
	"The Naalu Collective",
	"The Nekro Virus",
	"The Sardakk N’orr",
	"The Universities of Jol-Nar",
	"The Winnu",
	"The Xxcha Kingdom",
	"The Yssaril Tribes",
	"The Brotherhood of Yin",
	"The Embers of Muaat",
	"The Ghosts of Creuss",
	"The L1z1x Mindnet",
	"The Arborec"
  ]
var races = races_original
var currently_choosing
var current_choices = []
var number_of_choices = 3

var controller = Botkit.slackbot({
  // reconnect to Slack RTM when connection goes bad
  retry: Infinity,
  debug: false
})

// Assume single team mode if we have a SLACK_TOKEN
if (token) {
  console.log('Starting in single-team mode')
  console.log("cause there's this token" + token)
  controller.spawn({
    token: token,
    retry: Infinity
  }).startRTM(function (err, bot, payload) {
    if (err) {
      throw new Error(err)
    }

    console.log('Connected to Slack RTM')
  })
// Otherwise assume multi-team mode - setup beep boop resourcer connection
} else {
  console.log('Starting in Beep Boop multi-team mode')
  require('beepboop-botkit').start(controller, { debug: true })
}

controller.on('bot_channel_join', function (bot, message) {
  bot.reply(message, "I'm here!")
})

controller.hears(['list'], ['direct_mention','direct_message'], function (bot, message) {
  var reply = "Here are the currently available races:\n"
  races.forEach(function(item) {
    reply += "* " + item + "\n";
  })
  bot.reply(message, reply);
})

controller.hears(['do', 'do @(.*)], ['direct_mention'], function (bot, message) {
/*
  const { user, channel, text } = message;
  const userData = text.match(/<@([A-Z0–9]{9})>/); // parse the text for user's 9 character id
*/
  var reply = "I heard " + message.match[0] + ".\n";
  reply += "Plus the 1 was " + message.match[1] + ".\n";
  reply += "So that's the text '" + message.text + "'.";
  bot.reply(message, reply);
})

controller.hears(['hello', 'hi'], ['direct_mention'], function (bot, message) {
  bot.reply(message, 'Hello.')
})

controller.hears(['hello', 'hi'], ['direct_message'], function (bot, message) {
  bot.reply(message, 'Hello.')
  bot.reply(message, 'It\'s nice to talk to you directly.')
})

controller.hears('.*', ['mention'], function (bot, message) {
  bot.reply(message, 'You really do care about me. :heart:')
})

controller.hears('help', ['direct_message', 'direct_mention'], function (bot, message) {
  var help = 'I will respond to the following messages: \n' +
      '`bot hi` for a simple message.\n' +
      '`bot attachment` to see a Slack attachment message.\n' +
      '`@<your bot\'s name>` to demonstrate detecting a mention.\n' +
      '`bot help` to see this again.'
  bot.reply(message, help)
})

controller.hears(['attachment'], ['direct_message', 'direct_mention'], function (bot, message) {
  var text = 'Beep Beep Boop is a ridiculously simple hosting platform for your Slackbots.'
  var attachments = [{
    fallback: text,
    pretext: 'We bring bots to life. :sunglasses: :thumbsup:',
    title: 'Host, deploy and share your bot in seconds.',
    image_url: 'https://storage.googleapis.com/beepboophq/_assets/bot-1.22f6fb.png',
    title_link: 'https://beepboophq.com/',
    text: text,
    color: '#7CD197'
  }]

  bot.reply(message, {
    attachments: attachments
  }, function (err, resp) {
    console.log(err, resp)
  })
})

controller.hears('.*', ['direct_message', 'direct_mention'], function (bot, message) {
  bot.reply(message, 'Sorry <@' + message.user + '>, I don\'t understand. \n')
})
<commit_msg>fix typo<commit_after>var Botkit = require('botkit')

var token = process.env.SLACK_TOKEN

var races_original = [
	"The Barony of Letnev",
	"The Clan of Saar",
	"The Emirates of Hacan",
	"The Federation of Sol",
	"The Mentak Coalition",
	"The Naalu Collective",
	"The Nekro Virus",
	"The Sardakk N’orr",
	"The Universities of Jol-Nar",
	"The Winnu",
	"The Xxcha Kingdom",
	"The Yssaril Tribes",
	"The Brotherhood of Yin",
	"The Embers of Muaat",
	"The Ghosts of Creuss",
	"The L1z1x Mindnet",
	"The Arborec"
  ]
var races = races_original
var currently_choosing
var current_choices = []
var number_of_choices = 3

var controller = Botkit.slackbot({
  // reconnect to Slack RTM when connection goes bad
  retry: Infinity,
  debug: false
})

// Assume single team mode if we have a SLACK_TOKEN
if (token) {
  console.log('Starting in single-team mode')
  console.log("cause there's this token" + token)
  controller.spawn({
    token: token,
    retry: Infinity
  }).startRTM(function (err, bot, payload) {
    if (err) {
      throw new Error(err)
    }

    console.log('Connected to Slack RTM')
  })
// Otherwise assume multi-team mode - setup beep boop resourcer connection
} else {
  console.log('Starting in Beep Boop multi-team mode')
  require('beepboop-botkit').start(controller, { debug: true })
}

controller.on('bot_channel_join', function (bot, message) {
  bot.reply(message, "I'm here!")
})

controller.hears(['list'], ['direct_mention','direct_message'], function (bot, message) {
  var reply = "Here are the currently available races:\n"
  races.forEach(function(item) {
    reply += "* " + item + "\n";
  })
  bot.reply(message, reply);
})

controller.hears(['do', 'do @(.*)'], ['direct_mention'], function (bot, message) {
/*
  const { user, channel, text } = message;
  const userData = text.match(/<@([A-Z0–9]{9})>/); // parse the text for user's 9 character id
*/
  var reply = "I heard " + message.match[0] + ".\n";
  reply += "Plus the 1 was " + message.match[1] + ".\n";
  reply += "So that's the text '" + message.text + "'.";
  bot.reply(message, reply);
})

controller.hears(['hello', 'hi'], ['direct_mention'], function (bot, message) {
  bot.reply(message, 'Hello.')
})

controller.hears(['hello', 'hi'], ['direct_message'], function (bot, message) {
  bot.reply(message, 'Hello.')
  bot.reply(message, 'It\'s nice to talk to you directly.')
})

controller.hears('.*', ['mention'], function (bot, message) {
  bot.reply(message, 'You really do care about me. :heart:')
})

controller.hears('help', ['direct_message', 'direct_mention'], function (bot, message) {
  var help = 'I will respond to the following messages: \n' +
      '`bot hi` for a simple message.\n' +
      '`bot attachment` to see a Slack attachment message.\n' +
      '`@<your bot\'s name>` to demonstrate detecting a mention.\n' +
      '`bot help` to see this again.'
  bot.reply(message, help)
})

controller.hears(['attachment'], ['direct_message', 'direct_mention'], function (bot, message) {
  var text = 'Beep Beep Boop is a ridiculously simple hosting platform for your Slackbots.'
  var attachments = [{
    fallback: text,
    pretext: 'We bring bots to life. :sunglasses: :thumbsup:',
    title: 'Host, deploy and share your bot in seconds.',
    image_url: 'https://storage.googleapis.com/beepboophq/_assets/bot-1.22f6fb.png',
    title_link: 'https://beepboophq.com/',
    text: text,
    color: '#7CD197'
  }]

  bot.reply(message, {
    attachments: attachments
  }, function (err, resp) {
    console.log(err, resp)
  })
})

controller.hears('.*', ['direct_message', 'direct_mention'], function (bot, message) {
  bot.reply(message, 'Sorry <@' + message.user + '>, I don\'t understand. \n')
})
<|endoftext|>


<commit_before>'use strict';

var os            = require('os')
var Dias          = require('dias')
var pkg           = require('./package.json')
var Logger        = require('ceo-logger')
var middleServer  = require('middle-server')
var proxyPackage  = require('proxy-cache-packages')
var apiDoc        = require('./modules/api-doc')
var apiLatest     = require('./modules/api-latest')
var apiPackage    = require('./modules/api-package')
var favicon       = require('serve-favicon')(__dirname + '/favicon.ico')
var pakrStatic    = process.env.STATIC_URL || 'http://pakr-static.herokuapp.com'
var domain        = {
  pakr:       pakrStatic + '/$package/$version/$file', // proxy-cache-multi-domain override to include local files
  cdnjs:      'https://cdnjs.cloudflare.com/ajax/libs/$package/$version/$file',
  jsdelivr:   'https://cdn.jsdelivr.net/$package/$version/$file',
  google:     'https://ajax.googleapis.com/ajax/libs/$package/$version/$file',
  bootstrap:  'https://maxcdn.bootstrapcdn.com/$package/$version/$file',
  bootswatch: 'https://maxcdn.bootstrapcdn.com/bootswatch/$version/$package/$file',
}
var packageList = [
  'packages/strapdownjs/pakr.json',
  'cdnall_data.json',
]

Dias(function(dias) {
  var logVariables  = { server: { id: pkg.name, ver: pkg.version, ua: dias.useragent, node: dias.node, pid: process.pid } }
  var logger        = new Logger(logVariables, false)
  var config        = {
    dir:        './tmp',
    logRequest: true,
    domain:     domain,
    skipInit:   true, // skip initial initialization in proxyPackage() below, as init will be done manually. avoids double loading
    packageDataUrl: packageList
  }
  proxyPackage(config)
  var packages = proxyPackage.init()
  apiLatest.init({ packages: packages })
  apiPackage.init({ packages: packages })

  function packageMiddle(req, res, next) {
    proxyPackage(req, function proxyResults(err, data) {
      if (err) return next(err)
      var headers = data.headers
      var body    = data.body
      if (headers.type) res.type(headers.type)
      if (headers.code && headers.code >= 400) {
        res.status(headers.code).send(body)
        return
      }
      res.send(body)

      if (config.logRequest) {
        logger.info('type: ' + headers.type + ', length: ' + data.body.length)
      }
    })
  }

  function logError(err, req, res, next) {
    if ('string' == typeof err) {
      if (err.indexOf('Not Found') >= 0) {
        logger.info(err)
        res.status(404).send({ code: 404, error: err.replace(': /', ': ') })
        return
      } else {
        logger.warn(err)
      }
    } else {
      logger.error(err)
      if (err.stack) logger.error(err.stack)
    }
    res.status(500).send({ code: 500, error: err.message || err })
  }

  process.on('uncaughtException', function (err) {
    logger.error(err)
    logger.error(err.stack)
  })

  middleServer({
    logger: logger,
    pre:    [
      middleServer.log,
      favicon,
      apiDoc,
      apiLatest,
      apiPackage
    ],
    post:   [
      packageMiddle,
      logError
    ]
  })
})
<commit_msg>definable pakr-static domain<commit_after>'use strict';

var os            = require('os')
var Dias          = require('dias')
var pkg           = require('./package.json')
var Logger        = require('ceo-logger')
var middleServer  = require('middle-server')
var proxyPackage  = require('proxy-cache-packages')
var apiDoc        = require('./modules/api-doc')
var apiLatest     = require('./modules/api-latest')
var apiPackage    = require('./modules/api-package')
var favicon       = require('serve-favicon')(__dirname + '/favicon.ico')
var pakrStatic    = process.env.STATIC_URL || 'http://pakr-static.yie.me'
var domain        = {
  pakr:       pakrStatic + '/$package/$version/$file', // proxy-cache-multi-domain override to include local files
  cdnjs:      'https://cdnjs.cloudflare.com/ajax/libs/$package/$version/$file',
  jsdelivr:   'https://cdn.jsdelivr.net/$package/$version/$file',
  google:     'https://ajax.googleapis.com/ajax/libs/$package/$version/$file',
  bootstrap:  'https://maxcdn.bootstrapcdn.com/$package/$version/$file',
  bootswatch: 'https://maxcdn.bootstrapcdn.com/bootswatch/$version/$package/$file',
}
var packageList = [
  'cdnall_data.json',
  pakrStatic + '/pakr.json',
]

Dias(function(dias) {
  var logVariables  = { server: { id: pkg.name, ver: pkg.version, ua: dias.useragent, node: dias.node, pid: process.pid } }
  var logger        = new Logger(logVariables, false)
  var config        = {
    dir:        './tmp',
    logRequest: true, // log request transformations in proxy-cache-* layers // TODO: change to debug
    domain:     domain,
    skipInit:   true, // skip initial initialization in proxyPackage() below, as init will be done manually. avoids double loading
    packageDataUrl: packageList
  }
  proxyPackage(config)
  var packages = proxyPackage.init()
  apiLatest.init({ packages: packages })
  apiPackage.init({ packages: packages })

  function packageMiddle(req, res, next) {
    proxyPackage(req, function proxyResults(err, data) {
      if (err) return next(err)
      var headers = data.headers
      var body    = data.body
      if (headers.type) res.type(headers.type)
      if (headers.code && headers.code >= 400) {
        res.status(headers.code).send(body)
        return
      }
      res.send(body)

      if (config.logRequest) {
        logger.info('type: ' + headers.type + ', length: ' + data.body.length)
      }
    })
  }

  function logError(err, req, res, next) {
    if ('string' == typeof err) {
      if (err.indexOf('Not Found') >= 0) {
        logger.info(err)
        res.status(404).send({ code: 404, error: err.replace(': /', ': ') })
        return
      } else {
        logger.warn(err)
      }
    } else {
      logger.error(err)
      if (err.stack) logger.error(err.stack)
    }
    res.status(500).send({ code: 500, error: err.message || err })
  }

  process.on('uncaughtException', function (err) {
    logger.error(err)
    logger.error(err.stack)
  })

  middleServer({
    logger: logger,
    pre:    [
      middleServer.log,
      favicon,
      apiDoc,
      apiLatest,
      apiPackage
    ],
    post:   [
      packageMiddle,
      logError
    ]
  })
})
<|endoftext|>


<commit_before>// require belongs to commonjs spec that Node uses to import modules
// node hasn't implemented the "import" feature belong to es6 yet
const express = require('express');
const app = express();

app.get('/', (req, res) => {
   res.send({hi: 'dfsdfd'});
   console.dir(this);
});

// since we are using Heroku to host this server, we need to accept the port number given by Heroku
const PORT = process.env.PORT || 5000;
app.listen(PORT);<commit_msg>change hellow message<commit_after>// require belongs to commonjs spec that Node uses to import modules
// node hasn't implemented the "import" feature belong to es6 yet
const express = require('express');
const app = express();

app.get('/', (req, res) => {
   res.send({hi: 'sdfsf'});
   console.dir(this);
});

// since we are using Heroku to host this server, we need to accept the port number given by Heroku
const PORT = process.env.PORT || 5000;
app.listen(PORT);<|endoftext|>


<commit_before>var express = require('express');
var app = express();
var config = require('/etc/piksha/config')

app.get('/', function (req, res) {
  res.send(config.greeting);
});

app.listen(config.port);
<commit_msg>Fixing build.<commit_after>var express = require('express');
var app = express();
var config = require('/etc/piksha/config');

app.get('/', function (req, res) {
  res.send(config.greeting);
});

app.listen(config.port);
<|endoftext|>


<commit_before>import twig from 'twig';
import url from 'url';
import request from 'request';
import fs from 'fs';

// TODO: Split code into modules
export default function (req, res, next) {

  const options = {
    url: 'http://localhost:' + (process.env.PORT || 3000) + '/api'
  };

  let parsed = url.parse(req.url);
  let pathname = parsed.pathname;
  let file;

  if (!pathname.match(/api/) && !pathname.match(/\.(.*)$/)) {

    let data = parsed.path;

    if (parsed.pathname === '/') {
      file = 'front';
      data = '/front/';
    } else {
      file = pathname.split('/')[1];
    }

    let template = 'dist/views/page/' + file + '.twig';

    if (!fs.existsSync(template)) {
      console.log('Template not found');
      next();
    }

    request.get({url: options.url + data}, (error, response, body) => {

      if (error) {
        next();
      }

      if (response.statusCode === 404) {
        template = 'dist/views/page/404.twig';
      }

      twig.cache(false);
      twig.renderFile(
        template,
        JSON.parse(body),
        (err, html) => {
          res.end(html);
        }
      );

    });

  } else {
    next();
  }

}
<commit_msg>Apply `Content-Type` to response (#39)<commit_after>import twig from 'twig';
import url from 'url';
import request from 'request';
import fs from 'fs';

// TODO: Split code into modules
export default function (req, res, next) {

  const options = {
    url: 'http://localhost:' + (process.env.PORT || 3000) + '/api'
  };

  let parsed = url.parse(req.url);
  let pathname = parsed.pathname;
  let file;

  if (!pathname.match(/api/) && !pathname.match(/\.(.*)$/)) {

    let data = parsed.path;

    if (parsed.pathname === '/') {
      file = 'front';
      data = '/front/';
    } else {
      file = pathname.split('/')[1];
    }

    let template = 'dist/views/page/' + file + '.twig';

    if (!fs.existsSync(template)) {
      console.log('Template not found');
      next();
    }

    request.get({url: options.url + data}, (error, response, body) => {

      if (error) {
        next();
      }

      if (response.statusCode === 404) {
        template = 'dist/views/page/404.twig';
      }

      twig.cache(false);
      twig.renderFile(
        template,
        JSON.parse(body),
        (err, html) => {
          res.set({'Content-Type': 'text/html; charset=UTF-8'});
          res.end(html);
        }
      );

    });

  } else {
    next();
  }

}
<|endoftext|>


<commit_before>'use strict';

class WaterfallPromises {
  constructor(promiseFunc) {
    this.nextPromiseFunc = promiseFunc;
  }

  gen(args) {
    this.data = args;
    this.results = [];
    this.promise = Promise.resolve(true);

    return this.start();
  }

  start() {
    return this.promise.then((res) => {
      this.results.push(res);

      if (!this.data.length) {
        return Promise.resolve(this.results.slice(1));
      }

      const nextArg = this.data.shift();
      this.promise = this.nextPromiseFunc(nextArg);
      return this.start();
    });
  }
};

module.exports = WaterfallPromises;
<commit_msg>bugfix cut reference arguments<commit_after>'use strict';

class WaterfallPromises {
  constructor(promiseFunc) {
    this.nextPromiseFunc = promiseFunc;
  }

  gen(args) {
    this.data = (args || []).slice(0);
    this.results = [];
    this.promise = Promise.resolve(true);

    return this.start();
  }

  start() {
    return this.promise.then((res) => {
      this.results.push(res);

      if (!this.data.length) {
        return Promise.resolve(this.results.slice(1));
      }

      const nextArg = this.data.shift();
      this.promise = this.nextPromiseFunc(nextArg);
      return this.start();
    });
  }
};

module.exports = WaterfallPromises;
<|endoftext|>


<commit_before>#!/usr/bin/env node

var fs   = require('fs'),
    url  = require('url'),
    templates = require('./templates'),
    Server = require('./server').Server;

Server.new(function (req, res) {
    console.log('req.url', req.url);
    var parsedUrl = url.parse(req.url, true);
    var pathname = parsedUrl.pathname;

    fs.stat('.' + pathname, function (err, stats) {
        if(err && err.code === "ENOENT") {
            Server.notFound(res);
        } else if (err) {
            Server.serverError(res, err);
        } else if(stats.isDirectory()) {
            res.writeHead(200, Server.contentTypes['text/html']);

            fs.readdir('.' +pathname, function(err, files) {
                if (err) {
                    Server.serverError(res, err);
                }
                var baseUrl = pathname.match(/^\/$/)? '': pathname+'/';
                res.end(templates.main({baseUrl: baseUrl, files: files}));
            });
        } else {
            var contentType = Server.mimetype(pathname);
            res.writeHead(200, Server.contentTypes[contentType]);
            fs.readFile('.' + pathname, function(err, data){
                if(err) { throw err; }
                res.end(data);
            });
        }
    });
});
<commit_msg>Normalize path<commit_after>#!/usr/bin/env node

var fs   = require('fs'),
    path = require('path'),
    url  = require('url'),
    templates = require('./templates'),
    Server = require('./server').Server;

Server.new(function (req, res) {
    console.log(req.url);
    var parsedUrl = url.parse(req.url, true);
    var pathname = path.normalize(parsedUrl.pathname);

    fs.stat('.' + pathname, function (err, stats) {
        if(err && err.code === "ENOENT") {
            Server.notFound(res);
        } else if (err) {
            Server.serverError(res, err);
        } else if(stats.isDirectory()) {
            res.writeHead(200, Server.contentTypes['text/html']);

            fs.readdir('.' + pathname, function(err, files) {
                if (err) {
                    Server.serverError(res, err);
                }
                var baseUrl = pathname.match(/^\/$/)? '': pathname + '/';
                res.end(templates.main({baseUrl: baseUrl, files: files}));
            });
        } else {
            var contentType = Server.mimetype(pathname);
            res.writeHead(200, Server.contentTypes[contentType]);
            fs.readFile('.' + pathname, function(err, data){
                if(err) { throw err; }
                res.end(data);
            });
        }
    });
});
<|endoftext|>


<commit_before>module.exports = function bootstrap(str) {
  return function bootstrap(style) {
    var walk = require('rework-walk');
    walk(style, function(rule, node) {
      if (!rule.selectors) return rule;

      rule.selectors = rule.selectors.map(function(selector) {
        if (selector.indexOf('html') === 0) {
          // replace
          return selector.replace('html', 'html ' + str);
        }
        if (selector.indexOf('body') === 0) {
          // replace
          return selector.replace('body', 'body ' + str);
        } else if (selector.indexOf('.modal-backdrop') >= 0 || selector.indexOf('.fade') >= 0) {
          // ignore
          return selector;
        } else {
          // prepend
          return str + ' ' + selector;
        }
      });
    });
  }
};<commit_msg>ignore @font-face<commit_after>module.exports = function bootstrap(str) {
  return function bootstrap(style) {
    var walk = require('rework-walk');
    walk(style, function(rule, node) {
      if (!rule.selectors) return rule;

      rule.selectors = rule.selectors.map(function(selector) {
        if (selector.indexOf('html') === 0) {
          // replace
          return selector.replace('html', 'html ' + str);
        }
        if (selector.indexOf('body') === 0) {
          // replace
          return selector.replace('body', 'body ' + str);
        } else if (selector.indexOf('.modal-backdrop') >= 0 || selector.indexOf('.fade') >= 0 || selector.indexOf('font-face') >= 0) {
          // ignore
          return selector;
        } else {
          // prepend
          return str + ' ' + selector;
        }
      });
    });
  }
};
<|endoftext|>


<commit_before>
const depictsWholeNumber = require('depicts-whole-number').onlySafeNumbers
const c = {
  ESCAPE_CHAR: '\\',
  KEY_SEPARATOR: '.',
  EMPTY_STRING: '',
  REGEX: {
    SQUARE_BRACKETS: /[\[\]]/g,
    EXPLICIT_ARRAY: /\[(0|[1-9][0-9]*)\]/,
    EXPLICIT_ARRAY_GM: /\[(0|[1-9][0-9]*)\]/g
  }
}
const defaultOptions = {
  CustomDelimiter: c.KEY_SEPARATOR,
  AutocreateArrays: true,
  ExplicitArrays: false,
  CircularityCheck: false,
  MaxDepth: 0
}

/**
 * ObjectFx static class.
 * @class
 */
class ObjectFx {

  /**
   * Checks for valid array index
   * @param {String} s
   * @return {Boolean}
   */
  static _isValidArrayIndex (s) {
    return depictsWholeNumber(s)
  }

  /**
   * Checks for valid array index within square brackets (named 'explicit array' here)
   * @param {String} s
   * @return {Boolean}
   */
  static _containsValidArrayIndex (s) {
    const result = s.match(c.REGEX.EXPLICIT_ARRAY)
    if (!result) {
      return false
    }
    return depictsWholeNumber(result[1])
  }

  /**
   * Expands (unflattens) a flattened object
   * @param {Object} objFlat - flattened object
   * @param {Object} userOptions - options
   * @return {Object}
   */
  static unflatten (objFlat, userOptions) {
    return this.expand(objFlat, userOptions)
  }
  static expand (objFlat, userOptions) {
    if (Object.prototype.toString.call(objFlat) !== '[object Object]') {
      return null
    }
    const options = Object.prototype.toString.call(userOptions) === '[object Object]' ? Object.assign({}, defaultOptions, userOptions) : defaultOptions
    const prefix = 'root' + options.CustomDelimiter
    const regexConsecutiveSeparators = new RegExp('\\' + options.CustomDelimiter + '{2,}', 'g')
    const regexSurroundingSeparators = new RegExp('^\\' + options.CustomDelimiter + '+|\\' + options.CustomDelimiter + '+$', 'g')
    const objExp = {}
    let keys = Object.keys(objFlat)
    for (let i = 0, kln = keys.length; i < kln; i++) {
      const origKey = keys[i]
      let currKey = prefix + origKey
      if (options.ExplicitArrays) {
        currKey = currKey
          .replace(c.REGEX.EXPLICIT_ARRAY_GM, options.CustomDelimiter + '[$1]' + options.CustomDelimiter)
          .replace(regexConsecutiveSeparators, options.CustomDelimiter)
          .replace(regexSurroundingSeparators, c.EMPTY_STRING)
      }
      const chunks = currKey.split(options.CustomDelimiter)
      let obj = objExp
      for (let j = 0, cln = chunks.length; j < cln; j++) {
        let currChunk = chunks[j]
        let nextChunk = chunks[j + 1]
        if (options.ExplicitArrays) {
          currChunk = currChunk.replace(c.REGEX.SQUARE_BRACKETS, c.EMPTY_STRING)
        }
        if (!obj[currChunk]) {
          if (j > cln - 2) {
            obj[currChunk] = objFlat[origKey]
          } else {
            if ((options.AutocreateArrays && this._isValidArrayIndex(nextChunk)) ||
              (options.ExplicitArrays && this._containsValidArrayIndex(nextChunk))) {
              obj[currChunk] = []
            } else {
              obj[currChunk] = {}
            }
          }
        }
        if (options.ExplicitArrays && this._containsValidArrayIndex(currChunk)) {
          currChunk.replace(c.REGEX.SQUARE_BRACKETS, c.EMPTY_STRING)
        }
        obj = obj[currChunk]
      }
    }
    return objExp.root
  }

  /**
   * Flattens an object
   * @param {Object} objExp
   * @param {Object} userOptions - options
   * @return {Object}
   */
  static flatten (objExp, userOptions) {
    if (Object.prototype.toString.call(objExp) !== '[object Object]') {
      return null
    }
    const options = Object.prototype.toString.call(userOptions) === '[object Object]' ? Object.assign({}, defaultOptions, userOptions) : defaultOptions
    if (options.CircularityCheck) {
      try {
        JSON.stringify(objExp)
      } catch (err) {
        if (err.message.match(/circular structure/ig)) {
          throw TypeError('Unable to flatten circular structure')
        }
      }
    }

    let result = {}
    const recurse = (cur, prop, lev) => {
      if (options.MaxDepth > 0 && lev >= options.MaxDepth) {
        result[prop] = cur
        return
      }
      lev++
      if (typeof cur !== 'object') { // Object(cur) !== cur
        result[prop] = cur
      } else if (Array.isArray(cur)) { // https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Global_Objects/Array/isArray
        for (var i = 0, l = cur.length; i < l; i++) {
          if (options.ExplicitArrays) {
            recurse(cur[i], prop + '[' + i + ']', lev)
          } else {
            let prefix = prop
            if (prefix) {
              prefix += options.CustomDelimiter
            }
            recurse(cur[i], prefix + i, lev)
          }
        }
        if (l === 0) {
          result[prop] = []
        }
      } else {
        if (Object.prototype.toString.call(cur) === '[object Object]') { // cur && cur.toString() === '[object Object]'
          for (var p in cur) {
            recurse(cur[p], prop ? prop + options.CustomDelimiter + p : p, lev)
          }
        } else {
          result[prop] = cur
        }
      }
    }
    recurse(objExp, c.EMPTY_STRING, 0)
    return result
  }

}

module.exports = ObjectFx
<commit_msg>change flatten method: return null for circular objects when checked<commit_after>
const depictsWholeNumber = require('depicts-whole-number').onlySafeNumbers
const c = {
  ESCAPE_CHAR: '\\',
  KEY_SEPARATOR: '.',
  EMPTY_STRING: '',
  REGEX: {
    SQUARE_BRACKETS: /[\[\]]/g,
    EXPLICIT_ARRAY: /\[(0|[1-9][0-9]*)\]/,
    EXPLICIT_ARRAY_GM: /\[(0|[1-9][0-9]*)\]/g
  }
}
const defaultOptions = {
  CustomDelimiter: c.KEY_SEPARATOR,
  AutocreateArrays: true,
  ExplicitArrays: false,
  CircularityCheck: false,
  MaxDepth: 0
}

/**
 * ObjectFx static class.
 * @class
 */
class ObjectFx {

  /**
   * Checks for valid array index
   * @param {String} s
   * @return {Boolean}
   */
  static _isValidArrayIndex (s) {
    return depictsWholeNumber(s)
  }

  /**
   * Checks for valid array index within square brackets (named 'explicit array' here)
   * @param {String} s
   * @return {Boolean}
   */
  static _containsValidArrayIndex (s) {
    const result = s.match(c.REGEX.EXPLICIT_ARRAY)
    if (!result) {
      return false
    }
    return depictsWholeNumber(result[1])
  }

  /**
   * Expands (unflattens) a flattened object
   * @param {Object} objFlat - flattened object
   * @param {Object} userOptions - options
   * @return {Object}
   */
  static unflatten (objFlat, userOptions) {
    return this.expand(objFlat, userOptions)
  }
  static expand (objFlat, userOptions) {
    if (Object.prototype.toString.call(objFlat) !== '[object Object]') {
      return null
    }
    const options = Object.prototype.toString.call(userOptions) === '[object Object]' ? Object.assign({}, defaultOptions, userOptions) : defaultOptions
    const prefix = 'root' + options.CustomDelimiter
    const regexConsecutiveSeparators = new RegExp('\\' + options.CustomDelimiter + '{2,}', 'g')
    const regexSurroundingSeparators = new RegExp('^\\' + options.CustomDelimiter + '+|\\' + options.CustomDelimiter + '+$', 'g')
    const objExp = {}
    let keys = Object.keys(objFlat)
    for (let i = 0, kln = keys.length; i < kln; i++) {
      const origKey = keys[i]
      let currKey = prefix + origKey
      if (options.ExplicitArrays) {
        currKey = currKey
          .replace(c.REGEX.EXPLICIT_ARRAY_GM, options.CustomDelimiter + '[$1]' + options.CustomDelimiter)
          .replace(regexConsecutiveSeparators, options.CustomDelimiter)
          .replace(regexSurroundingSeparators, c.EMPTY_STRING)
      }
      const chunks = currKey.split(options.CustomDelimiter)
      let obj = objExp
      for (let j = 0, cln = chunks.length; j < cln; j++) {
        let currChunk = chunks[j]
        let nextChunk = chunks[j + 1]
        if (options.ExplicitArrays) {
          currChunk = currChunk.replace(c.REGEX.SQUARE_BRACKETS, c.EMPTY_STRING)
        }
        if (!obj[currChunk]) {
          if (j > cln - 2) {
            obj[currChunk] = objFlat[origKey]
          } else {
            if ((options.AutocreateArrays && this._isValidArrayIndex(nextChunk)) ||
              (options.ExplicitArrays && this._containsValidArrayIndex(nextChunk))) {
              obj[currChunk] = []
            } else {
              obj[currChunk] = {}
            }
          }
        }
        if (options.ExplicitArrays && this._containsValidArrayIndex(currChunk)) {
          currChunk.replace(c.REGEX.SQUARE_BRACKETS, c.EMPTY_STRING)
        }
        obj = obj[currChunk]
      }
    }
    return objExp.root
  }

  /**
   * Flattens an object
   * @param {Object} objExp
   * @param {Object} userOptions - options
   * @return {Object}
   */
  static flatten (objExp, userOptions) {
    if (Object.prototype.toString.call(objExp) !== '[object Object]') {
      return null
    }
    const options = Object.prototype.toString.call(userOptions) === '[object Object]' ? Object.assign({}, defaultOptions, userOptions) : defaultOptions
    if (options.CircularityCheck) {
      try {
        JSON.stringify(objExp)
      } catch (err) {
        if (err.message.match(/circular structure/ig)) {
          // throw TypeError('Unable to flatten circular structure')
          return null
        }
      }
    }

    let result = {}
    const recurse = (cur, prop, lev) => {
      if (options.MaxDepth > 0 && lev >= options.MaxDepth) {
        result[prop] = cur
        return
      }
      lev++
      if (typeof cur !== 'object') { // Object(cur) !== cur
        result[prop] = cur
      } else if (Array.isArray(cur)) { // https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Global_Objects/Array/isArray
        for (var i = 0, l = cur.length; i < l; i++) {
          if (options.ExplicitArrays) {
            recurse(cur[i], prop + '[' + i + ']', lev)
          } else {
            let prefix = prop
            if (prefix) {
              prefix += options.CustomDelimiter
            }
            recurse(cur[i], prefix + i, lev)
          }
        }
        if (l === 0) {
          result[prop] = []
        }
      } else {
        if (Object.prototype.toString.call(cur) === '[object Object]') { // cur && cur.toString() === '[object Object]'
          for (var p in cur) {
            recurse(cur[p], prop ? prop + options.CustomDelimiter + p : p, lev)
          }
        } else {
          result[prop] = cur
        }
      }
    }
    recurse(objExp, c.EMPTY_STRING, 0)
    return result
  }

}

module.exports = ObjectFx
<|endoftext|>


<commit_before>// @flow

const RNI18n = require('react-native').NativeModules.RNI18n;
const I18nJs = require('i18n-js');

I18nJs.locale = RNI18n.languages[0];
export const getLanguages = RNI18n.getLanguages;
export default I18nJs;
<commit_msg>Add a warning when the package is not linked<commit_after>// @flow

const RNI18n = require('react-native').NativeModules.RNI18n;
const I18nJs = require('i18n-js');

if (typeof RNI18n !== 'undefined') {
  I18nJs.locale = RNI18n.languages[0];
} else if (__DEV__) {
  console.warn('react-native-i18n module is not correctly linked');
}

export const getLanguages = RNI18n.getLanguages;
export default I18nJs;
<|endoftext|>