1
0
Fork 0
mirror of https://github.com/openstf/stf synced 2025-10-04 02:09:32 +02:00

Fix all lib/ files with ESLint rules with 0 errors.

This commit is contained in:
Gunther Brunner 2016-01-19 20:52:38 +09:00
parent 994977ea94
commit 434f63b3a9
69 changed files with 793 additions and 764 deletions

View file

@ -48,7 +48,7 @@
"no-new-wrappers": 2,
"no-new": 2,
"no-octal-escape": 2,
"no-octal": 2,
"no-octal": 1, // TODO: accept until we use ES6 0o755 notation
"no-param-reassign": 2,
"no-process-env": 0, // `2` is recommended
"no-proto": 2,
@ -62,7 +62,7 @@
"no-useless-call": 2, // `2` is recommended
"no-useless-concat": 2,
"no-void": 2,
"no-warning-comments": 1, // `[0, { "terms": ["todo", "fixme", "xxx"], "location": "start" }]` is recommended
"no-warning-comments": [1, { "terms": ["todo", "fixme", "@todo", "@fixme"]}], // `[0, { "terms": ["todo", "fixme", "xxx"], "location": "start" }]` is recommended
"no-with": 2,
"radix": 1, // `2` is recommended
"vars-on-top": 0, // `2` is recommended TODO: review this
@ -78,7 +78,7 @@
"no-label-var": 2,
"no-shadow-restricted-names": 2,
"no-shadow": 0, // TODO: 1 may be ok
"no-undefined": 2,
"no-undefined": 1,
"no-unused-vars": 1,
"no-use-before-define": 1, // TODO: 0 or 2 may be ok, sometimes there are ciclic dependencies
@ -86,7 +86,7 @@
"array-bracket-spacing": [2, "never"], // optionally set `[2, "never", {"singleValue": true, "objectsInArrays": true, "arraysInArrays": true}]`
"block-spacing": [2, "always"], // optionally set `[2, "always"]`
"brace-style": [2, "stroustrup", {"allowSingleLine": false}],
"camelcase": [2, {"properties": "always"}], // TODO: 2 might be too much
"camelcase": [2, {"properties": "never"}], // TODO: 2 might be too much
"comma-spacing": [2, {"before": false, "after": true}],
"comma-style": [1, "first"], // optionally set `[2, "first", {"exceptions": {"ArrayExpression": true, "ObjectExpression": true}}]`
"computed-property-spacing": [2, "never"],

View file

@ -903,7 +903,7 @@ program
.description('migrates the database to the latest version')
.action(function() {
var log = logger.createLogger('cli:migrate')
, db = require('./db')
var db = require('./db')
db.setup()
.then(function() {
@ -924,21 +924,21 @@ program
, 1)
.action(function(model, options) {
var log = logger.createLogger('cli:generate-fake-device')
, fake = require('./util/fakedevice')
, n = options.number
var fake = require('./util/fakedevice')
var n = options.number
function next() {
function nextDevice() {
return fake.generate(model)
.then(function(serial) {
log.info('Created fake device "%s"', serial)
if (--n) {
return next()
return nextDevice()
}
})
}
next()
nextDevice()
.then(function() {
process.exit(0)
})
@ -1069,7 +1069,7 @@ program
, 'whether to lock rotation when devices are being used')
.action(function(serials, options) {
var log = logger.createLogger('cli:local')
, procutil = require('./util/procutil')
var procutil = require('./util/procutil')
// Each forked process waits for signals to stop, and so we run over the
// default limit of 10. So, it's not a leak, but a refactor wouldn't hurt.
@ -1156,7 +1156,10 @@ program
'http://%s:%d/auth/%s/'
, options.publicIp
, options.poorxyPort
, ({oauth2: 'oauth', saml2: 'saml'}[options.authType]) || options.authType
, {
oauth2: 'oauth'
, saml2: 'saml'
}[options.authType] || options.authType
)
, '--websocket-url', util.format(
'http://%s:%d/'

View file

@ -320,7 +320,7 @@ dbapi.saveUserAccessToken = function(email, token) {
dbapi.removeUserAccessToken = function(email, title) {
return db.run(r.table('accessTokens').getAll(email, {
index: 'email'
}).filter({'title': title}).delete())
}).filter({title: title}).delete())
}
dbapi.loadAccessTokens = function(email) {

View file

@ -48,7 +48,7 @@ function connect() {
// Export connection as a Promise
db.connect = (function() {
var connection
, queue = []
var queue = []
lifecycle.observe(function() {
if (connection) {

View file

@ -28,7 +28,7 @@ module.exports = function(conn) {
function createIndex(table, index, options) {
var args = [index]
, rTable = r.table(table)
var rTable = r.table(table)
if (options) {
if (options.indexFunction) {

View file

@ -26,8 +26,8 @@ var markdownServe = require('markdown-serve')
module.exports = function(options) {
var log = logger.createLogger('app')
, app = express()
, server = http.createServer(app)
var app = express()
var server = http.createServer(app)
app.use('/static/wiki', markdownServe.middleware({
rootDirectory: pathutil.root('node_modules/stf-wiki')
@ -50,9 +50,9 @@ module.exports = function(options) {
}))
}
else {
log.info('Using webpack')
// Keep webpack-related requires here, as our prebuilt package won't
// have them at all.
log.info('Using webpack')
var webpackServerConfig = require('./../../../webpack.config').webpackServer
app.use('/static/app/build',
require('./middleware/webpack')(webpackServerConfig))

View file

@ -8,7 +8,7 @@ module.exports = function(options) {
if (req.query.jwt) {
// Coming from auth client
var data = jwtutil.decode(req.query.jwt, options.secret)
, redir = urlutil.removeParam(req.url, 'jwt')
var redir = urlutil.removeParam(req.url, 'jwt')
if (data) {
// Redirect once to get rid of the token
dbapi.saveUserAfterLogin({

View file

@ -14,9 +14,9 @@ var globalOptions = require('../../../../webpack.config').webpack
// Similar to webpack-dev-middleware, but integrates with our custom
// lifecycle, behaves more like normal express middleware, and removes
// all unnecessary features.
module.exports = function(options) {
module.exports = function(localOptions) {
var log = logger.createLogger('middleware:webpack')
options = _.defaults(options || {}, globalOptions)
var options = _.defaults(localOptions || {}, globalOptions)
var compiler = webpack(options)
var fs = compiler.outputFileSystem = new MemoryFileSystem()
@ -77,13 +77,12 @@ module.exports = function(options) {
if (valid) {
return Promise.resolve()
}
else {
log.info('Waiting for bundle to finish')
var resolver = Promise.defer()
queue.push(resolver)
return resolver.promise
}
}
return function(req, res, next) {
var parsedUrl = url.parse(req.url)

View file

@ -18,8 +18,8 @@ var lifecycle = require('../../util/lifecycle')
module.exports = function(options) {
var log = logger.createLogger('auth-ldap')
, app = express()
, server = Promise.promisifyAll(http.createServer(app))
var app = express()
var server = Promise.promisifyAll(http.createServer(app))
lifecycle.observe(function() {
log.info('Waiting for client connections to end')
@ -46,7 +46,7 @@ module.exports = function(options) {
app.use('/static/auth/ldap', serveStatic(pathutil.resource('auth/ldap')))
app.use(function(req, res, next) {
res.cookie('XSRF-TOKEN', req.csrfToken());
res.cookie('XSRF-TOKEN', req.csrfToken())
next()
})

View file

@ -17,8 +17,8 @@ var lifecycle = require('../../util/lifecycle')
module.exports = function(options) {
var log = logger.createLogger('auth-mock')
, app = express()
, server = Promise.promisifyAll(http.createServer(app))
var app = express()
var server = Promise.promisifyAll(http.createServer(app))
lifecycle.observe(function() {
log.info('Waiting for client connections to end')
@ -45,7 +45,7 @@ module.exports = function(options) {
app.use('/static/auth/mock', serveStatic(pathutil.resource('auth/mock')))
app.use(function(req, res, next) {
res.cookie('XSRF-TOKEN', req.csrfToken());
res.cookie('XSRF-TOKEN', req.csrfToken())
next()
})

View file

@ -10,8 +10,8 @@ var Strategy = require('./strategy')
module.exports = function(options) {
var log = logger.createLogger('auth-oauth2')
, app = express()
, server = http.createServer(app)
var app = express()
var server = http.createServer(app)
app.set('strict routing', true)
app.set('case sensitive routing', true)

View file

@ -18,14 +18,13 @@ Strategy.prototype.userProfile = function(accessToken, callback) {
if (err) {
return callback(err)
}
else {
try {
return callback(null, JSON.parse(data))
}
catch (err) {
return callback(err)
}
}
})
}

View file

@ -13,8 +13,8 @@ var jwtutil = require('../../util/jwtutil')
module.exports = function(options) {
var log = logger.createLogger('auth-saml2')
, app = express()
, server = http.createServer(app)
var app = express()
var server = http.createServer(app)
app.set('strict routing', true)
app.set('case sensitive routing', true)
@ -22,11 +22,11 @@ module.exports = function(options) {
app.use(passport.initialize())
passport.serializeUser(function(user, done) {
done(null, user);
});
done(null, user)
})
passport.deserializeUser(function(user, done) {
done(null, user);
});
done(null, user)
})
var verify = function(profile, done) {
return done(null, profile)

View file

@ -113,8 +113,8 @@ module.exports = syrup.serial()
router.on(wire.AccountAddMessage, function(channel, message) {
var reply = wireutil.reply(options.serial)
var type = "com.google"
var account = message.user + "@gmail.com";
var type = 'com.google'
var account = message.user + '@gmail.com'
log.info('Adding Google Account automatedly')

View file

@ -51,8 +51,17 @@ module.exports = syrup.serial()
function compareIgnoreCase(a, b) {
var la = (a || '').toLowerCase()
, lb = (b || '').toLowerCase()
return la === lb ? 0 : (la < lb ? -1 : 1)
var lb = (b || '').toLowerCase()
if (la === lb) {
return 0
}
else if (la < lb) {
return -1
}
else {
return 1
}
}
function updateBrowsers(data) {

View file

@ -40,7 +40,6 @@ module.exports = syrup.serial()
group.on('leave', function() {
plugin.removePackages()
})
})
.return(plugin)
})

View file

@ -18,8 +18,8 @@ module.exports = syrup.serial()
.dependency(require('./util/urlformat'))
.define(function(options, adb, router, push, group, solo, urlformat) {
var log = logger.createLogger('device:plugins:connect')
, plugin = Object.create(null)
, activeServer = null
var plugin = Object.create(null)
var activeServer = null
plugin.port = options.connectPort
plugin.url = urlformat(options.connectUrlPattern, plugin.port)

View file

@ -44,7 +44,7 @@ module.exports = syrup.serial()
if (/closed/.test(err.message) && times > 1) {
return Promise.delay(delay)
.then(function() {
return tryConnect(--times, delay * 2)
return tryConnect(times - 1, delay * 2)
})
}
return Promise.reject(err)

View file

@ -5,6 +5,115 @@ var net = require('net')
var ForwardReader = require('./reader')
var ForwardWriter = require('./writer')
// Handles a single connection
function DestHandler(id, conn, options) {
var dest = net.connect({
host: options.targetHost
, port: options.targetPort
})
var writer = dest.pipe(new ForwardWriter(id))
// We can't just pipe to conn because we don't want to end it
// when the dest closes. Instead we'll send a special packet
// to it (which is handled by the writer).
function maybePipeManually() {
var chunk
while ((chunk = writer.read())) {
if (!conn.write(chunk)) {
break
}
}
}
function readableListener() {
maybePipeManually()
}
function drainListener() {
maybePipeManually()
}
function endListener() {
conn.removeListener('drain', drainListener)
writer.removeListener('readable', readableListener)
this.emit('end')
}
function errorListener() {
writer.end()
}
writer.on('end', endListener.bind(this))
writer.on('readable', readableListener)
dest.on('error', errorListener)
conn.on('drain', drainListener)
this.end = function() {
dest.end()
}
this.write = function(chunk) {
dest.write(chunk)
}
events.EventEmitter.call(this)
}
util.inherits(DestHandler, events.EventEmitter)
// Handles a single port
function ForwardHandler(conn, options) {
var destHandlersById = Object.create(null)
function endListener() {
this.emit('end')
}
function packetEndListener(id) {
delete destHandlersById[id]
}
function packetListener(id, packet) {
var dest = destHandlersById[id]
if (packet) {
if (!dest) {
// Let's create a new connection
dest = destHandlersById[id] = new DestHandler(id, conn, options)
dest.on('end', packetEndListener.bind(null, id))
}
dest.write(packet)
}
else {
// It's a simulated fin packet
if (dest) {
dest.end()
}
}
}
function readableListener() {
// No-op but must exist so that we get the 'end' event.
}
conn.pipe(new ForwardReader())
.on('end', endListener.bind(this))
.on('packet', packetListener)
.on('readable', readableListener)
this.options = options
this.end = function() {
conn.end()
}
events.EventEmitter.call(this)
}
util.inherits(ForwardHandler, events.EventEmitter)
// Handles multiple ports
function ForwardManager() {
var handlersById = Object.create(null)
@ -61,113 +170,4 @@ function ForwardManager() {
util.inherits(ForwardManager, events.EventEmitter)
// Handles a single port
function ForwardHandler(conn, options) {
var destHandlersById = Object.create(null)
function endListener() {
this.emit('end')
}
function packetEndListener(id) {
delete destHandlersById[id]
}
function packetListener(id, packet) {
var dest = destHandlersById[id]
if (packet) {
if (!dest) {
// Let's create a new connection
dest = destHandlersById[id] = new DestHandler(id, conn, options)
dest.on('end', packetEndListener.bind(null, id))
}
dest.write(packet)
}
else {
// It's a simulated fin packet
if (dest) {
dest.end()
}
}
}
function readableListener() {
// No-op but must exist so that we get the 'end' event.
}
conn.pipe(new ForwardReader())
.on('end', endListener.bind(this))
.on('packet', packetListener)
.on('readable', readableListener)
this.options = options
this.end = function() {
conn.end()
}
events.EventEmitter.call(this)
}
util.inherits(ForwardHandler, events.EventEmitter)
// Handles a single connection
function DestHandler(id, conn, options) {
function endListener() {
conn.removeListener('drain', drainListener)
writer.removeListener('readable', readableListener)
this.emit('end')
}
function errorListener() {
writer.end()
}
function readableListener() {
maybePipeManually()
}
function drainListener() {
maybePipeManually()
}
// We can't just pipe to conn because we don't want to end it
// when the dest closes. Instead we'll send a special packet
// to it (which is handled by the writer).
function maybePipeManually() {
var chunk
while ((chunk = writer.read())) {
if (!conn.write(chunk)) {
break
}
}
}
var dest = net.connect({
host: options.targetHost
, port: options.targetPort
})
.on('error', errorListener)
var writer = dest.pipe(new ForwardWriter(id))
.on('end', endListener.bind(this))
.on('readable', readableListener)
conn.on('drain', drainListener)
this.end = function() {
dest.end()
}
this.write = function(chunk) {
dest.write(chunk)
}
events.EventEmitter.call(this)
}
util.inherits(DestHandler, events.EventEmitter)
module.exports = ForwardManager

View file

@ -11,9 +11,9 @@ function ForwardWriter(target) {
util.inherits(ForwardWriter, stream.Transform)
ForwardWriter.prototype._transform = function(chunk, encoding, done) {
var header
, length
ForwardWriter.prototype._transform = function(fullChunk, encoding, done) {
var chunk = fullChunk
var header, length
do {
length = Math.min(MAX_PACKET_SIZE, chunk.length)

View file

@ -19,8 +19,8 @@ module.exports = syrup.serial()
.dependency(require('../support/channels'))
.define(function(options, solo, ident, service, router, push, sub, channels) {
var log = logger.createLogger('device:plugins:group')
, currentGroup = null
, plugin = new events.EventEmitter()
var currentGroup = null
var plugin = new events.EventEmitter()
plugin.get = Promise.method(function() {
if (!currentGroup) {

View file

@ -27,7 +27,7 @@ module.exports = syrup.serial()
router.on(wire.InstallMessage, function(channel, message) {
var manifest = JSON.parse(message.manifest)
, pkg = manifest.package
var pkg = manifest.package
log.info('Installing package "%s" from "%s"', pkg, message.href)
@ -98,8 +98,8 @@ module.exports = syrup.serial()
pushApp()
.then(function(apk) {
var start = 50
, end = 90
, guesstimate = start
var end = 90
var guesstimate = start
sendProgress('installing_app', guesstimate)
return promiseutil.periodicNotify(

View file

@ -13,8 +13,8 @@ module.exports = syrup.serial()
.dependency(require('./group'))
.define(function(options, adb, router, push, group) {
var log = logger.createLogger('device:plugins:logcat')
, plugin = Object.create(null)
, activeLogcat = null
var plugin = Object.create(null)
var activeLogcat = null
plugin.start = function(filters) {
return group.get()

View file

@ -13,12 +13,12 @@ module.exports = syrup.serial()
log.info('Will mute master volume during use')
group.on('join', function() {
log.info('Muting master volume');
log.info('Muting master volume')
service.setMasterMute(true)
})
group.on('leave', function() {
log.info('Unmuting master volume');
log.info('Unmuting master volume')
service.setMasterMute(false)
})
}

View file

@ -176,11 +176,13 @@ module.exports = syrup.serial()
}
FrameProducer.prototype.nextFrame = function() {
var frame = null, chunk
var frame = null
var chunk
if (this.parser) {
while ((frame = this.parser.nextFrame()) === null) {
if ((chunk = this.socket.stream.read())) {
chunk = this.socket.stream.read()
if (chunk) {
this.parser.push(chunk)
}
else {
@ -243,9 +245,9 @@ module.exports = syrup.serial()
return lifecycle.fatal()
}
var match
if ((match = /^PID: (\d+)$/.exec(line))) {
this.pid = +match[1]
var match = /^PID: (\d+)$/.exec(line)
if (match) {
this.pid = Number(match[1])
this.emit('pid', this.pid)
}
@ -259,7 +261,7 @@ module.exports = syrup.serial()
}
var pidListener
return new Promise(function(resolve/*, reject*/) {
return new Promise(function(resolve) {
this.on('pid', pidListener = resolve)
}.bind(this)).bind(this)
.timeout(2000)
@ -279,7 +281,7 @@ module.exports = syrup.serial()
if (/closed/.test(err.message) && times > 1) {
return Promise.delay(delay)
.then(function() {
return tryConnect(--times, delay * 2)
return tryConnect(times - 1, delay * 2)
})
}
return Promise.reject(err)
@ -326,7 +328,7 @@ module.exports = syrup.serial()
socket.stream.removeListener('readable', this.readableListener)
var endListener
return new Promise(function(resolve/*, reject*/) {
return new Promise(function(resolve) {
socket.on('end', endListener = function() {
resolve(true)
})
@ -354,8 +356,8 @@ module.exports = syrup.serial()
}
var signum = {
'SIGTERM': -15
, 'SIGKILL': -9
SIGTERM: -15
, SIGKILL: -9
}[signal]
log.info('Sending %s to minicap', signal)
@ -478,8 +480,8 @@ module.exports = syrup.serial()
})
frameProducer.on('readable', function next() {
var frame
if ((frame = frameProducer.nextFrame())) {
var frame = frameProducer.nextFrame()
if (frame) {
Promise.settle([broadcastSet.keys().map(function(id) {
return broadcastSet.get(id).onFrame(frame)
})]).then(next)
@ -557,8 +559,8 @@ module.exports = syrup.serial()
}
ws.on('message', function(data) {
var match
if ((match = /^(on|off|(size) ([0-9]+)x([0-9]+))$/.exec(data))) {
var match = /^(on|off|(size) ([0-9]+)x([0-9]+))$/.exec(data)
if (match) {
switch (match[2] || match[1]) {
case 'on':
broadcastSet.insert(id, {
@ -570,7 +572,8 @@ module.exports = syrup.serial()
broadcastSet.remove(id)
break
case 'size':
frameProducer.updateProjection(+match[3], +match[4])
frameProducer.updateProjection(
Number(match[3]), Number(match[4]))
break
}
}

View file

@ -30,12 +30,17 @@ FrameParser.prototype.nextFrame = function() {
var bytesLeft = len - this.cursor
if (bytesLeft >= this.frameBodyLength) {
var completeBody = this.frameBody
? Buffer.concat([
var completeBody
if (this.frameBody) {
completeBody = Buffer.concat([
this.frameBody
, this.chunk.slice(this.cursor, this.cursor + this.frameBodyLength)
])
: this.chunk.slice(this.cursor, this.cursor + this.frameBodyLength)
}
else {
completeBody = this.chunk.slice(this.cursor,
this.cursor + this.frameBodyLength)
}
this.cursor += this.frameBodyLength
this.frameBodyLength = this.readFrameBytes = 0
@ -46,9 +51,13 @@ FrameParser.prototype.nextFrame = function() {
else {
// @todo Consider/benchmark continuation frames to prevent
// potential Buffer thrashing.
this.frameBody = this.frameBody
? Buffer.concat([this.frameBody, this.chunk.slice(this.cursor, len)])
: this.chunk.slice(this.cursor, len)
if (this.frameBody) {
this.frameBody =
Buffer.concat([this.frameBody, this.chunk.slice(this.cursor, len)])
}
else {
this.frameBody = this.chunk.slice(this.cursor, len)
}
this.frameBodyLength -= bytesLeft
this.readFrameBytes += bytesLeft

View file

@ -52,60 +52,6 @@ module.exports = syrup.serial()
, port: 1100
}
function openAgent() {
log.info('Launching agent')
return stopAgent()
.timeout(15000)
.then(function() {
return devutil.ensureUnusedPort(adb, options.serial, agent.port)
.timeout(10000)
})
.then(function() {
return adb.shell(options.serial, util.format(
"export CLASSPATH='%s'; exec app_process /system/bin '%s'"
, apk.path
, apk.main
))
.timeout(10000)
})
.then(function(out) {
streamutil.talk(log, 'Agent says: "%s"', out)
})
.then(function() {
return devutil.waitForPort(adb, options.serial, agent.port)
.timeout(10000)
})
.then(function(conn) {
agent.socket = conn
agent.writer = new ms.DelimitingStream()
agent.writer.pipe(conn)
return prepareForAgentDeath(conn)
})
}
function prepareForAgentDeath(conn) {
function endListener() {
var startTime = Date.now()
log.important('Agent connection ended, attempting to relaunch')
openService()
.timeout(5000)
.then(function() {
log.important('Agent relaunched in %dms', Date.now() - startTime)
})
.catch(function(err) {
log.fatal('Agent connection could not be relaunched', err.stack)
lifecycle.fatal()
})
}
conn.once('end', endListener)
conn.on('error', function(err) {
log.fatal('Agent connection had an error', err.stack)
lifecycle.fatal()
})
}
function stopAgent() {
return devutil.killProcsByComm(
adb
@ -164,34 +110,12 @@ module.exports = syrup.serial()
})
}
// The APK should be up to date at this point. If it was reinstalled, the
// service should have been automatically stopped while it was happening.
// So, we should be good to go.
function openService() {
log.info('Launching service')
return callService(util.format(
"-a '%s' -n '%s'"
, apk.startIntent.action
, apk.startIntent.component
))
.then(function() {
return devutil.waitForPort(adb, options.serial, service.port)
.timeout(15000)
})
.then(function(conn) {
service.socket = conn
service.reader = conn.pipe(new ms.DelimitedStream())
service.reader.on('data', handleEnvelope)
service.writer = new ms.DelimitingStream()
service.writer.pipe(conn)
return prepareForServiceDeath(conn)
})
}
function prepareForServiceDeath(conn) {
function endListener() {
var startTime = Date.now()
log.important('Service connection ended, attempting to relaunch')
/* eslint no-use-before-define: 0 */
openService()
.timeout(5000)
.then(function() {
@ -213,7 +137,7 @@ module.exports = syrup.serial()
function handleEnvelope(data) {
var envelope = apk.wire.Envelope.decode(data)
, message
var message
if (envelope.id !== null) {
messageResolver.resolve(envelope.id, envelope.message)
}
@ -294,6 +218,92 @@ module.exports = syrup.serial()
}
}
// The APK should be up to date at this point. If it was reinstalled, the
// service should have been automatically stopped while it was happening.
// So, we should be good to go.
function openService() {
log.info('Launching service')
return callService(util.format(
"-a '%s' -n '%s'"
, apk.startIntent.action
, apk.startIntent.component
))
.then(function() {
return devutil.waitForPort(adb, options.serial, service.port)
.timeout(15000)
})
.then(function(conn) {
service.socket = conn
service.reader = conn.pipe(new ms.DelimitedStream())
service.reader.on('data', handleEnvelope)
service.writer = new ms.DelimitingStream()
service.writer.pipe(conn)
return prepareForServiceDeath(conn)
})
}
function prepareForAgentDeath(conn) {
function endListener() {
var startTime = Date.now()
log.important('Agent connection ended, attempting to relaunch')
openService()
.timeout(5000)
.then(function() {
log.important('Agent relaunched in %dms', Date.now() - startTime)
})
.catch(function(err) {
log.fatal('Agent connection could not be relaunched', err.stack)
lifecycle.fatal()
})
}
conn.once('end', endListener)
conn.on('error', function(err) {
log.fatal('Agent connection had an error', err.stack)
lifecycle.fatal()
})
}
function openAgent() {
log.info('Launching agent')
return stopAgent()
.timeout(15000)
.then(function() {
return devutil.ensureUnusedPort(adb, options.serial, agent.port)
.timeout(10000)
})
.then(function() {
return adb.shell(options.serial, util.format(
"export CLASSPATH='%s'; exec app_process /system/bin '%s'"
, apk.path
, apk.main
))
.timeout(10000)
})
.then(function(out) {
streamutil.talk(log, 'Agent says: "%s"', out)
})
.then(function() {
return devutil.waitForPort(adb, options.serial, agent.port)
.timeout(10000)
})
.then(function(conn) {
agent.socket = conn
agent.writer = new ms.DelimitingStream()
agent.writer.pipe(conn)
return prepareForAgentDeath(conn)
})
}
function runAgentCommand(type, cmd) {
agent.writer.write(new apk.wire.Envelope(
null
, type
, cmd.encodeNB()
).encodeNB())
}
function keyEvent(data) {
return runAgentCommand(
apk.wire.MessageType.DO_KEYEVENT
@ -326,6 +336,17 @@ module.exports = syrup.serial()
return plugin.getClipboard()
}
function runServiceCommand(type, cmd) {
var resolver = Promise.defer()
var id = Math.floor(Math.random() * 0xFFFFFF)
service.writer.write(new apk.wire.Envelope(
id
, type
, cmd.encodeNB()
).encodeNB())
return messageResolver.await(id, resolver)
}
plugin.getDisplay = function(id) {
return runServiceCommand(
apk.wire.MessageType.GET_DISPLAY
@ -685,25 +706,6 @@ module.exports = syrup.serial()
})
}
function runServiceCommand(type, cmd) {
var resolver = Promise.defer()
var id = Math.floor(Math.random() * 0xFFFFFF)
service.writer.write(new apk.wire.Envelope(
id
, type
, cmd.encodeNB()
).encodeNB())
return messageResolver.await(id, resolver)
}
function runAgentCommand(type, cmd) {
agent.writer.write(new apk.wire.Envelope(
null
, type
, cmd.encodeNB()
).encodeNB())
}
return openAgent()
.then(openService)
.then(function() {

View file

@ -22,7 +22,11 @@ module.exports = syrup.serial()
.timeout(10000)
.then(function(stream) {
var resolver = Promise.defer()
, timer
var timer
function forceStop() {
stream.end()
}
function keepAliveListener(channel, message) {
clearTimeout(timer)
@ -51,10 +55,6 @@ module.exports = syrup.serial()
resolver.reject(err)
}
function forceStop() {
stream.end()
}
stream.setEncoding('utf8')
stream.on('readable', readableListener)

View file

@ -268,7 +268,7 @@ module.exports = syrup.serial()
if (/closed/.test(err.message) && times > 1) {
return Promise.delay(delay)
.then(function() {
return tryConnect(--times, delay * 2)
return tryConnect(times - 1, delay * 2)
})
}
return Promise.reject(err)
@ -315,7 +315,7 @@ module.exports = syrup.serial()
socket.stream.removeListener('readable', this.readableListener)
var endListener
return new Promise(function(resolve/*, reject*/) {
return new Promise(function(resolve) {
socket.on('end', endListener = function() {
resolve(true)
})
@ -343,8 +343,8 @@ module.exports = syrup.serial()
}
var signum = {
'SIGTERM': -15
, 'SIGKILL': -9
SIGTERM: -15
, SIGKILL: -9
}[signal]
log.info('Sending %s to minitouch', signal)
@ -395,7 +395,7 @@ module.exports = syrup.serial()
var args = chunk.toString().split(/ /g)
switch (args[0]) {
case 'v':
banner.version = +args[1]
banner.version = Number(args[1])
break
default:
throw new Error(util.format(
@ -432,7 +432,7 @@ module.exports = syrup.serial()
var args = chunk.toString().split(/ /g)
switch (args[0]) {
case '$':
banner.pid = +args[1]
banner.pid = Number(args[1])
break
default:
throw new Error(util.format(

View file

@ -8,9 +8,9 @@ module.exports = syrup.serial()
return data && data.flags && !!data.flags[flag]
}
, get: function(flag, defaultValue) {
return data && data.flags && data.flags[flag] !== void 0
? data.flags[flag]
: defaultValue
return data && data.flags && typeof data.flags[flag] !== 'undefined' ?
data.flags[flag] :
defaultValue
}
}
})

View file

@ -8,11 +8,11 @@ module.exports = syrup.serial()
.define(function(options, identity, data) {
function createSlug() {
var model = identity.model
, name = data ? data.name.id : ''
var name = data ? data.name.id : ''
return (name === '' || model.toLowerCase() === name.toLowerCase())
? tr.slugify(model)
: tr.slugify(name + ' ' + model)
return (name === '' || model.toLowerCase() === name.toLowerCase()) ?
tr.slugify(model) :
tr.slugify(name + ' ' + model)
}
var defaults = {

View file

@ -182,15 +182,16 @@ module.exports = syrup.serial()
var decoded = jpeg.decompressSync(
connState.lastFrame, connState.frameConfig)
conn.writeFramebufferUpdate([
{ xPosition: 0
conn.writeFramebufferUpdate([{
xPosition: 0
, yPosition: 0
, width: decoded.width
, height: decoded.height
, encodingType: VncConnection.ENCODING_RAW
, data: decoded.data
}
, { xPosition: 0
, {
xPosition: 0
, yPosition: 0
, width: decoded.width
, height: decoded.height
@ -203,7 +204,7 @@ module.exports = syrup.serial()
}
function vncStartListener(frameProducer) {
return new Promise(function(resolve/*, reject*/) {
return new Promise(function(resolve) {
connState.frameWidth = frameProducer.banner.virtualWidth
connState.frameHeight = frameProducer.banner.virtualHeight
resolve()
@ -211,7 +212,7 @@ module.exports = syrup.serial()
}
function vncFrameListener(frame) {
return new Promise(function(resolve/*, reject*/) {
return new Promise(function(resolve) {
connState.lastFrame = frame
connState.lastFrameTime = Date.now()
maybeSendFrame()
@ -238,8 +239,10 @@ module.exports = syrup.serial()
})
conn.on('formatchange', function(format) {
var same = os.endianness() === 'BE'
=== Boolean(format.bigEndianFlag)
var same = os.endianness() === 'BE' ===
Boolean(format.bigEndianFlag)
var formatOrder = (format.redShift > format.blueShift) === same
switch (format.bitsPerPixel) {
case 8:
connState.frameConfig = {
@ -248,20 +251,19 @@ module.exports = syrup.serial()
break
case 24:
connState.frameConfig = {
format: ((format.redShift > format.blueShift) === same)
? jpeg.FORMAT_BGR
: jpeg.FORMAT_RGB
format: formatOrder ? jpeg.FORMAT_BGR : jpeg.FORMAT_RGB
}
break
case 32:
var f
if (formatOrder) {
f = format.blueShift === 0 ? jpeg.FORMAT_BGRX : jpeg.FORMAT_XBGR
}
else {
f = format.redShift === 0 ? jpeg.FORMAT_RGBX : jpeg.FORMAT_XRGB
}
connState.frameConfig = {
format: ((format.redShift > format.blueShift) === same)
? (format.blueShift === 0
? jpeg.FORMAT_BGRX
: jpeg.FORMAT_XBGR)
: (format.redShift === 0
? jpeg.FORMAT_RGBX
: jpeg.FORMAT_XRGB)
format: f
}
break
}

View file

@ -90,7 +90,8 @@ VncConnection.CLIENT_MESSAGE_CLIENTCUTTEXT = 6
VncConnection.SERVER_MESSAGE_FBUPDATE = 0
var StateReverse = Object.create(null), State = {
var StateReverse = Object.create(null)
var State = {
STATE_NEED_CLIENT_VERSION: 10
, STATE_NEED_CLIENT_SECURITY: 20
, STATE_NEED_CLIENT_INIT: 30

View file

@ -12,7 +12,7 @@ module.exports = syrup.serial()
.dependency(require('../support/adb'))
.dependency(require('../support/abi'))
.define(function(options, adb, abi) {
var log = logger.createLogger('device:resources:minitouch') // jshint ignore:line
logger.createLogger('device:resources:minitouch')
var resources = {
bin: {

View file

@ -85,9 +85,9 @@ module.exports = syrup.serial()
})
.progressed(function() {
log.warn(
'STFService installation is taking a long time; '
+ 'perhaps you have to accept 3rd party app installation '
+ 'on the device?'
'STFService installation is taking a long time; ' +
'perhaps you have to accept 3rd party app installation ' +
'on the device?'
)
})
.then(function() {

View file

@ -7,7 +7,6 @@ module.exports = syrup.serial()
.define(function(options, properties) {
var log = logger.createLogger('device:support:abi')
return (function() {
function split(list) {
return list ? list.split(',') : []
}
@ -39,6 +38,5 @@ module.exports = syrup.serial()
log.info('Supports ABIs %s', abi.all.join(', '))
return abi
})()
})

View file

@ -26,7 +26,7 @@ module.exports = syrup.serial()
})
.then(function() {
// Establish always-on channels
;[wireutil.global].forEach(function(channel) {
[wireutil.global].forEach(function(channel) {
log.info('Subscribing to permanent channel "%s"', channel)
sub.subscribe(channel)
})

View file

@ -25,7 +25,7 @@ module.exports = function(options) {
var log = logger.createLogger('notify-hipchat')
var client = Promise.promisifyAll(new Hipchatter(options.token))
var buffer = []
, timer
var timer
// Input
var sub = zmqutil.socket('sub')
@ -45,16 +45,6 @@ module.exports = function(options) {
sub.subscribe(channel)
})
sub.on('message', wirerouter()
.on(wire.DeviceLogMessage, function(channel, message) {
if (message.priority >= options.priority) {
buffer.push(message)
clearTimeout(timer)
timer = setTimeout(push, 1000)
}
})
.handler())
function push() {
buffer.splice(0).forEach(function(entry) {
client.notifyAsync(options.room, {
@ -68,12 +58,22 @@ module.exports = function(options) {
)
, color: COLORS[entry.priority]
, notify: entry.priority >= options.notifyPriority
, 'message_format': 'html'
, message_format: 'html'
, token: options.token
})
})
}
sub.on('message', wirerouter()
.on(wire.DeviceLogMessage, function(channel, message) {
if (message.priority >= options.priority) {
buffer.push(message)
clearTimeout(timer)
timer = setTimeout(push, 1000)
}
})
.handler())
log.info('Listening for %s (or higher) level log messages',
logger.LevelLabel[options.priority])

View file

@ -7,9 +7,9 @@ var logger = require('../../util/logger')
module.exports = function(options) {
var log = logger.createLogger('poorxy')
, app = express()
, server = http.createServer(app)
, proxy = httpProxy.createProxyServer()
var app = express()
var server = http.createServer(app)
var proxy = httpProxy.createProxyServer()
proxy.on('error', function(err) {
log.error('Proxy had an error', err.stack)

View file

@ -32,12 +32,13 @@ module.exports = function(options) {
lifecycle.fatal()
})
// Device side
var devDealer = zmqutil.socket('dealer')
appDealer.on('message', function(channel, data) {
devDealer.send([channel, data])
})
// Device side
var devDealer = zmqutil.socket('dealer')
Promise.map(options.endpoints.devDealer, function(endpoint) {
return srv.resolve(endpoint).then(function(records) {
return srv.attempt(records, function(record) {

View file

@ -154,9 +154,8 @@ module.exports = function(options) {
log.info('Found device "%s" (%s)', device.id, device.type)
var privateTracker = new EventEmitter()
, willStop = false
, timer
, worker
var willStop = false
var timer, worker
// Wait for others to acknowledge the device
var register = new Promise(function(resolve) {
@ -176,149 +175,12 @@ module.exports = function(options) {
privateTracker.once('register', resolve)
})
register.then(function() {
log.info('Registered device "%s"', device.id)
check()
})
// Statistics
lists.all.push(device.id)
delayedTotals()
// Will be set to false when the device is removed
_.assign(device, {
present: true
})
// When any event occurs on the added device
function deviceListener(type, updatedDevice) {
// Okay, this is a bit unnecessary but it allows us to get rid of an
// ugly switch statement and return to the original style.
privateTracker.emit(type, updatedDevice)
}
// When the added device changes
function changeListener(updatedDevice) {
register.then(function() {
log.info(
'Device "%s" is now "%s" (was "%s")'
, device.id
, updatedDevice.type
, device.type
)
_.assign(device, {
type: updatedDevice.type
})
// Tell others the device changed
push.send([
wireutil.global
, wireutil.envelope(new wire.DeviceStatusMessage(
device.id
, wireutil.toDeviceStatus(device.type)
))
])
check()
})
}
// When the added device gets removed
function removeListener() {
register.then(function() {
log.info('Lost device "%s" (%s)', device.id, device.type)
clearTimeout(timer)
flippedTracker.removeListener(device.id, deviceListener)
_.pull(lists.all, device.id)
delayedTotals()
// Tell others the device is gone
push.send([
wireutil.global
, wireutil.envelope(new wire.DeviceAbsentMessage(
device.id
))
])
_.assign(device, {
present: false
})
check()
})
}
// Check if we can do anything with the device
function check() {
clearTimeout(timer)
if (device.present) {
// We might get multiple status updates in rapid succession,
// so let's wait for a while
switch (device.type) {
case 'device':
case 'emulator':
willStop = false
timer = setTimeout(work, 100)
break
default:
willStop = true
timer = setTimeout(stop, 100)
break
}
}
else {
stop()
}
}
// Starts a device worker and keeps it alive
function work() {
return (worker = workers[device.id] = spawn())
.then(function() {
log.info('Device worker "%s" has retired', device.id)
delete workers[device.id]
worker = null
// Tell others the device is gone
push.send([
wireutil.global
, wireutil.envelope(new wire.DeviceAbsentMessage(
device.id
))
])
})
.catch(procutil.ExitError, function(err) {
if (!willStop) {
log.error(
'Device worker "%s" died with code %s'
, device.id
, err.code
)
log.info('Restarting device worker "%s"', device.id)
return Promise.delay(500)
.then(function() {
return work()
})
}
})
}
// No more work required
function stop() {
if (worker) {
log.info('Shutting down device worker "%s"', device.id)
worker.cancel()
}
}
// Spawn a device worker
function spawn() {
var allocatedPorts = ports.splice(0, 4)
, proc = options.fork(device, allocatedPorts.slice())
, resolver = Promise.defer()
var proc = options.fork(device, allocatedPorts.slice())
var resolver = Promise.defer()
function exitListener(code, signal) {
if (signal) {
@ -398,6 +260,144 @@ module.exports = function(options) {
})
}
// Starts a device worker and keeps it alive
function work() {
return (worker = workers[device.id] = spawn())
.then(function() {
log.info('Device worker "%s" has retired', device.id)
delete workers[device.id]
worker = null
// Tell others the device is gone
push.send([
wireutil.global
, wireutil.envelope(new wire.DeviceAbsentMessage(
device.id
))
])
})
.catch(procutil.ExitError, function(err) {
if (!willStop) {
log.error(
'Device worker "%s" died with code %s'
, device.id
, err.code
)
log.info('Restarting device worker "%s"', device.id)
return Promise.delay(500)
.then(function() {
return work()
})
}
})
}
// No more work required
function stop() {
if (worker) {
log.info('Shutting down device worker "%s"', device.id)
worker.cancel()
}
}
// Check if we can do anything with the device
function check() {
clearTimeout(timer)
if (device.present) {
// We might get multiple status updates in rapid succession,
// so let's wait for a while
switch (device.type) {
case 'device':
case 'emulator':
willStop = false
timer = setTimeout(work, 100)
break
default:
willStop = true
timer = setTimeout(stop, 100)
break
}
}
else {
stop()
}
}
register.then(function() {
log.info('Registered device "%s"', device.id)
check()
})
// Statistics
lists.all.push(device.id)
delayedTotals()
// Will be set to false when the device is removed
_.assign(device, {
present: true
})
// When any event occurs on the added device
function deviceListener(type, updatedDevice) {
// Okay, this is a bit unnecessary but it allows us to get rid of an
// ugly switch statement and return to the original style.
privateTracker.emit(type, updatedDevice)
}
// When the added device changes
function changeListener(updatedDevice) {
register.then(function() {
log.info(
'Device "%s" is now "%s" (was "%s")'
, device.id
, updatedDevice.type
, device.type
)
_.assign(device, {
type: updatedDevice.type
})
// Tell others the device changed
push.send([
wireutil.global
, wireutil.envelope(new wire.DeviceStatusMessage(
device.id
, wireutil.toDeviceStatus(device.type)
))
])
check()
})
}
// When the added device gets removed
function removeListener() {
register.then(function() {
log.info('Lost device "%s" (%s)', device.id, device.type)
clearTimeout(timer)
flippedTracker.removeListener(device.id, deviceListener)
_.pull(lists.all, device.id)
delayedTotals()
// Tell others the device is gone
push.send([
wireutil.global
, wireutil.envelope(new wire.DeviceAbsentMessage(
device.id
))
])
_.assign(device, {
present: false
})
check()
})
}
flippedTracker.on(device.id, deviceListener)
privateTracker.on('change', changeListener)
privateTracker.on('remove', removeListener)

View file

@ -11,8 +11,8 @@ var manifest = require('./task/manifest')
module.exports = function(options) {
var log = logger.createLogger('storage:plugins:apk')
, app = express()
, server = http.createServer(app)
var app = express()
var server = http.createServer(app)
app.set('strict routing', true)
app.set('case sensitive routing', true)

View file

@ -13,8 +13,8 @@ var transform = require('./task/transform')
module.exports = function(options) {
var log = logger.createLogger('storage:plugins:image')
, app = express()
, server = http.createServer(app)
var app = express()
var server = http.createServer(app)
app.set('strict routing', true)
app.set('case sensitive routing', true)

View file

@ -5,8 +5,8 @@ module.exports = function(raw) {
if (raw && (parsed = RE_CROP.exec(raw))) {
return {
width: +parsed[1] || 0
, height: +parsed[2] || 0
width: Number(parsed[1]) || 0
, height: Number(parsed[2]) || 0
}
}

View file

@ -8,7 +8,7 @@ var request = require('request')
module.exports = function(path, options) {
return new Promise(function(resolve, reject) {
var res = request.get(url.resolve(options.storageUrl, path))
, ret = new stream.Readable().wrap(res) // Wrap old-style stream
var ret = new stream.Readable().wrap(res) // Wrap old-style stream
res.on('response', function(res) {
if (res.statusCode !== 200) {

View file

@ -15,8 +15,8 @@ var logger = require('../../util/logger')
module.exports = function(options) {
var log = logger.createLogger('storage:s3')
, app = express()
, server = http.createServer(app)
var app = express()
var server = http.createServer(app)
var s3 = new AWS.S3({
credentials: new AWS.SharedIniFileCredentials({
@ -151,5 +151,5 @@ module.exports = function(options) {
})
server.listen(options.port)
console.log('Listening on port %d', options.port)
log.info('Listening on port %d', options.port)
}

View file

@ -15,9 +15,9 @@ var download = require('../../util/download')
module.exports = function(options) {
var log = logger.createLogger('storage:temp')
, app = express()
, server = http.createServer(app)
, storage = new Storage()
var app = express()
var server = http.createServer(app)
var storage = new Storage()
app.set('strict routing', true)
app.set('case sensitive routing', true)
@ -59,9 +59,7 @@ module.exports = function(options) {
'/s/%s/%s%s'
, plugin
, file.id
, file.name
? util.format('/%s', path.basename(file.name))
: ''
, file.name ? util.format('/%s', path.basename(file.name)) : ''
)
}
})
@ -115,9 +113,9 @@ module.exports = function(options) {
'/s/%s/%s%s'
, plugin
, file.id
, file.name
? util.format('/%s', path.basename(file.name))
: ''
, file.name ?
util.format('/%s', path.basename(file.name)) :
''
)
}
})

View file

@ -25,12 +25,12 @@ var jwtutil = require('../../util/jwtutil')
module.exports = function(options) {
var log = logger.createLogger('websocket')
, server = http.createServer()
, io = socketio.listen(server, {
var server = http.createServer()
var io = socketio.listen(server, {
serveClient: false
, transports: ['websocket']
})
, channelRouter = new events.EventEmitter()
var channelRouter = new events.EventEmitter()
// Output
var push = zmqutil.socket('push')
@ -89,12 +89,14 @@ module.exports = function(options) {
io.on('connection', function(socket) {
var req = socket.request
, user = req.user
, channels = []
var user = req.user
var channels = []
user.ip = socket.handshake.query.uip || req.ip
socket.emit('socket.ip', user.ip)
var messageListener = wirerouter()
function joinChannel(channel) {
channels.push(channel)
channelRouter.on(channel, messageListener)
@ -118,7 +120,7 @@ module.exports = function(options) {
}
}
var messageListener = wirerouter()
messageListener
.on(wire.DeviceLogMessage, function(channel, message) {
socket.emit('device.log', message)
})
@ -346,7 +348,7 @@ module.exports = function(options) {
})
var tokenId = util.format('%s-%s', uuid.v4(), uuid.v4()).replace(/-/g, '')
, title = data.title
var title = data.title
return dbapi.saveUserAccessToken(user.email, {
title: title

View file

@ -2,7 +2,7 @@ var dbapi = require('../../../db/api')
module.exports = function(socket, next) {
var req = socket.request
, token = req.session.jwt
var token = req.session.jwt
if (token) {
return dbapi.loadUser(token.email)
.then(function(user) {

View file

@ -4,7 +4,7 @@ module.exports = function(options) {
var session = cookieSession(options)
return function(socket, next) {
var req = socket.request
, res = Object.create(null)
var res = Object.create(null)
session(req, res, next)
}
}

View file

@ -4,13 +4,14 @@ module.exports.list = function(val) {
module.exports.size = function(val) {
var match = /^(\d+)x(\d+)$/.exec(val)
return match ? [+match[1], +match[2]] : undefined
if (match) {
return [Number(match[1]), Number(match[2])]
}
}
module.exports.range = function(from, to) {
var items = []
, i
for (i = from; i <= to; ++i) {
for (var i = from; i <= to; ++i) {
items.push(i)
}
return items

View file

@ -70,7 +70,7 @@ devutil.listPidsByComm = function(adb, serial, comm, bin) {
.then(function(out) {
return new Promise(function(resolve) {
var header = false
, pids = []
var pids = []
out.pipe(split())
.on('data', function(chunk) {
if (header) {
@ -79,7 +79,7 @@ devutil.listPidsByComm = function(adb, serial, comm, bin) {
else {
var cols = chunk.toString().split(/\s+/)
if (cols.pop() === bin && users[cols[0]]) {
pids.push(+cols[1])
pids.push(Number(cols[1]))
}
}
})
@ -126,14 +126,14 @@ devutil.killProcsByComm = function(adb, serial, comm, bin, mode) {
devutil.makeIdentity = function(serial, properties) {
var model = properties['ro.product.model']
, brand = properties['ro.product.brand']
, manufacturer = properties['ro.product.manufacturer']
, operator = properties['gsm.sim.operator.alpha'] ||
var brand = properties['ro.product.brand']
var manufacturer = properties['ro.product.manufacturer']
var operator = properties['gsm.sim.operator.alpha'] ||
properties['gsm.operator.alpha']
, version = properties['ro.build.version.release']
, sdk = properties['ro.build.version.sdk']
, abi = properties['ro.product.cpu.abi']
, product = properties['ro.product.name']
var version = properties['ro.build.version.release']
var sdk = properties['ro.build.version.sdk']
var abi = properties['ro.product.cpu.abi']
var product = properties['ro.product.name']
// Remove brand prefix for consistency
if (model.substr(0, brand.length) === brand) {

View file

@ -29,7 +29,7 @@ module.exports.decode = function(payload, secret) {
var decoded = jws.decode(payload, {
json: true
})
, exp = decoded.header.exp
var exp = decoded.header.exp
if (exp && exp <= Date.now()) {
return null

View file

@ -7,15 +7,12 @@ var keyutil = module.exports = Object.create(null)
keyutil.parseKeyCharacterMap = function(stream) {
var resolver = Promise.defer()
, state = 'type_t'
, keymap = {
var state = 'type_t'
var keymap = {
type: null
, keys: []
}
, lastKey
, lastRule
, lastModifier
, lastBehavior
var lastKey, lastRule, lastModifier, lastBehavior
function fail(char, state) {
throw new Error(util.format(
@ -431,8 +428,8 @@ keyutil.parseKeyCharacterMap = function(stream) {
function readableListener() {
var chunk = stream.read()
, i = 0
, l = chunk.length
var i = 0
var l = chunk.length
try {
while (i < l) {
@ -461,7 +458,7 @@ keyutil.parseKeyCharacterMap = function(stream) {
keyutil.namedKey = function(name) {
var key = adb.Keycode['KEYCODE_' + name.toUpperCase()]
if (key === void 0) {
if (typeof key === 'undefined') {
throw new Error(util.format('Unknown key "%s"', name))
}
return key

View file

@ -19,7 +19,7 @@ module.exports.InvalidCredentialsError = InvalidCredentialsError
module.exports.login = function(options, username, password) {
function tryConnect() {
var resolver = Promise.defer()
, client = ldap.createClient({
var client = ldap.createClient({
url: options.url
, timeout: options.timeout
, maxConnections: 1
@ -44,7 +44,7 @@ module.exports.login = function(options, username, password) {
function tryFind(client) {
var resolver = Promise.defer()
, query = {
var query = {
scope: options.search.scope
, filter: new ldap.AndFilter({
filters: [

View file

@ -28,15 +28,6 @@ Logger.LevelLabel = {
Logger.globalIdentifier = '*'
Logger.createLogger = function(tag) {
return new Log(tag)
}
Logger.setGlobalIdentifier = function(identifier) {
Logger.globalIdentifier = identifier
return Logger
}
function Log(tag) {
this.tag = tag
this.names = {
@ -63,6 +54,15 @@ function Log(tag) {
util.inherits(Log, events.EventEmitter)
Logger.createLogger = function(tag) {
return new Log(tag)
}
Logger.setGlobalIdentifier = function(identifier) {
Logger.globalIdentifier = identifier
return Logger
}
Log.Entry = function(timestamp, priority, tag, pid, identifier, message) {
this.timestamp = timestamp
this.priority = priority
@ -129,6 +129,7 @@ Log.prototype._name = function(priority) {
return chalk[this.styles[priority]](this.names[priority])
}
/* eslint no-console: 0 */
Log.prototype._write = function(entry) {
console.error(this._format(entry))
this.emit('entry', entry)

View file

@ -2,12 +2,13 @@ var Promise = require('bluebird')
module.exports.periodicNotify = function(promise, interval) {
var resolver = Promise.defer()
, timer = setInterval(notify, interval)
function notify() {
resolver.progress()
}
var timer = setInterval(notify, interval)
function resolve(value) {
resolver.resolve(value)
}

View file

@ -31,11 +31,7 @@ module.exports.limit = function(limit, handler) {
var queue = []
var running = 0
function done() {
running -= 1
maybeNext()
}
/* eslint no-use-before-define: 0 */
function maybeNext() {
while (running < limit && queue.length) {
running += 1
@ -43,6 +39,11 @@ module.exports.limit = function(limit, handler) {
}
}
function done() {
running -= 1
maybeNext()
}
return function() {
queue.push(arguments)
maybeNext()

View file

@ -37,11 +37,11 @@ RiskyStream.prototype.expectEnd = function() {
RiskyStream.prototype.waitForEnd = function() {
var stream = this.stream
, endListener
var endListener
this.expectEnd()
return new Promise(function(resolve/*, reject*/) {
return new Promise(function(resolve) {
if (stream.ended) {
return resolve(true)
}

View file

@ -41,7 +41,7 @@ function shuffleWeighted(records) {
function pick(records, sum) {
var rand = Math.random() * sum
, counter = 0
var counter = 0
for (var i = 0, l = records.length; i < l; ++i) {
counter += records[i].weight
@ -117,7 +117,7 @@ srv.attempt = function(records, fn) {
}
return fn(records[i]).catch(srv.NEXT, function() {
return next(++i)
return next(i + 1)
})
}

View file

@ -50,7 +50,7 @@ Storage.prototype.check = function() {
Object.keys(this.files).forEach(function(id) {
var file = this.files[id]
, inactivePeriod = now - file.lastActivity
var inactivePeriod = now - file.lastActivity
if (inactivePeriod >= file.timeout) {
this.remove(id)

View file

@ -15,7 +15,7 @@ module.exports.NoSuchLineError = NoSuchLineError
module.exports.readAll = function(stream) {
var resolver = Promise.defer()
, collected = new Buffer(0)
var collected = new Buffer(0)
function errorListener(err) {
resolver.reject(err)
@ -45,7 +45,7 @@ module.exports.readAll = function(stream) {
module.exports.findLine = function(stream, re) {
var resolver = Promise.defer()
, piped = stream.pipe(split())
var piped = stream.pipe(split())
function errorListener(err) {
resolver.reject(err)

View file

@ -3,9 +3,12 @@ var url = require('url')
module.exports.addParams = function(originalUrl, params) {
var parsed = url.parse(originalUrl, true)
parsed.search = null
// TODO: change to ES6 loop
for (var key in params) {
if (params.dict.hasOwnProperty(key)) {
parsed.query[key] = params[key]
}
}
return url.format(parsed)
}

View file

@ -28,7 +28,7 @@ function normalizePassword(password) {
function encrypt(challenge, password) {
var key = normalizePassword(password)
, iv = new Buffer(0).fill(0)
var iv = new Buffer(0).fill(0)
// Note: do not call .final(), .update() is the one that gives us the
// desired result.

View file

@ -14,7 +14,7 @@ module.exports.socket = function() {
;['ZMQ_TCP_KEEPALIVE', 'ZMQ_TCP_KEEPALIVE_IDLE'].forEach(function(opt) {
if (process.env[opt]) {
try {
sock.setsockopt(zmq[opt], +process.env[opt])
sock.setsockopt(zmq[opt], Number(process.env[opt]))
}
catch (err) {
log.warn('ZeroMQ library too old, no support for %s', opt)

View file

@ -53,7 +53,7 @@ ChannelManager.prototype.keepalive = function(id) {
ChannelManager.prototype.check = function(id) {
var channel = this.channels[id]
, inactivePeriod = Date.now() - channel.lastActivity
var inactivePeriod = Date.now() - channel.lastActivity
if (inactivePeriod >= channel.timeout) {
this.unregister(id)

View file

@ -30,7 +30,7 @@ Router.prototype.removeListener = function(message, handler) {
Router.prototype.handler = function() {
return function(channel, data) {
var wrapper = wire.Envelope.decode(data)
, type = wire.ReverseMessageType[wrapper.type]
var type = wire.ReverseMessageType[wrapper.type]
if (type) {
this.emit(

View file

@ -44,7 +44,7 @@ SeqQueue.prototype.maybeConsume = function() {
var handler = this.list[this.lo]
// Have we received it yet?
if (handler) {
this.list[this.lo] = void 0
this.list[this.lo] = undefined
handler()
this.lo += 1
this.waiting -= 1