first commit

This commit is contained in:
2026-09-08 20:28:54 +08:00
commit 2ada8d3d5a
37380 changed files with 4886169 additions and 0 deletions
+14
View File
@@ -0,0 +1,14 @@
Copyright © 2013 CyberAgent, Inc.
Copyright © 2016 The OpenSTF Project
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
+1131
View File
File diff suppressed because it is too large Load Diff
+3
View File
@@ -0,0 +1,3 @@
#!/usr/bin/env node
require('../lib/cli')
+15
View File
@@ -0,0 +1,15 @@
(function() {
var Path;
Path = require('path');
module.exports = (function() {
switch (Path.extname(__filename)) {
case '.coffee':
return require('./src/adb');
default:
return require('./lib/adb');
}
})();
}).call(this);
+29
View File
@@ -0,0 +1,29 @@
var Adb, Client, Keycode, util;
Client = require('./adb/client');
Keycode = require('./adb/keycode');
util = require('./adb/util');
Adb = (function() {
function Adb() {}
Adb.createClient = function(options) {
if (options == null) {
options = {};
}
options.host || (options.host = process.env.ADB_HOST);
options.port || (options.port = process.env.ADB_PORT);
return new Client(options);
};
return Adb;
})();
Adb.Keycode = Keycode;
Adb.util = util;
module.exports = Adb;
+78
View File
@@ -0,0 +1,78 @@
var Auth, BigInteger, Promise, forge;
Promise = require('bluebird');
forge = require('node-forge');
BigInteger = forge.jsbn.BigInteger;
/*
The stucture of an ADB RSAPublicKey is as follows:
#define RSANUMBYTES 256 // 2048 bit key length
#define RSANUMWORDS (RSANUMBYTES / sizeof(uint32_t))
typedef struct RSAPublicKey {
int len; // Length of n[] in number of uint32_t
uint32_t n0inv; // -1 / n[0] mod 2^32
uint32_t n[RSANUMWORDS]; // modulus as little endian array
uint32_t rr[RSANUMWORDS]; // R^2 as little endian array
int exponent; // 3 or 65537
} RSAPublicKey;
*/
Auth = (function() {
var RE, readPublicKeyFromStruct;
function Auth() {}
RE = /^((?:[A-Za-z0-9+\/]{4})*(?:[A-Za-z0-9+\/]{2}==|[A-Za-z0-9+\/]{3}=)?)\0?( .*|)\s*$/;
readPublicKeyFromStruct = function(struct, comment) {
var e, key, len, md, n, offset;
if (!struct.length) {
throw new Error("Invalid public key");
}
offset = 0;
len = struct.readUInt32LE(offset) * 4;
offset += 4;
if (struct.length !== 4 + 4 + len + len + 4) {
throw new Error("Invalid public key");
}
offset += 4;
n = new Buffer(len);
struct.copy(n, 0, offset, offset + len);
[].reverse.call(n);
offset += len;
offset += len;
e = struct.readUInt32LE(offset);
if (!(e === 3 || e === 65537)) {
throw new Error("Invalid exponent " + e + ", only 3 and 65537 are supported");
}
key = forge.pki.setRsaPublicKey(new BigInteger(n.toString('hex'), 16), new BigInteger(e.toString(), 10));
md = forge.md.md5.create();
md.update(struct.toString('binary'));
key.fingerprint = md.digest().toHex().match(/../g).join(':');
key.comment = comment;
return key;
};
Auth.parsePublicKey = function(buffer) {
return new Promise(function(resolve, reject) {
var comment, match, struct;
if (match = RE.exec(buffer)) {
struct = new Buffer(match[1], 'base64');
comment = match[2].trim();
return resolve(readPublicKeyFromStruct(struct, comment));
} else {
return reject(new Error("Unrecognizable public key format"));
}
});
};
return Auth;
})();
module.exports = Auth;
+573
View File
@@ -0,0 +1,573 @@
var ClearCommand, Client, Connection, ForwardCommand, FrameBufferCommand, GetDevicePathCommand, GetFeaturesCommand, GetPackagesCommand, GetPropertiesCommand, GetSerialNoCommand, GetStateCommand, HostConnectCommand, HostDevicesCommand, HostDevicesWithPathsCommand, HostDisconnectCommand, HostKillCommand, HostTrackDevicesCommand, HostTransportCommand, HostVersionCommand, InstallCommand, IsInstalledCommand, ListForwardsCommand, ListReversesCommand, LocalCommand, LogCommand, Logcat, LogcatCommand, Monkey, MonkeyCommand, Parser, ProcStat, Promise, RebootCommand, RemountCommand, ReverseCommand, RootCommand, ScreencapCommand, ShellCommand, StartActivityCommand, StartServiceCommand, Sync, SyncCommand, TcpCommand, TcpIpCommand, TcpUsbServer, TrackJdwpCommand, UninstallCommand, UsbCommand, WaitBootCompleteCommand, WaitForDeviceCommand, debug;
Monkey = require('adbkit-monkey');
Logcat = require('adbkit-logcat');
Promise = require('bluebird');
debug = require('debug')('adb:client');
Connection = require('./connection');
Sync = require('./sync');
Parser = require('./parser');
ProcStat = require('./proc/stat');
HostVersionCommand = require('./command/host/version');
HostConnectCommand = require('./command/host/connect');
HostDevicesCommand = require('./command/host/devices');
HostDevicesWithPathsCommand = require('./command/host/deviceswithpaths');
HostDisconnectCommand = require('./command/host/disconnect');
HostTrackDevicesCommand = require('./command/host/trackdevices');
HostKillCommand = require('./command/host/kill');
HostTransportCommand = require('./command/host/transport');
ClearCommand = require('./command/host-transport/clear');
FrameBufferCommand = require('./command/host-transport/framebuffer');
GetFeaturesCommand = require('./command/host-transport/getfeatures');
GetPackagesCommand = require('./command/host-transport/getpackages');
GetPropertiesCommand = require('./command/host-transport/getproperties');
InstallCommand = require('./command/host-transport/install');
IsInstalledCommand = require('./command/host-transport/isinstalled');
ListReversesCommand = require('./command/host-transport/listreverses');
LocalCommand = require('./command/host-transport/local');
LogcatCommand = require('./command/host-transport/logcat');
LogCommand = require('./command/host-transport/log');
MonkeyCommand = require('./command/host-transport/monkey');
RebootCommand = require('./command/host-transport/reboot');
RemountCommand = require('./command/host-transport/remount');
RootCommand = require('./command/host-transport/root');
ReverseCommand = require('./command/host-transport/reverse');
ScreencapCommand = require('./command/host-transport/screencap');
ShellCommand = require('./command/host-transport/shell');
StartActivityCommand = require('./command/host-transport/startactivity');
StartServiceCommand = require('./command/host-transport/startservice');
SyncCommand = require('./command/host-transport/sync');
TcpCommand = require('./command/host-transport/tcp');
TcpIpCommand = require('./command/host-transport/tcpip');
TrackJdwpCommand = require('./command/host-transport/trackjdwp');
UninstallCommand = require('./command/host-transport/uninstall');
UsbCommand = require('./command/host-transport/usb');
WaitBootCompleteCommand = require('./command/host-transport/waitbootcomplete');
ForwardCommand = require('./command/host-serial/forward');
GetDevicePathCommand = require('./command/host-serial/getdevicepath');
GetSerialNoCommand = require('./command/host-serial/getserialno');
GetStateCommand = require('./command/host-serial/getstate');
ListForwardsCommand = require('./command/host-serial/listforwards');
WaitForDeviceCommand = require('./command/host-serial/waitfordevice');
TcpUsbServer = require('./tcpusb/server');
Client = (function() {
var NoUserOptionError;
function Client(options1) {
var base, base1;
this.options = options1 != null ? options1 : {};
(base = this.options).port || (base.port = 5037);
(base1 = this.options).bin || (base1.bin = 'adb');
}
Client.prototype.createTcpUsbBridge = function(serial, options) {
return new TcpUsbServer(this, serial, options);
};
Client.prototype.connection = function() {
var conn, connectListener, errorListener, resolver;
resolver = Promise.defer();
conn = new Connection(this.options).on('error', errorListener = function(err) {
return resolver.reject(err);
}).on('connect', connectListener = function() {
return resolver.resolve(conn);
}).connect();
return resolver.promise["finally"](function() {
conn.removeListener('error', errorListener);
return conn.removeListener('connect', connectListener);
});
};
Client.prototype.version = function(callback) {
return this.connection().then(function(conn) {
return new HostVersionCommand(conn).execute();
}).nodeify(callback);
};
Client.prototype.connect = function(host, port, callback) {
var ref;
if (port == null) {
port = 5555;
}
if (typeof port === 'function') {
callback = port;
port = 5555;
}
if (host.indexOf(':') !== -1) {
ref = host.split(':', 2), host = ref[0], port = ref[1];
}
return this.connection().then(function(conn) {
return new HostConnectCommand(conn).execute(host, port);
}).nodeify(callback);
};
Client.prototype.disconnect = function(host, port, callback) {
var ref;
if (port == null) {
port = 5555;
}
if (typeof port === 'function') {
callback = port;
port = 5555;
}
if (host.indexOf(':') !== -1) {
ref = host.split(':', 2), host = ref[0], port = ref[1];
}
return this.connection().then(function(conn) {
return new HostDisconnectCommand(conn).execute(host, port);
}).nodeify(callback);
};
Client.prototype.listDevices = function(callback) {
return this.connection().then(function(conn) {
return new HostDevicesCommand(conn).execute();
}).nodeify(callback);
};
Client.prototype.listDevicesWithPaths = function(callback) {
return this.connection().then(function(conn) {
return new HostDevicesWithPathsCommand(conn).execute();
}).nodeify(callback);
};
Client.prototype.trackDevices = function(callback) {
return this.connection().then(function(conn) {
return new HostTrackDevicesCommand(conn).execute();
}).nodeify(callback);
};
Client.prototype.kill = function(callback) {
return this.connection().then(function(conn) {
return new HostKillCommand(conn).execute();
}).nodeify(callback);
};
Client.prototype.getSerialNo = function(serial, callback) {
return this.connection().then(function(conn) {
return new GetSerialNoCommand(conn).execute(serial);
}).nodeify(callback);
};
Client.prototype.getDevicePath = function(serial, callback) {
return this.connection().then(function(conn) {
return new GetDevicePathCommand(conn).execute(serial);
}).nodeify(callback);
};
Client.prototype.getState = function(serial, callback) {
return this.connection().then(function(conn) {
return new GetStateCommand(conn).execute(serial);
}).nodeify(callback);
};
Client.prototype.getProperties = function(serial, callback) {
return this.transport(serial).then(function(transport) {
return new GetPropertiesCommand(transport).execute();
}).nodeify(callback);
};
Client.prototype.getFeatures = function(serial, callback) {
return this.transport(serial).then(function(transport) {
return new GetFeaturesCommand(transport).execute();
}).nodeify(callback);
};
Client.prototype.getPackages = function(serial, callback) {
return this.transport(serial).then(function(transport) {
return new GetPackagesCommand(transport).execute();
}).nodeify(callback);
};
Client.prototype.getDHCPIpAddress = function(serial, iface, callback) {
if (iface == null) {
iface = 'wlan0';
}
if (typeof iface === 'function') {
callback = iface;
iface = 'wlan0';
}
return this.getProperties(serial).then(function(properties) {
var ip;
if (ip = properties["dhcp." + iface + ".ipaddress"]) {
return ip;
}
throw new Error("Unable to find ipaddress for '" + iface + "'");
});
};
Client.prototype.forward = function(serial, local, remote, callback) {
return this.connection().then(function(conn) {
return new ForwardCommand(conn).execute(serial, local, remote);
}).nodeify(callback);
};
Client.prototype.listForwards = function(serial, callback) {
return this.connection().then(function(conn) {
return new ListForwardsCommand(conn).execute(serial);
}).nodeify(callback);
};
Client.prototype.reverse = function(serial, remote, local, callback) {
return this.transport(serial).then(function(transport) {
return new ReverseCommand(transport).execute(remote, local).nodeify(callback);
});
};
Client.prototype.listReverses = function(serial, callback) {
return this.transport(serial).then(function(transport) {
return new ListReversesCommand(transport).execute();
}).nodeify(callback);
};
Client.prototype.transport = function(serial, callback) {
return this.connection().then(function(conn) {
return new HostTransportCommand(conn).execute(serial)["return"](conn);
}).nodeify(callback);
};
Client.prototype.shell = function(serial, command, callback) {
return this.transport(serial).then(function(transport) {
return new ShellCommand(transport).execute(command);
}).nodeify(callback);
};
Client.prototype.reboot = function(serial, callback) {
return this.transport(serial).then(function(transport) {
return new RebootCommand(transport).execute();
}).nodeify(callback);
};
Client.prototype.remount = function(serial, callback) {
return this.transport(serial).then(function(transport) {
return new RemountCommand(transport).execute();
}).nodeify(callback);
};
Client.prototype.root = function(serial, callback) {
return this.transport(serial).then(function(transport) {
return new RootCommand(transport).execute();
}).nodeify(callback);
};
Client.prototype.trackJdwp = function(serial, callback) {
return this.transport(serial).then(function(transport) {
return new TrackJdwpCommand(transport).execute();
}).nodeify(callback);
};
Client.prototype.framebuffer = function(serial, format, callback) {
if (format == null) {
format = 'raw';
}
if (typeof format === 'function') {
callback = format;
format = 'raw';
}
return this.transport(serial).then(function(transport) {
return new FrameBufferCommand(transport).execute(format);
}).nodeify(callback);
};
Client.prototype.screencap = function(serial, callback) {
return this.transport(serial).then((function(_this) {
return function(transport) {
return new ScreencapCommand(transport).execute()["catch"](function(err) {
debug("Emulating screencap command due to '" + err + "'");
return _this.framebuffer(serial, 'png');
});
};
})(this)).nodeify(callback);
};
Client.prototype.openLocal = function(serial, path, callback) {
return this.transport(serial).then(function(transport) {
return new LocalCommand(transport).execute(path);
}).nodeify(callback);
};
Client.prototype.openLog = function(serial, name, callback) {
return this.transport(serial).then(function(transport) {
return new LogCommand(transport).execute(name);
}).nodeify(callback);
};
Client.prototype.openTcp = function(serial, port, host, callback) {
if (typeof host === 'function') {
callback = host;
host = void 0;
}
return this.transport(serial).then(function(transport) {
return new TcpCommand(transport).execute(port, host);
}).nodeify(callback);
};
Client.prototype.openMonkey = function(serial, port, callback) {
var tryConnect;
if (port == null) {
port = 1080;
}
if (typeof port === 'function') {
callback = port;
port = 1080;
}
tryConnect = (function(_this) {
return function(times) {
return _this.openTcp(serial, port).then(function(stream) {
return Monkey.connectStream(stream);
})["catch"](function(err) {
if (times -= 1) {
debug("Monkey can't be reached, trying " + times + " more times");
return Promise.delay(100).then(function() {
return tryConnect(times);
});
} else {
throw err;
}
});
};
})(this);
return tryConnect(1)["catch"]((function(_this) {
return function(err) {
return _this.transport(serial).then(function(transport) {
return new MonkeyCommand(transport).execute(port);
}).then(function(out) {
return tryConnect(20).then(function(monkey) {
return monkey.once('end', function() {
return out.end();
});
});
});
};
})(this)).nodeify(callback);
};
Client.prototype.openLogcat = function(serial, options, callback) {
if (typeof options === 'function') {
callback = options;
options = {};
}
return this.transport(serial).then(function(transport) {
return new LogcatCommand(transport).execute(options);
}).then(function(stream) {
return Logcat.readStream(stream, {
fixLineFeeds: false
});
}).nodeify(callback);
};
Client.prototype.openProcStat = function(serial, callback) {
return this.syncService(serial).then(function(sync) {
return new ProcStat(sync);
}).nodeify(callback);
};
Client.prototype.clear = function(serial, pkg, callback) {
return this.transport(serial).then(function(transport) {
return new ClearCommand(transport).execute(pkg);
}).nodeify(callback);
};
Client.prototype.install = function(serial, apk, callback) {
var temp;
temp = Sync.temp(typeof apk === 'string' ? apk : '_stream.apk');
return this.push(serial, apk, temp).then((function(_this) {
return function(transfer) {
var endListener, errorListener, resolver;
resolver = Promise.defer();
transfer.on('error', errorListener = function(err) {
return resolver.reject(err);
});
transfer.on('end', endListener = function() {
return resolver.resolve(_this.installRemote(serial, temp));
});
return resolver.promise["finally"](function() {
transfer.removeListener('error', errorListener);
return transfer.removeListener('end', endListener);
});
};
})(this)).nodeify(callback);
};
Client.prototype.installRemote = function(serial, apk, callback) {
return this.transport(serial).then((function(_this) {
return function(transport) {
return new InstallCommand(transport).execute(apk).then(function() {
return _this.shell(serial, ['rm', '-f', apk]);
}).then(function(stream) {
return new Parser(stream).readAll();
}).then(function(out) {
return true;
});
};
})(this)).nodeify(callback);
};
Client.prototype.uninstall = function(serial, pkg, callback) {
return this.transport(serial).then(function(transport) {
return new UninstallCommand(transport).execute(pkg);
}).nodeify(callback);
};
Client.prototype.isInstalled = function(serial, pkg, callback) {
return this.transport(serial).then(function(transport) {
return new IsInstalledCommand(transport).execute(pkg);
}).nodeify(callback);
};
Client.prototype.startActivity = function(serial, options, callback) {
return this.transport(serial).then(function(transport) {
return new StartActivityCommand(transport).execute(options);
})["catch"](NoUserOptionError, (function(_this) {
return function() {
options.user = null;
return _this.startActivity(serial, options);
};
})(this)).nodeify(callback);
};
Client.prototype.startService = function(serial, options, callback) {
return this.transport(serial).then(function(transport) {
if (!(options.user || options.user === null)) {
options.user = 0;
}
return new StartServiceCommand(transport).execute(options);
})["catch"](NoUserOptionError, (function(_this) {
return function() {
options.user = null;
return _this.startService(serial, options);
};
})(this)).nodeify(callback);
};
Client.prototype.syncService = function(serial, callback) {
return this.transport(serial).then(function(transport) {
return new SyncCommand(transport).execute();
}).nodeify(callback);
};
Client.prototype.stat = function(serial, path, callback) {
return this.syncService(serial).then(function(sync) {
return sync.stat(path)["finally"](function() {
return sync.end();
});
}).nodeify(callback);
};
Client.prototype.readdir = function(serial, path, callback) {
return this.syncService(serial).then(function(sync) {
return sync.readdir(path)["finally"](function() {
return sync.end();
});
}).nodeify(callback);
};
Client.prototype.pull = function(serial, path, callback) {
return this.syncService(serial).then(function(sync) {
return sync.pull(path).on('end', function() {
return sync.end();
});
}).nodeify(callback);
};
Client.prototype.push = function(serial, contents, path, mode, callback) {
if (typeof mode === 'function') {
callback = mode;
mode = void 0;
}
return this.syncService(serial).then(function(sync) {
return sync.push(contents, path, mode).on('end', function() {
return sync.end();
});
}).nodeify(callback);
};
Client.prototype.tcpip = function(serial, port, callback) {
if (port == null) {
port = 5555;
}
if (typeof port === 'function') {
callback = port;
port = 5555;
}
return this.transport(serial).then(function(transport) {
return new TcpIpCommand(transport).execute(port);
}).nodeify(callback);
};
Client.prototype.usb = function(serial, callback) {
return this.transport(serial).then(function(transport) {
return new UsbCommand(transport).execute();
}).nodeify(callback);
};
Client.prototype.waitBootComplete = function(serial, callback) {
return this.transport(serial).then(function(transport) {
return new WaitBootCompleteCommand(transport).execute();
}).nodeify(callback);
};
Client.prototype.waitForDevice = function(serial, callback) {
return this.connection().then(function(conn) {
return new WaitForDeviceCommand(conn).execute(serial);
}).nodeify(callback);
};
NoUserOptionError = function(err) {
return err.message.indexOf('--user') !== -1;
};
return Client;
})();
module.exports = Client;
+56
View File
@@ -0,0 +1,56 @@
var Command, Parser, Protocol, debug;
debug = require('debug')('adb:command');
Parser = require('./parser');
Protocol = require('./protocol');
Command = (function() {
var RE_ESCAPE, RE_SQUOT;
RE_SQUOT = /'/g;
RE_ESCAPE = /([$`\\!"])/g;
function Command(connection) {
this.connection = connection;
this.parser = this.connection.parser;
this.protocol = Protocol;
}
Command.prototype.execute = function() {
throw new Exception('Missing implementation');
};
Command.prototype._send = function(data) {
var encoded;
encoded = Protocol.encodeData(data);
debug("Send '" + encoded + "'");
this.connection.write(encoded);
return this;
};
Command.prototype._escape = function(arg) {
switch (typeof arg) {
case 'number':
return arg;
default:
return "'" + arg.toString().replace(RE_SQUOT, "'\"'\"'") + "'";
}
};
Command.prototype._escapeCompat = function(arg) {
switch (typeof arg) {
case 'number':
return arg;
default:
return '"' + arg.toString().replace(RE_ESCAPE, '\\$1') + '"';
}
};
return Command;
})();
module.exports = Command;
+45
View File
@@ -0,0 +1,45 @@
var Command, ForwardCommand, Protocol,
extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
hasProp = {}.hasOwnProperty;
Command = require('../../command');
Protocol = require('../../protocol');
ForwardCommand = (function(superClass) {
extend(ForwardCommand, superClass);
function ForwardCommand() {
return ForwardCommand.__super__.constructor.apply(this, arguments);
}
ForwardCommand.prototype.execute = function(serial, local, remote) {
this._send("host-serial:" + serial + ":forward:" + local + ";" + remote);
return this.parser.readAscii(4).then((function(_this) {
return function(reply) {
switch (reply) {
case Protocol.OKAY:
return _this.parser.readAscii(4).then(function(reply) {
switch (reply) {
case Protocol.OKAY:
return true;
case Protocol.FAIL:
return _this.parser.readError();
default:
return _this.parser.unexpected(reply, 'OKAY or FAIL');
}
});
case Protocol.FAIL:
return _this.parser.readError();
default:
return _this.parser.unexpected(reply, 'OKAY or FAIL');
}
};
})(this));
};
return ForwardCommand;
})(Command);
module.exports = ForwardCommand;
+38
View File
@@ -0,0 +1,38 @@
var Command, GetDevicePathCommand, Protocol,
extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
hasProp = {}.hasOwnProperty;
Command = require('../../command');
Protocol = require('../../protocol');
GetDevicePathCommand = (function(superClass) {
extend(GetDevicePathCommand, superClass);
function GetDevicePathCommand() {
return GetDevicePathCommand.__super__.constructor.apply(this, arguments);
}
GetDevicePathCommand.prototype.execute = function(serial) {
this._send("host-serial:" + serial + ":get-devpath");
return this.parser.readAscii(4).then((function(_this) {
return function(reply) {
switch (reply) {
case Protocol.OKAY:
return _this.parser.readValue().then(function(value) {
return value.toString();
});
case Protocol.FAIL:
return _this.parser.readError();
default:
return _this.parser.unexpected(reply, 'OKAY or FAIL');
}
};
})(this));
};
return GetDevicePathCommand;
})(Command);
module.exports = GetDevicePathCommand;
+38
View File
@@ -0,0 +1,38 @@
var Command, GetSerialNoCommand, Protocol,
extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
hasProp = {}.hasOwnProperty;
Command = require('../../command');
Protocol = require('../../protocol');
GetSerialNoCommand = (function(superClass) {
extend(GetSerialNoCommand, superClass);
function GetSerialNoCommand() {
return GetSerialNoCommand.__super__.constructor.apply(this, arguments);
}
GetSerialNoCommand.prototype.execute = function(serial) {
this._send("host-serial:" + serial + ":get-serialno");
return this.parser.readAscii(4).then((function(_this) {
return function(reply) {
switch (reply) {
case Protocol.OKAY:
return _this.parser.readValue().then(function(value) {
return value.toString();
});
case Protocol.FAIL:
return _this.parser.readError();
default:
return _this.parser.unexpected(reply, 'OKAY or FAIL');
}
};
})(this));
};
return GetSerialNoCommand;
})(Command);
module.exports = GetSerialNoCommand;
+38
View File
@@ -0,0 +1,38 @@
var Command, GetStateCommand, Protocol,
extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
hasProp = {}.hasOwnProperty;
Command = require('../../command');
Protocol = require('../../protocol');
GetStateCommand = (function(superClass) {
extend(GetStateCommand, superClass);
function GetStateCommand() {
return GetStateCommand.__super__.constructor.apply(this, arguments);
}
GetStateCommand.prototype.execute = function(serial) {
this._send("host-serial:" + serial + ":get-state");
return this.parser.readAscii(4).then((function(_this) {
return function(reply) {
switch (reply) {
case Protocol.OKAY:
return _this.parser.readValue().then(function(value) {
return value.toString();
});
case Protocol.FAIL:
return _this.parser.readError();
default:
return _this.parser.unexpected(reply, 'OKAY or FAIL');
}
};
})(this));
};
return GetStateCommand;
})(Command);
module.exports = GetStateCommand;
+56
View File
@@ -0,0 +1,56 @@
var Command, ListForwardsCommand, Protocol,
extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
hasProp = {}.hasOwnProperty;
Command = require('../../command');
Protocol = require('../../protocol');
ListForwardsCommand = (function(superClass) {
extend(ListForwardsCommand, superClass);
function ListForwardsCommand() {
return ListForwardsCommand.__super__.constructor.apply(this, arguments);
}
ListForwardsCommand.prototype.execute = function(serial) {
this._send("host-serial:" + serial + ":list-forward");
return this.parser.readAscii(4).then((function(_this) {
return function(reply) {
switch (reply) {
case Protocol.OKAY:
return _this.parser.readValue().then(function(value) {
return _this._parseForwards(value);
});
case Protocol.FAIL:
return _this.parser.readError();
default:
return _this.parser.unexpected(reply, 'OKAY or FAIL');
}
};
})(this));
};
ListForwardsCommand.prototype._parseForwards = function(value) {
var forward, forwards, i, len, local, ref, ref1, remote, serial;
forwards = [];
ref = value.toString().split('\n');
for (i = 0, len = ref.length; i < len; i++) {
forward = ref[i];
if (forward) {
ref1 = forward.split(/\s+/), serial = ref1[0], local = ref1[1], remote = ref1[2];
forwards.push({
serial: serial,
local: local,
remote: remote
});
}
}
return forwards;
};
return ListForwardsCommand;
})(Command);
module.exports = ListForwardsCommand;
+45
View File
@@ -0,0 +1,45 @@
var Command, Protocol, WaitForDeviceCommand,
extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
hasProp = {}.hasOwnProperty;
Command = require('../../command');
Protocol = require('../../protocol');
WaitForDeviceCommand = (function(superClass) {
extend(WaitForDeviceCommand, superClass);
function WaitForDeviceCommand() {
return WaitForDeviceCommand.__super__.constructor.apply(this, arguments);
}
WaitForDeviceCommand.prototype.execute = function(serial) {
this._send("host-serial:" + serial + ":wait-for-any");
return this.parser.readAscii(4).then((function(_this) {
return function(reply) {
switch (reply) {
case Protocol.OKAY:
return _this.parser.readAscii(4).then(function(reply) {
switch (reply) {
case Protocol.OKAY:
return serial;
case Protocol.FAIL:
return _this.parser.readError();
default:
return _this.parser.unexpected(reply, 'OKAY or FAIL');
}
});
case Protocol.FAIL:
return _this.parser.readError();
default:
return _this.parser.unexpected(reply, 'OKAY or FAIL');
}
};
})(this));
};
return WaitForDeviceCommand;
})(Command);
module.exports = WaitForDeviceCommand;
+45
View File
@@ -0,0 +1,45 @@
var ClearCommand, Command, Protocol,
extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
hasProp = {}.hasOwnProperty;
Command = require('../../command');
Protocol = require('../../protocol');
ClearCommand = (function(superClass) {
extend(ClearCommand, superClass);
function ClearCommand() {
return ClearCommand.__super__.constructor.apply(this, arguments);
}
ClearCommand.prototype.execute = function(pkg) {
this._send("shell:pm clear " + pkg);
return this.parser.readAscii(4).then((function(_this) {
return function(reply) {
switch (reply) {
case Protocol.OKAY:
return _this.parser.searchLine(/^(Success|Failed)$/)["finally"](function() {
return _this.parser.end();
}).then(function(result) {
switch (result[0]) {
case 'Success':
return true;
case 'Failed':
throw new Error("Package '" + pkg + "' could not be cleared");
}
});
case Protocol.FAIL:
return _this.parser.readError();
default:
return _this.parser.unexpected(reply, 'OKAY or FAIL');
}
};
})(this));
};
return ClearCommand;
})(Command);
module.exports = ClearCommand;
+114
View File
@@ -0,0 +1,114 @@
var Assert, Command, FrameBufferCommand, Protocol, RgbTransform, debug, spawn,
extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
hasProp = {}.hasOwnProperty;
Assert = require('assert');
spawn = require('child_process').spawn;
debug = require('debug')('adb:command:framebuffer');
Command = require('../../command');
Protocol = require('../../protocol');
RgbTransform = require('../../framebuffer/rgbtransform');
FrameBufferCommand = (function(superClass) {
extend(FrameBufferCommand, superClass);
function FrameBufferCommand() {
return FrameBufferCommand.__super__.constructor.apply(this, arguments);
}
FrameBufferCommand.prototype.execute = function(format) {
this._send('framebuffer:');
return this.parser.readAscii(4).then((function(_this) {
return function(reply) {
switch (reply) {
case Protocol.OKAY:
return _this.parser.readBytes(52).then(function(header) {
var meta, stream;
meta = _this._parseHeader(header);
switch (format) {
case 'raw':
stream = _this.parser.raw();
stream.meta = meta;
return stream;
default:
stream = _this._convert(meta, format);
stream.meta = meta;
return stream;
}
});
case Protocol.FAIL:
return _this.parser.readError();
default:
return _this.parser.unexpected(reply, 'OKAY or FAIL');
}
};
})(this));
};
FrameBufferCommand.prototype._convert = function(meta, format, raw) {
var proc, transform;
debug("Converting raw framebuffer stream into " + (format.toUpperCase()));
switch (meta.format) {
case 'rgb':
case 'rgba':
break;
default:
debug("Silently transforming '" + meta.format + "' into 'rgb' for `gm`");
transform = new RgbTransform(meta);
meta.format = 'rgb';
raw = this.parser.raw().pipe(transform);
}
proc = spawn('gm', ['convert', '-size', meta.width + "x" + meta.height, meta.format + ":-", format + ":-"]);
raw.pipe(proc.stdin);
return proc.stdout;
};
FrameBufferCommand.prototype._parseHeader = function(header) {
var meta, offset;
meta = {};
offset = 0;
meta.version = header.readUInt32LE(offset);
if (meta.version === 16) {
throw new Error('Old-style raw images are not supported');
}
offset += 4;
meta.bpp = header.readUInt32LE(offset);
offset += 4;
meta.size = header.readUInt32LE(offset);
offset += 4;
meta.width = header.readUInt32LE(offset);
offset += 4;
meta.height = header.readUInt32LE(offset);
offset += 4;
meta.red_offset = header.readUInt32LE(offset);
offset += 4;
meta.red_length = header.readUInt32LE(offset);
offset += 4;
meta.blue_offset = header.readUInt32LE(offset);
offset += 4;
meta.blue_length = header.readUInt32LE(offset);
offset += 4;
meta.green_offset = header.readUInt32LE(offset);
offset += 4;
meta.green_length = header.readUInt32LE(offset);
offset += 4;
meta.alpha_offset = header.readUInt32LE(offset);
offset += 4;
meta.alpha_length = header.readUInt32LE(offset);
meta.format = meta.blue_offset === 0 ? 'bgr' : 'rgb';
if (meta.bpp === 32 || meta.alpha_length) {
meta.format += 'a';
}
return meta;
};
return FrameBufferCommand;
})(Command);
module.exports = FrameBufferCommand;
+51
View File
@@ -0,0 +1,51 @@
var Command, GetFeaturesCommand, Protocol,
extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
hasProp = {}.hasOwnProperty;
Command = require('../../command');
Protocol = require('../../protocol');
GetFeaturesCommand = (function(superClass) {
var RE_FEATURE;
extend(GetFeaturesCommand, superClass);
function GetFeaturesCommand() {
return GetFeaturesCommand.__super__.constructor.apply(this, arguments);
}
RE_FEATURE = /^feature:(.*?)(?:=(.*?))?\r?$/gm;
GetFeaturesCommand.prototype.execute = function() {
this._send('shell:pm list features 2>/dev/null');
return this.parser.readAscii(4).then((function(_this) {
return function(reply) {
switch (reply) {
case Protocol.OKAY:
return _this.parser.readAll().then(function(data) {
return _this._parseFeatures(data.toString());
});
case Protocol.FAIL:
return _this.parser.readError();
default:
return _this.parser.unexpected(reply, 'OKAY or FAIL');
}
};
})(this));
};
GetFeaturesCommand.prototype._parseFeatures = function(value) {
var features, match;
features = {};
while (match = RE_FEATURE.exec(value)) {
features[match[1]] = match[2] || true;
}
return features;
};
return GetFeaturesCommand;
})(Command);
module.exports = GetFeaturesCommand;
+51
View File
@@ -0,0 +1,51 @@
var Command, GetPackagesCommand, Protocol,
extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
hasProp = {}.hasOwnProperty;
Command = require('../../command');
Protocol = require('../../protocol');
GetPackagesCommand = (function(superClass) {
var RE_PACKAGE;
extend(GetPackagesCommand, superClass);
function GetPackagesCommand() {
return GetPackagesCommand.__super__.constructor.apply(this, arguments);
}
RE_PACKAGE = /^package:(.*?)\r?$/gm;
GetPackagesCommand.prototype.execute = function() {
this._send('shell:pm list packages 2>/dev/null');
return this.parser.readAscii(4).then((function(_this) {
return function(reply) {
switch (reply) {
case Protocol.OKAY:
return _this.parser.readAll().then(function(data) {
return _this._parsePackages(data.toString());
});
case Protocol.FAIL:
return _this.parser.readError();
default:
return _this.parser.unexpected(reply, 'OKAY or FAIL');
}
};
})(this));
};
GetPackagesCommand.prototype._parsePackages = function(value) {
var features, match;
features = [];
while (match = RE_PACKAGE.exec(value)) {
features.push(match[1]);
}
return features;
};
return GetPackagesCommand;
})(Command);
module.exports = GetPackagesCommand;
+51
View File
@@ -0,0 +1,51 @@
var Command, GetPropertiesCommand, Protocol,
extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
hasProp = {}.hasOwnProperty;
Command = require('../../command');
Protocol = require('../../protocol');
GetPropertiesCommand = (function(superClass) {
var RE_KEYVAL;
extend(GetPropertiesCommand, superClass);
function GetPropertiesCommand() {
return GetPropertiesCommand.__super__.constructor.apply(this, arguments);
}
RE_KEYVAL = /^\[([\s\S]*?)\]: \[([\s\S]*?)\]\r?$/gm;
GetPropertiesCommand.prototype.execute = function() {
this._send('shell:getprop');
return this.parser.readAscii(4).then((function(_this) {
return function(reply) {
switch (reply) {
case Protocol.OKAY:
return _this.parser.readAll().then(function(data) {
return _this._parseProperties(data.toString());
});
case Protocol.FAIL:
return _this.parser.readError();
default:
return _this.parser.unexpected(reply, 'OKAY or FAIL');
}
};
})(this));
};
GetPropertiesCommand.prototype._parseProperties = function(value) {
var match, properties;
properties = {};
while (match = RE_KEYVAL.exec(value)) {
properties[match[1]] = match[2];
}
return properties;
};
return GetPropertiesCommand;
})(Command);
module.exports = GetPropertiesCommand;
+48
View File
@@ -0,0 +1,48 @@
var Command, InstallCommand, Protocol,
extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
hasProp = {}.hasOwnProperty;
Command = require('../../command');
Protocol = require('../../protocol');
InstallCommand = (function(superClass) {
extend(InstallCommand, superClass);
function InstallCommand() {
return InstallCommand.__super__.constructor.apply(this, arguments);
}
InstallCommand.prototype.execute = function(apk) {
this._send("shell:pm install -r " + (this._escapeCompat(apk)));
return this.parser.readAscii(4).then((function(_this) {
return function(reply) {
switch (reply) {
case Protocol.OKAY:
return _this.parser.searchLine(/^(Success|Failure \[(.*?)\])$/).then(function(match) {
var code, err;
if (match[1] === 'Success') {
return true;
} else {
code = match[2];
err = new Error(apk + " could not be installed [" + code + "]");
err.code = code;
throw err;
}
})["finally"](function() {
return _this.parser.readAll();
});
case Protocol.FAIL:
return _this.parser.readError();
default:
return _this.parser.unexpected(reply, 'OKAY or FAIL');
}
};
})(this));
};
return InstallCommand;
})(Command);
module.exports = InstallCommand;
+47
View File
@@ -0,0 +1,47 @@
var Command, IsInstalledCommand, Parser, Protocol,
extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
hasProp = {}.hasOwnProperty;
Command = require('../../command');
Protocol = require('../../protocol');
Parser = require('../../parser');
IsInstalledCommand = (function(superClass) {
extend(IsInstalledCommand, superClass);
function IsInstalledCommand() {
return IsInstalledCommand.__super__.constructor.apply(this, arguments);
}
IsInstalledCommand.prototype.execute = function(pkg) {
this._send("shell:pm path " + pkg + " 2>/dev/null");
return this.parser.readAscii(4).then((function(_this) {
return function(reply) {
switch (reply) {
case Protocol.OKAY:
return _this.parser.readAscii(8).then(function(reply) {
switch (reply) {
case 'package:':
return true;
default:
return _this.parser.unexpected(reply, "'package:'");
}
})["catch"](Parser.PrematureEOFError, function(err) {
return false;
});
case Protocol.FAIL:
return _this.parser.readError();
default:
return _this.parser.unexpected(reply, 'OKAY or FAIL');
}
};
})(this));
};
return IsInstalledCommand;
})(Command);
module.exports = IsInstalledCommand;
+55
View File
@@ -0,0 +1,55 @@
var Command, ListReversesCommand, Protocol,
extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
hasProp = {}.hasOwnProperty;
Command = require('../../command');
Protocol = require('../../protocol');
ListReversesCommand = (function(superClass) {
extend(ListReversesCommand, superClass);
function ListReversesCommand() {
return ListReversesCommand.__super__.constructor.apply(this, arguments);
}
ListReversesCommand.prototype.execute = function() {
this._send("reverse:list-forward");
return this.parser.readAscii(4).then((function(_this) {
return function(reply) {
switch (reply) {
case Protocol.OKAY:
return _this.parser.readValue().then(function(value) {
return _this._parseReverses(value);
});
case Protocol.FAIL:
return _this.parser.readError();
default:
return _this.parser.unexpected(reply, 'OKAY or FAIL');
}
};
})(this));
};
ListReversesCommand.prototype._parseReverses = function(value) {
var i, len, local, ref, ref1, remote, reverse, reverses, serial;
reverses = [];
ref = value.toString().split('\n');
for (i = 0, len = ref.length; i < len; i++) {
reverse = ref[i];
if (reverse) {
ref1 = reverse.split(/\s+/), serial = ref1[0], remote = ref1[1], local = ref1[2];
reverses.push({
remote: remote,
local: local
});
}
}
return reverses;
};
return ListReversesCommand;
})(Command);
module.exports = ListReversesCommand;
+36
View File
@@ -0,0 +1,36 @@
var Command, LocalCommand, Protocol,
extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
hasProp = {}.hasOwnProperty;
Command = require('../../command');
Protocol = require('../../protocol');
LocalCommand = (function(superClass) {
extend(LocalCommand, superClass);
function LocalCommand() {
return LocalCommand.__super__.constructor.apply(this, arguments);
}
LocalCommand.prototype.execute = function(path) {
this._send(/:/.test(path) ? path : "localfilesystem:" + path);
return this.parser.readAscii(4).then((function(_this) {
return function(reply) {
switch (reply) {
case Protocol.OKAY:
return _this.parser.raw();
case Protocol.FAIL:
return _this.parser.readError();
default:
return _this.parser.unexpected(reply, 'OKAY or FAIL');
}
};
})(this));
};
return LocalCommand;
})(Command);
module.exports = LocalCommand;
+36
View File
@@ -0,0 +1,36 @@
var Command, LogCommand, Protocol,
extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
hasProp = {}.hasOwnProperty;
Command = require('../../command');
Protocol = require('../../protocol');
LogCommand = (function(superClass) {
extend(LogCommand, superClass);
function LogCommand() {
return LogCommand.__super__.constructor.apply(this, arguments);
}
LogCommand.prototype.execute = function(name) {
this._send("log:" + name);
return this.parser.readAscii(4).then((function(_this) {
return function(reply) {
switch (reply) {
case Protocol.OKAY:
return _this.parser.raw();
case Protocol.FAIL:
return _this.parser.readError();
default:
return _this.parser.unexpected(reply, 'OKAY or FAIL');
}
};
})(this));
};
return LogCommand;
})(Command);
module.exports = LogCommand;
+48
View File
@@ -0,0 +1,48 @@
var Command, LineTransform, LogcatCommand, Protocol,
extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
hasProp = {}.hasOwnProperty;
Command = require('../../command');
Protocol = require('../../protocol');
LineTransform = require('../../linetransform');
LogcatCommand = (function(superClass) {
extend(LogcatCommand, superClass);
function LogcatCommand() {
return LogcatCommand.__super__.constructor.apply(this, arguments);
}
LogcatCommand.prototype.execute = function(options) {
var cmd;
if (options == null) {
options = {};
}
cmd = 'logcat -B *:I 2>/dev/null';
if (options.clear) {
cmd = "logcat -c 2>/dev/null && " + cmd;
}
this._send("shell:echo && " + cmd);
return this.parser.readAscii(4).then((function(_this) {
return function(reply) {
switch (reply) {
case Protocol.OKAY:
return _this.parser.raw().pipe(new LineTransform({
autoDetect: true
}));
case Protocol.FAIL:
return _this.parser.readError();
default:
return _this.parser.unexpected(reply, 'OKAY or FAIL');
}
};
})(this));
};
return LogcatCommand;
})(Command);
module.exports = LogcatCommand;
+42
View File
@@ -0,0 +1,42 @@
var Command, MonkeyCommand, Promise, Protocol,
extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
hasProp = {}.hasOwnProperty;
Promise = require('bluebird');
Command = require('../../command');
Protocol = require('../../protocol');
MonkeyCommand = (function(superClass) {
extend(MonkeyCommand, superClass);
function MonkeyCommand() {
return MonkeyCommand.__super__.constructor.apply(this, arguments);
}
MonkeyCommand.prototype.execute = function(port) {
this._send("shell:EXTERNAL_STORAGE=/data/local/tmp monkey --port " + port + " -v");
return this.parser.readAscii(4).then((function(_this) {
return function(reply) {
switch (reply) {
case Protocol.OKAY:
return _this.parser.searchLine(/^:Monkey:/).timeout(1000).then(function() {
return _this.parser.raw();
})["catch"](Promise.TimeoutError, function(err) {
return _this.parser.raw();
});
case Protocol.FAIL:
return _this.parser.readError();
default:
return _this.parser.unexpected(reply, 'OKAY or FAIL');
}
};
})(this));
};
return MonkeyCommand;
})(Command);
module.exports = MonkeyCommand;
+36
View File
@@ -0,0 +1,36 @@
var Command, Protocol, RebootCommand,
extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
hasProp = {}.hasOwnProperty;
Command = require('../../command');
Protocol = require('../../protocol');
RebootCommand = (function(superClass) {
extend(RebootCommand, superClass);
function RebootCommand() {
return RebootCommand.__super__.constructor.apply(this, arguments);
}
RebootCommand.prototype.execute = function() {
this._send('reboot:');
return this.parser.readAscii(4).then((function(_this) {
return function(reply) {
switch (reply) {
case Protocol.OKAY:
return _this.parser.readAll()["return"](true);
case Protocol.FAIL:
return _this.parser.readError();
default:
return _this.parser.unexpected(reply, 'OKAY or FAIL');
}
};
})(this));
};
return RebootCommand;
})(Command);
module.exports = RebootCommand;
+36
View File
@@ -0,0 +1,36 @@
var Command, Protocol, RemountCommand,
extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
hasProp = {}.hasOwnProperty;
Command = require('../../command');
Protocol = require('../../protocol');
RemountCommand = (function(superClass) {
extend(RemountCommand, superClass);
function RemountCommand() {
return RemountCommand.__super__.constructor.apply(this, arguments);
}
RemountCommand.prototype.execute = function() {
this._send('remount:');
return this.parser.readAscii(4).then((function(_this) {
return function(reply) {
switch (reply) {
case Protocol.OKAY:
return true;
case Protocol.FAIL:
return _this.parser.readError();
default:
return _this.parser.unexpected(reply, 'OKAY or FAIL');
}
};
})(this));
};
return RemountCommand;
})(Command);
module.exports = RemountCommand;
+45
View File
@@ -0,0 +1,45 @@
var Command, Protocol, ReverseCommand,
extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
hasProp = {}.hasOwnProperty;
Command = require('../../command');
Protocol = require('../../protocol');
ReverseCommand = (function(superClass) {
extend(ReverseCommand, superClass);
function ReverseCommand() {
return ReverseCommand.__super__.constructor.apply(this, arguments);
}
ReverseCommand.prototype.execute = function(remote, local) {
this._send("reverse:forward:" + remote + ";" + local);
return this.parser.readAscii(4).then((function(_this) {
return function(reply) {
switch (reply) {
case Protocol.OKAY:
return _this.parser.readAscii(4).then(function(reply) {
switch (reply) {
case Protocol.OKAY:
return true;
case Protocol.FAIL:
return _this.parser.readError();
default:
return _this.parser.unexpected(reply, 'OKAY or FAIL');
}
});
case Protocol.FAIL:
return _this.parser.readError();
default:
return _this.parser.unexpected(reply, 'OKAY or FAIL');
}
};
})(this));
};
return ReverseCommand;
})(Command);
module.exports = ReverseCommand;
+46
View File
@@ -0,0 +1,46 @@
var Command, Protocol, RootCommand,
extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
hasProp = {}.hasOwnProperty;
Command = require('../../command');
Protocol = require('../../protocol');
RootCommand = (function(superClass) {
var RE_OK;
extend(RootCommand, superClass);
function RootCommand() {
return RootCommand.__super__.constructor.apply(this, arguments);
}
RE_OK = /restarting adbd as root/;
RootCommand.prototype.execute = function() {
this._send('root:');
return this.parser.readAscii(4).then((function(_this) {
return function(reply) {
switch (reply) {
case Protocol.OKAY:
return _this.parser.readAll().then(function(value) {
if (RE_OK.test(value)) {
return true;
} else {
throw new Error(value.toString().trim());
}
});
case Protocol.FAIL:
return _this.parser.readError();
default:
return _this.parser.unexpected(reply, 'OKAY or FAIL');
}
};
})(this));
};
return RootCommand;
})(Command);
module.exports = RootCommand;
+52
View File
@@ -0,0 +1,52 @@
var Command, LineTransform, Parser, Promise, Protocol, ScreencapCommand,
extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
hasProp = {}.hasOwnProperty;
Promise = require('bluebird');
Command = require('../../command');
Protocol = require('../../protocol');
Parser = require('../../parser');
LineTransform = require('../../linetransform');
ScreencapCommand = (function(superClass) {
extend(ScreencapCommand, superClass);
function ScreencapCommand() {
return ScreencapCommand.__super__.constructor.apply(this, arguments);
}
ScreencapCommand.prototype.execute = function() {
this._send('shell:echo && screencap -p 2>/dev/null');
return this.parser.readAscii(4).then((function(_this) {
return function(reply) {
var transform;
switch (reply) {
case Protocol.OKAY:
transform = new LineTransform;
return _this.parser.readBytes(1).then(function(chunk) {
transform = new LineTransform({
autoDetect: true
});
transform.write(chunk);
return _this.parser.raw().pipe(transform);
})["catch"](Parser.PrematureEOFError, function() {
throw new Error('No support for the screencap command');
});
case Protocol.FAIL:
return _this.parser.readError();
default:
return _this.parser.unexpected(reply, 'OKAY or FAIL');
}
};
})(this));
};
return ScreencapCommand;
})(Command);
module.exports = ScreencapCommand;
+39
View File
@@ -0,0 +1,39 @@
var Command, Protocol, ShellCommand,
extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
hasProp = {}.hasOwnProperty;
Command = require('../../command');
Protocol = require('../../protocol');
ShellCommand = (function(superClass) {
extend(ShellCommand, superClass);
function ShellCommand() {
return ShellCommand.__super__.constructor.apply(this, arguments);
}
ShellCommand.prototype.execute = function(command) {
if (Array.isArray(command)) {
command = command.map(this._escape).join(' ');
}
this._send("shell:" + command);
return this.parser.readAscii(4).then((function(_this) {
return function(reply) {
switch (reply) {
case Protocol.OKAY:
return _this.parser.raw();
case Protocol.FAIL:
return _this.parser.readError();
default:
return _this.parser.unexpected(reply, 'OKAY or FAIL');
}
};
})(this));
};
return ShellCommand;
})(Command);
module.exports = ShellCommand;
+184
View File
@@ -0,0 +1,184 @@
var Command, Parser, Protocol, StartActivityCommand,
extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
hasProp = {}.hasOwnProperty;
Command = require('../../command');
Protocol = require('../../protocol');
Parser = require('../../parser');
StartActivityCommand = (function(superClass) {
var EXTRA_TYPES, RE_ERROR;
extend(StartActivityCommand, superClass);
function StartActivityCommand() {
return StartActivityCommand.__super__.constructor.apply(this, arguments);
}
RE_ERROR = /^Error: (.*)$/;
EXTRA_TYPES = {
string: 's',
"null": 'sn',
bool: 'z',
int: 'i',
long: 'l',
float: 'l',
uri: 'u',
component: 'cn'
};
StartActivityCommand.prototype.execute = function(options) {
var args;
args = this._intentArgs(options);
if (options.debug) {
args.push('-D');
}
if (options.wait) {
args.push('-W');
}
if (options.user || options.user === 0) {
args.push('--user', this._escape(options.user));
}
return this._run('start', args);
};
StartActivityCommand.prototype._run = function(command, args) {
this._send("shell:am " + command + " " + (args.join(' ')));
return this.parser.readAscii(4).then((function(_this) {
return function(reply) {
switch (reply) {
case Protocol.OKAY:
return _this.parser.searchLine(RE_ERROR)["finally"](function() {
return _this.parser.end();
}).then(function(match) {
throw new Error(match[1]);
})["catch"](Parser.PrematureEOFError, function(err) {
return true;
});
case Protocol.FAIL:
return _this.parser.readError();
default:
return _this.parser.unexpected(reply, 'OKAY or FAIL');
}
};
})(this));
};
StartActivityCommand.prototype._intentArgs = function(options) {
var args;
args = [];
if (options.extras) {
args.push.apply(args, this._formatExtras(options.extras));
}
if (options.action) {
args.push('-a', this._escape(options.action));
}
if (options.data) {
args.push('-d', this._escape(options.data));
}
if (options.mimeType) {
args.push('-t', this._escape(options.mimeType));
}
if (options.category) {
if (Array.isArray(options.category)) {
options.category.forEach((function(_this) {
return function(category) {
return args.push('-c', _this._escape(category));
};
})(this));
} else {
args.push('-c', this._escape(options.category));
}
}
if (options.component) {
args.push('-n', this._escape(options.component));
}
if (options.flags) {
args.push('-f', this._escape(options.flags));
}
return args;
};
StartActivityCommand.prototype._formatExtras = function(extras) {
if (!extras) {
return [];
}
if (Array.isArray(extras)) {
return extras.reduce((function(_this) {
return function(all, extra) {
return all.concat(_this._formatLongExtra(extra));
};
})(this), []);
} else {
return Object.keys(extras).reduce((function(_this) {
return function(all, key) {
return all.concat(_this._formatShortExtra(key, extras[key]));
};
})(this), []);
}
};
StartActivityCommand.prototype._formatShortExtra = function(key, value) {
var sugared;
sugared = {
key: key
};
if (value === null) {
sugared.type = 'null';
} else if (Array.isArray(value)) {
throw new Error("Refusing to format array value '" + key + "' using short syntax; empty array would cause unpredictable results due to unknown type. Please use long syntax instead.");
} else {
switch (typeof value) {
case 'string':
sugared.type = 'string';
sugared.value = value;
break;
case 'boolean':
sugared.type = 'bool';
sugared.value = value;
break;
case 'number':
sugared.type = 'int';
sugared.value = value;
break;
case 'object':
sugared = value;
sugared.key = key;
}
}
return this._formatLongExtra(sugared);
};
StartActivityCommand.prototype._formatLongExtra = function(extra) {
var args, type;
args = [];
if (!extra.type) {
extra.type = 'string';
}
type = EXTRA_TYPES[extra.type];
if (!type) {
throw new Error("Unsupported type '" + extra.type + "' for extra '" + extra.key + "'");
}
if (extra.type === 'null') {
args.push("--e" + type);
args.push(this._escape(extra.key));
} else if (Array.isArray(extra.value)) {
args.push("--e" + type + "a");
args.push(this._escape(extra.key));
args.push(this._escape(extra.value.join(',')));
} else {
args.push("--e" + type);
args.push(this._escape(extra.key));
args.push(this._escape(extra.value));
}
return args;
};
return StartActivityCommand;
})(Command);
module.exports = StartActivityCommand;
+33
View File
@@ -0,0 +1,33 @@
var Command, Parser, Protocol, StartActivityCommand, StartServiceCommand,
extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
hasProp = {}.hasOwnProperty;
Command = require('../../command');
Protocol = require('../../protocol');
Parser = require('../../parser');
StartActivityCommand = require('./startactivity');
StartServiceCommand = (function(superClass) {
extend(StartServiceCommand, superClass);
function StartServiceCommand() {
return StartServiceCommand.__super__.constructor.apply(this, arguments);
}
StartServiceCommand.prototype.execute = function(options) {
var args;
args = this._intentArgs(options);
if (options.user || options.user === 0) {
args.push('--user', this._escape(options.user));
}
return this._run('startservice', args);
};
return StartServiceCommand;
})(StartActivityCommand);
module.exports = StartServiceCommand;
+38
View File
@@ -0,0 +1,38 @@
var Command, Protocol, Sync, SyncCommand,
extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
hasProp = {}.hasOwnProperty;
Command = require('../../command');
Protocol = require('../../protocol');
Sync = require('../../sync');
SyncCommand = (function(superClass) {
extend(SyncCommand, superClass);
function SyncCommand() {
return SyncCommand.__super__.constructor.apply(this, arguments);
}
SyncCommand.prototype.execute = function() {
this._send('sync:');
return this.parser.readAscii(4).then((function(_this) {
return function(reply) {
switch (reply) {
case Protocol.OKAY:
return new Sync(_this.connection);
case Protocol.FAIL:
return _this.parser.readError();
default:
return _this.parser.unexpected(reply, 'OKAY or FAIL');
}
};
})(this));
};
return SyncCommand;
})(Command);
module.exports = SyncCommand;
+36
View File
@@ -0,0 +1,36 @@
var Command, Protocol, TcpCommand,
extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
hasProp = {}.hasOwnProperty;
Command = require('../../command');
Protocol = require('../../protocol');
TcpCommand = (function(superClass) {
extend(TcpCommand, superClass);
function TcpCommand() {
return TcpCommand.__super__.constructor.apply(this, arguments);
}
TcpCommand.prototype.execute = function(port, host) {
this._send(("tcp:" + port) + (host ? ":" + host : ''));
return this.parser.readAscii(4).then((function(_this) {
return function(reply) {
switch (reply) {
case Protocol.OKAY:
return _this.parser.raw();
case Protocol.FAIL:
return _this.parser.readError();
default:
return _this.parser.unexpected(reply, 'OKAY or FAIL');
}
};
})(this));
};
return TcpCommand;
})(Command);
module.exports = TcpCommand;
+46
View File
@@ -0,0 +1,46 @@
var Command, Protocol, TcpIpCommand,
extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
hasProp = {}.hasOwnProperty;
Command = require('../../command');
Protocol = require('../../protocol');
TcpIpCommand = (function(superClass) {
var RE_OK;
extend(TcpIpCommand, superClass);
function TcpIpCommand() {
return TcpIpCommand.__super__.constructor.apply(this, arguments);
}
RE_OK = /restarting in/;
TcpIpCommand.prototype.execute = function(port) {
this._send("tcpip:" + port);
return this.parser.readAscii(4).then((function(_this) {
return function(reply) {
switch (reply) {
case Protocol.OKAY:
return _this.parser.readAll().then(function(value) {
if (RE_OK.test(value)) {
return port;
} else {
throw new Error(value.toString().trim());
}
});
case Protocol.FAIL:
return _this.parser.readError();
default:
return _this.parser.unexpected(reply, 'OKAY or FAIL');
}
};
})(this));
};
return TcpIpCommand;
})(Command);
module.exports = TcpIpCommand;
+120
View File
@@ -0,0 +1,120 @@
var Command, EventEmitter, Parser, Promise, Protocol, TrackJdwpCommand,
extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
hasProp = {}.hasOwnProperty;
EventEmitter = require('events').EventEmitter;
Promise = require('bluebird');
Command = require('../../command');
Protocol = require('../../protocol');
Parser = require('../../parser');
TrackJdwpCommand = (function(superClass) {
var Tracker;
extend(TrackJdwpCommand, superClass);
function TrackJdwpCommand() {
return TrackJdwpCommand.__super__.constructor.apply(this, arguments);
}
TrackJdwpCommand.prototype.execute = function() {
this._send('track-jdwp');
return this.parser.readAscii(4).then((function(_this) {
return function(reply) {
switch (reply) {
case Protocol.OKAY:
return new Tracker(_this);
case Protocol.FAIL:
return _this.parser.readError();
default:
return _this.parser.unexpected(reply, 'OKAY or FAIL');
}
};
})(this));
};
Tracker = (function(superClass1) {
extend(Tracker, superClass1);
function Tracker(command) {
this.command = command;
this.pids = [];
this.pidMap = Object.create(null);
this.reader = this.read()["catch"](Parser.PrematureEOFError, (function(_this) {
return function(err) {
return _this.emit('end');
};
})(this))["catch"](Promise.CancellationError, (function(_this) {
return function(err) {
_this.command.connection.end();
return _this.emit('end');
};
})(this))["catch"]((function(_this) {
return function(err) {
_this.command.connection.end();
_this.emit('error', err);
return _this.emit('end');
};
})(this));
}
Tracker.prototype.read = function() {
return this.command.parser.readValue().cancellable().then((function(_this) {
return function(list) {
var maybeEmpty, pids;
pids = list.toString().split('\n');
if (maybeEmpty = pids.pop()) {
pids.push(maybeEmpty);
}
return _this.update(pids);
};
})(this));
};
Tracker.prototype.update = function(newList) {
var changeSet, i, j, len, len1, newMap, pid, ref;
changeSet = {
removed: [],
added: []
};
newMap = Object.create(null);
for (i = 0, len = newList.length; i < len; i++) {
pid = newList[i];
if (!this.pidMap[pid]) {
changeSet.added.push(pid);
this.emit('add', pid);
newMap[pid] = pid;
}
}
ref = this.pids;
for (j = 0, len1 = ref.length; j < len1; j++) {
pid = ref[j];
if (!newMap[pid]) {
changeSet.removed.push(pid);
this.emit('remove', pid);
}
}
this.pids = newList;
this.pidMap = newMap;
this.emit('changeSet', changeSet, newList);
return this;
};
Tracker.prototype.end = function() {
this.reader.cancel();
return this;
};
return Tracker;
})(EventEmitter);
return TrackJdwpCommand;
})(Command);
module.exports = TrackJdwpCommand;
+44
View File
@@ -0,0 +1,44 @@
var Command, Protocol, UninstallCommand,
extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
hasProp = {}.hasOwnProperty;
Command = require('../../command');
Protocol = require('../../protocol');
UninstallCommand = (function(superClass) {
extend(UninstallCommand, superClass);
function UninstallCommand() {
return UninstallCommand.__super__.constructor.apply(this, arguments);
}
UninstallCommand.prototype.execute = function(pkg) {
this._send("shell:pm uninstall " + pkg);
return this.parser.readAscii(4).then((function(_this) {
return function(reply) {
switch (reply) {
case Protocol.OKAY:
return _this.parser.searchLine(/^(Success|Failure.*|.*Unknown package:.*)$/).then(function(match) {
if (match[1] === 'Success') {
return true;
} else {
return true;
}
})["finally"](function() {
return _this.parser.readAll();
});
case Protocol.FAIL:
return _this.parser.readError();
default:
return _this.parser.unexpected(reply, "OKAY or FAIL");
}
};
})(this));
};
return UninstallCommand;
})(Command);
module.exports = UninstallCommand;
+46
View File
@@ -0,0 +1,46 @@
var Command, Protocol, UsbCommand,
extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
hasProp = {}.hasOwnProperty;
Command = require('../../command');
Protocol = require('../../protocol');
UsbCommand = (function(superClass) {
var RE_OK;
extend(UsbCommand, superClass);
function UsbCommand() {
return UsbCommand.__super__.constructor.apply(this, arguments);
}
RE_OK = /restarting in/;
UsbCommand.prototype.execute = function() {
this._send('usb:');
return this.parser.readAscii(4).then((function(_this) {
return function(reply) {
switch (reply) {
case Protocol.OKAY:
return _this.parser.readAll().then(function(value) {
if (RE_OK.test(value)) {
return true;
} else {
throw new Error(value.toString().trim());
}
});
case Protocol.FAIL:
return _this.parser.readError();
default:
return _this.parser.unexpected(reply, 'OKAY or FAIL');
}
};
})(this));
};
return UsbCommand;
})(Command);
module.exports = UsbCommand;
+42
View File
@@ -0,0 +1,42 @@
var Command, Protocol, WaitBootCompleteCommand, debug,
extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
hasProp = {}.hasOwnProperty;
debug = require('debug')('adb:command:waitboot');
Command = require('../../command');
Protocol = require('../../protocol');
WaitBootCompleteCommand = (function(superClass) {
extend(WaitBootCompleteCommand, superClass);
function WaitBootCompleteCommand() {
return WaitBootCompleteCommand.__super__.constructor.apply(this, arguments);
}
WaitBootCompleteCommand.prototype.execute = function() {
this._send('shell:while getprop sys.boot_completed 2>/dev/null; do sleep 1; done');
return this.parser.readAscii(4).then((function(_this) {
return function(reply) {
switch (reply) {
case Protocol.OKAY:
return _this.parser.searchLine(/^1$/)["finally"](function() {
return _this.parser.end();
}).then(function() {
return true;
});
case Protocol.FAIL:
return _this.parser.readError();
default:
return _this.parser.unexpected(reply, 'OKAY or FAIL');
}
};
})(this));
};
return WaitBootCompleteCommand;
})(Command);
module.exports = WaitBootCompleteCommand;
+46
View File
@@ -0,0 +1,46 @@
var Command, ConnectCommand, Protocol,
extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
hasProp = {}.hasOwnProperty;
Command = require('../../command');
Protocol = require('../../protocol');
ConnectCommand = (function(superClass) {
var RE_OK;
extend(ConnectCommand, superClass);
function ConnectCommand() {
return ConnectCommand.__super__.constructor.apply(this, arguments);
}
RE_OK = /connected to|already connected/;
ConnectCommand.prototype.execute = function(host, port) {
this._send("host:connect:" + host + ":" + port);
return this.parser.readAscii(4).then((function(_this) {
return function(reply) {
switch (reply) {
case Protocol.OKAY:
return _this.parser.readValue().then(function(value) {
if (RE_OK.test(value)) {
return host + ":" + port;
} else {
throw new Error(value.toString());
}
});
case Protocol.FAIL:
return _this.parser.readError();
default:
return _this.parser.unexpected(reply, 'OKAY or FAIL');
}
};
})(this));
};
return ConnectCommand;
})(Command);
module.exports = ConnectCommand;
+64
View File
@@ -0,0 +1,64 @@
var Command, HostDevicesCommand, Protocol,
extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
hasProp = {}.hasOwnProperty;
Command = require('../../command');
Protocol = require('../../protocol');
HostDevicesCommand = (function(superClass) {
extend(HostDevicesCommand, superClass);
function HostDevicesCommand() {
return HostDevicesCommand.__super__.constructor.apply(this, arguments);
}
HostDevicesCommand.prototype.execute = function() {
this._send('host:devices');
return this.parser.readAscii(4).then((function(_this) {
return function(reply) {
switch (reply) {
case Protocol.OKAY:
return _this._readDevices();
case Protocol.FAIL:
return _this.parser.readError();
default:
return _this.parser.unexpected(reply, 'OKAY or FAIL');
}
};
})(this));
};
HostDevicesCommand.prototype._readDevices = function() {
return this.parser.readValue().then((function(_this) {
return function(value) {
return _this._parseDevices(value);
};
})(this));
};
HostDevicesCommand.prototype._parseDevices = function(value) {
var devices, i, id, len, line, ref, ref1, type;
devices = [];
if (!value.length) {
return devices;
}
ref = value.toString('ascii').split('\n');
for (i = 0, len = ref.length; i < len; i++) {
line = ref[i];
if (line) {
ref1 = line.split('\t'), id = ref1[0], type = ref1[1];
devices.push({
id: id,
type: type
});
}
}
return devices;
};
return HostDevicesCommand;
})(Command);
module.exports = HostDevicesCommand;
+65
View File
@@ -0,0 +1,65 @@
var Command, HostDevicesWithPathsCommand, Protocol,
extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
hasProp = {}.hasOwnProperty;
Command = require('../../command');
Protocol = require('../../protocol');
HostDevicesWithPathsCommand = (function(superClass) {
extend(HostDevicesWithPathsCommand, superClass);
function HostDevicesWithPathsCommand() {
return HostDevicesWithPathsCommand.__super__.constructor.apply(this, arguments);
}
HostDevicesWithPathsCommand.prototype.execute = function() {
this._send('host:devices-l');
return this.parser.readAscii(4).then((function(_this) {
return function(reply) {
switch (reply) {
case Protocol.OKAY:
return _this._readDevices();
case Protocol.FAIL:
return _this.parser.readError();
default:
return _this.parser.unexpected(reply, 'OKAY or FAIL');
}
};
})(this));
};
HostDevicesWithPathsCommand.prototype._readDevices = function() {
return this.parser.readValue().then((function(_this) {
return function(value) {
return _this._parseDevices(value);
};
})(this));
};
HostDevicesWithPathsCommand.prototype._parseDevices = function(value) {
var devices, i, id, len, line, path, ref, ref1, type;
devices = [];
if (!value.length) {
return devices;
}
ref = value.toString('ascii').split('\n');
for (i = 0, len = ref.length; i < len; i++) {
line = ref[i];
if (line) {
ref1 = line.split(/\s+/), id = ref1[0], type = ref1[1], path = ref1[2];
devices.push({
id: id,
type: type,
path: path
});
}
}
return devices;
};
return HostDevicesWithPathsCommand;
})(Command);
module.exports = HostDevicesWithPathsCommand;
+46
View File
@@ -0,0 +1,46 @@
var Command, DisconnectCommand, Protocol,
extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
hasProp = {}.hasOwnProperty;
Command = require('../../command');
Protocol = require('../../protocol');
DisconnectCommand = (function(superClass) {
var RE_OK;
extend(DisconnectCommand, superClass);
function DisconnectCommand() {
return DisconnectCommand.__super__.constructor.apply(this, arguments);
}
RE_OK = /^$/;
DisconnectCommand.prototype.execute = function(host, port) {
this._send("host:disconnect:" + host + ":" + port);
return this.parser.readAscii(4).then((function(_this) {
return function(reply) {
switch (reply) {
case Protocol.OKAY:
return _this.parser.readValue().then(function(value) {
if (RE_OK.test(value)) {
return host + ":" + port;
} else {
throw new Error(value.toString());
}
});
case Protocol.FAIL:
return _this.parser.readError();
default:
return _this.parser.unexpected(reply, 'OKAY or FAIL');
}
};
})(this));
};
return DisconnectCommand;
})(Command);
module.exports = DisconnectCommand;
+36
View File
@@ -0,0 +1,36 @@
var Command, HostKillCommand, Protocol,
extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
hasProp = {}.hasOwnProperty;
Command = require('../../command');
Protocol = require('../../protocol');
HostKillCommand = (function(superClass) {
extend(HostKillCommand, superClass);
function HostKillCommand() {
return HostKillCommand.__super__.constructor.apply(this, arguments);
}
HostKillCommand.prototype.execute = function() {
this._send('host:kill');
return this.parser.readAscii(4).then((function(_this) {
return function(reply) {
switch (reply) {
case Protocol.OKAY:
return true;
case Protocol.FAIL:
return _this.parser.readError();
default:
return _this.parser.unexpected(reply, 'OKAY or FAIL');
}
};
})(this));
};
return HostKillCommand;
})(Command);
module.exports = HostKillCommand;
+40
View File
@@ -0,0 +1,40 @@
var Command, HostDevicesCommand, HostTrackDevicesCommand, Protocol, Tracker,
extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
hasProp = {}.hasOwnProperty;
Command = require('../../command');
Protocol = require('../../protocol');
Tracker = require('../../tracker');
HostDevicesCommand = require('./devices');
HostTrackDevicesCommand = (function(superClass) {
extend(HostTrackDevicesCommand, superClass);
function HostTrackDevicesCommand() {
return HostTrackDevicesCommand.__super__.constructor.apply(this, arguments);
}
HostTrackDevicesCommand.prototype.execute = function() {
this._send('host:track-devices');
return this.parser.readAscii(4).then((function(_this) {
return function(reply) {
switch (reply) {
case Protocol.OKAY:
return new Tracker(_this);
case Protocol.FAIL:
return _this.parser.readError();
default:
return _this.parser.unexpected(reply, 'OKAY or FAIL');
}
};
})(this));
};
return HostTrackDevicesCommand;
})(HostDevicesCommand);
module.exports = HostTrackDevicesCommand;
+36
View File
@@ -0,0 +1,36 @@
var Command, HostTransportCommand, Protocol,
extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
hasProp = {}.hasOwnProperty;
Command = require('../../command');
Protocol = require('../../protocol');
HostTransportCommand = (function(superClass) {
extend(HostTransportCommand, superClass);
function HostTransportCommand() {
return HostTransportCommand.__super__.constructor.apply(this, arguments);
}
HostTransportCommand.prototype.execute = function(serial) {
this._send("host:transport:" + serial);
return this.parser.readAscii(4).then((function(_this) {
return function(reply) {
switch (reply) {
case Protocol.OKAY:
return true;
case Protocol.FAIL:
return _this.parser.readError();
default:
return _this.parser.unexpected(reply, 'OKAY or FAIL');
}
};
})(this));
};
return HostTransportCommand;
})(Command);
module.exports = HostTransportCommand;
+42
View File
@@ -0,0 +1,42 @@
var Command, HostVersionCommand, Protocol,
extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
hasProp = {}.hasOwnProperty;
Command = require('../../command');
Protocol = require('../../protocol');
HostVersionCommand = (function(superClass) {
extend(HostVersionCommand, superClass);
function HostVersionCommand() {
return HostVersionCommand.__super__.constructor.apply(this, arguments);
}
HostVersionCommand.prototype.execute = function() {
this._send('host:version');
return this.parser.readAscii(4).then((function(_this) {
return function(reply) {
switch (reply) {
case Protocol.OKAY:
return _this.parser.readValue().then(function(value) {
return _this._parseVersion(value);
});
case Protocol.FAIL:
return _this.parser.readError();
default:
return _this._parseVersion(reply);
}
};
})(this));
};
HostVersionCommand.prototype._parseVersion = function(version) {
return parseInt(version, 16);
};
return HostVersionCommand;
})(Command);
module.exports = HostVersionCommand;
+108
View File
@@ -0,0 +1,108 @@
var Connection, EventEmitter, Net, Parser, debug, dump, execFile,
extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
hasProp = {}.hasOwnProperty;
Net = require('net');
debug = require('debug')('adb:connection');
EventEmitter = require('events').EventEmitter;
execFile = require('child_process').execFile;
Parser = require('./parser');
dump = require('./dump');
Connection = (function(superClass) {
extend(Connection, superClass);
function Connection(options1) {
this.options = options1;
this.socket = null;
this.parser = null;
this.triedStarting = false;
}
Connection.prototype.connect = function() {
this.socket = Net.connect(this.options);
this.socket.setNoDelay(true);
this.parser = new Parser(this.socket);
this.socket.on('connect', (function(_this) {
return function() {
return _this.emit('connect');
};
})(this));
this.socket.on('end', (function(_this) {
return function() {
return _this.emit('end');
};
})(this));
this.socket.on('drain', (function(_this) {
return function() {
return _this.emit('drain');
};
})(this));
this.socket.on('timeout', (function(_this) {
return function() {
return _this.emit('timeout');
};
})(this));
this.socket.on('error', (function(_this) {
return function(err) {
return _this._handleError(err);
};
})(this));
this.socket.on('close', (function(_this) {
return function(hadError) {
return _this.emit('close', hadError);
};
})(this));
return this;
};
Connection.prototype.end = function() {
this.socket.end();
return this;
};
Connection.prototype.write = function(data, callback) {
this.socket.write(dump(data), callback);
return this;
};
Connection.prototype.startServer = function(callback) {
debug("Starting ADB server via '" + this.options.bin + " start-server'");
return this._exec(['start-server'], {}, callback);
};
Connection.prototype._exec = function(args, options, callback) {
debug("CLI: " + this.options.bin + " " + (args.join(' ')));
execFile(this.options.bin, args, options, callback);
return this;
};
Connection.prototype._handleError = function(err) {
if (err.code === 'ECONNREFUSED' && !this.triedStarting) {
debug("Connection was refused, let's try starting the server once");
this.triedStarting = true;
this.startServer((function(_this) {
return function(err) {
if (err) {
return _this._handleError(err);
}
return _this.connect();
};
})(this));
} else {
debug("Connection had an error: " + err.message);
this.emit('error', err);
this.end();
}
};
return Connection;
})(EventEmitter);
module.exports = Connection;
+15
View File
@@ -0,0 +1,15 @@
var fs, out;
fs = require('fs');
if (process.env.ADBKIT_DUMP) {
out = fs.createWriteStream('adbkit.dump');
module.exports = function(chunk) {
out.write(chunk);
return chunk;
};
} else {
module.exports = function(chunk) {
return chunk;
};
}
+55
View File
@@ -0,0 +1,55 @@
var Assert, RgbTransform, Stream,
extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
hasProp = {}.hasOwnProperty;
Assert = require('assert');
Stream = require('stream');
RgbTransform = (function(superClass) {
extend(RgbTransform, superClass);
function RgbTransform(meta, options) {
this.meta = meta;
this._buffer = new Buffer('');
Assert.ok(this.meta.bpp === 24 || this.meta.bpp === 32, 'Only 24-bit and 32-bit raw images with 8-bits per color are supported');
this._r_pos = this.meta.red_offset / 8;
this._g_pos = this.meta.green_offset / 8;
this._b_pos = this.meta.blue_offset / 8;
this._a_pos = this.meta.alpha_offset / 8;
this._pixel_bytes = this.meta.bpp / 8;
RgbTransform.__super__.constructor.call(this, options);
}
RgbTransform.prototype._transform = function(chunk, encoding, done) {
var b, g, r, sourceCursor, target, targetCursor;
if (this._buffer.length) {
this._buffer = Buffer.concat([this._buffer, chunk], this._buffer.length + chunk.length);
} else {
this._buffer = chunk;
}
sourceCursor = 0;
targetCursor = 0;
target = this._pixel_bytes === 3 ? this._buffer : new Buffer(Math.max(4, chunk.length / this._pixel_bytes * 3));
while (this._buffer.length - sourceCursor >= this._pixel_bytes) {
r = this._buffer[sourceCursor + this._r_pos];
g = this._buffer[sourceCursor + this._g_pos];
b = this._buffer[sourceCursor + this._b_pos];
target[targetCursor + 0] = r;
target[targetCursor + 1] = g;
target[targetCursor + 2] = b;
sourceCursor += this._pixel_bytes;
targetCursor += 3;
}
if (targetCursor) {
this.push(target.slice(0, targetCursor));
this._buffer = this._buffer.slice(sourceCursor);
}
done();
};
return RgbTransform;
})(Stream.Transform);
module.exports = RgbTransform;
+225
View File
@@ -0,0 +1,225 @@
module.exports = {
KEYCODE_UNKNOWN: 0,
KEYCODE_SOFT_LEFT: 1,
KEYCODE_SOFT_RIGHT: 2,
KEYCODE_HOME: 3,
KEYCODE_BACK: 4,
KEYCODE_CALL: 5,
KEYCODE_ENDCALL: 6,
KEYCODE_0: 7,
KEYCODE_1: 8,
KEYCODE_2: 9,
KEYCODE_3: 10,
KEYCODE_4: 11,
KEYCODE_5: 12,
KEYCODE_6: 13,
KEYCODE_7: 14,
KEYCODE_8: 15,
KEYCODE_9: 16,
KEYCODE_STAR: 17,
KEYCODE_POUND: 18,
KEYCODE_DPAD_UP: 19,
KEYCODE_DPAD_DOWN: 20,
KEYCODE_DPAD_LEFT: 21,
KEYCODE_DPAD_RIGHT: 22,
KEYCODE_DPAD_CENTER: 23,
KEYCODE_VOLUME_UP: 24,
KEYCODE_VOLUME_DOWN: 25,
KEYCODE_POWER: 26,
KEYCODE_CAMERA: 27,
KEYCODE_CLEAR: 28,
KEYCODE_A: 29,
KEYCODE_B: 30,
KEYCODE_C: 31,
KEYCODE_D: 32,
KEYCODE_E: 33,
KEYCODE_F: 34,
KEYCODE_G: 35,
KEYCODE_H: 36,
KEYCODE_I: 37,
KEYCODE_J: 38,
KEYCODE_K: 39,
KEYCODE_L: 40,
KEYCODE_M: 41,
KEYCODE_N: 42,
KEYCODE_O: 43,
KEYCODE_P: 44,
KEYCODE_Q: 45,
KEYCODE_R: 46,
KEYCODE_S: 47,
KEYCODE_T: 48,
KEYCODE_U: 49,
KEYCODE_V: 50,
KEYCODE_W: 51,
KEYCODE_X: 52,
KEYCODE_Y: 53,
KEYCODE_Z: 54,
KEYCODE_COMMA: 55,
KEYCODE_PERIOD: 56,
KEYCODE_ALT_LEFT: 57,
KEYCODE_ALT_RIGHT: 58,
KEYCODE_SHIFT_LEFT: 59,
KEYCODE_SHIFT_RIGHT: 60,
KEYCODE_TAB: 61,
KEYCODE_SPACE: 62,
KEYCODE_SYM: 63,
KEYCODE_EXPLORER: 64,
KEYCODE_ENVELOPE: 65,
KEYCODE_ENTER: 66,
KEYCODE_DEL: 67,
KEYCODE_GRAVE: 68,
KEYCODE_MINUS: 69,
KEYCODE_EQUALS: 70,
KEYCODE_LEFT_BRACKET: 71,
KEYCODE_RIGHT_BRACKET: 72,
KEYCODE_BACKSLASH: 73,
KEYCODE_SEMICOLON: 74,
KEYCODE_APOSTROPHE: 75,
KEYCODE_SLASH: 76,
KEYCODE_AT: 77,
KEYCODE_NUM: 78,
KEYCODE_HEADSETHOOK: 79,
KEYCODE_FOCUS: 80,
KEYCODE_PLUS: 81,
KEYCODE_MENU: 82,
KEYCODE_NOTIFICATION: 83,
KEYCODE_SEARCH: 84,
KEYCODE_MEDIA_PLAY_PAUSE: 85,
KEYCODE_MEDIA_STOP: 86,
KEYCODE_MEDIA_NEXT: 87,
KEYCODE_MEDIA_PREVIOUS: 88,
KEYCODE_MEDIA_REWIND: 89,
KEYCODE_MEDIA_FAST_FORWARD: 90,
KEYCODE_MUTE: 91,
KEYCODE_PAGE_UP: 92,
KEYCODE_PAGE_DOWN: 93,
KEYCODE_PICTSYMBOLS: 94,
KEYCODE_SWITCH_CHARSET: 95,
KEYCODE_BUTTON_A: 96,
KEYCODE_BUTTON_B: 97,
KEYCODE_BUTTON_C: 98,
KEYCODE_BUTTON_X: 99,
KEYCODE_BUTTON_Y: 100,
KEYCODE_BUTTON_Z: 101,
KEYCODE_BUTTON_L1: 102,
KEYCODE_BUTTON_R1: 103,
KEYCODE_BUTTON_L2: 104,
KEYCODE_BUTTON_R2: 105,
KEYCODE_BUTTON_THUMBL: 106,
KEYCODE_BUTTON_THUMBR: 107,
KEYCODE_BUTTON_START: 108,
KEYCODE_BUTTON_SELECT: 109,
KEYCODE_BUTTON_MODE: 110,
KEYCODE_ESCAPE: 111,
KEYCODE_FORWARD_DEL: 112,
KEYCODE_CTRL_LEFT: 113,
KEYCODE_CTRL_RIGHT: 114,
KEYCODE_CAPS_LOCK: 115,
KEYCODE_SCROLL_LOCK: 116,
KEYCODE_META_LEFT: 117,
KEYCODE_META_RIGHT: 118,
KEYCODE_FUNCTION: 119,
KEYCODE_SYSRQ: 120,
KEYCODE_BREAK: 121,
KEYCODE_MOVE_HOME: 122,
KEYCODE_MOVE_END: 123,
KEYCODE_INSERT: 124,
KEYCODE_FORWARD: 125,
KEYCODE_MEDIA_PLAY: 126,
KEYCODE_MEDIA_PAUSE: 127,
KEYCODE_MEDIA_CLOSE: 128,
KEYCODE_MEDIA_EJECT: 129,
KEYCODE_MEDIA_RECORD: 130,
KEYCODE_F1: 131,
KEYCODE_F2: 132,
KEYCODE_F3: 133,
KEYCODE_F4: 134,
KEYCODE_F5: 135,
KEYCODE_F6: 136,
KEYCODE_F7: 137,
KEYCODE_F8: 138,
KEYCODE_F9: 139,
KEYCODE_F10: 140,
KEYCODE_F11: 141,
KEYCODE_F12: 142,
KEYCODE_NUM_LOCK: 143,
KEYCODE_NUMPAD_0: 144,
KEYCODE_NUMPAD_1: 145,
KEYCODE_NUMPAD_2: 146,
KEYCODE_NUMPAD_3: 147,
KEYCODE_NUMPAD_4: 148,
KEYCODE_NUMPAD_5: 149,
KEYCODE_NUMPAD_6: 150,
KEYCODE_NUMPAD_7: 151,
KEYCODE_NUMPAD_8: 152,
KEYCODE_NUMPAD_9: 153,
KEYCODE_NUMPAD_DIVIDE: 154,
KEYCODE_NUMPAD_MULTIPLY: 155,
KEYCODE_NUMPAD_SUBTRACT: 156,
KEYCODE_NUMPAD_ADD: 157,
KEYCODE_NUMPAD_DOT: 158,
KEYCODE_NUMPAD_COMMA: 159,
KEYCODE_NUMPAD_ENTER: 160,
KEYCODE_NUMPAD_EQUALS: 161,
KEYCODE_NUMPAD_LEFT_PAREN: 162,
KEYCODE_NUMPAD_RIGHT_PAREN: 163,
KEYCODE_VOLUME_MUTE: 164,
KEYCODE_INFO: 165,
KEYCODE_CHANNEL_UP: 166,
KEYCODE_CHANNEL_DOWN: 167,
KEYCODE_ZOOM_IN: 168,
KEYCODE_ZOOM_OUT: 169,
KEYCODE_TV: 170,
KEYCODE_WINDOW: 171,
KEYCODE_GUIDE: 172,
KEYCODE_DVR: 173,
KEYCODE_BOOKMARK: 174,
KEYCODE_CAPTIONS: 175,
KEYCODE_SETTINGS: 176,
KEYCODE_TV_POWER: 177,
KEYCODE_TV_INPUT: 178,
KEYCODE_STB_POWER: 179,
KEYCODE_STB_INPUT: 180,
KEYCODE_AVR_POWER: 181,
KEYCODE_AVR_INPUT: 182,
KEYCODE_PROG_RED: 183,
KEYCODE_PROG_GREEN: 184,
KEYCODE_PROG_YELLOW: 185,
KEYCODE_PROG_BLUE: 186,
KEYCODE_APP_SWITCH: 187,
KEYCODE_BUTTON_1: 188,
KEYCODE_BUTTON_2: 189,
KEYCODE_BUTTON_3: 190,
KEYCODE_BUTTON_4: 191,
KEYCODE_BUTTON_5: 192,
KEYCODE_BUTTON_6: 193,
KEYCODE_BUTTON_7: 194,
KEYCODE_BUTTON_8: 195,
KEYCODE_BUTTON_9: 196,
KEYCODE_BUTTON_10: 197,
KEYCODE_BUTTON_11: 198,
KEYCODE_BUTTON_12: 199,
KEYCODE_BUTTON_13: 200,
KEYCODE_BUTTON_14: 201,
KEYCODE_BUTTON_15: 202,
KEYCODE_BUTTON_16: 203,
KEYCODE_LANGUAGE_SWITCH: 204,
KEYCODE_MANNER_MODE: 205,
KEYCODE_3D_MODE: 206,
KEYCODE_CONTACTS: 207,
KEYCODE_CALENDAR: 208,
KEYCODE_MUSIC: 209,
KEYCODE_CALCULATOR: 210,
KEYCODE_ZENKAKU_HANKAKU: 211,
KEYCODE_EISU: 212,
KEYCODE_MUHENKAN: 213,
KEYCODE_HENKAN: 214,
KEYCODE_KATAKANA_HIRAGANA: 215,
KEYCODE_YEN: 216,
KEYCODE_RO: 217,
KEYCODE_KANA: 218,
KEYCODE_ASSIST: 219,
KEYCODE_BRIGHTNESS_DOWN: 220,
KEYCODE_BRIGHTNESS_UP: 221,
KEYCODE_MEDIA_AUDIO_TRACK: 222
};
+87
View File
@@ -0,0 +1,87 @@
var LineTransform, Stream,
extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
hasProp = {}.hasOwnProperty;
Stream = require('stream');
LineTransform = (function(superClass) {
extend(LineTransform, superClass);
function LineTransform(options) {
if (options == null) {
options = {};
}
this.savedR = null;
this.autoDetect = options.autoDetect || false;
this.transformNeeded = true;
this.skipBytes = 0;
delete options.autoDetect;
LineTransform.__super__.constructor.call(this, options);
}
LineTransform.prototype._nullTransform = function(chunk, encoding, done) {
this.push(chunk);
done();
};
LineTransform.prototype._transform = function(chunk, encoding, done) {
var hi, last, lo, skip;
if (this.autoDetect) {
if (chunk[0] === 0x0a) {
this.transformNeeded = false;
this.skipBytes = 1;
} else {
this.skipBytes = 2;
}
this.autoDetect = false;
}
if (this.skipBytes) {
skip = Math.min(chunk.length, this.skipBytes);
chunk = chunk.slice(skip);
this.skipBytes -= skip;
}
if (!chunk.length) {
return done();
}
if (!this.transformNeeded) {
return this._nullTransform(chunk, encoding, done);
}
lo = 0;
hi = 0;
if (this.savedR) {
if (chunk[0] !== 0x0a) {
this.push(this.savedR);
}
this.savedR = null;
}
last = chunk.length - 1;
while (hi <= last) {
if (chunk[hi] === 0x0d) {
if (hi === last) {
this.savedR = chunk.slice(last);
break;
} else if (chunk[hi + 1] === 0x0a) {
this.push(chunk.slice(lo, hi));
lo = hi + 1;
}
}
hi += 1;
}
if (hi !== lo) {
this.push(chunk.slice(lo, hi));
}
done();
};
LineTransform.prototype._flush = function(done) {
if (this.savedR) {
this.push(this.savedR);
}
return done();
};
return LineTransform;
})(Stream.Transform);
module.exports = LineTransform;
+291
View File
@@ -0,0 +1,291 @@
var Parser, Promise, Protocol,
extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
hasProp = {}.hasOwnProperty;
Promise = require('bluebird');
Protocol = require('./protocol');
Parser = (function() {
function Parser(stream) {
this.stream = stream;
this.ended = false;
}
Parser.prototype.end = function() {
var endListener, errorListener, resolver, tryRead;
if (this.ended) {
return Promise.resolve(true);
}
resolver = Promise.defer();
tryRead = (function(_this) {
return function() {
while (_this.stream.read()) {
continue;
}
};
})(this);
this.stream.on('readable', tryRead);
this.stream.on('error', errorListener = function(err) {
return resolver.reject(err);
});
this.stream.on('end', endListener = (function(_this) {
return function() {
_this.ended = true;
return resolver.resolve(true);
};
})(this));
this.stream.read(0);
this.stream.end();
return resolver.promise.cancellable()["finally"]((function(_this) {
return function() {
_this.stream.removeListener('readable', tryRead);
_this.stream.removeListener('error', errorListener);
return _this.stream.removeListener('end', endListener);
};
})(this));
};
Parser.prototype.raw = function() {
return this.stream;
};
Parser.prototype.readAll = function() {
var all, endListener, errorListener, resolver, tryRead;
all = new Buffer(0);
resolver = Promise.defer();
tryRead = (function(_this) {
return function() {
var chunk;
while (chunk = _this.stream.read()) {
all = Buffer.concat([all, chunk]);
}
if (_this.ended) {
return resolver.resolve(all);
}
};
})(this);
this.stream.on('readable', tryRead);
this.stream.on('error', errorListener = function(err) {
return resolver.reject(err);
});
this.stream.on('end', endListener = (function(_this) {
return function() {
_this.ended = true;
return resolver.resolve(all);
};
})(this));
tryRead();
return resolver.promise.cancellable()["finally"]((function(_this) {
return function() {
_this.stream.removeListener('readable', tryRead);
_this.stream.removeListener('error', errorListener);
return _this.stream.removeListener('end', endListener);
};
})(this));
};
Parser.prototype.readAscii = function(howMany) {
return this.readBytes(howMany).then(function(chunk) {
return chunk.toString('ascii');
});
};
Parser.prototype.readBytes = function(howMany) {
var endListener, errorListener, resolver, tryRead;
resolver = Promise.defer();
tryRead = (function(_this) {
return function() {
var chunk;
if (howMany) {
if (chunk = _this.stream.read(howMany)) {
howMany -= chunk.length;
if (howMany === 0) {
return resolver.resolve(chunk);
}
}
if (_this.ended) {
return resolver.reject(new Parser.PrematureEOFError(howMany));
}
} else {
return resolver.resolve(new Buffer(0));
}
};
})(this);
endListener = (function(_this) {
return function() {
_this.ended = true;
return resolver.reject(new Parser.PrematureEOFError(howMany));
};
})(this);
errorListener = function(err) {
return resolver.reject(err);
};
this.stream.on('readable', tryRead);
this.stream.on('error', errorListener);
this.stream.on('end', endListener);
tryRead();
return resolver.promise.cancellable()["finally"]((function(_this) {
return function() {
_this.stream.removeListener('readable', tryRead);
_this.stream.removeListener('error', errorListener);
return _this.stream.removeListener('end', endListener);
};
})(this));
};
Parser.prototype.readByteFlow = function(howMany, targetStream) {
var endListener, errorListener, resolver, tryRead;
resolver = Promise.defer();
tryRead = (function(_this) {
return function() {
var chunk;
if (howMany) {
while (chunk = _this.stream.read(howMany) || _this.stream.read()) {
howMany -= chunk.length;
targetStream.write(chunk);
if (howMany === 0) {
return resolver.resolve();
}
}
if (_this.ended) {
return resolver.reject(new Parser.PrematureEOFError(howMany));
}
} else {
return resolver.resolve();
}
};
})(this);
endListener = (function(_this) {
return function() {
_this.ended = true;
return resolver.reject(new Parser.PrematureEOFError(howMany));
};
})(this);
errorListener = function(err) {
return resolver.reject(err);
};
this.stream.on('readable', tryRead);
this.stream.on('error', errorListener);
this.stream.on('end', endListener);
tryRead();
return resolver.promise.cancellable()["finally"]((function(_this) {
return function() {
_this.stream.removeListener('readable', tryRead);
_this.stream.removeListener('error', errorListener);
return _this.stream.removeListener('end', endListener);
};
})(this));
};
Parser.prototype.readError = function() {
return this.readValue().then(function(value) {
return Promise.reject(new Parser.FailError(value.toString()));
});
};
Parser.prototype.readValue = function() {
return this.readAscii(4).then((function(_this) {
return function(value) {
var length;
length = Protocol.decodeLength(value);
return _this.readBytes(length);
};
})(this));
};
Parser.prototype.readUntil = function(code) {
var read, skipped;
skipped = new Buffer(0);
read = (function(_this) {
return function() {
return _this.readBytes(1).then(function(chunk) {
if (chunk[0] === code) {
return skipped;
} else {
skipped = Buffer.concat([skipped, chunk]);
return read();
}
});
};
})(this);
return read();
};
Parser.prototype.searchLine = function(re) {
return this.readLine().then((function(_this) {
return function(line) {
var match;
if (match = re.exec(line)) {
return match;
} else {
return _this.searchLine(re);
}
};
})(this));
};
Parser.prototype.readLine = function() {
return this.readUntil(0x0a).then(function(line) {
if (line[line.length - 1] === 0x0d) {
return line.slice(0, -1);
} else {
return line;
}
});
};
Parser.prototype.unexpected = function(data, expected) {
return Promise.reject(new Parser.UnexpectedDataError(data, expected));
};
return Parser;
})();
Parser.FailError = (function(superClass) {
extend(FailError, superClass);
function FailError(message) {
Error.call(this);
this.name = 'FailError';
this.message = "Failure: '" + message + "'";
Error.captureStackTrace(this, Parser.FailError);
}
return FailError;
})(Error);
Parser.PrematureEOFError = (function(superClass) {
extend(PrematureEOFError, superClass);
function PrematureEOFError(howManyMissing) {
Error.call(this);
this.name = 'PrematureEOFError';
this.message = "Premature end of stream, needed " + howManyMissing + " more bytes";
this.missingBytes = howManyMissing;
Error.captureStackTrace(this, Parser.PrematureEOFError);
}
return PrematureEOFError;
})(Error);
Parser.UnexpectedDataError = (function(superClass) {
extend(UnexpectedDataError, superClass);
function UnexpectedDataError(unexpected, expected) {
Error.call(this);
this.name = 'UnexpectedDataError';
this.message = "Unexpected '" + unexpected + "', was expecting " + expected;
this.unexpected = unexpected;
this.expected = expected;
Error.captureStackTrace(this, Parser.UnexpectedDataError);
}
return UnexpectedDataError;
})(Error);
module.exports = Parser;
+137
View File
@@ -0,0 +1,137 @@
var EventEmitter, Parser, ProcStat, split,
extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
hasProp = {}.hasOwnProperty;
EventEmitter = require('events').EventEmitter;
split = require('split');
Parser = require('../parser');
ProcStat = (function(superClass) {
var RE_COLSEP, RE_CPULINE;
extend(ProcStat, superClass);
RE_CPULINE = /^cpu[0-9]+ .*$/mg;
RE_COLSEP = /\ +/g;
function ProcStat(sync) {
this.sync = sync;
this.interval = 1000;
this.stats = this._emptyStats();
this._ignore = {};
this._timer = setInterval((function(_this) {
return function() {
return _this.update();
};
})(this), this.interval);
this.update();
}
ProcStat.prototype.end = function() {
clearInterval(this._timer);
this.sync.end();
return this.sync = null;
};
ProcStat.prototype.update = function() {
return new Parser(this.sync.pull('/proc/stat')).readAll().then((function(_this) {
return function(out) {
return _this._parse(out);
};
})(this))["catch"]((function(_this) {
return function(err) {
_this._error(err);
};
})(this));
};
ProcStat.prototype._parse = function(out) {
var cols, i, len, line, match, stats, total, type, val;
stats = this._emptyStats();
while (match = RE_CPULINE.exec(out)) {
line = match[0];
cols = line.split(RE_COLSEP);
type = cols.shift();
if (this._ignore[type] === line) {
continue;
}
total = 0;
for (i = 0, len = cols.length; i < len; i++) {
val = cols[i];
total += +val;
}
stats.cpus[type] = {
line: line,
user: +cols[0] || 0,
nice: +cols[1] || 0,
system: +cols[2] || 0,
idle: +cols[3] || 0,
iowait: +cols[4] || 0,
irq: +cols[5] || 0,
softirq: +cols[6] || 0,
steal: +cols[7] || 0,
guest: +cols[8] || 0,
guestnice: +cols[9] || 0,
total: total
};
}
return this._set(stats);
};
ProcStat.prototype._set = function(stats) {
var cur, found, id, loads, m, old, ref, ticks;
loads = {};
found = false;
ref = stats.cpus;
for (id in ref) {
cur = ref[id];
old = this.stats.cpus[id];
if (!old) {
continue;
}
ticks = cur.total - old.total;
if (ticks > 0) {
found = true;
m = 100 / ticks;
loads[id] = {
user: Math.floor(m * (cur.user - old.user)),
nice: Math.floor(m * (cur.nice - old.nice)),
system: Math.floor(m * (cur.system - old.system)),
idle: Math.floor(m * (cur.idle - old.idle)),
iowait: Math.floor(m * (cur.iowait - old.iowait)),
irq: Math.floor(m * (cur.irq - old.irq)),
softirq: Math.floor(m * (cur.softirq - old.softirq)),
steal: Math.floor(m * (cur.steal - old.steal)),
guest: Math.floor(m * (cur.guest - old.guest)),
guestnice: Math.floor(m * (cur.guestnice - old.guestnice)),
total: 100
};
} else {
this._ignore[id] = cur.line;
delete stats.cpus[id];
}
}
if (found) {
this.emit('load', loads);
}
return this.stats = stats;
};
ProcStat.prototype._error = function(err) {
return this.emit('error', err);
};
ProcStat.prototype._emptyStats = function() {
return {
cpus: {}
};
};
return ProcStat;
})(EventEmitter);
module.exports = ProcStat;
+45
View File
@@ -0,0 +1,45 @@
var Protocol;
Protocol = (function() {
function Protocol() {}
Protocol.OKAY = 'OKAY';
Protocol.FAIL = 'FAIL';
Protocol.STAT = 'STAT';
Protocol.LIST = 'LIST';
Protocol.DENT = 'DENT';
Protocol.RECV = 'RECV';
Protocol.DATA = 'DATA';
Protocol.DONE = 'DONE';
Protocol.SEND = 'SEND';
Protocol.QUIT = 'QUIT';
Protocol.decodeLength = function(length) {
return parseInt(length, 16);
};
Protocol.encodeLength = function(length) {
return ('0000' + length.toString(16)).slice(-4).toUpperCase();
};
Protocol.encodeData = function(data) {
if (!Buffer.isBuffer(data)) {
data = new Buffer(data);
}
return Buffer.concat([new Buffer(Protocol.encodeLength(data.length)), data]);
};
return Protocol;
})();
module.exports = Protocol;
+336
View File
@@ -0,0 +1,336 @@
var Entry, EventEmitter, Fs, Parser, Path, Promise, Protocol, PullTransfer, PushTransfer, Stats, Sync, debug,
extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
hasProp = {}.hasOwnProperty;
Fs = require('fs');
Path = require('path');
Promise = require('bluebird');
EventEmitter = require('events').EventEmitter;
debug = require('debug')('adb:sync');
Parser = require('./parser');
Protocol = require('./protocol');
Stats = require('./sync/stats');
Entry = require('./sync/entry');
PushTransfer = require('./sync/pushtransfer');
PullTransfer = require('./sync/pulltransfer');
Sync = (function(superClass) {
var DATA_MAX_LENGTH, DEFAULT_CHMOD, TEMP_PATH;
extend(Sync, superClass);
TEMP_PATH = '/data/local/tmp';
DEFAULT_CHMOD = 0x1a4;
DATA_MAX_LENGTH = 65536;
Sync.temp = function(path) {
return TEMP_PATH + "/" + (Path.basename(path));
};
function Sync(connection) {
this.connection = connection;
this.parser = this.connection.parser;
}
Sync.prototype.stat = function(path, callback) {
this._sendCommandWithArg(Protocol.STAT, path);
return this.parser.readAscii(4).then((function(_this) {
return function(reply) {
switch (reply) {
case Protocol.STAT:
return _this.parser.readBytes(12).then(function(stat) {
var mode, mtime, size;
mode = stat.readUInt32LE(0);
size = stat.readUInt32LE(4);
mtime = stat.readUInt32LE(8);
if (mode === 0) {
return _this._enoent(path);
} else {
return new Stats(mode, size, mtime);
}
});
case Protocol.FAIL:
return _this._readError();
default:
return _this.parser.unexpected(reply, 'STAT or FAIL');
}
};
})(this)).nodeify(callback);
};
Sync.prototype.readdir = function(path, callback) {
var files, readNext;
files = [];
readNext = (function(_this) {
return function() {
return _this.parser.readAscii(4).then(function(reply) {
switch (reply) {
case Protocol.DENT:
return _this.parser.readBytes(16).then(function(stat) {
var mode, mtime, namelen, size;
mode = stat.readUInt32LE(0);
size = stat.readUInt32LE(4);
mtime = stat.readUInt32LE(8);
namelen = stat.readUInt32LE(12);
return _this.parser.readBytes(namelen).then(function(name) {
name = name.toString();
if (!(name === '.' || name === '..')) {
files.push(new Entry(name, mode, size, mtime));
}
return readNext();
});
});
case Protocol.DONE:
return _this.parser.readBytes(16).then(function(zero) {
return files;
});
case Protocol.FAIL:
return _this._readError();
default:
return _this.parser.unexpected(reply, 'DENT, DONE or FAIL');
}
});
};
})(this);
this._sendCommandWithArg(Protocol.LIST, path);
return readNext().nodeify(callback);
};
Sync.prototype.push = function(contents, path, mode) {
if (typeof contents === 'string') {
return this.pushFile(contents, path, mode);
} else {
return this.pushStream(contents, path, mode);
}
};
Sync.prototype.pushFile = function(file, path, mode) {
if (mode == null) {
mode = DEFAULT_CHMOD;
}
mode || (mode = DEFAULT_CHMOD);
return this.pushStream(Fs.createReadStream(file), path, mode);
};
Sync.prototype.pushStream = function(stream, path, mode) {
if (mode == null) {
mode = DEFAULT_CHMOD;
}
mode |= Stats.S_IFREG;
this._sendCommandWithArg(Protocol.SEND, path + "," + mode);
return this._writeData(stream, Math.floor(Date.now() / 1000));
};
Sync.prototype.pull = function(path) {
this._sendCommandWithArg(Protocol.RECV, "" + path);
return this._readData();
};
Sync.prototype.end = function() {
this.connection.end();
return this;
};
Sync.prototype.tempFile = function(path) {
return Sync.temp(path);
};
Sync.prototype._writeData = function(stream, timeStamp) {
var readReply, reader, transfer, writeData, writer;
transfer = new PushTransfer;
writeData = (function(_this) {
return function() {
var endListener, errorListener, readableListener, resolver, track, waitForDrain, writeNext, writer;
resolver = Promise.defer();
writer = Promise.resolve().cancellable();
stream.on('end', endListener = function() {
return writer.then(function() {
_this._sendCommandWithLength(Protocol.DONE, timeStamp);
return resolver.resolve();
});
});
waitForDrain = function() {
var drainListener;
resolver = Promise.defer();
_this.connection.on('drain', drainListener = function() {
return resolver.resolve();
});
return resolver.promise["finally"](function() {
return _this.connection.removeListener('drain', drainListener);
});
};
track = function() {
return transfer.pop();
};
writeNext = function() {
var chunk;
if (chunk = stream.read(DATA_MAX_LENGTH) || stream.read()) {
_this._sendCommandWithLength(Protocol.DATA, chunk.length);
transfer.push(chunk.length);
if (_this.connection.write(chunk, track)) {
return writeNext();
} else {
return waitForDrain().then(writeNext);
}
} else {
return Promise.resolve();
}
};
stream.on('readable', readableListener = function() {
return writer.then(writeNext);
});
stream.on('error', errorListener = function(err) {
return resolver.reject(err);
});
return resolver.promise["finally"](function() {
stream.removeListener('end', endListener);
stream.removeListener('readable', readableListener);
stream.removeListener('error', errorListener);
return writer.cancel();
});
};
})(this);
readReply = (function(_this) {
return function() {
return _this.parser.readAscii(4).then(function(reply) {
switch (reply) {
case Protocol.OKAY:
return _this.parser.readBytes(4).then(function(zero) {
return true;
});
case Protocol.FAIL:
return _this._readError();
default:
return _this.parser.unexpected(reply, 'OKAY or FAIL');
}
});
};
})(this);
writer = writeData().cancellable()["catch"](Promise.CancellationError, (function(_this) {
return function(err) {
return _this.connection.end();
};
})(this))["catch"](function(err) {
transfer.emit('error', err);
return reader.cancel();
});
reader = readReply().cancellable()["catch"](Promise.CancellationError, function(err) {
return true;
})["catch"](function(err) {
transfer.emit('error', err);
return writer.cancel();
})["finally"](function() {
return transfer.end();
});
transfer.on('cancel', function() {
writer.cancel();
return reader.cancel();
});
return transfer;
};
Sync.prototype._readData = function() {
var cancelListener, readNext, reader, transfer;
transfer = new PullTransfer;
readNext = (function(_this) {
return function() {
return _this.parser.readAscii(4).cancellable().then(function(reply) {
switch (reply) {
case Protocol.DATA:
return _this.parser.readBytes(4).then(function(lengthData) {
var length;
length = lengthData.readUInt32LE(0);
return _this.parser.readByteFlow(length, transfer).then(readNext);
});
case Protocol.DONE:
return _this.parser.readBytes(4).then(function(zero) {
return true;
});
case Protocol.FAIL:
return _this._readError();
default:
return _this.parser.unexpected(reply, 'DATA, DONE or FAIL');
}
});
};
})(this);
reader = readNext()["catch"](Promise.CancellationError, (function(_this) {
return function(err) {
return _this.connection.end();
};
})(this))["catch"](function(err) {
return transfer.emit('error', err);
})["finally"](function() {
transfer.removeListener('cancel', cancelListener);
return transfer.end();
});
transfer.on('cancel', cancelListener = function() {
return reader.cancel();
});
return transfer;
};
Sync.prototype._readError = function() {
return this.parser.readBytes(4).then((function(_this) {
return function(length) {
return _this.parser.readBytes(length.readUInt32LE(0)).then(function(buf) {
return Promise.reject(new Parser.FailError(buf.toString()));
});
};
})(this))["finally"]((function(_this) {
return function() {
return _this.parser.end();
};
})(this));
};
Sync.prototype._sendCommandWithLength = function(cmd, length) {
var payload;
if (cmd !== Protocol.DATA) {
debug(cmd);
}
payload = new Buffer(cmd.length + 4);
payload.write(cmd, 0, cmd.length);
payload.writeUInt32LE(length, cmd.length);
return this.connection.write(payload);
};
Sync.prototype._sendCommandWithArg = function(cmd, arg) {
var payload, pos;
debug(cmd + " " + arg);
payload = new Buffer(cmd.length + 4 + arg.length);
pos = 0;
payload.write(cmd, pos, cmd.length);
pos += cmd.length;
payload.writeUInt32LE(arg.length, pos);
pos += 4;
payload.write(arg, pos);
return this.connection.write(payload);
};
Sync.prototype._enoent = function(path) {
var err;
err = new Error("ENOENT, no such file or directory '" + path + "'");
err.errno = 34;
err.code = 'ENOENT';
err.path = path;
return Promise.reject(err);
};
return Sync;
})(EventEmitter);
module.exports = Sync;
+23
View File
@@ -0,0 +1,23 @@
var Entry, Stats,
extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
hasProp = {}.hasOwnProperty;
Stats = require('./stats');
Entry = (function(superClass) {
extend(Entry, superClass);
function Entry(name, mode, size, mtime) {
this.name = name;
Entry.__super__.constructor.call(this, mode, size, mtime);
}
Entry.prototype.toString = function() {
return this.name;
};
return Entry;
})(Stats);
module.exports = Entry;
+31
View File
@@ -0,0 +1,31 @@
var PullTransfer, Stream,
extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
hasProp = {}.hasOwnProperty;
Stream = require('stream');
PullTransfer = (function(superClass) {
extend(PullTransfer, superClass);
function PullTransfer() {
this.stats = {
bytesTransferred: 0
};
PullTransfer.__super__.constructor.call(this);
}
PullTransfer.prototype.cancel = function() {
return this.emit('cancel');
};
PullTransfer.prototype.write = function(chunk, encoding, callback) {
this.stats.bytesTransferred += chunk.length;
this.emit('progress', this.stats);
return PullTransfer.__super__.write.call(this, chunk, encoding, callback);
};
return PullTransfer;
})(Stream.PassThrough);
module.exports = PullTransfer;
+40
View File
@@ -0,0 +1,40 @@
var EventEmitter, PushTransfer,
extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
hasProp = {}.hasOwnProperty;
EventEmitter = require('events').EventEmitter;
PushTransfer = (function(superClass) {
extend(PushTransfer, superClass);
function PushTransfer() {
this._stack = [];
this.stats = {
bytesTransferred: 0
};
}
PushTransfer.prototype.cancel = function() {
return this.emit('cancel');
};
PushTransfer.prototype.push = function(byteCount) {
return this._stack.push(byteCount);
};
PushTransfer.prototype.pop = function() {
var byteCount;
byteCount = this._stack.pop();
this.stats.bytesTransferred += byteCount;
return this.emit('progress', this.stats);
};
PushTransfer.prototype.end = function() {
return this.emit('end');
};
return PushTransfer;
})(EventEmitter);
module.exports = PushTransfer;
+54
View File
@@ -0,0 +1,54 @@
var Fs, Stats,
extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
hasProp = {}.hasOwnProperty;
Fs = require('fs');
Stats = (function(superClass) {
extend(Stats, superClass);
Stats.S_IFMT = 0xf000;
Stats.S_IFSOCK = 0xc000;
Stats.S_IFLNK = 0xa000;
Stats.S_IFREG = 0x8000;
Stats.S_IFBLK = 0x6000;
Stats.S_IFDIR = 0x4000;
Stats.S_IFCHR = 0x2000;
Stats.S_IFIFO = 0x1000;
Stats.S_ISUID = 0x800;
Stats.S_ISGID = 0x400;
Stats.S_ISVTX = 0x200;
Stats.S_IRWXU = 0x1c0;
Stats.S_IRUSR = 0x100;
Stats.S_IWUSR = 0x80;
Stats.S_IXUSR = 0x40;
Stats.S_IRWXG = 0x38;
Stats.S_IRGRP = 0x20;
function Stats(mode, size, mtime) {
this.mode = mode;
this.size = size;
this.mtime = new Date(mtime * 1000);
}
return Stats;
})(Fs.Stats);
module.exports = Stats;
+112
View File
@@ -0,0 +1,112 @@
var Packet;
Packet = (function() {
Packet.A_SYNC = 0x434e5953;
Packet.A_CNXN = 0x4e584e43;
Packet.A_OPEN = 0x4e45504f;
Packet.A_OKAY = 0x59414b4f;
Packet.A_CLSE = 0x45534c43;
Packet.A_WRTE = 0x45545257;
Packet.A_AUTH = 0x48545541;
Packet.checksum = function(data) {
var char, i, len, sum;
sum = 0;
if (data) {
for (i = 0, len = data.length; i < len; i++) {
char = data[i];
sum += char;
}
}
return sum;
};
Packet.magic = function(command) {
return (command ^ 0xffffffff) >>> 0;
};
Packet.assemble = function(command, arg0, arg1, data) {
var chunk;
if (data) {
chunk = new Buffer(24 + data.length);
chunk.writeUInt32LE(command, 0);
chunk.writeUInt32LE(arg0, 4);
chunk.writeUInt32LE(arg1, 8);
chunk.writeUInt32LE(data.length, 12);
chunk.writeUInt32LE(Packet.checksum(data), 16);
chunk.writeUInt32LE(Packet.magic(command), 20);
data.copy(chunk, 24);
return chunk;
} else {
chunk = new Buffer(24);
chunk.writeUInt32LE(command, 0);
chunk.writeUInt32LE(arg0, 4);
chunk.writeUInt32LE(arg1, 8);
chunk.writeUInt32LE(0, 12);
chunk.writeUInt32LE(0, 16);
chunk.writeUInt32LE(Packet.magic(command), 20);
return chunk;
}
};
Packet.swap32 = function(n) {
var buffer;
buffer = new Buffer(4);
buffer.writeUInt32LE(n, 0);
return buffer.readUInt32BE(0);
};
function Packet(command1, arg01, arg11, length, check, magic, data1) {
this.command = command1;
this.arg0 = arg01;
this.arg1 = arg11;
this.length = length;
this.check = check;
this.magic = magic;
this.data = data1;
}
Packet.prototype.verifyChecksum = function() {
return this.check === Packet.checksum(this.data);
};
Packet.prototype.verifyMagic = function() {
return this.magic === Packet.magic(this.command);
};
Packet.prototype.toString = function() {
var type;
type = (function() {
switch (this.command) {
case Packet.A_SYNC:
return "SYNC";
case Packet.A_CNXN:
return "CNXN";
case Packet.A_OPEN:
return "OPEN";
case Packet.A_OKAY:
return "OKAY";
case Packet.A_CLSE:
return "CLSE";
case Packet.A_WRTE:
return "WRTE";
case Packet.A_AUTH:
return "AUTH";
default:
throw new Error("Unknown command {@command}");
}
}).call(this);
return type + " arg0=" + this.arg0 + " arg1=" + this.arg1 + " length=" + this.length;
};
return Packet;
})();
module.exports = Packet;
+121
View File
@@ -0,0 +1,121 @@
var EventEmitter, Packet, PacketReader,
extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
hasProp = {}.hasOwnProperty;
EventEmitter = require('events').EventEmitter;
Packet = require('./packet');
PacketReader = (function(superClass) {
extend(PacketReader, superClass);
function PacketReader(stream) {
this.stream = stream;
PacketReader.__super__.constructor.call(this);
this.inBody = false;
this.buffer = null;
this.packet = null;
this.stream.on('readable', this._tryRead.bind(this));
this.stream.on('error', (function(_this) {
return function(err) {
return _this.emit('error', err);
};
})(this));
this.stream.on('end', (function(_this) {
return function() {
return _this.emit('end');
};
})(this));
setImmediate(this._tryRead.bind(this));
}
PacketReader.prototype._tryRead = function() {
var header;
while (this._appendChunk()) {
while (this.buffer) {
if (this.inBody) {
if (!(this.buffer.length >= this.packet.length)) {
break;
}
this.packet.data = this._consume(this.packet.length);
if (!this.packet.verifyChecksum()) {
this.emit('error', new PacketReader.ChecksumError(this.packet));
return;
}
this.emit('packet', this.packet);
this.inBody = false;
} else {
if (!(this.buffer.length >= 24)) {
break;
}
header = this._consume(24);
this.packet = new Packet(header.readUInt32LE(0), header.readUInt32LE(4), header.readUInt32LE(8), header.readUInt32LE(12), header.readUInt32LE(16), header.readUInt32LE(20), new Buffer(0));
if (!this.packet.verifyMagic()) {
this.emit('error', new PacketReader.MagicError(this.packet));
return;
}
if (this.packet.length === 0) {
this.emit('packet', this.packet);
} else {
this.inBody = true;
}
}
}
}
};
PacketReader.prototype._appendChunk = function() {
var chunk;
if (chunk = this.stream.read()) {
if (this.buffer) {
return this.buffer = Buffer.concat([this.buffer, chunk], this.buffer.length + chunk.length);
} else {
return this.buffer = chunk;
}
} else {
return null;
}
};
PacketReader.prototype._consume = function(length) {
var chunk;
chunk = this.buffer.slice(0, length);
this.buffer = length === this.buffer.length ? null : this.buffer.slice(length);
return chunk;
};
return PacketReader;
})(EventEmitter);
PacketReader.ChecksumError = (function(superClass) {
extend(ChecksumError, superClass);
function ChecksumError(packet) {
this.packet = packet;
Error.call(this);
this.name = 'ChecksumError';
this.message = "Checksum mismatch";
Error.captureStackTrace(this, PacketReader.ChecksumError);
}
return ChecksumError;
})(Error);
PacketReader.MagicError = (function(superClass) {
extend(MagicError, superClass);
function MagicError(packet) {
this.packet = packet;
Error.call(this);
this.name = 'MagicError';
this.message = "Magic value mismatch";
Error.captureStackTrace(this, PacketReader.MagicError);
}
return MagicError;
})(Error);
module.exports = PacketReader;
+21
View File
@@ -0,0 +1,21 @@
var RollingCounter;
RollingCounter = (function() {
function RollingCounter(max, min) {
this.max = max;
this.min = min != null ? min : 1;
this.now = this.min;
}
RollingCounter.prototype.next = function() {
if (!(this.now < this.max)) {
this.now = this.min;
}
return ++this.now;
};
return RollingCounter;
})();
module.exports = RollingCounter;
+79
View File
@@ -0,0 +1,79 @@
var EventEmitter, Net, Server, Socket,
extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
hasProp = {}.hasOwnProperty;
Net = require('net');
EventEmitter = require('events').EventEmitter;
Socket = require('./socket');
Server = (function(superClass) {
extend(Server, superClass);
function Server(client, serial, options) {
this.client = client;
this.serial = serial;
this.options = options;
this.connections = [];
this.server = Net.createServer({
allowHalfOpen: true
});
this.server.on('error', (function(_this) {
return function(err) {
return _this.emit('error', err);
};
})(this));
this.server.on('listening', (function(_this) {
return function() {
return _this.emit('listening');
};
})(this));
this.server.on('close', (function(_this) {
return function() {
return _this.emit('close');
};
})(this));
this.server.on('connection', (function(_this) {
return function(conn) {
var socket;
socket = new Socket(_this.client, _this.serial, conn, _this.options);
_this.connections.push(socket);
socket.on('error', function(err) {
return _this.emit('error', err);
});
socket.once('end', function() {
return _this.connections = _this.connections.filter(function(val) {
return val !== socket;
});
});
return _this.emit('connection', socket);
};
})(this));
}
Server.prototype.listen = function() {
this.server.listen.apply(this.server, arguments);
return this;
};
Server.prototype.close = function() {
this.server.close();
return this;
};
Server.prototype.end = function() {
var conn, i, len, ref;
ref = this.connections;
for (i = 0, len = ref.length; i < len; i++) {
conn = ref[i];
conn.end();
}
return this;
};
return Server;
})(EventEmitter);
module.exports = Server;
+203
View File
@@ -0,0 +1,203 @@
var EventEmitter, Packet, Parser, Promise, Protocol, Service, debug,
extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
hasProp = {}.hasOwnProperty;
EventEmitter = require('events').EventEmitter;
Promise = require('bluebird');
debug = require('debug')('adb:tcpusb:service');
Parser = require('../parser');
Protocol = require('../protocol');
Packet = require('./packet');
Service = (function(superClass) {
extend(Service, superClass);
function Service(client, serial, localId1, remoteId, socket) {
this.client = client;
this.serial = serial;
this.localId = localId1;
this.remoteId = remoteId;
this.socket = socket;
Service.__super__.constructor.call(this);
this.opened = false;
this.ended = false;
this.transport = null;
this.needAck = false;
}
Service.prototype.end = function() {
var err, localId;
if (this.transport) {
this.transport.end();
}
if (this.ended) {
return this;
}
debug('O:A_CLSE');
localId = this.opened ? this.localId : 0;
try {
this.socket.write(Packet.assemble(Packet.A_CLSE, localId, this.remoteId, null));
} catch (_error) {
err = _error;
}
this.transport = null;
this.ended = true;
this.emit('end');
return this;
};
Service.prototype.handle = function(packet) {
return Promise["try"]((function(_this) {
return function() {
switch (packet.command) {
case Packet.A_OPEN:
return _this._handleOpenPacket(packet);
case Packet.A_OKAY:
return _this._handleOkayPacket(packet);
case Packet.A_WRTE:
return _this._handleWritePacket(packet);
case Packet.A_CLSE:
return _this._handleClosePacket(packet);
default:
throw new Error("Unexpected packet " + packet.command);
}
};
})(this))["catch"]((function(_this) {
return function(err) {
_this.emit('error', err);
return _this.end();
};
})(this));
};
Service.prototype._handleOpenPacket = function(packet) {
debug('I:A_OPEN', packet);
return this.client.transport(this.serial).then((function(_this) {
return function(transport) {
_this.transport = transport;
if (_this.ended) {
throw new LateTransportError();
}
_this.transport.write(Protocol.encodeData(packet.data.slice(0, -1)));
return _this.transport.parser.readAscii(4).then(function(reply) {
switch (reply) {
case Protocol.OKAY:
debug('O:A_OKAY');
_this.socket.write(Packet.assemble(Packet.A_OKAY, _this.localId, _this.remoteId, null));
return _this.opened = true;
case Protocol.FAIL:
return _this.transport.parser.readError();
default:
return _this.transport.parser.unexpected(reply, 'OKAY or FAIL');
}
});
};
})(this)).then((function(_this) {
return function() {
return new Promise(function(resolve, reject) {
_this.transport.socket.on('readable', function() {
return _this._tryPush();
}).on('end', resolve).on('error', reject);
return _this._tryPush();
});
};
})(this))["finally"]((function(_this) {
return function() {
return _this.end();
};
})(this));
};
Service.prototype._handleOkayPacket = function(packet) {
debug('I:A_OKAY', packet);
if (this.ended) {
return;
}
if (!this.transport) {
throw new Service.PrematurePacketError(packet);
}
this.needAck = false;
return this._tryPush();
};
Service.prototype._handleWritePacket = function(packet) {
debug('I:A_WRTE', packet);
if (this.ended) {
return;
}
if (!this.transport) {
throw new Service.PrematurePacketError(packet);
}
if (packet.data) {
this.transport.write(packet.data);
}
debug('O:A_OKAY');
return this.socket.write(Packet.assemble(Packet.A_OKAY, this.localId, this.remoteId, null));
};
Service.prototype._handleClosePacket = function(packet) {
debug('I:A_CLSE', packet);
if (this.ended) {
return;
}
if (!this.transport) {
throw new Service.PrematurePacketError(packet);
}
return this.end();
};
Service.prototype._tryPush = function() {
var chunk;
if (this.needAck || this.ended) {
return;
}
if (chunk = this._readChunk(this.transport.socket)) {
debug('O:A_WRTE');
this.socket.write(Packet.assemble(Packet.A_WRTE, this.localId, this.remoteId, chunk));
return this.needAck = true;
}
};
Service.prototype._readChunk = function(stream) {
return stream.read(this.socket.maxPayload) || stream.read();
};
return Service;
})(EventEmitter);
Service.PrematurePacketError = (function(superClass) {
extend(PrematurePacketError, superClass);
function PrematurePacketError(packet1) {
this.packet = packet1;
Error.call(this);
this.name = 'PrematurePacketError';
this.message = "Premature packet";
Error.captureStackTrace(this, Service.PrematurePacketError);
}
return PrematurePacketError;
})(Error);
Service.LateTransportError = (function(superClass) {
extend(LateTransportError, superClass);
function LateTransportError() {
Error.call(this);
this.name = 'LateTransportError';
this.message = "Late transport";
Error.captureStackTrace(this, Service.LateTransportError);
}
return LateTransportError;
})(Error);
module.exports = Service;
+48
View File
@@ -0,0 +1,48 @@
var ServiceMap;
ServiceMap = (function() {
function ServiceMap() {
this.remotes = Object.create(null);
this.count = 0;
}
ServiceMap.prototype.end = function() {
var ref, remote, remoteId;
ref = this.remotes;
for (remoteId in ref) {
remote = ref[remoteId];
remote.end();
}
this.remotes = Object.create(null);
this.count = 0;
};
ServiceMap.prototype.insert = function(remoteId, socket) {
if (this.remotes[remoteId]) {
throw new Error("Remote ID " + remoteId + " is already being used");
} else {
this.count += 1;
return this.remotes[remoteId] = socket;
}
};
ServiceMap.prototype.get = function(remoteId) {
return this.remotes[remoteId] || null;
};
ServiceMap.prototype.remove = function(remoteId) {
var remote;
if (remote = this.remotes[remoteId]) {
delete this.remotes[remoteId];
this.count -= 1;
return remote;
} else {
return null;
}
};
return ServiceMap;
})();
module.exports = ServiceMap;
+314
View File
@@ -0,0 +1,314 @@
var Auth, EventEmitter, Forge, Packet, PacketReader, Parser, Promise, Protocol, RollingCounter, Service, ServiceMap, Socket, crypto, debug,
extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
hasProp = {}.hasOwnProperty;
crypto = require('crypto');
EventEmitter = require('events').EventEmitter;
Promise = require('bluebird');
Forge = require('node-forge');
debug = require('debug')('adb:tcpusb:socket');
Parser = require('../parser');
Protocol = require('../protocol');
Auth = require('../auth');
Packet = require('./packet');
PacketReader = require('./packetreader');
Service = require('./service');
ServiceMap = require('./servicemap');
RollingCounter = require('./rollingcounter');
Socket = (function(superClass) {
var AUTH_RSAPUBLICKEY, AUTH_SIGNATURE, AUTH_TOKEN, TOKEN_LENGTH, UINT16_MAX, UINT32_MAX;
extend(Socket, superClass);
UINT32_MAX = 0xFFFFFFFF;
UINT16_MAX = 0xFFFF;
AUTH_TOKEN = 1;
AUTH_SIGNATURE = 2;
AUTH_RSAPUBLICKEY = 3;
TOKEN_LENGTH = 20;
function Socket(client, serial, socket, options) {
var base;
this.client = client;
this.serial = serial;
this.socket = socket;
this.options = options != null ? options : {};
(base = this.options).auth || (base.auth = Promise.resolve(true));
this.ended = false;
this.socket.setNoDelay(true);
this.reader = new PacketReader(this.socket).on('packet', this._handle.bind(this)).on('error', (function(_this) {
return function(err) {
debug("PacketReader error: " + err.message);
return _this.end();
};
})(this)).on('end', this.end.bind(this));
this.version = 1;
this.maxPayload = 4096;
this.authorized = false;
this.syncToken = new RollingCounter(UINT32_MAX);
this.remoteId = new RollingCounter(UINT32_MAX);
this.services = new ServiceMap;
this.remoteAddress = this.socket.remoteAddress;
this.token = null;
this.signature = null;
}
Socket.prototype.end = function() {
if (this.ended) {
return this;
}
this.services.end();
this.socket.end();
this.ended = true;
this.emit('end');
return this;
};
Socket.prototype._error = function(err) {
this.emit('error', err);
return this.end();
};
Socket.prototype._handle = function(packet) {
if (this.ended) {
return;
}
this.emit('userActivity', packet);
return Promise["try"]((function(_this) {
return function() {
switch (packet.command) {
case Packet.A_SYNC:
return _this._handleSyncPacket(packet);
case Packet.A_CNXN:
return _this._handleConnectionPacket(packet);
case Packet.A_OPEN:
return _this._handleOpenPacket(packet);
case Packet.A_OKAY:
case Packet.A_WRTE:
case Packet.A_CLSE:
return _this._forwardServicePacket(packet);
case Packet.A_AUTH:
return _this._handleAuthPacket(packet);
default:
throw new Error("Unknown command " + packet.command);
}
};
})(this))["catch"](Socket.AuthError, (function(_this) {
return function() {
return _this.end();
};
})(this))["catch"](Socket.UnauthorizedError, (function(_this) {
return function() {
return _this.end();
};
})(this))["catch"]((function(_this) {
return function(err) {
return _this._error(err);
};
})(this));
};
Socket.prototype._handleSyncPacket = function(packet) {
debug('I:A_SYNC');
debug('O:A_SYNC');
return this.write(Packet.assemble(Packet.A_SYNC, 1, this.syncToken.next(), null));
};
Socket.prototype._handleConnectionPacket = function(packet) {
var version;
debug('I:A_CNXN', packet);
version = Packet.swap32(packet.arg0);
this.maxPayload = Math.min(UINT16_MAX, packet.arg1);
return this._createToken().then((function(_this) {
return function(token) {
_this.token = token;
debug("Created challenge '" + (_this.token.toString('base64')) + "'");
debug('O:A_AUTH');
return _this.write(Packet.assemble(Packet.A_AUTH, AUTH_TOKEN, 0, _this.token));
};
})(this));
};
Socket.prototype._handleAuthPacket = function(packet) {
debug('I:A_AUTH', packet);
switch (packet.arg0) {
case AUTH_SIGNATURE:
debug("Received signature '" + (packet.data.toString('base64')) + "'");
if (!this.signature) {
this.signature = packet.data;
}
debug('O:A_AUTH');
return this.write(Packet.assemble(Packet.A_AUTH, AUTH_TOKEN, 0, this.token));
case AUTH_RSAPUBLICKEY:
if (!this.signature) {
throw new Socket.AuthError("Public key sent before signature");
}
if (!(packet.data && packet.data.length >= 2)) {
throw new Socket.AuthError("Empty RSA public key");
}
debug("Received RSA public key '" + (packet.data.toString('base64')) + "'");
return Auth.parsePublicKey(this._skipNull(packet.data)).then((function(_this) {
return function(key) {
var digest, sig;
digest = _this.token.toString('binary');
sig = _this.signature.toString('binary');
if (!key.verify(digest, sig)) {
debug("Signature mismatch");
throw new Socket.AuthError("Signature mismatch");
}
debug("Signature verified");
return key;
};
})(this)).then((function(_this) {
return function(key) {
return _this.options.auth(key)["catch"](function(err) {
debug("Connection rejected by user-defined auth handler");
throw new Socket.AuthError("Rejected by user-defined handler");
});
};
})(this)).then((function(_this) {
return function() {
return _this._deviceId();
};
})(this)).then((function(_this) {
return function(id) {
_this.authorized = true;
debug('O:A_CNXN');
return _this.write(Packet.assemble(Packet.A_CNXN, Packet.swap32(_this.version), _this.maxPayload, id));
};
})(this));
default:
throw new Error("Unknown authentication method " + packet.arg0);
}
};
Socket.prototype._handleOpenPacket = function(packet) {
var localId, name, remoteId, service;
if (!this.authorized) {
throw new Socket.UnauthorizedError();
}
remoteId = packet.arg0;
localId = this.remoteId.next();
if (!(packet.data && packet.data.length >= 2)) {
throw new Error("Empty service name");
}
name = this._skipNull(packet.data);
debug("Calling " + name);
service = new Service(this.client, this.serial, localId, remoteId, this);
return new Promise((function(_this) {
return function(resolve, reject) {
service.on('error', reject);
service.on('end', resolve);
_this.services.insert(localId, service);
debug("Handling " + _this.services.count + " services simultaneously");
return service.handle(packet);
};
})(this))["catch"](function(err) {
return true;
})["finally"]((function(_this) {
return function() {
_this.services.remove(localId);
debug("Handling " + _this.services.count + " services simultaneously");
return service.end();
};
})(this));
};
Socket.prototype._forwardServicePacket = function(packet) {
var localId, remoteId, service;
if (!this.authorized) {
throw new Socket.UnauthorizedError();
}
remoteId = packet.arg0;
localId = packet.arg1;
if (service = this.services.get(localId)) {
return service.handle(packet);
} else {
return debug("Received a packet to a service that may have been closed already");
}
};
Socket.prototype.write = function(chunk) {
if (this.ended) {
return;
}
return this.socket.write(chunk);
};
Socket.prototype._createToken = function() {
return Promise.promisify(crypto.randomBytes)(TOKEN_LENGTH);
};
Socket.prototype._skipNull = function(data) {
return data.slice(0, -1);
};
Socket.prototype._deviceId = function() {
debug("Loading device properties to form a standard device ID");
return this.client.getProperties(this.serial).then(function(properties) {
var id, prop;
id = ((function() {
var i, len, ref, results;
ref = ['ro.product.name', 'ro.product.model', 'ro.product.device'];
results = [];
for (i = 0, len = ref.length; i < len; i++) {
prop = ref[i];
results.push(prop + "=" + properties[prop] + ";");
}
return results;
})()).join('');
return new Buffer("device::" + id + "\0");
});
};
return Socket;
})(EventEmitter);
Socket.AuthError = (function(superClass) {
extend(AuthError, superClass);
function AuthError(message) {
this.message = message;
Error.call(this);
this.name = 'AuthError';
Error.captureStackTrace(this, Socket.AuthError);
}
return AuthError;
})(Error);
Socket.UnauthorizedError = (function(superClass) {
extend(UnauthorizedError, superClass);
function UnauthorizedError() {
Error.call(this);
this.name = 'UnauthorizedError';
this.message = "Unauthorized access";
Error.captureStackTrace(this, Socket.UnauthorizedError);
}
return UnauthorizedError;
})(Error);
module.exports = Socket;
+89
View File
@@ -0,0 +1,89 @@
var EventEmitter, Parser, Promise, Tracker,
extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
hasProp = {}.hasOwnProperty;
EventEmitter = require('events').EventEmitter;
Promise = require('bluebird');
Parser = require('./parser');
Tracker = (function(superClass) {
extend(Tracker, superClass);
function Tracker(command) {
this.command = command;
this.deviceList = [];
this.deviceMap = {};
this.reader = this.read()["catch"](Promise.CancellationError, function() {
return true;
})["catch"](Parser.PrematureEOFError, function() {
throw new Error('Connection closed');
})["catch"]((function(_this) {
return function(err) {
_this.emit('error', err);
};
})(this))["finally"]((function(_this) {
return function() {
return _this.command.parser.end().then(function() {
return _this.emit('end');
});
};
})(this));
}
Tracker.prototype.read = function() {
return this.command._readDevices().cancellable().then((function(_this) {
return function(list) {
_this.update(list);
return _this.read();
};
})(this));
};
Tracker.prototype.update = function(newList) {
var changeSet, device, i, j, len, len1, newMap, oldDevice, ref;
changeSet = {
removed: [],
changed: [],
added: []
};
newMap = {};
for (i = 0, len = newList.length; i < len; i++) {
device = newList[i];
oldDevice = this.deviceMap[device.id];
if (oldDevice) {
if (oldDevice.type !== device.type) {
changeSet.changed.push(device);
this.emit('change', device, oldDevice);
}
} else {
changeSet.added.push(device);
this.emit('add', device);
}
newMap[device.id] = device;
}
ref = this.deviceList;
for (j = 0, len1 = ref.length; j < len1; j++) {
device = ref[j];
if (!newMap[device.id]) {
changeSet.removed.push(device);
this.emit('remove', device);
}
}
this.emit('changeSet', changeSet);
this.deviceList = newList;
this.deviceMap = newMap;
return this;
};
Tracker.prototype.end = function() {
this.reader.cancel();
return this;
};
return Tracker;
})(EventEmitter);
module.exports = Tracker;
+13
View File
@@ -0,0 +1,13 @@
var Auth, Parser;
Parser = require('./parser');
Auth = require('./auth');
module.exports.readAll = function(stream, callback) {
return new Parser(stream).readAll(stream).nodeify(callback);
};
module.exports.parsePublicKey = function(keyString, callback) {
return Auth.parsePublicKey(keyString).nodeify(callback);
};
+66
View File
@@ -0,0 +1,66 @@
var Adb, Auth, PacketReader, Promise, forge, fs, pkg, program;
fs = require('fs');
program = require('commander');
Promise = require('bluebird');
forge = require('node-forge');
pkg = require('../package');
Adb = require('./adb');
Auth = require('./adb/auth');
PacketReader = require('./adb/tcpusb/packetreader');
Promise.longStackTraces();
program.version(pkg.version);
program.command('pubkey-convert <file>').option('-f, --format <format>', 'format (pem or openssh)', String, 'pem').description('Converts an ADB-generated public key into PEM format.').action(function(file, options) {
return Auth.parsePublicKey(fs.readFileSync(file)).then(function(key) {
switch (options.format.toLowerCase()) {
case 'pem':
return console.log(forge.pki.publicKeyToPem(key).trim());
case 'openssh':
return console.log(forge.ssh.publicKeyToOpenSSH(key, 'adbkey').trim());
default:
console.error("Unsupported format '" + options.format + "'");
return process.exit(1);
}
});
});
program.command('pubkey-fingerprint <file>').description('Outputs the fingerprint of an ADB-generated public key.').action(function(file) {
return Auth.parsePublicKey(fs.readFileSync(file)).then(function(key) {
return console.log('%s %s', key.fingerprint, key.comment);
});
});
program.command('usb-device-to-tcp <serial>').option('-p, --port <port>', 'port number', String, 6174).description('Provides an USB device over TCP using a translating proxy.').action(function(serial, options) {
var adb, server;
adb = Adb.createClient();
server = adb.createTcpUsbBridge(serial, {
auth: function() {
return Promise.resolve();
}
}).on('listening', function() {
return console.info('Connect with `adb connect localhost:%d`', options.port);
}).on('error', function(err) {
return console.error("An error occured: " + err.message);
});
return server.listen(options.port);
});
program.command('parse-tcp-packets <file>').description('Parses ADB TCP packets from the given file.').action(function(file, options) {
var reader;
reader = new PacketReader(fs.createReadStream(file));
return reader.on('packet', function(packet) {
return console.log(packet.toString());
});
});
program.parse(process.argv);
+419
View File
@@ -0,0 +1,419 @@
2.20.3 / 2019-10-11
==================
* Support Node.js 0.10 (Revert #1059)
* Ran "npm unpublish commander@2.20.2". There is no 2.20.2.
2.20.1 / 2019-09-29
==================
* Improve executable subcommand tracking
* Update dev dependencies
2.20.0 / 2019-04-02
==================
* fix: resolve symbolic links completely when hunting for subcommands (#935)
* Update index.d.ts (#930)
* Update Readme.md (#924)
* Remove --save option as it isn't required anymore (#918)
* Add link to the license file (#900)
* Added example of receiving args from options (#858)
* Added missing semicolon (#882)
* Add extension to .eslintrc (#876)
2.19.0 / 2018-10-02
==================
* Removed newline after Options and Commands headers (#864)
* Bugfix - Error output (#862)
* Fix to change default value to string (#856)
2.18.0 / 2018-09-07
==================
* Standardize help output (#853)
* chmod 644 travis.yml (#851)
* add support for execute typescript subcommand via ts-node (#849)
2.17.1 / 2018-08-07
==================
* Fix bug in command emit (#844)
2.17.0 / 2018-08-03
==================
* fixed newline output after help information (#833)
* Fix to emit the action even without command (#778)
* npm update (#823)
2.16.0 / 2018-06-29
==================
* Remove Makefile and `test/run` (#821)
* Make 'npm test' run on Windows (#820)
* Add badge to display install size (#807)
* chore: cache node_modules (#814)
* chore: remove Node.js 4 (EOL), add Node.js 10 (#813)
* fixed typo in readme (#812)
* Fix types (#804)
* Update eslint to resolve vulnerabilities in lodash (#799)
* updated readme with custom event listeners. (#791)
* fix tests (#794)
2.15.0 / 2018-03-07
==================
* Update downloads badge to point to graph of downloads over time instead of duplicating link to npm
* Arguments description
2.14.1 / 2018-02-07
==================
* Fix typing of help function
2.14.0 / 2018-02-05
==================
* only register the option:version event once
* Fixes issue #727: Passing empty string for option on command is set to undefined
* enable eqeqeq rule
* resolves #754 add linter configuration to project
* resolves #560 respect custom name for version option
* document how to override the version flag
* document using options per command
2.13.0 / 2018-01-09
==================
* Do not print default for --no-
* remove trailing spaces in command help
* Update CI's Node.js to LTS and latest version
* typedefs: Command and Option types added to commander namespace
2.12.2 / 2017-11-28
==================
* fix: typings are not shipped
2.12.1 / 2017-11-23
==================
* Move @types/node to dev dependency
2.12.0 / 2017-11-22
==================
* add attributeName() method to Option objects
* Documentation updated for options with --no prefix
* typings: `outputHelp` takes a string as the first parameter
* typings: use overloads
* feat(typings): update to match js api
* Print default value in option help
* Fix translation error
* Fail when using same command and alias (#491)
* feat(typings): add help callback
* fix bug when description is add after command with options (#662)
* Format js code
* Rename History.md to CHANGELOG.md (#668)
* feat(typings): add typings to support TypeScript (#646)
* use current node
2.11.0 / 2017-07-03
==================
* Fix help section order and padding (#652)
* feature: support for signals to subcommands (#632)
* Fixed #37, --help should not display first (#447)
* Fix translation errors. (#570)
* Add package-lock.json
* Remove engines
* Upgrade package version
* Prefix events to prevent conflicts between commands and options (#494)
* Removing dependency on graceful-readlink
* Support setting name in #name function and make it chainable
* Add .vscode directory to .gitignore (Visual Studio Code metadata)
* Updated link to ruby commander in readme files
2.10.0 / 2017-06-19
==================
* Update .travis.yml. drop support for older node.js versions.
* Fix require arguments in README.md
* On SemVer you do not start from 0.0.1
* Add missing semi colon in readme
* Add save param to npm install
* node v6 travis test
* Update Readme_zh-CN.md
* Allow literal '--' to be passed-through as an argument
* Test subcommand alias help
* link build badge to master branch
* Support the alias of Git style sub-command
* added keyword commander for better search result on npm
* Fix Sub-Subcommands
* test node.js stable
* Fixes TypeError when a command has an option called `--description`
* Update README.md to make it beginner friendly and elaborate on the difference between angled and square brackets.
* Add chinese Readme file
2.9.0 / 2015-10-13
==================
* Add option `isDefault` to set default subcommand #415 @Qix-
* Add callback to allow filtering or post-processing of help text #434 @djulien
* Fix `undefined` text in help information close #414 #416 @zhiyelee
2.8.1 / 2015-04-22
==================
* Back out `support multiline description` Close #396 #397
2.8.0 / 2015-04-07
==================
* Add `process.execArg` support, execution args like `--harmony` will be passed to sub-commands #387 @DigitalIO @zhiyelee
* Fix bug in Git-style sub-commands #372 @zhiyelee
* Allow commands to be hidden from help #383 @tonylukasavage
* When git-style sub-commands are in use, yet none are called, display help #382 @claylo
* Add ability to specify arguments syntax for top-level command #258 @rrthomas
* Support multiline descriptions #208 @zxqfox
2.7.1 / 2015-03-11
==================
* Revert #347 (fix collisions when option and first arg have same name) which causes a bug in #367.
2.7.0 / 2015-03-09
==================
* Fix git-style bug when installed globally. Close #335 #349 @zhiyelee
* Fix collisions when option and first arg have same name. Close #346 #347 @tonylukasavage
* Add support for camelCase on `opts()`. Close #353 @nkzawa
* Add node.js 0.12 and io.js to travis.yml
* Allow RegEx options. #337 @palanik
* Fixes exit code when sub-command failing. Close #260 #332 @pirelenito
* git-style `bin` files in $PATH make sense. Close #196 #327 @zhiyelee
2.6.0 / 2014-12-30
==================
* added `Command#allowUnknownOption` method. Close #138 #318 @doozr @zhiyelee
* Add application description to the help msg. Close #112 @dalssoft
2.5.1 / 2014-12-15
==================
* fixed two bugs incurred by variadic arguments. Close #291 @Quentin01 #302 @zhiyelee
2.5.0 / 2014-10-24
==================
* add support for variadic arguments. Closes #277 @whitlockjc
2.4.0 / 2014-10-17
==================
* fixed a bug on executing the coercion function of subcommands option. Closes #270
* added `Command.prototype.name` to retrieve command name. Closes #264 #266 @tonylukasavage
* added `Command.prototype.opts` to retrieve all the options as a simple object of key-value pairs. Closes #262 @tonylukasavage
* fixed a bug on subcommand name. Closes #248 @jonathandelgado
* fixed function normalize doesnt honor option terminator. Closes #216 @abbr
2.3.0 / 2014-07-16
==================
* add command alias'. Closes PR #210
* fix: Typos. Closes #99
* fix: Unused fs module. Closes #217
2.2.0 / 2014-03-29
==================
* add passing of previous option value
* fix: support subcommands on windows. Closes #142
* Now the defaultValue passed as the second argument of the coercion function.
2.1.0 / 2013-11-21
==================
* add: allow cflag style option params, unit test, fixes #174
2.0.0 / 2013-07-18
==================
* remove input methods (.prompt, .confirm, etc)
1.3.2 / 2013-07-18
==================
* add support for sub-commands to co-exist with the original command
1.3.1 / 2013-07-18
==================
* add quick .runningCommand hack so you can opt-out of other logic when running a sub command
1.3.0 / 2013-07-09
==================
* add EACCES error handling
* fix sub-command --help
1.2.0 / 2013-06-13
==================
* allow "-" hyphen as an option argument
* support for RegExp coercion
1.1.1 / 2012-11-20
==================
* add more sub-command padding
* fix .usage() when args are present. Closes #106
1.1.0 / 2012-11-16
==================
* add git-style executable subcommand support. Closes #94
1.0.5 / 2012-10-09
==================
* fix `--name` clobbering. Closes #92
* fix examples/help. Closes #89
1.0.4 / 2012-09-03
==================
* add `outputHelp()` method.
1.0.3 / 2012-08-30
==================
* remove invalid .version() defaulting
1.0.2 / 2012-08-24
==================
* add `--foo=bar` support [arv]
* fix password on node 0.8.8. Make backward compatible with 0.6 [focusaurus]
1.0.1 / 2012-08-03
==================
* fix issue #56
* fix tty.setRawMode(mode) was moved to tty.ReadStream#setRawMode() (i.e. process.stdin.setRawMode())
1.0.0 / 2012-07-05
==================
* add support for optional option descriptions
* add defaulting of `.version()` to package.json's version
0.6.1 / 2012-06-01
==================
* Added: append (yes or no) on confirmation
* Added: allow node.js v0.7.x
0.6.0 / 2012-04-10
==================
* Added `.prompt(obj, callback)` support. Closes #49
* Added default support to .choose(). Closes #41
* Fixed the choice example
0.5.1 / 2011-12-20
==================
* Fixed `password()` for recent nodes. Closes #36
0.5.0 / 2011-12-04
==================
* Added sub-command option support [itay]
0.4.3 / 2011-12-04
==================
* Fixed custom help ordering. Closes #32
0.4.2 / 2011-11-24
==================
* Added travis support
* Fixed: line-buffered input automatically trimmed. Closes #31
0.4.1 / 2011-11-18
==================
* Removed listening for "close" on --help
0.4.0 / 2011-11-15
==================
* Added support for `--`. Closes #24
0.3.3 / 2011-11-14
==================
* Fixed: wait for close event when writing help info [Jerry Hamlet]
0.3.2 / 2011-11-01
==================
* Fixed long flag definitions with values [felixge]
0.3.1 / 2011-10-31
==================
* Changed `--version` short flag to `-V` from `-v`
* Changed `.version()` so it's configurable [felixge]
0.3.0 / 2011-10-31
==================
* Added support for long flags only. Closes #18
0.2.1 / 2011-10-24
==================
* "node": ">= 0.4.x < 0.7.0". Closes #20
0.2.0 / 2011-09-26
==================
* Allow for defaults that are not just boolean. Default peassignment only occurs for --no-*, optional, and required arguments. [Jim Isaacs]
0.1.0 / 2011-08-24
==================
* Added support for custom `--help` output
0.0.5 / 2011-08-18
==================
* Changed: when the user enters nothing prompt for password again
* Fixed issue with passwords beginning with numbers [NuckChorris]
0.0.4 / 2011-08-15
==================
* Fixed `Commander#args`
0.0.3 / 2011-08-15
==================
* Added default option value support
0.0.2 / 2011-08-15
==================
* Added mask support to `Command#password(str[, mask], fn)`
* Added `Command#password(str, fn)`
0.0.1 / 2010-01-03
==================
* Initial release
+22
View File
@@ -0,0 +1,22 @@
(The MIT License)
Copyright (c) 2011 TJ Holowaychuk <tj@vision-media.ca>
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
'Software'), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+428
View File
@@ -0,0 +1,428 @@
# Commander.js
[![Build Status](https://api.travis-ci.org/tj/commander.js.svg?branch=master)](http://travis-ci.org/tj/commander.js)
[![NPM Version](http://img.shields.io/npm/v/commander.svg?style=flat)](https://www.npmjs.org/package/commander)
[![NPM Downloads](https://img.shields.io/npm/dm/commander.svg?style=flat)](https://npmcharts.com/compare/commander?minimal=true)
[![Install Size](https://packagephobia.now.sh/badge?p=commander)](https://packagephobia.now.sh/result?p=commander)
[![Join the chat at https://gitter.im/tj/commander.js](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/tj/commander.js?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)
The complete solution for [node.js](http://nodejs.org) command-line interfaces, inspired by Ruby's [commander](https://github.com/commander-rb/commander).
[API documentation](http://tj.github.com/commander.js/)
## Installation
$ npm install commander
## Option parsing
Options with commander are defined with the `.option()` method, also serving as documentation for the options. The example below parses args and options from `process.argv`, leaving remaining args as the `program.args` array which were not consumed by options.
```js
#!/usr/bin/env node
/**
* Module dependencies.
*/
var program = require('commander');
program
.version('0.1.0')
.option('-p, --peppers', 'Add peppers')
.option('-P, --pineapple', 'Add pineapple')
.option('-b, --bbq-sauce', 'Add bbq sauce')
.option('-c, --cheese [type]', 'Add the specified type of cheese [marble]', 'marble')
.parse(process.argv);
console.log('you ordered a pizza with:');
if (program.peppers) console.log(' - peppers');
if (program.pineapple) console.log(' - pineapple');
if (program.bbqSauce) console.log(' - bbq');
console.log(' - %s cheese', program.cheese);
```
Short flags may be passed as a single arg, for example `-abc` is equivalent to `-a -b -c`. Multi-word options such as "--template-engine" are camel-cased, becoming `program.templateEngine` etc.
Note that multi-word options starting with `--no` prefix negate the boolean value of the following word. For example, `--no-sauce` sets the value of `program.sauce` to false.
```js
#!/usr/bin/env node
/**
* Module dependencies.
*/
var program = require('commander');
program
.option('--no-sauce', 'Remove sauce')
.parse(process.argv);
console.log('you ordered a pizza');
if (program.sauce) console.log(' with sauce');
else console.log(' without sauce');
```
To get string arguments from options you will need to use angle brackets <> for required inputs or square brackets [] for optional inputs.
e.g. ```.option('-m --myarg [myVar]', 'my super cool description')```
Then to access the input if it was passed in.
e.g. ```var myInput = program.myarg```
**NOTE**: If you pass a argument without using brackets the example above will return true and not the value passed in.
## Version option
Calling the `version` implicitly adds the `-V` and `--version` options to the command.
When either of these options is present, the command prints the version number and exits.
$ ./examples/pizza -V
0.0.1
If you want your program to respond to the `-v` option instead of the `-V` option, simply pass custom flags to the `version` method using the same syntax as the `option` method.
```js
program
.version('0.0.1', '-v, --version')
```
The version flags can be named anything, but the long option is required.
## Command-specific options
You can attach options to a command.
```js
#!/usr/bin/env node
var program = require('commander');
program
.command('rm <dir>')
.option('-r, --recursive', 'Remove recursively')
.action(function (dir, cmd) {
console.log('remove ' + dir + (cmd.recursive ? ' recursively' : ''))
})
program.parse(process.argv)
```
A command's options are validated when the command is used. Any unknown options will be reported as an error. However, if an action-based command does not define an action, then the options are not validated.
## Coercion
```js
function range(val) {
return val.split('..').map(Number);
}
function list(val) {
return val.split(',');
}
function collect(val, memo) {
memo.push(val);
return memo;
}
function increaseVerbosity(v, total) {
return total + 1;
}
program
.version('0.1.0')
.usage('[options] <file ...>')
.option('-i, --integer <n>', 'An integer argument', parseInt)
.option('-f, --float <n>', 'A float argument', parseFloat)
.option('-r, --range <a>..<b>', 'A range', range)
.option('-l, --list <items>', 'A list', list)
.option('-o, --optional [value]', 'An optional value')
.option('-c, --collect [value]', 'A repeatable value', collect, [])
.option('-v, --verbose', 'A value that can be increased', increaseVerbosity, 0)
.parse(process.argv);
console.log(' int: %j', program.integer);
console.log(' float: %j', program.float);
console.log(' optional: %j', program.optional);
program.range = program.range || [];
console.log(' range: %j..%j', program.range[0], program.range[1]);
console.log(' list: %j', program.list);
console.log(' collect: %j', program.collect);
console.log(' verbosity: %j', program.verbose);
console.log(' args: %j', program.args);
```
## Regular Expression
```js
program
.version('0.1.0')
.option('-s --size <size>', 'Pizza size', /^(large|medium|small)$/i, 'medium')
.option('-d --drink [drink]', 'Drink', /^(coke|pepsi|izze)$/i)
.parse(process.argv);
console.log(' size: %j', program.size);
console.log(' drink: %j', program.drink);
```
## Variadic arguments
The last argument of a command can be variadic, and only the last argument. To make an argument variadic you have to
append `...` to the argument name. Here is an example:
```js
#!/usr/bin/env node
/**
* Module dependencies.
*/
var program = require('commander');
program
.version('0.1.0')
.command('rmdir <dir> [otherDirs...]')
.action(function (dir, otherDirs) {
console.log('rmdir %s', dir);
if (otherDirs) {
otherDirs.forEach(function (oDir) {
console.log('rmdir %s', oDir);
});
}
});
program.parse(process.argv);
```
An `Array` is used for the value of a variadic argument. This applies to `program.args` as well as the argument passed
to your action as demonstrated above.
## Specify the argument syntax
```js
#!/usr/bin/env node
var program = require('commander');
program
.version('0.1.0')
.arguments('<cmd> [env]')
.action(function (cmd, env) {
cmdValue = cmd;
envValue = env;
});
program.parse(process.argv);
if (typeof cmdValue === 'undefined') {
console.error('no command given!');
process.exit(1);
}
console.log('command:', cmdValue);
console.log('environment:', envValue || "no environment given");
```
Angled brackets (e.g. `<cmd>`) indicate required input. Square brackets (e.g. `[env]`) indicate optional input.
## Git-style sub-commands
```js
// file: ./examples/pm
var program = require('commander');
program
.version('0.1.0')
.command('install [name]', 'install one or more packages')
.command('search [query]', 'search with optional query')
.command('list', 'list packages installed', {isDefault: true})
.parse(process.argv);
```
When `.command()` is invoked with a description argument, no `.action(callback)` should be called to handle sub-commands, otherwise there will be an error. This tells commander that you're going to use separate executables for sub-commands, much like `git(1)` and other popular tools.
The commander will try to search the executables in the directory of the entry script (like `./examples/pm`) with the name `program-command`, like `pm-install`, `pm-search`.
Options can be passed with the call to `.command()`. Specifying `true` for `opts.noHelp` will remove the subcommand from the generated help output. Specifying `true` for `opts.isDefault` will run the subcommand if no other subcommand is specified.
If the program is designed to be installed globally, make sure the executables have proper modes, like `755`.
### `--harmony`
You can enable `--harmony` option in two ways:
* Use `#! /usr/bin/env node --harmony` in the sub-commands scripts. Note some os version dont support this pattern.
* Use the `--harmony` option when call the command, like `node --harmony examples/pm publish`. The `--harmony` option will be preserved when spawning sub-command process.
## Automated --help
The help information is auto-generated based on the information commander already knows about your program, so the following `--help` info is for free:
```
$ ./examples/pizza --help
Usage: pizza [options]
An application for pizzas ordering
Options:
-h, --help output usage information
-V, --version output the version number
-p, --peppers Add peppers
-P, --pineapple Add pineapple
-b, --bbq Add bbq sauce
-c, --cheese <type> Add the specified type of cheese [marble]
-C, --no-cheese You do not want any cheese
```
## Custom help
You can display arbitrary `-h, --help` information
by listening for "--help". Commander will automatically
exit once you are done so that the remainder of your program
does not execute causing undesired behaviors, for example
in the following executable "stuff" will not output when
`--help` is used.
```js
#!/usr/bin/env node
/**
* Module dependencies.
*/
var program = require('commander');
program
.version('0.1.0')
.option('-f, --foo', 'enable some foo')
.option('-b, --bar', 'enable some bar')
.option('-B, --baz', 'enable some baz');
// must be before .parse() since
// node's emit() is immediate
program.on('--help', function(){
console.log('')
console.log('Examples:');
console.log(' $ custom-help --help');
console.log(' $ custom-help -h');
});
program.parse(process.argv);
console.log('stuff');
```
Yields the following help output when `node script-name.js -h` or `node script-name.js --help` are run:
```
Usage: custom-help [options]
Options:
-h, --help output usage information
-V, --version output the version number
-f, --foo enable some foo
-b, --bar enable some bar
-B, --baz enable some baz
Examples:
$ custom-help --help
$ custom-help -h
```
## .outputHelp(cb)
Output help information without exiting.
Optional callback cb allows post-processing of help text before it is displayed.
If you want to display help by default (e.g. if no command was provided), you can use something like:
```js
var program = require('commander');
var colors = require('colors');
program
.version('0.1.0')
.command('getstream [url]', 'get stream URL')
.parse(process.argv);
if (!process.argv.slice(2).length) {
program.outputHelp(make_red);
}
function make_red(txt) {
return colors.red(txt); //display the help text in red on the console
}
```
## .help(cb)
Output help information and exit immediately.
Optional callback cb allows post-processing of help text before it is displayed.
## Custom event listeners
You can execute custom actions by listening to command and option events.
```js
program.on('option:verbose', function () {
process.env.VERBOSE = this.verbose;
});
// error on unknown commands
program.on('command:*', function () {
console.error('Invalid command: %s\nSee --help for a list of available commands.', program.args.join(' '));
process.exit(1);
});
```
## Examples
```js
var program = require('commander');
program
.version('0.1.0')
.option('-C, --chdir <path>', 'change the working directory')
.option('-c, --config <path>', 'set config path. defaults to ./deploy.conf')
.option('-T, --no-tests', 'ignore test hook');
program
.command('setup [env]')
.description('run setup commands for all envs')
.option("-s, --setup_mode [mode]", "Which setup mode to use")
.action(function(env, options){
var mode = options.setup_mode || "normal";
env = env || 'all';
console.log('setup for %s env(s) with %s mode', env, mode);
});
program
.command('exec <cmd>')
.alias('ex')
.description('execute the given remote cmd')
.option("-e, --exec_mode <mode>", "Which exec mode to use")
.action(function(cmd, options){
console.log('exec "%s" using %s mode', cmd, options.exec_mode);
}).on('--help', function() {
console.log('');
console.log('Examples:');
console.log('');
console.log(' $ deploy exec sequential');
console.log(' $ deploy exec async');
});
program
.command('*')
.action(function(env){
console.log('deploying "%s"', env);
});
program.parse(process.argv);
```
More Demos can be found in the [examples](https://github.com/tj/commander.js/tree/master/examples) directory.
## License
[MIT](https://github.com/tj/commander.js/blob/master/LICENSE)
File diff suppressed because it is too large Load Diff
+38
View File
@@ -0,0 +1,38 @@
{
"name": "commander",
"version": "2.20.3",
"description": "the complete solution for node.js command-line programs",
"keywords": [
"commander",
"command",
"option",
"parser"
],
"author": "TJ Holowaychuk <tj@vision-media.ca>",
"license": "MIT",
"repository": {
"type": "git",
"url": "https://github.com/tj/commander.js.git"
},
"scripts": {
"lint": "eslint index.js",
"test": "node test/run.js && npm run test-typings",
"test-typings": "tsc -p tsconfig.json"
},
"main": "index",
"files": [
"index.js",
"typings/index.d.ts"
],
"dependencies": {},
"devDependencies": {
"@types/node": "^12.7.8",
"eslint": "^6.4.0",
"should": "^13.2.3",
"sinon": "^7.5.0",
"standard": "^14.3.1",
"ts-node": "^8.4.1",
"typescript": "^3.6.3"
},
"typings": "typings/index.d.ts"
}
+310
View File
@@ -0,0 +1,310 @@
// Type definitions for commander 2.11
// Project: https://github.com/visionmedia/commander.js
// Definitions by: Alan Agius <https://github.com/alan-agius4>, Marcelo Dezem <https://github.com/mdezem>, vvakame <https://github.com/vvakame>, Jules Randolph <https://github.com/sveinburne>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
declare namespace local {
class Option {
flags: string;
required: boolean;
optional: boolean;
bool: boolean;
short?: string;
long: string;
description: string;
/**
* Initialize a new `Option` with the given `flags` and `description`.
*
* @param {string} flags
* @param {string} [description]
*/
constructor(flags: string, description?: string);
}
class Command extends NodeJS.EventEmitter {
[key: string]: any;
args: string[];
/**
* Initialize a new `Command`.
*
* @param {string} [name]
*/
constructor(name?: string);
/**
* Set the program version to `str`.
*
* This method auto-registers the "-V, --version" flag
* which will print the version number when passed.
*
* @param {string} str
* @param {string} [flags]
* @returns {Command} for chaining
*/
version(str: string, flags?: string): Command;
/**
* Add command `name`.
*
* The `.action()` callback is invoked when the
* command `name` is specified via __ARGV__,
* and the remaining arguments are applied to the
* function for access.
*
* When the `name` is "*" an un-matched command
* will be passed as the first arg, followed by
* the rest of __ARGV__ remaining.
*
* @example
* program
* .version('0.0.1')
* .option('-C, --chdir <path>', 'change the working directory')
* .option('-c, --config <path>', 'set config path. defaults to ./deploy.conf')
* .option('-T, --no-tests', 'ignore test hook')
*
* program
* .command('setup')
* .description('run remote setup commands')
* .action(function() {
* console.log('setup');
* });
*
* program
* .command('exec <cmd>')
* .description('run the given remote command')
* .action(function(cmd) {
* console.log('exec "%s"', cmd);
* });
*
* program
* .command('teardown <dir> [otherDirs...]')
* .description('run teardown commands')
* .action(function(dir, otherDirs) {
* console.log('dir "%s"', dir);
* if (otherDirs) {
* otherDirs.forEach(function (oDir) {
* console.log('dir "%s"', oDir);
* });
* }
* });
*
* program
* .command('*')
* .description('deploy the given env')
* .action(function(env) {
* console.log('deploying "%s"', env);
* });
*
* program.parse(process.argv);
*
* @param {string} name
* @param {string} [desc] for git-style sub-commands
* @param {CommandOptions} [opts] command options
* @returns {Command} the new command
*/
command(name: string, desc?: string, opts?: commander.CommandOptions): Command;
/**
* Define argument syntax for the top-level command.
*
* @param {string} desc
* @returns {Command} for chaining
*/
arguments(desc: string): Command;
/**
* Parse expected `args`.
*
* For example `["[type]"]` becomes `[{ required: false, name: 'type' }]`.
*
* @param {string[]} args
* @returns {Command} for chaining
*/
parseExpectedArgs(args: string[]): Command;
/**
* Register callback `fn` for the command.
*
* @example
* program
* .command('help')
* .description('display verbose help')
* .action(function() {
* // output help here
* });
*
* @param {(...args: any[]) => void} fn
* @returns {Command} for chaining
*/
action(fn: (...args: any[]) => void): Command;
/**
* Define option with `flags`, `description` and optional
* coercion `fn`.
*
* The `flags` string should contain both the short and long flags,
* separated by comma, a pipe or space. The following are all valid
* all will output this way when `--help` is used.
*
* "-p, --pepper"
* "-p|--pepper"
* "-p --pepper"
*
* @example
* // simple boolean defaulting to false
* program.option('-p, --pepper', 'add pepper');
*
* --pepper
* program.pepper
* // => Boolean
*
* // simple boolean defaulting to true
* program.option('-C, --no-cheese', 'remove cheese');
*
* program.cheese
* // => true
*
* --no-cheese
* program.cheese
* // => false
*
* // required argument
* program.option('-C, --chdir <path>', 'change the working directory');
*
* --chdir /tmp
* program.chdir
* // => "/tmp"
*
* // optional argument
* program.option('-c, --cheese [type]', 'add cheese [marble]');
*
* @param {string} flags
* @param {string} [description]
* @param {((arg1: any, arg2: any) => void) | RegExp} [fn] function or default
* @param {*} [defaultValue]
* @returns {Command} for chaining
*/
option(flags: string, description?: string, fn?: ((arg1: any, arg2: any) => void) | RegExp, defaultValue?: any): Command;
option(flags: string, description?: string, defaultValue?: any): Command;
/**
* Allow unknown options on the command line.
*
* @param {boolean} [arg] if `true` or omitted, no error will be thrown for unknown options.
* @returns {Command} for chaining
*/
allowUnknownOption(arg?: boolean): Command;
/**
* Parse `argv`, settings options and invoking commands when defined.
*
* @param {string[]} argv
* @returns {Command} for chaining
*/
parse(argv: string[]): Command;
/**
* Parse options from `argv` returning `argv` void of these options.
*
* @param {string[]} argv
* @returns {ParseOptionsResult}
*/
parseOptions(argv: string[]): commander.ParseOptionsResult;
/**
* Return an object containing options as key-value pairs
*
* @returns {{[key: string]: any}}
*/
opts(): { [key: string]: any };
/**
* Set the description to `str`.
*
* @param {string} str
* @param {{[argName: string]: string}} argsDescription
* @return {(Command | string)}
*/
description(str: string, argsDescription?: {[argName: string]: string}): Command;
description(): string;
/**
* Set an alias for the command.
*
* @param {string} alias
* @return {(Command | string)}
*/
alias(alias: string): Command;
alias(): string;
/**
* Set or get the command usage.
*
* @param {string} str
* @return {(Command | string)}
*/
usage(str: string): Command;
usage(): string;
/**
* Set the name of the command.
*
* @param {string} str
* @return {Command}
*/
name(str: string): Command;
/**
* Get the name of the command.
*
* @return {string}
*/
name(): string;
/**
* Output help information for this command.
*
* @param {(str: string) => string} [cb]
*/
outputHelp(cb?: (str: string) => string): void;
/** Output help information and exit.
*
* @param {(str: string) => string} [cb]
*/
help(cb?: (str: string) => string): never;
}
}
declare namespace commander {
type Command = local.Command
type Option = local.Option
interface CommandOptions {
noHelp?: boolean;
isDefault?: boolean;
}
interface ParseOptionsResult {
args: string[];
unknown: string[];
}
interface CommanderStatic extends Command {
Command: typeof local.Command;
Option: typeof local.Option;
CommandOptions: CommandOptions;
ParseOptionsResult: ParseOptionsResult;
}
}
declare const commander: commander.CommanderStatic;
export = commander;
+1
View File
@@ -0,0 +1 @@
repo_token: SIAeZjKYlHK74rbcFvNHMUzjRiMpflxve
+11
View File
@@ -0,0 +1,11 @@
{
"env": {
"browser": true,
"node": true
},
"rules": {
"no-console": 0,
"no-empty": [1, { "allowEmptyCatch": true }]
},
"extends": "eslint:recommended"
}
+9
View File
@@ -0,0 +1,9 @@
support
test
examples
example
*.sock
dist
yarn.lock
coverage
bower.json
+14
View File
@@ -0,0 +1,14 @@
language: node_js
node_js:
- "6"
- "5"
- "4"
install:
- make node_modules
script:
- make lint
- make test
- make coveralls
+362
View File
@@ -0,0 +1,362 @@
2.6.9 / 2017-09-22
==================
* remove ReDoS regexp in %o formatter (#504)
2.6.8 / 2017-05-18
==================
* Fix: Check for undefined on browser globals (#462, @marbemac)
2.6.7 / 2017-05-16
==================
* Fix: Update ms to 2.0.0 to fix regular expression denial of service vulnerability (#458, @hubdotcom)
* Fix: Inline extend function in node implementation (#452, @dougwilson)
* Docs: Fix typo (#455, @msasad)
2.6.5 / 2017-04-27
==================
* Fix: null reference check on window.documentElement.style.WebkitAppearance (#447, @thebigredgeek)
* Misc: clean up browser reference checks (#447, @thebigredgeek)
* Misc: add npm-debug.log to .gitignore (@thebigredgeek)
2.6.4 / 2017-04-20
==================
* Fix: bug that would occure if process.env.DEBUG is a non-string value. (#444, @LucianBuzzo)
* Chore: ignore bower.json in npm installations. (#437, @joaovieira)
* Misc: update "ms" to v0.7.3 (@tootallnate)
2.6.3 / 2017-03-13
==================
* Fix: Electron reference to `process.env.DEBUG` (#431, @paulcbetts)
* Docs: Changelog fix (@thebigredgeek)
2.6.2 / 2017-03-10
==================
* Fix: DEBUG_MAX_ARRAY_LENGTH (#420, @slavaGanzin)
* Docs: Add backers and sponsors from Open Collective (#422, @piamancini)
* Docs: Add Slackin invite badge (@tootallnate)
2.6.1 / 2017-02-10
==================
* Fix: Module's `export default` syntax fix for IE8 `Expected identifier` error
* Fix: Whitelist DEBUG_FD for values 1 and 2 only (#415, @pi0)
* Fix: IE8 "Expected identifier" error (#414, @vgoma)
* Fix: Namespaces would not disable once enabled (#409, @musikov)
2.6.0 / 2016-12-28
==================
* Fix: added better null pointer checks for browser useColors (@thebigredgeek)
* Improvement: removed explicit `window.debug` export (#404, @tootallnate)
* Improvement: deprecated `DEBUG_FD` environment variable (#405, @tootallnate)
2.5.2 / 2016-12-25
==================
* Fix: reference error on window within webworkers (#393, @KlausTrainer)
* Docs: fixed README typo (#391, @lurch)
* Docs: added notice about v3 api discussion (@thebigredgeek)
2.5.1 / 2016-12-20
==================
* Fix: babel-core compatibility
2.5.0 / 2016-12-20
==================
* Fix: wrong reference in bower file (@thebigredgeek)
* Fix: webworker compatibility (@thebigredgeek)
* Fix: output formatting issue (#388, @kribblo)
* Fix: babel-loader compatibility (#383, @escwald)
* Misc: removed built asset from repo and publications (@thebigredgeek)
* Misc: moved source files to /src (#378, @yamikuronue)
* Test: added karma integration and replaced babel with browserify for browser tests (#378, @yamikuronue)
* Test: coveralls integration (#378, @yamikuronue)
* Docs: simplified language in the opening paragraph (#373, @yamikuronue)
2.4.5 / 2016-12-17
==================
* Fix: `navigator` undefined in Rhino (#376, @jochenberger)
* Fix: custom log function (#379, @hsiliev)
* Improvement: bit of cleanup + linting fixes (@thebigredgeek)
* Improvement: rm non-maintainted `dist/` dir (#375, @freewil)
* Docs: simplified language in the opening paragraph. (#373, @yamikuronue)
2.4.4 / 2016-12-14
==================
* Fix: work around debug being loaded in preload scripts for electron (#368, @paulcbetts)
2.4.3 / 2016-12-14
==================
* Fix: navigation.userAgent error for react native (#364, @escwald)
2.4.2 / 2016-12-14
==================
* Fix: browser colors (#367, @tootallnate)
* Misc: travis ci integration (@thebigredgeek)
* Misc: added linting and testing boilerplate with sanity check (@thebigredgeek)
2.4.1 / 2016-12-13
==================
* Fix: typo that broke the package (#356)
2.4.0 / 2016-12-13
==================
* Fix: bower.json references unbuilt src entry point (#342, @justmatt)
* Fix: revert "handle regex special characters" (@tootallnate)
* Feature: configurable util.inspect()`options for NodeJS (#327, @tootallnate)
* Feature: %O`(big O) pretty-prints objects (#322, @tootallnate)
* Improvement: allow colors in workers (#335, @botverse)
* Improvement: use same color for same namespace. (#338, @lchenay)
2.3.3 / 2016-11-09
==================
* Fix: Catch `JSON.stringify()` errors (#195, Jovan Alleyne)
* Fix: Returning `localStorage` saved values (#331, Levi Thomason)
* Improvement: Don't create an empty object when no `process` (Nathan Rajlich)
2.3.2 / 2016-11-09
==================
* Fix: be super-safe in index.js as well (@TooTallNate)
* Fix: should check whether process exists (Tom Newby)
2.3.1 / 2016-11-09
==================
* Fix: Added electron compatibility (#324, @paulcbetts)
* Improvement: Added performance optimizations (@tootallnate)
* Readme: Corrected PowerShell environment variable example (#252, @gimre)
* Misc: Removed yarn lock file from source control (#321, @fengmk2)
2.3.0 / 2016-11-07
==================
* Fix: Consistent placement of ms diff at end of output (#215, @gorangajic)
* Fix: Escaping of regex special characters in namespace strings (#250, @zacronos)
* Fix: Fixed bug causing crash on react-native (#282, @vkarpov15)
* Feature: Enabled ES6+ compatible import via default export (#212 @bucaran)
* Feature: Added %O formatter to reflect Chrome's console.log capability (#279, @oncletom)
* Package: Update "ms" to 0.7.2 (#315, @DevSide)
* Package: removed superfluous version property from bower.json (#207 @kkirsche)
* Readme: fix USE_COLORS to DEBUG_COLORS
* Readme: Doc fixes for format string sugar (#269, @mlucool)
* Readme: Updated docs for DEBUG_FD and DEBUG_COLORS environment variables (#232, @mattlyons0)
* Readme: doc fixes for PowerShell (#271 #243, @exoticknight @unreadable)
* Readme: better docs for browser support (#224, @matthewmueller)
* Tooling: Added yarn integration for development (#317, @thebigredgeek)
* Misc: Renamed History.md to CHANGELOG.md (@thebigredgeek)
* Misc: Added license file (#226 #274, @CantemoInternal @sdaitzman)
* Misc: Updated contributors (@thebigredgeek)
2.2.0 / 2015-05-09
==================
* package: update "ms" to v0.7.1 (#202, @dougwilson)
* README: add logging to file example (#193, @DanielOchoa)
* README: fixed a typo (#191, @amir-s)
* browser: expose `storage` (#190, @stephenmathieson)
* Makefile: add a `distclean` target (#189, @stephenmathieson)
2.1.3 / 2015-03-13
==================
* Updated stdout/stderr example (#186)
* Updated example/stdout.js to match debug current behaviour
* Renamed example/stderr.js to stdout.js
* Update Readme.md (#184)
* replace high intensity foreground color for bold (#182, #183)
2.1.2 / 2015-03-01
==================
* dist: recompile
* update "ms" to v0.7.0
* package: update "browserify" to v9.0.3
* component: fix "ms.js" repo location
* changed bower package name
* updated documentation about using debug in a browser
* fix: security error on safari (#167, #168, @yields)
2.1.1 / 2014-12-29
==================
* browser: use `typeof` to check for `console` existence
* browser: check for `console.log` truthiness (fix IE 8/9)
* browser: add support for Chrome apps
* Readme: added Windows usage remarks
* Add `bower.json` to properly support bower install
2.1.0 / 2014-10-15
==================
* node: implement `DEBUG_FD` env variable support
* package: update "browserify" to v6.1.0
* package: add "license" field to package.json (#135, @panuhorsmalahti)
2.0.0 / 2014-09-01
==================
* package: update "browserify" to v5.11.0
* node: use stderr rather than stdout for logging (#29, @stephenmathieson)
1.0.4 / 2014-07-15
==================
* dist: recompile
* example: remove `console.info()` log usage
* example: add "Content-Type" UTF-8 header to browser example
* browser: place %c marker after the space character
* browser: reset the "content" color via `color: inherit`
* browser: add colors support for Firefox >= v31
* debug: prefer an instance `log()` function over the global one (#119)
* Readme: update documentation about styled console logs for FF v31 (#116, @wryk)
1.0.3 / 2014-07-09
==================
* Add support for multiple wildcards in namespaces (#122, @seegno)
* browser: fix lint
1.0.2 / 2014-06-10
==================
* browser: update color palette (#113, @gscottolson)
* common: make console logging function configurable (#108, @timoxley)
* node: fix %o colors on old node <= 0.8.x
* Makefile: find node path using shell/which (#109, @timoxley)
1.0.1 / 2014-06-06
==================
* browser: use `removeItem()` to clear localStorage
* browser, node: don't set DEBUG if namespaces is undefined (#107, @leedm777)
* package: add "contributors" section
* node: fix comment typo
* README: list authors
1.0.0 / 2014-06-04
==================
* make ms diff be global, not be scope
* debug: ignore empty strings in enable()
* node: make DEBUG_COLORS able to disable coloring
* *: export the `colors` array
* npmignore: don't publish the `dist` dir
* Makefile: refactor to use browserify
* package: add "browserify" as a dev dependency
* Readme: add Web Inspector Colors section
* node: reset terminal color for the debug content
* node: map "%o" to `util.inspect()`
* browser: map "%j" to `JSON.stringify()`
* debug: add custom "formatters"
* debug: use "ms" module for humanizing the diff
* Readme: add "bash" syntax highlighting
* browser: add Firebug color support
* browser: add colors for WebKit browsers
* node: apply log to `console`
* rewrite: abstract common logic for Node & browsers
* add .jshintrc file
0.8.1 / 2014-04-14
==================
* package: re-add the "component" section
0.8.0 / 2014-03-30
==================
* add `enable()` method for nodejs. Closes #27
* change from stderr to stdout
* remove unnecessary index.js file
0.7.4 / 2013-11-13
==================
* remove "browserify" key from package.json (fixes something in browserify)
0.7.3 / 2013-10-30
==================
* fix: catch localStorage security error when cookies are blocked (Chrome)
* add debug(err) support. Closes #46
* add .browser prop to package.json. Closes #42
0.7.2 / 2013-02-06
==================
* fix package.json
* fix: Mobile Safari (private mode) is broken with debug
* fix: Use unicode to send escape character to shell instead of octal to work with strict mode javascript
0.7.1 / 2013-02-05
==================
* add repository URL to package.json
* add DEBUG_COLORED to force colored output
* add browserify support
* fix component. Closes #24
0.7.0 / 2012-05-04
==================
* Added .component to package.json
* Added debug.component.js build
0.6.0 / 2012-03-16
==================
* Added support for "-" prefix in DEBUG [Vinay Pulim]
* Added `.enabled` flag to the node version [TooTallNate]
0.5.0 / 2012-02-02
==================
* Added: humanize diffs. Closes #8
* Added `debug.disable()` to the CS variant
* Removed padding. Closes #10
* Fixed: persist client-side variant again. Closes #9
0.4.0 / 2012-02-01
==================
* Added browser variant support for older browsers [TooTallNate]
* Added `debug.enable('project:*')` to browser variant [TooTallNate]
* Added padding to diff (moved it to the right)
0.3.0 / 2012-01-26
==================
* Added millisecond diff when isatty, otherwise UTC string
0.2.0 / 2012-01-22
==================
* Added wildcard support
0.1.0 / 2011-12-02
==================
* Added: remove colors unless stderr isatty [TooTallNate]
0.0.1 / 2010-01-03
==================
* Initial release
+19
View File
@@ -0,0 +1,19 @@
(The MIT License)
Copyright (c) 2014 TJ Holowaychuk <tj@vision-media.ca>
Permission is hereby granted, free of charge, to any person obtaining a copy of this software
and associated documentation files (the 'Software'), to deal in the Software without restriction,
including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial
portions of the Software.
THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT
LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+50
View File
@@ -0,0 +1,50 @@
# get Makefile directory name: http://stackoverflow.com/a/5982798/376773
THIS_MAKEFILE_PATH:=$(word $(words $(MAKEFILE_LIST)),$(MAKEFILE_LIST))
THIS_DIR:=$(shell cd $(dir $(THIS_MAKEFILE_PATH));pwd)
# BIN directory
BIN := $(THIS_DIR)/node_modules/.bin
# Path
PATH := node_modules/.bin:$(PATH)
SHELL := /bin/bash
# applications
NODE ?= $(shell which node)
YARN ?= $(shell which yarn)
PKG ?= $(if $(YARN),$(YARN),$(NODE) $(shell which npm))
BROWSERIFY ?= $(NODE) $(BIN)/browserify
.FORCE:
install: node_modules
node_modules: package.json
@NODE_ENV= $(PKG) install
@touch node_modules
lint: .FORCE
eslint browser.js debug.js index.js node.js
test-node: .FORCE
istanbul cover node_modules/mocha/bin/_mocha -- test/**.js
test-browser: .FORCE
mkdir -p dist
@$(BROWSERIFY) \
--standalone debug \
. > dist/debug.js
karma start --single-run
rimraf dist
test: .FORCE
concurrently \
"make test-node" \
"make test-browser"
coveralls:
cat ./coverage/lcov.info | ./node_modules/coveralls/bin/coveralls.js
.PHONY: all install clean distclean
+312
View File
@@ -0,0 +1,312 @@
# debug
[![Build Status](https://travis-ci.org/visionmedia/debug.svg?branch=master)](https://travis-ci.org/visionmedia/debug) [![Coverage Status](https://coveralls.io/repos/github/visionmedia/debug/badge.svg?branch=master)](https://coveralls.io/github/visionmedia/debug?branch=master) [![Slack](https://visionmedia-community-slackin.now.sh/badge.svg)](https://visionmedia-community-slackin.now.sh/) [![OpenCollective](https://opencollective.com/debug/backers/badge.svg)](#backers)
[![OpenCollective](https://opencollective.com/debug/sponsors/badge.svg)](#sponsors)
A tiny node.js debugging utility modelled after node core's debugging technique.
**Discussion around the V3 API is under way [here](https://github.com/visionmedia/debug/issues/370)**
## Installation
```bash
$ npm install debug
```
## Usage
`debug` exposes a function; simply pass this function the name of your module, and it will return a decorated version of `console.error` for you to pass debug statements to. This will allow you to toggle the debug output for different parts of your module as well as the module as a whole.
Example _app.js_:
```js
var debug = require('debug')('http')
, http = require('http')
, name = 'My App';
// fake app
debug('booting %s', name);
http.createServer(function(req, res){
debug(req.method + ' ' + req.url);
res.end('hello\n');
}).listen(3000, function(){
debug('listening');
});
// fake worker of some kind
require('./worker');
```
Example _worker.js_:
```js
var debug = require('debug')('worker');
setInterval(function(){
debug('doing some work');
}, 1000);
```
The __DEBUG__ environment variable is then used to enable these based on space or comma-delimited names. Here are some examples:
![debug http and worker](http://f.cl.ly/items/18471z1H402O24072r1J/Screenshot.png)
![debug worker](http://f.cl.ly/items/1X413v1a3M0d3C2c1E0i/Screenshot.png)
#### Windows note
On Windows the environment variable is set using the `set` command.
```cmd
set DEBUG=*,-not_this
```
Note that PowerShell uses different syntax to set environment variables.
```cmd
$env:DEBUG = "*,-not_this"
```
Then, run the program to be debugged as usual.
## Millisecond diff
When actively developing an application it can be useful to see when the time spent between one `debug()` call and the next. Suppose for example you invoke `debug()` before requesting a resource, and after as well, the "+NNNms" will show you how much time was spent between calls.
![](http://f.cl.ly/items/2i3h1d3t121M2Z1A3Q0N/Screenshot.png)
When stdout is not a TTY, `Date#toUTCString()` is used, making it more useful for logging the debug information as shown below:
![](http://f.cl.ly/items/112H3i0e0o0P0a2Q2r11/Screenshot.png)
## Conventions
If you're using this in one or more of your libraries, you _should_ use the name of your library so that developers may toggle debugging as desired without guessing names. If you have more than one debuggers you _should_ prefix them with your library name and use ":" to separate features. For example "bodyParser" from Connect would then be "connect:bodyParser".
## Wildcards
The `*` character may be used as a wildcard. Suppose for example your library has debuggers named "connect:bodyParser", "connect:compress", "connect:session", instead of listing all three with `DEBUG=connect:bodyParser,connect:compress,connect:session`, you may simply do `DEBUG=connect:*`, or to run everything using this module simply use `DEBUG=*`.
You can also exclude specific debuggers by prefixing them with a "-" character. For example, `DEBUG=*,-connect:*` would include all debuggers except those starting with "connect:".
## Environment Variables
When running through Node.js, you can set a few environment variables that will
change the behavior of the debug logging:
| Name | Purpose |
|-----------|-------------------------------------------------|
| `DEBUG` | Enables/disables specific debugging namespaces. |
| `DEBUG_COLORS`| Whether or not to use colors in the debug output. |
| `DEBUG_DEPTH` | Object inspection depth. |
| `DEBUG_SHOW_HIDDEN` | Shows hidden properties on inspected objects. |
__Note:__ The environment variables beginning with `DEBUG_` end up being
converted into an Options object that gets used with `%o`/`%O` formatters.
See the Node.js documentation for
[`util.inspect()`](https://nodejs.org/api/util.html#util_util_inspect_object_options)
for the complete list.
## Formatters
Debug uses [printf-style](https://wikipedia.org/wiki/Printf_format_string) formatting. Below are the officially supported formatters:
| Formatter | Representation |
|-----------|----------------|
| `%O` | Pretty-print an Object on multiple lines. |
| `%o` | Pretty-print an Object all on a single line. |
| `%s` | String. |
| `%d` | Number (both integer and float). |
| `%j` | JSON. Replaced with the string '[Circular]' if the argument contains circular references. |
| `%%` | Single percent sign ('%'). This does not consume an argument. |
### Custom formatters
You can add custom formatters by extending the `debug.formatters` object. For example, if you wanted to add support for rendering a Buffer as hex with `%h`, you could do something like:
```js
const createDebug = require('debug')
createDebug.formatters.h = (v) => {
return v.toString('hex')
}
// …elsewhere
const debug = createDebug('foo')
debug('this is hex: %h', new Buffer('hello world'))
// foo this is hex: 68656c6c6f20776f726c6421 +0ms
```
## Browser support
You can build a browser-ready script using [browserify](https://github.com/substack/node-browserify),
or just use the [browserify-as-a-service](https://wzrd.in/) [build](https://wzrd.in/standalone/debug@latest),
if you don't want to build it yourself.
Debug's enable state is currently persisted by `localStorage`.
Consider the situation shown below where you have `worker:a` and `worker:b`,
and wish to debug both. You can enable this using `localStorage.debug`:
```js
localStorage.debug = 'worker:*'
```
And then refresh the page.
```js
a = debug('worker:a');
b = debug('worker:b');
setInterval(function(){
a('doing some work');
}, 1000);
setInterval(function(){
b('doing some work');
}, 1200);
```
#### Web Inspector Colors
Colors are also enabled on "Web Inspectors" that understand the `%c` formatting
option. These are WebKit web inspectors, Firefox ([since version
31](https://hacks.mozilla.org/2014/05/editable-box-model-multiple-selection-sublime-text-keys-much-more-firefox-developer-tools-episode-31/))
and the Firebug plugin for Firefox (any version).
Colored output looks something like:
![](https://cloud.githubusercontent.com/assets/71256/3139768/b98c5fd8-e8ef-11e3-862a-f7253b6f47c6.png)
## Output streams
By default `debug` will log to stderr, however this can be configured per-namespace by overriding the `log` method:
Example _stdout.js_:
```js
var debug = require('debug');
var error = debug('app:error');
// by default stderr is used
error('goes to stderr!');
var log = debug('app:log');
// set this namespace to log via console.log
log.log = console.log.bind(console); // don't forget to bind to console!
log('goes to stdout');
error('still goes to stderr!');
// set all output to go via console.info
// overrides all per-namespace log settings
debug.log = console.info.bind(console);
error('now goes to stdout via console.info');
log('still goes to stdout, but via console.info now');
```
## Authors
- TJ Holowaychuk
- Nathan Rajlich
- Andrew Rhyne
## Backers
Support us with a monthly donation and help us continue our activities. [[Become a backer](https://opencollective.com/debug#backer)]
<a href="https://opencollective.com/debug/backer/0/website" target="_blank"><img src="https://opencollective.com/debug/backer/0/avatar.svg"></a>
<a href="https://opencollective.com/debug/backer/1/website" target="_blank"><img src="https://opencollective.com/debug/backer/1/avatar.svg"></a>
<a href="https://opencollective.com/debug/backer/2/website" target="_blank"><img src="https://opencollective.com/debug/backer/2/avatar.svg"></a>
<a href="https://opencollective.com/debug/backer/3/website" target="_blank"><img src="https://opencollective.com/debug/backer/3/avatar.svg"></a>
<a href="https://opencollective.com/debug/backer/4/website" target="_blank"><img src="https://opencollective.com/debug/backer/4/avatar.svg"></a>
<a href="https://opencollective.com/debug/backer/5/website" target="_blank"><img src="https://opencollective.com/debug/backer/5/avatar.svg"></a>
<a href="https://opencollective.com/debug/backer/6/website" target="_blank"><img src="https://opencollective.com/debug/backer/6/avatar.svg"></a>
<a href="https://opencollective.com/debug/backer/7/website" target="_blank"><img src="https://opencollective.com/debug/backer/7/avatar.svg"></a>
<a href="https://opencollective.com/debug/backer/8/website" target="_blank"><img src="https://opencollective.com/debug/backer/8/avatar.svg"></a>
<a href="https://opencollective.com/debug/backer/9/website" target="_blank"><img src="https://opencollective.com/debug/backer/9/avatar.svg"></a>
<a href="https://opencollective.com/debug/backer/10/website" target="_blank"><img src="https://opencollective.com/debug/backer/10/avatar.svg"></a>
<a href="https://opencollective.com/debug/backer/11/website" target="_blank"><img src="https://opencollective.com/debug/backer/11/avatar.svg"></a>
<a href="https://opencollective.com/debug/backer/12/website" target="_blank"><img src="https://opencollective.com/debug/backer/12/avatar.svg"></a>
<a href="https://opencollective.com/debug/backer/13/website" target="_blank"><img src="https://opencollective.com/debug/backer/13/avatar.svg"></a>
<a href="https://opencollective.com/debug/backer/14/website" target="_blank"><img src="https://opencollective.com/debug/backer/14/avatar.svg"></a>
<a href="https://opencollective.com/debug/backer/15/website" target="_blank"><img src="https://opencollective.com/debug/backer/15/avatar.svg"></a>
<a href="https://opencollective.com/debug/backer/16/website" target="_blank"><img src="https://opencollective.com/debug/backer/16/avatar.svg"></a>
<a href="https://opencollective.com/debug/backer/17/website" target="_blank"><img src="https://opencollective.com/debug/backer/17/avatar.svg"></a>
<a href="https://opencollective.com/debug/backer/18/website" target="_blank"><img src="https://opencollective.com/debug/backer/18/avatar.svg"></a>
<a href="https://opencollective.com/debug/backer/19/website" target="_blank"><img src="https://opencollective.com/debug/backer/19/avatar.svg"></a>
<a href="https://opencollective.com/debug/backer/20/website" target="_blank"><img src="https://opencollective.com/debug/backer/20/avatar.svg"></a>
<a href="https://opencollective.com/debug/backer/21/website" target="_blank"><img src="https://opencollective.com/debug/backer/21/avatar.svg"></a>
<a href="https://opencollective.com/debug/backer/22/website" target="_blank"><img src="https://opencollective.com/debug/backer/22/avatar.svg"></a>
<a href="https://opencollective.com/debug/backer/23/website" target="_blank"><img src="https://opencollective.com/debug/backer/23/avatar.svg"></a>
<a href="https://opencollective.com/debug/backer/24/website" target="_blank"><img src="https://opencollective.com/debug/backer/24/avatar.svg"></a>
<a href="https://opencollective.com/debug/backer/25/website" target="_blank"><img src="https://opencollective.com/debug/backer/25/avatar.svg"></a>
<a href="https://opencollective.com/debug/backer/26/website" target="_blank"><img src="https://opencollective.com/debug/backer/26/avatar.svg"></a>
<a href="https://opencollective.com/debug/backer/27/website" target="_blank"><img src="https://opencollective.com/debug/backer/27/avatar.svg"></a>
<a href="https://opencollective.com/debug/backer/28/website" target="_blank"><img src="https://opencollective.com/debug/backer/28/avatar.svg"></a>
<a href="https://opencollective.com/debug/backer/29/website" target="_blank"><img src="https://opencollective.com/debug/backer/29/avatar.svg"></a>
## Sponsors
Become a sponsor and get your logo on our README on Github with a link to your site. [[Become a sponsor](https://opencollective.com/debug#sponsor)]
<a href="https://opencollective.com/debug/sponsor/0/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/0/avatar.svg"></a>
<a href="https://opencollective.com/debug/sponsor/1/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/1/avatar.svg"></a>
<a href="https://opencollective.com/debug/sponsor/2/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/2/avatar.svg"></a>
<a href="https://opencollective.com/debug/sponsor/3/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/3/avatar.svg"></a>
<a href="https://opencollective.com/debug/sponsor/4/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/4/avatar.svg"></a>
<a href="https://opencollective.com/debug/sponsor/5/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/5/avatar.svg"></a>
<a href="https://opencollective.com/debug/sponsor/6/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/6/avatar.svg"></a>
<a href="https://opencollective.com/debug/sponsor/7/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/7/avatar.svg"></a>
<a href="https://opencollective.com/debug/sponsor/8/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/8/avatar.svg"></a>
<a href="https://opencollective.com/debug/sponsor/9/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/9/avatar.svg"></a>
<a href="https://opencollective.com/debug/sponsor/10/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/10/avatar.svg"></a>
<a href="https://opencollective.com/debug/sponsor/11/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/11/avatar.svg"></a>
<a href="https://opencollective.com/debug/sponsor/12/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/12/avatar.svg"></a>
<a href="https://opencollective.com/debug/sponsor/13/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/13/avatar.svg"></a>
<a href="https://opencollective.com/debug/sponsor/14/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/14/avatar.svg"></a>
<a href="https://opencollective.com/debug/sponsor/15/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/15/avatar.svg"></a>
<a href="https://opencollective.com/debug/sponsor/16/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/16/avatar.svg"></a>
<a href="https://opencollective.com/debug/sponsor/17/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/17/avatar.svg"></a>
<a href="https://opencollective.com/debug/sponsor/18/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/18/avatar.svg"></a>
<a href="https://opencollective.com/debug/sponsor/19/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/19/avatar.svg"></a>
<a href="https://opencollective.com/debug/sponsor/20/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/20/avatar.svg"></a>
<a href="https://opencollective.com/debug/sponsor/21/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/21/avatar.svg"></a>
<a href="https://opencollective.com/debug/sponsor/22/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/22/avatar.svg"></a>
<a href="https://opencollective.com/debug/sponsor/23/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/23/avatar.svg"></a>
<a href="https://opencollective.com/debug/sponsor/24/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/24/avatar.svg"></a>
<a href="https://opencollective.com/debug/sponsor/25/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/25/avatar.svg"></a>
<a href="https://opencollective.com/debug/sponsor/26/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/26/avatar.svg"></a>
<a href="https://opencollective.com/debug/sponsor/27/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/27/avatar.svg"></a>
<a href="https://opencollective.com/debug/sponsor/28/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/28/avatar.svg"></a>
<a href="https://opencollective.com/debug/sponsor/29/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/29/avatar.svg"></a>
## License
(The MIT License)
Copyright (c) 2014-2016 TJ Holowaychuk &lt;tj@vision-media.ca&gt;
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
'Software'), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+19
View File
@@ -0,0 +1,19 @@
{
"name": "debug",
"repo": "visionmedia/debug",
"description": "small debugging utility",
"version": "2.6.9",
"keywords": [
"debug",
"log",
"debugger"
],
"main": "src/browser.js",
"scripts": [
"src/browser.js",
"src/debug.js"
],
"dependencies": {
"rauchg/ms.js": "0.7.1"
}
}
+70
View File
@@ -0,0 +1,70 @@
// Karma configuration
// Generated on Fri Dec 16 2016 13:09:51 GMT+0000 (UTC)
module.exports = function(config) {
config.set({
// base path that will be used to resolve all patterns (eg. files, exclude)
basePath: '',
// frameworks to use
// available frameworks: https://npmjs.org/browse/keyword/karma-adapter
frameworks: ['mocha', 'chai', 'sinon'],
// list of files / patterns to load in the browser
files: [
'dist/debug.js',
'test/*spec.js'
],
// list of files to exclude
exclude: [
'src/node.js'
],
// preprocess matching files before serving them to the browser
// available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
preprocessors: {
},
// test results reporter to use
// possible values: 'dots', 'progress'
// available reporters: https://npmjs.org/browse/keyword/karma-reporter
reporters: ['progress'],
// web server port
port: 9876,
// enable / disable colors in the output (reporters and logs)
colors: true,
// level of logging
// possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
logLevel: config.LOG_INFO,
// enable / disable watching file and executing tests whenever any file changes
autoWatch: true,
// start these browsers
// available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
browsers: ['PhantomJS'],
// Continuous Integration mode
// if true, Karma captures browsers, runs the tests and exits
singleRun: false,
// Concurrency level
// how many browser should be started simultaneous
concurrency: Infinity
})
}
+1
View File
@@ -0,0 +1 @@
module.exports = require('./src/node');
+49
View File
@@ -0,0 +1,49 @@
{
"name": "debug",
"version": "2.6.9",
"repository": {
"type": "git",
"url": "git://github.com/visionmedia/debug.git"
},
"description": "small debugging utility",
"keywords": [
"debug",
"log",
"debugger"
],
"author": "TJ Holowaychuk <tj@vision-media.ca>",
"contributors": [
"Nathan Rajlich <nathan@tootallnate.net> (http://n8.io)",
"Andrew Rhyne <rhyneandrew@gmail.com>"
],
"license": "MIT",
"dependencies": {
"ms": "2.0.0"
},
"devDependencies": {
"browserify": "9.0.3",
"chai": "^3.5.0",
"concurrently": "^3.1.0",
"coveralls": "^2.11.15",
"eslint": "^3.12.1",
"istanbul": "^0.4.5",
"karma": "^1.3.0",
"karma-chai": "^0.1.0",
"karma-mocha": "^1.3.0",
"karma-phantomjs-launcher": "^1.0.2",
"karma-sinon": "^1.0.5",
"mocha": "^3.2.0",
"mocha-lcov-reporter": "^1.2.0",
"rimraf": "^2.5.4",
"sinon": "^1.17.6",
"sinon-chai": "^2.8.0"
},
"main": "./src/index.js",
"browser": "./src/browser.js",
"component": {
"scripts": {
"debug/index.js": "browser.js",
"debug/debug.js": "debug.js"
}
}
}
+185
View File
@@ -0,0 +1,185 @@
/**
* This is the web browser implementation of `debug()`.
*
* Expose `debug()` as the module.
*/
exports = module.exports = require('./debug');
exports.log = log;
exports.formatArgs = formatArgs;
exports.save = save;
exports.load = load;
exports.useColors = useColors;
exports.storage = 'undefined' != typeof chrome
&& 'undefined' != typeof chrome.storage
? chrome.storage.local
: localstorage();
/**
* Colors.
*/
exports.colors = [
'lightseagreen',
'forestgreen',
'goldenrod',
'dodgerblue',
'darkorchid',
'crimson'
];
/**
* Currently only WebKit-based Web Inspectors, Firefox >= v31,
* and the Firebug extension (any Firefox version) are known
* to support "%c" CSS customizations.
*
* TODO: add a `localStorage` variable to explicitly enable/disable colors
*/
function useColors() {
// NB: In an Electron preload script, document will be defined but not fully
// initialized. Since we know we're in Chrome, we'll just detect this case
// explicitly
if (typeof window !== 'undefined' && window.process && window.process.type === 'renderer') {
return true;
}
// is webkit? http://stackoverflow.com/a/16459606/376773
// document is undefined in react-native: https://github.com/facebook/react-native/pull/1632
return (typeof document !== 'undefined' && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance) ||
// is firebug? http://stackoverflow.com/a/398120/376773
(typeof window !== 'undefined' && window.console && (window.console.firebug || (window.console.exception && window.console.table))) ||
// is firefox >= v31?
// https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages
(typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31) ||
// double check webkit in userAgent just in case we are in a worker
(typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/));
}
/**
* Map %j to `JSON.stringify()`, since no Web Inspectors do that by default.
*/
exports.formatters.j = function(v) {
try {
return JSON.stringify(v);
} catch (err) {
return '[UnexpectedJSONParseError]: ' + err.message;
}
};
/**
* Colorize log arguments if enabled.
*
* @api public
*/
function formatArgs(args) {
var useColors = this.useColors;
args[0] = (useColors ? '%c' : '')
+ this.namespace
+ (useColors ? ' %c' : ' ')
+ args[0]
+ (useColors ? '%c ' : ' ')
+ '+' + exports.humanize(this.diff);
if (!useColors) return;
var c = 'color: ' + this.color;
args.splice(1, 0, c, 'color: inherit')
// the final "%c" is somewhat tricky, because there could be other
// arguments passed either before or after the %c, so we need to
// figure out the correct index to insert the CSS into
var index = 0;
var lastC = 0;
args[0].replace(/%[a-zA-Z%]/g, function(match) {
if ('%%' === match) return;
index++;
if ('%c' === match) {
// we only are interested in the *last* %c
// (the user may have provided their own)
lastC = index;
}
});
args.splice(lastC, 0, c);
}
/**
* Invokes `console.log()` when available.
* No-op when `console.log` is not a "function".
*
* @api public
*/
function log() {
// this hackery is required for IE8/9, where
// the `console.log` function doesn't have 'apply'
return 'object' === typeof console
&& console.log
&& Function.prototype.apply.call(console.log, console, arguments);
}
/**
* Save `namespaces`.
*
* @param {String} namespaces
* @api private
*/
function save(namespaces) {
try {
if (null == namespaces) {
exports.storage.removeItem('debug');
} else {
exports.storage.debug = namespaces;
}
} catch(e) {}
}
/**
* Load `namespaces`.
*
* @return {String} returns the previously persisted debug modes
* @api private
*/
function load() {
var r;
try {
r = exports.storage.debug;
} catch(e) {}
// If debug isn't set in LS, and we're in Electron, try to load $DEBUG
if (!r && typeof process !== 'undefined' && 'env' in process) {
r = process.env.DEBUG;
}
return r;
}
/**
* Enable namespaces listed in `localStorage.debug` initially.
*/
exports.enable(load());
/**
* Localstorage attempts to return the localstorage.
*
* This is necessary because safari throws
* when a user disables cookies/localstorage
* and you attempt to access it.
*
* @return {LocalStorage}
* @api private
*/
function localstorage() {
try {
return window.localStorage;
} catch (e) {}
}
+202
View File
@@ -0,0 +1,202 @@
/**
* This is the common logic for both the Node.js and web browser
* implementations of `debug()`.
*
* Expose `debug()` as the module.
*/
exports = module.exports = createDebug.debug = createDebug['default'] = createDebug;
exports.coerce = coerce;
exports.disable = disable;
exports.enable = enable;
exports.enabled = enabled;
exports.humanize = require('ms');
/**
* The currently active debug mode names, and names to skip.
*/
exports.names = [];
exports.skips = [];
/**
* Map of special "%n" handling functions, for the debug "format" argument.
*
* Valid key names are a single, lower or upper-case letter, i.e. "n" and "N".
*/
exports.formatters = {};
/**
* Previous log timestamp.
*/
var prevTime;
/**
* Select a color.
* @param {String} namespace
* @return {Number}
* @api private
*/
function selectColor(namespace) {
var hash = 0, i;
for (i in namespace) {
hash = ((hash << 5) - hash) + namespace.charCodeAt(i);
hash |= 0; // Convert to 32bit integer
}
return exports.colors[Math.abs(hash) % exports.colors.length];
}
/**
* Create a debugger with the given `namespace`.
*
* @param {String} namespace
* @return {Function}
* @api public
*/
function createDebug(namespace) {
function debug() {
// disabled?
if (!debug.enabled) return;
var self = debug;
// set `diff` timestamp
var curr = +new Date();
var ms = curr - (prevTime || curr);
self.diff = ms;
self.prev = prevTime;
self.curr = curr;
prevTime = curr;
// turn the `arguments` into a proper Array
var args = new Array(arguments.length);
for (var i = 0; i < args.length; i++) {
args[i] = arguments[i];
}
args[0] = exports.coerce(args[0]);
if ('string' !== typeof args[0]) {
// anything else let's inspect with %O
args.unshift('%O');
}
// apply any `formatters` transformations
var index = 0;
args[0] = args[0].replace(/%([a-zA-Z%])/g, function(match, format) {
// if we encounter an escaped % then don't increase the array index
if (match === '%%') return match;
index++;
var formatter = exports.formatters[format];
if ('function' === typeof formatter) {
var val = args[index];
match = formatter.call(self, val);
// now we need to remove `args[index]` since it's inlined in the `format`
args.splice(index, 1);
index--;
}
return match;
});
// apply env-specific formatting (colors, etc.)
exports.formatArgs.call(self, args);
var logFn = debug.log || exports.log || console.log.bind(console);
logFn.apply(self, args);
}
debug.namespace = namespace;
debug.enabled = exports.enabled(namespace);
debug.useColors = exports.useColors();
debug.color = selectColor(namespace);
// env-specific initialization logic for debug instances
if ('function' === typeof exports.init) {
exports.init(debug);
}
return debug;
}
/**
* Enables a debug mode by namespaces. This can include modes
* separated by a colon and wildcards.
*
* @param {String} namespaces
* @api public
*/
function enable(namespaces) {
exports.save(namespaces);
exports.names = [];
exports.skips = [];
var split = (typeof namespaces === 'string' ? namespaces : '').split(/[\s,]+/);
var len = split.length;
for (var i = 0; i < len; i++) {
if (!split[i]) continue; // ignore empty strings
namespaces = split[i].replace(/\*/g, '.*?');
if (namespaces[0] === '-') {
exports.skips.push(new RegExp('^' + namespaces.substr(1) + '$'));
} else {
exports.names.push(new RegExp('^' + namespaces + '$'));
}
}
}
/**
* Disable debug output.
*
* @api public
*/
function disable() {
exports.enable('');
}
/**
* Returns true if the given mode name is enabled, false otherwise.
*
* @param {String} name
* @return {Boolean}
* @api public
*/
function enabled(name) {
var i, len;
for (i = 0, len = exports.skips.length; i < len; i++) {
if (exports.skips[i].test(name)) {
return false;
}
}
for (i = 0, len = exports.names.length; i < len; i++) {
if (exports.names[i].test(name)) {
return true;
}
}
return false;
}
/**
* Coerce `val`.
*
* @param {Mixed} val
* @return {Mixed}
* @api private
*/
function coerce(val) {
if (val instanceof Error) return val.stack || val.message;
return val;
}
+10
View File
@@ -0,0 +1,10 @@
/**
* Detect Electron renderer process, which is node, but we should
* treat as a browser.
*/
if (typeof process !== 'undefined' && process.type === 'renderer') {
module.exports = require('./browser.js');
} else {
module.exports = require('./node.js');
}
+15
View File
@@ -0,0 +1,15 @@
module.exports = inspectorLog;
// black hole
const nullStream = new (require('stream').Writable)();
nullStream._write = () => {};
/**
* Outputs a `console.log()` to the Node.js Inspector console *only*.
*/
function inspectorLog() {
const stdout = console._stdout;
console._stdout = nullStream;
console.log.apply(console, arguments);
console._stdout = stdout;
}
+248
View File
@@ -0,0 +1,248 @@
/**
* Module dependencies.
*/
var tty = require('tty');
var util = require('util');
/**
* This is the Node.js implementation of `debug()`.
*
* Expose `debug()` as the module.
*/
exports = module.exports = require('./debug');
exports.init = init;
exports.log = log;
exports.formatArgs = formatArgs;
exports.save = save;
exports.load = load;
exports.useColors = useColors;
/**
* Colors.
*/
exports.colors = [6, 2, 3, 4, 5, 1];
/**
* Build up the default `inspectOpts` object from the environment variables.
*
* $ DEBUG_COLORS=no DEBUG_DEPTH=10 DEBUG_SHOW_HIDDEN=enabled node script.js
*/
exports.inspectOpts = Object.keys(process.env).filter(function (key) {
return /^debug_/i.test(key);
}).reduce(function (obj, key) {
// camel-case
var prop = key
.substring(6)
.toLowerCase()
.replace(/_([a-z])/g, function (_, k) { return k.toUpperCase() });
// coerce string value into JS value
var val = process.env[key];
if (/^(yes|on|true|enabled)$/i.test(val)) val = true;
else if (/^(no|off|false|disabled)$/i.test(val)) val = false;
else if (val === 'null') val = null;
else val = Number(val);
obj[prop] = val;
return obj;
}, {});
/**
* The file descriptor to write the `debug()` calls to.
* Set the `DEBUG_FD` env variable to override with another value. i.e.:
*
* $ DEBUG_FD=3 node script.js 3>debug.log
*/
var fd = parseInt(process.env.DEBUG_FD, 10) || 2;
if (1 !== fd && 2 !== fd) {
util.deprecate(function(){}, 'except for stderr(2) and stdout(1), any other usage of DEBUG_FD is deprecated. Override debug.log if you want to use a different log function (https://git.io/debug_fd)')()
}
var stream = 1 === fd ? process.stdout :
2 === fd ? process.stderr :
createWritableStdioStream(fd);
/**
* Is stdout a TTY? Colored output is enabled when `true`.
*/
function useColors() {
return 'colors' in exports.inspectOpts
? Boolean(exports.inspectOpts.colors)
: tty.isatty(fd);
}
/**
* Map %o to `util.inspect()`, all on a single line.
*/
exports.formatters.o = function(v) {
this.inspectOpts.colors = this.useColors;
return util.inspect(v, this.inspectOpts)
.split('\n').map(function(str) {
return str.trim()
}).join(' ');
};
/**
* Map %o to `util.inspect()`, allowing multiple lines if needed.
*/
exports.formatters.O = function(v) {
this.inspectOpts.colors = this.useColors;
return util.inspect(v, this.inspectOpts);
};
/**
* Adds ANSI color escape codes if enabled.
*
* @api public
*/
function formatArgs(args) {
var name = this.namespace;
var useColors = this.useColors;
if (useColors) {
var c = this.color;
var prefix = ' \u001b[3' + c + ';1m' + name + ' ' + '\u001b[0m';
args[0] = prefix + args[0].split('\n').join('\n' + prefix);
args.push('\u001b[3' + c + 'm+' + exports.humanize(this.diff) + '\u001b[0m');
} else {
args[0] = new Date().toUTCString()
+ ' ' + name + ' ' + args[0];
}
}
/**
* Invokes `util.format()` with the specified arguments and writes to `stream`.
*/
function log() {
return stream.write(util.format.apply(util, arguments) + '\n');
}
/**
* Save `namespaces`.
*
* @param {String} namespaces
* @api private
*/
function save(namespaces) {
if (null == namespaces) {
// If you set a process.env field to null or undefined, it gets cast to the
// string 'null' or 'undefined'. Just delete instead.
delete process.env.DEBUG;
} else {
process.env.DEBUG = namespaces;
}
}
/**
* Load `namespaces`.
*
* @return {String} returns the previously persisted debug modes
* @api private
*/
function load() {
return process.env.DEBUG;
}
/**
* Copied from `node/src/node.js`.
*
* XXX: It's lame that node doesn't expose this API out-of-the-box. It also
* relies on the undocumented `tty_wrap.guessHandleType()` which is also lame.
*/
function createWritableStdioStream (fd) {
var stream;
var tty_wrap = process.binding('tty_wrap');
// Note stream._type is used for test-module-load-list.js
switch (tty_wrap.guessHandleType(fd)) {
case 'TTY':
stream = new tty.WriteStream(fd);
stream._type = 'tty';
// Hack to have stream not keep the event loop alive.
// See https://github.com/joyent/node/issues/1726
if (stream._handle && stream._handle.unref) {
stream._handle.unref();
}
break;
case 'FILE':
var fs = require('fs');
stream = new fs.SyncWriteStream(fd, { autoClose: false });
stream._type = 'fs';
break;
case 'PIPE':
case 'TCP':
var net = require('net');
stream = new net.Socket({
fd: fd,
readable: false,
writable: true
});
// FIXME Should probably have an option in net.Socket to create a
// stream from an existing fd which is writable only. But for now
// we'll just add this hack and set the `readable` member to false.
// Test: ./node test/fixtures/echo.js < /etc/passwd
stream.readable = false;
stream.read = null;
stream._type = 'pipe';
// FIXME Hack to have stream not keep the event loop alive.
// See https://github.com/joyent/node/issues/1726
if (stream._handle && stream._handle.unref) {
stream._handle.unref();
}
break;
default:
// Probably an error on in uv_guess_handle()
throw new Error('Implement me. Unknown stream file type!');
}
// For supporting legacy API we put the FD here.
stream.fd = fd;
stream._isStdio = true;
return stream;
}
/**
* Init logic for `debug` instances.
*
* Create a new `inspectOpts` object in case `useColors` is set
* differently for a particular `debug` instance.
*/
function init (debug) {
debug.inspectOpts = {};
var keys = Object.keys(exports.inspectOpts);
for (var i = 0; i < keys.length; i++) {
debug.inspectOpts[keys[i]] = exports.inspectOpts[keys[i]];
}
}
/**
* Enable namespaces listed in `process.env.DEBUG` initially.
*/
exports.enable(load());
+152
View File
@@ -0,0 +1,152 @@
/**
* Helpers.
*/
var s = 1000;
var m = s * 60;
var h = m * 60;
var d = h * 24;
var y = d * 365.25;
/**
* Parse or format the given `val`.
*
* Options:
*
* - `long` verbose formatting [false]
*
* @param {String|Number} val
* @param {Object} [options]
* @throws {Error} throw an error if val is not a non-empty string or a number
* @return {String|Number}
* @api public
*/
module.exports = function(val, options) {
options = options || {};
var type = typeof val;
if (type === 'string' && val.length > 0) {
return parse(val);
} else if (type === 'number' && isNaN(val) === false) {
return options.long ? fmtLong(val) : fmtShort(val);
}
throw new Error(
'val is not a non-empty string or a valid number. val=' +
JSON.stringify(val)
);
};
/**
* Parse the given `str` and return milliseconds.
*
* @param {String} str
* @return {Number}
* @api private
*/
function parse(str) {
str = String(str);
if (str.length > 100) {
return;
}
var match = /^((?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|years?|yrs?|y)?$/i.exec(
str
);
if (!match) {
return;
}
var n = parseFloat(match[1]);
var type = (match[2] || 'ms').toLowerCase();
switch (type) {
case 'years':
case 'year':
case 'yrs':
case 'yr':
case 'y':
return n * y;
case 'days':
case 'day':
case 'd':
return n * d;
case 'hours':
case 'hour':
case 'hrs':
case 'hr':
case 'h':
return n * h;
case 'minutes':
case 'minute':
case 'mins':
case 'min':
case 'm':
return n * m;
case 'seconds':
case 'second':
case 'secs':
case 'sec':
case 's':
return n * s;
case 'milliseconds':
case 'millisecond':
case 'msecs':
case 'msec':
case 'ms':
return n;
default:
return undefined;
}
}
/**
* Short format for `ms`.
*
* @param {Number} ms
* @return {String}
* @api private
*/
function fmtShort(ms) {
if (ms >= d) {
return Math.round(ms / d) + 'd';
}
if (ms >= h) {
return Math.round(ms / h) + 'h';
}
if (ms >= m) {
return Math.round(ms / m) + 'm';
}
if (ms >= s) {
return Math.round(ms / s) + 's';
}
return ms + 'ms';
}
/**
* Long format for `ms`.
*
* @param {Number} ms
* @return {String}
* @api private
*/
function fmtLong(ms) {
return plural(ms, d, 'day') ||
plural(ms, h, 'hour') ||
plural(ms, m, 'minute') ||
plural(ms, s, 'second') ||
ms + ' ms';
}
/**
* Pluralization helper.
*/
function plural(ms, n, name) {
if (ms < n) {
return;
}
if (ms < n * 1.5) {
return Math.floor(ms / n) + ' ' + name;
}
return Math.ceil(ms / n) + ' ' + name + 's';
}
+21
View File
@@ -0,0 +1,21 @@
The MIT License (MIT)
Copyright (c) 2016 Zeit, Inc.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
+37
View File
@@ -0,0 +1,37 @@
{
"name": "ms",
"version": "2.0.0",
"description": "Tiny milisecond conversion utility",
"repository": "zeit/ms",
"main": "./index",
"files": [
"index.js"
],
"scripts": {
"precommit": "lint-staged",
"lint": "eslint lib/* bin/*",
"test": "mocha tests.js"
},
"eslintConfig": {
"extends": "eslint:recommended",
"env": {
"node": true,
"es6": true
}
},
"lint-staged": {
"*.js": [
"npm run lint",
"prettier --single-quote --write",
"git add"
]
},
"license": "MIT",
"devDependencies": {
"eslint": "3.19.0",
"expect.js": "0.3.1",
"husky": "0.13.3",
"lint-staged": "3.4.1",
"mocha": "3.4.1"
}
}
+51
View File
@@ -0,0 +1,51 @@
# ms
[![Build Status](https://travis-ci.org/zeit/ms.svg?branch=master)](https://travis-ci.org/zeit/ms)
[![Slack Channel](http://zeit-slackin.now.sh/badge.svg)](https://zeit.chat/)
Use this package to easily convert various time formats to milliseconds.
## Examples
```js
ms('2 days') // 172800000
ms('1d') // 86400000
ms('10h') // 36000000
ms('2.5 hrs') // 9000000
ms('2h') // 7200000
ms('1m') // 60000
ms('5s') // 5000
ms('1y') // 31557600000
ms('100') // 100
```
### Convert from milliseconds
```js
ms(60000) // "1m"
ms(2 * 60000) // "2m"
ms(ms('10 hours')) // "10h"
```
### Time format written-out
```js
ms(60000, { long: true }) // "1 minute"
ms(2 * 60000, { long: true }) // "2 minutes"
ms(ms('10 hours'), { long: true }) // "10 hours"
```
## Features
- Works both in [node](https://nodejs.org) and in the browser.
- If a number is supplied to `ms`, a string with a unit is returned.
- If a string that contains the number is supplied, it returns it as a number (e.g.: it returns `100` for `'100'`).
- If you pass a string with a number and a valid unit, the number of equivalent ms is returned.
## Caught a bug?
1. [Fork](https://help.github.com/articles/fork-a-repo/) this repository to your own GitHub account and then [clone](https://help.github.com/articles/cloning-a-repository/) it to your local device
2. Link the package to the global module directory: `npm link`
3. Within the module you want to test your local development instance of ms, just link it to the dependencies: `npm link ms`. Instead of the default one from npm, node will now use your clone of ms!
As always, you can run the tests using: `npm test`
+64
View File
@@ -0,0 +1,64 @@
{
"name": "adbkit",
"version": "2.11.1",
"description": "A pure Node.js client for the Android Debug Bridge.",
"keywords": [
"adb",
"adbkit",
"android",
"logcat",
"monkey"
],
"bin": {
"adbkit": "./bin/adbkit"
},
"bugs": {
"url": "https://github.com/openstf/adbkit/issues"
},
"license": "Apache-2.0",
"author": {
"name": "The OpenSTF Project",
"email": "contact@openstf.io",
"url": "https://openstf.io"
},
"main": "./index",
"repository": {
"type": "git",
"url": "https://github.com/openstf/adbkit.git"
},
"scripts": {
"postpublish": "grunt clean",
"prepublish": "grunt test coffee",
"test": "grunt test"
},
"dependencies": {
"adbkit-logcat": "^1.1.0",
"adbkit-monkey": "~1.0.1",
"bluebird": "~2.9.24",
"commander": "^2.3.0",
"debug": "~2.6.3",
"node-forge": "^0.7.1",
"split": "~0.3.3"
},
"devDependencies": {
"bench": "~0.3.5",
"chai": "~2.2.0",
"coffee-script": "~1.9.1",
"grunt": "~0.4.5",
"grunt-cli": "~0.1.13",
"grunt-coffeelint": "0.0.13",
"grunt-contrib-clean": "~0.6.0",
"grunt-contrib-coffee": "~0.13.0",
"grunt-contrib-watch": "~0.6.1",
"grunt-exec": "~0.4.3",
"grunt-jsonlint": "~1.0.4",
"grunt-notify": "~0.4.1",
"mocha": "~2.2.1",
"sinon": "~1.14.1",
"sinon-chai": "~2.7.0",
"coffeelint": "~1.9.3"
},
"engines": {
"node": ">= 0.10.4"
}
}