HttpClient

A HTTP request abstraction layer to be used in node.js / browsers environments.

@class
@memberof CamSDK.client
10952
function(config) {
  config = config || {};

  config.headers = config.headers || {};
  if (!config.headers.Accept) {
    config.headers.Accept = 'application/hal+json, application/json; q=0.5';
  }

  if (!config.baseUrl) {
    throw new Error('HttpClient needs a `baseUrl` configuration property.');
  }

  Events.attach(this);

  this.config = config;
}
339836
@Singleton
    HttpClientHandler<HttpRequest<?>, HttpResponse<?>> httpClientHandler(HttpTracing httpTracing) {
        return HttpClientHandler.create(httpTracing, new HttpClientAdapter<HttpRequest<?>, HttpResponse<?>>() {
            @Override
            public String method(HttpRequest<?> request) {
                return request.getMethod().name();
            }

            @Override
            public String url(HttpRequest<?> request) {
                return request.getUri().toString();
            }

            @Override
            public String requestHeader(HttpRequest<?> request, String name) {
                return request.getHeaders().get(name);
            }

            @Override
            public Integer statusCode(HttpResponse<?> response) {
                return response.getStatus().getCode();
            }

            @Override
            public boolean parseServerIpAndPort(HttpRequest<?> request, Endpoint.Builder builder) {
                InetAddress address = request.getServerAddress().getAddress();
                return builder.parseIp(address);
            }

            @Override
            public String methodFromResponse(HttpResponse<?> httpResponse) {
                return httpResponse.getAttribute(HttpAttributes.METHOD_NAME, String.class)
                                   .orElseGet(() -> super.methodFromResponse(httpResponse));
            }

            @Override
            public String route(HttpResponse<?> response) {
                Optional<String> value = response.getAttribute(HttpAttributes.URI_TEMPLATE, String.class);
                return value.orElseGet(() -> super.route(response));
            }
        });
    }
704959
function HttpViewEngine(context) {
    if (this.constructor === HttpViewEngine.prototype.constructor) {
        throw new AbstractClassError();
    }
    /**
     * @name HttpViewEngine#context
     * @type HttpContext
     * @description Gets or sets an instance of HttpContext that represents the current HTTP context.
     */
    /**
     * @type {HttpContext}
     */
    var ctx = context;
    Object.defineProperty(this,'context', {
        get: function() {
            return ctx;
        },
        set: function(value) {
            ctx = value;
        },
        configurable:false,
        enumerable:false
    });
}
721930
function _request (method, url, options, session) {
    // require options to be object
    options = requireValidOptionalObject(options)
    // set http method
    options.method = method
    // merge arguments into options
    options.uri = url
    // make request
    return request(options, session)
}
1094307
def request(self, method, url, params=None, data=None, headers=None, auth=None,
                timeout=None, allow_redirects=False):
        
        raise TwilioException('HttpClient is an abstract class')
1335074
function getClientHandler(baseUrl) {
    return function(options) {
        return new teleport.Promise(function(resolve, reject) {
            try {
                var httpMethod = (options.method || 'GET').toUpperCase();
                var path = options.path;
                var url = baseUrl + path;
                var data = options.data || {};
                var h = request(httpMethod, url)//
                .set(options.headers || {})//
                .query(options.query || {}) //
                .send(data)//
                .end(function(err, res) {
                    try {
                        if (err)
                            throw err;
                        if (!res || !res.ok)
                            throw new Error('Result is not defined');
                        
                        var json = res.body;
                        if (!json){
                            json = JSON.parse(res.text);
                        }                        
                        var result = {
                            headers : res.headers,
                            data : json
                        }
                        return resolve(result);
                    } catch (err) {
                        return reject(err);
                    }
                });
            } catch (err) {
                return reject(err);
            }
        });
    }
}
971497
function(apiClient) {
    this.apiClient = apiClient || ApiClient.instance;



    /**
     * Add existing contacts to a list
     * @param {Number} listId Id of the list
     * @param {module:model/AddContactToList} contactEmails Emails addresses of the contacts
     * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with an object containing data of type {@link module:model/PostContactInfo} and HTTP response
     */
    this.addContactToListWithHttpInfo = function(listId, contactEmails) {
      var postBody = contactEmails;

      // verify the required parameter 'listId' is set
      if (listId === undefined || listId === null) {
        throw new Error("Missing the required parameter 'listId' when calling addContactToList");
      }

      // verify the required parameter 'contactEmails' is set
      if (contactEmails === undefined || contactEmails === null) {
        throw new Error("Missing the required parameter 'contactEmails' when calling addContactToList");
      }


      var pathParams = {
        'listId': listId
      };
      var queryParams = {
      };
      var collectionQueryParams = {
      };
      var headerParams = {
      };
      var formParams = {
      };

      var authNames = ['api-key', 'partner-key'];
      var contentTypes = ['application/json'];
      var accepts = ['application/json'];
      var returnType = PostContactInfo;

      return this.apiClient.callApi(
        '/contacts/lists/{listId}/contacts/add', 'POST',
        pathParams, queryParams, collectionQueryParams, headerParams, formParams, postBody,
        authNames, contentTypes, accepts, returnType
      );
    }

    /**
     * Add existing contacts to a list
     * @param {Number} listId Id of the list
     * @param {module:model/AddContactToList} contactEmails Emails addresses of the contacts
     * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with data of type {@link module:model/PostContactInfo}
     */
    this.addContactToList = function(listId, contactEmails) {
      return this.addContactToListWithHttpInfo(listId, contactEmails)
        .then(function(response_and_data) {
          return response_and_data.data;
        });
    }


    /**
     * Create a list
     * @param {module:model/CreateList} createList Values to create a list
     * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with an object containing data of type {@link module:model/CreateModel} and HTTP response
     */
    this.createListWithHttpInfo = function(createList) {
      var postBody = createList;

      // verify the required parameter 'createList' is set
      if (createList === undefined || createList === null) {
        throw new Error("Missing the required parameter 'createList' when calling createList");
      }


      var pathParams = {
      };
      var queryParams = {
      };
      var collectionQueryParams = {
      };
      var headerParams = {
      };
      var formParams = {
      };

      var authNames = ['api-key', 'partner-key'];
      var contentTypes = ['application/json'];
      var accepts = ['application/json'];
      var returnType = CreateModel;

      return this.apiClient.callApi(
        '/contacts/lists', 'POST',
        pathParams, queryParams, collectionQueryParams, headerParams, formParams, postBody,
        authNames, contentTypes, accepts, returnType
      );
    }

    /**
     * Create a list
     * @param {module:model/CreateList} createList Values to create a list
     * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with data of type {@link module:model/CreateModel}
     */
    this.createList = function(createList) {
      return this.createListWithHttpInfo(createList)
        .then(function(response_and_data) {
          return response_and_data.data;
        });
    }


    /**
     * Delete a list
     * @param {Number} listId Id of the list
     * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with an object containing HTTP response
     */
    this.deleteListWithHttpInfo = function(listId) {
      var postBody = null;

      // verify the required parameter 'listId' is set
      if (listId === undefined || listId === null) {
        throw new Error("Missing the required parameter 'listId' when calling deleteList");
      }


      var pathParams = {
        'listId': listId
      };
      var queryParams = {
      };
      var collectionQueryParams = {
      };
      var headerParams = {
      };
      var formParams = {
      };

      var authNames = ['api-key', 'partner-key'];
      var contentTypes = ['application/json'];
      var accepts = ['application/json'];
      var returnType = null;

      return this.apiClient.callApi(
        '/contacts/lists/{listId}', 'DELETE',
        pathParams, queryParams, collectionQueryParams, headerParams, formParams, postBody,
        authNames, contentTypes, accepts, returnType
      );
    }

    /**
     * Delete a list
     * @param {Number} listId Id of the list
     * @return {Promise} a {@link https://www.promisejs.org/|Promise}
     */
    this.deleteList = function(listId) {
      return this.deleteListWithHttpInfo(listId)
        .then(function(response_and_data) {
          return response_and_data.data;
        });
    }


    /**
     * Get the contacts in a list
     * @param {Number} listId Id of the list
     * @param {Object} opts Optional parameters
     * @param {Date} opts.modifiedSince Filter (urlencoded) the contacts modified after a given UTC date-time (YYYY-MM-DDTHH:mm:ss.SSSZ). Prefer to pass your timezone in date-time format for accurate result.
     * @param {Number} opts.limit Number of documents per page (default to 50)
     * @param {Number} opts.offset Index of the first document of the page (default to 0)
     * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with an object containing data of type {@link module:model/GetContacts} and HTTP response
     */
    this.getContactsFromListWithHttpInfo = function(listId, opts) {
      opts = opts || {};
      var postBody = null;

      // verify the required parameter 'listId' is set
      if (listId === undefined || listId === null) {
        throw new Error("Missing the required parameter 'listId' when calling getContactsFromList");
      }


      var pathParams = {
        'listId': listId
      };
      var queryParams = {
        'modifiedSince': opts['modifiedSince'],
        'limit': opts['limit'],
        'offset': opts['offset'],
      };
      var collectionQueryParams = {
      };
      var headerParams = {
      };
      var formParams = {
      };

      var authNames = ['api-key', 'partner-key'];
      var contentTypes = ['application/json'];
      var accepts = ['application/json'];
      var returnType = GetContacts;

      return this.apiClient.callApi(
        '/contacts/lists/{listId}/contacts', 'GET',
        pathParams, queryParams, collectionQueryParams, headerParams, formParams, postBody,
        authNames, contentTypes, accepts, returnType
      );
    }

    /**
     * Get the contacts in a list
     * @param {Number} listId Id of the list
     * @param {Object} opts Optional parameters
     * @param {Date} opts.modifiedSince Filter (urlencoded) the contacts modified after a given UTC date-time (YYYY-MM-DDTHH:mm:ss.SSSZ). Prefer to pass your timezone in date-time format for accurate result.
     * @param {Number} opts.limit Number of documents per page (default to 50)
     * @param {Number} opts.offset Index of the first document of the page (default to 0)
     * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with data of type {@link module:model/GetContacts}
     */
    this.getContactsFromList = function(listId, opts) {
      return this.getContactsFromListWithHttpInfo(listId, opts)
        .then(function(response_and_data) {
          return response_and_data.data;
        });
    }


    /**
     * Get the lists in a folder
     * @param {Number} folderId Id of the folder
     * @param {Object} opts Optional parameters
     * @param {Number} opts.limit Number of documents per page (default to 10)
     * @param {Number} opts.offset Index of the first document of the page (default to 0)
     * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with an object containing data of type {@link module:model/GetFolderLists} and HTTP response
     */
    this.getFolderListsWithHttpInfo = function(folderId, opts) {
      opts = opts || {};
      var postBody = null;

      // verify the required parameter 'folderId' is set
      if (folderId === undefined || folderId === null) {
        throw new Error("Missing the required parameter 'folderId' when calling getFolderLists");
      }


      var pathParams = {
        'folderId': folderId
      };
      var queryParams = {
        'limit': opts['limit'],
        'offset': opts['offset'],
      };
      var collectionQueryParams = {
      };
      var headerParams = {
      };
      var formParams = {
      };

      var authNames = ['api-key', 'partner-key'];
      var contentTypes = ['application/json'];
      var accepts = ['application/json'];
      var returnType = GetFolderLists;

      return this.apiClient.callApi(
        '/contacts/folders/{folderId}/lists', 'GET',
        pathParams, queryParams, collectionQueryParams, headerParams, formParams, postBody,
        authNames, contentTypes, accepts, returnType
      );
    }

    /**
     * Get the lists in a folder
     * @param {Number} folderId Id of the folder
     * @param {Object} opts Optional parameters
     * @param {Number} opts.limit Number of documents per page (default to 10)
     * @param {Number} opts.offset Index of the first document of the page (default to 0)
     * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with data of type {@link module:model/GetFolderLists}
     */
    this.getFolderLists = function(folderId, opts) {
      return this.getFolderListsWithHttpInfo(folderId, opts)
        .then(function(response_and_data) {
          return response_and_data.data;
        });
    }


    /**
     * Get the details of a list
     * @param {Number} listId Id of the list
     * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with an object containing data of type {@link module:model/GetExtendedList} and HTTP response
     */
    this.getListWithHttpInfo = function(listId) {
      var postBody = null;

      // verify the required parameter 'listId' is set
      if (listId === undefined || listId === null) {
        throw new Error("Missing the required parameter 'listId' when calling getList");
      }


      var pathParams = {
        'listId': listId
      };
      var queryParams = {
      };
      var collectionQueryParams = {
      };
      var headerParams = {
      };
      var formParams = {
      };

      var authNames = ['api-key', 'partner-key'];
      var contentTypes = ['application/json'];
      var accepts = ['application/json'];
      var returnType = GetExtendedList;

      return this.apiClient.callApi(
        '/contacts/lists/{listId}', 'GET',
        pathParams, queryParams, collectionQueryParams, headerParams, formParams, postBody,
        authNames, contentTypes, accepts, returnType
      );
    }

    /**
     * Get the details of a list
     * @param {Number} listId Id of the list
     * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with data of type {@link module:model/GetExtendedList}
     */
    this.getList = function(listId) {
      return this.getListWithHttpInfo(listId)
        .then(function(response_and_data) {
          return response_and_data.data;
        });
    }


    /**
     * Get all the lists
     * @param {Object} opts Optional parameters
     * @param {Number} opts.limit Number of documents per page (default to 10)
     * @param {Number} opts.offset Index of the first document of the page (default to 0)
     * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with an object containing data of type {@link module:model/GetLists} and HTTP response
     */
    this.getListsWithHttpInfo = function(opts) {
      opts = opts || {};
      var postBody = null;


      var pathParams = {
      };
      var queryParams = {
        'limit': opts['limit'],
        'offset': opts['offset'],
      };
      var collectionQueryParams = {
      };
      var headerParams = {
      };
      var formParams = {
      };

      var authNames = ['api-key', 'partner-key'];
      var contentTypes = ['application/json'];
      var accepts = ['application/json'];
      var returnType = GetLists;

      return this.apiClient.callApi(
        '/contacts/lists', 'GET',
        pathParams, queryParams, collectionQueryParams, headerParams, formParams, postBody,
        authNames, contentTypes, accepts, returnType
      );
    }

    /**
     * Get all the lists
     * @param {Object} opts Optional parameters
     * @param {Number} opts.limit Number of documents per page (default to 10)
     * @param {Number} opts.offset Index of the first document of the page (default to 0)
     * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with data of type {@link module:model/GetLists}
     */
    this.getLists = function(opts) {
      return this.getListsWithHttpInfo(opts)
        .then(function(response_and_data) {
          return response_and_data.data;
        });
    }


    /**
     * Remove existing contacts from a list
     * @param {Number} listId Id of the list
     * @param {module:model/RemoveContactFromList} contactEmails Emails adresses of the contact
     * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with an object containing data of type {@link module:model/PostContactInfo} and HTTP response
     */
    this.removeContactFromListWithHttpInfo = function(listId, contactEmails) {
      var postBody = contactEmails;

      // verify the required parameter 'listId' is set
      if (listId === undefined || listId === null) {
        throw new Error("Missing the required parameter 'listId' when calling removeContactFromList");
      }

      // verify the required parameter 'contactEmails' is set
      if (contactEmails === undefined || contactEmails === null) {
        throw new Error("Missing the required parameter 'contactEmails' when calling removeContactFromList");
      }


      var pathParams = {
        'listId': listId
      };
      var queryParams = {
      };
      var collectionQueryParams = {
      };
      var headerParams = {
      };
      var formParams = {
      };

      var authNames = ['api-key', 'partner-key'];
      var contentTypes = ['application/json'];
      var accepts = ['application/json'];
      var returnType = PostContactInfo;

      return this.apiClient.callApi(
        '/contacts/lists/{listId}/contacts/remove', 'POST',
        pathParams, queryParams, collectionQueryParams, headerParams, formParams, postBody,
        authNames, contentTypes, accepts, returnType
      );
    }

    /**
     * Remove existing contacts from a list
     * @param {Number} listId Id of the list
     * @param {module:model/RemoveContactFromList} contactEmails Emails adresses of the contact
     * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with data of type {@link module:model/PostContactInfo}
     */
    this.removeContactFromList = function(listId, contactEmails) {
      return this.removeContactFromListWithHttpInfo(listId, contactEmails)
        .then(function(response_and_data) {
          return response_and_data.data;
        });
    }


    /**
     * Update a list
     * @param {Number} listId Id of the list
     * @param {module:model/UpdateList} updateList Values to update a list
     * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with an object containing HTTP response
     */
    this.updateListWithHttpInfo = function(listId, updateList) {
      var postBody = updateList;

      // verify the required parameter 'listId' is set
      if (listId === undefined || listId === null) {
        throw new Error("Missing the required parameter 'listId' when calling updateList");
      }

      // verify the required parameter 'updateList' is set
      if (updateList === undefined || updateList === null) {
        throw new Error("Missing the required parameter 'updateList' when calling updateList");
      }


      var pathParams = {
        'listId': listId
      };
      var queryParams = {
      };
      var collectionQueryParams = {
      };
      var headerParams = {
      };
      var formParams = {
      };

      var authNames = ['api-key', 'partner-key'];
      var contentTypes = ['application/json'];
      var accepts = ['application/json'];
      var returnType = null;

      return this.apiClient.callApi(
        '/contacts/lists/{listId}', 'PUT',
        pathParams, queryParams, collectionQueryParams, headerParams, formParams, postBody,
        authNames, contentTypes, accepts, returnType
      );
    }

    /**
     * Update a list
     * @param {Number} listId Id of the list
     * @param {module:model/UpdateList} updateList Values to update a list
     * @return {Promise} a {@link https://www.promisejs.org/|Promise}
     */
    this.updateList = function(listId, updateList) {
      return this.updateListWithHttpInfo(listId, updateList)
        .then(function(response_and_data) {
          return response_and_data.data;
        });
    }
  }
1357758
function Client(server, conn){
  this.server = server;
  this.conn = conn;
  this.encoder = server.encoder;
  this.decoder = new server.parser.Decoder();
  this.id = conn.id;
  this.request = conn.request;
  this.setup();
  this.sockets = {};
  this.nsps = {};
  this.connectBuffer = [];
}
1374696
function(apiClient) {
    this.apiClient = apiClient || ApiClient.instance;



    /**
     * Finds a code
     * Finds a code
     * @param {String} codeId Id of the code
     * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with data of type {@link module:model/Code}
     */
    this.findCode = function(codeId) {
      var postBody = null;

      // verify the required parameter 'codeId' is set
      if (codeId == undefined || codeId == null) {
        throw "Missing the required parameter 'codeId' when calling findCode";
      }


      var pathParams = {
        'codeId': codeId
      };
      var queryParams = {
      };
      var headerParams = {
      };
      var formParams = {
      };

      var authNames = ['basicAuth'];
      var contentTypes = ['application/json;charset=utf-8'];
      var accepts = ['application/json;charset=utf-8'];
      var returnType = Code;

      return this.apiClient.callApi(
        '/codes/{codeId}', 'GET',
        pathParams, queryParams, headerParams, formParams, postBody,
        authNames, contentTypes, accepts, returnType
      );
    }


    /**
     * Lists codes
     * Lists codes
     * @param {Object} opts Optional parameters
     * @param {Array.<String>} opts.types Filter results by types
     * @param {String} opts.search Search codes by free-text query
     * @param {String} opts.sortBy define order (NATURAL or SCORE). Default is SCORE
     * @param {String} opts.sortDir ASC or DESC. Default is ASC
     * @param {Integer} opts.firstResult First result
     * @param {Integer} opts.maxResults Max results
     * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with data of type {@link Array.<module:model/Code>}
     */
    this.listCodes = function(opts) {
      opts = opts || {};
      var postBody = null;


      var pathParams = {
      };
      var queryParams = {
        'types': this.apiClient.buildCollectionParam(opts['types'], 'csv'),
        'search': opts['search'],
        'sortBy': opts['sortBy'],
        'sortDir': opts['sortDir'],
        'firstResult': opts['firstResult'],
        'maxResults': opts['maxResults']
      };
      var headerParams = {
      };
      var formParams = {
      };

      var authNames = ['basicAuth'];
      var contentTypes = ['application/json;charset=utf-8'];
      var accepts = ['application/json;charset=utf-8'];
      var returnType = [Code];

      return this.apiClient.callApi(
        '/codes', 'GET',
        pathParams, queryParams, headerParams, formParams, postBody,
        authNames, contentTypes, accepts, returnType
      );
    }
  }
759664
function HttpBackend() {
    this.requests = [];
    this.expectedRequests = [];
    const self = this;

    // All the promises our flush requests have returned. When all these promises are
    // resolved or rejected, there are no more flushes in progress.
    // For simplicity we never remove promises from this loop: this is a mock utility
    // for short duration tests, so this keeps it simpler.
    this._flushPromises = [];

    // the request function dependency that the SDK needs.
    this.requestFn = function(opts, callback) {
        const req = new Request(opts, callback);
        console.log(`${Date.now()} HTTP backend received request: ${req}`);
        self.requests.push(req);

        const abort = function() {
            const idx = self.requests.indexOf(req);
            if (idx >= 0) {
                console.log("Aborting HTTP request: %s %s", opts.method,
                            opts.uri);
                self.requests.splice(idx, 1);
                req.callback("aborted");
            }
        };

        return {
            abort: abort,
        };
    };

    // very simplistic mapping from the whatwg fetch interface onto the request
    // interface, so we can use the same mock backend for both.
    this.fetchFn = function(input, init) {
        init = init || {};
        const requestOpts = {
            uri: input,
            method: init.method || 'GET',
            body: init.body,
        };

        return new Promise((resolve, reject) => {
            function callback(err, response, body) {
                if (err) {
                    reject(err);
                }
                resolve({
                    ok: response.statusCode >= 200 && response.statusCode < 300,
                    json: () => JSON.parse(body),
                });
            };

            const req = new Request(requestOpts, callback);
            console.log(`HTTP backend received request: ${req}`);
            self.requests.push(req);
        });
    };
}
804872
function Client(app) {
  if (!(this instanceof Client)) return new Client(app);
  this._base = '';
  this._url = '';
  this.serialize = serializers.raw;
  this.parse = parsers.raw;
  this.middlewares = [];
  this.expectations = [];
  this.options = {
    followRedirect: false,
    method: 'GET',
    headers: {}
  };

  if (app) this.app(app);
}
249233
function WebCamController() {
    var flow = new oflow.WebCamFlow(),
        readyCallback,
        waitReady = true;

    return {
        mount: function (handle) {
            flow.onCalculated(function (direction) {
                if (waitReady) {
                    readyCallback();
                    waitReady = false;
                }
                handle.move(-direction.v * 10);
            });
            flow.startCapture();
        },
        dismount: function () {
            flow.stopCapture();
        },
        onReady: function (callback) {
            readyCallback = callback;
        },
        step: function () {
        }
    };
}
748255
public static RequestResponse callHttpPost(HttpJsonRpcClient client, String url,
            Map<String, Object> headers, Map<String, Object> urlParams, Object requestData) {
        return client.doPost(url, headers, urlParams, requestData);
    }
714820
public static Client http(ClientSettings clientSettings) {
    HttpClientCodec clientCodec =
        new HttpClientCodec(DataCodec.getInstance(clientSettings.contentType()));

    ClientTransport clientTransport =
        new HttpClientTransport(clientSettings, clientCodec, clientSettings.loopResources());

    return new Client(clientTransport, clientCodec, clientSettings.errorMapper());
  }
1294153
function Client(client) {
  this._client = client;
  this.query = this.query.bind(this);
  this.end = this.end.bind(this);
}
458857
function request (url) {
  return new Promise((resolve, reject) => {
    const xhr = new XMLHttpRequest()

    xhr.open('GET', url)
    xhr.setRequestHeader('Content-Type', 'application/json')
    xhr.addEventListener('load', _ => {
      try {
        const response = JSON.parse(xhr.response)

        resolve(response)
      } catch (e) {
        reject(e)
      };
    })

    xhr.send(null)
  })
}
832408
function APIRequest(method, url) {
	var data, callback, opts, req, headers = messageHeaders(this);
	callback = ( typeof(arguments[2]) === 'function' ? arguments[2] : (data = arguments[2], arguments[3]) );

	if (isNode) {
		opts = URL.parse(url);
		opts.method = method;
		opts.headers = headers;

		req = requesters[opts.protocol.slice(0, -1)].request(opts, function(res) {
			var chunks = [];
			res.on('data', function(c) { chunks[chunks.length] = c; });
			res.once('end', function() {
				chunks = Buffer.concat(chunks);
				Zlib.gunzip(chunks, function(err, uc) {
					if (!err) uc = uc.toString();
					try { res.body = JSON.parse(uc || chunks); } catch(e) {}
					return callback(null, res);
				});
			});
		});
		if (type(data) === 'object' || method.toLowerCase() === 'get') req.setHeader("Content-Type", "application/json; charset=utf-8");
		if (data instanceof Multipart) req.setHeader("Content-Type", "multipart/form-data; boundary=" + data.boundary);
		if (data) req.write( data.result || JSON.stringify(data), data.result ? 'binary' : 'utf-8' );
		req.end();

		return req.once('error', function(e) { return callback(e.message); });
	}

	req = new XMLHttpRequest();
	req.open(method.toUpperCase(), url, true);
	for (var key in headers) {
		req.setRequestHeader(key, headers[key]);
	}
	req.onreadystatechange = function() {
		if (req.readyState == 4) {
			req.statusCode = req.status;
			req.statusMessage = req.statusText;
			try {req.body = JSON.parse(req.responseText);} catch (e) { return handleErrCB(e, callback); }
			callback(null, req);
		}
	};
	if (type(data) === 'object' || method.toLowerCase() === 'get') req.setRequestHeader("Content-Type", "application/json; charset=utf-8");
	if (data instanceof Multipart) req.setRequestHeader("Content-Type", "multipart/form-data; boundary=" + data.boundary);
	if (data) return req.send( data.result ? data.result : JSON.stringify(data) );
	req.send(null);
}