aboutsummaryrefslogtreecommitdiffstats
path: root/app
diff options
context:
space:
mode:
Diffstat (limited to 'app')
-rw-r--r--app/scripts/background.js112
-rw-r--r--app/scripts/chromereload.js2071
-rw-r--r--app/scripts/contentscript.js10
-rw-r--r--app/scripts/inpage.js11
-rw-r--r--app/scripts/lib/auto-faucet.js4
-rw-r--r--app/scripts/lib/auto-reload.js15
-rw-r--r--app/scripts/lib/config-manager.js115
-rw-r--r--app/scripts/lib/ensnare.js10
-rw-r--r--app/scripts/lib/id-management.js41
-rw-r--r--app/scripts/lib/idStore.js99
-rw-r--r--app/scripts/lib/inpage-provider.js36
-rw-r--r--app/scripts/lib/local-message-stream.js19
-rw-r--r--app/scripts/lib/message-manager.js20
-rw-r--r--app/scripts/lib/notifications.js41
-rw-r--r--app/scripts/lib/obj-multiplex.js13
-rw-r--r--app/scripts/lib/port-stream.js15
-rw-r--r--app/scripts/lib/remote-store.js34
-rw-r--r--app/scripts/lib/stream-utils.js17
-rw-r--r--app/scripts/migrations/002.js4
-rw-r--r--app/scripts/migrations/003.js4
-rw-r--r--app/scripts/migrations/004.js16
-rw-r--r--app/scripts/popup.js19
22 files changed, 1330 insertions, 1396 deletions
diff --git a/app/scripts/background.js b/app/scripts/background.js
index 66108c251..6934e9d3e 100644
--- a/app/scripts/background.js
+++ b/app/scripts/background.js
@@ -1,11 +1,9 @@
const urlUtil = require('url')
const Dnode = require('dnode')
const eos = require('end-of-stream')
-const combineStreams = require('pumpify')
const extend = require('xtend')
const EthStore = require('eth-store')
const MetaMaskProvider = require('web3-provider-engine/zero.js')
-const ObjectMultiplex = require('./lib/obj-multiplex')
const PortStream = require('./lib/port-stream.js')
const IdentityStore = require('./lib/idStore')
const createUnlockRequestNotification = require('./lib/notifications.js').createUnlockRequestNotification
@@ -22,7 +20,7 @@ const Web3 = require('web3')
//
chrome.runtime.onConnect.addListener(connectRemote)
-function connectRemote(remotePort){
+function connectRemote (remotePort) {
var isMetaMaskInternalProcess = (remotePort.name === 'popup')
var portStream = new PortStream(remotePort)
if (isMetaMaskInternalProcess) {
@@ -35,7 +33,7 @@ function connectRemote(remotePort){
}
}
-function setupUntrustedCommunication(connectionStream, originDomain){
+function setupUntrustedCommunication (connectionStream, originDomain) {
// setup multiplexing
var mx = setupMultiplex(connectionStream)
// connect features
@@ -43,7 +41,7 @@ function setupUntrustedCommunication(connectionStream, originDomain){
setupPublicConfig(mx.createStream('publicConfig'))
}
-function setupTrustedCommunication(connectionStream, originDomain){
+function setupTrustedCommunication (connectionStream, originDomain) {
// setup multiplexing
var mx = setupMultiplex(connectionStream)
// connect features
@@ -55,13 +53,12 @@ function setupTrustedCommunication(connectionStream, originDomain){
// state and network
//
-var providerConfig = configManager.getProvider()
var idStore = new IdentityStore()
var providerOpts = {
rpcUrl: configManager.getCurrentRpcAddress(),
// account mgmt
- getAccounts: function(cb){
+ getAccounts: function (cb) {
var selectedAddress = idStore.getSelectedAddress()
var result = selectedAddress ? [selectedAddress] : []
cb(null, result)
@@ -79,8 +76,8 @@ idStore.web3 = web3
idStore.getNetwork()
// log new blocks
-provider.on('block', function(block){
- console.log('BLOCK CHANGED:', '#'+block.number.toString('hex'), '0x'+block.hash.toString('hex'))
+provider.on('block', function (block) {
+ console.log('BLOCK CHANGED:', '#' + block.number.toString('hex'), '0x' + block.hash.toString('hex'))
// Check network when restoring connectivity:
if (idStore._currentState.network === 'loading') {
@@ -93,7 +90,7 @@ provider.on('error', idStore.getNetwork.bind(idStore))
var ethStore = new EthStore(provider)
idStore.setStore(ethStore)
-function getState(){
+function getState () {
var state = extend(
ethStore.getState(),
idStore.getState(),
@@ -115,47 +112,46 @@ var initPublicState = extend(
var publicConfigStore = new HostStore(initPublicState)
// subscribe to changes
-configManager.subscribe(function(state){
+configManager.subscribe(function (state) {
storeSetFromObj(publicConfigStore, configToPublic(state))
})
-idStore.on('update', function(state){
+idStore.on('update', function (state) {
storeSetFromObj(publicConfigStore, idStoreToPublic(state))
})
// idStore substate
-function idStoreToPublic(state){
+function idStoreToPublic (state) {
return {
selectedAddress: state.selectedAddress,
}
}
// config substate
-function configToPublic(state){
+function configToPublic (state) {
return {
provider: state.provider,
}
}
// dump obj into store
-function storeSetFromObj(store, obj){
- Object.keys(obj).forEach(function(key){
+function storeSetFromObj (store, obj) {
+ Object.keys(obj).forEach(function (key) {
store.set(key, obj[key])
})
}
-
//
// remote features
//
-function setupPublicConfig(stream){
+function setupPublicConfig (stream) {
var storeStream = publicConfigStore.createStream()
stream.pipe(storeStream).pipe(stream)
}
-function setupProviderConnection(stream, originDomain){
+function setupProviderConnection (stream, originDomain) {
// decorate all payloads with origin domain
- stream.on('data', function onRpcRequest(request){
+ stream.on('data', function onRpcRequest (request) {
var payloads = Array.isArray(request) ? request : [request]
- payloads.forEach(function(payload){
+ payloads.forEach(function (payload) {
// Append origin to rpc payload
payload.origin = originDomain
// Append origin to signature request
@@ -166,7 +162,10 @@ function setupProviderConnection(stream, originDomain){
}
})
// handle rpc request
- provider.sendAsync(request, function onPayloadHandled(err, response){
+ provider.sendAsync(request, function onPayloadHandled (err, response) {
+ if (err) {
+ return logger(err)
+ }
logger(null, request, response)
try {
stream.write(response)
@@ -176,54 +175,52 @@ function setupProviderConnection(stream, originDomain){
})
})
- function logger(err, request, response){
+ function logger (err, request, response) {
if (err) return console.error(err.stack)
if (!request.isMetamaskInternal) {
console.log(`RPC (${originDomain}):`, request, '->', response)
- if (response.error) console.error('Error in RPC response:\n'+response.error.message)
+ if (response.error) console.error('Error in RPC response:\n' + response.error.message)
}
}
}
-function setupControllerConnection(stream){
+function setupControllerConnection (stream) {
var dnode = Dnode({
- getState: function(cb){ cb(null, getState()) },
- setRpcTarget: setRpcTarget,
- setProviderType: setProviderType,
+ getState: function (cb) { cb(null, getState()) },
+ setRpcTarget: setRpcTarget,
+ setProviderType: setProviderType,
useEtherscanProvider: useEtherscanProvider,
- agreeToDisclaimer: agreeToDisclaimer,
+ agreeToDisclaimer: agreeToDisclaimer,
// forward directly to idStore
- createNewVault: idStore.createNewVault.bind(idStore),
- recoverFromSeed: idStore.recoverFromSeed.bind(idStore),
- submitPassword: idStore.submitPassword.bind(idStore),
+ createNewVault: idStore.createNewVault.bind(idStore),
+ recoverFromSeed: idStore.recoverFromSeed.bind(idStore),
+ submitPassword: idStore.submitPassword.bind(idStore),
setSelectedAddress: idStore.setSelectedAddress.bind(idStore),
approveTransaction: idStore.approveTransaction.bind(idStore),
- cancelTransaction: idStore.cancelTransaction.bind(idStore),
- signMessage: idStore.signMessage.bind(idStore),
- cancelMessage: idStore.cancelMessage.bind(idStore),
- setLocked: idStore.setLocked.bind(idStore),
+ cancelTransaction: idStore.cancelTransaction.bind(idStore),
+ signMessage: idStore.signMessage.bind(idStore),
+ cancelMessage: idStore.cancelMessage.bind(idStore),
+ setLocked: idStore.setLocked.bind(idStore),
clearSeedWordCache: idStore.clearSeedWordCache.bind(idStore),
- exportAccount: idStore.exportAccount.bind(idStore),
- revealAccount: idStore.revealAccount.bind(idStore),
- saveAccountLabel: idStore.saveAccountLabel.bind(idStore),
- tryPassword: idStore.tryPassword.bind(idStore),
- recoverSeed: idStore.recoverSeed.bind(idStore),
+ exportAccount: idStore.exportAccount.bind(idStore),
+ revealAccount: idStore.revealAccount.bind(idStore),
+ saveAccountLabel: idStore.saveAccountLabel.bind(idStore),
+ tryPassword: idStore.tryPassword.bind(idStore),
+ recoverSeed: idStore.recoverSeed.bind(idStore),
})
stream.pipe(dnode).pipe(stream)
- dnode.on('remote', function(remote){
-
+ dnode.on('remote', function (remote) {
// push updates to popup
ethStore.on('update', sendUpdate)
idStore.on('update', sendUpdate)
// teardown on disconnect
- eos(stream, function unsubscribe(){
+ eos(stream, function unsubscribe () {
ethStore.removeListener('update', sendUpdate)
})
- function sendUpdate(){
+ function sendUpdate () {
var state = getState()
remote.sendUpdate(state)
}
-
})
}
@@ -233,7 +230,7 @@ function setupControllerConnection(stream){
idStore.on('update', updateBadge)
-function updateBadge(state){
+function updateBadge (state) {
var label = ''
var unconfTxs = configManager.unconfirmedTxs()
var unconfTxLen = Object.keys(unconfTxs).length
@@ -251,7 +248,7 @@ function updateBadge(state){
// Add unconfirmed Tx + Msg
//
-function newUnsignedTransaction(txParams, onTxDoneCb){
+function newUnsignedTransaction (txParams, onTxDoneCb) {
var state = idStore.getState()
if (!state.isUnlocked) {
createUnlockRequestNotification({
@@ -263,20 +260,19 @@ function newUnsignedTransaction(txParams, onTxDoneCb){
}
}
-function newUnsignedMessage(msgParams, cb){
+function newUnsignedMessage (msgParams, cb) {
var state = idStore.getState()
if (!state.isUnlocked) {
createUnlockRequestNotification({
title: 'Account Unlock Request',
})
- var msgId = idStore.addUnconfirmedMessage(msgParams, cb)
} else {
addUnconfirmedMsg(msgParams, cb)
}
}
-function addUnconfirmedTx(txParams, onTxDoneCb){
- idStore.addUnconfirmedTransaction(txParams, onTxDoneCb, function(err, txData){
+function addUnconfirmedTx (txParams, onTxDoneCb) {
+ idStore.addUnconfirmedTransaction(txParams, onTxDoneCb, function (err, txData) {
if (err) return onTxDoneCb(err)
createTxNotification({
title: 'New Unsigned Transaction',
@@ -287,7 +283,7 @@ function addUnconfirmedTx(txParams, onTxDoneCb){
})
}
-function addUnconfirmedMsg(msgParams, cb){
+function addUnconfirmedMsg (msgParams, cb) {
var msgId = idStore.addUnconfirmedMessage(msgParams, cb)
createMsgNotification({
title: 'New Unsigned Message',
@@ -301,7 +297,7 @@ function addUnconfirmedMsg(msgParams, cb){
// config
//
-function agreeToDisclaimer(cb) {
+function agreeToDisclaimer (cb) {
try {
configManager.setConfirmed(true)
cb()
@@ -311,23 +307,23 @@ function agreeToDisclaimer(cb) {
}
// called from popup
-function setRpcTarget(rpcTarget){
+function setRpcTarget (rpcTarget) {
configManager.setRpcTarget(rpcTarget)
chrome.runtime.reload()
idStore.getNetwork()
}
-function setProviderType(type) {
+function setProviderType (type) {
configManager.setProviderType(type)
chrome.runtime.reload()
idStore.getNetwork()
}
-function useEtherscanProvider() {
+function useEtherscanProvider () {
configManager.useEtherscanProvider()
chrome.runtime.reload()
}
// util
-function noop(){}
+function noop () {}
diff --git a/app/scripts/chromereload.js b/app/scripts/chromereload.js
index 24adc7022..283a131f1 100644
--- a/app/scripts/chromereload.js
+++ b/app/scripts/chromereload.js
@@ -32,1187 +32,1160 @@
window.LiveReloadOptions = { host: 'localhost' };
-
-(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
-(function() {
- var Connector, PROTOCOL_6, PROTOCOL_7, Parser, Version, _ref;
-
- _ref = require('./protocol'), Parser = _ref.Parser, PROTOCOL_6 = _ref.PROTOCOL_6, PROTOCOL_7 = _ref.PROTOCOL_7;
-
- Version = '2.2.2';
-
- exports.Connector = Connector = (function() {
- function Connector(options, WebSocket, Timer, handlers) {
- this.options = options;
- this.WebSocket = WebSocket;
- this.Timer = Timer;
- this.handlers = handlers;
- this._uri = "ws" + (this.options.https ? "s" : "") + "://" + this.options.host + ":" + this.options.port + "/livereload";
- this._nextDelay = this.options.mindelay;
- this._connectionDesired = false;
- this.protocol = 0;
- this.protocolParser = new Parser({
- connected: (function(_this) {
- return function(protocol) {
- _this.protocol = protocol;
- _this._handshakeTimeout.stop();
- _this._nextDelay = _this.options.mindelay;
- _this._disconnectionReason = 'broken';
- return _this.handlers.connected(protocol);
- };
- })(this),
- error: (function(_this) {
- return function(e) {
- _this.handlers.error(e);
- return _this._closeOnError();
- };
- })(this),
- message: (function(_this) {
- return function(message) {
- return _this.handlers.message(message);
- };
- })(this)
- });
- this._handshakeTimeout = new Timer((function(_this) {
- return function() {
- if (!_this._isSocketConnected()) {
- return;
+(function e (t, n, r) { function s (o, u) { if (!n[o]) { if (!t[o]) { var a = typeof require === 'function' && require; if (!u && a) return a(o, !0); if (i) return i(o, !0); var f = new Error("Cannot find module '" + o + "'"); throw f.code = 'MODULE_NOT_FOUND', f } var l = n[o] = {exports: {}}; t[o][0].call(l.exports, function (e) { var n = t[o][1][e]; return s(n ? n : e) }, l, l.exports, e, t, n, r) } return n[o].exports } var i = typeof require === 'function' && require; for (var o = 0; o < r.length; o++)s(r[o]); return s })({1: [function (require, module, exports) {
+ (function () {
+ var Connector, PROTOCOL_6, PROTOCOL_7, Parser, Version, _ref
+
+ _ref = require('./protocol'), Parser = _ref.Parser, PROTOCOL_6 = _ref.PROTOCOL_6, PROTOCOL_7 = _ref.PROTOCOL_7
+
+ Version = '2.2.2'
+
+ exports.Connector = Connector = (function () {
+ function Connector (options, WebSocket, Timer, handlers) {
+ this.options = options
+ this.WebSocket = WebSocket
+ this.Timer = Timer
+ this.handlers = handlers
+ this._uri = 'ws' + (this.options.https ? 's' : '') + '://' + this.options.host + ':' + this.options.port + '/livereload'
+ this._nextDelay = this.options.mindelay
+ this._connectionDesired = false
+ this.protocol = 0
+ this.protocolParser = new Parser({
+ connected: (function (_this) {
+ return function (protocol) {
+ _this.protocol = protocol
+ _this._handshakeTimeout.stop()
+ _this._nextDelay = _this.options.mindelay
+ _this._disconnectionReason = 'broken'
+ return _this.handlers.connected(protocol)
+ }
+ })(this),
+ error: (function (_this) {
+ return function (e) {
+ _this.handlers.error(e)
+ return _this._closeOnError()
+ }
+ })(this),
+ message: (function (_this) {
+ return function (message) {
+ return _this.handlers.message(message)
+ }
+ })(this),
+ })
+ this._handshakeTimeout = new Timer((function (_this) {
+ return function () {
+ if (!_this._isSocketConnected()) {
+ return
+ }
+ _this._disconnectionReason = 'handshake-timeout'
+ return _this.socket.close()
}
- _this._disconnectionReason = 'handshake-timeout';
- return _this.socket.close();
- };
- })(this));
- this._reconnectTimer = new Timer((function(_this) {
- return function() {
- if (!_this._connectionDesired) {
- return;
+ })(this))
+ this._reconnectTimer = new Timer((function (_this) {
+ return function () {
+ if (!_this._connectionDesired) {
+ return
+ }
+ return _this.connect()
}
- return _this.connect();
- };
- })(this));
- this.connect();
- }
-
- Connector.prototype._isSocketConnected = function() {
- return this.socket && this.socket.readyState === this.WebSocket.OPEN;
- };
-
- Connector.prototype.connect = function() {
- this._connectionDesired = true;
- if (this._isSocketConnected()) {
- return;
- }
- this._reconnectTimer.stop();
- this._disconnectionReason = 'cannot-connect';
- this.protocolParser.reset();
- this.handlers.connecting();
- this.socket = new this.WebSocket(this._uri);
- this.socket.onopen = (function(_this) {
- return function(e) {
- return _this._onopen(e);
- };
- })(this);
- this.socket.onclose = (function(_this) {
- return function(e) {
- return _this._onclose(e);
- };
- })(this);
- this.socket.onmessage = (function(_this) {
- return function(e) {
- return _this._onmessage(e);
- };
- })(this);
- return this.socket.onerror = (function(_this) {
- return function(e) {
- return _this._onerror(e);
- };
- })(this);
- };
-
- Connector.prototype.disconnect = function() {
- this._connectionDesired = false;
- this._reconnectTimer.stop();
- if (!this._isSocketConnected()) {
- return;
+ })(this))
+ this.connect()
}
- this._disconnectionReason = 'manual';
- return this.socket.close();
- };
- Connector.prototype._scheduleReconnection = function() {
- if (!this._connectionDesired) {
- return;
+ Connector.prototype._isSocketConnected = function () {
+ return this.socket && this.socket.readyState === this.WebSocket.OPEN
}
- if (!this._reconnectTimer.running) {
- this._reconnectTimer.start(this._nextDelay);
- return this._nextDelay = Math.min(this.options.maxdelay, this._nextDelay * 2);
- }
- };
- Connector.prototype.sendCommand = function(command) {
- if (this.protocol == null) {
- return;
- }
- return this._sendCommand(command);
- };
-
- Connector.prototype._sendCommand = function(command) {
- return this.socket.send(JSON.stringify(command));
- };
-
- Connector.prototype._closeOnError = function() {
- this._handshakeTimeout.stop();
- this._disconnectionReason = 'error';
- return this.socket.close();
- };
-
- Connector.prototype._onopen = function(e) {
- var hello;
- this.handlers.socketConnected();
- this._disconnectionReason = 'handshake-failed';
- hello = {
- command: 'hello',
- protocols: [PROTOCOL_6, PROTOCOL_7]
- };
- hello.ver = Version;
- if (this.options.ext) {
- hello.ext = this.options.ext;
+ Connector.prototype.connect = function () {
+ this._connectionDesired = true
+ if (this._isSocketConnected()) {
+ return
+ }
+ this._reconnectTimer.stop()
+ this._disconnectionReason = 'cannot-connect'
+ this.protocolParser.reset()
+ this.handlers.connecting()
+ this.socket = new this.WebSocket(this._uri)
+ this.socket.onopen = (function (_this) {
+ return function (e) {
+ return _this._onopen(e)
+ }
+ })(this)
+ this.socket.onclose = (function (_this) {
+ return function (e) {
+ return _this._onclose(e)
+ }
+ })(this)
+ this.socket.onmessage = (function (_this) {
+ return function (e) {
+ return _this._onmessage(e)
+ }
+ })(this)
+ return this.socket.onerror = (function (_this) {
+ return function (e) {
+ return _this._onerror(e)
+ }
+ })(this)
}
- if (this.options.extver) {
- hello.extver = this.options.extver;
+
+ Connector.prototype.disconnect = function () {
+ this._connectionDesired = false
+ this._reconnectTimer.stop()
+ if (!this._isSocketConnected()) {
+ return
+ }
+ this._disconnectionReason = 'manual'
+ return this.socket.close()
}
- if (this.options.snipver) {
- hello.snipver = this.options.snipver;
+
+ Connector.prototype._scheduleReconnection = function () {
+ if (!this._connectionDesired) {
+ return
+ }
+ if (!this._reconnectTimer.running) {
+ this._reconnectTimer.start(this._nextDelay)
+ return this._nextDelay = Math.min(this.options.maxdelay, this._nextDelay * 2)
+ }
}
- this._sendCommand(hello);
- return this._handshakeTimeout.start(this.options.handshake_timeout);
- };
- Connector.prototype._onclose = function(e) {
- this.protocol = 0;
- this.handlers.disconnected(this._disconnectionReason, this._nextDelay);
- return this._scheduleReconnection();
- };
+ Connector.prototype.sendCommand = function (command) {
+ if (this.protocol == null) {
+ return
+ }
+ return this._sendCommand(command)
+ }
- Connector.prototype._onerror = function(e) {};
+ Connector.prototype._sendCommand = function (command) {
+ return this.socket.send(JSON.stringify(command))
+ }
- Connector.prototype._onmessage = function(e) {
- return this.protocolParser.process(e.data);
- };
+ Connector.prototype._closeOnError = function () {
+ this._handshakeTimeout.stop()
+ this._disconnectionReason = 'error'
+ return this.socket.close()
+ }
- return Connector;
+ Connector.prototype._onopen = function (e) {
+ var hello
+ this.handlers.socketConnected()
+ this._disconnectionReason = 'handshake-failed'
+ hello = {
+ command: 'hello',
+ protocols: [PROTOCOL_6, PROTOCOL_7],
+ }
+ hello.ver = Version
+ if (this.options.ext) {
+ hello.ext = this.options.ext
+ }
+ if (this.options.extver) {
+ hello.extver = this.options.extver
+ }
+ if (this.options.snipver) {
+ hello.snipver = this.options.snipver
+ }
+ this._sendCommand(hello)
+ return this._handshakeTimeout.start(this.options.handshake_timeout)
+ }
- })();
+ Connector.prototype._onclose = function (e) {
+ this.protocol = 0
+ this.handlers.disconnected(this._disconnectionReason, this._nextDelay)
+ return this._scheduleReconnection()
+ }
-}).call(this);
+ Connector.prototype._onerror = function (e) {}
-},{"./protocol":6}],2:[function(require,module,exports){
-(function() {
- var CustomEvents;
+ Connector.prototype._onmessage = function (e) {
+ return this.protocolParser.process(e.data)
+ }
- CustomEvents = {
- bind: function(element, eventName, handler) {
- if (element.addEventListener) {
- return element.addEventListener(eventName, handler, false);
- } else if (element.attachEvent) {
- element[eventName] = 1;
- return element.attachEvent('onpropertychange', function(event) {
- if (event.propertyName === eventName) {
- return handler();
+ return Connector
+ })()
+ }).call(this)
+}, {'./protocol': 6}], 2: [function (require, module, exports) {
+ (function () {
+ var CustomEvents
+
+ CustomEvents = {
+ bind: function (element, eventName, handler) {
+ if (element.addEventListener) {
+ return element.addEventListener(eventName, handler, false)
+ } else if (element.attachEvent) {
+ element[eventName] = 1
+ return element.attachEvent('onpropertychange', function (event) {
+ if (event.propertyName === eventName) {
+ return handler()
+ }
+ })
+ } else {
+ throw new Error('Attempt to attach custom event ' + eventName + " to something which isn't a DOMElement")
+ }
+ },
+ fire: function (element, eventName) {
+ var event
+ if (element.addEventListener) {
+ event = document.createEvent('HTMLEvents')
+ event.initEvent(eventName, true, true)
+ return document.dispatchEvent(event)
+ } else if (element.attachEvent) {
+ if (element[eventName]) {
+ return element[eventName]++
}
- });
- } else {
- throw new Error("Attempt to attach custom event " + eventName + " to something which isn't a DOMElement");
- }
- },
- fire: function(element, eventName) {
- var event;
- if (element.addEventListener) {
- event = document.createEvent('HTMLEvents');
- event.initEvent(eventName, true, true);
- return document.dispatchEvent(event);
- } else if (element.attachEvent) {
- if (element[eventName]) {
- return element[eventName]++;
+ } else {
+ throw new Error('Attempt to fire custom event ' + eventName + " on something which isn't a DOMElement")
}
- } else {
- throw new Error("Attempt to fire custom event " + eventName + " on something which isn't a DOMElement");
- }
+ },
}
- };
- exports.bind = CustomEvents.bind;
+ exports.bind = CustomEvents.bind
- exports.fire = CustomEvents.fire;
+ exports.fire = CustomEvents.fire
+ }).call(this)
+}, {}], 3: [function (require, module, exports) {
+ (function () {
+ var LessPlugin
-}).call(this);
+ module.exports = LessPlugin = (function () {
+ LessPlugin.identifier = 'less'
-},{}],3:[function(require,module,exports){
-(function() {
- var LessPlugin;
+ LessPlugin.version = '1.0'
- module.exports = LessPlugin = (function() {
- LessPlugin.identifier = 'less';
-
- LessPlugin.version = '1.0';
-
- function LessPlugin(window, host) {
- this.window = window;
- this.host = host;
- }
+ function LessPlugin (window, host) {
+ this.window = window
+ this.host = host
+ }
- LessPlugin.prototype.reload = function(path, options) {
- if (this.window.less && this.window.less.refresh) {
- if (path.match(/\.less$/i)) {
- return this.reloadLess(path);
- }
- if (options.originalPath.match(/\.less$/i)) {
- return this.reloadLess(options.originalPath);
+ LessPlugin.prototype.reload = function (path, options) {
+ if (this.window.less && this.window.less.refresh) {
+ if (path.match(/\.less$/i)) {
+ return this.reloadLess(path)
+ }
+ if (options.originalPath.match(/\.less$/i)) {
+ return this.reloadLess(options.originalPath)
+ }
}
+ return false
}
- return false;
- };
-
- LessPlugin.prototype.reloadLess = function(path) {
- var link, links, _i, _len;
- links = (function() {
- var _i, _len, _ref, _results;
- _ref = document.getElementsByTagName('link');
- _results = [];
- for (_i = 0, _len = _ref.length; _i < _len; _i++) {
- link = _ref[_i];
- if (link.href && link.rel.match(/^stylesheet\/less$/i) || (link.rel.match(/stylesheet/i) && link.type.match(/^text\/(x-)?less$/i))) {
- _results.push(link);
+
+ LessPlugin.prototype.reloadLess = function (path) {
+ var link, links, _i, _len
+ links = (function () {
+ var _i, _len, _ref, _results
+ _ref = document.getElementsByTagName('link')
+ _results = []
+ for (_i = 0, _len = _ref.length; _i < _len; _i++) {
+ link = _ref[_i]
+ if (link.href && link.rel.match(/^stylesheet\/less$/i) || (link.rel.match(/stylesheet/i) && link.type.match(/^text\/(x-)?less$/i))) {
+ _results.push(link)
+ }
}
+ return _results
+ })()
+ if (links.length === 0) {
+ return false
}
- return _results;
- })();
- if (links.length === 0) {
- return false;
- }
- for (_i = 0, _len = links.length; _i < _len; _i++) {
- link = links[_i];
- link.href = this.host.generateCacheBustUrl(link.href);
+ for (_i = 0, _len = links.length; _i < _len; _i++) {
+ link = links[_i]
+ link.href = this.host.generateCacheBustUrl(link.href)
+ }
+ this.host.console.log('LiveReload is asking LESS to recompile all stylesheets')
+ this.window.less.refresh(true)
+ return true
}
- this.host.console.log("LiveReload is asking LESS to recompile all stylesheets");
- this.window.less.refresh(true);
- return true;
- };
- LessPlugin.prototype.analyze = function() {
- return {
- disable: !!(this.window.less && this.window.less.refresh)
- };
- };
-
- return LessPlugin;
-
- })();
-
-}).call(this);
-
-},{}],4:[function(require,module,exports){
-(function() {
- var Connector, LiveReload, Options, Reloader, Timer,
- __hasProp = {}.hasOwnProperty;
-
- Connector = require('./connector').Connector;
-
- Timer = require('./timer').Timer;
-
- Options = require('./options').Options;
-
- Reloader = require('./reloader').Reloader;
-
- exports.LiveReload = LiveReload = (function() {
- function LiveReload(window) {
- var k, v, _ref;
- this.window = window;
- this.listeners = {};
- this.plugins = [];
- this.pluginIdentifiers = {};
- this.console = this.window.console && this.window.console.log && this.window.console.error ? this.window.location.href.match(/LR-verbose/) ? this.window.console : {
- log: function() {},
- error: this.window.console.error.bind(this.window.console)
- } : {
- log: function() {},
- error: function() {}
- };
- if (!(this.WebSocket = this.window.WebSocket || this.window.MozWebSocket)) {
- this.console.error("LiveReload disabled because the browser does not seem to support web sockets");
- return;
+ LessPlugin.prototype.analyze = function () {
+ return {
+ disable: !!(this.window.less && this.window.less.refresh),
+ }
}
- if ('LiveReloadOptions' in window) {
- this.options = new Options();
- _ref = window['LiveReloadOptions'];
- for (k in _ref) {
- if (!__hasProp.call(_ref, k)) continue;
- v = _ref[k];
- this.options.set(k, v);
+
+ return LessPlugin
+ })()
+ }).call(this)
+}, {}], 4: [function (require, module, exports) {
+ (function () {
+ var Connector, LiveReload, Options, Reloader, Timer,
+ __hasProp = {}.hasOwnProperty
+
+ Connector = require('./connector').Connector
+
+ Timer = require('./timer').Timer
+
+ Options = require('./options').Options
+
+ Reloader = require('./reloader').Reloader
+
+ exports.LiveReload = LiveReload = (function () {
+ function LiveReload (window) {
+ var k, v, _ref
+ this.window = window
+ this.listeners = {}
+ this.plugins = []
+ this.pluginIdentifiers = {}
+ this.console = this.window.console && this.window.console.log && this.window.console.error ? this.window.location.href.match(/LR-verbose/) ? this.window.console : {
+ log: function () {},
+ error: this.window.console.error.bind(this.window.console),
+ } : {
+ log: function () {},
+ error: function () {},
}
- } else {
- this.options = Options.extract(this.window.document);
- if (!this.options) {
- this.console.error("LiveReload disabled because it could not find its own <SCRIPT> tag");
- return;
+ if (!(this.WebSocket = this.window.WebSocket || this.window.MozWebSocket)) {
+ this.console.error('LiveReload disabled because the browser does not seem to support web sockets')
+ return
}
- }
- this.reloader = new Reloader(this.window, this.console, Timer);
- this.connector = new Connector(this.options, this.WebSocket, Timer, {
- connecting: (function(_this) {
- return function() {};
- })(this),
- socketConnected: (function(_this) {
- return function() {};
- })(this),
- connected: (function(_this) {
- return function(protocol) {
- var _base;
- if (typeof (_base = _this.listeners).connect === "function") {
- _base.connect();
- }
- _this.log("LiveReload is connected to " + _this.options.host + ":" + _this.options.port + " (protocol v" + protocol + ").");
- return _this.analyze();
- };
- })(this),
- error: (function(_this) {
- return function(e) {
- if (e instanceof ProtocolError) {
- if (typeof console !== "undefined" && console !== null) {
- return console.log("" + e.message + ".");
- }
- } else {
- if (typeof console !== "undefined" && console !== null) {
- return console.log("LiveReload internal error: " + e.message);
+ if ('LiveReloadOptions' in window) {
+ this.options = new Options()
+ _ref = window['LiveReloadOptions']
+ for (k in _ref) {
+ if (!__hasProp.call(_ref, k)) continue
+ v = _ref[k]
+ this.options.set(k, v)
+ }
+ } else {
+ this.options = Options.extract(this.window.document)
+ if (!this.options) {
+ this.console.error('LiveReload disabled because it could not find its own <SCRIPT> tag')
+ return
+ }
+ }
+ this.reloader = new Reloader(this.window, this.console, Timer)
+ this.connector = new Connector(this.options, this.WebSocket, Timer, {
+ connecting: (function (_this) {
+ return function () {}
+ })(this),
+ socketConnected: (function (_this) {
+ return function () {}
+ })(this),
+ connected: (function (_this) {
+ return function (protocol) {
+ var _base
+ if (typeof (_base = _this.listeners).connect === 'function') {
+ _base.connect()
}
+ _this.log('LiveReload is connected to ' + _this.options.host + ':' + _this.options.port + ' (protocol v' + protocol + ').')
+ return _this.analyze()
}
- };
- })(this),
- disconnected: (function(_this) {
- return function(reason, nextDelay) {
- var _base;
- if (typeof (_base = _this.listeners).disconnect === "function") {
- _base.disconnect();
+ })(this),
+ error: (function (_this) {
+ return function (e) {
+ if (e instanceof ProtocolError) {
+ if (typeof console !== 'undefined' && console !== null) {
+ return console.log('' + e.message + '.')
+ }
+ } else {
+ if (typeof console !== 'undefined' && console !== null) {
+ return console.log('LiveReload internal error: ' + e.message)
+ }
+ }
}
- switch (reason) {
- case 'cannot-connect':
- return _this.log("LiveReload cannot connect to " + _this.options.host + ":" + _this.options.port + ", will retry in " + nextDelay + " sec.");
- case 'broken':
- return _this.log("LiveReload disconnected from " + _this.options.host + ":" + _this.options.port + ", reconnecting in " + nextDelay + " sec.");
- case 'handshake-timeout':
- return _this.log("LiveReload cannot connect to " + _this.options.host + ":" + _this.options.port + " (handshake timeout), will retry in " + nextDelay + " sec.");
- case 'handshake-failed':
- return _this.log("LiveReload cannot connect to " + _this.options.host + ":" + _this.options.port + " (handshake failed), will retry in " + nextDelay + " sec.");
- case 'manual':
- break;
- case 'error':
- break;
- default:
- return _this.log("LiveReload disconnected from " + _this.options.host + ":" + _this.options.port + " (" + reason + "), reconnecting in " + nextDelay + " sec.");
+ })(this),
+ disconnected: (function (_this) {
+ return function (reason, nextDelay) {
+ var _base
+ if (typeof (_base = _this.listeners).disconnect === 'function') {
+ _base.disconnect()
+ }
+ switch (reason) {
+ case 'cannot-connect':
+ return _this.log('LiveReload cannot connect to ' + _this.options.host + ':' + _this.options.port + ', will retry in ' + nextDelay + ' sec.')
+ case 'broken':
+ return _this.log('LiveReload disconnected from ' + _this.options.host + ':' + _this.options.port + ', reconnecting in ' + nextDelay + ' sec.')
+ case 'handshake-timeout':
+ return _this.log('LiveReload cannot connect to ' + _this.options.host + ':' + _this.options.port + ' (handshake timeout), will retry in ' + nextDelay + ' sec.')
+ case 'handshake-failed':
+ return _this.log('LiveReload cannot connect to ' + _this.options.host + ':' + _this.options.port + ' (handshake failed), will retry in ' + nextDelay + ' sec.')
+ case 'manual':
+ break
+ case 'error':
+ break
+ default:
+ return _this.log('LiveReload disconnected from ' + _this.options.host + ':' + _this.options.port + ' (' + reason + '), reconnecting in ' + nextDelay + ' sec.')
+ }
}
- };
- })(this),
- message: (function(_this) {
- return function(message) {
- switch (message.command) {
- case 'reload':
- return _this.performReload(message);
- case 'alert':
- return _this.performAlert(message);
+ })(this),
+ message: (function (_this) {
+ return function (message) {
+ switch (message.command) {
+ case 'reload':
+ return _this.performReload(message)
+ case 'alert':
+ return _this.performAlert(message)
+ }
}
- };
- })(this)
- });
- this.initialized = true;
- }
+ })(this),
+ })
+ this.initialized = true
+ }
- LiveReload.prototype.on = function(eventName, handler) {
- return this.listeners[eventName] = handler;
- };
-
- LiveReload.prototype.log = function(message) {
- return this.console.log("" + message);
- };
-
- LiveReload.prototype.performReload = function(message) {
- var _ref, _ref1;
- this.log("LiveReload received reload request: " + (JSON.stringify(message, null, 2)));
- return this.reloader.reload(message.path, {
- liveCSS: (_ref = message.liveCSS) != null ? _ref : true,
- liveImg: (_ref1 = message.liveImg) != null ? _ref1 : true,
- originalPath: message.originalPath || '',
- overrideURL: message.overrideURL || '',
- serverURL: "http://" + this.options.host + ":" + this.options.port
- });
- };
-
- LiveReload.prototype.performAlert = function(message) {
- return alert(message.message);
- };
-
- LiveReload.prototype.shutDown = function() {
- var _base;
- if (!this.initialized) {
- return;
+ LiveReload.prototype.on = function (eventName, handler) {
+ return this.listeners[eventName] = handler
}
- this.connector.disconnect();
- this.log("LiveReload disconnected.");
- return typeof (_base = this.listeners).shutdown === "function" ? _base.shutdown() : void 0;
- };
-
- LiveReload.prototype.hasPlugin = function(identifier) {
- return !!this.pluginIdentifiers[identifier];
- };
-
- LiveReload.prototype.addPlugin = function(pluginClass) {
- var plugin;
- if (!this.initialized) {
- return;
+
+ LiveReload.prototype.log = function (message) {
+ return this.console.log('' + message)
}
- if (this.hasPlugin(pluginClass.identifier)) {
- return;
+
+ LiveReload.prototype.performReload = function (message) {
+ var _ref, _ref1
+ this.log('LiveReload received reload request: ' + (JSON.stringify(message, null, 2)))
+ return this.reloader.reload(message.path, {
+ liveCSS: (_ref = message.liveCSS) != null ? _ref : true,
+ liveImg: (_ref1 = message.liveImg) != null ? _ref1 : true,
+ originalPath: message.originalPath || '',
+ overrideURL: message.overrideURL || '',
+ serverURL: 'http://' + this.options.host + ':' + this.options.port,
+ })
}
- this.pluginIdentifiers[pluginClass.identifier] = true;
- plugin = new pluginClass(this.window, {
- _livereload: this,
- _reloader: this.reloader,
- _connector: this.connector,
- console: this.console,
- Timer: Timer,
- generateCacheBustUrl: (function(_this) {
- return function(url) {
- return _this.reloader.generateCacheBustUrl(url);
- };
- })(this)
- });
- this.plugins.push(plugin);
- this.reloader.addPlugin(plugin);
- };
-
- LiveReload.prototype.analyze = function() {
- var plugin, pluginData, pluginsData, _i, _len, _ref;
- if (!this.initialized) {
- return;
+
+ LiveReload.prototype.performAlert = function (message) {
+ return alert(message.message)
}
- if (!(this.connector.protocol >= 7)) {
- return;
+
+ LiveReload.prototype.shutDown = function () {
+ var _base
+ if (!this.initialized) {
+ return
+ }
+ this.connector.disconnect()
+ this.log('LiveReload disconnected.')
+ return typeof (_base = this.listeners).shutdown === 'function' ? _base.shutdown() : void 0
}
- pluginsData = {};
- _ref = this.plugins;
- for (_i = 0, _len = _ref.length; _i < _len; _i++) {
- plugin = _ref[_i];
- pluginsData[plugin.constructor.identifier] = pluginData = (typeof plugin.analyze === "function" ? plugin.analyze() : void 0) || {};
- pluginData.version = plugin.constructor.version;
+
+ LiveReload.prototype.hasPlugin = function (identifier) {
+ return !!this.pluginIdentifiers[identifier]
+ }
+
+ LiveReload.prototype.addPlugin = function (pluginClass) {
+ var plugin
+ if (!this.initialized) {
+ return
+ }
+ if (this.hasPlugin(pluginClass.identifier)) {
+ return
+ }
+ this.pluginIdentifiers[pluginClass.identifier] = true
+ plugin = new pluginClass(this.window, {
+ _livereload: this,
+ _reloader: this.reloader,
+ _connector: this.connector,
+ console: this.console,
+ Timer: Timer,
+ generateCacheBustUrl: (function (_this) {
+ return function (url) {
+ return _this.reloader.generateCacheBustUrl(url)
+ }
+ })(this),
+ })
+ this.plugins.push(plugin)
+ this.reloader.addPlugin(plugin)
}
- this.connector.sendCommand({
- command: 'info',
- plugins: pluginsData,
- url: this.window.location.href
- });
- };
-
- return LiveReload;
-
- })();
-
-}).call(this);
-
-},{"./connector":1,"./options":5,"./reloader":7,"./timer":9}],5:[function(require,module,exports){
-(function() {
- var Options;
-
- exports.Options = Options = (function() {
- function Options() {
- this.https = false;
- this.host = null;
- this.port = 35729;
- this.snipver = null;
- this.ext = null;
- this.extver = null;
- this.mindelay = 1000;
- this.maxdelay = 60000;
- this.handshake_timeout = 5000;
- }
- Options.prototype.set = function(name, value) {
- if (typeof value === 'undefined') {
- return;
+ LiveReload.prototype.analyze = function () {
+ var plugin, pluginData, pluginsData, _i, _len, _ref
+ if (!this.initialized) {
+ return
+ }
+ if (!(this.connector.protocol >= 7)) {
+ return
+ }
+ pluginsData = {}
+ _ref = this.plugins
+ for (_i = 0, _len = _ref.length; _i < _len; _i++) {
+ plugin = _ref[_i]
+ pluginsData[plugin.constructor.identifier] = pluginData = (typeof plugin.analyze === 'function' ? plugin.analyze() : void 0) || {}
+ pluginData.version = plugin.constructor.version
+ }
+ this.connector.sendCommand({
+ command: 'info',
+ plugins: pluginsData,
+ url: this.window.location.href,
+ })
}
- if (!isNaN(+value)) {
- value = +value;
+
+ return LiveReload
+ })()
+ }).call(this)
+}, {'./connector': 1, './options': 5, './reloader': 7, './timer': 9}], 5: [function (require, module, exports) {
+ (function () {
+ var Options
+
+ exports.Options = Options = (function () {
+ function Options () {
+ this.https = false
+ this.host = null
+ this.port = 35729
+ this.snipver = null
+ this.ext = null
+ this.extver = null
+ this.mindelay = 1000
+ this.maxdelay = 60000
+ this.handshake_timeout = 5000
}
- return this[name] = value;
- };
-
- return Options;
-
- })();
-
- Options.extract = function(document) {
- var element, keyAndValue, m, mm, options, pair, src, _i, _j, _len, _len1, _ref, _ref1;
- _ref = document.getElementsByTagName('script');
- for (_i = 0, _len = _ref.length; _i < _len; _i++) {
- element = _ref[_i];
- if ((src = element.src) && (m = src.match(/^[^:]+:\/\/(.*)\/z?livereload\.js(?:\?(.*))?$/))) {
- options = new Options();
- options.https = src.indexOf("https") === 0;
- if (mm = m[1].match(/^([^\/:]+)(?::(\d+))?$/)) {
- options.host = mm[1];
- if (mm[2]) {
- options.port = parseInt(mm[2], 10);
- }
+
+ Options.prototype.set = function (name, value) {
+ if (typeof value === 'undefined') {
+ return
+ }
+ if (!isNaN(+value)) {
+ value = +value
}
- if (m[2]) {
- _ref1 = m[2].split('&');
- for (_j = 0, _len1 = _ref1.length; _j < _len1; _j++) {
- pair = _ref1[_j];
- if ((keyAndValue = pair.split('=')).length > 1) {
- options.set(keyAndValue[0].replace(/-/g, '_'), keyAndValue.slice(1).join('='));
+ return this[name] = value
+ }
+
+ return Options
+ })()
+
+ Options.extract = function (document) {
+ var element, keyAndValue, m, mm, options, pair, src, _i, _j, _len, _len1, _ref, _ref1
+ _ref = document.getElementsByTagName('script')
+ for (_i = 0, _len = _ref.length; _i < _len; _i++) {
+ element = _ref[_i]
+ if ((src = element.src) && (m = src.match(/^[^:]+:\/\/(.*)\/z?livereload\.js(?:\?(.*))?$/))) {
+ options = new Options()
+ options.https = src.indexOf('https') === 0
+ if (mm = m[1].match(/^([^\/:]+)(?::(\d+))?$/)) {
+ options.host = mm[1]
+ if (mm[2]) {
+ options.port = parseInt(mm[2], 10)
+ }
+ }
+ if (m[2]) {
+ _ref1 = m[2].split('&')
+ for (_j = 0, _len1 = _ref1.length; _j < _len1; _j++) {
+ pair = _ref1[_j]
+ if ((keyAndValue = pair.split('=')).length > 1) {
+ options.set(keyAndValue[0].replace(/-/g, '_'), keyAndValue.slice(1).join('='))
+ }
}
}
+ return options
}
- return options;
}
+ return null
}
- return null;
- };
+ }).call(this)
+}, {}], 6: [function (require, module, exports) {
+ (function () {
+ var PROTOCOL_6, PROTOCOL_7, Parser, ProtocolError,
+ __indexOf = [].indexOf || function (item) { for (var i = 0, l = this.length; i < l; i++) { if (i in this && this[i] === item) return i } return -1 }
-}).call(this);
+ exports.PROTOCOL_6 = PROTOCOL_6 = 'http://livereload.com/protocols/official-6'
-},{}],6:[function(require,module,exports){
-(function() {
- var PROTOCOL_6, PROTOCOL_7, Parser, ProtocolError,
- __indexOf = [].indexOf || function(item) { for (var i = 0, l = this.length; i < l; i++) { if (i in this && this[i] === item) return i; } return -1; };
+ exports.PROTOCOL_7 = PROTOCOL_7 = 'http://livereload.com/protocols/official-7'
- exports.PROTOCOL_6 = PROTOCOL_6 = 'http://livereload.com/protocols/official-6';
-
- exports.PROTOCOL_7 = PROTOCOL_7 = 'http://livereload.com/protocols/official-7';
-
- exports.ProtocolError = ProtocolError = (function() {
- function ProtocolError(reason, data) {
- this.message = "LiveReload protocol error (" + reason + ") after receiving data: \"" + data + "\".";
- }
-
- return ProtocolError;
+ exports.ProtocolError = ProtocolError = (function () {
+ function ProtocolError (reason, data) {
+ this.message = 'LiveReload protocol error (' + reason + ') after receiving data: "' + data + '".'
+ }
- })();
+ return ProtocolError
+ })()
- exports.Parser = Parser = (function() {
- function Parser(handlers) {
- this.handlers = handlers;
- this.reset();
- }
+ exports.Parser = Parser = (function () {
+ function Parser (handlers) {
+ this.handlers = handlers
+ this.reset()
+ }
- Parser.prototype.reset = function() {
- return this.protocol = null;
- };
+ Parser.prototype.reset = function () {
+ return this.protocol = null
+ }
- Parser.prototype.process = function(data) {
- var command, e, message, options, _ref;
- try {
- if (this.protocol == null) {
- if (data.match(/^!!ver:([\d.]+)$/)) {
- this.protocol = 6;
- } else if (message = this._parseMessage(data, ['hello'])) {
- if (!message.protocols.length) {
- throw new ProtocolError("no protocols specified in handshake message");
- } else if (__indexOf.call(message.protocols, PROTOCOL_7) >= 0) {
- this.protocol = 7;
- } else if (__indexOf.call(message.protocols, PROTOCOL_6) >= 0) {
- this.protocol = 6;
- } else {
- throw new ProtocolError("no supported protocols found");
+ Parser.prototype.process = function (data) {
+ var command, e, message, options, _ref
+ try {
+ if (this.protocol == null) {
+ if (data.match(/^!!ver:([\d.]+)$/)) {
+ this.protocol = 6
+ } else if (message = this._parseMessage(data, ['hello'])) {
+ if (!message.protocols.length) {
+ throw new ProtocolError('no protocols specified in handshake message')
+ } else if (__indexOf.call(message.protocols, PROTOCOL_7) >= 0) {
+ this.protocol = 7
+ } else if (__indexOf.call(message.protocols, PROTOCOL_6) >= 0) {
+ this.protocol = 6
+ } else {
+ throw new ProtocolError('no supported protocols found')
+ }
}
+ return this.handlers.connected(this.protocol)
+ } else if (this.protocol === 6) {
+ message = JSON.parse(data)
+ if (!message.length) {
+ throw new ProtocolError('protocol 6 messages must be arrays')
+ }
+ command = message[0], options = message[1]
+ if (command !== 'refresh') {
+ throw new ProtocolError('unknown protocol 6 command')
+ }
+ return this.handlers.message({
+ command: 'reload',
+ path: options.path,
+ liveCSS: (_ref = options.apply_css_live) != null ? _ref : true,
+ })
+ } else {
+ message = this._parseMessage(data, ['reload', 'alert'])
+ return this.handlers.message(message)
}
- return this.handlers.connected(this.protocol);
- } else if (this.protocol === 6) {
- message = JSON.parse(data);
- if (!message.length) {
- throw new ProtocolError("protocol 6 messages must be arrays");
- }
- command = message[0], options = message[1];
- if (command !== 'refresh') {
- throw new ProtocolError("unknown protocol 6 command");
+ } catch (_error) {
+ e = _error
+ if (e instanceof ProtocolError) {
+ return this.handlers.error(e)
+ } else {
+ throw e
}
- return this.handlers.message({
- command: 'reload',
- path: options.path,
- liveCSS: (_ref = options.apply_css_live) != null ? _ref : true
- });
- } else {
- message = this._parseMessage(data, ['reload', 'alert']);
- return this.handlers.message(message);
}
- } catch (_error) {
- e = _error;
- if (e instanceof ProtocolError) {
- return this.handlers.error(e);
- } else {
- throw e;
+ }
+
+ Parser.prototype._parseMessage = function (data, validCommands) {
+ var e, message, _ref
+ try {
+ message = JSON.parse(data)
+ } catch (_error) {
+ e = _error
+ throw new ProtocolError('unparsable JSON', data)
+ }
+ if (!message.command) {
+ throw new ProtocolError('missing "command" key', data)
}
+ if (_ref = message.command, __indexOf.call(validCommands, _ref) < 0) {
+ throw new ProtocolError("invalid command '" + message.command + "', only valid commands are: " + (validCommands.join(', ')) + ')', data)
+ }
+ return message
}
- };
-
- Parser.prototype._parseMessage = function(data, validCommands) {
- var e, message, _ref;
- try {
- message = JSON.parse(data);
- } catch (_error) {
- e = _error;
- throw new ProtocolError('unparsable JSON', data);
+
+ return Parser
+ })()
+ }).call(this)
+}, {}], 7: [function (require, module, exports) {
+ (function () {
+ var IMAGE_STYLES, Reloader, numberOfMatchingSegments, pathFromUrl, pathsMatch, pickBestMatch, splitUrl
+
+ splitUrl = function (url) {
+ var hash, index, params
+ if ((index = url.indexOf('#')) >= 0) {
+ hash = url.slice(index)
+ url = url.slice(0, index)
+ } else {
+ hash = ''
}
- if (!message.command) {
- throw new ProtocolError('missing "command" key', data);
+ if ((index = url.indexOf('?')) >= 0) {
+ params = url.slice(index)
+ url = url.slice(0, index)
+ } else {
+ params = ''
}
- if (_ref = message.command, __indexOf.call(validCommands, _ref) < 0) {
- throw new ProtocolError("invalid command '" + message.command + "', only valid commands are: " + (validCommands.join(', ')) + ")", data);
+ return {
+ url: url,
+ params: params,
+ hash: hash,
}
- return message;
- };
-
- return Parser;
-
- })();
-
-}).call(this);
-
-},{}],7:[function(require,module,exports){
-(function() {
- var IMAGE_STYLES, Reloader, numberOfMatchingSegments, pathFromUrl, pathsMatch, pickBestMatch, splitUrl;
-
- splitUrl = function(url) {
- var hash, index, params;
- if ((index = url.indexOf('#')) >= 0) {
- hash = url.slice(index);
- url = url.slice(0, index);
- } else {
- hash = '';
- }
- if ((index = url.indexOf('?')) >= 0) {
- params = url.slice(index);
- url = url.slice(0, index);
- } else {
- params = '';
}
- return {
- url: url,
- params: params,
- hash: hash
- };
- };
-
- pathFromUrl = function(url) {
- var path;
- url = splitUrl(url).url;
- if (url.indexOf('file://') === 0) {
- path = url.replace(/^file:\/\/(localhost)?/, '');
- } else {
- path = url.replace(/^([^:]+:)?\/\/([^:\/]+)(:\d*)?\//, '/');
- }
- return decodeURIComponent(path);
- };
-
- pickBestMatch = function(path, objects, pathFunc) {
- var bestMatch, object, score, _i, _len;
- bestMatch = {
- score: 0
- };
- for (_i = 0, _len = objects.length; _i < _len; _i++) {
- object = objects[_i];
- score = numberOfMatchingSegments(path, pathFunc(object));
- if (score > bestMatch.score) {
- bestMatch = {
- object: object,
- score: score
- };
+
+ pathFromUrl = function (url) {
+ var path
+ url = splitUrl(url).url
+ if (url.indexOf('file://') === 0) {
+ path = url.replace(/^file:\/\/(localhost)?/, '')
+ } else {
+ path = url.replace(/^([^:]+:)?\/\/([^:\/]+)(:\d*)?\//, '/')
}
+ return decodeURIComponent(path)
}
- if (bestMatch.score > 0) {
- return bestMatch;
- } else {
- return null;
- }
- };
-
- numberOfMatchingSegments = function(path1, path2) {
- var comps1, comps2, eqCount, len;
- path1 = path1.replace(/^\/+/, '').toLowerCase();
- path2 = path2.replace(/^\/+/, '').toLowerCase();
- if (path1 === path2) {
- return 10000;
- }
- comps1 = path1.split('/').reverse();
- comps2 = path2.split('/').reverse();
- len = Math.min(comps1.length, comps2.length);
- eqCount = 0;
- while (eqCount < len && comps1[eqCount] === comps2[eqCount]) {
- ++eqCount;
+
+ pickBestMatch = function (path, objects, pathFunc) {
+ var bestMatch, object, score, _i, _len
+ bestMatch = {
+ score: 0,
+ }
+ for (_i = 0, _len = objects.length; _i < _len; _i++) {
+ object = objects[_i]
+ score = numberOfMatchingSegments(path, pathFunc(object))
+ if (score > bestMatch.score) {
+ bestMatch = {
+ object: object,
+ score: score,
+ }
+ }
+ }
+ if (bestMatch.score > 0) {
+ return bestMatch
+ } else {
+ return null
+ }
}
- return eqCount;
- };
-
- pathsMatch = function(path1, path2) {
- return numberOfMatchingSegments(path1, path2) > 0;
- };
-
- IMAGE_STYLES = [
- {
- selector: 'background',
- styleNames: ['backgroundImage']
- }, {
- selector: 'border',
- styleNames: ['borderImage', 'webkitBorderImage', 'MozBorderImage']
+
+ numberOfMatchingSegments = function (path1, path2) {
+ var comps1, comps2, eqCount, len
+ path1 = path1.replace(/^\/+/, '').toLowerCase()
+ path2 = path2.replace(/^\/+/, '').toLowerCase()
+ if (path1 === path2) {
+ return 10000
+ }
+ comps1 = path1.split('/').reverse()
+ comps2 = path2.split('/').reverse()
+ len = Math.min(comps1.length, comps2.length)
+ eqCount = 0
+ while (eqCount < len && comps1[eqCount] === comps2[eqCount]) {
+ ++eqCount
+ }
+ return eqCount
}
- ];
-
- exports.Reloader = Reloader = (function() {
- function Reloader(window, console, Timer) {
- this.window = window;
- this.console = console;
- this.Timer = Timer;
- this.document = this.window.document;
- this.importCacheWaitPeriod = 200;
- this.plugins = [];
+
+ pathsMatch = function (path1, path2) {
+ return numberOfMatchingSegments(path1, path2) > 0
}
- Reloader.prototype.addPlugin = function(plugin) {
- return this.plugins.push(plugin);
- };
+ IMAGE_STYLES = [
+ {
+ selector: 'background',
+ styleNames: ['backgroundImage'],
+ }, {
+ selector: 'border',
+ styleNames: ['borderImage', 'webkitBorderImage', 'MozBorderImage'],
+ },
+ ]
+
+ exports.Reloader = Reloader = (function () {
+ function Reloader (window, console, Timer) {
+ this.window = window
+ this.console = console
+ this.Timer = Timer
+ this.document = this.window.document
+ this.importCacheWaitPeriod = 200
+ this.plugins = []
+ }
- Reloader.prototype.analyze = function(callback) {
- return results;
- };
+ Reloader.prototype.addPlugin = function (plugin) {
+ return this.plugins.push(plugin)
+ }
- Reloader.prototype.reload = function(path, options) {
- var plugin, _base, _i, _len, _ref;
- this.options = options;
- if ((_base = this.options).stylesheetReloadTimeout == null) {
- _base.stylesheetReloadTimeout = 15000;
+ Reloader.prototype.analyze = function (callback) {
+ return results
}
- _ref = this.plugins;
- for (_i = 0, _len = _ref.length; _i < _len; _i++) {
- plugin = _ref[_i];
- if (plugin.reload && plugin.reload(path, options)) {
- return;
+
+ Reloader.prototype.reload = function (path, options) {
+ var plugin, _base, _i, _len, _ref
+ this.options = options
+ if ((_base = this.options).stylesheetReloadTimeout == null) {
+ _base.stylesheetReloadTimeout = 15000
}
- }
- if (options.liveCSS) {
- if (path.match(/\.css$/i)) {
- if (this.reloadStylesheet(path)) {
- return;
+ _ref = this.plugins
+ for (_i = 0, _len = _ref.length; _i < _len; _i++) {
+ plugin = _ref[_i]
+ if (plugin.reload && plugin.reload(path, options)) {
+ return
}
}
- }
- if (options.liveImg) {
- if (path.match(/\.(jpe?g|png|gif)$/i)) {
- this.reloadImages(path);
- return;
+ if (options.liveCSS) {
+ if (path.match(/\.css$/i)) {
+ if (this.reloadStylesheet(path)) {
+ return
+ }
+ }
}
+ if (options.liveImg) {
+ if (path.match(/\.(jpe?g|png|gif)$/i)) {
+ this.reloadImages(path)
+ return
+ }
+ }
+ return this.reloadPage()
}
- return this.reloadPage();
- };
- Reloader.prototype.reloadPage = function() {
- return this.window.document.location.reload();
- };
+ Reloader.prototype.reloadPage = function () {
+ return this.window.document.location.reload()
+ }
- Reloader.prototype.reloadImages = function(path) {
- var expando, img, selector, styleNames, styleSheet, _i, _j, _k, _l, _len, _len1, _len2, _len3, _ref, _ref1, _ref2, _ref3, _results;
- expando = this.generateUniqueString();
- _ref = this.document.images;
- for (_i = 0, _len = _ref.length; _i < _len; _i++) {
- img = _ref[_i];
- if (pathsMatch(path, pathFromUrl(img.src))) {
- img.src = this.generateCacheBustUrl(img.src, expando);
+ Reloader.prototype.reloadImages = function (path) {
+ var expando, img, selector, styleNames, styleSheet, _i, _j, _k, _l, _len, _len1, _len2, _len3, _ref, _ref1, _ref2, _ref3, _results
+ expando = this.generateUniqueString()
+ _ref = this.document.images
+ for (_i = 0, _len = _ref.length; _i < _len; _i++) {
+ img = _ref[_i]
+ if (pathsMatch(path, pathFromUrl(img.src))) {
+ img.src = this.generateCacheBustUrl(img.src, expando)
+ }
}
- }
- if (this.document.querySelectorAll) {
- for (_j = 0, _len1 = IMAGE_STYLES.length; _j < _len1; _j++) {
- _ref1 = IMAGE_STYLES[_j], selector = _ref1.selector, styleNames = _ref1.styleNames;
- _ref2 = this.document.querySelectorAll("[style*=" + selector + "]");
- for (_k = 0, _len2 = _ref2.length; _k < _len2; _k++) {
- img = _ref2[_k];
- this.reloadStyleImages(img.style, styleNames, path, expando);
+ if (this.document.querySelectorAll) {
+ for (_j = 0, _len1 = IMAGE_STYLES.length; _j < _len1; _j++) {
+ _ref1 = IMAGE_STYLES[_j], selector = _ref1.selector, styleNames = _ref1.styleNames
+ _ref2 = this.document.querySelectorAll('[style*=' + selector + ']')
+ for (_k = 0, _len2 = _ref2.length; _k < _len2; _k++) {
+ img = _ref2[_k]
+ this.reloadStyleImages(img.style, styleNames, path, expando)
+ }
}
}
- }
- if (this.document.styleSheets) {
- _ref3 = this.document.styleSheets;
- _results = [];
- for (_l = 0, _len3 = _ref3.length; _l < _len3; _l++) {
- styleSheet = _ref3[_l];
- _results.push(this.reloadStylesheetImages(styleSheet, path, expando));
+ if (this.document.styleSheets) {
+ _ref3 = this.document.styleSheets
+ _results = []
+ for (_l = 0, _len3 = _ref3.length; _l < _len3; _l++) {
+ styleSheet = _ref3[_l]
+ _results.push(this.reloadStylesheetImages(styleSheet, path, expando))
+ }
+ return _results
}
- return _results;
- }
- };
-
- Reloader.prototype.reloadStylesheetImages = function(styleSheet, path, expando) {
- var e, rule, rules, styleNames, _i, _j, _len, _len1;
- try {
- rules = styleSheet != null ? styleSheet.cssRules : void 0;
- } catch (_error) {
- e = _error;
}
- if (!rules) {
- return;
- }
- for (_i = 0, _len = rules.length; _i < _len; _i++) {
- rule = rules[_i];
- switch (rule.type) {
- case CSSRule.IMPORT_RULE:
- this.reloadStylesheetImages(rule.styleSheet, path, expando);
- break;
- case CSSRule.STYLE_RULE:
- for (_j = 0, _len1 = IMAGE_STYLES.length; _j < _len1; _j++) {
- styleNames = IMAGE_STYLES[_j].styleNames;
- this.reloadStyleImages(rule.style, styleNames, path, expando);
- }
- break;
- case CSSRule.MEDIA_RULE:
- this.reloadStylesheetImages(rule, path, expando);
+
+ Reloader.prototype.reloadStylesheetImages = function (styleSheet, path, expando) {
+ var e, rule, rules, styleNames, _i, _j, _len, _len1
+ try {
+ rules = styleSheet != null ? styleSheet.cssRules : void 0
+ } catch (_error) {
+ e = _error
+ }
+ if (!rules) {
+ return
+ }
+ for (_i = 0, _len = rules.length; _i < _len; _i++) {
+ rule = rules[_i]
+ switch (rule.type) {
+ case CSSRule.IMPORT_RULE:
+ this.reloadStylesheetImages(rule.styleSheet, path, expando)
+ break
+ case CSSRule.STYLE_RULE:
+ for (_j = 0, _len1 = IMAGE_STYLES.length; _j < _len1; _j++) {
+ styleNames = IMAGE_STYLES[_j].styleNames
+ this.reloadStyleImages(rule.style, styleNames, path, expando)
+ }
+ break
+ case CSSRule.MEDIA_RULE:
+ this.reloadStylesheetImages(rule, path, expando)
+ }
}
}
- };
-
- Reloader.prototype.reloadStyleImages = function(style, styleNames, path, expando) {
- var newValue, styleName, value, _i, _len;
- for (_i = 0, _len = styleNames.length; _i < _len; _i++) {
- styleName = styleNames[_i];
- value = style[styleName];
- if (typeof value === 'string') {
- newValue = value.replace(/\burl\s*\(([^)]*)\)/, (function(_this) {
- return function(match, src) {
- if (pathsMatch(path, pathFromUrl(src))) {
- return "url(" + (_this.generateCacheBustUrl(src, expando)) + ")";
- } else {
- return match;
+
+ Reloader.prototype.reloadStyleImages = function (style, styleNames, path, expando) {
+ var newValue, styleName, value, _i, _len
+ for (_i = 0, _len = styleNames.length; _i < _len; _i++) {
+ styleName = styleNames[_i]
+ value = style[styleName]
+ if (typeof value === 'string') {
+ newValue = value.replace(/\burl\s*\(([^)]*)\)/, (function (_this) {
+ return function (match, src) {
+ if (pathsMatch(path, pathFromUrl(src))) {
+ return 'url(' + (_this.generateCacheBustUrl(src, expando)) + ')'
+ } else {
+ return match
+ }
}
- };
- })(this));
- if (newValue !== value) {
- style[styleName] = newValue;
+ })(this))
+ if (newValue !== value) {
+ style[styleName] = newValue
+ }
}
}
}
- };
-
- Reloader.prototype.reloadStylesheet = function(path) {
- var imported, link, links, match, style, _i, _j, _k, _l, _len, _len1, _len2, _len3, _ref, _ref1;
- links = (function() {
- var _i, _len, _ref, _results;
- _ref = this.document.getElementsByTagName('link');
- _results = [];
+
+ Reloader.prototype.reloadStylesheet = function (path) {
+ var imported, link, links, match, style, _i, _j, _k, _l, _len, _len1, _len2, _len3, _ref, _ref1
+ links = (function () {
+ var _i, _len, _ref, _results
+ _ref = this.document.getElementsByTagName('link')
+ _results = []
+ for (_i = 0, _len = _ref.length; _i < _len; _i++) {
+ link = _ref[_i]
+ if (link.rel.match(/^stylesheet$/i) && !link.__LiveReload_pendingRemoval) {
+ _results.push(link)
+ }
+ }
+ return _results
+ }).call(this)
+ imported = []
+ _ref = this.document.getElementsByTagName('style')
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
- link = _ref[_i];
- if (link.rel.match(/^stylesheet$/i) && !link.__LiveReload_pendingRemoval) {
- _results.push(link);
+ style = _ref[_i]
+ if (style.sheet) {
+ this.collectImportedStylesheets(style, style.sheet, imported)
}
}
- return _results;
- }).call(this);
- imported = [];
- _ref = this.document.getElementsByTagName('style');
- for (_i = 0, _len = _ref.length; _i < _len; _i++) {
- style = _ref[_i];
- if (style.sheet) {
- this.collectImportedStylesheets(style, style.sheet, imported);
+ for (_j = 0, _len1 = links.length; _j < _len1; _j++) {
+ link = links[_j]
+ this.collectImportedStylesheets(link, link.sheet, imported)
}
- }
- for (_j = 0, _len1 = links.length; _j < _len1; _j++) {
- link = links[_j];
- this.collectImportedStylesheets(link, link.sheet, imported);
- }
- if (this.window.StyleFix && this.document.querySelectorAll) {
- _ref1 = this.document.querySelectorAll('style[data-href]');
- for (_k = 0, _len2 = _ref1.length; _k < _len2; _k++) {
- style = _ref1[_k];
- links.push(style);
+ if (this.window.StyleFix && this.document.querySelectorAll) {
+ _ref1 = this.document.querySelectorAll('style[data-href]')
+ for (_k = 0, _len2 = _ref1.length; _k < _len2; _k++) {
+ style = _ref1[_k]
+ links.push(style)
+ }
}
- }
- this.console.log("LiveReload found " + links.length + " LINKed stylesheets, " + imported.length + " @imported stylesheets");
- match = pickBestMatch(path, links.concat(imported), (function(_this) {
- return function(l) {
- return pathFromUrl(_this.linkHref(l));
- };
- })(this));
- if (match) {
- if (match.object.rule) {
- this.console.log("LiveReload is reloading imported stylesheet: " + match.object.href);
- this.reattachImportedRule(match.object);
+ this.console.log('LiveReload found ' + links.length + ' LINKed stylesheets, ' + imported.length + ' @imported stylesheets')
+ match = pickBestMatch(path, links.concat(imported), (function (_this) {
+ return function (l) {
+ return pathFromUrl(_this.linkHref(l))
+ }
+ })(this))
+ if (match) {
+ if (match.object.rule) {
+ this.console.log('LiveReload is reloading imported stylesheet: ' + match.object.href)
+ this.reattachImportedRule(match.object)
+ } else {
+ this.console.log('LiveReload is reloading stylesheet: ' + (this.linkHref(match.object)))
+ this.reattachStylesheetLink(match.object)
+ }
} else {
- this.console.log("LiveReload is reloading stylesheet: " + (this.linkHref(match.object)));
- this.reattachStylesheetLink(match.object);
- }
- } else {
- this.console.log("LiveReload will reload all stylesheets because path '" + path + "' did not match any specific one");
- for (_l = 0, _len3 = links.length; _l < _len3; _l++) {
- link = links[_l];
- this.reattachStylesheetLink(link);
- }
- }
- return true;
- };
-
- Reloader.prototype.collectImportedStylesheets = function(link, styleSheet, result) {
- var e, index, rule, rules, _i, _len;
- try {
- rules = styleSheet != null ? styleSheet.cssRules : void 0;
- } catch (_error) {
- e = _error;
- }
- if (rules && rules.length) {
- for (index = _i = 0, _len = rules.length; _i < _len; index = ++_i) {
- rule = rules[index];
- switch (rule.type) {
- case CSSRule.CHARSET_RULE:
- continue;
- case CSSRule.IMPORT_RULE:
- result.push({
- link: link,
- rule: rule,
- index: index,
- href: rule.href
- });
- this.collectImportedStylesheets(link, rule.styleSheet, result);
- break;
- default:
- break;
+ this.console.log("LiveReload will reload all stylesheets because path '" + path + "' did not match any specific one")
+ for (_l = 0, _len3 = links.length; _l < _len3; _l++) {
+ link = links[_l]
+ this.reattachStylesheetLink(link)
}
}
+ return true
}
- };
-
- Reloader.prototype.waitUntilCssLoads = function(clone, func) {
- var callbackExecuted, executeCallback, poll;
- callbackExecuted = false;
- executeCallback = (function(_this) {
- return function() {
- if (callbackExecuted) {
- return;
- }
- callbackExecuted = true;
- return func();
- };
- })(this);
- clone.onload = (function(_this) {
- return function() {
- _this.console.log("LiveReload: the new stylesheet has finished loading");
- _this.knownToSupportCssOnLoad = true;
- return executeCallback();
- };
- })(this);
- if (!this.knownToSupportCssOnLoad) {
- (poll = (function(_this) {
- return function() {
- if (clone.sheet) {
- _this.console.log("LiveReload is polling until the new CSS finishes loading...");
- return executeCallback();
- } else {
- return _this.Timer.start(50, poll);
+
+ Reloader.prototype.collectImportedStylesheets = function (link, styleSheet, result) {
+ var e, index, rule, rules, _i, _len
+ try {
+ rules = styleSheet != null ? styleSheet.cssRules : void 0
+ } catch (_error) {
+ e = _error
+ }
+ if (rules && rules.length) {
+ for (index = _i = 0, _len = rules.length; _i < _len; index = ++_i) {
+ rule = rules[index]
+ switch (rule.type) {
+ case CSSRule.CHARSET_RULE:
+ continue
+ case CSSRule.IMPORT_RULE:
+ result.push({
+ link: link,
+ rule: rule,
+ index: index,
+ href: rule.href,
+ })
+ this.collectImportedStylesheets(link, rule.styleSheet, result)
+ break
+ default:
+ break
}
- };
- })(this))();
+ }
+ }
}
- return this.Timer.start(this.options.stylesheetReloadTimeout, executeCallback);
- };
- Reloader.prototype.linkHref = function(link) {
- return link.href || link.getAttribute('data-href');
- };
-
- Reloader.prototype.reattachStylesheetLink = function(link) {
- var clone, parent;
- if (link.__LiveReload_pendingRemoval) {
- return;
- }
- link.__LiveReload_pendingRemoval = true;
- if (link.tagName === 'STYLE') {
- clone = this.document.createElement('link');
- clone.rel = 'stylesheet';
- clone.media = link.media;
- clone.disabled = link.disabled;
- } else {
- clone = link.cloneNode(false);
- }
- clone.href = this.generateCacheBustUrl(this.linkHref(link));
- parent = link.parentNode;
- if (parent.lastChild === link) {
- parent.appendChild(clone);
- } else {
- parent.insertBefore(clone, link.nextSibling);
- }
- return this.waitUntilCssLoads(clone, (function(_this) {
- return function() {
- var additionalWaitingTime;
- if (/AppleWebKit/.test(navigator.userAgent)) {
- additionalWaitingTime = 5;
- } else {
- additionalWaitingTime = 200;
- }
- return _this.Timer.start(additionalWaitingTime, function() {
- var _ref;
- if (!link.parentNode) {
- return;
+ Reloader.prototype.waitUntilCssLoads = function (clone, func) {
+ var callbackExecuted, executeCallback, poll
+ callbackExecuted = false
+ executeCallback = (function (_this) {
+ return function () {
+ if (callbackExecuted) {
+ return
}
- link.parentNode.removeChild(link);
- clone.onreadystatechange = null;
- return (_ref = _this.window.StyleFix) != null ? _ref.link(clone) : void 0;
- });
- };
- })(this));
- };
-
- Reloader.prototype.reattachImportedRule = function(_arg) {
- var href, index, link, media, newRule, parent, rule, tempLink;
- rule = _arg.rule, index = _arg.index, link = _arg.link;
- parent = rule.parentStyleSheet;
- href = this.generateCacheBustUrl(rule.href);
- media = rule.media.length ? [].join.call(rule.media, ', ') : '';
- newRule = "@import url(\"" + href + "\") " + media + ";";
- rule.__LiveReload_newHref = href;
- tempLink = this.document.createElement("link");
- tempLink.rel = 'stylesheet';
- tempLink.href = href;
- tempLink.__LiveReload_pendingRemoval = true;
- if (link.parentNode) {
- link.parentNode.insertBefore(tempLink, link);
- }
- return this.Timer.start(this.importCacheWaitPeriod, (function(_this) {
- return function() {
- if (tempLink.parentNode) {
- tempLink.parentNode.removeChild(tempLink);
+ callbackExecuted = true
+ return func()
}
- if (rule.__LiveReload_newHref !== href) {
- return;
+ })(this)
+ clone.onload = (function (_this) {
+ return function () {
+ _this.console.log('LiveReload: the new stylesheet has finished loading')
+ _this.knownToSupportCssOnLoad = true
+ return executeCallback()
}
- parent.insertRule(newRule, index);
- parent.deleteRule(index + 1);
- rule = parent.cssRules[index];
- rule.__LiveReload_newHref = href;
- return _this.Timer.start(_this.importCacheWaitPeriod, function() {
- if (rule.__LiveReload_newHref !== href) {
- return;
+ })(this)
+ if (!this.knownToSupportCssOnLoad) {
+ (poll = (function (_this) {
+ return function () {
+ if (clone.sheet) {
+ _this.console.log('LiveReload is polling until the new CSS finishes loading...')
+ return executeCallback()
+ } else {
+ return _this.Timer.start(50, poll)
+ }
}
- parent.insertRule(newRule, index);
- return parent.deleteRule(index + 1);
- });
- };
- })(this));
- };
-
- Reloader.prototype.generateUniqueString = function() {
- return 'livereload=' + Date.now();
- };
-
- Reloader.prototype.generateCacheBustUrl = function(url, expando) {
- var hash, oldParams, originalUrl, params, _ref;
- if (expando == null) {
- expando = this.generateUniqueString();
- }
- _ref = splitUrl(url), url = _ref.url, hash = _ref.hash, oldParams = _ref.params;
- if (this.options.overrideURL) {
- if (url.indexOf(this.options.serverURL) < 0) {
- originalUrl = url;
- url = this.options.serverURL + this.options.overrideURL + "?url=" + encodeURIComponent(url);
- this.console.log("LiveReload is overriding source URL " + originalUrl + " with " + url);
+ })(this))()
}
+ return this.Timer.start(this.options.stylesheetReloadTimeout, executeCallback)
+ }
+
+ Reloader.prototype.linkHref = function (link) {
+ return link.href || link.getAttribute('data-href')
}
- params = oldParams.replace(/(\?|&)livereload=(\d+)/, function(match, sep) {
- return "" + sep + expando;
- });
- if (params === oldParams) {
- if (oldParams.length === 0) {
- params = "?" + expando;
+
+ Reloader.prototype.reattachStylesheetLink = function (link) {
+ var clone, parent
+ if (link.__LiveReload_pendingRemoval) {
+ return
+ }
+ link.__LiveReload_pendingRemoval = true
+ if (link.tagName === 'STYLE') {
+ clone = this.document.createElement('link')
+ clone.rel = 'stylesheet'
+ clone.media = link.media
+ clone.disabled = link.disabled
+ } else {
+ clone = link.cloneNode(false)
+ }
+ clone.href = this.generateCacheBustUrl(this.linkHref(link))
+ parent = link.parentNode
+ if (parent.lastChild === link) {
+ parent.appendChild(clone)
} else {
- params = "" + oldParams + "&" + expando;
+ parent.insertBefore(clone, link.nextSibling)
}
+ return this.waitUntilCssLoads(clone, (function (_this) {
+ return function () {
+ var additionalWaitingTime
+ if (/AppleWebKit/.test(navigator.userAgent)) {
+ additionalWaitingTime = 5
+ } else {
+ additionalWaitingTime = 200
+ }
+ return _this.Timer.start(additionalWaitingTime, function () {
+ var _ref
+ if (!link.parentNode) {
+ return
+ }
+ link.parentNode.removeChild(link)
+ clone.onreadystatechange = null
+ return (_ref = _this.window.StyleFix) != null ? _ref.link(clone) : void 0
+ })
+ }
+ })(this))
}
- return url + params + hash;
- };
- return Reloader;
+ Reloader.prototype.reattachImportedRule = function (_arg) {
+ var href, index, link, media, newRule, parent, rule, tempLink
+ rule = _arg.rule, index = _arg.index, link = _arg.link
+ parent = rule.parentStyleSheet
+ href = this.generateCacheBustUrl(rule.href)
+ media = rule.media.length ? [].join.call(rule.media, ', ') : ''
+ newRule = '@import url("' + href + '") ' + media + ';'
+ rule.__LiveReload_newHref = href
+ tempLink = this.document.createElement('link')
+ tempLink.rel = 'stylesheet'
+ tempLink.href = href
+ tempLink.__LiveReload_pendingRemoval = true
+ if (link.parentNode) {
+ link.parentNode.insertBefore(tempLink, link)
+ }
+ return this.Timer.start(this.importCacheWaitPeriod, (function (_this) {
+ return function () {
+ if (tempLink.parentNode) {
+ tempLink.parentNode.removeChild(tempLink)
+ }
+ if (rule.__LiveReload_newHref !== href) {
+ return
+ }
+ parent.insertRule(newRule, index)
+ parent.deleteRule(index + 1)
+ rule = parent.cssRules[index]
+ rule.__LiveReload_newHref = href
+ return _this.Timer.start(_this.importCacheWaitPeriod, function () {
+ if (rule.__LiveReload_newHref !== href) {
+ return
+ }
+ parent.insertRule(newRule, index)
+ return parent.deleteRule(index + 1)
+ })
+ }
+ })(this))
+ }
- })();
+ Reloader.prototype.generateUniqueString = function () {
+ return 'livereload=' + Date.now()
+ }
-}).call(this);
+ Reloader.prototype.generateCacheBustUrl = function (url, expando) {
+ var hash, oldParams, originalUrl, params, _ref
+ if (expando == null) {
+ expando = this.generateUniqueString()
+ }
+ _ref = splitUrl(url), url = _ref.url, hash = _ref.hash, oldParams = _ref.params
+ if (this.options.overrideURL) {
+ if (url.indexOf(this.options.serverURL) < 0) {
+ originalUrl = url
+ url = this.options.serverURL + this.options.overrideURL + '?url=' + encodeURIComponent(url)
+ this.console.log('LiveReload is overriding source URL ' + originalUrl + ' with ' + url)
+ }
+ }
+ params = oldParams.replace(/(\?|&)livereload=(\d+)/, function (match, sep) {
+ return '' + sep + expando
+ })
+ if (params === oldParams) {
+ if (oldParams.length === 0) {
+ params = '?' + expando
+ } else {
+ params = '' + oldParams + '&' + expando
+ }
+ }
+ return url + params + hash
+ }
-},{}],8:[function(require,module,exports){
-(function() {
- var CustomEvents, LiveReload, k;
+ return Reloader
+ })()
+ }).call(this)
+}, {}], 8: [function (require, module, exports) {
+ (function () {
+ var CustomEvents, LiveReload, k
- CustomEvents = require('./customevents');
+ CustomEvents = require('./customevents')
- LiveReload = window.LiveReload = new (require('./livereload').LiveReload)(window);
+ LiveReload = window.LiveReload = new (require('./livereload').LiveReload)(window)
- for (k in window) {
- if (k.match(/^LiveReloadPlugin/)) {
- LiveReload.addPlugin(window[k]);
- }
- }
-
- LiveReload.addPlugin(require('./less'));
-
- LiveReload.on('shutdown', function() {
- return delete window.LiveReload;
- });
-
- LiveReload.on('connect', function() {
- return CustomEvents.fire(document, 'LiveReloadConnect');
- });
-
- LiveReload.on('disconnect', function() {
- return CustomEvents.fire(document, 'LiveReloadDisconnect');
- });
-
- CustomEvents.bind(document, 'LiveReloadShutDown', function() {
- return LiveReload.shutDown();
- });
-
-}).call(this);
-
-},{"./customevents":2,"./less":3,"./livereload":4}],9:[function(require,module,exports){
-(function() {
- var Timer;
-
- exports.Timer = Timer = (function() {
- function Timer(func) {
- this.func = func;
- this.running = false;
- this.id = null;
- this._handler = (function(_this) {
- return function() {
- _this.running = false;
- _this.id = null;
- return _this.func();
- };
- })(this);
+ for (k in window) {
+ if (k.match(/^LiveReloadPlugin/)) {
+ LiveReload.addPlugin(window[k])
+ }
}
- Timer.prototype.start = function(timeout) {
- if (this.running) {
- clearTimeout(this.id);
- }
- this.id = setTimeout(this._handler, timeout);
- return this.running = true;
- };
-
- Timer.prototype.stop = function() {
- if (this.running) {
- clearTimeout(this.id);
- this.running = false;
- return this.id = null;
+ LiveReload.addPlugin(require('./less'))
+
+ LiveReload.on('shutdown', function () {
+ return delete window.LiveReload
+ })
+
+ LiveReload.on('connect', function () {
+ return CustomEvents.fire(document, 'LiveReloadConnect')
+ })
+
+ LiveReload.on('disconnect', function () {
+ return CustomEvents.fire(document, 'LiveReloadDisconnect')
+ })
+
+ CustomEvents.bind(document, 'LiveReloadShutDown', function () {
+ return LiveReload.shutDown()
+ })
+ }).call(this)
+}, {'./customevents': 2, './less': 3, './livereload': 4}], 9: [function (require, module, exports) {
+ (function () {
+ var Timer
+
+ exports.Timer = Timer = (function () {
+ function Timer (func) {
+ this.func = func
+ this.running = false
+ this.id = null
+ this._handler = (function (_this) {
+ return function () {
+ _this.running = false
+ _this.id = null
+ return _this.func()
+ }
+ })(this)
}
- };
- return Timer;
-
- })();
+ Timer.prototype.start = function (timeout) {
+ if (this.running) {
+ clearTimeout(this.id)
+ }
+ this.id = setTimeout(this._handler, timeout)
+ return this.running = true
+ }
- Timer.start = function(timeout, func) {
- return setTimeout(func, timeout);
- };
+ Timer.prototype.stop = function () {
+ if (this.running) {
+ clearTimeout(this.id)
+ this.running = false
+ return this.id = null
+ }
+ }
-}).call(this);
+ return Timer
+ })()
-},{}]},{},[8]); \ No newline at end of file
+ Timer.start = function (timeout, func) {
+ return setTimeout(func, timeout)
+ }
+ }).call(this)
+}, {}]}, {}, [8])
diff --git a/app/scripts/contentscript.js b/app/scripts/contentscript.js
index 43ae5bc98..ad90059b7 100644
--- a/app/scripts/contentscript.js
+++ b/app/scripts/contentscript.js
@@ -2,12 +2,10 @@ const LocalMessageDuplexStream = require('./lib/local-message-stream.js')
const PortStream = require('./lib/port-stream.js')
const ObjectMultiplex = require('./lib/obj-multiplex')
-
-
// inject in-page script
var scriptTag = document.createElement('script')
scriptTag.src = chrome.extension.getURL('scripts/inpage.js')
-scriptTag.onload = function() { this.parentNode.removeChild(this) }
+scriptTag.onload = function () { this.parentNode.removeChild(this) }
var container = document.head || document.documentElement
// append as first child
container.insertBefore(scriptTag, container.children[0])
@@ -32,7 +30,7 @@ mx.pipe(pageStream)
var reloadStream = mx.createStream('reload')
reloadStream.on('error', console.error.bind(console))
-// if we lose connection with the plugin, trigger tab refresh
-pluginStream.on('close', function(){
+// if we lose connection with the plugin, trigger tab refresh
+pluginStream.on('close', function () {
reloadStream.write({ method: 'reset' })
-}) \ No newline at end of file
+})
diff --git a/app/scripts/inpage.js b/app/scripts/inpage.js
index b8532747e..e6f4078c8 100644
--- a/app/scripts/inpage.js
+++ b/app/scripts/inpage.js
@@ -8,7 +8,6 @@ restoreContextAfterImports()
// remove from window
delete window.Web3
-
//
// setup plugin communication
//
@@ -27,7 +26,7 @@ var inpageProvider = new MetamaskInpageProvider(metamaskStream)
//
var web3 = new Web3(inpageProvider)
-web3.setProvider = function(){
+web3.setProvider = function () {
console.log('MetaMask - overrode web3.setProvider')
}
console.log('MetaMask - injected web3')
@@ -40,7 +39,7 @@ var reloadStream = inpageProvider.multiStream.createStream('reload')
setupDappAutoReload(web3, reloadStream)
// set web3 defaultAcount
-inpageProvider.publicConfigStore.subscribe(function(state){
+inpageProvider.publicConfigStore.subscribe(function (state) {
web3.eth.defaultAccount = state.selectedAddress
})
@@ -51,13 +50,13 @@ inpageProvider.publicConfigStore.subscribe(function(state){
// need to make sure we aren't affected by overlapping namespaces
// and that we dont affect the app with our namespace
// mostly a fix for web3's BigNumber if AMD's "define" is defined...
-var __define = undefined
+var __define
-function cleanContextForImports(){
+function cleanContextForImports () {
__define = global.define
delete global.define
}
-function restoreContextAfterImports(){
+function restoreContextAfterImports () {
global.define = __define
}
diff --git a/app/scripts/lib/auto-faucet.js b/app/scripts/lib/auto-faucet.js
index b347add44..59cf0ec20 100644
--- a/app/scripts/lib/auto-faucet.js
+++ b/app/scripts/lib/auto-faucet.js
@@ -1,11 +1,9 @@
var uri = 'https://faucet.metamask.io/'
-module.exports = function(address) {
-
+module.exports = function (address) {
var http = new XMLHttpRequest()
var data = address
http.open('POST', uri, true)
http.setRequestHeader('Content-type', 'application/rawdata')
http.send(data)
-
}
diff --git a/app/scripts/lib/auto-reload.js b/app/scripts/lib/auto-reload.js
index 95a744b2c..b45f02009 100644
--- a/app/scripts/lib/auto-reload.js
+++ b/app/scripts/lib/auto-reload.js
@@ -3,13 +3,11 @@ const ensnare = require('./ensnare.js')
module.exports = setupDappAutoReload
-
-function setupDappAutoReload(web3, controlStream){
-
+function setupDappAutoReload (web3, controlStream) {
// export web3 as a global, checking for usage
var pageIsUsingWeb3 = false
var resetWasRequested = false
- global.web3 = ensnare(web3, once(function(){
+ global.web3 = ensnare(web3, once(function () {
// if web3 usage happened after a reset request, trigger reset late
if (resetWasRequested) return triggerReset()
// mark web3 as used
@@ -19,7 +17,7 @@ function setupDappAutoReload(web3, controlStream){
}))
// listen for reset requests from metamask
- controlStream.once('data', function(){
+ controlStream.once('data', function () {
resetWasRequested = true
// ignore if web3 was not used
if (!pageIsUsingWeb3) return
@@ -28,10 +26,9 @@ function setupDappAutoReload(web3, controlStream){
})
// reload the page
- function triggerReset(){
- setTimeout(function(){
+ function triggerReset () {
+ setTimeout(function () {
global.location.reload()
}, 500)
}
-
-} \ No newline at end of file
+}
diff --git a/app/scripts/lib/config-manager.js b/app/scripts/lib/config-manager.js
index 24571748f..a3ff0bdfb 100644
--- a/app/scripts/lib/config-manager.js
+++ b/app/scripts/lib/config-manager.js
@@ -7,7 +7,6 @@ const STORAGE_KEY = 'metamask-config'
const TESTNET_RPC = MetamaskConfig.network.testnet
const MAINNET_RPC = MetamaskConfig.network.mainnet
-
/* The config-manager is a convenience object
* wrapping a pojo-migrator.
*
@@ -16,7 +15,7 @@ const MAINNET_RPC = MetamaskConfig.network.mainnet
* particular portions of the state.
*/
module.exports = ConfigManager
-function ConfigManager() {
+function ConfigManager () {
// ConfigManager is observable and will emit updates
this._subs = []
@@ -26,7 +25,7 @@ function ConfigManager() {
* getData(), which returns the app-consumable data object
* saveData(), which persists the app-consumable data object.
*/
- this.migrator = new Migrator({
+ this.migrator = new Migrator({
// Migrations must start at version 1 or later.
// They are objects with a `version` number
@@ -41,20 +40,20 @@ function ConfigManager() {
loadData: loadData,
// How to persist migrated config.
- setData: function(data) {
+ setData: function (data) {
window.localStorage[STORAGE_KEY] = JSON.stringify(data)
},
})
}
-ConfigManager.prototype.setConfig = function(config) {
+ConfigManager.prototype.setConfig = function (config) {
var data = this.migrator.getData()
data.config = config
this.setData(data)
this._emitUpdates(config)
}
-ConfigManager.prototype.getConfig = function() {
+ConfigManager.prototype.getConfig = function () {
var data = this.migrator.getData()
if ('config' in data) {
return data.config
@@ -62,12 +61,12 @@ ConfigManager.prototype.getConfig = function() {
return {
provider: {
type: 'testnet',
- }
+ },
}
}
}
-ConfigManager.prototype.setRpcTarget = function(rpcUrl) {
+ConfigManager.prototype.setRpcTarget = function (rpcUrl) {
var config = this.getConfig()
config.provider = {
type: 'rpc',
@@ -76,7 +75,7 @@ ConfigManager.prototype.setRpcTarget = function(rpcUrl) {
this.setConfig(config)
}
-ConfigManager.prototype.setProviderType = function(type) {
+ConfigManager.prototype.setProviderType = function (type) {
var config = this.getConfig()
config.provider = {
type: type,
@@ -84,7 +83,7 @@ ConfigManager.prototype.setProviderType = function(type) {
this.setConfig(config)
}
-ConfigManager.prototype.useEtherscanProvider = function() {
+ConfigManager.prototype.useEtherscanProvider = function () {
var config = this.getConfig()
config.provider = {
type: 'etherscan',
@@ -92,75 +91,75 @@ ConfigManager.prototype.useEtherscanProvider = function() {
this.setConfig(config)
}
-ConfigManager.prototype.getProvider = function() {
+ConfigManager.prototype.getProvider = function () {
var config = this.getConfig()
return config.provider
}
-ConfigManager.prototype.setData = function(data) {
+ConfigManager.prototype.setData = function (data) {
this.migrator.saveData(data)
}
-ConfigManager.prototype.getData = function() {
+ConfigManager.prototype.getData = function () {
return this.migrator.getData()
}
-ConfigManager.prototype.setWallet = function(wallet) {
+ConfigManager.prototype.setWallet = function (wallet) {
var data = this.migrator.getData()
data.wallet = wallet
this.setData(data)
}
-ConfigManager.prototype.getSelectedAccount = function() {
+ConfigManager.prototype.getSelectedAccount = function () {
var config = this.getConfig()
return config.selectedAccount
}
-ConfigManager.prototype.setSelectedAccount = function(address) {
+ConfigManager.prototype.setSelectedAccount = function (address) {
var config = this.getConfig()
config.selectedAccount = address
this.setConfig(config)
}
-ConfigManager.prototype.getWallet = function() {
+ConfigManager.prototype.getWallet = function () {
return this.migrator.getData().wallet
}
// Takes a boolean
-ConfigManager.prototype.setShowSeedWords = function(should) {
+ConfigManager.prototype.setShowSeedWords = function (should) {
var data = this.migrator.getData()
data.showSeedWords = should
this.setData(data)
}
-ConfigManager.prototype.getShouldShowSeedWords = function() {
+ConfigManager.prototype.getShouldShowSeedWords = function () {
var data = this.migrator.getData()
return data.showSeedWords
}
-ConfigManager.prototype.getCurrentRpcAddress = function() {
+ConfigManager.prototype.getCurrentRpcAddress = function () {
var provider = this.getProvider()
if (!provider) return null
- switch (provider.type) {
+ switch (provider.type) {
- case 'mainnet':
- return MAINNET_RPC
+ case 'mainnet':
+ return MAINNET_RPC
- case 'testnet':
- return TESTNET_RPC
+ case 'testnet':
+ return TESTNET_RPC
- default:
- return provider && provider.rpcTarget ? provider.rpcTarget : TESTNET_RPC
- }
+ default:
+ return provider && provider.rpcTarget ? provider.rpcTarget : TESTNET_RPC
+ }
}
-ConfigManager.prototype.clearWallet = function() {
+ConfigManager.prototype.clearWallet = function () {
var data = this.getConfig()
delete data.wallet
this.setData(data)
}
-ConfigManager.prototype.setData = function(data) {
+ConfigManager.prototype.setData = function (data) {
this.migrator.saveData(data)
}
@@ -168,7 +167,7 @@ ConfigManager.prototype.setData = function(data) {
// Tx
//
-ConfigManager.prototype.getTxList = function() {
+ConfigManager.prototype.getTxList = function () {
var data = this.migrator.getData()
if (data.transactions !== undefined) {
return data.transactions
@@ -177,45 +176,45 @@ ConfigManager.prototype.getTxList = function() {
}
}
-ConfigManager.prototype.unconfirmedTxs = function() {
+ConfigManager.prototype.unconfirmedTxs = function () {
var transactions = this.getTxList()
return transactions.filter(tx => tx.status === 'unconfirmed')
.reduce((result, tx) => { result[tx.id] = tx; return result }, {})
}
-ConfigManager.prototype._saveTxList = function(txList) {
+ConfigManager.prototype._saveTxList = function (txList) {
var data = this.migrator.getData()
data.transactions = txList
this.setData(data)
}
-ConfigManager.prototype.addTx = function(tx) {
+ConfigManager.prototype.addTx = function (tx) {
var transactions = this.getTxList()
transactions.push(tx)
this._saveTxList(transactions)
}
-ConfigManager.prototype.getTx = function(txId) {
+ConfigManager.prototype.getTx = function (txId) {
var transactions = this.getTxList()
var matching = transactions.filter(tx => tx.id === txId)
return matching.length > 0 ? matching[0] : null
}
-ConfigManager.prototype.confirmTx = function(txId) {
+ConfigManager.prototype.confirmTx = function (txId) {
this._setTxStatus(txId, 'confirmed')
}
-ConfigManager.prototype.rejectTx = function(txId) {
+ConfigManager.prototype.rejectTx = function (txId) {
this._setTxStatus(txId, 'rejected')
}
-ConfigManager.prototype._setTxStatus = function(txId, status) {
+ConfigManager.prototype._setTxStatus = function (txId, status) {
var tx = this.getTx(txId)
tx.status = status
this.updateTx(tx)
}
-ConfigManager.prototype.updateTx = function(tx) {
+ConfigManager.prototype.updateTx = function (tx) {
var transactions = this.getTxList()
var found, index
transactions.forEach((otherTx, i) => {
@@ -232,19 +231,19 @@ ConfigManager.prototype.updateTx = function(tx) {
// wallet nickname methods
-ConfigManager.prototype.getWalletNicknames = function() {
+ConfigManager.prototype.getWalletNicknames = function () {
var data = this.getData()
- let nicknames = ('walletNicknames' in data) ? data.walletNicknames : {}
+ const nicknames = ('walletNicknames' in data) ? data.walletNicknames : {}
return nicknames
}
-ConfigManager.prototype.nicknameForWallet = function(account) {
- let nicknames = this.getWalletNicknames()
+ConfigManager.prototype.nicknameForWallet = function (account) {
+ const nicknames = this.getWalletNicknames()
return nicknames[account]
}
-ConfigManager.prototype.setNicknameForWallet = function(account, nickname) {
- let nicknames = this.getWalletNicknames()
+ConfigManager.prototype.setNicknameForWallet = function (account, nickname) {
+ const nicknames = this.getWalletNicknames()
nicknames[account] = nickname
var data = this.getData()
data.walletNicknames = nicknames
@@ -253,37 +252,35 @@ ConfigManager.prototype.setNicknameForWallet = function(account, nickname) {
// observable
-ConfigManager.prototype.subscribe = function(fn){
+ConfigManager.prototype.subscribe = function (fn) {
this._subs.push(fn)
var unsubscribe = this.unsubscribe.bind(this, fn)
return unsubscribe
}
-ConfigManager.prototype.unsubscribe = function(fn){
+ConfigManager.prototype.unsubscribe = function (fn) {
var index = this._subs.indexOf(fn)
if (index !== -1) this._subs.splice(index, 1)
}
-ConfigManager.prototype._emitUpdates = function(state){
- this._subs.forEach(function(handler){
+ConfigManager.prototype._emitUpdates = function (state) {
+ this._subs.forEach(function (handler) {
handler(state)
})
}
-ConfigManager.prototype.setConfirmed = function(confirmed) {
+ConfigManager.prototype.setConfirmed = function (confirmed) {
var data = this.getData()
data.isConfirmed = confirmed
this.setData(data)
}
-ConfigManager.prototype.getConfirmed = function() {
+ConfigManager.prototype.getConfirmed = function () {
var data = this.getData()
return ('isConfirmed' in data) && data.isConfirmed
}
-
-function loadData() {
-
+function loadData () {
var oldData = getOldStyleData()
var newData
try {
@@ -298,14 +295,14 @@ function loadData() {
config: {
provider: {
type: 'testnet',
- }
- }
- }
- }, oldData ? oldData : null, newData ? newData : null)
+ },
+ },
+ },
+ }, oldData || null, newData || null)
return data
}
-function getOldStyleData() {
+function getOldStyleData () {
var config, wallet, seedWords
var result = {
diff --git a/app/scripts/lib/ensnare.js b/app/scripts/lib/ensnare.js
index b70330a5a..6100f7c79 100644
--- a/app/scripts/lib/ensnare.js
+++ b/app/scripts/lib/ensnare.js
@@ -1,21 +1,21 @@
module.exports = ensnare
// creates a proxy object that calls cb everytime the obj's properties/fns are accessed
-function ensnare(obj, cb){
+function ensnare (obj, cb) {
var proxy = {}
- Object.keys(obj).forEach(function(key){
+ Object.keys(obj).forEach(function (key) {
var val = obj[key]
switch (typeof val) {
case 'function':
- proxy[key] = function(){
+ proxy[key] = function () {
cb()
val.apply(obj, arguments)
}
return
default:
Object.defineProperty(proxy, key, {
- get: function(){ cb(); return obj[key] },
- set: function(val){ cb(); return obj[key] = val },
+ get: function () { cb(); return obj[key] },
+ set: function (val) { cb(); obj[key] = val; return val },
})
return
}
diff --git a/app/scripts/lib/id-management.js b/app/scripts/lib/id-management.js
index 5de1f438f..30ea866f4 100644
--- a/app/scripts/lib/id-management.js
+++ b/app/scripts/lib/id-management.js
@@ -4,19 +4,18 @@ const configManager = require('./config-manager-singleton')
module.exports = IdManagement
-
-function IdManagement(opts) {
+function IdManagement (opts) {
if (!opts) opts = {}
this.keyStore = opts.keyStore
this.derivedKey = opts.derivedKey
this.hdPathString = "m/44'/60'/0'/0"
- this.getAddresses = function(){
- return keyStore.getAddresses(this.hdPathString).map(function(address){ return '0x'+address })
+ this.getAddresses = function () {
+ return this.keyStore.getAddresses(this.hdPathString).map(function (address) { return '0x' + address })
}
- this.signTx = function(txParams){
+ this.signTx = function (txParams) {
// normalize values
txParams.to = ethUtil.addHexPrefix(txParams.to)
txParams.from = ethUtil.addHexPrefix(txParams.from)
@@ -44,34 +43,34 @@ function IdManagement(opts) {
this.signMsg = function (address, message) {
// sign message
- var privKeyHex = this.exportPrivateKey(address);
- var privKey = ethUtil.toBuffer(privKeyHex);
- var msgSig = ethUtil.ecsign(new Buffer(message.replace('0x',''), 'hex'), privKey);
- var rawMsgSig = ethUtil.bufferToHex(concatSig(msgSig.v, msgSig.r, msgSig.s));
- return rawMsgSig;
- };
+ var privKeyHex = this.exportPrivateKey(address)
+ var privKey = ethUtil.toBuffer(privKeyHex)
+ var msgSig = ethUtil.ecsign(new Buffer(message.replace('0x', ''), 'hex'), privKey)
+ var rawMsgSig = ethUtil.bufferToHex(concatSig(msgSig.v, msgSig.r, msgSig.s))
+ return rawMsgSig
+ }
- this.getSeed = function(){
+ this.getSeed = function () {
return this.keyStore.getSeed(this.derivedKey)
}
- this.exportPrivateKey = function(address) {
+ this.exportPrivateKey = function (address) {
var privKeyHex = ethUtil.addHexPrefix(this.keyStore.exportPrivateKey(address, this.derivedKey, this.hdPathString))
return privKeyHex
}
}
-function pad_with_zeroes(number, length){
- var my_string = '' + number;
- while (my_string.length < length) {
- my_string = '0' + my_string;
+function padWithZeroes (number, length) {
+ var myString = '' + number
+ while (myString.length < length) {
+ myString = '0' + myString
}
- return my_string;
+ return myString
}
-function concatSig(v, r, s) {
- r = pad_with_zeroes(ethUtil.fromSigned(r), 64)
- s = pad_with_zeroes(ethUtil.fromSigned(s), 64)
+function concatSig (v, r, s) {
+ r = padWithZeroes(ethUtil.fromSigned(r), 64)
+ s = padWithZeroes(ethUtil.fromSigned(s), 64)
r = ethUtil.stripHexPrefix(r.toString('hex'))
s = ethUtil.stripHexPrefix(s.toString('hex'))
v = ethUtil.stripHexPrefix(ethUtil.intToHex(v))
diff --git a/app/scripts/lib/idStore.js b/app/scripts/lib/idStore.js
index 8c736eac9..d9657dacf 100644
--- a/app/scripts/lib/idStore.js
+++ b/app/scripts/lib/idStore.js
@@ -1,10 +1,7 @@
const EventEmitter = require('events').EventEmitter
const inherits = require('util').inherits
-const Transaction = require('ethereumjs-tx')
const ethUtil = require('ethereumjs-util')
const LightwalletKeyStore = require('eth-lightwallet').keystore
-const LightwalletSigner = require('eth-lightwallet').signing
-const async = require('async')
const clone = require('clone')
const extend = require('xtend')
const createId = require('web3-provider-engine/util/random-id')
@@ -15,12 +12,10 @@ const messageManager = require('./message-manager')
const DEFAULT_RPC = 'https://testrpc.metamask.io/'
const IdManagement = require('./id-management')
-
module.exports = IdentityStore
-
inherits(IdentityStore, EventEmitter)
-function IdentityStore(opts = {}) {
+function IdentityStore (opts = {}) {
EventEmitter.call(this)
// we just use the ethStore to auto-add accounts
@@ -46,7 +41,7 @@ function IdentityStore(opts = {}) {
// public
//
-IdentityStore.prototype.createNewVault = function(password, entropy, cb){
+IdentityStore.prototype.createNewVault = function (password, entropy, cb) {
delete this._keyStore
configManager.clearWallet()
this._createIdmgmt(password, null, entropy, (err) => {
@@ -62,14 +57,14 @@ IdentityStore.prototype.createNewVault = function(password, entropy, cb){
})
}
-IdentityStore.prototype.recoverSeed = function(cb){
+IdentityStore.prototype.recoverSeed = function (cb) {
configManager.setShowSeedWords(true)
if (!this._idmgmt) return cb(new Error('Unauthenticated. Please sign in.'))
var seedWords = this._idmgmt.getSeed()
cb(null, seedWords)
}
-IdentityStore.prototype.recoverFromSeed = function(password, seed, cb){
+IdentityStore.prototype.recoverFromSeed = function (password, seed, cb) {
this._createIdmgmt(password, seed, null, (err) => {
if (err) return cb(err)
@@ -79,18 +74,17 @@ IdentityStore.prototype.recoverFromSeed = function(password, seed, cb){
})
}
-IdentityStore.prototype.setStore = function(store){
+IdentityStore.prototype.setStore = function (store) {
this._ethStore = store
}
-IdentityStore.prototype.clearSeedWordCache = function(cb) {
+IdentityStore.prototype.clearSeedWordCache = function (cb) {
configManager.setShowSeedWords(false)
cb(null, configManager.getSelectedAccount())
}
-IdentityStore.prototype.getState = function(){
+IdentityStore.prototype.getState = function () {
var seedWords = this.getSeedIfUnlocked()
- var wallet = configManager.getWallet()
return clone(extend(this._currentState, {
isInitialized: !!configManager.getWallet() && !seedWords,
isUnlocked: this._isUnlocked(),
@@ -104,7 +98,7 @@ IdentityStore.prototype.getState = function(){
}))
}
-IdentityStore.prototype.getSeedIfUnlocked = function() {
+IdentityStore.prototype.getSeedIfUnlocked = function () {
var showSeed = configManager.getShouldShowSeedWords()
var idmgmt = this._idmgmt
var shouldShow = showSeed && !!idmgmt
@@ -112,11 +106,11 @@ IdentityStore.prototype.getSeedIfUnlocked = function() {
return seedWords
}
-IdentityStore.prototype.getSelectedAddress = function(){
+IdentityStore.prototype.getSelectedAddress = function () {
return configManager.getSelectedAccount()
}
-IdentityStore.prototype.setSelectedAddress = function(address, cb){
+IdentityStore.prototype.setSelectedAddress = function (address, cb) {
if (!address) {
var addresses = this._getAddresses()
address = addresses[0]
@@ -126,8 +120,7 @@ IdentityStore.prototype.setSelectedAddress = function(address, cb){
if (cb) return cb(null, address)
}
-IdentityStore.prototype.revealAccount = function(cb) {
- let addresses = this._getAddresses()
+IdentityStore.prototype.revealAccount = function (cb) {
const derivedKey = this._idmgmt.derivedKey
const keyStore = this._keyStore
@@ -135,14 +128,12 @@ IdentityStore.prototype.revealAccount = function(cb) {
keyStore.generateNewAddress(derivedKey, 1)
configManager.setWallet(keyStore.serialize())
- addresses = this._getAddresses()
this._loadIdentities()
this._didUpdate()
cb(null)
}
-IdentityStore.prototype.getNetwork = function(err) {
-
+IdentityStore.prototype.getNetwork = function (err) {
if (err) {
this._currentState.network = 'loading'
this._didUpdate()
@@ -160,13 +151,13 @@ IdentityStore.prototype.getNetwork = function(err) {
})
}
-IdentityStore.prototype.setLocked = function(cb){
+IdentityStore.prototype.setLocked = function (cb) {
delete this._keyStore
delete this._idmgmt
cb()
}
-IdentityStore.prototype.submitPassword = function(password, cb){
+IdentityStore.prototype.submitPassword = function (password, cb) {
this.tryPassword(password, (err) => {
if (err) return cb(err)
// load identities before returning...
@@ -175,7 +166,7 @@ IdentityStore.prototype.submitPassword = function(password, cb){
})
}
-IdentityStore.prototype.exportAccount = function(address, cb) {
+IdentityStore.prototype.exportAccount = function (address, cb) {
var privateKey = this._idmgmt.exportPrivateKey(address)
cb(null, privateKey)
}
@@ -185,7 +176,7 @@ IdentityStore.prototype.exportAccount = function(address, cb) {
//
// comes from dapp via zero-client hooked-wallet provider
-IdentityStore.prototype.addUnconfirmedTransaction = function(txParams, onTxDoneCb, cb){
+IdentityStore.prototype.addUnconfirmedTransaction = function (txParams, onTxDoneCb, cb) {
var self = this
// create txData obj with parameters and meta data
var time = (new Date()).getTime()
@@ -208,13 +199,13 @@ IdentityStore.prototype.addUnconfirmedTransaction = function(txParams, onTxDoneC
// perform static analyis on the target contract code
var provider = self._ethStore._query.currentProvider
if (txParams.to) {
- provider.sendAsync({ id: 1, method: 'eth_getCode', params: [txParams.to, 'latest'] }, function(err, res){
+ provider.sendAsync({ id: 1, method: 'eth_getCode', params: [txParams.to, 'latest'] }, function (err, res) {
if (err) return didComplete(err)
if (res.error) return didComplete(res.error)
var code = ethUtil.toBuffer(res.result)
if (code !== '0x') {
var ops = ethBinToOps(code)
- var containsDelegateCall = ops.some((op)=>op.name === 'DELEGATECALL')
+ var containsDelegateCall = ops.some((op) => op.name === 'DELEGATECALL')
txData.containsDelegateCall = containsDelegateCall
didComplete()
} else {
@@ -225,19 +216,17 @@ IdentityStore.prototype.addUnconfirmedTransaction = function(txParams, onTxDoneC
didComplete()
}
- function didComplete(err){
+ function didComplete (err) {
if (err) return cb(err)
// signal update
self._didUpdate()
// signal completion of add tx
cb(null, txData)
}
-
}
// comes from metamask ui
-IdentityStore.prototype.approveTransaction = function(txId, cb){
- var txData = configManager.getTx(txId)
+IdentityStore.prototype.approveTransaction = function (txId, cb) {
var approvalCb = this._unconfTxCbs[txId] || noop
// accept tx
@@ -250,8 +239,7 @@ IdentityStore.prototype.approveTransaction = function(txId, cb){
}
// comes from metamask ui
-IdentityStore.prototype.cancelTransaction = function(txId){
- var txData = configManager.getTx(txId)
+IdentityStore.prototype.cancelTransaction = function (txId) {
var approvalCb = this._unconfTxCbs[txId] || noop
// reject tx
@@ -263,7 +251,7 @@ IdentityStore.prototype.cancelTransaction = function(txId){
}
// performs the actual signing, no autofill of params
-IdentityStore.prototype.signTransaction = function(txParams, cb){
+IdentityStore.prototype.signTransaction = function (txParams, cb) {
try {
console.log('signing tx...', txParams)
var rawTx = this._idmgmt.signTx(txParams)
@@ -278,8 +266,7 @@ IdentityStore.prototype.signTransaction = function(txParams, cb){
//
// comes from dapp via zero-client hooked-wallet provider
-IdentityStore.prototype.addUnconfirmedMessage = function(msgParams, cb){
-
+IdentityStore.prototype.addUnconfirmedMessage = function (msgParams, cb) {
// create txData obj with parameters and meta data
var time = (new Date()).getTime()
var msgId = createId()
@@ -303,8 +290,7 @@ IdentityStore.prototype.addUnconfirmedMessage = function(msgParams, cb){
}
// comes from metamask ui
-IdentityStore.prototype.approveMessage = function(msgId, cb){
- var msgData = messageManager.getMsg(msgId)
+IdentityStore.prototype.approveMessage = function (msgId, cb) {
var approvalCb = this._unconfMsgCbs[msgId] || noop
// accept msg
@@ -317,8 +303,7 @@ IdentityStore.prototype.approveMessage = function(msgId, cb){
}
// comes from metamask ui
-IdentityStore.prototype.cancelMessage = function(msgId){
- var txData = messageManager.getMsg(msgId)
+IdentityStore.prototype.cancelMessage = function (msgId) {
var approvalCb = this._unconfMsgCbs[msgId] || noop
// reject tx
@@ -330,7 +315,7 @@ IdentityStore.prototype.cancelMessage = function(msgId){
}
// performs the actual signing, no autofill of params
-IdentityStore.prototype.signMessage = function(msgParams, cb){
+IdentityStore.prototype.signMessage = function (msgParams, cb) {
try {
console.log('signing msg...', msgParams.data)
var rawMsg = this._idmgmt.signMsg(msgParams.from, msgParams.data)
@@ -351,17 +336,17 @@ IdentityStore.prototype.signMessage = function(msgParams, cb){
// private
//
-IdentityStore.prototype._didUpdate = function(){
+IdentityStore.prototype._didUpdate = function () {
this.emit('update', this.getState())
}
-IdentityStore.prototype._isUnlocked = function(){
+IdentityStore.prototype._isUnlocked = function () {
var result = Boolean(this._keyStore) && Boolean(this._idmgmt)
return result
}
// load identities from keyStoreet
-IdentityStore.prototype._loadIdentities = function(){
+IdentityStore.prototype._loadIdentities = function () {
if (!this._isUnlocked()) throw new Error('not unlocked')
var addresses = this._getAddresses()
@@ -369,7 +354,7 @@ IdentityStore.prototype._loadIdentities = function(){
// // add to ethStore
this._ethStore.addAccount(address)
// add to identities
- const defaultLabel = 'Wallet ' + (i+1)
+ const defaultLabel = 'Wallet ' + (i + 1)
const nickname = configManager.nicknameForWallet(address)
var identity = {
name: nickname || defaultLabel,
@@ -381,7 +366,7 @@ IdentityStore.prototype._loadIdentities = function(){
this._didUpdate()
}
-IdentityStore.prototype.saveAccountLabel = function(account, label, cb) {
+IdentityStore.prototype.saveAccountLabel = function (account, label, cb) {
configManager.setNicknameForWallet(account, label)
this._loadIdentities()
cb(null, label)
@@ -393,7 +378,7 @@ IdentityStore.prototype.saveAccountLabel = function(account, label, cb) {
// The UI will have to check the balance to know.
// If there is no balance and it mayBeFauceting,
// then it is in fact fauceting.
-IdentityStore.prototype._mayBeFauceting = function(i) {
+IdentityStore.prototype._mayBeFauceting = function (i) {
var config = configManager.getProvider()
if (i === 0 &&
config.type === 'rpc' &&
@@ -407,11 +392,11 @@ IdentityStore.prototype._mayBeFauceting = function(i) {
// keyStore managment - unlocking + deserialization
//
-IdentityStore.prototype.tryPassword = function(password, cb){
+IdentityStore.prototype.tryPassword = function (password, cb) {
this._createIdmgmt(password, null, null, cb)
}
-IdentityStore.prototype._createIdmgmt = function(password, seed, entropy, cb){
+IdentityStore.prototype._createIdmgmt = function (password, seed, entropy, cb) {
var keyStore = null
LightwalletKeyStore.deriveKeyFromPassword(password, (err, derivedKey) => {
if (err) return cb(err)
@@ -446,9 +431,9 @@ IdentityStore.prototype._createIdmgmt = function(password, seed, entropy, cb){
})
}
-IdentityStore.prototype._restoreFromSeed = function(password, seed, derivedKey) {
+IdentityStore.prototype._restoreFromSeed = function (password, seed, derivedKey) {
var keyStore = new LightwalletKeyStore(seed, derivedKey, this.hdPathString)
- keyStore.addHdDerivationPath(this.hdPathString, derivedKey, {curve: 'secp256k1', purpose: 'sign'});
+ keyStore.addHdDerivationPath(this.hdPathString, derivedKey, {curve: 'secp256k1', purpose: 'sign'})
keyStore.setDefaultHdDerivationPath(this.hdPathString)
keyStore.generateNewAddress(derivedKey, 3)
@@ -457,10 +442,10 @@ IdentityStore.prototype._restoreFromSeed = function(password, seed, derivedKey)
return keyStore
}
-IdentityStore.prototype._createFirstWallet = function(entropy, derivedKey) {
+IdentityStore.prototype._createFirstWallet = function (entropy, derivedKey) {
var secretSeed = LightwalletKeyStore.generateRandomSeed(entropy)
var keyStore = new LightwalletKeyStore(secretSeed, derivedKey, this.hdPathString)
- keyStore.addHdDerivationPath(this.hdPathString, derivedKey, {curve: 'secp256k1', purpose: 'sign'});
+ keyStore.addHdDerivationPath(this.hdPathString, derivedKey, {curve: 'secp256k1', purpose: 'sign'})
keyStore.setDefaultHdDerivationPath(this.hdPathString)
keyStore.generateNewAddress(derivedKey, 3)
@@ -470,15 +455,15 @@ IdentityStore.prototype._createFirstWallet = function(entropy, derivedKey) {
}
// get addresses and normalize address hexString
-IdentityStore.prototype._getAddresses = function() {
- return this._keyStore.getAddresses(this.hdPathString).map((address) => { return '0x'+address })
+IdentityStore.prototype._getAddresses = function () {
+ return this._keyStore.getAddresses(this.hdPathString).map((address) => { return '0x' + address })
}
-IdentityStore.prototype._autoFaucet = function() {
+IdentityStore.prototype._autoFaucet = function () {
var addresses = this._getAddresses()
autoFaucet(addresses[0])
}
// util
-function noop(){}
+function noop () {}
diff --git a/app/scripts/lib/inpage-provider.js b/app/scripts/lib/inpage-provider.js
index 70b0d80dd..3b6ec154f 100644
--- a/app/scripts/lib/inpage-provider.js
+++ b/app/scripts/lib/inpage-provider.js
@@ -7,13 +7,12 @@ const MetamaskConfig = require('../config.js')
module.exports = MetamaskInpageProvider
-
-function MetamaskInpageProvider(connectionStream){
+function MetamaskInpageProvider (connectionStream) {
const self = this
- // setup connectionStream multiplexing
+ // setup connectionStream multiplexing
var multiStream = ObjectMultiplex()
- Streams.pipe(connectionStream, multiStream, connectionStream, function(err){
+ Streams.pipe(connectionStream, multiStream, connectionStream, function (err) {
console.warn('MetamaskInpageProvider - lost connection to MetaMask')
if (err) throw err
})
@@ -22,7 +21,7 @@ function MetamaskInpageProvider(connectionStream){
// subscribe to metamask public config
var publicConfigStore = remoteStoreWithLocalStorageCache('MetaMask-Config')
var storeStream = publicConfigStore.createStream()
- Streams.pipe(storeStream, multiStream.createStream('publicConfig'), storeStream, function(err){
+ Streams.pipe(storeStream, multiStream.createStream('publicConfig'), storeStream, function (err) {
console.warn('MetamaskInpageProvider - lost connection to MetaMask publicConfig')
if (err) throw err
})
@@ -31,13 +30,13 @@ function MetamaskInpageProvider(connectionStream){
// connect to sync provider
self.syncProvider = createSyncProvider(publicConfigStore.get('provider'))
// subscribe to publicConfig to update the syncProvider on change
- publicConfigStore.subscribe(function(state){
+ publicConfigStore.subscribe(function (state) {
self.syncProvider = createSyncProvider(state.provider)
})
// connect to async provider
var asyncProvider = new StreamProvider()
- Streams.pipe(asyncProvider, multiStream.createStream('provider'), asyncProvider, function(err){
+ Streams.pipe(asyncProvider, multiStream.createStream('provider'), asyncProvider, function (err) {
console.warn('MetamaskInpageProvider - lost connection to MetaMask provider')
if (err) throw err
})
@@ -47,21 +46,22 @@ function MetamaskInpageProvider(connectionStream){
self.sendAsync = asyncProvider.sendAsync.bind(asyncProvider)
}
-MetamaskInpageProvider.prototype.send = function(payload){
+MetamaskInpageProvider.prototype.send = function (payload) {
const self = this
+ let selectedAddress
var result = null
switch (payload.method) {
case 'eth_accounts':
// read from localStorage
- var selectedAddress = self.publicConfigStore.get('selectedAddress')
+ selectedAddress = self.publicConfigStore.get('selectedAddress')
result = selectedAddress ? [selectedAddress] : []
break
case 'eth_coinbase':
// read from localStorage
- var selectedAddress = self.publicConfigStore.get('selectedAddress')
+ selectedAddress = self.publicConfigStore.get('selectedAddress')
result = selectedAddress || '0x0000000000000000000000000000000000000000'
break
@@ -79,24 +79,24 @@ MetamaskInpageProvider.prototype.send = function(payload){
}
}
-MetamaskInpageProvider.prototype.sendAsync = function(){
+MetamaskInpageProvider.prototype.sendAsync = function () {
throw new Error('MetamaskInpageProvider - sendAsync not overwritten')
}
-MetamaskInpageProvider.prototype.isConnected = function(){
+MetamaskInpageProvider.prototype.isConnected = function () {
return true
}
// util
-function createSyncProvider(providerConfig){
+function createSyncProvider (providerConfig) {
providerConfig = providerConfig || {}
- var syncProviderUrl = undefined
+ let syncProviderUrl
if (providerConfig.rpcTarget) {
syncProviderUrl = providerConfig.rpcTarget
} else {
- switch(providerConfig.type) {
+ switch (providerConfig.type) {
case 'testnet':
syncProviderUrl = MetamaskConfig.network.testnet
break
@@ -110,14 +110,14 @@ function createSyncProvider(providerConfig){
return new HttpProvider(syncProviderUrl)
}
-function remoteStoreWithLocalStorageCache(storageKey){
+function remoteStoreWithLocalStorageCache (storageKey) {
// read local cache
var initState = JSON.parse(localStorage[storageKey] || '{}')
var store = new RemoteStore(initState)
// cache the latest state locally
- store.subscribe(function(state){
+ store.subscribe(function (state) {
localStorage[storageKey] = JSON.stringify(state)
})
return store
-} \ No newline at end of file
+}
diff --git a/app/scripts/lib/local-message-stream.js b/app/scripts/lib/local-message-stream.js
index 76fedd9df..821e51046 100644
--- a/app/scripts/lib/local-message-stream.js
+++ b/app/scripts/lib/local-message-stream.js
@@ -3,10 +3,9 @@ const inherits = require('util').inherits
module.exports = LocalMessageDuplexStream
-
inherits(LocalMessageDuplexStream, Duplex)
-function LocalMessageDuplexStream(opts){
+function LocalMessageDuplexStream (opts) {
Duplex.call(this, {
objectMode: true,
})
@@ -21,19 +20,19 @@ function LocalMessageDuplexStream(opts){
// private
-LocalMessageDuplexStream.prototype._onMessage = function(event){
+LocalMessageDuplexStream.prototype._onMessage = function (event) {
var msg = event.data
// console.log('LocalMessageDuplexStream ('+this._name+') - heard message...', event)
// validate message
- if (event.origin !== location.origin) return //console.log('LocalMessageDuplexStream ('+this._name+') - rejected - (event.origin !== location.origin) ')
- if (typeof msg !== 'object') return //console.log('LocalMessageDuplexStream ('+this._name+') - rejected - (typeof msg !== "object") ')
- if (msg.target !== this._name) return //console.log('LocalMessageDuplexStream ('+this._name+') - rejected - (msg.target !== this._name) ', msg.target, this._name)
- if (!msg.data) return //console.log('LocalMessageDuplexStream ('+this._name+') - rejected - (!msg.data) ')
+ if (event.origin !== location.origin) return // console.log('LocalMessageDuplexStream ('+this._name+') - rejected - (event.origin !== location.origin) ')
+ if (typeof msg !== 'object') return // console.log('LocalMessageDuplexStream ('+this._name+') - rejected - (typeof msg !== "object") ')
+ if (msg.target !== this._name) return // console.log('LocalMessageDuplexStream ('+this._name+') - rejected - (msg.target !== this._name) ', msg.target, this._name)
+ if (!msg.data) return // console.log('LocalMessageDuplexStream ('+this._name+') - rejected - (!msg.data) ')
// console.log('LocalMessageDuplexStream ('+this._name+') - accepted', msg.data)
// forward message
try {
this.push(msg.data)
- } catch(err) {
+ } catch (err) {
this.emit('error', err)
}
}
@@ -42,7 +41,7 @@ LocalMessageDuplexStream.prototype._onMessage = function(event){
LocalMessageDuplexStream.prototype._read = noop
-LocalMessageDuplexStream.prototype._write = function(data, encoding, cb){
+LocalMessageDuplexStream.prototype._write = function (data, encoding, cb) {
// console.log('LocalMessageDuplexStream ('+this._name+') - sending message...')
var message = {
target: this._target,
@@ -54,4 +53,4 @@ LocalMessageDuplexStream.prototype._write = function(data, encoding, cb){
// util
-function noop(){} \ No newline at end of file
+function noop () {}
diff --git a/app/scripts/lib/message-manager.js b/app/scripts/lib/message-manager.js
index 91edb7759..b609b820e 100644
--- a/app/scripts/lib/message-manager.js
+++ b/app/scripts/lib/message-manager.js
@@ -1,50 +1,50 @@
module.exports = new MessageManager()
-function MessageManager(opts) {
+function MessageManager (opts) {
this.messages = []
}
-MessageManager.prototype.getMsgList = function() {
+MessageManager.prototype.getMsgList = function () {
return this.messages
}
-MessageManager.prototype.unconfirmedMsgs = function() {
+MessageManager.prototype.unconfirmedMsgs = function () {
var messages = this.getMsgList()
return messages.filter(msg => msg.status === 'unconfirmed')
.reduce((result, msg) => { result[msg.id] = msg; return result }, {})
}
-MessageManager.prototype._saveMsgList = function(msgList) {
+MessageManager.prototype._saveMsgList = function (msgList) {
this.messages = msgList
}
-MessageManager.prototype.addMsg = function(msg) {
+MessageManager.prototype.addMsg = function (msg) {
var messages = this.getMsgList()
messages.push(msg)
this._saveMsgList(messages)
}
-MessageManager.prototype.getMsg = function(msgId) {
+MessageManager.prototype.getMsg = function (msgId) {
var messages = this.getMsgList()
var matching = messages.filter(msg => msg.id === msgId)
return matching.length > 0 ? matching[0] : null
}
-MessageManager.prototype.confirmMsg = function(msgId) {
+MessageManager.prototype.confirmMsg = function (msgId) {
this._setMsgStatus(msgId, 'confirmed')
}
-MessageManager.prototype.rejectMsg = function(msgId) {
+MessageManager.prototype.rejectMsg = function (msgId) {
this._setMsgStatus(msgId, 'rejected')
}
-MessageManager.prototype._setMsgStatus = function(msgId, status) {
+MessageManager.prototype._setMsgStatus = function (msgId, status) {
var msg = this.getMsg(msgId)
if (msg) msg.status = status
this.updateMsg(msg)
}
-MessageManager.prototype.updateMsg = function(msg) {
+MessageManager.prototype.updateMsg = function (msg) {
var messages = this.getMsgList()
var found, index
messages.forEach((otherMsg, i) => {
diff --git a/app/scripts/lib/notifications.js b/app/scripts/lib/notifications.js
index 90edaea12..af2dc2054 100644
--- a/app/scripts/lib/notifications.js
+++ b/app/scripts/lib/notifications.js
@@ -10,13 +10,12 @@ module.exports = {
setupListeners()
-function setupListeners(){
-
+function setupListeners () {
// guard for chrome bug https://github.com/MetaMask/metamask-plugin/issues/236
if (!chrome.notifications) return console.error('Chrome notifications API missing...')
// notification button press
- chrome.notifications.onButtonClicked.addListener(function(notificationId, buttonIndex){
+ chrome.notifications.onButtonClicked.addListener(function (notificationId, buttonIndex) {
var handlers = notificationHandlers[notificationId]
if (buttonIndex === 0) {
handlers.confirm()
@@ -27,14 +26,13 @@ function setupListeners(){
})
// notification teardown
- chrome.notifications.onClosed.addListener(function(notificationId){
+ chrome.notifications.onClosed.addListener(function (notificationId) {
delete notificationHandlers[notificationId]
})
-
}
// creation helper
-function createUnlockRequestNotification(opts){
+function createUnlockRequestNotification (opts) {
// guard for chrome bug https://github.com/MetaMask/metamask-plugin/issues/236
if (!chrome.notifications) return console.error('Chrome notifications API missing...')
var message = 'An Ethereum app has requested a signature. Please unlock your account.'
@@ -46,18 +44,17 @@ function createUnlockRequestNotification(opts){
title: opts.title,
message: message,
})
-
}
-function createTxNotification(opts){
+function createTxNotification (opts) {
// guard for chrome bug https://github.com/MetaMask/metamask-plugin/issues/236
if (!chrome.notifications) return console.error('Chrome notifications API missing...')
var message = [
- 'Submitted by '+opts.txParams.origin,
- 'to: '+uiUtils.addressSummary(opts.txParams.to),
- 'from: '+uiUtils.addressSummary(opts.txParams.from),
- 'value: '+uiUtils.formatBalance(opts.txParams.value),
- 'data: '+uiUtils.dataSize(opts.txParams.data),
+ 'Submitted by ' + opts.txParams.origin,
+ 'to: ' + uiUtils.addressSummary(opts.txParams.to),
+ 'from: ' + uiUtils.addressSummary(opts.txParams.from),
+ 'value: ' + uiUtils.formatBalance(opts.txParams.value),
+ 'data: ' + uiUtils.dataSize(opts.txParams.data),
].join('\n')
var id = createId()
@@ -69,9 +66,9 @@ function createTxNotification(opts){
message: message,
buttons: [{
title: 'confirm',
- },{
+ }, {
title: 'cancel',
- }]
+ }],
})
notificationHandlers[id] = {
confirm: opts.confirm,
@@ -79,13 +76,13 @@ function createTxNotification(opts){
}
}
-function createMsgNotification(opts){
+function createMsgNotification (opts) {
// guard for chrome bug https://github.com/MetaMask/metamask-plugin/issues/236
if (!chrome.notifications) return console.error('Chrome notifications API missing...')
var message = [
- 'Submitted by '+opts.msgParams.origin,
- 'to be signed by: '+uiUtils.addressSummary(opts.msgParams.from),
- 'message:\n'+opts.msgParams.data,
+ 'Submitted by ' + opts.msgParams.origin,
+ 'to be signed by: ' + uiUtils.addressSummary(opts.msgParams.from),
+ 'message:\n' + opts.msgParams.data,
].join('\n')
var id = createId()
@@ -97,12 +94,12 @@ function createMsgNotification(opts){
message: message,
buttons: [{
title: 'confirm',
- },{
+ }, {
title: 'cancel',
- }]
+ }],
})
notificationHandlers[id] = {
confirm: opts.confirm,
cancel: opts.cancel,
}
-} \ No newline at end of file
+}
diff --git a/app/scripts/lib/obj-multiplex.js b/app/scripts/lib/obj-multiplex.js
index ad1d914f8..f54ff7653 100644
--- a/app/scripts/lib/obj-multiplex.js
+++ b/app/scripts/lib/obj-multiplex.js
@@ -2,11 +2,10 @@ const through = require('through2')
module.exports = ObjectMultiplex
-
-function ObjectMultiplex(opts){
+function ObjectMultiplex (opts) {
opts = opts || {}
// create multiplexer
- var mx = through.obj(function(chunk, enc, cb) {
+ var mx = through.obj(function (chunk, enc, cb) {
var name = chunk.name
var data = chunk.data
var substream = mx.streams[name]
@@ -19,19 +18,19 @@ function ObjectMultiplex(opts){
})
mx.streams = {}
// create substreams
- mx.createStream = function(name) {
- var substream = mx.streams[name] = through.obj(function(chunk, enc, cb) {
+ mx.createStream = function (name) {
+ var substream = mx.streams[name] = through.obj(function (chunk, enc, cb) {
mx.push({
name: name,
data: chunk,
})
return cb()
})
- mx.on('end', function() {
+ mx.on('end', function () {
return substream.emit('end')
})
if (opts.error) {
- mx.on('error', function() {
+ mx.on('error', function () {
return substream.emit('error')
})
}
diff --git a/app/scripts/lib/port-stream.js b/app/scripts/lib/port-stream.js
index 2644741fc..1889e3c04 100644
--- a/app/scripts/lib/port-stream.js
+++ b/app/scripts/lib/port-stream.js
@@ -3,10 +3,9 @@ const inherits = require('util').inherits
module.exports = PortDuplexStream
-
inherits(PortDuplexStream, Duplex)
-function PortDuplexStream(port){
+function PortDuplexStream (port) {
Duplex.call(this, {
objectMode: true,
})
@@ -17,7 +16,7 @@ function PortDuplexStream(port){
// private
-PortDuplexStream.prototype._onMessage = function(msg){
+PortDuplexStream.prototype._onMessage = function (msg) {
if (Buffer.isBuffer(msg)) {
delete msg._isBuffer
var data = new Buffer(msg)
@@ -29,11 +28,11 @@ PortDuplexStream.prototype._onMessage = function(msg){
}
}
-PortDuplexStream.prototype._onDisconnect = function(){
+PortDuplexStream.prototype._onDisconnect = function () {
try {
// this.end()
this.emit('close')
- } catch(err){
+ } catch (err) {
this.emit('error', err)
}
}
@@ -42,7 +41,7 @@ PortDuplexStream.prototype._onDisconnect = function(){
PortDuplexStream.prototype._read = noop
-PortDuplexStream.prototype._write = function(msg, encoding, cb){
+PortDuplexStream.prototype._write = function (msg, encoding, cb) {
try {
if (Buffer.isBuffer(msg)) {
var data = msg.toJSON()
@@ -54,7 +53,7 @@ PortDuplexStream.prototype._write = function(msg, encoding, cb){
this._port.postMessage(msg)
}
cb()
- } catch(err){
+ } catch (err) {
console.error(err)
// this.emit('error', err)
cb(new Error('PortDuplexStream - disconnected'))
@@ -63,4 +62,4 @@ PortDuplexStream.prototype._write = function(msg, encoding, cb){
// util
-function noop(){} \ No newline at end of file
+function noop () {}
diff --git a/app/scripts/lib/remote-store.js b/app/scripts/lib/remote-store.js
index 2dbdde811..fbfab7bad 100644
--- a/app/scripts/lib/remote-store.js
+++ b/app/scripts/lib/remote-store.js
@@ -6,32 +6,32 @@ module.exports = {
RemoteStore: RemoteStore,
}
-function BaseStore(initState){
+function BaseStore (initState) {
this._state = initState || {}
this._subs = []
}
-BaseStore.prototype.set = function(key, value){
+BaseStore.prototype.set = function (key, value) {
throw Error('Not implemented.')
}
-BaseStore.prototype.get = function(key){
+BaseStore.prototype.get = function (key) {
return this._state[key]
}
-BaseStore.prototype.subscribe = function(fn){
+BaseStore.prototype.subscribe = function (fn) {
this._subs.push(fn)
var unsubscribe = this.unsubscribe.bind(this, fn)
return unsubscribe
}
-BaseStore.prototype.unsubscribe = function(fn){
+BaseStore.prototype.unsubscribe = function (fn) {
var index = this._subs.indexOf(fn)
if (index !== -1) this._subs.splice(index, 1)
}
-BaseStore.prototype._emitUpdates = function(state){
- this._subs.forEach(function(handler){
+BaseStore.prototype._emitUpdates = function (state) {
+ this._subs.forEach(function (handler) {
handler(state)
})
}
@@ -41,16 +41,16 @@ BaseStore.prototype._emitUpdates = function(state){
//
inherits(HostStore, BaseStore)
-function HostStore(initState, opts){
+function HostStore (initState, opts) {
BaseStore.call(this, initState)
}
-HostStore.prototype.set = function(key, value){
+HostStore.prototype.set = function (key, value) {
this._state[key] = value
process.nextTick(this._emitUpdates.bind(this, this._state))
}
-HostStore.prototype.createStream = function(){
+HostStore.prototype.createStream = function () {
var dnode = Dnode({
// update: this._didUpdate.bind(this),
})
@@ -58,8 +58,8 @@ HostStore.prototype.createStream = function(){
return dnode
}
-HostStore.prototype._didConnect = function(remote){
- this.subscribe(function(state){
+HostStore.prototype._didConnect = function (remote) {
+ this.subscribe(function (state) {
remote.update(state)
})
remote.update(this._state)
@@ -70,16 +70,16 @@ HostStore.prototype._didConnect = function(remote){
//
inherits(RemoteStore, BaseStore)
-function RemoteStore(initState, opts){
+function RemoteStore (initState, opts) {
BaseStore.call(this, initState)
this._remote = null
}
-RemoteStore.prototype.set = function(key, value){
+RemoteStore.prototype.set = function (key, value) {
this._remote.set(key, value)
}
-RemoteStore.prototype.createStream = function(){
+RemoteStore.prototype.createStream = function () {
var dnode = Dnode({
update: this._didUpdate.bind(this),
})
@@ -87,11 +87,11 @@ RemoteStore.prototype.createStream = function(){
return dnode
}
-RemoteStore.prototype._didConnect = function(remote){
+RemoteStore.prototype._didConnect = function (remote) {
this._remote = remote
}
-RemoteStore.prototype._didUpdate = function(state){
+RemoteStore.prototype._didUpdate = function (state) {
this._state = state
this._emitUpdates(state)
}
diff --git a/app/scripts/lib/stream-utils.js b/app/scripts/lib/stream-utils.js
index ca245ca9a..1b7b89d14 100644
--- a/app/scripts/lib/stream-utils.js
+++ b/app/scripts/lib/stream-utils.js
@@ -1,36 +1,35 @@
const Through = require('through2')
const ObjectMultiplex = require('./obj-multiplex')
-
module.exports = {
jsonParseStream: jsonParseStream,
jsonStringifyStream: jsonStringifyStream,
setupMultiplex: setupMultiplex,
}
-function jsonParseStream(){
- return Through.obj(function(serialized, encoding, cb){
+function jsonParseStream () {
+ return Through.obj(function (serialized, encoding, cb) {
this.push(JSON.parse(serialized))
cb()
})
}
-function jsonStringifyStream(){
- return Through.obj(function(obj, encoding, cb){
+function jsonStringifyStream () {
+ return Through.obj(function (obj, encoding, cb) {
this.push(JSON.stringify(obj))
cb()
})
}
-function setupMultiplex(connectionStream){
+function setupMultiplex (connectionStream) {
var mx = ObjectMultiplex()
connectionStream.pipe(mx).pipe(connectionStream)
- mx.on('error', function(err) {
+ mx.on('error', function (err) {
console.error(err)
})
- connectionStream.on('error', function(err) {
+ connectionStream.on('error', function (err) {
console.error(err)
mx.destroy()
})
return mx
-} \ No newline at end of file
+}
diff --git a/app/scripts/migrations/002.js b/app/scripts/migrations/002.js
index ab6a256ab..0b654f825 100644
--- a/app/scripts/migrations/002.js
+++ b/app/scripts/migrations/002.js
@@ -1,7 +1,7 @@
module.exports = {
version: 2,
- migrate: function(data) {
+ migrate: function (data) {
try {
if (data.config.provider.type === 'etherscan') {
data.config.provider.type = 'rpc'
@@ -9,5 +9,5 @@ module.exports = {
}
} catch (e) {}
return data
- }
+ },
}
diff --git a/app/scripts/migrations/003.js b/app/scripts/migrations/003.js
index 087f8bcd9..617c55c09 100644
--- a/app/scripts/migrations/003.js
+++ b/app/scripts/migrations/003.js
@@ -4,12 +4,12 @@ var newTestRpc = 'https://testrpc.metamask.io/'
module.exports = {
version: 3,
- migrate: function(data) {
+ migrate: function (data) {
try {
if (data.config.provider.rpcTarget === oldTestRpc) {
data.config.provider.rpcTarget = newTestRpc
}
} catch (e) {}
return data
- }
+ },
}
diff --git a/app/scripts/migrations/004.js b/app/scripts/migrations/004.js
index 2e3164baf..1329a1eed 100644
--- a/app/scripts/migrations/004.js
+++ b/app/scripts/migrations/004.js
@@ -1,22 +1,22 @@
module.exports = {
version: 4,
- migrate: function(data) {
+ migrate: function (data) {
try {
if (data.config.provider.type !== 'rpc') return data
switch (data.config.provider.rpcTarget) {
case 'https://testrpc.metamask.io/':
- data.config.provider = {
- type: 'testnet'
- }
+ data.config.provider = {
+ type: 'testnet',
+ }
break
case 'https://rpc.metamask.io/':
- data.config.provider = {
- type: 'mainnet'
- }
+ data.config.provider = {
+ type: 'mainnet',
+ }
break
}
} catch (_) {}
return data
- }
+ },
}
diff --git a/app/scripts/popup.js b/app/scripts/popup.js
index 4fa6e1127..5173507fa 100644
--- a/app/scripts/popup.js
+++ b/app/scripts/popup.js
@@ -19,7 +19,7 @@ async.parallel({
accountManager: connectToAccountManager,
}, setupApp)
-function connectToAccountManager(cb){
+function connectToAccountManager (cb) {
// setup communication with background
var pluginPort = chrome.runtime.connect({name: 'popup'})
var portStream = new PortStream(pluginPort)
@@ -30,7 +30,7 @@ function connectToAccountManager(cb){
setupWeb3Connection(mx.createStream('provider'))
}
-function setupWeb3Connection(stream){
+function setupWeb3Connection (stream) {
var remoteProvider = new StreamProvider()
remoteProvider.pipe(stream).pipe(remoteProvider)
stream.on('error', console.error.bind(console))
@@ -38,23 +38,23 @@ function setupWeb3Connection(stream){
global.web3 = new Web3(remoteProvider)
}
-function setupControllerConnection(stream, cb){
+function setupControllerConnection (stream, cb) {
var eventEmitter = new EventEmitter()
var background = Dnode({
- sendUpdate: function(state){
+ sendUpdate: function (state) {
eventEmitter.emit('update', state)
},
})
stream.pipe(background).pipe(stream)
- background.once('remote', function(accountManager){
+ background.once('remote', function (accountManager) {
// setup push events
accountManager.on = eventEmitter.on.bind(eventEmitter)
cb(null, accountManager)
})
}
-function getCurrentDomain(cb){
- chrome.tabs.query({active: true, currentWindow: true}, function(results){
+function getCurrentDomain (cb) {
+ chrome.tabs.query({active: true, currentWindow: true}, function (results) {
var activeTab = results[0]
var currentUrl = activeTab && activeTab.url
var currentDomain = url.parse(currentUrl).host
@@ -65,16 +65,15 @@ function getCurrentDomain(cb){
})
}
-function setupApp(err, opts){
+function setupApp (err, opts) {
if (err) {
alert(err.stack)
throw err
- return
}
var container = document.getElementById('app-content')
- var app = MetaMaskUi({
+ MetaMaskUi({
container: container,
accountManager: opts.accountManager,
currentDomain: opts.currentDomain,