/*Utils functions: many of this functions are supported natively in nodejs but there are not implemented yet in the espruino API
and the idea behind this library is to support embed systems and that is why I added them here.
962529
function queryStringToJSON(url) {
  if (url === '') {
    return '';
  }
  var pairs = (url).slice(0).split('&'), result = {};
  for (var idx in pairs) {
    var pair = pairs[idx].split('=');
    if (!!pair[0]) {
      result[pair[0].toLowerCase()] = decodeURIComponent(pair[1] || '');
    }
  }
  return result;
}
556311
async function _process(
  args,
  { fetch },
  {
    _omitScript,
    maxWidth,
    hideMedia,
    hideThread,
    align,
    lang,
    theme,
    linkColor,
    widgetType
  }
) {
  const params = {
    url: args[0],
    omitScript: _omitScript,
    maxWidth,
    hideMedia,
    hideThread,
    align,
    lang,
    theme,
    linkColor,
    widgetType
  }
  try {
    const apiUrl = `https://api.twitter.com/1/statuses/oembed.json?${getQuery(
      params
    )}`
    const res = await (isBrowser ? jsonp : fetch)(apiUrl)
    return await res.json()
  } catch (e) {
    return {
      html: ""
    }
  }
}
860990
function getKeys(params, key, allowEmpty) {
  if (!Array.isArray(params)) { throw new Error(`[ethjs-util] method getKeys expecting type Array as 'params' input, got '${typeof params}'`); }
  if (typeof key !== 'string') { throw new Error(`[ethjs-util] method getKeys expecting type String for input 'key' got '${typeof key}'.`); }

  var result = []; // eslint-disable-line

  for (var i = 0; i < params.length; i++) { // eslint-disable-line
    var value = params[i][key]; // eslint-disable-line
    if (allowEmpty && !value) {
      value = '';
    } else if (typeof(value) !== 'string') {
      throw new Error('invalid abi');
    }
    result.push(value);
  }

  return result;
}
872820
function contributedExecFunc(service, name, progress, returnType, addedOutputFunction) {
		if (typeof(service.callback) !== "function") { //$NON-NLS-0$
			return undefined;
		}

		return function(args, context) {
			/* Use orion/Deferred since it supports progress, gcli/promise does not */
			//var promise = context.createPromise();
			var promise = new Deferred();

			var output = null;
			if (addedOutputFunction) {
				output = args["output"]; //$NON-NLS-0$
				if (output) {
					if (output.resourceExists()) {
						/* value is an array of nodes, in this context will always have a size of 1 */
						output = output.getValue()[0];
					} else {
						/* value is a string representing a non-existent resource */
						output = output.getValue();
					}
				}
				delete args.output;
			}

			/*
			 * The following function calls getPluginRepresentation(), if present, on all
			 * properties in object, in order to give custom types an opportunity to provide
			 * plugins with different representations of their instances than are used
			 * internally.
			 */
			var convertToPluginArgs = function(object, resultFn) {
				var keys = Object.keys(object);
				if (keys.length === 0) {
					resultFn(object);
				} else {
					var resultCount = 0;
					keys.forEach(function(current) {
						(function(key) {
							(function(value, fn) {
								if (value && value.getPluginRepresentation) {
									value.getPluginRepresentation().then(function(newValue) {
										fn(newValue);
									});
								} else {
									fn(value);
								}
							}(object[key], function(newValue) {
								object[key] = newValue;
								if (++resultCount === keys.length) {
									resultFn(object);
								}
							}));
						}(current));
					});
				}
			};

			convertToPluginArgs(args, function(pluginArgs) {
				function getCommandString(name, args) {
					var result = name;
					for (var key in args){
						result += " "; //$NON-NLS-0$
						result += args[key];
					}
					return result;
				}
				var resolvedFn = function(result) {
					var commandResult = new CommandResult(result, returnType);
					processResult(promise, commandResult, output);
				};
				var errorFn = function(error) {
					resolveError(promise, error);
				};
				var progressFn = function(data) {
					if (data && data.uriTemplate) {
						/* delegated UI request */
						var uriTemplate = new URITemplate(data.uriTemplate);
						var cwd = shellPageFileService.getCurrentDirectory();
						var href = uriTemplate.expand({}); // TODO
						var iframe = document.createElement("iframe"); //$NON-NLS-0$
						iframe.id = name;
						iframe.name = name;
						iframe.type = "text/html"; //$NON-NLS-0$
						iframe.sandbox = "allow-scripts allow-same-origin allow-forms"; //$NON-NLS-0$
						iframe.frameborder = 1;
						iframe.src = href;
						iframe.className = "delegatedUI"; //$NON-NLS-0$
						if (data.width) {
							iframe.style.width = data.width;
						}
						if (data.height) {
							iframe.style.height = data.height;
						}
						var outputElements = document.getElementsByClassName("gcli-row-out"); //$NON-NLS-0$
						var parentElement = outputElements[outputElements.length - 1];
						parentElement.appendChild(iframe);
						/* listen for notification from the iframe, expecting either a "result", "error" or "progress" property */
						window.addEventListener("message", function _messageHandler(event) { //$NON-NLS-0$
							if (event.source !== iframe.contentWindow) {
								return;
							}
							if (typeof event.data === "string") { //$NON-NLS-0$
								var data = JSON.parse(event.data);
								if (data.pageService === "orion.page.delegatedUI" && data.source === name) { //$NON-NLS-0$
									window.removeEventListener("message", _messageHandler, false); //$NON-NLS-0$
									if (data.error) {
										errorFn(data.error);
									} else {
										parentElement.removeChild(iframe);
										if (data.result) {
											resolvedFn(data.result);
										} else if (data.progress) {
											progressFn(data.progress);
										}
									}
								}
							}
						}, false);
					} else {
						if (typeof promise.progress === "function") { //$NON-NLS-0$
							var commandResult = new CommandResult(data, returnType);
							processResult(promise, commandResult, output, true);
						}
					}
				};
				progress.progress(service.callback(pluginArgs, {cwd: getCWD()}), "Executing command " + getCommandString(name, args)).then(resolvedFn, errorFn, progressFn); //$NON-NLS-0$
			});
			return promise;
		};
	}
1049582
function createFunction() {
      // Lazy define.
      createFunction = function(args, body) {
        var result,
            anchor = freeDefine ? freeDefine.amd : Benchmark,
            prop = uid + 'createFunction';

        runScript((freeDefine ? 'define.amd.' : 'Benchmark.') + prop + '=function(' + args + '){' + body + '}');
        result = anchor[prop];
        delete anchor[prop];
        return result;
      };
      // Fix JaegerMonkey bug.
      // For more information see http://bugzil.la/639720.
      createFunction = support.browser && (createFunction('', 'return"' + uid + '"') || _.noop)() == uid ? createFunction : Function;
      return createFunction.apply(null, arguments);
    }
738017
function (tpl) {
            var func = this.compile(tpl);
            return 'function(' + func.params.join(',') + '){\n' +
                func.source.join('\n') +
                '}';
        }
818037
function Slack(opts, debug) {
  if (!(this instanceof Slack)) return new Slack(opts);
  this.opts = opts;
  this.debug = debug;

  /**
   * Do everything.
   */

  this.import = function *() {
    try {
      console.log('Starting import');
      yield this.tokens();
      console.log('Got tokens');
      yield this.login();
      console.log('Logged in');
    } catch (e) {
      console.log('Uh oh! ' + e);
      throw e;
    }
    console.log('Getting emoji page');
    var emojiList = '';
    var aliasList = '';
    for (var i = 0; i < Object.keys(this.opts.emojis).length; i++) {
      var e = this.opts.emojis[i];
      if (e.src) {
        var uploadRes = yield this.upload(e.name, e.src);
        emojiList += ' :' + e.name + ':';
      }
      if (e.aliases) {
        for (var n = 0; n < e.aliases.length; n++) {
          yield this.alias(e.name, e.aliases[n]);
          aliasList += ' :' + e.aliases[n] + ':';
        }
      }
    }
    console.log('Uploaded emojis:' + emojiList);
    console.log('Uploaded emoji aliases:' + aliasList);
    return 'Success';
  };

  /**
   * Get login page (aka credentials).
   */

  this.tokens = function *() {
    var opts = this.opts;
    opts.jar = opts.jar || { _jar: { store: { idx: {} } } };
    var load = {
      url: opts.url + loginFormPath,
      headers: headers,
      jar: opts.jar,
      method: 'GET'
    };
    var res = yield request(load);
    var $ = cheerio.load(res[0].body);
    if (this.debug) write($('title').text(), $.html());
    opts.formData = {
      signin: $('#signin_form input[name="signin"]').attr('value'),
      redir: $('#signin_form input[name="redir"]').attr('value'),
      crumb: $('#signin_form input[name="crumb"]').attr('value'),
      remember: 'on',
      email: opts.email,
      password: opts.password
    };
    if (!opts.formData.signin && !opts.formData.redir && !opts.formData.crumb) throw new Error('Login error: could not get login form for ' + opts.url);
    return this.opts = opts;
  };

  /**
   * Log into Slack and populate cookies.
   */

  this.login = function *() {
    var opts = this.opts;
    var load = {
      url: opts.url + loginFormPath,
      headers: headers,
      jar: opts.jar,
      method: 'POST',
      followAllRedirects: true,
      formData: opts.formData
    };
    var res = yield request(load);
    if(res[0].body.indexOf("Sorry, you entered an incorrect email address or password.") != -1){
      throw new Error('Login error: incorrect username / password');
    }

    if(res[0].body.indexOf("Enter your authentication code") != -1){

      var $ = cheerio.load(res[0].body);

      var inputs = $("form input")

      var formData = {};

      inputs.each(function(i,v){
        formData[v.attribs.name] = v.attribs.value;
      })

      user_2fa_code = yield ask('2FA Code: ', isPassword, 'A password (as defined by this script) needs to have at least one character (not including you).');
      formData["2fa_code"] = user_2fa_code

      delete formData[undefined]
      delete formData['input']

      var load_2fa = {
        url: opts.url + "/",
        headers: headers,
        jar: opts.jar,
        method: 'POST',
        followAllRedirects: true,
        formData: formData
      };
      res = yield request(load_2fa);
    }

    //TODO: it may be necessary in the future to replace this with a user-supplied token
    var match = apiTokenRegex.exec(res[0].body);
    if (!match || !match[1]) {
      throw new Error('Application Error: unable to find api token on login page');
    }
    opts.apiToken = match[1];

    return this.opts = opts;
  };

  /**
   * Upload the emoji.
   */

  this.upload = function *(name, emoji) {
    console.log('Uploading %s with %s', name, emoji);
    return new Promise(function(resolve, reject, notify) {
      var opts = this.opts;
      var r = req({
        url: opts.url + emojiAddEndpoint,
        headers: headers,
        method: 'POST',
        jar: opts.jar,
        followAllRedirects: true
      }, function(err, res, body) {
        if (err || !body) return reject(err);
        resolve(body);
      });
      var form = r.form();
      form.append('name', name);
      form.append('mode', 'data');
      form.append('image', req(emoji));
      form.append('token', opts.apiToken);
    }.bind(this));
  };

  this.alias = function *(name, alias) {
    console.log('Aliasing %s to %s', alias, name);
    return new Promise(function(resolve, reject, notify) {
      var opts = this.opts;
      var r = req({
        url: opts.url + emojiAddEndpoint,
      headers: {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36'},
        method: 'POST',
        jar: opts.jar,
        followAllRedirects: true
      }, function(err, res, body) {
        if (err || !body) return reject(err);
        resolve(body);
      });
      var form = r.form();
      form.append('name', alias);
      form.append('mode', 'alias');
      form.append('alias', name);
      form.append('token', opts.apiToken);
    }.bind(this));
  };
}
147880
function (beyond) {
        "use strict";
    
        var items = {};
        var keys = [];
        Object.defineProperty(this, 'items', {
            'get': function () {
                return items;
            }
        });
        Object.defineProperty(this, 'keys', {
            'get': function () {
                return keys;
            }
        });
        Object.defineProperty(this, 'length', {
            'get': function () {
                return keys.length;
            }
        });
    
        this.get = function (name) {
    
            if (items[name]) return items[name];
    
            var library = new Library(beyond, name);
            items[name] = library;
            keys.push(name);
    
            return library;
    
        };
    
    }
71893
function has(name) {
      if (has[name] !== undef) {
        // Return cached feature test result.
        return has[name];
      }
      var isSupported;
      if (name == "bug-string-char-index") {
        // IE <= 7 doesn't support accessing string characters using square
        // bracket notation. IE 8 only supports this for primitives.
        isSupported = "a"[0] != "a";
      } else if (name == "json") {
        // Indicates whether both `JSON.stringify` and `JSON.parse` are
        // supported.
        isSupported = has("json-stringify") && has("json-parse");
      } else {
        var value, serialized = '{"a":[1,true,false,null,"\\u0000\\b\\n\\f\\r\\t"]}';
        // Test `JSON.stringify`.
        if (name == "json-stringify") {
          var stringify = exports.stringify, stringifySupported = typeof stringify == "function" && isExtended;
          if (stringifySupported) {
            // A test function object with a custom `toJSON` method.
            (value = function () {
              return 1;
            }).toJSON = value;
            try {
              stringifySupported =
                // Firefox 3.1b1 and b2 serialize string, number, and boolean
                // primitives as object literals.
                stringify(0) === "0" &&
                // FF 3.1b1, b2, and JSON 2 serialize wrapped primitives as object
                // literals.
                stringify(new Number()) === "0" &&
                stringify(new String()) == '""' &&
                // FF 3.1b1, 2 throw an error if the value is `null`, `undefined`, or
                // does not define a canonical JSON representation (this applies to
                // objects with `toJSON` properties as well, *unless* they are nested
                // within an object or array).
                stringify(getClass) === undef &&
                // IE 8 serializes `undefined` as `"undefined"`. Safari <= 5.1.7 and
                // FF 3.1b3 pass this test.
                stringify(undef) === undef &&
                // Safari <= 5.1.7 and FF 3.1b3 throw `Error`s and `TypeError`s,
                // respectively, if the value is omitted entirely.
                stringify() === undef &&
                // FF 3.1b1, 2 throw an error if the given value is not a number,
                // string, array, object, Boolean, or `null` literal. This applies to
                // objects with custom `toJSON` methods as well, unless they are nested
                // inside object or array literals. YUI 3.0.0b1 ignores custom `toJSON`
                // methods entirely.
                stringify(value) === "1" &&
                stringify([value]) == "[1]" &&
                // Prototype <= 1.6.1 serializes `[undefined]` as `"[]"` instead of
                // `"[null]"`.
                stringify([undef]) == "[null]" &&
                // YUI 3.0.0b1 fails to serialize `null` literals.
                stringify(null) == "null" &&
                // FF 3.1b1, 2 halts serialization if an array contains a function:
                // `[1, true, getClass, 1]` serializes as "[1,true,],". FF 3.1b3
                // elides non-JSON values from objects and arrays, unless they
                // define custom `toJSON` methods.
                stringify([undef, getClass, null]) == "[null,null,null]" &&
                // Simple serialization test. FF 3.1b1 uses Unicode escape sequences
                // where character escape codes are expected (e.g., `\b` => `\u0008`).
                stringify({ "a": [value, true, false, null, "\x00\b\n\f\r\t"] }) == serialized &&
                // FF 3.1b1 and b2 ignore the `filter` and `width` arguments.
                stringify(null, value) === "1" &&
                stringify([1, 2], null, 1) == "[\n 1,\n 2\n]" &&
                // JSON 2, Prototype <= 1.7, and older WebKit builds incorrectly
                // serialize extended years.
                stringify(new Date(-8.64e15)) == '"-271821-04-20T00:00:00.000Z"' &&
                // The milliseconds are optional in ES 5, but required in 5.1.
                stringify(new Date(8.64e15)) == '"+275760-09-13T00:00:00.000Z"' &&
                // Firefox <= 11.0 incorrectly serializes years prior to 0 as negative
                // four-digit years instead of six-digit years. Credits: @Yaffle.
                stringify(new Date(-621987552e5)) == '"-000001-01-01T00:00:00.000Z"' &&
                // Safari <= 5.1.5 and Opera >= 10.53 incorrectly serialize millisecond
                // values less than 1000. Credits: @Yaffle.
                stringify(new Date(-1)) == '"1969-12-31T23:59:59.999Z"';
            } catch (exception) {
              stringifySupported = false;
            }
          }
          isSupported = stringifySupported;
        }
        // Test `JSON.parse`.
        if (name == "json-parse") {
          var parse = exports.parse;
          if (typeof parse == "function") {
            try {
              // FF 3.1b1, b2 will throw an exception if a bare literal is provided.
              // Conforming implementations should also coerce the initial argument to
              // a string prior to parsing.
              if (parse("0") === 0 && !parse(false)) {
                // Simple parsing test.
                value = parse(serialized);
                var parseSupported = value["a"].length == 5 && value["a"][0] === 1;
                if (parseSupported) {
                  try {
                    // Safari <= 5.1.2 and FF 3.1b1 allow unescaped tabs in strings.
                    parseSupported = !parse('"\t"');
                  } catch (exception) {}
                  if (parseSupported) {
                    try {
                      // FF 4.0 and 4.0.1 allow leading `+` signs and leading
                      // decimal points. FF 4.0, 4.0.1, and IE 9-10 also allow
                      // certain octal literals.
                      parseSupported = parse("01") !== 1;
                    } catch (exception) {}
                  }
                  if (parseSupported) {
                    try {
                      // FF 4.0, 4.0.1, and Rhino 1.7R3-R4 allow trailing decimal
                      // points. These environments, along with FF 3.1b1 and 2,
                      // also allow trailing commas in JSON objects and arrays.
                      parseSupported = parse("1.") !== 1;
                    } catch (exception) {}
                  }
                }
              }
            } catch (exception) {
              parseSupported = false;
            }
          }
          isSupported = parseSupported;
        }
      }
      return has[name] = !!isSupported;
    }
37591
function isAPIEnabled(embed) {
  var regex = '\/?api=1&player_id=' + embed.id;
  regex = new RegExp(regex);
  return regex.test(embed.src);
}
77776
function define (File, utils) {
  const { callable } = utils;
  const { debug, error, strong } = utils.cnsl;
  const { regexpEscape, uniqueMatch } = utils.string;

  return class NUNJUCKSFile extends File {
    /**
     * Constructor
     * @param {String} id
     * @param {String} filepath
     * @param {Object} options
     *  - {Object} caches
     *  - {Object} fileExtensions
     *  - {Function} fileFactory
     *  - {Object} globalAliases
     *  - {Array} npmModulepaths
     *  - {Object} pluginOptions
     *  - {Object} runtimeOptions
     */
    constructor (id, filepath, options) {
      super(id, filepath, options);

      this.workflows.writeable = WORKFLOW_WRITEABLE;
    }

    /**
     * Parse file contents for dependency references
     * @param {Object} buildOptions
     *  - {Boolean} batch
     *  - {Boolean} bootstrap
     *  - {Boolean} boilerplate
     *  - {Boolean} browser
     *  - {Boolean} bundle
     *  - {Boolean} compress
     *  - {Array} ignoredFiles
     *  - {Boolean} helpers
     *  - {Boolean} watchOnly
     * @param {Function} fn(err)
     */
    parse (buildOptions, fn) {
      super.parse(buildOptions, (err) => {
        if (err) return fn(err);

        // Find sidecar json file
        const sidecarData = super.parseSidecarDependency();
        // Parse includes
        let matches = uniqueMatch(this.content, RE_INCLUDE)
          .map((match) => {
            match.id = match.match;
            match.isInclude = true;
            return match;
          });

        // Parse imports
        matches.push(...uniqueMatch(this.content, RE_IMPORT)
          .map((match) => {
            match.id = match.match;
            match.isImport = true;
            return match;
          }));
        if (sidecarData) matches.push(sidecarData);

        super.addDependencies(matches, buildOptions);
        fn();
      });
    }

    /**
     * Replace relative dependency references with fully resolved
     * @param {Object} buildOptions
     *  - {Boolean} batch
     *  - {Boolean} bootstrap
     *  - {Boolean} boilerplate
     *  - {Boolean} browser
     *  - {Boolean} bundle
     *  - {Boolean} compress
     *  - {Boolean} helpers
     *  - {Array} ignoredFiles
     *  - {Boolean} import
     *  - {Boolean} watchOnly
     * @param {Function} fn(err)
     */
    replaceReferences (buildOptions, fn) {
      [...this.getAllDependencies(), this].forEach((file) => {
        if (file instanceof NUNJUCKSFile && this.dependencyReferences.length) {
          let content = file.content;

          file.dependencyReferences.forEach((reference) => {
            if (reference.file && reference.isImport) {
              const context = reference.context.replace(reference.id, reference.file.filepath);

              // Create new RegExp so that flags work properly
              content = content.replace(new RegExp(regexpEscape(reference.context), 'g'), context);
            }
          });

          file.setContent(content);
        }
      });
      fn();
    }

    /**
     * Inline css/img/js dependency content
     * @param {Object} buildOptions
     *  - {Boolean} batch
     *  - {Boolean} bootstrap
     *  - {Boolean} boilerplate
     *  - {Boolean} browser
     *  - {Boolean} bundle
     *  - {Boolean} compress
     *  - {Boolean} helpers
     *  - {Array} ignoredFiles
     *  - {Boolean} import
     *  - {Boolean} watchOnly
     * @param {Function} fn(err)
     */
    inlineInlineable (buildOptions, fn) {
      // Only dependencies
      parallel([...this.getAllDependencies()].reduce((inlineable, file) => {
        if (file instanceof NUNJUCKSFile && this.dependencyReferences.length) {
          inlineable.push(callable(file, 'inline', buildOptions));
        }
        return inlineable;
      }, []), fn);
    }

    /**
     * Inline included content
     * @param {Object} buildOptions
     *  - {Boolean} batch
     *  - {Boolean} bootstrap
     *  - {Boolean} boilerplate
     *  - {Boolean} browser
     *  - {Boolean} bundle
     *  - {Boolean} compress
     *  - {Boolean} helpers
     *  - {Array} ignoredFiles
     *  - {Boolean} import
     *  - {Boolean} watchOnly
     * @param {Function} fn(err)
     */
    inlineIncludes (buildOptions, fn) {
      [...this.getAllDependencies(), this].forEach((file) => {
        if (file instanceof NUNJUCKSFile && file.dependencyReferences.length) {
          let content = file.content;

          file.dependencyReferences.forEach((reference) => {
            if (reference.file && reference.context && reference.isInclude) {
              content = content.replace(new RegExp(regexpEscape(reference.context), 'g'), reference.file.content);
            }
          });

          file.setContent(content);
        }
      });
      fn();
    }

    /**
     * Compile file contents
     * @param {Object} buildOptions
     *  - {Boolean} batch
     *  - {Boolean} bootstrap
     *  - {Boolean} boilerplate
     *  - {Boolean} browser
     *  - {Boolean} bundle
     *  - {Boolean} compress
     *  - {Array} ignoredFiles
     *  - {Boolean} helpers
     *  - {Boolean} watchOnly
     * @param {Function} fn(err)
     */
    compile (buildOptions, fn) {
      const options = Object.assign({}, DEFAULT_OPTIONS, this.options.pluginOptions.nunjucks);

      nunjucks.configure(null, options);
      nunjucks.renderString(this.content, this.findSidecarDependency(), (err, content) => {
        if (err) {
          if (!this.options.runtimeOptions.watch) return fn(err);
          error(err, 4, false);
        }
        this.setContent(content);
        debug(`compile: ${strong(this.relpath)}`, 4);
        fn();
      });
    }

    /**
     * Reparse file contents for dependency references
     * @param {Object} buildOptions
     *  - {Boolean} batch
     *  - {Boolean} bootstrap
     *  - {Boolean} boilerplate
     *  - {Boolean} browser
     *  - {Boolean} bundle
     *  - {Boolean} compress
     *  - {Array} ignoredFiles
     *  - {Boolean} helpers
     *  - {Boolean} watchOnly
     * @param {Function} fn(err)
     */
    reparse (buildOptions, fn) {
      this.allDependencies = null;
      this.allDependencyReferences = null;
      this.dependencies = [];
      this.dependencyReferences = [];

      super.parse(buildOptions, fn);
    }
  };
}
390434
function (/**Array|Object*/tmpl, /**Object*/data) /**String*/{
            var res= "";
            // there are thre possible declarations array of functions, string and function
            // array case
            if (franky.isArray(tmpl)) {
                res = franky.map(tmpl, function (item) {
                    return typeof item === "string" ?
                        item:
                        item(data);
                }).join("");
            // function case
            } else if (franky.isFunction(tmpl)) {
                res = tmpl(data);
            // default string case
            } else {
                res = tmpl.toString();
            }

            return res;
        }
367476
function(definition, callback) {
      // if no definition is provided, then the user wants see all the indexes
      if (typeof definition === 'function' || typeof definition === 'undefined') {
        callback = definition;
        return nano.request({ path: encodeURIComponent(db) + '/_index' }, callback);
      } else {
        // the user wants to create a new index
        return nano.request({ path: encodeURIComponent(db) + '/_index',
          method: 'post',
          body: definition}, callback);
      }
    }
561239
function js2dtCLI (jsonFile, ramlTypeName) {
  const jsonData = fs.readFileSync(jsonFile).toString()

  if (ramlTypeName != null) {
    const raml = js2dt.js2dt(jsonData, ramlTypeName)
    return `#%RAML 1.0 Library\n${yaml.safeDump({ types: raml }, { 'noRefs': true })}`
  } else {
    const typeName = 'this__should__be__the__only__type'
    const raml = js2dt.js2dt(jsonData, typeName)

    const keys = Object.keys(raml)
    if (keys.length !== 1 || !keys.includes(typeName)) {
      throw new Error(`There is more than one type (${JSON.stringify(keys)}), please specify a name for the raml library`)
    }

    return `#%RAML 1.0 DataType\n${yaml.safeDump(raml[typeName], { 'noRefs': true })}`
  }
}
986067
async function initRepo({
  repository,
  token,
  endpoint,
  forkMode,
  forkToken,
  gitPrivateKey,
  gitFs,
  localDir,
  includeForks,
}) {
  logger.debug(`initRepo("${repository}")`);
  const opts = hostRules.find({ platform: 'github' }, { token, endpoint });
  if (!opts.token) {
    throw new Error(`No token found for GitHub repository ${repository}`);
  }
  hostRules.update({ ...opts, platform: 'github', default: true });
  logger.info('Authenticated as user: ' + (await getRenovateUsername()));
  logger.info('Using renovate version: ' + global.renovateVersion);
  // config is used by the platform api itself, not necessary for the app layer to know
  cleanRepo();
  config.isGhe = endpoint && !endpoint.startsWith('https://api.github.com');
  config.localDir = localDir;
  config.platform = 'github';
  config.repository = repository;
  [config.repositoryOwner, config.repositoryName] = repository.split('/');
  config.gitPrivateKey = gitPrivateKey;
  // platformConfig is passed back to the app layer and contains info about the platform they require
  const platformConfig = {};
  let res;
  try {
    res = await get(`repos/${repository}`);
    logger.trace({ repositoryDetails: res.body }, 'Repository details');
    // istanbul ignore if
    if (res.body.fork && gitFs && !includeForks) {
      try {
        const renovateConfig = JSON.parse(
          Buffer.from(
            (await get(
              `repos/${config.repository}/contents/${defaultConfigFile}`
            )).body.content,
            'base64'
          ).toString()
        );
        if (!renovateConfig.includeForks) {
          throw new Error();
        }
      } catch (err) {
        throw new Error('fork');
      }
    }
    // istanbul ignore if
    if (res.body.full_name && res.body.full_name !== repository) {
      logger.info(
        { repository, this_repository: res.body.full_name },
        'Repository has been renamed'
      );
      throw new Error('renamed');
    }
    if (res.body.archived) {
      logger.info(
        'Repository is archived - throwing error to abort renovation'
      );
      throw new Error('archived');
    }
    platformConfig.privateRepo = res.body.private === true;
    platformConfig.isFork = res.body.fork === true;
    const owner = res.body.owner.login;
    logger.debug(`${repository} owner = ${owner}`);
    // Use default branch as PR target unless later overridden.
    config.defaultBranch = res.body.default_branch;
    // Base branch may be configured but defaultBranch is always fixed
    config.baseBranch = config.defaultBranch;
    logger.debug(`${repository} default branch = ${config.baseBranch}`);
    // GitHub allows administrators to block certain types of merge, so we need to check it
    if (res.body.allow_rebase_merge) {
      config.mergeMethod = 'rebase';
    } else if (res.body.allow_squash_merge) {
      config.mergeMethod = 'squash';
    } else if (res.body.allow_merge_commit) {
      config.mergeMethod = 'merge';
    } else {
      // This happens if we don't have Administrator read access, it is not a critical error
      logger.info('Could not find allowed merge methods for repo');
    }
  } catch (err) /* istanbul ignore next */ {
    logger.debug('Caught initRepo error');
    if (err.message === 'archived' || err.message === 'renamed') {
      throw err;
    }
    if (err.statusCode === 403) {
      throw new Error('forbidden');
    }
    if (err.statusCode === 404) {
      throw new Error('not-found');
    }
    if (err.message.startsWith('Repository access blocked')) {
      throw new Error('blocked');
    }
    if (err.message === 'fork') {
      throw err;
    }
    logger.info({ err }, 'Unknown GitHub initRepo error');
    throw err;
  }
  // This shouldn't be necessary, but occasional strange errors happened until it was added
  config.issueList = null;
  config.prList = null;
  config.openPrList = null;
  config.closedPrList = null;
  config.storage = new Storage();
  await config.storage.initRepo(config);
  if (forkMode) {
    logger.info('Bot is in forkMode');
    config.forkToken = forkToken;
    // Save parent SHA then delete
    const parentSha = await getBaseCommitSHA();
    config.baseCommitSHA = null;
    // save parent name then delete
    config.parentRepo = config.repository;
    config.repository = null;
    // Get list of existing repos
    const existingRepos = (await get('user/repos?per_page=100', {
      token: forkToken || opts.token,
      paginate: true,
    })).body.map(r => r.full_name);
    try {
      config.repository = (await get.post(`repos/${repository}/forks`, {
        token: forkToken || opts.token,
      })).body.full_name;
    } catch (err) /* istanbul ignore next */ {
      logger.info({ err }, 'Error forking repository');
      throw new Error('cannot-fork');
    }
    if (existingRepos.includes(config.repository)) {
      logger.info(
        { repository_fork: config.repository },
        'Found existing fork'
      );
      // Need to update base branch
      logger.debug(
        { baseBranch: config.baseBranch, parentSha },
        'Setting baseBranch ref in fork'
      );
      // This is a lovely "hack" by GitHub that lets us force update our fork's master
      // with the base commit from the parent repository
      try {
        await get.patch(
          `repos/${config.repository}/git/refs/heads/${config.baseBranch}`,
          {
            body: {
              sha: parentSha,
              force: true,
            },
            token: forkToken || opts.token,
          }
        );
      } catch (err) /* istanbul ignore next */ {
        if (
          err.statusCode === 422 &&
          err.message.startsWith('Object does not exist')
        ) {
          throw new Error('repository-changed');
        }
      }
    } else {
      logger.info({ repository_fork: config.repository }, 'Created fork');
      // Wait an arbitrary 30s to hopefully give GitHub enough time for forking to complete
      await delay(30000);
    }
    await config.storage.initRepo(config);
  }

  // istanbul ignore if
  if (gitFs) {
    logger.debug('Enabling Git FS');
    let { host } = URL.parse(opts.endpoint);
    if (host === 'api.github.com') {
      host = null;
    }
    host = host || 'github.com';
    const url = GitStorage.getUrl({
      gitFs,
      auth:
        config.forkToken ||
        (global.appMode ? `x-access-token:${opts.token}` : opts.token),
      hostname: host,
      repository: config.repository,
    });
    config.storage = new GitStorage();
    await config.storage.initRepo({
      ...config,
      url,
    });
  }

  return platformConfig;
}
487563
function define(JSFile, utils) {
  return class JSXFile extends JSFile {
    /**
     * Parse 'content' for dependency references
     * @param {String} content
     * @returns {Array}
     */
    parseDependencyReferences(content) {
      const references = super.parseDependencyReferences(content);

      references[0].push({ context: "require('react')", match: 'react', id: 'react' });

      return references;
    }

    /**
     * Transpile file contents
     * @param {Object} buildOptions
     *  - {Boolean} batch
     *  - {Boolean} bootstrap
     *  - {Boolean} boilerplate
     *  - {Boolean} browser
     *  - {Boolean} bundle
     *  - {Boolean} compress
     *  - {Boolean} helpers
     *  - {Array} ignoredFiles
     *  - {Boolean} import
     *  - {Boolean} watchOnly
     * @param {Function} fn(err)
     */
    transpile(buildOptions, fn) {
      super.transpile(buildOptions, (err) => {
        if (err) return fn && fn();
        this.prependContent("var React = $m['react'].exports;");
        fn();
      });
    }
  };
}
710177
function(type, url, data, options, callback) {
  /* Make a request to the given URL, and call:
   *  callback(http_code, headers, data);
   *
   * Arguments:
   *  - options: hash, with the possible members:
   *    - emulate_browser: Add some firefox headers if set to True
   *    - additional_headers: hash containing some headers to add / redefine.
   */
  var body;
  var purl = URL.parse(url);
  var qs = purl.query || '';
  var secure = purl.protocol == 'https:';
  var default_port = secure && 443 || 80;
  var client = http.createClient(purl.port || default_port, purl.hostname, secure);
  client.addListener('error', function(err) {
    console.log('Error in nodetk web client.');
    console.log(err.message);
    console.log(err.stack);
  });
  var headers = {
    'host': purl.hostname,
  };
  extend(headers, options.additional_headers || {});
  if(options.emulate_browser) extend(headers, {
    'User-Agent': 'Mozilla/5.0 (X11; U; Linux i686; fr; rv:1.9.1.9) Gecko/20100401 Ubuntu/9.10 (karmic) Firefox/3.5.9',
    'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
    'Accept-Language': 'fr-fr,fr;q=0.8,en;q=0.5,en-us;q=0.3',
    //'Accept-Encoding': 'gzip,deflate',
  });
  if(type == 'POST' || type == 'PUT' || type == "DELETE") {
    body = data && querystring.stringify(data) || "";
    headers['content-type'] = 'application/x-www-form-urlencoded';
    headers['content-length'] = Buffer.byteLength(body);
  }
  else if (data) {
    if(qs) qs += '&';
    qs += querystring.stringify(data);
  }
  var request = client.request(type, purl.pathname +'?'+ qs, headers);
  if(body) {
    request.write(body, 'utf8');
  }
  request.end();
  var data = '';
  request.on('response', function(response) {
    response.setEncoding('utf8');
    response.on('data', function(chunk) {
      data += chunk;
    });
    response.on('end', function() {
      callback(response.statusCode, response.headers, data);
    });
  });
}