UNPKG

peri-templating-api

Version:
2,249 lines 67.3 kB
/**
 * PERI Templating API (for Javascript) 0.1.0.
 *
 * Copyright (c) 2014-2021 Platforme International.
 *
 * This source code is licensed under the Apache 2.0 license found in the
 * LICENSE file in the root directory of this source tree.
 */
(function (global, factory) {
  typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
  typeof define === 'function' && define.amd ? define(['exports'], factory) :
  (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.ripeTemplating = {}));
}(this, (function (exports) { 'use strict';

  function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) {
    try {
      var info = gen[key](arg);
      var value = info.value;
    } catch (error) {
      reject(error);
      return;
    }

    if (info.done) {
      resolve(value);
    } else {
      Promise.resolve(value).then(_next, _throw);
    }
  }

  function _asyncToGenerator(fn) {
    return function () {
      var self = this,
          args = arguments;
      return new Promise(function (resolve, reject) {
        var gen = fn.apply(self, args);

        function _next(value) {
          asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value);
        }

        function _throw(err) {
          asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);
        }

        _next(undefined);
      });
    };
  }

  function _classCallCheck(instance, Constructor) {
    if (!(instance instanceof Constructor)) {
      throw new TypeError("Cannot call a class as a function");
    }
  }

  function _defineProperties(target, props) {
    for (var i = 0; i < props.length; i++) {
      var descriptor = props[i];
      descriptor.enumerable = descriptor.enumerable || false;
      descriptor.configurable = true;
      if ("value" in descriptor) descriptor.writable = true;
      Object.defineProperty(target, descriptor.key, descriptor);
    }
  }

  function _createClass(Constructor, protoProps, staticProps) {
    if (protoProps) _defineProperties(Constructor.prototype, protoProps);
    if (staticProps) _defineProperties(Constructor, staticProps);
    return Constructor;
  }

  function _inherits(subClass, superClass) {
    if (typeof superClass !== "function" && superClass !== null) {
      throw new TypeError("Super expression must either be null or a function");
    }

    subClass.prototype = Object.create(superClass && superClass.prototype, {
      constructor: {
        value: subClass,
        writable: true,
        configurable: true
      }
    });
    if (superClass) _setPrototypeOf(subClass, superClass);
  }

  function _getPrototypeOf(o) {
    _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) {
      return o.__proto__ || Object.getPrototypeOf(o);
    };
    return _getPrototypeOf(o);
  }

  function _setPrototypeOf(o, p) {
    _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) {
      o.__proto__ = p;
      return o;
    };

    return _setPrototypeOf(o, p);
  }

  function _isNativeReflectConstruct() {
    if (typeof Reflect === "undefined" || !Reflect.construct) return false;
    if (Reflect.construct.sham) return false;
    if (typeof Proxy === "function") return true;

    try {
      Date.prototype.toString.call(Reflect.construct(Date, [], function () {}));
      return true;
    } catch (e) {
      return false;
    }
  }

  function _assertThisInitialized(self) {
    if (self === void 0) {
      throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
    }

    return self;
  }

  function _possibleConstructorReturn(self, call) {
    if (call && (typeof call === "object" || typeof call === "function")) {
      return call;
    }

    return _assertThisInitialized(self);
  }

  function _createSuper(Derived) {
    var hasNativeReflectConstruct = _isNativeReflectConstruct();

    return function _createSuperInternal() {
      var Super = _getPrototypeOf(Derived),
          result;

      if (hasNativeReflectConstruct) {
        var NewTarget = _getPrototypeOf(this).constructor;

        result = Reflect.construct(Super, arguments, NewTarget);
      } else {
        result = Super.apply(this, arguments);
      }

      return _possibleConstructorReturn(this, result);
    };
  }

  function _superPropBase(object, property) {
    while (!Object.prototype.hasOwnProperty.call(object, property)) {
      object = _getPrototypeOf(object);
      if (object === null) break;
    }

    return object;
  }

  function _get(target, property, receiver) {
    if (typeof Reflect !== "undefined" && Reflect.get) {
      _get = Reflect.get;
    } else {
      _get = function _get(target, property, receiver) {
        var base = _superPropBase(target, property);

        if (!base) return;
        var desc = Object.getOwnPropertyDescriptor(base, property);

        if (desc.get) {
          return desc.get.call(receiver);
        }

        return desc.value;
      };
    }

    return _get(target, property, receiver || target);
  }

  function _slicedToArray(arr, i) {
    return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest();
  }

  function _arrayWithHoles(arr) {
    if (Array.isArray(arr)) return arr;
  }

  function _iterableToArrayLimit(arr, i) {
    if (typeof Symbol === "undefined" || !(Symbol.iterator in Object(arr))) return;
    var _arr = [];
    var _n = true;
    var _d = false;
    var _e = undefined;

    try {
      for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) {
        _arr.push(_s.value);

        if (i && _arr.length === i) break;
      }
    } catch (err) {
      _d = true;
      _e = err;
    } finally {
      try {
        if (!_n && _i["return"] != null) _i["return"]();
      } finally {
        if (_d) throw _e;
      }
    }

    return _arr;
  }

  function _unsupportedIterableToArray(o, minLen) {
    if (!o) return;
    if (typeof o === "string") return _arrayLikeToArray(o, minLen);
    var n = Object.prototype.toString.call(o).slice(8, -1);
    if (n === "Object" && o.constructor) n = o.constructor.name;
    if (n === "Map" || n === "Set") return Array.from(o);
    if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen);
  }

  function _arrayLikeToArray(arr, len) {
    if (len == null || len > arr.length) len = arr.length;

    for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i];

    return arr2;
  }

  function _nonIterableRest() {
    throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
  }

  function _createForOfIteratorHelper(o, allowArrayLike) {
    var it;

    if (typeof Symbol === "undefined" || o[Symbol.iterator] == null) {
      if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") {
        if (it) o = it;
        var i = 0;

        var F = function () {};

        return {
          s: F,
          n: function () {
            if (i >= o.length) return {
              done: true
            };
            return {
              done: false,
              value: o[i++]
            };
          },
          e: function (e) {
            throw e;
          },
          f: F
        };
      }

      throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
    }

    var normalCompletion = true,
        didErr = false,
        err;
    return {
      s: function () {
        it = o[Symbol.iterator]();
      },
      n: function () {
        var step = it.next();
        normalCompletion = step.done;
        return step;
      },
      e: function (e) {
        didErr = true;
        err = e;
      },
      f: function () {
        try {
          if (!normalCompletion && it.return != null) it.return();
        } finally {
          if (didErr) throw err;
        }
      }
    };
  }

  var global$1 = typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {};

  // based off https://github.com/defunctzombie/node-process/blob/master/browser.js

  function defaultSetTimout() {
    throw new Error('setTimeout has not been defined');
  }

  function defaultClearTimeout() {
    throw new Error('clearTimeout has not been defined');
  }

  var cachedSetTimeout = defaultSetTimout;
  var cachedClearTimeout = defaultClearTimeout;

  if (typeof global$1.setTimeout === 'function') {
    cachedSetTimeout = setTimeout;
  }

  if (typeof global$1.clearTimeout === 'function') {
    cachedClearTimeout = clearTimeout;
  }

  function runTimeout(fun) {
    if (cachedSetTimeout === setTimeout) {
      //normal enviroments in sane situations
      return setTimeout(fun, 0);
    } // if setTimeout wasn't available but was latter defined


    if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) {
      cachedSetTimeout = setTimeout;
      return setTimeout(fun, 0);
    }

    try {
      // when when somebody has screwed with setTimeout but no I.E. maddness
      return cachedSetTimeout(fun, 0);
    } catch (e) {
      try {
        // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
        return cachedSetTimeout.call(null, fun, 0);
      } catch (e) {
        // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error
        return cachedSetTimeout.call(this, fun, 0);
      }
    }
  }

  function runClearTimeout(marker) {
    if (cachedClearTimeout === clearTimeout) {
      //normal enviroments in sane situations
      return clearTimeout(marker);
    } // if clearTimeout wasn't available but was latter defined


    if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) {
      cachedClearTimeout = clearTimeout;
      return clearTimeout(marker);
    }

    try {
      // when when somebody has screwed with setTimeout but no I.E. maddness
      return cachedClearTimeout(marker);
    } catch (e) {
      try {
        // When we are in I.E. but the script has been evaled so I.E. doesn't  trust the global object when called normally
        return cachedClearTimeout.call(null, marker);
      } catch (e) {
        // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error.
        // Some versions of I.E. have different rules for clearTimeout vs setTimeout
        return cachedClearTimeout.call(this, marker);
      }
    }
  }

  var queue = [];
  var draining = false;
  var currentQueue;
  var queueIndex = -1;

  function cleanUpNextTick() {
    if (!draining || !currentQueue) {
      return;
    }

    draining = false;

    if (currentQueue.length) {
      queue = currentQueue.concat(queue);
    } else {
      queueIndex = -1;
    }

    if (queue.length) {
      drainQueue();
    }
  }

  function drainQueue() {
    if (draining) {
      return;
    }

    var timeout = runTimeout(cleanUpNextTick);
    draining = true;
    var len = queue.length;

    while (len) {
      currentQueue = queue;
      queue = [];

      while (++queueIndex < len) {
        if (currentQueue) {
          currentQueue[queueIndex].run();
        }
      }

      queueIndex = -1;
      len = queue.length;
    }

    currentQueue = null;
    draining = false;
    runClearTimeout(timeout);
  }

  function nextTick(fun) {
    var args = new Array(arguments.length - 1);

    if (arguments.length > 1) {
      for (var i = 1; i < arguments.length; i++) {
        args[i - 1] = arguments[i];
      }
    }

    queue.push(new Item(fun, args));

    if (queue.length === 1 && !draining) {
      runTimeout(drainQueue);
    }
  } // v8 likes predictible objects


  function Item(fun, array) {
    this.fun = fun;
    this.array = array;
  }

  Item.prototype.run = function () {
    this.fun.apply(null, this.array);
  };

  var title = 'browser';
  var platform = 'browser';
  var browser = true;
  var env = {};
  var argv = [];
  var version = ''; // empty string to avoid regexp issues

  var versions = {};
  var release = {};
  var config = {};

  function noop() {}

  var on = noop;
  var addListener = noop;
  var once = noop;
  var off = noop;
  var removeListener = noop;
  var removeAllListeners = noop;
  var emit = noop;

  function binding(name) {
    throw new Error('process.binding is not supported');
  }

  function cwd() {
    return '/';
  }

  function chdir(dir) {
    throw new Error('process.chdir is not supported');
  }

  function umask() {
    return 0;
  } // from https://github.com/kumavis/browser-process-hrtime/blob/master/index.js


  var performance = global$1.performance || {};

  var performanceNow = performance.now || performance.mozNow || performance.msNow || performance.oNow || performance.webkitNow || function () {
    return new Date().getTime();
  }; // generate timestamp or delta
  // see http://nodejs.org/api/process.html#process_process_hrtime


  function hrtime(previousTimestamp) {
    var clocktime = performanceNow.call(performance) * 1e-3;
    var seconds = Math.floor(clocktime);
    var nanoseconds = Math.floor(clocktime % 1 * 1e9);

    if (previousTimestamp) {
      seconds = seconds - previousTimestamp[0];
      nanoseconds = nanoseconds - previousTimestamp[1];

      if (nanoseconds < 0) {
        seconds--;
        nanoseconds += 1e9;
      }
    }

    return [seconds, nanoseconds];
  }

  var startTime = new Date();

  function uptime() {
    var currentTime = new Date();
    var dif = currentTime - startTime;
    return dif / 1000;
  }

  var browser$1 = {
    nextTick: nextTick,
    title: title,
    browser: browser,
    env: env,
    argv: argv,
    version: version,
    versions: versions,
    on: on,
    addListener: addListener,
    once: once,
    off: off,
    removeListener: removeListener,
    removeAllListeners: removeAllListeners,
    emit: emit,
    binding: binding,
    cwd: cwd,
    chdir: chdir,
    umask: umask,
    hrtime: hrtime,
    platform: platform,
    release: release,
    config: config,
    uptime: uptime
  };

  const promises = {};

  // Copyright Joyent, Inc. and other Node contributors.
  //
  // Permission is hereby granted, free of charge, to any person obtaining a
  // copy of this software and associated documentation files (the
  // "Software"), to deal in the Software without restriction, including
  // without limitation the rights to use, copy, modify, merge, publish,
  // distribute, sublicense, and/or sell copies of the Software, and to permit
  // persons to whom the Software is furnished to do so, subject to the
  // following conditions:
  //
  // The above copyright notice and this permission notice shall be included
  // in all copies or substantial portions of the Software.
  //
  // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  // USE OR OTHER DEALINGS IN THE SOFTWARE.
  // resolves . and .. elements in a path array with directory names there
  // must be no slashes, empty elements, or device names (c:\) in the array
  // (so also no leading and trailing slashes - it does not distinguish
  // relative and absolute paths)
  function normalizeArray(parts, allowAboveRoot) {
    // if the path tries to go above the root, `up` ends up > 0
    var up = 0;

    for (var i = parts.length - 1; i >= 0; i--) {
      var last = parts[i];

      if (last === '.') {
        parts.splice(i, 1);
      } else if (last === '..') {
        parts.splice(i, 1);
        up++;
      } else if (up) {
        parts.splice(i, 1);
        up--;
      }
    } // if the path is allowed to go above the root, restore leading ..s


    if (allowAboveRoot) {
      for (; up--; up) {
        parts.unshift('..');
      }
    }

    return parts;
  } // Split a filename into [root, dir, basename, ext], unix version
  // 'root' is just a slash, or nothing.


  var splitPathRe = /^(\/?|)([\s\S]*?)((?:\.{1,2}|[^\/]+?|)(\.[^.\/]*|))(?:[\/]*)$/;

  var splitPath = function splitPath(filename) {
    return splitPathRe.exec(filename).slice(1);
  }; // path.resolve([from ...], to)
  // posix version


  function resolve() {
    var resolvedPath = '',
        resolvedAbsolute = false;

    for (var i = arguments.length - 1; i >= -1 && !resolvedAbsolute; i--) {
      var path = i >= 0 ? arguments[i] : '/'; // Skip empty and invalid entries

      if (typeof path !== 'string') {
        throw new TypeError('Arguments to path.resolve must be strings');
      } else if (!path) {
        continue;
      }

      resolvedPath = path + '/' + resolvedPath;
      resolvedAbsolute = path.charAt(0) === '/';
    } // At this point the path should be resolved to a full absolute path, but
    // handle relative paths to be safe (might happen when process.cwd() fails)
    // Normalize the path


    resolvedPath = normalizeArray(filter(resolvedPath.split('/'), function (p) {
      return !!p;
    }), !resolvedAbsolute).join('/');
    return (resolvedAbsolute ? '/' : '') + resolvedPath || '.';
  }
  // posix version

  function normalize(path) {
    var isPathAbsolute = isAbsolute(path),
        trailingSlash = substr(path, -1) === '/'; // Normalize the path

    path = normalizeArray(filter(path.split('/'), function (p) {
      return !!p;
    }), !isPathAbsolute).join('/');

    if (!path && !isPathAbsolute) {
      path = '.';
    }

    if (path && trailingSlash) {
      path += '/';
    }

    return (isPathAbsolute ? '/' : '') + path;
  }

  function isAbsolute(path) {
    return path.charAt(0) === '/';
  } // posix version

  function join() {
    var paths = Array.prototype.slice.call(arguments, 0);
    return normalize(filter(paths, function (p, index) {
      if (typeof p !== 'string') {
        throw new TypeError('Arguments to path.join must be strings');
      }

      return p;
    }).join('/'));
  } // path.relative(from, to)
  function dirname(path) {
    var result = splitPath(path),
        root = result[0],
        dir = result[1];

    if (!root && !dir) {
      // No dirname whatsoever
      return '.';
    }

    if (dir) {
      // It has a dirname, strip trailing slash
      dir = dir.substr(0, dir.length - 1);
    }

    return root + dir;
  }

  function filter(xs, f) {
    if (xs.filter) return xs.filter(f);
    var res = [];

    for (var i = 0; i < xs.length; i++) {
      if (f(xs[i], i, xs)) res.push(xs[i]);
    }

    return res;
  } // String.prototype.substr - negative index don't work in IE8


  var substr = 'ab'.substr(-1) === 'b' ? function (str, start, len) {
    return str.substr(start, len);
  } : function (str, start, len) {
    if (start < 0) start = str.length + start;
    return str.substr(start, len);
  };

  var fetch$1 = fetch;

  var Observable = /*#__PURE__*/function () {
    function Observable() {
      _classCallCheck(this, Observable);

      this.callbacks = {};
    }

    _createClass(Observable, [{
      key: "bind",
      value: function bind(event, callback) {
        var callbacks = this.callbacks[event] || [];
        callbacks.push(callback);
        this.callbacks[event] = callbacks;
        return callback;
      }
    }, {
      key: "unbind",
      value: function unbind(event, callback) {
        var callbacks = this.callbacks[event] || [];

        if (!callback) {
          delete this.callbacks[event];
          return;
        }

        var index = callbacks.indexOf(callback);

        if (index === -1) {
          return;
        }

        callbacks.splice(index, 1);
        this.callbacks[event] = callbacks;
      }
    }, {
      key: "trigger",
      value: function trigger(event) {
        var callbacks = this.callbacks[event] || [];
        var results = [];

        var _iterator = _createForOfIteratorHelper(callbacks),
            _step;

        try {
          for (_iterator.s(); !(_step = _iterator.n()).done;) {
            var callback = _step.value;
            var result = callback.apply(this, Array.prototype.slice.call(arguments, 1));
            result !== undefined && result !== null && results.push(result);
          }
        } catch (err) {
          _iterator.e(err);
        } finally {
          _iterator.f();
        }

        return Promise.all(results);
      }
    }]);

    return Observable;
  }();

  var _verify = function verify(condition) {
    var message = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null;
    var code = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : null;
    var exception = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : null;
    var kwargs = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : {};
    if (condition) return;
    message = message || "Verification failed";
    var Exception = exception || Error;
    kwargs = Object.assign({}, kwargs);
    if (message !== null && message !== undefined) kwargs.message = message;
    if (code !== null && message !== undefined) kwargs.code = code;
    var throwable = new Exception(kwargs.message || undefined);
    throwable.kwargs = kwargs;

    for (var _i = 0, _Object$entries = Object.entries(kwargs); _i < _Object$entries.length; _i++) {
      var _Object$entries$_i = _slicedToArray(_Object$entries[_i], 2),
          key = _Object$entries$_i[0],
          value = _Object$entries$_i[1];

      if (throwable[key] !== undefined) continue;
      throwable[key] = value;
    }

    throw throwable;
  };

  var HOME_DIR = null;

  var pathExists = /*#__PURE__*/function () {
    var _ref = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee(path) {
      return regeneratorRuntime.wrap(function _callee$(_context) {
        while (1) {
          switch (_context.prev = _context.next) {
            case 0:
              _context.prev = 0;
              _context.next = 3;
              return promises.access(path);

            case 3:
              _context.next = 8;
              break;

            case 5:
              _context.prev = 5;
              _context.t0 = _context["catch"](0);
              return _context.abrupt("return", false);

            case 8:
              return _context.abrupt("return", true);

            case 9:
            case "end":
              return _context.stop();
          }
        }
      }, _callee, null, [[0, 5]]);
    }));

    return function pathExists(_x) {
      return _ref.apply(this, arguments);
    };
  }();

  var expandUser = function expandUser(path) {
    if (!path) return path;
    if (path === "~") return _homeDir();
    if (path.slice(0, 2) !== "~/") return path;
    return join(HOME_DIR, path.slice(2));
  };

  var getEnv = function getEnv(name) {
    // eslint-disable-next-line no-undef
    if (typeof Deno !== "undefined") return Deno.env.get(name);
    return env[name];
  };

  var getEnvObject = function getEnvObject() {
    // eslint-disable-next-line no-undef
    if (typeof Deno !== "undefined") return Deno.env.toObject();
    return env;
  };

  var _homeDir = function _homeDir() {
    if (HOME_DIR !== null) return HOME_DIR;
    var isWindows = Boolean(typeof browser$1 !== "undefined" && browser$1.platform === "win32");
    HOME_DIR = getEnv(isWindows ? "USERPROFILE" : "HOME") || "/";
    return HOME_DIR;
  };

  var FILE_NAME = "yonius.json";
  var HOME_FILE = "~/.home";
  var IMPORT_NAMES = ["$import", "$include", "$IMPORT", "$INCLUDE"];
  var CASTS = {
    "int": function int(v) {
      return typeof v === "number" ? v : parseInt(v);
    },
    "float": function float(v) {
      return typeof v === "number" ? v : parseFloat(v);
    },
    bool: function bool(v) {
      return typeof v === "boolean" ? v : ["1", "true", "True"].includes(v);
    },
    list: function list(v) {
      return Array.isArray(v) ? v : v.split(";");
    },
    tuple: function tuple(v) {
      return Array.isArray(v) ? v : v.split(";");
    }
  };
  var globals = typeof global$1 === "undefined" ? typeof window === "undefined" ? typeof self === "undefined" ? {} : self : window : global$1;
  globals.CONFIGS = globals.CONFIGS === undefined ? {} : globals.CONFIGS;
  globals.CONFIG_F = globals.CONFIG_F === undefined ? [] : globals.CONFIG_F;
  globals.HOMES = globals.HOMES === undefined ? [] : globals.HOMES;
  globals.LOADED = globals.LOADED === undefined ? false : globals.LOADED;

  var conf = function conf(name) {
    var fallback = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : undefined;
    var cast = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : null;
    var ctx = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : null;
    var configs = ctx ? ctx.configs : globals.CONFIGS;
    cast = _castR(cast);
    var value = configs[name] === undefined ? fallback : configs[name];
    if (cast && value !== undefined && value !== null) value = cast(value);
    return value;
  };

  var load = /*#__PURE__*/function () {
    var _ref3 = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee3() {
      var names,
          path,
          encoding,
          force,
          ctx,
          paths,
          homes,
          _iterator2,
          _step2,
          home,
          _iterator3,
          _step3,
          _path,
          _iterator4,
          _step4,
          _name2,
          _args3 = arguments;

      return regeneratorRuntime.wrap(function _callee3$(_context3) {
        while (1) {
          switch (_context3.prev = _context3.next) {
            case 0:
              names = _args3.length > 0 && _args3[0] !== undefined ? _args3[0] : [FILE_NAME];
              path = _args3.length > 1 && _args3[1] !== undefined ? _args3[1] : null;
              encoding = _args3.length > 2 && _args3[2] !== undefined ? _args3[2] : "utf-8";
              force = _args3.length > 3 && _args3[3] !== undefined ? _args3[3] : false;
              ctx = _args3.length > 4 && _args3[4] !== undefined ? _args3[4] : null;

              if (!(globals.LOADED && !force)) {
                _context3.next = 7;
                break;
              }

              return _context3.abrupt("return");

            case 7:
              paths = [];
              _context3.next = 10;
              return getHomes();

            case 10:
              homes = _context3.sent;
              _iterator2 = _createForOfIteratorHelper(homes);

              try {
                for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) {
                  home = _step2.value;
                  paths = paths.concat([join(home), join(home, ".config")]);
                }
              } catch (err) {
                _iterator2.e(err);
              } finally {
                _iterator2.f();
              }

              paths.push(path);
              _iterator3 = _createForOfIteratorHelper(paths);
              _context3.prev = 15;

              _iterator3.s();

            case 17:
              if ((_step3 = _iterator3.n()).done) {
                _context3.next = 38;
                break;
              }

              _path = _step3.value;
              _iterator4 = _createForOfIteratorHelper(names);
              _context3.prev = 20;

              _iterator4.s();

            case 22:
              if ((_step4 = _iterator4.n()).done) {
                _context3.next = 28;
                break;
              }

              _name2 = _step4.value;
              _context3.next = 26;
              return loadFile(_name2, _path, encoding, ctx);

            case 26:
              _context3.next = 22;
              break;

            case 28:
              _context3.next = 33;
              break;

            case 30:
              _context3.prev = 30;
              _context3.t0 = _context3["catch"](20);

              _iterator4.e(_context3.t0);

            case 33:
              _context3.prev = 33;

              _iterator4.f();

              return _context3.finish(33);

            case 36:
              _context3.next = 17;
              break;

            case 38:
              _context3.next = 43;
              break;

            case 40:
              _context3.prev = 40;
              _context3.t1 = _context3["catch"](15);

              _iterator3.e(_context3.t1);

            case 43:
              _context3.prev = 43;

              _iterator3.f();

              return _context3.finish(43);

            case 46:
              _context3.next = 48;
              return loadEnv(ctx);

            case 48:
              globals.LOADED = true;

            case 49:
            case "end":
              return _context3.stop();
          }
        }
      }, _callee3, null, [[15, 40, 43, 46], [20, 30, 33, 36]]);
    }));

    return function load() {
      return _ref3.apply(this, arguments);
    };
  }();

  var loadFile = /*#__PURE__*/function () {
    var _ref4 = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee4() {
      var name,
          path,
          encoding,
          ctx,
          configs,
          configF,
          key,
          value,
          exists,
          filePath,
          basePath,
          data,
          dataJ,
          _i2,
          _Object$entries2,
          _Object$entries2$_i,
          _args4 = arguments;

      return regeneratorRuntime.wrap(function _callee4$(_context4) {
        while (1) {
          switch (_context4.prev = _context4.next) {
            case 0:
              name = _args4.length > 0 && _args4[0] !== undefined ? _args4[0] : FILE_NAME;
              path = _args4.length > 1 && _args4[1] !== undefined ? _args4[1] : null;
              encoding = _args4.length > 2 && _args4[2] !== undefined ? _args4[2] : "utf-8";
              ctx = _args4.length > 3 && _args4[3] !== undefined ? _args4[3] : null;
              configs = ctx ? ctx.configs : globals.CONFIGS;
              configF = ctx ? ctx.configF : globals.CONFIG_F;
              if (path) path = normalize(path);
              if (path) filePath = join(path, name);else filePath = name;
              filePath = resolve(filePath);
              filePath = normalize(filePath);
              basePath = dirname(filePath);
              _context4.next = 13;
              return pathExists(filePath);

            case 13:
              exists = _context4.sent;

              if (exists) {
                _context4.next = 16;
                break;
              }

              return _context4.abrupt("return");

            case 16:
              exists = configF.includes(filePath);
              if (exists) configF.splice(configF.indexOf(filePath), 1);
              configF.push(filePath);
              _context4.next = 21;
              return promises.readFile(filePath, {
                encoding: encoding
              });

            case 21:
              data = _context4.sent;
              dataJ = JSON.parse(data);
              _context4.next = 25;
              return _loadIncludes(basePath, dataJ, encoding);

            case 25:
              _i2 = 0, _Object$entries2 = Object.entries(dataJ);

            case 26:
              if (!(_i2 < _Object$entries2.length)) {
                _context4.next = 36;
                break;
              }

              _Object$entries2$_i = _slicedToArray(_Object$entries2[_i2], 2);
              key = _Object$entries2$_i[0];
              value = _Object$entries2$_i[1];

              if (_isValid(key)) {
                _context4.next = 32;
                break;
              }

              return _context4.abrupt("continue", 33);

            case 32:
              configs[key] = value;

            case 33:
              _i2++;
              _context4.next = 26;
              break;

            case 36:
            case "end":
              return _context4.stop();
          }
        }
      }, _callee4);
    }));

    return function loadFile() {
      return _ref4.apply(this, arguments);
    };
  }();

  var loadEnv = /*#__PURE__*/function () {
    var _ref5 = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee5() {
      var ctx,
          env,
          configs,
          _args5 = arguments;
      return regeneratorRuntime.wrap(function _callee5$(_context5) {
        while (1) {
          switch (_context5.prev = _context5.next) {
            case 0:
              ctx = _args5.length > 0 && _args5[0] !== undefined ? _args5[0] : null;
              env = getEnvObject();
              configs = ctx ? ctx.configs : globals.CONFIGS;

              if (!(env === undefined || env === null)) {
                _context5.next = 5;
                break;
              }

              return _context5.abrupt("return");

            case 5:
              Object.entries(env).forEach(function (_ref6) {
                var _ref7 = _slicedToArray(_ref6, 2),
                    key = _ref7[0],
                    value = _ref7[1];

                configs[key] = value;
              });

            case 6:
            case "end":
              return _context5.stop();
          }
        }
      }, _callee5);
    }));

    return function loadEnv() {
      return _ref5.apply(this, arguments);
    };
  }();

  var getHomes = /*#__PURE__*/function () {
    var _ref8 = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee6() {
      var filePath,
          fallback,
          encoding,
          forceDefault,
          env,
          exists,
          data,
          paths,
          _iterator5,
          _step5,
          path,
          _args6 = arguments;

      return regeneratorRuntime.wrap(function _callee6$(_context6) {
        while (1) {
          switch (_context6.prev = _context6.next) {
            case 0:
              filePath = _args6.length > 0 && _args6[0] !== undefined ? _args6[0] : HOME_FILE;
              fallback = _args6.length > 1 && _args6[1] !== undefined ? _args6[1] : "~";
              encoding = _args6.length > 2 && _args6[2] !== undefined ? _args6[2] : "utf-8";
              forceDefault = _args6.length > 3 && _args6[3] !== undefined ? _args6[3] : false;

              if (!(globals.HOMES.length > 0)) {
                _context6.next = 6;
                break;
              }

              return _context6.abrupt("return", globals.HOMES);

            case 6:
              env = getEnvObject();
              globals.HOMES = env.HOMES === undefined ? null : env.HOMES;
              globals.HOMES = globals.HOMES ? globals.HOMES.split(";") : globals.HOMES;

              if (!(globals.HOMES !== null)) {
                _context6.next = 11;
                break;
              }

              return _context6.abrupt("return", globals.HOMES);

            case 11:
              fallback = expandUser(fallback);
              fallback = normalize(fallback);
              globals.HOMES = [fallback];
              filePath = expandUser(filePath);
              filePath = normalize(filePath);
              _context6.next = 18;
              return pathExists(filePath);

            case 18:
              exists = _context6.sent;

              if (exists) {
                _context6.next = 21;
                break;
              }

              return _context6.abrupt("return", globals.HOMES);

            case 21:
              if (!forceDefault) globals.HOMES.splice(0, globals.HOMES.length);
              _context6.next = 24;
              return promises.readFile(filePath, {
                encoding: encoding
              });

            case 24:
              data = _context6.sent;
              data = data.trim();
              paths = data.split(/\r?\n/);
              paths = paths.map(function (v) {
                return v.trim();
              });
              _iterator5 = _createForOfIteratorHelper(paths);
              _context6.prev = 29;

              _iterator5.s();

            case 31:
              if ((_step5 = _iterator5.n()).done) {
                _context6.next = 41;
                break;
              }

              path = _step5.value;
              path = path.trim();

              if (path) {
                _context6.next = 36;
                break;
              }

              return _context6.abrupt("continue", 39);

            case 36:
              path = expandUser(path);
              path = normalize(path);
              globals.HOMES.push(path);

            case 39:
              _context6.next = 31;
              break;

            case 41:
              _context6.next = 46;
              break;

            case 43:
              _context6.prev = 43;
              _context6.t0 = _context6["catch"](29);

              _iterator5.e(_context6.t0);

            case 46:
              _context6.prev = 46;

              _iterator5.f();

              return _context6.finish(46);

            case 49:
              return _context6.abrupt("return", globals.HOMES);

            case 50:
            case "end":
              return _context6.stop();
          }
        }
      }, _callee6, null, [[29, 43, 46, 49]]);
    }));

    return function getHomes() {
      return _ref8.apply(this, arguments);
    };
  }();

  var _castR = function _castR(cast) {
    return CASTS[cast] === undefined ? cast : CASTS[cast];
  };

  var _loadIncludes = /*#__PURE__*/function () {
    var _ref9 = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee7(basePath, config) {
      var encoding,
          includes,
          _iterator6,
          _step6,
          alias,
          _iterator7,
          _step7,
          include,
          _args7 = arguments;

      return regeneratorRuntime.wrap(function _callee7$(_context7) {
        while (1) {
          switch (_context7.prev = _context7.next) {
            case 0:
              encoding = _args7.length > 2 && _args7[2] !== undefined ? _args7[2] : "utf-8";
              includes = [];
              _iterator6 = _createForOfIteratorHelper(IMPORT_NAMES);

              try {
                for (_iterator6.s(); !(_step6 = _iterator6.n()).done;) {
                  alias = _step6.value;
                  includes = config[alias] === undefined ? includes : config[alias];
                }
              } catch (err) {
                _iterator6.e(err);
              } finally {
                _iterator6.f();
              }

              if (typeof includes === "string") {
                includes = includes.split(";");
              }

              _iterator7 = _createForOfIteratorHelper(includes);
              _context7.prev = 6;

              _iterator7.s();

            case 8:
              if ((_step7 = _iterator7.n()).done) {
                _context7.next = 14;
                break;
              }

              include = _step7.value;
              _context7.next = 12;
              return loadFile(include, basePath, encoding);

            case 12:
              _context7.next = 8;
              break;

            case 14:
              _context7.next = 19;
              break;

            case 16:
              _context7.prev = 16;
              _context7.t0 = _context7["catch"](6);

              _iterator7.e(_context7.t0);

            case 19:
              _context7.prev = 19;

              _iterator7.f();

              return _context7.finish(19);

            case 22:
            case "end":
              return _context7.stop();
          }
        }
      }, _callee7, null, [[6, 16, 19, 22]]);
    }));

    return function _loadIncludes(_x3, _x4) {
      return _ref9.apply(this, arguments);
    };
  }();

  var _isValid = function _isValid(key) {
    if (IMPORT_NAMES.includes(key)) return false;
    return true;
  };
  /**
   * Encodes the multiple values as and encoded URI component, the
   * values can be wither defined as an array (order is preserved)
   * or as an object (where sequence order is not preserved).
   *
   * The value of each item can be either a primitive type or a sequence
   * in case it's of sequence the values are going to be encoded as
   * multiple parameters separated by the '&' character.
   *
   * @param {(Array|Object[])} values The values to be encoded as an
   * URI component (like GET params).
   * @returns {String} A string with the query encoded values.
   */


  var urlEncode = function urlEncode(values) {
    // constructs the parts array that is going to
    // store the multiple and values
    var parts = []; // in case the provided value is not an array
    // then assumes it's an object and retrieve entries

    if (!Array.isArray(values)) {
      values = Object.entries(values);
    } // iterates over the complete set of pairs available
    // from the key value pairs to be able to encode them
    // properly, notice that the values themselves can be
    // sequences allowing multiple repetition of key


    values.forEach(function (_ref25) {
      var _ref26 = _slicedToArray(_ref25, 2),
          key = _ref26[0],
          value = _ref26[1];

      if (!Array.isArray(value)) {
        value = [value];
      }

      var keyEncoded = encodeURIComponent(key);
      value.forEach(function (_value) {
        if (_value === undefined || _value === null) {
          return;
        }

        var valueEncoded = encodeURIComponent(_value);
        parts.push("".concat(keyEncoded, "=").concat(valueEncoded));
      });
    }); // joins the complete set of parts with the and
    // separator and then returns the final string value

    return parts.join("&");
  };

  var AUTH_ERRORS = [401, 403, 440, 499];

  var API = /*#__PURE__*/function (_Observable) {
    _inherits(API, _Observable);

    var _super6 = _createSuper(API);

    function API() {
      var _this2;

      var kwargs = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};

      _classCallCheck(this, API);

      _this2 = _super6.call(this);
      _this2.kwargs = kwargs;
      return _this2;
    }

    _createClass(API, [{
      key: "build",
      value: function () {
        var _build = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee9(method, url) {
          return regeneratorRuntime.wrap(function _callee9$(_context9) {
            while (1) {
              switch (_context9.prev = _context9.next) {
                case 0:

                case 1:
                case "end":
                  return _context9.stop();
              }
            }
          }, _callee9);
        }));

        function build(_x7, _x8) {
          return _build.apply(this, arguments);
        }

        return build;
      }()
    }, {
      key: "authCallback",
      value: function () {
        var _authCallback = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee10(params, headers) {
          return regeneratorRuntime.wrap(function _callee10$(_context10) {
            while (1) {
              switch (_context10.prev = _context10.next) {
                case 0:
                case "end":
                  return _context10.stop();
              }
            }
          }, _callee10);
        }));

        function authCallback(_x9, _x10) {
          return _authCallback.apply(this, arguments);
        }

        return authCallback;
      }()
    }, {
      key: "get",
      value: function () {
        var _get = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee11(url) {
          var options,
              result,
              _args11 = arguments;
          return regeneratorRuntime.wrap(function _callee11$(_context11) {
            while (1) {
              switch (_context11.prev = _context11.next) {
                case 0:
                  options = _args11.length > 1 && _args11[1] !== undefined ? _args11[1] : {};
                  _context11.next = 3;
                  return this.methodBasic("GET", url, options);

                case 3:
                  result = _context11.sent;
                  return _context11.abrupt("return", result);

                case 5:
                case "end":
                  return _context11.stop();
              }
            }
          }, _callee11, this);
        }));

        function get(_x11) {
          return _get.apply(this, arguments);
        }

        return get;
      }()
    }, {
      key: "post",
      value: function () {
        var _post = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee12(url) {
          var options,
              result,
              _args12 = arguments;
          return regeneratorRuntime.wrap(function _callee12$(_context12) {
            while (1) {
              switch (_context12.prev = _context12.next) {
                case 0:
                  options = _args12.length > 1 && _args12[1] !== undefined ? _args12[1] : {};
                  _context12.next = 3;
                  return this.methodPayload("POST", url, options);

                case 3:
                  result = _context12.sent;
                  return _context12.abrupt("return", result);

                case 5:
                case "end":
                  return _context12.stop();
              }
            }
          }, _callee12, this);
        }));

        function post(_x12) {
          return _post.apply(this, arguments);
        }

        return post;
      }()
    }, {
      key: "put",
      value: function () {
        var _put = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee13(url) {
          var options,
              result,
              _args13 = arguments;
          return regeneratorRuntime.wrap(function _callee13$(_context13) {
            while (1) {
              switch (_context13.prev = _context13.next) {
                case 0:
                  options = _args13.length > 1 && _args13[1] !== undefined ? _args13[1] : {};
                  _context13.next = 3;
                  return this.methodPayload("PUT", url, options);

                case 3:
                  result = _context13.sent;
                  return _context13.abrupt("return", result);

                case 5:
                case "end":
                  return _context13.stop();
              }
            }
          }, _callee13, this);
        }));

        function put(_x13) {
          return _put.apply(this, arguments);
        }

        return put;
      }()
    }, {
      key: "delete",
      value: function () {
        var _delete2 = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee14(url) {
          var options,
              result,
              _args14 = arguments;
          return regeneratorRuntime.wrap(function _callee14$(_context14) {
            while (1) {
              switch (_context14.prev = _context14.next) {
                case 0:
                  options = _args14.length > 1 && _args14[1] !== undefined ? _args14[1] : {};
                  _context14.next = 3;
                  return this.methodBasic("DELETE", url, options);

                case 3:
                  result = _context14.sent;
                  return _context14.abrupt("return", result);

                case 5:
                case "end":
                  return _context14.stop();
              }
            }
          }, _callee14, this);
        }));

        function _delete(_x14) {
          return _delete2.apply(this, arguments);
        }

        return _delete;
      }()
    }, {
      key: "patch",
      value: function () {
        var _patch = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee15(url) {
          var options,
              result,
              _args15 = arguments;
          return regeneratorRuntime.wrap(function _callee15$(_context15) {
            while (1) {
              switch (_context15.prev = _context15.next) {
                case 0:
                  options = _args15.length > 1 && _args15[1] !== undefined ? _args15[1] : {};
                  _context15.next = 3;
                  return this.methodPayload("PATCH", url, options);

                case 3:
                  result = _context15.sent;
                  return _context15.abrupt("return", result);

                case 5:
                case "end":
                  return _context15.stop();
              }
            }
          }, _callee15, this);
        }));

        function patch(_x15) {
          return _patch.apply(this, arguments);
        }

        return patch;
      }()
    }, {
      key: "options",
      value: function () {
        var _options2 = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee16(url) {
          var _options,
              result,
              _args16 = arguments;

          return regeneratorRuntime.wrap(function _callee16$(_context16) {
            while (1) {
              switch (_context16.prev = _context16.next) {
                case 0:
                  _options = _args16.length > 1 && _args16[1] !== undefined ? _args16[1] : {};
                  _context16.next = 3;
                  return this.methodBasic("OPTIONS", url, _options);

                case 3:
                  result = _context16.sent;
                  return _context16.abrupt("return", result);

                case 5:
                case "end":
                  return _context16.stop();
              }
            }
          }, _callee16, this);
        }));

        function options(_x16) {
          return _options2.apply(this, arguments);
        }

        return options;
      }()
    }, {
      key: "methodBasic",
      value: function () {
        var _methodBasic2 = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee17(method, url) {
          var options,
              _args17 = arguments;
          return regeneratorRuntime.wrap(function _callee17$(_context17) {
            while (1) {
              switch (_context17.prev = _context17.next) {
                case 0:
                  options = _args17.length > 2 && _args17[2] !== undefined ? _args17[2] : {};
                  options.params = options.params !== undefined ? options.params : {};
                  options.headers = options.headers !== undefined ? options.headers : {};
                  _context17.prev = 3;
                  _context17.next = 6;
                  return this._methodBasic(method, url, options);

                case 6:
                  return _context17.abrupt("return", _context17.sent);

                case 9:
                  _context17.prev = 9;
                  _context17.t0 = _context17["catch"](3);

                  if (!AUTH_ERRORS.includes(_context17.t0.code)) {
                    _context17.next = 19;
                    break;
                  }

                  _context17.next = 14;
                  return this.authCallback(options.params, options.headers);

                case 14:
                  _context17.next = 16;
                  return this._methodBasic(method, url, options);

                case 16:
                  return _context17.abrupt("return", _context17.sent);

                case 19:
                  throw _context17.t0;

                case 20:
                case "end":
                  return _context17.stop();
              }
            }
          }, _callee17, this, [[3, 9]]);
        }));

        function methodBasic(_x17, _x18) {
          return _methodBasic2.apply(this, arguments);
        }

        return methodBasic;
      }()
    }, {
      key: "methodPayload",
      value: function () {
        var _methodPayload2 = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee18(method, url) {
          var options,
              _args18 = arguments;
          return regeneratorRuntime.wrap(function _callee18$(_context18) {
            while (1) {
              switch (_context18.prev = _context18.next) {
                case 0:
                  options = _args18.length > 2 && _args18[2] !== undefined ? _args18[2] : {};
                  options.params = options.params !== undefined ? options.params : {};
                  options.headers = options.headers !== undefined ? options.headers : {};
                  _context18.prev = 3;
                  _context18.next = 6;
                  return this._methodPayload(method, url, options);

                case 6:
                  return _context18.abrupt("return", _context18.sent);

                case 9:
                  _context18.prev = 9;
                  _context18.t0 = _context18["catch"](3);

                  if (!AUTH_ERRORS.includes(_context18.t0.code)) {
                    _context18.next = 19;
                    break;
                  }

                  _context18.next = 14;
                  return this.authCallback(options.params, options.headers);

                case 14:
                  _context18.next = 16;
                  return this._methodPayload(method, url, options);

                case 16:
                  return _context18.abrupt("return", _context18.sent);

                case 19:
                  throw _context18.t0;

                case 20:
                case "end":
                  return _context18.stop();
              }
            }
          }, _callee18, this, [[3, 9]]);
        }));

        function methodPayload(_x19, _x20) {
          return _methodPayload2.apply(this, arguments);
        }

        return methodPayload;
      }()
    }, {
      key: "_methodBasic",
      value: function () {
        var _methodBasic3 = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee19(method, url) {
          var options,
              params,
              headers,
              kwargs,
              handle,
              query,
              response,
              result,
              _args19 = arguments;
          return regeneratorRuntime.wrap(function _callee19$(_context19) {
            while (1) {
              switch (_context19.prev = _context19.next) {
                case 0:
                  options = _args19.length > 2 && _args19[2] !== undefined ? _args19[2] : {};
                  params = options.params !== undefined ? options.params : {};
                  headers = options.headers !== undefined ? options.headers : {};
                  kwargs = options.kwargs !== undefined ? options.kwargs : {};
                  handle = options.handle !== undefined ? options.handle : true;
                  _context19.next = 7;
                  return this.build(method, url, {
                    params: params,
                    headers: headers,
                    kwargs: kwargs
                  });

                case 7:
                  query = urlEncode(params || {});
                  if (query) url += url.includes("?") ? "&" + query : "?" + query;
                  _context19.next = 11;
                  return fetch$1(url, {
                    method: method,
                    headers: headers || {}
                  });

                case 11:
                  response = _context19.sent;

                  if (!handle) {
                    _context19.next = 18;
                    break;
                  }

                  _context19.next = 15;
                  return this._handleResponse(response);

                case 15:
                  _context19.t0 = _context19.sent;
                  _context19.next = 19;
                  break;

                case 18:
                  _context19.t0 = response;

                case 19:
                  result = _context19.t0;
                  return _context19.abrupt("return", result);

                case 21:
                case "end":
                  return _context19.stop();
              }
            }
          }, _callee19, this);
        }));

        function _methodBasic(_x21, _x22) {
          return _methodBasic3.apply(this, arguments);
        }

        return _methodBasic;
      }()
    }, {
      key: "_methodPayload",
      value: function () {
        var _methodPayload3 = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee20(method, url) {
          var options,
              params,
              headers,
              data,
              dataJ,
              dataM,
              mime,
              kwargs,
              handle,
              query,
              response,
              result,
              _args20 = arguments;
          return regeneratorRuntime.wrap(function _callee20$(_context20) {
            while (1) {
              switch (_context20.prev = _context20.next) {
                case 0:
                  options = _args20.length > 2 && _args20[2] !== undefined ? _args20[2] : {};
                  params = options.params !== undefined ? options.params : {};
                  headers = options.headers !== undefined ? options.headers : {};
                  data = options.data !== undefined ? options.data : null;
                  dataJ = options.dataJ !== undefined ? options.dataJ : null;
                  dataM = options.dataM !== undefined ? options.dataM : null;
                  mime = options.mime !== undefined ? options.mime : null;
                  kwargs = options.kwargs !== undefined ? options.kwargs : {};
                  handle = options.handle !== undefined ? options.handle : true;
                  _context20.next = 11;
                  return this.build(method, url, {
                    params: params,
                    headers: headers,
                    data: data,
                    dataJ: dataJ,
                    dataM: dataM,
                    mime: mime,
                    kwargs: kwargs
                  });

                case 11:
                  query = urlEncode(params || {});

                  if (data !== null) {
                    if (query) url += url.includes("?") ? "&" + query : "?" + query;
                  } else if (dataJ !== null) {
                    data = JSON.stringify(dataJ);
                    if (query) url += url.includes("?") ? "&" + query : "?" + query;
                    mime = mime || "application/json";
                  } else if (dataM !== null) {
                    if (query) url += url.includes("?") ? "&" + query : "?" + query;
                  } else if (query) {
                    data = query;
                    mime = mime || "application/x-www-form-urlencoded";
                  }

                  headers = Object.assign({}, headers);
                  if (mime) headers["Content-Type"] = mime;
                  _context20.next = 17;
                  return fetch$1(url, {
                    method: method,
                    headers: headers || {},
                    body: data
                  });

                case 17:
                  response = _context20.sent;

                  if (!handle) {
                    _context20.next = 24;
                    break;
                  }

                  _context20.next = 21;
                  return this._handleResponse(response);

                case 21:
                  _context20.t0 = _context20.sent;
                  _context20.next = 25;
                  break;

                case 24:
                  _context20.t0 = response;

                case 25:
                  result = _context20.t0;
                  return _context20.abrupt("return", result);

                case 27:
                case "end":
                  return _context20.stop();
              }
            }
          }, _callee20, this);
        }));

        function _methodPayload(_x23, _x24) {
          return _methodPayload3.apply(this, arguments);
        }

        return _methodPayload;
      }()
    }, {
      key: "_handleResponse",
      value: function () {
        var _handleResponse2 = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee21(response) {
          var errorMessage,
              result,
              _args21 = arguments;
          return regeneratorRuntime.wrap(function _callee21$(_context21) {
            while (1) {
              switch (_context21.prev = _context21.next) {
                case 0:
                  errorMessage = _args21.length > 1 && _args21[1] !== undefined ? _args21[1] : "Problem in request";
                  result = null;

                  if (!(response.headers.get("content-type") && response.headers.get("content-type").toLowerCase().startsWith("application/json"))) {
                    _context21.next = 8;
                    break;
                  }

                  _context21.next = 5;
                  return response.json();

                case 5:
                  result = _context21.sent;
                  _context21.next = 17;
                  break;

                case 8:
                  if (!(response.headers.get("content-type") && response.headers.get("content-type").toLowerCase().startsWith("text/"))) {
                    _context21.next = 14;
                    break;
                  }

                  _context21.next = 11;
                  return response.text();

                case 11:
                  result = _context21.sent;
                  _context21.next = 17;
                  break;

                case 14:
                  _context21.next = 16;
                  return response.blob();

                case 16:
                  result = _context21.sent;

                case 17:
                  _verify(response.ok, result.error || errorMessage, response.status || 500);

                  return _context21.abrupt("return", result);

                case 19:
                case "end":
                  return _context21.stop();
              }
            }
          }, _callee21);
        }));

        function _handleResponse(_x25) {
          return _handleResponse2.apply(this, arguments);
        }

        return _handleResponse;
      }()
    }]);

    return API;
  }(Observable);

  var load$1 = /*#__PURE__*/function () {
    var _ref28 = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee24() {
      return regeneratorRuntime.wrap(function _callee24$(_context24) {
        while (1) {
          switch (_context24.prev = _context24.next) {
            case 0:
              _context24.next = 2;
              return load();

            case 2:
            case "end":
              return _context24.stop();
          }
        }
      }, _callee24);
    }));

    return function load$1() {
      return _ref28.apply(this, arguments);
    };
  }();

  var BASE_URL = "http://localhost:3000/";
  var API$1 = /*#__PURE__*/function (_BaseAPI) {
    _inherits(API, _BaseAPI);

    var _super = _createSuper(API);

    function API() {
      var _this;

      var kwargs = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};

      _classCallCheck(this, API);

      _this = _super.call(this, kwargs);
      _this.baseUrl = conf("PERI_TEMPLATING_BASE_URL", BASE_URL);
      _this.token = conf("PERI_TEMPLATING_TOKEN", null);
      _this.baseUrl = kwargs.baseUrl === undefined ? _this.baseUrl : kwargs.baseUrl;
      _this.token = kwargs.token === undefined ? _this.token : kwargs.token;
      return _this;
    }

    _createClass(API, [{
      key: "build",
      value: function () {
        var _build = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee(method, url) {
          var options,
              auth,
              _args = arguments;
          return regeneratorRuntime.wrap(function _callee$(_context) {
            while (1) {
              switch (_context.prev = _context.next) {
                case 0:
                  options = _args.length > 2 && _args[2] !== undefined ? _args[2] : {};
                  _context.next = 3;
                  return _get(_getPrototypeOf(API.prototype), "build", this).call(this, method, url, options);

                case 3:
                  options.headers = options.params !== undefined ? options.headers : {};
                  options.kwargs = options.kwargs !== undefined ? options.kwargs : {};
                  auth = options.kwargs.auth === undefined ? true : options.kwargs.auth;
                  delete options.kwargs.auth;

                  if (auth) {
                    options.headers.Authorization = "Bearer ".concat(this.token);
                  }

                case 8:
                case "end":
                  return _context.stop();
              }
            }
          }, _callee, this);
        }));

        function build(_x, _x2) {
          return _build.apply(this, arguments);
        }

        return build;
      }()
    }, {
      key: "render",
      value: function () {
        var _render = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee2(template, payload) {
          var url;
          return regeneratorRuntime.wrap(function _callee2$(_context2) {
            while (1) {
              switch (_context2.prev = _context2.next) {
                case 0:
                  url = this.baseUrl + template;
                  _context2.next = 3;
                  return this.post(url, {
                    dataJ: payload
                  });

                case 3:
                  return _context2.abrupt("return", _context2.sent);

                case 4:
                case "end":
                  return _context2.stop();
              }
            }
          }, _callee2, this);
        }));

        function render(_x3, _x4) {
          return _render.apply(this, arguments);
        }

        return render;
      }()
    }], [{
      key: "load",
      value: function () {
        var _load2 = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee3() {
          return regeneratorRuntime.wrap(function _callee3$(_context3) {
            while (1) {
              switch (_context3.prev = _context3.next) {
                case 0:
                  _context3.next = 2;
                  return load$1();

                case 2:
                case "end":
                  return _context3.stop();
              }
            }
          }, _callee3);
        }));

        function load() {
          return _load2.apply(this, arguments);
        }

        return load;
      }()
    }]);

    return API;
  }(API);

  exports.API = API$1;

  Object.defineProperty(exports, '__esModule', { value: true });

})));
//# sourceMappingURL=peri-templating-api.umd.js.map