CommandHandler constructor
@param {Object}   meta      Meta infos like: { name: 'name', version: 1 }
@param {Function} cmdHndlFn Function handle
`function(aggId, cmd, commandHandler, callback){}`
@constructor
329014
function CommandHandler (meta, cmdHndlFn) {
  DefaultCommandHandler.call(this, meta);

  console.log('Is your use case not solvable without a custom command handling? Sagas? Micro-Services?');

  meta = meta || {};

  this.version = meta.version || 0;

  if (!cmdHndlFn || !_.isFunction(cmdHndlFn)) {
    var err = new Error('CommandHandler function not injected!');
    debug(err);
    throw err;
  }

  this.cmdHndlFn = cmdHndlFn;
}
1113376
private void installMetaClassCreationHandle() {
           try {
               final Class customMetaClassHandle = Class.forName("groovy.runtime.metaclass.CustomMetaClassCreationHandle");
               final Constructor customMetaClassHandleConstructor = customMetaClassHandle.getConstructor();
                 this.metaClassCreationHandle = (MetaClassCreationHandle)customMetaClassHandleConstructor.newInstance();
           } catch (final ClassNotFoundException e) {
               this.metaClassCreationHandle = new MetaClassCreationHandle();
           } catch (final Exception e) {
               throw new GroovyRuntimeException("Could not instantiate custom Metaclass creation handle: "+ e, e);
           }
    }
12343
function Definition (meta) {
  if (!this.name && meta && meta.name) {
    this.name = meta.name;
  }

  this.options = {};

  this.definitions = {
    command: {
      id: 'id'
////      name: 'name',                   // optional
////      aggregateId: 'aggregate.id',    // optional
////      context: 'context.name',        // optional
////      aggregate: 'aggregate.name',    // optional
////      payload: 'payload',             // optional
////      revision: 'revision',           // optional
////      version: 'version',             // optional
//      meta: 'meta'                    // optional (will be passed directly to corresponding event(s))
    },
    event: {
////      correlationId: 'correlationId', // optional
////      id: 'id',                       // optional
      name: 'name'
////      aggregateId: 'aggregate.id',    // optional
//      context: 'context.name',        // optional
//      aggregate: 'aggregate.name',    // optional
////      payload: 'payload',             // optional
////      revision: 'revision'            // optional
//      version: 'version',             // optional
//      meta: 'meta'                    // optional (will be passed directly from corresponding command)
    }
  };
}
292821
function handleMeta(doc, title) {
  // If this is an image we need to not try and parse it
  if (imageRegex.test(title)) {
    return {}
  }
  const md = new MetaRemarkable()
  const page = md.render(doc)

  // Initialize an empty object
  let lowerMeta = {}

  // transform meta keys to lowercase (easier to work with)
  if (page.meta){
    lowerMeta = _.transform(page.meta, function (result, val, key) {
      result[key.toLowerCase()] = val
    })
  }
  return lowerMeta
}
1252075
function (CommandsHandlerModel, opt_config) {

	// Configuration
	this.config = opt_config || helper.getConfig(false);

	// WebSocket Connection
	this.webSocket = null;
	this.heartbeatTimer = null;

	// Instances of the plugins
	this.pluginInstances = {};
	this._initPlugins();

	// Instances of the command modules
	this.commandModules = {};
	this._initCommandModules();

	// Make an instance of the CommandsHandler
	var ch_logger = new HandlerLogger(this);
	var handler_helper = new HandlerHelper(this);
	this.commandsHandler = new CommandsHandlerModel(this.config, ch_logger, handler_helper);

	// Check the command arguments
	if (process.argv.indexOf('--dev') != -1 || process.argv.indexOf('--development') != -1) {
		this.config.isDebugMode = true;
	}

	// Check the options
	this.isDebugMode = this.config.isDebugMode || false;

	// Check the configuration
	if (this.config.denhubServerHost == null){
		throw new Error('A required configuration undefined: denhubServerHost');
	} else if (this.config.deviceName == null) {
		throw new Error('A required configuration undefined: deviceName');
	} else if (this.config.deviceType == null) {
		throw new Error('A required configuration undefined: deviceType');
	}

	// Interval time (millisec) for reconnecting to server
	this.config.reconnectDelayTime = this.config.reconnectDelayTime || 5000;

	// Interval time (millisec) for restarting when the fatal error occurred
	this.config.restartDelayTime = this.config.restartDelayTime || 6000;

	// Interval time (millisec) for heartbeat sending
	this.config.heartbeatIntervalTime = this.config.heartbeatIntervalTime || 10000;

}
111818
function Event (meta, evtFn) {
  Definition.call(this, meta);

  meta = meta || {};

  if (evtFn && !_.isFunction(evtFn)) {
    var err = new Error('Event function not injected!');
    debug(err);
    throw err;
  }

  this.version = meta.version || 0;
  this.payload = meta.payload === '' ? meta.payload : (meta.payload || null);

  this.evtFn = evtFn;
}
743126
function Command(handler, options, desc) {
  Command.super_.apply(this, [handler, options, desc]);
}
470333
function CommandDispatcher (tree, definition, commandBumper) {
  if (!tree || !_.isObject(tree) || !_.isFunction(tree.getCommandHandler)) {
    var err = new Error('Please pass a valid tree!');
    debug(err);
    throw err;
  }

  if (!definition || !_.isObject(definition)) {
    var err = new Error('Please pass a valid command definition!');
    debug(err);
    throw err;
  }

  this.tree = tree;
  this.definition = definition;

  this.commandBumper = commandBumper;
}
1088759
function handleConfigObject(oCfg, mHandlers) {

		function processConfig(key, value) {
			var handler = mHandlers[key];
			if ( typeof handler === 'function' ) {
				if ( handler.length === 1) {
					handler(value);
				} else if ( value != null ) {
					forEach(value, handler);
				}
			} else {
				log.warning("configuration option " + key + " not supported (ignored)");
			}
		}

		// Make sure the 'baseUrl' handler is called first as
		// other handlers (e.g. paths) depend on it
		if (oCfg.baseUrl) {
			processConfig("baseUrl", oCfg.baseUrl);
		}

		forEach(oCfg, function(key, value) {
			// Ignore "baseUrl" here as it will be handled above
			if (key !== "baseUrl") {
				processConfig(key, value);
			}
		});
	}
920910
function parse(meta) {
  if (typeof meta !== 'string') {
    throw new Error('`Parse`\'s first argument should be a string')
  }

  return meta.split(/[\r\n]/)
    .filter(function (line) { // remove blank line
      return /\S+/.test(line) &&
        line.indexOf('==UserScript==') === -1 &&
        line.indexOf('==/UserScript==') === -1
    })
    .reduce(function (obj, line) {
      var arr = line.trim().replace(/^\/\//, '').trim().split(/\s+/)
      var key = arr[0].slice(1)
      var value = arr.slice(1).join(' ')

      if (isUndefined(obj[key])) {
        obj[key] = value
      } else if (Array.isArray(obj[key])) {
        obj[key].push(value)
      } else {
        obj[key] = [obj[key], value]
      }

      return obj
    }, {})
}
110102
function Command(args) {
  if (false === (this instanceof Command)) throw new Error('new operator required');
  if (typeof args == 'function') { // shorthand for function command
    args = {type: 'Function', contents: args};
  }
  if (args instanceof Procedure) { // shorthand for Procedure command
    args = {type: 'Procedure', contents: args};
  }
  args = args || {};
  var i;
  var unusedProperties = getInvalidProperties(args,
    ['name', 'description', 'type', 'contents', 'scope', 'timeout', 'theme', 'icon', 'bucket', 'presentationMode','location','images']);
  var errorList = [];
  for (i = 0; i < unusedProperties.length; i++) errorList.push('invalid property: ' + unusedProperties[i]);
  if (errorList.length > 1) throw new Error('error creating Command: multiple errors');
  if (errorList.length) throw new Error('error creating Command: ' + errorList[0]);
  for (i in args) this[i] = args[i];
  this.name = this.name || "a command"; // name is optional
  if ('string' != typeof this.name) throw new Error('name must be string');
  if ('undefined' == typeof this.description) this.description = this.name + ' Command';
  if ('undefined' == typeof this.type) this.type = 'Stub';
  if (!contains(Command.getTypes(), this.type)) throw new Error('Invalid command type: ' + this.type);
  switch (this.type) {
    case 'Stub':
      break;
    case 'Menu':
      if (!(this.contents instanceof Array)) throw new Error('contents must be array of menu items');
      if (!this.contents.length) throw new Error('contents must be array of menu items');
      for (i in this.contents) {
        if (this.contents.hasOwnProperty(i))
          if (typeof this.contents[i] != 'string' && !(this.contents[i] instanceof Command))
            throw new Error('contents must be array of menu items');
      }
      break;
    case 'Presentation':
      if (!(this.contents instanceof Presentation)) throw new Error('contents must be a Presentation');
      this.presentationMode = this.presentationMode || 'View';
      if (!contains(Command.getPresentationModes(), this.presentationMode)) throw new Error('Invalid presentationMode: ' + this.presentationMode);
      //['View', 'Edit', 'List']
      break;
    case 'Function':
      if (typeof this.contents != 'function') throw new Error('contents must be a Function');
      break;
    case 'Procedure':
      if (!(this.contents instanceof Procedure)) throw new Error('contents must be a Procedure');
      break;
    default:
      throw new TypeError();
  }
  if ('undefined' != typeof this.scope)
    if (!((this.scope instanceof Model) || (this.scope instanceof List)))
      throw new Error('optional scope property must be Model or List');
  if ('undefined' != typeof this.timeout)
    if (typeof this.timeout != 'number') throw new Error('timeout must be a Number');
  if ('undefined' != typeof this.timeout)
    if (typeof this.timeout != 'number') throw new Error('timeout must be a Number');
  if ('undefined' != typeof this.theme) {
    if ('string' != typeof this.theme) throw new Error('invalid theme');
    if (!contains(['default', 'primary', 'success', 'info', 'warning', 'danger', 'link'], this.theme))
      throw new Error('invalid theme');
  }
  if ('undefined' != typeof this.icon) {
    if ('string' != typeof this.icon) throw new Error('invalid icon');
    if (!contains(['fa', 'glyphicon'], this.icon.split('-')[0]) || !this.icon.split('-')[1])
      throw new Error('invalid icon');
  }

  // Validations done
  this._eventListeners = [];
}
1075462
function handler(current, argv) {
        var cmds = pargv._commands;
        var completions = [];
        if (pargv._env.EXEC === argv[0])
            argv.shift(); // remove first arg which is app/exec name.
        var tmpCmd = pargv.getCommand(utils.first(argv)); // is first is known command.
        if (tmpCmd) { // limit to single command if known.
            cmds = {}; // set the commands to just the one known command.
            cmds[tmpCmd._name] = tmpCmd;
            var sliced_1 = argv.slice(1); // remove command name.
            var curCmdIdx_1 = 0;
            var lastCmdIdx_1 = tmpCmd._arguments.length - 1; // last index for commands.
            sliced_1.forEach(function (el, i) {
                if (!constants_1.FLAG_EXP.test(el) && i <= lastCmdIdx_1) {
                    var prev_1 = sliced_1[i - 1] || null;
                    var prevKey = tmpCmd.isOption(prev_1);
                    if (!prevKey && !constants_1.FLAG_EXP.test(prev_1)) // could be val for option.
                        curCmdIdx_1 = i;
                }
            });
            var curIdx = sliced_1.length - 1;
            var prevIdx = sliced_1.length - 2;
            var prev = sliced_1[prevIdx] || null;
            var isFlagPrev = prev && constants_1.FLAG_EXP.test(prev);
            var isBool = tmpCmd.isBool(prev);
            var isOption = isFlagPrev && !isBool;
            var isCommand = (curCmdIdx_1 >= 0) &&
                (curCmdIdx_1 <= lastCmdIdx_1);
            //  !FLAG_EXP.test(sliced[curIdx])
            if (isCommand || isOption) {
                var key = isOption ? tmpCmd.aliasToKey(prev) : tmpCmd.aliasToKey(curCmdIdx_1);
                if (tmpCmd._completions[key])
                    completions = completions.concat(tmpCmd._completions[key]);
            }
            if (tmpCmd._completions['*']) // anon custom completions.
                completions = completions.concat(tmpCmd._completions['*']);
        }
        else {
            var _loop_1 = function (k) {
                var cmd = cmds[k];
                [cmd._name].concat(cmd.aliases(cmd._name) || []) // iterate commands.
                    .forEach(function (el, i) {
                    if (!~completions.indexOf(el))
                        completions.push(el);
                });
                cmd._options.forEach(function (o) {
                    if (!~completions.indexOf(o))
                        completions.push(o);
                    (cmd.aliases(o) || []).forEach(function (el) {
                        if (!~completions.indexOf(el))
                            completions.push(el);
                    });
                });
            };
            for (var k in cmds) {
                _loop_1(k);
            }
        }
        // TODO: clunky redundant need to refactor this.
        var _options = completions.filter(function (c) { return constants_1.FLAG_EXP.test(c); });
        var _cmds = completions.filter(function (c) { return !constants_1.FLAG_EXP.test(c); });
        return _cmds.sort().concat(_options.sort());
    }
1035836
function (cmd, callback) {
    if (!cmd || !_.isObject(cmd)) {
      var err = new Error('Please pass a valid command!');
      debug(err);
      throw err;
    }

    if (!callback || !_.isFunction(callback)) {
      var err = new Error('Please pass a valid callback!');
      debug(err);
      throw err;
    }

    var target = this.getTargetInformation(cmd);

    var commandHandler = this.tree.getCommandHandler(target);

    // if (!commandHandler) {
    //   commandHandler = this.tree.getCommandHandlerByOldTarget(target);
    // }

    if (!commandHandler) {
      var err = new Error('No command handler found for ' + target.name);
      debug(err);
      return callback(err);
    }

    if (!this.commandBumper) {
      return commandHandler.handle(cmd, callback);
    }

    var key = target.context + target.aggregate + target.aggregateId + dotty.get(cmd, this.definition.id);

    this.commandBumper.add(key, function (err, added) {
      if (err) {
        return callback(err);
      }

      if (!added) {
        return callback(new DuplicateCommandError('Command already seen!'));
      }

      commandHandler.handle(cmd, callback);
    });
  }
131084
function processMeta (markdownContent) {
  let meta = {};
  let metaArr;
  let metaString;
  let metas;

  let yamlObject;

  switch (true) {
    case _metaRegex.test(markdownContent):
      metaArr = markdownContent.match(_metaRegex);
      metaString = metaArr ? metaArr[1].trim() : '';

      if (metaString) {
        metas = metaString.match(/(.*): (.*)/ig);
        metas.forEach(item => {
          const parts = item.split(': ');
          if (parts[0] && parts[1]) {
            meta[cleanString(parts[0], true)] = parts[1].trim();
          }
        });
      }
      break;

    case _metaRegexYaml.test(markdownContent):
      metaArr = markdownContent.match(_metaRegexYaml);
      metaString = metaArr ? metaArr[1].trim() : '';
      yamlObject = yaml.safeLoad(metaString);
      meta = cleanObjectStrings(yamlObject);
      break;

    default:
    // No meta information
  }

  return meta;
}
685761
function initAppHandlers (cfg = {}) {
	_.each(handlers, (handler, name) => App[name] = _.partial(handler, _, (_.isFunction(cfg[name])) ? cfg[name] : _.noop));
}
1353178
function Definition (meta) {
  if (!this.name && meta) {
    this.name = meta.name;
  }

  this.options = {};

  this.definitions = {
    command: {
      id: 'id',
      name: 'name',
      aggregateId: 'aggregate.id'
//      context: 'context.name',        // optional
//      aggregate: 'aggregate.name',    // optional
//      payload: 'payload',             // optional
//      revision: 'revision',           // optional
//      version: 'version',             // optional
//      meta: 'meta'                    // optional (will be passed directly to corresponding event(s))
    },
    event: {
      correlationId: 'correlationId',
      id: 'id',
      name: 'name',
      aggregateId: 'aggregate.id',
//      context: 'context.name',        // optional
//      aggregate: 'aggregate.name',    // optional
      payload: 'payload',               // optional
      revision: 'revision'              // optional
//      version: 'version',             // optional
//      meta: 'meta'                    // optional (will be passed directly from corresponding command)
    }
  };
}
533635
public function bindHandler($commandName, $handler)
    {
        // If the $handler given is an instance of CommandHandler, simply bind that
        if ($handler instanceof CommandHandler) {
            $this->handlers[$commandName] = $handler;
            return;
        }

        // If the handler given is callable, wrap it up in a CallableCommandHandler for executing later
        if (is_callable($handler)) {
            return $this->bindHandler($commandName, new CallableCommandHandler($handler));
        }

        // If the handler given is a string, wrap it up in a LazyLoadingCommandHandler for loading later
        if (is_string($handler)) {
            return $this->bindHandler($commandName, new LazyLoadingCommandHandler($handler, $this->container));
        }

        throw new \InvalidArgumentException('Could not push handler. Command Handlers should be an
            instance of Chief\CommandHandler, a callable, or a string representing a CommandHandler class');
    }