========================================================================= lang/instanceOf.js =========================================================================
6977
function instanceOf(object, klass) {
  // Handle exceptions where the target object originates from another frame.
  // This is handy for JSON parsing (amongst other things).
  
  if (typeof klass != "function") {
    throw new TypeError("Invalid 'instanceOf' operand.");
  }

  if (object == null) return false;
  
  /*@cc_on  
  // COM objects don't have a constructor
  if (typeof object.constructor != "function") {
    return typeOf(object) == typeof klass.prototype.valueOf();
  }
  @*/
    if (object.constructor == klass) return true;
    if (klass.ancestorOf) return klass.ancestorOf(object.constructor);
  /*@if (@_jscript_version < 5.1)
    // do nothing
  @else @*/
    if (object instanceof klass) return true;
  /*@end @*/

  // If the class is a base2 class then it would have passed the test above.
  if (Base.ancestorOf == klass.ancestorOf) return false;
  
  // base2 objects can only be instances of Object.
  if (Base.ancestorOf == object.constructor.ancestorOf) return klass == Object;
  
  switch (klass) {
    case Array: // This is the only troublesome one.
      return !!(typeof object == "object" && object.join && object.splice);
    case Function:
      return typeOf(object) == "function";
    case RegExp:
      return typeof object.constructor.$1 == "string";
    case Date:
      return !!object.getTimezoneOffset;
    case String:
    case Number:
    case Boolean:
      return typeOf(object) == typeof klass.prototype.valueOf();
    case Object:
      return true;
  }
  
  return false;
}
604605
function babelTransform(srcFile, destFile) {
    return new Promise((resolve, reject) => {
        // copy src file to local first
        const localSrcFile = `${destFile}.local`;

        // if file exist, then delete it
        Promise.resolve(existsFile(localSrcFile, READ_WRITE_PERMISSION))
          .then((value) => {
              if (!value) {
                  return true;
              }

              return fsPromise.unlinkAsync(localSrcFile);
          })
          .then(() => fsPromise.linkAsync(srcFile, localSrcFile))
          .then(() => {
              babel.transformFile(localSrcFile, (error, result) => {
                  if (error) {
                      console.error(`Error in babel compiling ${srcFile} - ${error}`);
                      reject(error);
                      return;
                  }

                  // if file exist, then delete it
                  Promise.resolve(existsFile(destFile, READ_WRITE_PERMISSION))
                    .then((value) => {
                        if (!value) {
                            return true;
                        }

                        return fsPromise.unlinkAsync(destFile);
                    })
                    .then(() => {
                        const stream = FS.createWriteStream(destFile);

                        stream.on('finish', () => {
                            resolve(true);
                        });

                        stream.write(result.code);
                        stream.end();
                    });
              });
          });
    });
}
414187
function caseOf (/* ...args, matcher */) {
    var args = slice.call(arguments, 0, -1);
    var matcher = arguments[arguments.length - 1];
    var context = this === exports ? null : this;
  
    if (typeof matcher === "function") {
      if (!matcher.__matchChain) throw new Error("Not a matcher function");
      return matcher.apply(context, args);
    }
  
    return pattern(matcher).apply(context, args);
  }
279780
function instance_getters () {
        var _parseArguments = parseArguments$1(arguments),
            getters = _parseArguments.getters,
            options = _parseArguments.options;

        return Object.keys(getters).reduce(function (instanceGetters, name) {
            instanceGetters[name] = function (state, otherGetters) {
                return function (instanceKey) {
                    var instance = state[options.stateKey || 'instances'].find(function (obj) {
                        return obj[options.instanceKey || 'id'] === instanceKey;
                    });

                    if (instance) {
                        return getters[name](instance, otherGetters, state, instanceKey);
                    }
                };
            };

            return instanceGetters;
        }, {});
    }
545546
function compileLanguage(language) {
  compileMode(language)

  // Compile a language mode, optionally with a parent.
  function compileMode(mode, parent) {
    var compiledKeywords = {}
    var terminators

    if (mode.compiled) {
      return
    }

    mode.compiled = true

    mode.keywords = mode.keywords || mode.beginKeywords

    if (mode.keywords) {
      if (typeof mode.keywords === 'string') {
        flatten('keyword', mode.keywords)
      } else {
        Object.keys(mode.keywords).forEach(function(className) {
          flatten(className, mode.keywords[className])
        })
      }

      mode.keywords = compiledKeywords
    }

    mode.lexemesRe = langRe(mode.lexemes || /\w+/, true)

    if (parent) {
      if (mode.beginKeywords) {
        mode.begin =
          '\\b(' + mode.beginKeywords.split(space).join(verticalBar) + ')\\b'
      }

      if (!mode.begin) {
        mode.begin = /\B|\b/
      }

      mode.beginRe = langRe(mode.begin)

      if (!mode.end && !mode.endsWithParent) {
        mode.end = /\B|\b/
      }

      if (mode.end) {
        mode.endRe = langRe(mode.end)
      }

      mode.terminatorEnd = source(mode.end) || ''

      if (mode.endsWithParent && parent.terminatorEnd) {
        mode.terminatorEnd +=
          (mode.end ? verticalBar : '') + parent.terminatorEnd
      }
    }

    if (mode.illegal) {
      mode.illegalRe = langRe(mode.illegal)
    }

    if (mode.relevance === undefined) {
      mode.relevance = 1
    }

    if (!mode.contains) {
      mode.contains = []
    }

    mode.contains = concat.apply(
      [],
      mode.contains.map(function(c) {
        return expandMode(c === 'self' ? mode : c)
      })
    )

    mode.contains.forEach(function(c) {
      compileMode(c, mode)
    })

    if (mode.starts) {
      compileMode(mode.starts, parent)
    }

    terminators = mode.contains
      .map(map)
      .concat([mode.terminatorEnd, mode.illegal])
      .map(source)
      .filter(Boolean)

    mode.terminators =
      terminators.length === 0
        ? {exec: execNoop}
        : langRe(terminators.join(verticalBar), true)

    function map(c) {
      return c.beginKeywords ? '\\.?(' + c.begin + ')\\.?' : c.begin
    }

    // Flatten a classname.
    function flatten(className, value) {
      var pairs
      var pair
      var index
      var length

      if (language[keyInsensitive]) {
        value = value.toLowerCase()
      }

      pairs = value.split(space)
      length = pairs.length
      index = -1

      while (++index < length) {
        pair = pairs[index].split(verticalBar)

        compiledKeywords[pair[0]] = [className, pair[1] ? Number(pair[1]) : 1]
      }
    }
  }

  // Create a regex for `value`.
  function langRe(value, global) {
    return new RegExp(
      source(value),
      'm' + (language[keyInsensitive] ? 'i' : '') + (global ? 'g' : '')
    )
  }

  // Get the source of an expression or string.
  function source(re) {
    return (re && re.source) || re
  }
}
874816
function Example() {

  var oMX = new MergeXML(); /* instantiate the class */
  var fls = [];             /* output files info */

  /**
   * get element object
   * @param {string} id
   */
  var $ = function(id) {
    return document.getElementById(id);
  };

  /**
   * add event handler
   * @param {string} evt
   * @param {string} id
   * @param {function} fnc
   */
  var AddEvent = function(evt, id, fnc) {
    var elem = $(id);
    if (elem.addEventListener)  // W3C DOM
      elem.addEventListener(evt, fnc, false);
    else if (elem.attachEvent) { // IE DOM
      elem.attachEvent('on' + evt, fnc);
    }
    else { // No much to do
      elem[evt] = fnc;
    }
  };

  /**
   * FileList objects handler
   * @param {object} evt
   */
  var FileSelect = function(evt) {
    $('output').innerHTML = '';
    $('result').innerHTML = '';
    oMX.Init(); /* begin with new objects */
    fls = [];
    var cnt = 0;
    var files = evt.target.files; /* FileList object */
    for (var i = 0; i < files.length; i++) { /* loop the selected files */
      var reader = new FileReader();
      reader.onload = function(file) {
        fls[cnt + 1] = oMX.AddFile(file) ? true : false;  /* get a file */
        var c = $('result').innerHTML;
        if (c !== '') {
          c += ', ';
        }
        $('result').innerHTML = c + fls[cnt];
        cnt += 2;
      };
      fls.push(files[i].name, null);
      reader.readAsText(files[i]);
    }
  };

  /**
   * Check results
   * @return {mixed} array -- files list
   *                 string -- error
   *                 null -- loading yet
   */
  var FileCheck = function() {
    var r = [];
    for (var i = 0; i < fls.length; i += 2) {
      if (fls[i + 1]) {
        r.push(fls[i]);
      } else {
        r = fls[i + 1] === false ? fls[i] : null;
        break;
      }
    }
    return r;
  };

  /**
   * Show results
   */
  var FileMerge = function() {
    var err = '';
    var r = FileCheck();
    if (typeof r === 'string') {
      err = oMX.error.text + ': ' + r;
    } else if (r === null) {
      err = 'Files are not loaded yet';
    } else if (oMX.count < 2) {
      err = 'Minimum 2 files are required';
    }
    $('output').innerHTML = err ? err : oMX.Get(2);
  };

  if (oMX.error.code !== '') {
    $('output').innerHTML = oMX.error.text; /* no DOM support */
  } else if (!window.File || !window.FileList || !window.FileReader) {
    $('output').innerHTML = 'Sorry, the demo needs a browser supporting FileReader API';
  } else {
    AddEvent('change', 'files', FileSelect);
    AddEvent('click', 'merge', FileMerge);
  }

}
1341263
function Lexer(defunct) {
  if (typeof defunct !== "function") defunct = Lexer.defunct;
  
  var tokens = [], rules = [], remove = 0;
  
  this.state = 0;
  this.index = 0;
  this.input = "";
  
  this.addRule = function (pattern, action, start) {
    var global = pattern.global;
    
    if (!global) {
      var flags = "g";
      if (pattern.multiline) flags += "m";
      if (pattern.ignoreCase) flags += "i";
      pattern = new RegExp(pattern.source, flags);
    }
    
    if (!Array.isArray(start)) start = [0];

    rules.push({
      pattern: pattern,
      global: global,
      action: action,
      start: start
    });

    return this;
  };

  this.setInput = function (input) {
    remove = 0;
    this.state = 0;
    this.index = 0;
    tokens.length = 0;
    this.input = input;
    return this;
  };

  this.lex = function () {
    if (tokens.length) return tokens.shift();

    this.reject = true;

    while (this.index <= this.input.length) {
      var matches = scan.call(this).splice(remove);
      var index = this.index;

      while (matches.length) {
        if (this.reject) {
          var match = matches.shift();
          var result = match.result;
          var length = match.length;
          this.index += length;
          this.reject = false;
          remove++;

          var token = match.action.apply(this, result);
          if (this.reject)
            this.index = result.index;
          else if (typeof token !== "undefined") {
            if (Array.isArray(token)) {
              tokens = token.slice(1);
              token = token[0];
            }
            if (length) remove = 0;
            return token;
          }
        }
        else break;
      }

      var input = this.input;

      if (index < input.length) {
        if (this.reject) {
          remove = 0;
          var token = defunct.call(this, input.charAt(this.index++));
          if (typeof token !== "undefined") {
            if (Array.isArray(token)) {
              tokens = token.slice(1);
              return token[0];
            }
            else return token;
          }
        }
        else {
          if (this.index !== index)
            remove = 0;
          this.reject = true;
        }
      }
      else if (matches.length)
        this.reject = true;
      else break;
    }
  };

  function scan() {
    var matches = [];
    var index = 0;

    var state = this.state;
    var lastIndex = this.index;
    var input = this.input;

    for (var i = 0, length = rules.length; i < length; i++) {
      var rule = rules[i];
      var start = rule.start;
      var states = start.length;

      if ((!states || start.indexOf(state) >= 0) ||
        (state % 2 && states === 1 && !start[0])) {
        var pattern = rule.pattern;
        pattern.lastIndex = lastIndex;
        var result = pattern.exec(input);

        if (result && result.index === lastIndex) {
          var j = matches.push({
            result: result,
            action: rule.action,
            length: result[0].length
          });

          if (rule.global) index = j;

          while (--j > index) {
            var k = j - 1;

            if (matches[j].length > matches[k].length) {
              var temple = matches[j];
              matches[j] = matches[k];
              matches[k] = temple;
            }
          }
        }
      }
    }

    return matches;
  }
}
123529
function initCustomPointerTypemaps(typemapsdir) {
  return fs.readdirAsync(typemapsdir).then(function(dirs) {
    return Promise.all(_.map(dirs, function(dir) {
      // get all js*.i directives from class-specific subdirectories, to be parsed below for %typemaps directives
      return fs.readdirAsync(typemapsdir + '/' + dir).then(function(files) {
        var directive = _.find(files, function(fn) {
          return ((path.extname(fn) == '.i') && (path.basename(fn).search(/^js/) != -1));
        });
        var data = {};
        if (directive) {
          data[dir] = typemapsdir + '/' + dir + '/' + directive;
        }
        return data;
      }).catch(function(e) {
        // get all .i directives from top level directory, and parse for %array_class directives
        if (e.code == 'ENOTDIR') {
          var fn = dir;
          if (path.extname(fn) == '.i') {
            return fs.readFileAsync(typemapsdir + '/' + fn, 'utf8').then(function(directives) {
              var arraytypes = _.filter(directives.split(/\n/), function(line) {
                return (line.search(/^%array_class/) != -1);
              });
              _.each(arraytypes, function(arraytype) {
                var parsed = arraytype.match(/%array_class\(([A-Za-z0-9_]+)[\s]*,[\s]*([A-Za-z0-9_]+)\)/);
                if (parsed) {
                  var from = parsed[1];
                  var to = parsed[2];
                  xml2js.ARRAY_TYPEMAPS[from] = { arrayType: to, classes: [] };
                } else {
                  console.log('Incorrectly parsed array_class from ' + fn + ': ' + arraytype);
                }
              });
            });
          }
        } else {
          throw e;
        }
      });
    }));
  }).then(function(__directivesFiles) {
    // parse for %typemaps & %pointer_functions directives
    var _directivesFiles = _.filter(__directivesFiles, function(data) { return !_.isEmpty(data); });
    var directivesFiles = _.object(_.map(_directivesFiles, _.keys), _.flatten(_.map(_directivesFiles, _.values)));
    return Promise.all(_.map(directivesFiles, function(directivesFn, className) {
      return fs.readFileAsync(directivesFn, 'utf8').then(function(directives) {
        var typemaps = _.filter(directives.split(/\n/), function(line) {
          return (line.search(/^%typemap/) != -1);
        });
        _.each(typemaps, function(typemap) {
          var parsed = typemap.match(/%typemap\((in|out)\)[\s]+([A-Za-z0-9_]+[\s]*[\*])/);
          if (parsed) {
            var dir = parsed[1]; // TODO: ignored for now
            var type = normalizePointer(parsed[2]);
            var datatype = getPointerDataType(type);
            if (_.has(xml2js.ARRAY_TYPEMAPS, datatype)) {
              xml2js.ARRAY_TYPEMAPS[datatype].classes.push(className);
            } else {
              console.log('Ignored typemap from ' + directivesFn + ': ' + typemap.replace('{', '') + ' (no %array_class directive found for ' + datatype + ')');
            }
          } else {
            console.log('Ignored typemap from ' + directivesFn + ': ' + typemap.replace('{', '') + ' (only considering in/out typemaps of pointer types)');
          }
        });
        var ptrfns = _.filter(directives.split(/\n/), function(line) {
          return (line.search(/^%pointer_functions/) != -1);
        });
        _.each(ptrfns, function(ptrfn) {
          var parsed = ptrfn.match(/%pointer_functions\(([A-Za-z0-9_]+)[\s]*,[\s]*([A-Za-z0-9_]+)\)/);
          if (parsed) {
            var from = parsed[1];
            var to = parsed[2];
            if (!_.has(xml2js.POINTER_TYPEMAPS, className)) {
              xml2js.POINTER_TYPEMAPS[className] = {};
            }
            xml2js.POINTER_TYPEMAPS[className][from] = to;
          }
        });
      });
    }));
  });
}
626177
function TypeParser(defaultBuilder) {

	/* TODO
	 * - function(this:) // type of this
	 * - function(new:) // constructor
	 */
	var rLexer = /\s*(Array\.?<|Object\.?<|Set\.?<|Promise\.?<|function\(|\{|:|\(|\||\}|>|\)|,|\[\]|\*|\?|!|\.\.\.)|\s*((?:module:)?\w+(?:[\/.#~]\w+)*)|./g;

	var input,
		builder,
		token,
		tokenStr;

	function next(expected) {
		if ( expected !== undefined && token !== expected ) {
			throw new SyntaxError("TypeParser: expected '" + expected + "', but found '" + tokenStr + "' (pos: " + rLexer.lastIndex + ", input='" + input + "')");
		}
		var match = rLexer.exec(input);
		if ( match ) {
			tokenStr = match[1] || match[2];
			token = match[1] || (match[2] && 'symbol');
			if ( !token ) {
				throw new SyntaxError("TypeParser: unexpected '" + tokenStr + "' (pos: " + match.index + ", input='" + input + "')");
			}
		} else {
			tokenStr = token = null;
		}
	}

	function parseType() {
		var nullable = false;
		var mandatory = false;
		if ( token === '?' ) {
			next();
			nullable = true;
		} else if ( token === '!' ) {
			next();
			mandatory = true;
		}

		var type;

		if ( token === 'Array.<' || token === 'Array<' ) {
			next();
			var componentType = parseType();
			next('>');
			type = builder.array(componentType);
		} else if ( token === 'Object.<' || token === 'Object<' ) {
			next();
			var keyType;
			var valueType = parseType();
			if ( token === ',' ) {
				next();
				keyType = valueType;
				valueType = parseType();
			} else {
				keyType = builder.synthetic(builder.simpleType('string'));
			}
			next('>');
			type = builder.object(keyType, valueType);
		} else if ( token === 'Set.<' || token === 'Set<' ) {
			next();
			var elementType = parseType();
			next('>');
			type = builder.set(elementType);
		} else if ( token === 'Promise.<' || token === 'Promise<' ) {
			next();
			var resultType = parseType();
			next('>');
			type = builder.promise(resultType);
		} else if ( token === 'function(' ) {
			next();
			var thisType, constructorType, paramTypes = [], returnType;
			if ( tokenStr === 'this' ) {
				next();
				next(':');
				thisType = parseType();
				if ( token === ',' ) {
					next();
				}
			} else if ( tokenStr === 'new' ) {
				next();
				next(':');
				constructorType = parseType();
				if ( token === ',' ) {
					next();
				}
			}
			while ( token === 'symbol' || token === '...' ) {
				var repeatable = token === '...';
				if ( repeatable) {
					next();
				}
				var paramType = parseType();
				if ( repeatable ) {
					paramType = builder.repeatable(paramType);
				}
				paramTypes.push(paramType);
				if ( token === ',' ) {
					if ( repeatable ) {
						throw new SyntaxError("TypeParser: only the last parameter of a function can be repeatable (pos: " + rLexer.lastIndex + ", input='" + input + "')");
					}
					next();
				}
			}
			next(')');
			if ( token === ':' ) {
				next(':');
				returnType = parseType();
			}
			type = builder.function(paramTypes, returnType, thisType, constructorType);
		} else if ( token === '{' ) {
			var structure = Object.create(null);
			var propName,propType;
			next();
			do {
				propName = tokenStr;
				if ( !/^\w+$/.test(propName) ) {
					throw new SyntaxError("TypeParser: structure field must have a simple name (pos: " + rLexer.lastIndex + ", input='" + input + "', field:'" + propName + "')");
				}
				next('symbol');
				if ( token === ':' ) {
					next();
					propType = parseType();
				} else {
					propType = builder.synthetic(builder.simpleType('any'));
				}
				structure[propName] = propType;
				if ( token === '}' ) {
					break;
				}
				next(',');
			} while (token);
			next('}');
			type = builder.structure(structure);
		} else if ( token === '(' ) {
			next();
			type = parseTypes();
			next(')');
		} else if ( token === '*' ) {
			next();
			type = builder.simpleType('*');
		} else {
			type = builder.simpleType(tokenStr);
			next('symbol');
			while ( token === '[]' ) {
				next();
				type = builder.array(type);
			}
		}
		if ( nullable ) {
			type = builder.nullable(type);
		}
		if ( mandatory ) {
			type = builder.mandatory(type);
		}
		return type;
	}

	function parseTypes() {
		var types = [];
		do {
			types.push(parseType());
			if ( token !== '|' ) {
				break;
			}
			next();
		} while (token);
		return types.length === 1 ? types[0] : builder.union(types);
	}

	this.parse = function(typeStr, tempBuilder) {
		builder = tempBuilder || defaultBuilder || TypeParser.ASTBuilder;
		input = String(typeStr);
		rLexer.lastIndex = 0;
		next();
		var type = parseTypes();
		next(null);
		return type;
	};

}
634444
function ContextHelper(contexts) {

    var self = {};

    /**
     * ContextHelper Constructor
     * */
    var init = function(contexts) {

        if ( typeof(contexts) == 'undefined' ) {
            var contexts = {
                paths : {}
            }
        }

        self.contexts = contexts;

        if ( typeof(ContextHelper.initialized) != 'undefined' && ContextHelper.instance) {
            self = ContextHelper.instance;
        } else {
            ContextHelper.initialized = true;
            ContextHelper.instance = self
        }



        return self
    }

    self.configure = function(contexts) {
        joinContext(contexts)
    }

    joinContext = function(context) {
        merge(self.contexts, context, true)
    }

    var parseCtxObject = function (o, obj) {

        for (var i in o) {
            if (o[i] !== null && typeof(o[i]) == 'object') {
                parseCtxObject(o[i], obj);
            } else if (o[i] == '_content_'){
                o[i] = obj
            }
        }

        return o
    }

    setContext = function(name, obj, force) {

        if (arguments.length > 1) {
            //console.log("Globla setter active ", name, obj);
            if ( typeof(name) == 'undefined' || name == '' ) {
                var name = 'global'
            }

            if (/\./.test(name) ) {
                var keys        = name.split(/\./g)
                    , newObj    = {}
                    , str       = '{'
                    , _count    = 0;

                for (var k = 0, len = keys.length; k<len; ++k) {
                    str +=  "\""+ keys.splice(0,1)[0] + "\":{";

                    ++_count;
                    if (k == len-1) {
                        str = str.substr(0, str.length-1);
                        str += "\"_content_\"";
                        for (var c = 0; c<_count; ++c) {
                            str += "}"
                        }
                    }
                }

                newObj = parseCtxObject(JSON.parse(str), obj);
                if (force) {
                    var key = name.split(/\./g);
                    self.contexts = merge(self.contexts, newObj, true);
                } else {
                    self.contexts =  merge(self.contexts, newObj)
                }

            } else {
                if (!self.contexts[name])
                    self.contexts[name] = {};

                if ( typeof(self.contexts[name]) != 'undefined' && !force) {
                    self.contexts[name] = obj
                } else {
                    self.contexts[name] = merge(self.contexts[name], obj, force)
                }
            }

        } else {
            //console.debug("setting context ", arguments[0]);
            self.contexts = arguments[0]
        }

        ContextHelper.instance = self;
    }

    getContext = function(name) {

        if ( typeof(name) != 'undefined' ) {
            try {
                //return clone(self.contexts[name])
                return self.contexts[name]
            } catch (err) {
                return undefined
            }
        } else {
            return self.contexts
        }
    }


    var throwError = function(code, err) {
        var router      = getContext('router');
        if (router) {
            var res                 = router.response
                , next              = router.next
                , hasViews          = router.hasViews
                , isUsingTemplate   = isUsingTemplate
                , code              = code;


            if (arguments.length < 2) {
                var err = code;
                code = 500
            }

            if ( !hasViews || !isUsingTemplate ) {
                if (!res.headersSent) {
                    res.writeHead(code, { 'Content-Type': 'application/json'} );
                    res.end(JSON.stringify({
                        status: code,
                        error: 'Error '+ code +'. '+ err.stack
                    }))
                } else {
                    next()
                }

            } else {
                if (!res.headersSent) {
                    res.writeHead(code, { 'Content-Type': 'text/html'} );
                    res.end('<h1>Error '+ code +'.</h1><pre>'+ err.stack + '</pre>')
                } else {
                    next()
                }
            }
        } else {
            throw err
        }
    }

    /**
     * Get bundle library
     *
     * TODO - cleanup
     *
     * @param {string} [ bundle ] - Bundle name
     * @param {string} lib  - Library name (module or file)
     *
     * */
    getLib = function(bundle, lib) {
        var ctx       = self.contexts;

        if (arguments.length == 1 || !bundle) {
            //console.debug(
            //    '\n[ 0 ] = '+ __stack[0].getFileName(),
            //    '\n[ 1 ] = '+ __stack[1].getFileName(),
            //    '\n[ 2 ] = '+ __stack[2].getFileName(),
            //    '\n[ 3 ] = '+ __stack[3].getFileName(),
            //    '\n[ 4 ] = '+ __stack[4].getFileName(),
            //    '\n[ 5 ] = '+ __stack[5].getFileName(),
            //    '\n[ 6 ] = '+ __stack[6].getFileName()
            //);
            var lib         = (arguments.length == 1) ? bundle : lib
                , bundle    = null
                , libPath   = null
                , file      = null
                , stackFileName = null;
                //, file      = ( !/node_modules/.test(__stack[1].getFileName()) ) ?  __stack[1].getFileName() : __stack[2].getFileName()
            for (var i = 1, len = 10; i<len; ++i) {
                stackFileName = __stack[i].getFileName();
                if ( stackFileName && !/node_modules/.test(stackFileName) ) {
                    file = stackFileName;
                    break;
                }
            }
            var a           = file.replace('.js', '').split('/')
                , i         = a.length-1;

            if (bundle == lib) {
                bundle = ctx.bundle
            } else {

                if (ctx.bundles) {
                    for (; i >= 0; --i) {
                        index = ctx.bundles.indexOf(a[i]);
                        if ( index > -1 ) {
                            ctx.bundle = bundle = ctx.bundles[index];

                            break
                        }
                    }
                } else if (ctx.bundle) {
                    bundle = ctx.bundle
                }

            }
        }
        // else {
        //     var libPath     = null
        //         , conf      = getContext('gina').config
        //         , env       = conf.env
        //         , cacheless = conf.isCacheless();
        // }
        var env     = ctx.env;
        var cacheless = ctx.cacheless;
        var Config  = ctx.gina.Config;
        var conf = new Config({
            env             : env,
            executionPath   : getPath('root'),
            startingApp     : bundle,
            ginaPath        : getPath('gina').core
        }).getInstance(bundle);

        if ( typeof(lib) != 'undefined' ) {

            try {

                if (!libPath)
                    libPath = conf.bundlesConfiguration.conf[bundle][env].libPath;

                var libToLoad = _(libPath +'/'+ lib, true);

                if (cacheless) delete require.cache[libToLoad];

                // init with options
                try {
                    var LibClass = require(libToLoad);
                    /**
                     * getConfig
                     *
                     * @param {string} [name]
                     *
                     * @return {object} bundleConfiguration - By default config from the bundle where the lib is located
                     * */
                    LibClass.prototype.getConfig = function (name) {
                        if ( typeof(name) != 'undefined' && typeof( conf.envConf[bundle][env].content[name] ) != 'undefined' ) {
                            return conf.envConf[bundle][env].content[name]
                        }

                        return conf.envConf[bundle][env]
                    };

                    return new LibClass ({
                        bundle      : bundle,
                        env         : env,
                        cacheless   : cacheless,
                        libPath     : libPath
                    })

                } catch(err) {
                    throwError(500, err)
                }

            } catch (err) {
                console.error(err.stack||err.message||err);
                throwError(500, err);
                return undefined
            }
        } else {
            console.error( new Error("no `lib` found"));
            throwError(500, new Error("`lib` [ "+name+" ] not found"))
            return undefined
        }

    }

    /**
     * Whisper
     * Convert replace constant names dictionary by its value
     *
     * @param {object} dictionary
     * @param {object} replaceable
     *
     * @return {object} revealed
     * */
    whisper = function(dictionary, replaceable, rule) {
        var s, key;
        if ( typeof(rule) != 'undefined') {
            return replaceable.replace(rule, function(s, key) {
                return dictionary[key] || s;
            })
        } else {

            if ( typeof(replaceable) == 'object' &&  !/\[native code\]/.test(replaceable.constructor) ||  typeof(replaceable) == 'function' /** && /Object/.test(replaceable.constructor) */ ) { // /Object/.test(replaceable.constructor)
                for (var attr in replaceable) {
                    if ( typeof(replaceable[attr]) != 'function') {
                        replaceable[attr] = (typeof(replaceable[attr]) != 'string' && typeof(replaceable[attr]) != 'object') ? JSON.stringify(replaceable[attr], null, 2) : replaceable[attr];
                        if (replaceable[attr] && typeof(replaceable[attr]) != 'object') {
                            replaceable[attr] = replaceable[attr].replace(/\{(\w+)\}/g, function(s, key) {
                                return dictionary[key] || s;
                            })
                        }
                    }
                }
                return replaceable
            } else { // mixing with classes
                replaceable = JSON.stringify(replaceable, null, 2);

                return JSON.parse(
                    replaceable.replace(/\{(\w+)\}/g, function(s, key) {
                        return dictionary[key] || s;
                    })
                )
            }
        }
    }

    isWin32 = function() {
        return (os.platform() == 'win32') ? true : false;
    }

    return init(contexts)
}
148363
function highlight(language_name, value) {
    if (!compileModes.called) {
      compileModes();
      compileModes.called = true;
    }

    function subMode(lexem, mode) {
      for (var i = 0; i < mode.contains.length; i++) {
        if (mode.contains[i].beginRe.test(lexem)) {
          return mode.contains[i];
        }
      }
    }

    function endOfMode(mode_index, lexem) {
      if (modes[mode_index].end && modes[mode_index].endRe.test(lexem))
        return 1;
      if (modes[mode_index].endsWithParent) {
        var level = endOfMode(mode_index - 1, lexem);
        return level ? level + 1 : 0;
      }
      return 0;
    }

    function isIllegal(lexem, mode) {
      return mode.illegalRe && mode.illegalRe.test(lexem);
    }

    function compileTerminators(mode, language) {
      var terminators = [];

      for (var i = 0; i < mode.contains.length; i++) {
        terminators.push(mode.contains[i].begin);
      }

      var index = modes.length - 1;
      do {
        if (modes[index].end) {
          terminators.push(modes[index].end);
        }
        index--;
      } while (modes[index + 1].endsWithParent);

      if (mode.illegal) {
        terminators.push(mode.illegal);
      }

      return langRe(language, '(' + terminators.join('|') + ')', true);
    }

    function eatModeChunk(value, index) {
      var mode = modes[modes.length - 1];
      if (!mode.terminators) {
        mode.terminators = compileTerminators(mode, language);
      }
      mode.terminators.lastIndex = index;
      var match = mode.terminators.exec(value);
      if (match)
        return [value.substr(index, match.index - index), match[0], false];
      else
        return [value.substr(index), '', true];
    }

    function keywordMatch(mode, match) {
      var match_str = language.case_insensitive ? match[0].toLowerCase() : match[0]
      for (var className in mode.keywordGroups) {
        if (!mode.keywordGroups.hasOwnProperty(className))
          continue;
        var value = mode.keywordGroups[className].hasOwnProperty(match_str);
        if (value)
          return [className, value];
      }
      return false;
    }

    function processKeywords(buffer, mode) {
      if (!mode.keywords)
        return escape(buffer);
      var result = '';
      var last_index = 0;
      mode.lexemsRe.lastIndex = 0;
      var match = mode.lexemsRe.exec(buffer);
      while (match) {
        result += escape(buffer.substr(last_index, match.index - last_index));
        var keyword_match = keywordMatch(mode, match);
        if (keyword_match) {
          keyword_count += keyword_match[1];
          result += '<span class="'+ keyword_match[0] +'">' + escape(match[0]) + '</span>';
        } else {
          result += escape(match[0]);
        }
        last_index = mode.lexemsRe.lastIndex;
        match = mode.lexemsRe.exec(buffer);
      }
      result += escape(buffer.substr(last_index, buffer.length - last_index));
      return result;
    }

    function processBuffer(buffer, mode) {
      if (mode.subLanguage && languages[mode.subLanguage]) {
        var result = highlight(mode.subLanguage, buffer);
        keyword_count += result.keyword_count;
        return result.value;
      } else {
        return processKeywords(buffer, mode);
      }
    }

    function startNewMode(mode, lexem) {
      var markup = mode.className?'<span class="' + mode.className + '">':'';
      if (mode.returnBegin) {
        result += markup;
        mode.buffer = '';
      } else if (mode.excludeBegin) {
        result += escape(lexem) + markup;
        mode.buffer = '';
      } else {
        result += markup;
        mode.buffer = lexem;
      }
      modes.push(mode);
      relevance += mode.relevance;
    }

    function processModeInfo(buffer, lexem, end) {
      var current_mode = modes[modes.length - 1];
      if (end) {
        result += processBuffer(current_mode.buffer + buffer, current_mode);
        return false;
      }

      var new_mode = subMode(lexem, current_mode);
      if (new_mode) {
        result += processBuffer(current_mode.buffer + buffer, current_mode);
        startNewMode(new_mode, lexem);
        return new_mode.returnBegin;
      }

      var end_level = endOfMode(modes.length - 1, lexem);
      if (end_level) {
        var markup = current_mode.className?'</span>':'';
        if (current_mode.returnEnd) {
          result += processBuffer(current_mode.buffer + buffer, current_mode) + markup;
        } else if (current_mode.excludeEnd) {
          result += processBuffer(current_mode.buffer + buffer, current_mode) + markup + escape(lexem);
        } else {
          result += processBuffer(current_mode.buffer + buffer + lexem, current_mode) + markup;
        }
        while (end_level > 1) {
          markup = modes[modes.length - 2].className?'</span>':'';
          result += markup;
          end_level--;
          modes.length--;
        }
        var last_ended_mode = modes[modes.length - 1];
        modes.length--;
        modes[modes.length - 1].buffer = '';
        if (last_ended_mode.starts) {
          startNewMode(last_ended_mode.starts, '');
        }
        return current_mode.returnEnd;
      }

      if (isIllegal(lexem, current_mode))
        throw 'Illegal';
    }

    var language = languages[language_name];
    var modes = [language.defaultMode];
    var relevance = 0;
    var keyword_count = 0;
    var result = '';
    try {
      var index = 0;
      language.defaultMode.buffer = '';
      do {
        var mode_info = eatModeChunk(value, index);
        var return_lexem = processModeInfo(mode_info[0], mode_info[1], mode_info[2]);
        index += mode_info[0].length;
        if (!return_lexem) {
          index += mode_info[1].length;
        }
      } while (!mode_info[2]);
      if(modes.length > 1)
        throw 'Illegal';
      return {
        relevance: relevance,
        keyword_count: keyword_count,
        value: result
      }
    } catch (e) {
      if (e == 'Illegal') {
        return {
          relevance: 0,
          keyword_count: 0,
          value: escape(value)
        }
      } else {
        throw e;
      }
    }
  }
132718
function instanceOfOne(x) {
    for (var _len5 = arguments.length, types = new Array(_len5 > 1 ? _len5 - 1 : 0), _key5 = 1; _key5 < _len5; _key5++) {
      types[_key5 - 1] = arguments[_key5];
    }

    return types.some((0, _object.instanceOf)(x));
  }
359687
function () {
      var e = {
        type: 'literal',
        value: this.value.toString()
      };
      if (this.lang !== undefined) {
        e.lang = this.lang;
      } else if (this.datatype !== undefined) {
        e.datatype = this.datatype.toString();
      }
      return e;
    }
1346017
function addTextLocale(locale, body, options = {}) {
  const gt = new Gettext();
  const domain = 'messages';
  const {
    filter,
    gettextDefaultCharset = 'UTF-8',
  } = options;

  if (body.length > 0) {
    gt.addTranslations(locale, domain, po.parse(body, gettextDefaultCharset));
  }

  if (filter) {
    const filterAsync = Promise.promisify(filter);
    return filterAsync(gt, locale);
  }

  return Promise.resolve(gt.catalogs[locale] && gt.catalogs[locale][domain].translations);
}
1262139
function compile(grammar) {
  var tree = ometa.parser.matchAll(grammar, 'topLevel', undefined) //, error_handler("Error while parsing OMeta grammar"));
	var parserString = ometa.translator.match(tree, 'trans', undefined)//, error_handler("Error while translating grammar"));
  return parserString;
}
194543
function Lisp (input, lib, tables, host) {
  const Context = function (scope, parent) {
    this.scope = scope
    this.parent = parent

    this.get = function (identifier) {
      if (identifier in this.scope) {
        return this.scope[identifier]
      } else if (this.parent !== undefined) {
        return this.parent.get(identifier)
      }
    }
  }

  const special = {
    let: function (input, context) {
      const letContext = input[1].reduce(function (acc, x) {
        acc.scope[x[0].value] = interpret(x[1], context)
        return acc
      }, new Context({}, context))

      return interpret(input[2], letContext)
    },

    lambda: function (input, context) {
      return function () {
        const lambdaArguments = arguments
        const lambdaScope = input[1].reduce(function (acc, x, i) {
          acc[x.value] = lambdaArguments[i]
          return acc
        }, {})

        return interpret(input[2], new Context(lambdaScope, context))
      }
    }
  }

  const interpretList = function (input, context) {
    if (input.length > 0 && input[0].value in special) {
      return special[input[0].value](input, context)
    }
    const list = input.map(function (x) { return interpret(x, context) })
    return list[0] instanceof Function ? list[0].apply(undefined, list.slice(1)) : list
  }

  const interpret = function (input, context) {
    if (context === undefined) {
      return interpret(input, new Context(lib))
    } else if (input instanceof Array) {
      return interpretList(input, context)
    } else if (input.type === 'identifier') {
      return context.get(input.value)
    } else if (input.type === 'keyword') {
      return host[input.value] ? host[input.value] : null
    } else if (input.type === 'number' || input.type === 'string' || input.type === 'bool') {
      return input.value
    }
  }

  const categorize = function (input) {
    if (!isNaN(parseFloat(input))) {
      return { type: 'number', value: parseFloat(input) }
    } else if (input[0] === '"' && input.slice(-1) === '"') {
      return { type: 'string', value: input.slice(1, -1) }
    } else if (input[0] === ':') {
      return { type: 'keyword', value: input.substr(1, input.length - 1) }
    } else if (input === 'true' || input === 'false') {
      return { type: 'bool', value: input === 'true' }
    } else {
      return { type: 'identifier', value: input }
    }
  }

  const parenthesize = function (input, list) {
    if (list === undefined) { return parenthesize(input, []) }

    const token = input.shift()

    if (token === undefined) {
      return list.pop()
    } else if (token === '(') {
      list.push(parenthesize(input, []))
      return parenthesize(input, list)
    } else if (token === ')') {
      return list
    } else {
      return parenthesize(input, list.concat(categorize(token)))
    }
  }

  const tokenize = function (input) {
    return input.split('"').map(function (x, i) { return i % 2 === 0 ? x.replace(/\(/g, ' ( ').replace(/\)/g, ' ) ') : x.replace(/ /g, '!whitespace!') }).join('"').trim().split(/\s+/).map(function (x) { return x.replace(/!whitespace!/g, ' ') })
  }

  this.parse = function (input) {
    return parenthesize(tokenize(input))
  }

  this.toString = function () {
    return `${interpret(this.parse(input))}`
  }
}
510809
function (string, obj, instOf) {
        if (string instanceof instOf) {
            return string;
        }
        if (string === true && obj instanceof instOf) {
            return obj;
        }
        if (!obj) { return null; }
        obj = obj.get(string);
        if (obj instanceof instOf) {
            return obj;
        }
        return null;
    }