<commit_before>//
// TODO:
// 1. Build dependency graph for $refs and process second pass in dependency order
//

var wire = (function(){

	var tos = Object.prototype.toString,
		arrt = '[object Array]',
		uniqueNameCount = 0, // used to generate unique names
		requires = [], // amd module names to be loaded
		deps = {}, // dependency graph
		context = {},
		undef;

	function uniqueName(seed) {
		return '_' + (seed ? seed : 'instance') + '_' + uniqueNameCount++;
	}

	function isModule(spec) {
		return spec.module;
	}

	function isRef(spec) {
		return spec.$ref !== undef;
	}

	function isArray(it) {
		return tos.call(it) === arrt;
	}

	function pivot(map) {
		// Pivots a map of key -> array, and returns the pivoted version
		// map: Object
		// 		Must be a set of key -> array pairs
		var pivoted = {};

		for(var p in map) {
			var arr = map[p];
			for (var i = arr.length - 1; i >= 0; i--){
				var key = arr[i];
				if(!pivoted[key]) {
					pivoted[key] = [];
				}

				pivoted[key].push(p);
			};
		}

		return pivoted;
	}

	function collectModules(spec) {
		// Look for modules in objects and arrays.  Skip simple values
		// in this pass.
		if(isArray(spec)) {
			collectModulesFromArray(spec);
		} else if(typeof spec == 'object') {

			if(isModule(spec)) {
				requires.push(spec.module);

				// TODO: REMOVE
				// For testing only
				// define(name, [], spec.module);

				if(spec.properties) {
					collectModules(spec.properties);
				} else if (spec.args) {
					collectModules(spec.args);
				}

			} else {
				for(var prop in spec) {
					collectModules(spec[prop], prop);
				}
			}
		}
	}

	function collectModulesFromArray(arr) {
		for (var i = arr.length - 1; i >= 0; i--){
			collectModules(arr[i]);
		};
	}

	function loadModules(moduleNames, callback) {
		require(moduleNames, callback);
	}

	function getLoadedModule(name) {
		return require(name);
	}

	function constructWithFactory(spec, name) {
		var module = getLoadedModule(name);
		if(!module) {
			throw Error("ERROR: no module loaded with name: " + name);
		}

		var func = spec.create.name,
			args = spec.create.args ? construct(spec.create.args) : [];

		return module[func].apply(module, args);
	}

	function constructWithNew(spec, name) {
		var module = getLoadedModule(spec.module);
		if(!module) {
			throw Error("ERROR: no module loaded with name: " + name);
		}

		return spec.create ? instantiate(module, spec.create) : new module();
	}

	var Factory = function Factory(ctor, args) {
			return ctor.apply(this, args);
		};

	function instantiate(ctor, args) {
		Factory.prototype = ctor.prototype;
		Factory.prototype.constructor = ctor;
		return new Factory(ctor, construct(args));
	}

	function callInit(target, func, args) {
		args = args ? construct(args) : [];
		func.apply(target, isArray(args) ? args : [args]);
	}

	function addReadyInit(target, func, args) {
		require.ready(function() {
			callInit(target, func, args);
		});
	}

	function setProperties(target, properties) {
		// TODO: plugins for property setting?
		var set = typeof target.set == 'function'
			? function(key, value) { target.set(key, construct(value)); }
			: function(key, value) { target[key] = construct(value); };

		for(var p in properties) {
			set(p, construct(properties[p], p));
		}
	}

	function processFuncList(list, target, callback) {
		var func;
		if(typeof list == "string") {
			// console.log("calling " + list + "()");
			func = target[list];
			if(typeof func == "function") {
				callback(target, func, []);
			}
		} else {
			for(var f in list) {
				// console.log("calling " + f + "(" + list[f] + ")");
				func = target[f];
				if(typeof func == "function") {
					callback(target, func, list[f]);
				}
			}
		}
	}

	function construct(spec, name) {
		// By default, just return the spec if it's not an object or array
		var result = spec;

		// If spec is an object or array, process it
		if(isArray(spec)) {
			// If it's an array, construct() each element
			result = [];
			for (var i=0; i < spec.length; i++) {
				result.push(construct(spec[i]));
			}

		} else if(typeof spec == 'object') {
			// If it's a module
			//  - if it has a create function, call it, with args and set result
			//  - if no factory function, invoke new as constructor and set result
			//  - if init function, invoke after factory or constructor
			// If it's not a module
			//  - recursive construct() and set result
			if(isModule(spec)) {
				name = name || spec.name;
				if(spec.create) {
					// TODO: Handle calling a factory method and using the return value as result? See constructWithFactory()
					// console.log('constructing ' + name + " from " + spec.module);
					result = constructWithNew(spec, name);
				} else {
					// console.log('setting ' + name + ' as module ' + spec.module + ' directly');
					result = getLoadedModule(spec.module);
				}

				if(spec.properties && typeof spec.properties == 'object') {
					// console.log("setting props on " + spec.name);

					setProperties(result, spec.properties);
				}

				// If it has init functions, call it
				if(spec.init) {
					processFuncList(spec.init, result, addReadyInit);
				}

				if(name) context[name] = result;

			} else if (isRef(spec)) {
				result = resolve(spec.$ref);
			} else {
				result = {};
				for(var prop in spec) {
					result[prop] = construct(spec[prop], prop);
				}
			}
		} else {
			if(name) context[name] = result;
		}

		return result;
	}

	function resolve(ref) {
		// Resolve a reference
		// TODO: Plugins for resolving references?

		return context[ref];
	}

	// main wire() export
	var w = function(spec, ready) {
		// 1. First pass, build module list for require, call require
		// 2. Second pass, depth first instantiate

		// First pass
		collectModules(spec);

		// Second pass happens after modules loaded by require loader
		require(requires, function() {
			// Second pass, construct actual instances
			var context = construct(spec);

			// Call callback when entire context is ready
			ready(context);
		});

	};

	// Export other helpers
	w.construct = construct;
	w.resolve = resolve;

	return w;
})();

// Fake require.  REMOVE!!!  Testing only

(function(window){
	var modules = {},
		uniqueNameCount = 0,
		tos = Object.prototype.toString,
		arrt = '[object Array]';

	function uniqueName() {
		return "_" + uniqueNameCount++;
	}

	if(!window.define) {
		window.define = function(name, deps, factory) {
			if(!factory) {
				name = uniqueName();
				deps = name;
				factory = deps;
			}

			if(!(name in modules)) {
				modules[name] = typeof factory == "function" ? factory() : factory;
			}
		};
	}

	if(!window.require) {
		var r = window.require = function(deps, callback) {
			if(tos.call(deps) === arrt) {
				// deps is an array
				var args = [];
				for (var i=0; i < deps.length; i++) {
					args.push(modules[deps[i]]);
				};
				return callback.apply(null, args);
			}
			else {
				// deps is a name
				var module = modules[deps];
				return module;
			}
		};

		r.ready = function(func) {
			func();
		};
	}

})(window);

<commit_msg>Added comment about reference resolution case in construct()<commit_after>//
// TODO:
// 1. Build dependency graph for $refs and process second pass in dependency order
//

var wire = (function(){

	var tos = Object.prototype.toString,
		arrt = '[object Array]',
		uniqueNameCount = 0, // used to generate unique names
		requires = [], // amd module names to be loaded
		deps = {}, // dependency graph
		context = {},
		undef;

	function uniqueName(seed) {
		return '_' + (seed ? seed : 'instance') + '_' + uniqueNameCount++;
	}

	function isModule(spec) {
		return spec.module;
	}

	function isRef(spec) {
		return spec.$ref !== undef;
	}

	function isArray(it) {
		return tos.call(it) === arrt;
	}

	function pivot(map) {
		// Pivots a map of key -> array, and returns the pivoted version
		// map: Object
		// 		Must be a set of key -> array pairs
		var pivoted = {};

		for(var p in map) {
			var arr = map[p];
			for (var i = arr.length - 1; i >= 0; i--){
				var key = arr[i];
				if(!pivoted[key]) {
					pivoted[key] = [];
				}

				pivoted[key].push(p);
			};
		}

		return pivoted;
	}

	function collectModules(spec) {
		// Look for modules in objects and arrays.  Skip simple values
		// in this pass.
		if(isArray(spec)) {
			collectModulesFromArray(spec);
		} else if(typeof spec == 'object') {

			if(isModule(spec)) {
				requires.push(spec.module);

				// TODO: REMOVE
				// For testing only
				// define(name, [], spec.module);

				if(spec.properties) {
					collectModules(spec.properties);
				} else if (spec.args) {
					collectModules(spec.args);
				}

			} else {
				for(var prop in spec) {
					collectModules(spec[prop], prop);
				}
			}
		}
	}

	function collectModulesFromArray(arr) {
		for (var i = arr.length - 1; i >= 0; i--){
			collectModules(arr[i]);
		};
	}

	function loadModules(moduleNames, callback) {
		require(moduleNames, callback);
	}

	function getLoadedModule(name) {
		return require(name);
	}

	function constructWithFactory(spec, name) {
		var module = getLoadedModule(name);
		if(!module) {
			throw Error("ERROR: no module loaded with name: " + name);
		}

		var func = spec.create.name,
			args = spec.create.args ? construct(spec.create.args) : [];

		return module[func].apply(module, args);
	}

	function constructWithNew(spec, name) {
		var module = getLoadedModule(spec.module);
		if(!module) {
			throw Error("ERROR: no module loaded with name: " + name);
		}

		return spec.create ? instantiate(module, spec.create) : new module();
	}

	var Factory = function Factory(ctor, args) {
			return ctor.apply(this, args);
		};

	function instantiate(ctor, args) {
		Factory.prototype = ctor.prototype;
		Factory.prototype.constructor = ctor;
		return new Factory(ctor, construct(args));
	}

	function callInit(target, func, args) {
		args = args ? construct(args) : [];
		func.apply(target, isArray(args) ? args : [args]);
	}

	function addReadyInit(target, func, args) {
		require.ready(function() {
			callInit(target, func, args);
		});
	}

	function setProperties(target, properties) {
		// TODO: plugins for property setting?
		var set = typeof target.set == 'function'
			? function(key, value) { target.set(key, construct(value)); }
			: function(key, value) { target[key] = construct(value); };

		for(var p in properties) {
			set(p, construct(properties[p], p));
		}
	}

	function processFuncList(list, target, callback) {
		var func;
		if(typeof list == "string") {
			// console.log("calling " + list + "()");
			func = target[list];
			if(typeof func == "function") {
				callback(target, func, []);
			}
		} else {
			for(var f in list) {
				// console.log("calling " + f + "(" + list[f] + ")");
				func = target[f];
				if(typeof func == "function") {
					callback(target, func, list[f]);
				}
			}
		}
	}

	function construct(spec, name) {
		// By default, just return the spec if it's not an object or array
		var result = spec;

		// If spec is an object or array, process it
		if(isArray(spec)) {
			// If it's an array, construct() each element
			result = [];
			for (var i=0; i < spec.length; i++) {
				result.push(construct(spec[i]));
			}

		} else if(typeof spec == 'object') {
			// If it's a module
			//  - if it has a create function, call it, with args and set result
			//  - if no factory function, invoke new as constructor and set result
			//  - if init function, invoke after factory or constructor
			// If it's a reference
			//  - resolve the reference directly, no recursive construction
			// If it's not a module
			//  - recursive construct() and set result
			if(isModule(spec)) {
				name = name || spec.name;
				if(spec.create) {
					// TODO: Handle calling a factory method and using the return value as result? See constructWithFactory()
					// console.log('constructing ' + name + " from " + spec.module);
					result = constructWithNew(spec, name);
				} else {
					// console.log('setting ' + name + ' as module ' + spec.module + ' directly');
					result = getLoadedModule(spec.module);
				}

				if(spec.properties && typeof spec.properties == 'object') {
					// console.log("setting props on " + spec.name);

					setProperties(result, spec.properties);
				}

				// If it has init functions, call it
				if(spec.init) {
					processFuncList(spec.init, result, addReadyInit);
				}

				if(name) context[name] = result;

			} else if (isRef(spec)) {
				result = resolve(spec.$ref);
			} else {
				result = {};
				for(var prop in spec) {
					result[prop] = construct(spec[prop], prop);
				}
			}
		} else {
			if(name) context[name] = result;
		}

		return result;
	}

	function resolve(ref) {
		// Resolve a reference
		// TODO: Plugins for resolving references?

		return context[ref];
	}

	// main wire() export
	var w = function(spec, ready) {
		// 1. First pass, build module list for require, call require
		// 2. Second pass, depth first instantiate

		// First pass
		collectModules(spec);

		// Second pass happens after modules loaded by require loader
		require(requires, function() {
			// Second pass, construct actual instances
			var context = construct(spec);

			// Call callback when entire context is ready
			ready(context);
		});

	};

	// Export other helpers
	w.construct = construct;
	w.resolve = resolve;

	return w;
})();

// Fake require.  REMOVE!!!  Testing only

(function(window){
	var modules = {},
		uniqueNameCount = 0,
		tos = Object.prototype.toString,
		arrt = '[object Array]';

	function uniqueName() {
		return "_" + uniqueNameCount++;
	}

	if(!window.define) {
		window.define = function(name, deps, factory) {
			if(!factory) {
				name = uniqueName();
				deps = name;
				factory = deps;
			}

			if(!(name in modules)) {
				modules[name] = typeof factory == "function" ? factory() : factory;
			}
		};
	}

	if(!window.require) {
		var r = window.require = function(deps, callback) {
			if(tos.call(deps) === arrt) {
				// deps is an array
				var args = [];
				for (var i=0; i < deps.length; i++) {
					args.push(modules[deps[i]]);
				};
				return callback.apply(null, args);
			}
			else {
				// deps is a name
				var module = modules[deps];
				return module;
			}
		};

		r.ready = function(func) {
			func();
		};
	}

})(window);

<|endoftext|>


<commit_before>'use strict'

var solc = require('solc/wrapper')
var solcABI = require('solc/abi')

var webworkify = require('webworkify')

var compilerInput = require('./compiler-input')

var remixLib = require('remix-lib')
var EventManager = remixLib.EventManager

var txHelper = require('./txHelper')

/*
  trigger compilationFinished, compilerLoaded, compilationStarted, compilationDuration
*/
function Compiler (handleImportCall) {
  var self = this
  this.event = new EventManager()

  var compileJSON

  var worker = null

  var currentVersion

  var optimize = false

  this.setOptimize = function (_optimize) {
    optimize = _optimize
  }

  var compilationStartTime = null
  this.event.register('compilationFinished', (success, data, source) => {
    if (success && compilationStartTime) {
      this.event.trigger('compilationDuration', [(new Date().getTime()) - compilationStartTime])
    }
    compilationStartTime = null
  })

  this.event.register('compilationStarted', () => {
    compilationStartTime = new Date().getTime()
  })

  var internalCompile = function (files, target, missingInputs) {
    gatherImports(files, target, missingInputs, function (error, input) {
      if (error) {
        self.lastCompilationResult = null
        self.event.trigger('compilationFinished', [false, {'error': { formattedMessage: error, severity: 'error' }}, files])
      } else {
        compileJSON(input, optimize ? 1 : 0)
      }
    })
  }

  var compile = function (files, target) {
    self.event.trigger('compilationStarted', [])
    internalCompile(files, target)
  }
  this.compile = compile

  function setCompileJSON (_compileJSON) {
    compileJSON = _compileJSON
  }
  this.setCompileJSON = setCompileJSON // this is exposed for testing

  function onCompilerLoaded (version) {
    currentVersion = version
    self.event.trigger('compilerLoaded', [version])
  }

  function onInternalCompilerLoaded () {
    if (worker === null) {
      var compiler;
      if (typeof(window) == 'undefined') {
        compiler = require('solc');
      } else {
        compiler = solc(window.Module)
      }

      compileJSON = function (source, optimize, cb) {
        var missingInputs = []
        var missingInputsCallback = function (path) {
          missingInputs.push(path)
          return { error: 'Deferred import' }
        }

        var result
        try {
          var input = compilerInput(source.sources, {optimize: optimize, target: source.target})
          result = compiler.compileStandardWrapper(input, missingInputsCallback)
          result = JSON.parse(result)
        } catch (exception) {
          result = { error: 'Uncaught JavaScript exception:\n' + exception }
        }

        compilationFinished(result, missingInputs, source)
      }
      onCompilerLoaded(compiler.version())
    }
  }
  this.onInternalCompilerLoaded = onInternalCompilerLoaded; // exposed for use in node

  this.lastCompilationResult = {
    data: null,
    source: null
  }

  /**
    * return the contract obj of the given @arg name. Uses last compilation result.
    * return null if not found
    * @param {String} name    - contract name
    * @returns contract obj and associated file: { contract, file } or null
    */
  this.getContract = (name) => {
    if (this.lastCompilationResult.data && this.lastCompilationResult.data.contracts) {
      return txHelper.getContract(name, this.lastCompilationResult.data.contracts)
    }
    return null
  }

  /**
    * call the given @arg cb (function) for all the contracts. Uses last compilation result
    * @param {Function} cb    - callback
    */
  this.visitContracts = (cb) => {
    if (this.lastCompilationResult.data && this.lastCompilationResult.data.contracts) {
      return txHelper.visitContracts(this.lastCompilationResult.data.contracts, cb)
    }
    return null
  }

  /**
    * return the compiled contracts from the last compilation result
    * @return {Object}     - contracts
    */
  this.getContracts = () => {
    if (this.lastCompilationResult.data && this.lastCompilationResult.data.contracts) {
      return this.lastCompilationResult.data.contracts
    }
    return null
  }

   /**
    * return the sources from the last compilation result
    * @param {Object} cb    - map of sources
    */
  this.getSources = () => {
    if (this.lastCompilationResult.source) {
      return this.lastCompilationResult.source.sources
    }
    return null
  }

  /**
    * return the sources @arg fileName from the last compilation result
    * @param {Object} cb    - map of sources
    */
  this.getSource = (fileName) => {
    if (this.lastCompilationResult.source) {
      return this.lastCompilationResult.source.sources[fileName]
    }
    return null
  }

  /**
    * return the source from the last compilation result that has the given index. null if source not found
    * @param {Int} index    - index of the source
    */
  this.getSourceName = (index) => {
    if (this.lastCompilationResult.data && this.lastCompilationResult.data.sources) {
      return Object.keys(this.lastCompilationResult.data.sources)[index]
    }
    return null
  }

  function compilationFinished (data, missingInputs, source) {
    var noFatalErrors = true // ie warnings are ok

    function isValidError (error) {
      // The deferred import is not a real error
      // FIXME: maybe have a better check?
      if (/Deferred import/.exec(error.message)) {
        return false
      }

      return error.severity !== 'warning'
    }

    if (data['error'] !== undefined) {
      // Ignore warnings (and the 'Deferred import' error as those are generated by us as a workaround
      if (isValidError(data['error'])) {
        noFatalErrors = false
      }
    }
    if (data['errors'] !== undefined) {
      data['errors'].forEach(function (err) {
        // Ignore warnings and the 'Deferred import' error as those are generated by us as a workaround
        if (isValidError(err)) {
          noFatalErrors = false
        }
      })
    }

    if (!noFatalErrors) {
      // There are fatal errors - abort here
      self.lastCompilationResult = null
      self.event.trigger('compilationFinished', [false, data, source])
    } else if (missingInputs !== undefined && missingInputs.length > 0) {
      // try compiling again with the new set of inputs
      internalCompile(source.sources, source.target, missingInputs)
    } else {
      data = updateInterface(data)

      self.lastCompilationResult = {
        data: data,
        source: source
      }
      self.event.trigger('compilationFinished', [true, data, source])
    }
  }

  // TODO: needs to be changed to be more node friendly
  this.loadVersion = function (usingWorker, url) {
    console.log('Loading ' + url + ' ' + (usingWorker ? 'with worker' : 'without worker'))
    self.event.trigger('loadingCompiler', [url, usingWorker])

    if (usingWorker) {
      loadWorker(url)
    } else {
      loadInternal(url)
    }
  }

  function loadInternal (url) {
    delete window.Module
    // NOTE: workaround some browsers?
    window.Module = undefined

    // Set a safe fallback until the new one is loaded
    setCompileJSON(function (source, optimize) {
      compilationFinished({ error: { formattedMessage: 'Compiler not yet loaded.' } })
    })

    var newScript = document.createElement('script')
    newScript.type = 'text/javascript'
    newScript.src = url
    document.getElementsByTagName('head')[0].appendChild(newScript)
    var check = window.setInterval(function () {
      if (!window.Module) {
        return
      }
      window.clearInterval(check)
      onInternalCompilerLoaded()
    }, 200)
  }

  function loadWorker (url) {
    if (worker !== null) {
      worker.terminate()
    }
    worker = webworkify(require('./compiler-worker.js'))
    var jobs = []
    worker.addEventListener('message', function (msg) {
      var data = msg.data
      switch (data.cmd) {
        case 'versionLoaded':
          onCompilerLoaded(data.data)
          break
        case 'compiled':
          var result
          try {
            result = JSON.parse(data.data)
          } catch (exception) {
            result = { 'error': 'Invalid JSON output from the compiler: ' + exception }
          }
          var sources = {}
          if (data.job in jobs !== undefined) {
            sources = jobs[data.job].sources
            delete jobs[data.job]
          }
          compilationFinished(result, data.missingInputs, sources)
          break
      }
    })
    worker.onerror = function (msg) {
      compilationFinished({ error: 'Worker error: ' + msg.data })
    }
    worker.addEventListener('error', function (msg) {
      compilationFinished({ error: 'Worker error: ' + msg.data })
    })
    compileJSON = function (source, optimize) {
      jobs.push({sources: source})
      worker.postMessage({cmd: 'compile', job: jobs.length - 1, input: compilerInput(source.sources, {optimize: optimize, target: source.target})})
    }
    worker.postMessage({cmd: 'loadVersion', data: url})
  }

  function gatherImports (files, target, importHints, cb) {
    importHints = importHints || []

    // FIXME: This will only match imports if the file begins with one.
    //        It should tokenize by lines and check each.
    // eslint-disable-next-line no-useless-escape
    var importRegex = /^\s*import\s*[\'\"]([^\'\"]+)[\'\"];/g

    for (var fileName in files) {
      var match
      while ((match = importRegex.exec(files[fileName].content))) {
        var importFilePath = match[1]
        if (importFilePath.startsWith('./')) {
          var path = /(.*\/).*/.exec(target)
          if (path !== null) {
            importFilePath = importFilePath.replace('./', path[1])
          } else {
            importFilePath = importFilePath.slice(2)
          }
        }

        // FIXME: should be using includes or sets, but there's also browser compatibility..
        if (importHints.indexOf(importFilePath) === -1) {
          importHints.push(importFilePath)
        }
      }
    }

    while (importHints.length > 0) {
      var m = importHints.pop()
      if (m in files) {
        continue
      }

      if (handleImportCall) {
        handleImportCall(m, function (err, content) {
          if (err) {
            cb(err)
          } else {
            files[m] = { content }
            gatherImports(files, target, importHints, cb)
          }
        })
      }

      return
    }

    cb(null, { 'sources': files, 'target': target })
  }

  function truncateVersion (version) {
    var tmp = /^(\d+.\d+.\d+)/.exec(version)
    if (tmp) {
      return tmp[1]
    }
    return version
  }

  function updateInterface (data) {
    txHelper.visitContracts(data.contracts, (contract) => {
      data.contracts[contract.file][contract.name].abi = solcABI.update(truncateVersion(currentVersion), contract.object.abi)
    })
    return data
  }
}

module.exports = Compiler
<commit_msg>lint is king<commit_after>'use strict'

var solc = require('solc/wrapper')
var solcABI = require('solc/abi')

var webworkify = require('webworkify')

var compilerInput = require('./compiler-input')

var remixLib = require('remix-lib')
var EventManager = remixLib.EventManager

var txHelper = require('./txHelper')

/*
  trigger compilationFinished, compilerLoaded, compilationStarted, compilationDuration
*/
function Compiler (handleImportCall) {
  var self = this
  this.event = new EventManager()

  var compileJSON

  var worker = null

  var currentVersion

  var optimize = false

  this.setOptimize = function (_optimize) {
    optimize = _optimize
  }

  var compilationStartTime = null
  this.event.register('compilationFinished', (success, data, source) => {
    if (success && compilationStartTime) {
      this.event.trigger('compilationDuration', [(new Date().getTime()) - compilationStartTime])
    }
    compilationStartTime = null
  })

  this.event.register('compilationStarted', () => {
    compilationStartTime = new Date().getTime()
  })

  var internalCompile = function (files, target, missingInputs) {
    gatherImports(files, target, missingInputs, function (error, input) {
      if (error) {
        self.lastCompilationResult = null
        self.event.trigger('compilationFinished', [false, {'error': { formattedMessage: error, severity: 'error' }}, files])
      } else {
        compileJSON(input, optimize ? 1 : 0)
      }
    })
  }

  var compile = function (files, target) {
    self.event.trigger('compilationStarted', [])
    internalCompile(files, target)
  }
  this.compile = compile

  function setCompileJSON (_compileJSON) {
    compileJSON = _compileJSON
  }
  this.setCompileJSON = setCompileJSON // this is exposed for testing

  function onCompilerLoaded (version) {
    currentVersion = version
    self.event.trigger('compilerLoaded', [version])
  }

  function onInternalCompilerLoaded () {
    if (worker === null) {
      var compiler
      if (typeof (window) === 'undefined') {
        compiler = require('solc')
      } else {
        compiler = solc(window.Module)
      }

      compileJSON = function (source, optimize, cb) {
        var missingInputs = []
        var missingInputsCallback = function (path) {
          missingInputs.push(path)
          return { error: 'Deferred import' }
        }

        var result
        try {
          var input = compilerInput(source.sources, {optimize: optimize, target: source.target})
          result = compiler.compileStandardWrapper(input, missingInputsCallback)
          result = JSON.parse(result)
        } catch (exception) {
          result = { error: 'Uncaught JavaScript exception:\n' + exception }
        }

        compilationFinished(result, missingInputs, source)
      }
      onCompilerLoaded(compiler.version())
    }
  }
  // exposed for use in node
  this.onInternalCompilerLoaded = onInternalCompilerLoaded

  this.lastCompilationResult = {
    data: null,
    source: null
  }

  /**
    * return the contract obj of the given @arg name. Uses last compilation result.
    * return null if not found
    * @param {String} name    - contract name
    * @returns contract obj and associated file: { contract, file } or null
    */
  this.getContract = (name) => {
    if (this.lastCompilationResult.data && this.lastCompilationResult.data.contracts) {
      return txHelper.getContract(name, this.lastCompilationResult.data.contracts)
    }
    return null
  }

  /**
    * call the given @arg cb (function) for all the contracts. Uses last compilation result
    * @param {Function} cb    - callback
    */
  this.visitContracts = (cb) => {
    if (this.lastCompilationResult.data && this.lastCompilationResult.data.contracts) {
      return txHelper.visitContracts(this.lastCompilationResult.data.contracts, cb)
    }
    return null
  }

  /**
    * return the compiled contracts from the last compilation result
    * @return {Object}     - contracts
    */
  this.getContracts = () => {
    if (this.lastCompilationResult.data && this.lastCompilationResult.data.contracts) {
      return this.lastCompilationResult.data.contracts
    }
    return null
  }

   /**
    * return the sources from the last compilation result
    * @param {Object} cb    - map of sources
    */
  this.getSources = () => {
    if (this.lastCompilationResult.source) {
      return this.lastCompilationResult.source.sources
    }
    return null
  }

  /**
    * return the sources @arg fileName from the last compilation result
    * @param {Object} cb    - map of sources
    */
  this.getSource = (fileName) => {
    if (this.lastCompilationResult.source) {
      return this.lastCompilationResult.source.sources[fileName]
    }
    return null
  }

  /**
    * return the source from the last compilation result that has the given index. null if source not found
    * @param {Int} index    - index of the source
    */
  this.getSourceName = (index) => {
    if (this.lastCompilationResult.data && this.lastCompilationResult.data.sources) {
      return Object.keys(this.lastCompilationResult.data.sources)[index]
    }
    return null
  }

  function compilationFinished (data, missingInputs, source) {
    var noFatalErrors = true // ie warnings are ok

    function isValidError (error) {
      // The deferred import is not a real error
      // FIXME: maybe have a better check?
      if (/Deferred import/.exec(error.message)) {
        return false
      }

      return error.severity !== 'warning'
    }

    if (data['error'] !== undefined) {
      // Ignore warnings (and the 'Deferred import' error as those are generated by us as a workaround
      if (isValidError(data['error'])) {
        noFatalErrors = false
      }
    }
    if (data['errors'] !== undefined) {
      data['errors'].forEach(function (err) {
        // Ignore warnings and the 'Deferred import' error as those are generated by us as a workaround
        if (isValidError(err)) {
          noFatalErrors = false
        }
      })
    }

    if (!noFatalErrors) {
      // There are fatal errors - abort here
      self.lastCompilationResult = null
      self.event.trigger('compilationFinished', [false, data, source])
    } else if (missingInputs !== undefined && missingInputs.length > 0) {
      // try compiling again with the new set of inputs
      internalCompile(source.sources, source.target, missingInputs)
    } else {
      data = updateInterface(data)

      self.lastCompilationResult = {
        data: data,
        source: source
      }
      self.event.trigger('compilationFinished', [true, data, source])
    }
  }

  // TODO: needs to be changed to be more node friendly
  this.loadVersion = function (usingWorker, url) {
    console.log('Loading ' + url + ' ' + (usingWorker ? 'with worker' : 'without worker'))
    self.event.trigger('loadingCompiler', [url, usingWorker])

    if (usingWorker) {
      loadWorker(url)
    } else {
      loadInternal(url)
    }
  }

  function loadInternal (url) {
    delete window.Module
    // NOTE: workaround some browsers?
    window.Module = undefined

    // Set a safe fallback until the new one is loaded
    setCompileJSON(function (source, optimize) {
      compilationFinished({ error: { formattedMessage: 'Compiler not yet loaded.' } })
    })

    var newScript = document.createElement('script')
    newScript.type = 'text/javascript'
    newScript.src = url
    document.getElementsByTagName('head')[0].appendChild(newScript)
    var check = window.setInterval(function () {
      if (!window.Module) {
        return
      }
      window.clearInterval(check)
      onInternalCompilerLoaded()
    }, 200)
  }

  function loadWorker (url) {
    if (worker !== null) {
      worker.terminate()
    }
    worker = webworkify(require('./compiler-worker.js'))
    var jobs = []
    worker.addEventListener('message', function (msg) {
      var data = msg.data
      switch (data.cmd) {
        case 'versionLoaded':
          onCompilerLoaded(data.data)
          break
        case 'compiled':
          var result
          try {
            result = JSON.parse(data.data)
          } catch (exception) {
            result = { 'error': 'Invalid JSON output from the compiler: ' + exception }
          }
          var sources = {}
          if (data.job in jobs !== undefined) {
            sources = jobs[data.job].sources
            delete jobs[data.job]
          }
          compilationFinished(result, data.missingInputs, sources)
          break
      }
    })
    worker.onerror = function (msg) {
      compilationFinished({ error: 'Worker error: ' + msg.data })
    }
    worker.addEventListener('error', function (msg) {
      compilationFinished({ error: 'Worker error: ' + msg.data })
    })
    compileJSON = function (source, optimize) {
      jobs.push({sources: source})
      worker.postMessage({cmd: 'compile', job: jobs.length - 1, input: compilerInput(source.sources, {optimize: optimize, target: source.target})})
    }
    worker.postMessage({cmd: 'loadVersion', data: url})
  }

  function gatherImports (files, target, importHints, cb) {
    importHints = importHints || []

    // FIXME: This will only match imports if the file begins with one.
    //        It should tokenize by lines and check each.
    // eslint-disable-next-line no-useless-escape
    var importRegex = /^\s*import\s*[\'\"]([^\'\"]+)[\'\"];/g

    for (var fileName in files) {
      var match
      while ((match = importRegex.exec(files[fileName].content))) {
        var importFilePath = match[1]
        if (importFilePath.startsWith('./')) {
          var path = /(.*\/).*/.exec(target)
          if (path !== null) {
            importFilePath = importFilePath.replace('./', path[1])
          } else {
            importFilePath = importFilePath.slice(2)
          }
        }

        // FIXME: should be using includes or sets, but there's also browser compatibility..
        if (importHints.indexOf(importFilePath) === -1) {
          importHints.push(importFilePath)
        }
      }
    }

    while (importHints.length > 0) {
      var m = importHints.pop()
      if (m in files) {
        continue
      }

      if (handleImportCall) {
        handleImportCall(m, function (err, content) {
          if (err) {
            cb(err)
          } else {
            files[m] = { content }
            gatherImports(files, target, importHints, cb)
          }
        })
      }

      return
    }

    cb(null, { 'sources': files, 'target': target })
  }

  function truncateVersion (version) {
    var tmp = /^(\d+.\d+.\d+)/.exec(version)
    if (tmp) {
      return tmp[1]
    }
    return version
  }

  function updateInterface (data) {
    txHelper.visitContracts(data.contracts, (contract) => {
      data.contracts[contract.file][contract.name].abi = solcABI.update(truncateVersion(currentVersion), contract.object.abi)
    })
    return data
  }
}

module.exports = Compiler
<|endoftext|>


<commit_before>'use strict'

var solc = require('solc/wrapper')
var solcABI = require('solc/abi')

var webworkify = require('webworkify')

var compilerInput = require('./compiler-input')

var remixLib = require('remix-lib')
var EventManager = remixLib.EventManager

var txHelper = require('./txHelper')

/*
  trigger compilationFinished, compilerLoaded, compilationStarted, compilationDuration
*/
function Compiler (handleImportCall) {
  var self = this
  this.event = new EventManager()

  var compileJSON

  var worker = null

  var currentVersion

  var optimize = false

  this.setOptimize = function (_optimize) {
    optimize = _optimize
  }

  var compilationStartTime = null
  this.event.register('compilationFinished', (success, data, source) => {
    if (success && compilationStartTime) {
      this.event.trigger('compilationDuration', [(new Date().getTime()) - compilationStartTime])
    }
    compilationStartTime = null
  })

  this.event.register('compilationStarted', () => {
    compilationStartTime = new Date().getTime()
  })

  var internalCompile = function (files, target, missingInputs) {
    gatherImports(files, target, missingInputs, function (error, input) {
      if (error) {
        self.lastCompilationResult = null
        self.event.trigger('compilationFinished', [false, {'error': { formattedMessage: error, severity: 'error' }}, files])
      } else {
        compileJSON(input, optimize ? 1 : 0)
      }
    })
  }

  var compile = function (files, target) {
    self.event.trigger('compilationStarted', [])
    internalCompile(files, target)
  }
  this.compile = compile

  function setCompileJSON (_compileJSON) {
    compileJSON = _compileJSON
  }
  this.setCompileJSON = setCompileJSON // this is exposed for testing

  function onCompilerLoaded (version) {
    currentVersion = version
    self.event.trigger('compilerLoaded', [version])
  }

  function onInternalCompilerLoaded () {
    if (worker === null) {
      var compiler = solc(window.Module)

      compileJSON = function (source, optimize, cb) {
        var missingInputs = []
        var missingInputsCallback = function (path) {
          missingInputs.push(path)
          return { error: 'Deferred import' }
        }

        var result
        try {
          var input = compilerInput(source.sources, {optimize: optimize, target: source.target})
          result = compiler.compileStandardWrapper(input, missingInputsCallback)
          result = JSON.parse(result)
        } catch (exception) {
          result = { error: 'Uncaught JavaScript exception:\n' + exception }
        }

        compilationFinished(result, missingInputs, source)
      }
      onCompilerLoaded(compiler.version())
    }
  }
  // exposed for use in node
  this.onInternalCompilerLoaded = onInternalCompilerLoaded

  this.lastCompilationResult = {
    data: null,
    source: null
  }

  /**
    * return the contract obj of the given @arg name. Uses last compilation result.
    * return null if not found
    * @param {String} name    - contract name
    * @returns contract obj and associated file: { contract, file } or null
    */
  this.getContract = (name) => {
    if (this.lastCompilationResult.data && this.lastCompilationResult.data.contracts) {
      return txHelper.getContract(name, this.lastCompilationResult.data.contracts)
    }
    return null
  }

  /**
    * call the given @arg cb (function) for all the contracts. Uses last compilation result
    * @param {Function} cb    - callback
    */
  this.visitContracts = (cb) => {
    if (this.lastCompilationResult.data && this.lastCompilationResult.data.contracts) {
      return txHelper.visitContracts(this.lastCompilationResult.data.contracts, cb)
    }
    return null
  }

  /**
    * return the compiled contracts from the last compilation result
    * @return {Object}     - contracts
    */
  this.getContracts = () => {
    if (this.lastCompilationResult.data && this.lastCompilationResult.data.contracts) {
      return this.lastCompilationResult.data.contracts
    }
    return null
  }

   /**
    * return the sources from the last compilation result
    * @param {Object} cb    - map of sources
    */
  this.getSources = () => {
    if (this.lastCompilationResult.source) {
      return this.lastCompilationResult.source.sources
    }
    return null
  }

  /**
    * return the sources @arg fileName from the last compilation result
    * @param {Object} cb    - map of sources
    */
  this.getSource = (fileName) => {
    if (this.lastCompilationResult.source) {
      return this.lastCompilationResult.source.sources[fileName]
    }
    return null
  }

  /**
    * return the source from the last compilation result that has the given index. null if source not found
    * @param {Int} index    - index of the source
    */
  this.getSourceName = (index) => {
    if (this.lastCompilationResult.data && this.lastCompilationResult.data.sources) {
      return Object.keys(this.lastCompilationResult.data.sources)[index]
    }
    return null
  }

  function compilationFinished (data, missingInputs, source) {
    var noFatalErrors = true // ie warnings are ok

    function isValidError (error) {
      // The deferred import is not a real error
      // FIXME: maybe have a better check?
      if (/Deferred import/.exec(error.message)) {
        return false
      }

      return error.severity !== 'warning'
    }

    if (data['error'] !== undefined) {
      // Ignore warnings (and the 'Deferred import' error as those are generated by us as a workaround
      if (isValidError(data['error'])) {
        noFatalErrors = false
      }
    }
    if (data['errors'] !== undefined) {
      data['errors'].forEach(function (err) {
        // Ignore warnings and the 'Deferred import' error as those are generated by us as a workaround
        if (isValidError(err)) {
          noFatalErrors = false
        }
      })
    }

    if (!noFatalErrors) {
      // There are fatal errors - abort here
      self.lastCompilationResult = null
      self.event.trigger('compilationFinished', [false, data, source])
    } else if (missingInputs !== undefined && missingInputs.length > 0) {
      // try compiling again with the new set of inputs
      internalCompile(source.sources, source.target, missingInputs)
    } else {
      data = updateInterface(data)

      self.lastCompilationResult = {
        data: data,
        source: source
      }
      self.event.trigger('compilationFinished', [true, data, source])
    }
  }

  // TODO: needs to be changed to be more node friendly
  this.loadVersion = function (usingWorker, url) {
    console.log('Loading ' + url + ' ' + (usingWorker ? 'with worker' : 'without worker'))
    self.event.trigger('loadingCompiler', [url, usingWorker])

    if (usingWorker) {
      loadWorker(url)
    } else {
      loadInternal(url)
    }
  }

  function loadInternal (url) {
    delete window.Module
    // NOTE: workaround some browsers?
    window.Module = undefined

    // Set a safe fallback until the new one is loaded
    setCompileJSON(function (source, optimize) {
      compilationFinished({ error: { formattedMessage: 'Compiler not yet loaded.' } })
    })

    var newScript = document.createElement('script')
    newScript.type = 'text/javascript'
    newScript.src = url
    document.getElementsByTagName('head')[0].appendChild(newScript)
    var check = window.setInterval(function () {
      if (!window.Module) {
        return
      }
      window.clearInterval(check)
      onInternalCompilerLoaded()
    }, 200)
  }

  function loadWorker (url) {
    if (worker !== null) {
      worker.terminate()
    }
    worker = webworkify(require('./compiler-worker.js'))
    var jobs = []
    worker.addEventListener('message', function (msg) {
      var data = msg.data
      switch (data.cmd) {
        case 'versionLoaded':
          onCompilerLoaded(data.data)
          break
        case 'compiled':
          var result
          try {
            result = JSON.parse(data.data)
          } catch (exception) {
            result = { 'error': 'Invalid JSON output from the compiler: ' + exception }
          }
          var sources = {}
          if (data.job in jobs !== undefined) {
            sources = jobs[data.job].sources
            delete jobs[data.job]
          }
          compilationFinished(result, data.missingInputs, sources)
          break
      }
    })
    worker.onerror = function (msg) {
      compilationFinished({ error: 'Worker error: ' + msg.data })
    }
    worker.addEventListener('error', function (msg) {
      compilationFinished({ error: 'Worker error: ' + msg.data })
    })
    compileJSON = function (source, optimize) {
      jobs.push({sources: source})
      worker.postMessage({cmd: 'compile', job: jobs.length - 1, input: compilerInput(source.sources, {optimize: optimize, target: source.target})})
    }
    worker.postMessage({cmd: 'loadVersion', data: url})
  }

  function gatherImports (files, target, importHints, cb) {
    importHints = importHints || []

    // FIXME: This will only match imports if the file begins with one.
    //        It should tokenize by lines and check each.
    // eslint-disable-next-line no-useless-escape
    var importRegex = /^\s*import\s*[\'\"]([^\'\"]+)[\'\"];/g

    for (var fileName in files) {
      var match
      while ((match = importRegex.exec(files[fileName].content))) {
        var importFilePath = match[1]
        if (importFilePath.startsWith('./')) {
          var path = /(.*\/).*/.exec(target)
          if (path !== null) {
            importFilePath = importFilePath.replace('./', path[1])
          } else {
            importFilePath = importFilePath.slice(2)
          }
        }

        // FIXME: should be using includes or sets, but there's also browser compatibility..
        if (importHints.indexOf(importFilePath) === -1) {
          importHints.push(importFilePath)
        }
      }
    }

    while (importHints.length > 0) {
      var m = importHints.pop()
      if (m in files) {
        continue
      }

      if (handleImportCall) {
        handleImportCall(m, function (err, content) {
          if (err) {
            cb(err)
          } else {
            files[m] = { content }
            gatherImports(files, target, importHints, cb)
          }
        })
      }

      return
    }

    cb(null, { 'sources': files, 'target': target })
  }

  function truncateVersion (version) {
    var tmp = /^(\d+.\d+.\d+)/.exec(version)
    if (tmp) {
      return tmp[1]
    }
    return version
  }

  function updateInterface (data) {
    txHelper.visitContracts(data.contracts, (contract) => {
      data.contracts[contract.file][contract.name].abi = solcABI.update(truncateVersion(currentVersion), contract.object.abi)
    })
    return data
  }
}

module.exports = Compiler
<commit_msg>Revert "remove solc require which is causing issues with browserify"<commit_after>'use strict'

var solc = require('solc/wrapper')
var solcABI = require('solc/abi')

var webworkify = require('webworkify')

var compilerInput = require('./compiler-input')

var remixLib = require('remix-lib')
var EventManager = remixLib.EventManager

var txHelper = require('./txHelper')

/*
  trigger compilationFinished, compilerLoaded, compilationStarted, compilationDuration
*/
function Compiler (handleImportCall) {
  var self = this
  this.event = new EventManager()

  var compileJSON

  var worker = null

  var currentVersion

  var optimize = false

  this.setOptimize = function (_optimize) {
    optimize = _optimize
  }

  var compilationStartTime = null
  this.event.register('compilationFinished', (success, data, source) => {
    if (success && compilationStartTime) {
      this.event.trigger('compilationDuration', [(new Date().getTime()) - compilationStartTime])
    }
    compilationStartTime = null
  })

  this.event.register('compilationStarted', () => {
    compilationStartTime = new Date().getTime()
  })

  var internalCompile = function (files, target, missingInputs) {
    gatherImports(files, target, missingInputs, function (error, input) {
      if (error) {
        self.lastCompilationResult = null
        self.event.trigger('compilationFinished', [false, {'error': { formattedMessage: error, severity: 'error' }}, files])
      } else {
        compileJSON(input, optimize ? 1 : 0)
      }
    })
  }

  var compile = function (files, target) {
    self.event.trigger('compilationStarted', [])
    internalCompile(files, target)
  }
  this.compile = compile

  function setCompileJSON (_compileJSON) {
    compileJSON = _compileJSON
  }
  this.setCompileJSON = setCompileJSON // this is exposed for testing

  function onCompilerLoaded (version) {
    currentVersion = version
    self.event.trigger('compilerLoaded', [version])
  }

  function onInternalCompilerLoaded () {
    if (worker === null) {
      var compiler
      if (typeof (window) === 'undefined') {
        compiler = require('solc')
      } else {
        compiler = solc(window.Module)
      }

      compileJSON = function (source, optimize, cb) {
        var missingInputs = []
        var missingInputsCallback = function (path) {
          missingInputs.push(path)
          return { error: 'Deferred import' }
        }

        var result
        try {
          var input = compilerInput(source.sources, {optimize: optimize, target: source.target})
          result = compiler.compileStandardWrapper(input, missingInputsCallback)
          result = JSON.parse(result)
        } catch (exception) {
          result = { error: 'Uncaught JavaScript exception:\n' + exception }
        }

        compilationFinished(result, missingInputs, source)
      }
      onCompilerLoaded(compiler.version())
    }
  }
  // exposed for use in node
  this.onInternalCompilerLoaded = onInternalCompilerLoaded

  this.lastCompilationResult = {
    data: null,
    source: null
  }

  /**
    * return the contract obj of the given @arg name. Uses last compilation result.
    * return null if not found
    * @param {String} name    - contract name
    * @returns contract obj and associated file: { contract, file } or null
    */
  this.getContract = (name) => {
    if (this.lastCompilationResult.data && this.lastCompilationResult.data.contracts) {
      return txHelper.getContract(name, this.lastCompilationResult.data.contracts)
    }
    return null
  }

  /**
    * call the given @arg cb (function) for all the contracts. Uses last compilation result
    * @param {Function} cb    - callback
    */
  this.visitContracts = (cb) => {
    if (this.lastCompilationResult.data && this.lastCompilationResult.data.contracts) {
      return txHelper.visitContracts(this.lastCompilationResult.data.contracts, cb)
    }
    return null
  }

  /**
    * return the compiled contracts from the last compilation result
    * @return {Object}     - contracts
    */
  this.getContracts = () => {
    if (this.lastCompilationResult.data && this.lastCompilationResult.data.contracts) {
      return this.lastCompilationResult.data.contracts
    }
    return null
  }

   /**
    * return the sources from the last compilation result
    * @param {Object} cb    - map of sources
    */
  this.getSources = () => {
    if (this.lastCompilationResult.source) {
      return this.lastCompilationResult.source.sources
    }
    return null
  }

  /**
    * return the sources @arg fileName from the last compilation result
    * @param {Object} cb    - map of sources
    */
  this.getSource = (fileName) => {
    if (this.lastCompilationResult.source) {
      return this.lastCompilationResult.source.sources[fileName]
    }
    return null
  }

  /**
    * return the source from the last compilation result that has the given index. null if source not found
    * @param {Int} index    - index of the source
    */
  this.getSourceName = (index) => {
    if (this.lastCompilationResult.data && this.lastCompilationResult.data.sources) {
      return Object.keys(this.lastCompilationResult.data.sources)[index]
    }
    return null
  }

  function compilationFinished (data, missingInputs, source) {
    var noFatalErrors = true // ie warnings are ok

    function isValidError (error) {
      // The deferred import is not a real error
      // FIXME: maybe have a better check?
      if (/Deferred import/.exec(error.message)) {
        return false
      }

      return error.severity !== 'warning'
    }

    if (data['error'] !== undefined) {
      // Ignore warnings (and the 'Deferred import' error as those are generated by us as a workaround
      if (isValidError(data['error'])) {
        noFatalErrors = false
      }
    }
    if (data['errors'] !== undefined) {
      data['errors'].forEach(function (err) {
        // Ignore warnings and the 'Deferred import' error as those are generated by us as a workaround
        if (isValidError(err)) {
          noFatalErrors = false
        }
      })
    }

    if (!noFatalErrors) {
      // There are fatal errors - abort here
      self.lastCompilationResult = null
      self.event.trigger('compilationFinished', [false, data, source])
    } else if (missingInputs !== undefined && missingInputs.length > 0) {
      // try compiling again with the new set of inputs
      internalCompile(source.sources, source.target, missingInputs)
    } else {
      data = updateInterface(data)

      self.lastCompilationResult = {
        data: data,
        source: source
      }
      self.event.trigger('compilationFinished', [true, data, source])
    }
  }

  // TODO: needs to be changed to be more node friendly
  this.loadVersion = function (usingWorker, url) {
    console.log('Loading ' + url + ' ' + (usingWorker ? 'with worker' : 'without worker'))
    self.event.trigger('loadingCompiler', [url, usingWorker])

    if (usingWorker) {
      loadWorker(url)
    } else {
      loadInternal(url)
    }
  }

  function loadInternal (url) {
    delete window.Module
    // NOTE: workaround some browsers?
    window.Module = undefined

    // Set a safe fallback until the new one is loaded
    setCompileJSON(function (source, optimize) {
      compilationFinished({ error: { formattedMessage: 'Compiler not yet loaded.' } })
    })

    var newScript = document.createElement('script')
    newScript.type = 'text/javascript'
    newScript.src = url
    document.getElementsByTagName('head')[0].appendChild(newScript)
    var check = window.setInterval(function () {
      if (!window.Module) {
        return
      }
      window.clearInterval(check)
      onInternalCompilerLoaded()
    }, 200)
  }

  function loadWorker (url) {
    if (worker !== null) {
      worker.terminate()
    }
    worker = webworkify(require('./compiler-worker.js'))
    var jobs = []
    worker.addEventListener('message', function (msg) {
      var data = msg.data
      switch (data.cmd) {
        case 'versionLoaded':
          onCompilerLoaded(data.data)
          break
        case 'compiled':
          var result
          try {
            result = JSON.parse(data.data)
          } catch (exception) {
            result = { 'error': 'Invalid JSON output from the compiler: ' + exception }
          }
          var sources = {}
          if (data.job in jobs !== undefined) {
            sources = jobs[data.job].sources
            delete jobs[data.job]
          }
          compilationFinished(result, data.missingInputs, sources)
          break
      }
    })
    worker.onerror = function (msg) {
      compilationFinished({ error: 'Worker error: ' + msg.data })
    }
    worker.addEventListener('error', function (msg) {
      compilationFinished({ error: 'Worker error: ' + msg.data })
    })
    compileJSON = function (source, optimize) {
      jobs.push({sources: source})
      worker.postMessage({cmd: 'compile', job: jobs.length - 1, input: compilerInput(source.sources, {optimize: optimize, target: source.target})})
    }
    worker.postMessage({cmd: 'loadVersion', data: url})
  }

  function gatherImports (files, target, importHints, cb) {
    importHints = importHints || []

    // FIXME: This will only match imports if the file begins with one.
    //        It should tokenize by lines and check each.
    // eslint-disable-next-line no-useless-escape
    var importRegex = /^\s*import\s*[\'\"]([^\'\"]+)[\'\"];/g

    for (var fileName in files) {
      var match
      while ((match = importRegex.exec(files[fileName].content))) {
        var importFilePath = match[1]
        if (importFilePath.startsWith('./')) {
          var path = /(.*\/).*/.exec(target)
          if (path !== null) {
            importFilePath = importFilePath.replace('./', path[1])
          } else {
            importFilePath = importFilePath.slice(2)
          }
        }

        // FIXME: should be using includes or sets, but there's also browser compatibility..
        if (importHints.indexOf(importFilePath) === -1) {
          importHints.push(importFilePath)
        }
      }
    }

    while (importHints.length > 0) {
      var m = importHints.pop()
      if (m in files) {
        continue
      }

      if (handleImportCall) {
        handleImportCall(m, function (err, content) {
          if (err) {
            cb(err)
          } else {
            files[m] = { content }
            gatherImports(files, target, importHints, cb)
          }
        })
      }

      return
    }

    cb(null, { 'sources': files, 'target': target })
  }

  function truncateVersion (version) {
    var tmp = /^(\d+.\d+.\d+)/.exec(version)
    if (tmp) {
      return tmp[1]
    }
    return version
  }

  function updateInterface (data) {
    txHelper.visitContracts(data.contracts, (contract) => {
      data.contracts[contract.file][contract.name].abi = solcABI.update(truncateVersion(currentVersion), contract.object.abi)
    })
    return data
  }
}

module.exports = Compiler
<|endoftext|>


<commit_before>moduleAid.VERSION = '2.0.0';
moduleAid.LAZY = true;

// xmlHttpRequest(url, callback, method, async) - aid for quickly using the nsIXMLHttpRequest interface
//	url - (string) to send the request
//	callback - (function) to be called after request is completed; expects callback(xmlhttp, e) where xmlhttp = xmlhttprequest return object and e = event object
//	(optional) method - either (string) "POST" or (string) "GET"
//	(optional) async - (bool) defines whether to perform the operation asynchronously, defaults to true
this.xmlHttpRequest = function(url, callback, method, async) {
	if(!method) { method = "GET"; }
	if(async !== false) { async = true; }

	var xmlhttp = Cc["@mozilla.org/xmlextras/xmlhttprequest;1"].createInstance(Ci.nsIXMLHttpRequest);
	xmlhttp.open(method, url, async);
	if(async) {
		xmlhttp.onreadystatechange = function(e) { callback(xmlhttp, e); };
	}
	xmlhttp.send();
	if(!async) {
		callback(xmlhttp);
	}
	return xmlhttp;
};

// aSync(aFunc, aDelay) - lets me run aFunc asynchronously, basically it's a one shot timer with a delay of aDelay msec
//	aFunc - (function) to be called asynchronously
//	(optional) aDelay - (int) msec to set the timer, defaults to 0msec
this.aSync = function(aFunc, aDelay) {
	var newTimer = {
		timer: Cc["@mozilla.org/timer;1"].createInstance(Ci.nsITimer),
		handler: aFunc.bind(self),
		cancel: function() {
			this.timer.cancel();
		}
	};
	newTimer.timer.init(newTimer.handler, (!aDelay) ? 0 : aDelay, Ci.nsITimer.TYPE_ONE_SHOT);
	return newTimer;
};

// dispatch(obj, properties) - creates and dispatches an event and returns (bool) whether preventDefault was called on it
//	obj - (xul element) object to dispatch the event from, it will be e.target
//	properties - (obj) expecting the following sub properties defining the following event characteristics:
//		type - (str) the event type
//		(optional) bubbles - (bool) defaults to true
//		(optional) cancelable - (bool) defaults to true
this.dispatch = function(obj, properties) {
	if(!obj || !obj.ownerDocument || !obj.dispatchEvent || !properties || !properties.type) { return false; }

	var bubbles = properties.bubbles || true;
	var cancelable = properties.cancelable || true;

	var event = obj.ownerDocument.createEvent('Event');
	event.initEvent(properties.type, bubbles, cancelable);
	return obj.dispatchEvent(event);
};

// compareFunction(a, b, strict) - returns (bool) if a === b
//	a - (function) to compare
//	b - (function) to compare
//	(optional) strict - false compares function source as (string), true does not, defaults to false
this.compareFunction = function(a, b, strict) {
	if(a === b || (!strict && a.toSource() == b.toSource())) {
		return true;
	}
	return false;
};

// isAncestor(aNode, aParent, aWindow) - Checks if aNode decends from aParent
//	aNode - (xul element) node to check for ancestry
//	aParent - (xul element) node to check if ancestor of aNode
//	(dont set) aWindow - to be used internally by isAncestor()
this.isAncestor = function(aNode, aParent, aWindow) {
	if(!aNode || !aParent) { return false; };

	if(aNode == aParent) { return true; }

	var ownDocument = aNode.ownerDocument || aNode.document;
	if(ownDocument && ownDocument == aParent) { return true; }
	if(aNode.compareDocumentPosition && (aNode.compareDocumentPosition(aParent) & aNode.DOCUMENT_POSITION_CONTAINS)) { return true; }

	var browsers = aParent.getElementsByTagName('browser');
	for(var i=0; i<browsers.length; i++) {
		if(isAncestor(aNode, browsers[i].contentDocument, browsers[i].contentWindow)) { return true; }
	}

	if(!aWindow) { return false; }
	for(var i=0; i<aWindow.frames.length; i++) {
		if(isAncestor(aNode, aWindow.frames[i].document, aWindow.frames[i])) { return true; }
	}
	return false;
};

// hideIt(aNode, show) - in theory this should collapse whatever I want
//	aNode - (xul element) node to collapse
//	(optional) show - false collapses aNode, true 'un'collapses it, defaults to false
this.hideIt = function(aNode, show) {
	toggleAttribute(aNode, 'collapsed', !show);
};

// trim(str) - trims whitespaces from a string (found in http://blog.stevenlevithan.com/archives/faster-trim-javascript -> trim3())
//	str - (string) to trim
this.trim = function(str) {
	if(typeof(str) != 'string') {
		return '';
	}

	return str.substring(Math.max(str.search(/\S/), 0), str.search(/\S\s*$/) + 1);
};

// closeCustomize() - useful for when you want to close the customize toolbar dialogs for whatever reason
this.closeCustomize = function() {
	windowMediator.callOnAll(function(aWindow) { try { aWindow.close(); } catch(ex) {} }, null, "chrome://global/content/customizeToolbar.xul");
};
<commit_msg>cleaned up a description<commit_after>moduleAid.VERSION = '2.0.0';
moduleAid.LAZY = true;

// xmlHttpRequest(url, callback, method, async) - aid for quickly using the nsIXMLHttpRequest interface
//	url - (string) to send the request
//	callback - (function) to be called after request is completed; expects callback(xmlhttp, e) where xmlhttp = xmlhttprequest return object and e = event object
//	(optional) method - either (string) "POST" or (string) "GET"
//	(optional) async - (bool) defines whether to perform the operation asynchronously, defaults to true
this.xmlHttpRequest = function(url, callback, method, async) {
	if(!method) { method = "GET"; }
	if(async !== false) { async = true; }

	var xmlhttp = Cc["@mozilla.org/xmlextras/xmlhttprequest;1"].createInstance(Ci.nsIXMLHttpRequest);
	xmlhttp.open(method, url, async);
	if(async) {
		xmlhttp.onreadystatechange = function(e) { callback(xmlhttp, e); };
	}
	xmlhttp.send();
	if(!async) {
		callback(xmlhttp);
	}
	return xmlhttp;
};

// aSync(aFunc, aDelay) - lets me run aFunc asynchronously, basically it's a one shot timer with a delay of aDelay msec
//	aFunc - (function) to be called asynchronously
//	(optional) aDelay - (int) msec to set the timer, defaults to 0msec
this.aSync = function(aFunc, aDelay) {
	var newTimer = {
		timer: Cc["@mozilla.org/timer;1"].createInstance(Ci.nsITimer),
		handler: aFunc.bind(self),
		cancel: function() {
			this.timer.cancel();
		}
	};
	newTimer.timer.init(newTimer.handler, (!aDelay) ? 0 : aDelay, Ci.nsITimer.TYPE_ONE_SHOT);
	return newTimer;
};

// dispatch(obj, properties) - creates and dispatches an event and returns (bool) whether preventDefault was called on it
//	obj - (xul element) object to dispatch the event from, it will be e.target
//	properties - (obj) expecting the following sub properties defining the following event characteristics:
//		type - (str) the event type
//		(optional) bubbles - (bool) defaults to true
//		(optional) cancelable - (bool) defaults to true
this.dispatch = function(obj, properties) {
	if(!obj || !obj.ownerDocument || !obj.dispatchEvent || !properties || !properties.type) { return false; }

	var bubbles = properties.bubbles || true;
	var cancelable = properties.cancelable || true;

	var event = obj.ownerDocument.createEvent('Event');
	event.initEvent(properties.type, bubbles, cancelable);
	return obj.dispatchEvent(event);
};

// compareFunction(a, b, strict) - returns (bool) if a === b
//	a - (function) to compare
//	b - (function) to compare
//	(optional) strict - false compares function source as (string), true does not, defaults to false
this.compareFunction = function(a, b, strict) {
	if(a === b || (!strict && a.toSource() == b.toSource())) {
		return true;
	}
	return false;
};

// isAncestor(aNode, aParent) - Checks if aNode decends from aParent
//	aNode - (xul element) node to check for ancestry
//	aParent - (xul element) node to check if ancestor of aNode
//	(dont set) aWindow - to be used internally by isAncestor()
this.isAncestor = function(aNode, aParent, aWindow) {
	if(!aNode || !aParent) { return false; };

	if(aNode == aParent) { return true; }

	var ownDocument = aNode.ownerDocument || aNode.document;
	if(ownDocument && ownDocument == aParent) { return true; }
	if(aNode.compareDocumentPosition && (aNode.compareDocumentPosition(aParent) & aNode.DOCUMENT_POSITION_CONTAINS)) { return true; }

	var browsers = aParent.getElementsByTagName('browser');
	for(var i=0; i<browsers.length; i++) {
		if(isAncestor(aNode, browsers[i].contentDocument, browsers[i].contentWindow)) { return true; }
	}

	if(!aWindow) { return false; }
	for(var i=0; i<aWindow.frames.length; i++) {
		if(isAncestor(aNode, aWindow.frames[i].document, aWindow.frames[i])) { return true; }
	}
	return false;
};

// hideIt(aNode, show) - in theory this should collapse whatever I want
//	aNode - (xul element) node to collapse
//	(optional) show - false collapses aNode, true 'un'collapses it, defaults to false
this.hideIt = function(aNode, show) {
	toggleAttribute(aNode, 'collapsed', !show);
};

// trim(str) - trims whitespaces from a string (found in http://blog.stevenlevithan.com/archives/faster-trim-javascript -> trim3())
//	str - (string) to trim
this.trim = function(str) {
	if(typeof(str) != 'string') {
		return '';
	}

	return str.substring(Math.max(str.search(/\S/), 0), str.search(/\S\s*$/) + 1);
};

// closeCustomize() - useful for when you want to close the customize toolbar dialogs for whatever reason
this.closeCustomize = function() {
	windowMediator.callOnAll(function(aWindow) { try { aWindow.close(); } catch(ex) {} }, null, "chrome://global/content/customizeToolbar.xul");
};
<|endoftext|>


<commit_before>/*jslint node:true*/
"use strict";
var net = require('net'),
    util = require('util'),
    events = require('events');

function XBMC(options) {

    var xbmc, config,
        self = this,
        jsonrpc_id = 0,
        message_queue = {},
        buffer = '';

    options = options || {};

    config = {
        'port': 9090,
        'reconnect': true,
        'reconnect_sleep': 5
    };
    self.is_connected = false;

    // Main send function
    // Callback will be called when response is received
    // All API methods (fetched from XBMC) call this function
    function send(method, params, callback) {
        var id, message;

        if (self.is_connected) {

            jsonrpc_id += 1;
            id = jsonrpc_id;
            message = JSON.stringify({
                'jsonrpc': '2.0',
                'method': method,
                'params': params,
                'id': id
            });

            xbmc.write(message);

            message_queue[id] = {
                'id': id,
                'method': method,
                'params': params,
                'callback': callback
            };

            self.emit("debug", util.format("Sent command to %s:%s: %j", config.host, config.port, message));
            return true;
        }

        if (typeof callback === 'function') {
            callback(false);
        }
        return false;
    }

    self.connect = function (options) {

        var connection_properties;

        if (typeof options !== 'undefined') {
            if (typeof options.host !== 'undefined') { config.host = options.host; }
            if (typeof options.port !== 'undefined') { config.port = options.port; }
            if (typeof options.reconnect !== 'undefined') { config.reconnect = options.reconnect; }
            if (typeof options.reconnect_sleep !== 'undefined') { config.reconnect_sleep = options.reconnect_sleep; }
        }

        connection_properties = {"host": config.host, "port": config.port};

        self.emit("debug", util.format("Connecting to %s:%s", config.host, config.port));

        if (typeof xbmc === 'undefined') {

            xbmc = net.connect(connection_properties);

            xbmc.on('connect', function () {

                self.is_connected = true;

                // Do a jsonrpc introspect to create all methods
                // so you can call xbmc.Player.Stop(params, callback)
                // instead of xbmc.send('Player.Stop', params, callback)
                send('JSONRPC.Introspect', {}, function (res) {

                    var method, notification;

                    // TODO: Possible to merge method and notification functions?
                    function create_method(method_name) {
                        var parts = method_name.split("."),
                            namespace = parts[0],
                            method = parts[1];

                        if (typeof self[namespace] === 'undefined') {
                            self[namespace] = {};
                        }
                        self[namespace][method] = function (arg1, arg2) {
                            var params = (typeof arg1 !== 'function') ? arg1 : {},
                                callback = (typeof arg1 === 'function') ? arg1 : arg2;
                            send(method_name, params, callback);
                        };
                    }
                    function create_notification(method_name) {
                        var parts = method_name.split("."),
                            namespace = parts[0],
                            method = parts[1];

                        if (typeof self[namespace] === 'undefined') {
                            self[namespace] = {};
                        }
                        self[namespace][method] = function (callback) {
                            self.on(method_name, callback);
                        };
                    }

                    for (method in res.result.methods) {
                        create_method(method);
                    }

                    for (notification in res.result.notifications) {
                        create_notification(notification);
                    }

                    self.emit("debug", util.format("Connected to %s:%s", config.host, config.port));
                    self.emit('connect');
                });
            });

            xbmc.on('close', function () {

                self.is_connected = false;
                self.emit("debug", util.format("Disconnedted from %s:%s", config.host, config.port));
                self.emit('close');

                if (config.reconnect) {

                    setTimeout(self.connect, config.reconnect_sleep * 1000);
                }
            });

            xbmc.on('error', function (err) {

                self.emit("error", util.format("Server error on (%s:%s): %j", config.host, config.port, err));
                xbmc.destroy();
            });

            xbmc.on('data', function (data) {

                self.emit("debug", util.format("Received data from %s:%s: %s", config.host, config.port, data));

                buffer += data;

                try {
                    // Try to parse data in buffer
                    data = JSON.parse(buffer);
                } catch (e) {
                    // Return if not parsable yet (partial data)
                    return;
                }
                buffer = "";

                if (typeof message_queue[data.id] === 'object') {

                    if (typeof message_queue[data.id].callback === 'function') {
                        message_queue[data.id].callback(data);
                    }
                    delete message_queue[data.id];

                } else {

                    self.emit(data.method, data.params);
                }
            });

            return;
        }
        xbmc.connect(connection_properties);
        return;
    };

    self.close = self.disconnect = function () {

        if (self.is_connected) {
            xbmc.destroy();
        }
    };
}
util.inherits(XBMC, events.EventEmitter);

module.exports = new XBMC();<commit_msg>Code cleanup and minor bugfix<commit_after>/*jslint node:true*/
"use strict";
var self, xbmc, config,
    net = require('net'),
    util = require('util'),
    events = require('events'),
    jsonrpc_id = 0,
    message_queue = {},
    buffer = '';

module.exports = self = new events.EventEmitter();

config = {
    'port': 9090,
    'reconnect': false,
    'reconnect_sleep': 5
};
self.is_connected = false;

// Main send function
// Callback will be called when response is received
// All API methods (fetched from XBMC) call this function
self.send = function (method, params, callback) {
    var id, message;

    if (self.is_connected) {

        jsonrpc_id += 1;
        id = jsonrpc_id;
        message = JSON.stringify({
            'jsonrpc': '2.0',
            'method': method,
            'params': params,
            'id': id
        });

        xbmc.write(message);

        message_queue[id] = {
            'id': id,
            'method': method,
            'params': params,
            'callback': callback
        };

        self.emit("debug", util.format("Sent command to %s:%s: %j", config.host, config.port, message));
        return true;
    }

    if (typeof callback === 'function') {
        callback(false);
    }
    return false;
}

self.connect = function (options) {

    var connection_properties;

    if (typeof options !== 'undefined') {
        if (typeof options.host !== 'undefined') { config.host = options.host; }
        if (typeof options.port !== 'undefined') { config.port = options.port; }
        if (typeof options.reconnect !== 'undefined') { config.reconnect = options.reconnect; }
        if (typeof options.reconnect_sleep !== 'undefined') { config.reconnect_sleep = options.reconnect_sleep; }
    }

    connection_properties = {"host": config.host, "port": config.port};

    self.emit("debug", util.format("Connecting to %s:%s", config.host, config.port));

    if (typeof xbmc === 'undefined') {

        xbmc = net.connect(connection_properties);

        xbmc.on('connect', function () {

            self.is_connected = true;

            // Do a jsonrpc introspect to create all methods
            // so you can call xbmc.Player.Stop(params, callback)
            // instead of xbmc.send('Player.Stop', params, callback)
            self.send('JSONRPC.Introspect', {}, function (res) {

                var method, notification;

                // TODO: Possible to merge method and notification functions?
                function create_method(method_name) {
                    var parts = method_name.split("."),
                        namespace = parts[0],
                        method = parts[1];

                    if (typeof self[namespace] === 'undefined') {
                        self[namespace] = {};
                    }
                    self[namespace][method] = function (arg1, arg2) {
                        var params = (typeof arg1 !== 'function') ? arg1 : {},
                            callback = (typeof arg1 === 'function') ? arg1 : arg2;
                        self.send(method_name, params, callback);
                    };
                }
                function create_notification(method_name) {
                    var parts = method_name.split("."),
                        namespace = parts[0],
                        method = parts[1];

                    if (typeof self[namespace] === 'undefined') {
                        self[namespace] = {};
                    }
                    self[namespace][method] = function (callback) {
                        self.on(method_name, callback);
                    };
                }

                for (method in res.result.methods) {
                    create_method(method);
                }

                for (notification in res.result.notifications) {
                    create_notification(notification);
                }

                self.emit("debug", util.format("Connected to %s:%s", config.host, config.port));
                self.emit('connect');
            });
        });

        xbmc.on('close', function () {

            self.is_connected = false;
            self.emit("debug", util.format("Disconnedted from %s:%s", config.host, config.port));
            self.emit('close');

            if (config.reconnect) {

                setTimeout(self.connect, config.reconnect_sleep * 1000);
            }
        });

        xbmc.on('error', function (err) {

            self.emit("error", util.format("Server error on (%s:%s): %j", config.host, config.port, err));
            xbmc.destroy();
        });

        xbmc.on('data', function (data) {

            self.emit("debug", util.format("Received data from %s:%s: %s", config.host, config.port, data));

            buffer += data;

            try {
                // Try to parse data in buffer
                data = JSON.parse(buffer);
            } catch (e) {
                // Return if not parsable yet (partial data)
                return;
            }
            buffer = "";

            if (typeof message_queue[data.id] === 'object') {

                if (typeof message_queue[data.id].callback === 'function') {
                    message_queue[data.id].callback(data);
                }
                delete message_queue[data.id];

            } else {

                self.emit(data.method, data.params);
            }
        });

        return;
    }
    xbmc.connect(connection_properties);
    return;
};

self.close = self.disconnect = function () {

    if (self.is_connected) {
        xbmc.destroy();
    }
};<|endoftext|>


<commit_before>(function() {
    Iris.Renderer.extend({
	  about : function() {
	      return {
	      name: "treegraph",
	      author: "Annette Greiner",
	      version: "1.0",
	      requires: [ 'd3.js' ],
	      options: {'width': 960,
			       'height': 1200,
			       'padding': 40,
			        'data': 'exampleData()',
			       'target': "chart"},
	      classes: ["link", "node"],
	      data_format: "tree"
	    };
	  },
	  exampleData: function(){
		var dataobj =   {
   "name": "analytics",
   "children": [
    {
     "name": "cluster",
     "children": [
      {"name": "AgglomerativeCluster", "size": 938},
      {"name": "CommunityStructure", "size": 812},
      {"name": "HierarchicalCluster", "size": 3714},
      {"name": "MergeEdge", "size": 243}
     ]
    },
    {
     "name": "graph",
     "children": [
      {"name": "BetweennessCentrality", "size": 534},
      {"name": "LinkDistance", "size": 2731},
      {"name": "MaxFlowMinCut", "size": 4840},
      {"name": "ShortestPaths", "size": 2914},
      {"name": "SpanningTree", "size": 416}
     ]
    },
    {
     "name": "optimization",
     "children": [
      {"name": "AspectRatioBanker", "size": 4074}
     ]
    }
   ]
  };
  	      	return  dataobj;
	     },
	  render : function( settings ) {

	     var options = { width: 960,
			       height: 1200,
			       padding: 20,
			       target: "chart",
			       data: {} };
	       $.extend(options, settings);

	      options.target.innerHTML = "";

		  //-------

		 var cluster = d3.layout.cluster()
		     .size([options.height, options.width + 200 ]);

		 var diagonal = d3.svg.diagonal()
		     .projection(function(d) { return [d.y, d.x]; });

		 var vis = d3.select(options.target).append("svg")
		     .attr("width", options.width)
		     .attr("height", options.height)
		   .append("g")
		     .attr("transform", "translate(40, 0)");

	   var nodes = cluster.nodes(options.data);

	   var link = vis.selectAll("path.link")
	       .data(cluster.links(nodes))
	     .enter().append("path")
	       .attr("class", "link")
	       .attr("d", diagonal)
	       .attr("style", "fill: none; stroke: #ccc;", "stroke-width: 1.5px;");

	   var node = vis.selectAll("g.node")
	       .data(nodes)
	     .enter().append("g")
	       .attr("class", "node")
	       .attr("style", "font: 10px sans-serif;")
	       .attr("transform", function(d) { return "translate(" + d.y + "," + d.x + ")"; });

	   node.append("circle")
	       .attr("r", 4.5)
	       .attr("style", "fill: #fff; stroke: steelblue; stroke-width: 1.5px;");

	   node.append("text")
	       .attr("dx", function(d) { return d.children ? -8 : 8; })
	       .attr("dy", 3)
	       .attr("text-anchor", function(d) { return d.children ? "end" : "start"; })
	       .text(function(d) { return d.name; });
	}
});

}).call(this);

<commit_msg>changes for new version of a renderer<commit_after>(function() {
    Iris.Renderer.extend({
	  about : {
	      name: "treegraph",
	      author: "Annette Greiner",
	      version: "1.0",
	      requires: [ 'd3.js' ],
		  defaults: { width: 960,
			       height: 1200,
			       padding: 20,
			       data: "exampleData()"
			      },
	      classes: ["link", "node"],
	      dataFormat: "tree"
	  },
	  exampleData: function(){
		var dataobj =   {
   "name": "analytics",
   "children": [
    {
     "name": "cluster",
     "children": [
      {"name": "AgglomerativeCluster", "size": 938},
      {"name": "CommunityStructure", "size": 812},
      {"name": "HierarchicalCluster", "size": 3714},
      {"name": "MergeEdge", "size": 243}
     ]
    },
    {
     "name": "graph",
     "children": [
      {"name": "BetweennessCentrality", "size": 534},
      {"name": "LinkDistance", "size": 2731},
      {"name": "MaxFlowMinCut", "size": 4840},
      {"name": "ShortestPaths", "size": 2914},
      {"name": "SpanningTree", "size": 416}
     ]
    },
    {
     "name": "optimization",
     "children": [
      {"name": "AspectRatioBanker", "size": 4074}
     ]
    }
   ]
  };
  	      	return  dataobj;
	     },
	  render : function( options ) {

	      options.target.innerHTML = "";

		  //-------

		 var cluster = d3.layout.cluster()
		     .size([options.height, options.width + 200 ]);

		 var diagonal = d3.svg.diagonal()
		     .projection(function(d) { return [d.y, d.x]; });

		 var vis = d3.select(options.target).append("svg")
		     .attr("width", options.width)
		     .attr("height", options.height)
		   .append("g")
		     .attr("transform", "translate(40, 0)");

	   var nodes = cluster.nodes(options.data);

	   var link = vis.selectAll("path.link")
	       .data(cluster.links(nodes))
	     .enter().append("path")
	       .attr("class", "link")
	       .attr("d", diagonal)
	       .attr("style", "fill: none; stroke: #ccc;", "stroke-width: 1.5px;");

	   var node = vis.selectAll("g.node")
	       .data(nodes)
	     .enter().append("g")
	       .attr("class", "node")
	       .attr("style", "font: 10px sans-serif;")
	       .attr("transform", function(d) { return "translate(" + d.y + "," + d.x + ")"; });

	   node.append("circle")
	       .attr("r", 4.5)
	       .attr("style", "fill: #fff; stroke: steelblue; stroke-width: 1.5px;");

	   node.append("text")
	       .attr("dx", function(d) { return d.children ? -8 : 8; })
	       .attr("dy", 3)
	       .attr("text-anchor", function(d) { return d.children ? "end" : "start"; })
	       .text(function(d) { return d.name; });
	}
});

}).call(this);

<|endoftext|>


<commit_before>import React from 'react'
import { connect } from 'react-redux'
import { Route } from 'react-router-dom'

import MobSelectors from '~client/mobrender/redux/selectors'
import { Loading } from '~client/components/await'
import { selectMobilization, asyncFetchWidgets, asyncUpdateWidget } from '~client/mobrender/redux/action-creators'
import { SettingsPageLayout, SettingsPageContentLayout } from '~client/components/layout'
import { SettingsMenu } from '~client/mobilizations/widgets/__plugins__/donation/components'

// Pages
import DonationBasic from '~routes/admin/authenticated/sidebar/widgets-donation-settings/donation/page.connected'

const injectProps = (Component, props) => routeProps => <Component {...routeProps} {...props} />

class WidgetsDonation extends React.Component {
  componentDidMount () {
    const { match: { params } } = this.props
    !this.props.mobilization && this.props.selectMobilization(params.mobilization_id)
    !this.props.widgetsIsLoaded && this.props.asyncFetchWidgets(params.mobilization_id)
  }

  render () {
    const { match: { path }, ...rest } = this.props
    const { mobilization, widget, location, widgetsIsLoaded } = this.props

    return !mobilization || !widgetsIsLoaded ? (
      <Loading />
    ) : (
      <SettingsPageLayout>
        <SettingsMenu mobilization={mobilization} widget={widget} location={location} />
        <SettingsPageContentLayout>
          <Route exact path={`${path}`} render={injectProps(DonationBasic, rest)} />
        </SettingsPageContentLayout>
      </SettingsPageLayout>
    )
  }
}

const mapStateToProps = (state, props) => {
  const { match: { params: { widget_id: widgetId } } } = props
  const selectors = MobSelectors(state, props)

  return {
    widgetsIsLoaded: selectors.widgetsIsLoaded(),
    mobilization: selectors.getMobilization(),
    widget: selectors.getWidget(widgetId)
  }
}

const mapActionsToProps = {
  asyncWidgetUpdate: asyncUpdateWidget,
  selectMobilization,
  asyncFetchWidgets
}

export default connect(mapStateToProps, mapActionsToProps)(WidgetsDonation)
<commit_msg>chore(routes-v1): migrate donation widget settings routes<commit_after>import React from 'react'
import { connect } from 'react-redux'
import { Route } from 'react-router-dom'

import MobSelectors from '~client/mobrender/redux/selectors'
import { Loading } from '~client/components/await'
import { selectMobilization, asyncFetchWidgets, asyncUpdateWidget } from '~client/mobrender/redux/action-creators'
import { SettingsPageLayout, SettingsPageContentLayout } from '~client/components/layout'
import { SettingsMenu } from '~client/mobilizations/widgets/__plugins__/donation/components'

// Pages
import Adjustments from '~routes/admin/authenticated/sidebar/widgets-donation-settings/adjustments/page.connected'
import Autofire from '~routes/admin/authenticated/sidebar/widgets-donation-settings/autofire/page.connected'
import Finish from '~routes/admin/authenticated/sidebar/widgets-donation-settings/finish/page'
import Settings from '~routes/admin/authenticated/sidebar/widgets-donation-settings/donation/page.connected'

const injectProps = (Component, props) => routeProps => <Component {...props} {...routeProps} />

class WidgetsDonation extends React.Component {
  componentDidMount () {
    const { match: { params } } = this.props
    !this.props.mobilization && this.props.selectMobilization(params.mobilization_id)
    !this.props.widgetsIsLoaded && this.props.asyncFetchWidgets(params.mobilization_id)
  }

  render () {
    const { match: { path }, ...rest } = this.props
    const { mobilization, widget, location, widgetsIsLoaded } = this.props

    return !mobilization || !widgetsIsLoaded ? <Loading /> : (
      <SettingsPageLayout>
        <SettingsMenu mobilization={mobilization} widget={widget} location={location} />
        <SettingsPageContentLayout>
          <Route exact path={`${path}`} render={injectProps(Adjustments, rest)} />
          <Route exact path={`${path}/autofire`} render={injectProps(Autofire, rest)} />
          <Route exact path={`${path}/finish`} render={injectProps(Finish, rest)} />
          <Route exact path={`${path}/settings`} render={injectProps(Settings, rest)} />
        </SettingsPageContentLayout>
      </SettingsPageLayout>
    )
  }
}

const mapStateToProps = (state, props) => {
  const { match: { params: { widget_id: widgetId } } } = props
  const selectors = MobSelectors(state, props)

  return {
    widgetsIsLoaded: selectors.widgetsIsLoaded(),
    mobilization: selectors.getMobilization(),
    widget: selectors.getWidget(widgetId)
  }
}

const mapActionsToProps = {
  asyncWidgetUpdate: asyncUpdateWidget,
  selectMobilization,
  asyncFetchWidgets
}

export default connect(mapStateToProps, mapActionsToProps)(WidgetsDonation)
<|endoftext|>