UNPKG

async-http

Version:

Asynchronous HTTP request API

1,029 lines 39.3 kB
var __extends = this.__extends || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } __.prototype = b.prototype; d.prototype = new __(); }; var async_promise_1 = require('async-promise'); var xhr_1 = require('./xhr'); var encoding = require('./encoding'); var MAX_INT32 = -1 >>> 1; var UriParser = /^((?:(https?:)\/\/)(?:[^:@]*(?:\:[^@]*)?@)?(([a-z\d-\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF\.]+)(?:\:(\d+))?)?)?(?![a-z\d-]+\:)((?:^|\/)[^\?\#]*)?(\?[^#]*)?(#.*)?$/i; var UriParts = { "protocol": 2, "hostname": 4, "port": 5, "pathname": 6, "search": 7, "hash": 8 }; var UriPorts = { "http:": 80, "https:": 443 }; var hasOwn = Object.prototype.hasOwnProperty; var GENERAL_KNOWN_HEADERS = /^(Cache-Control|Connection|Date|Pragma|Trailer|Transfer-Encoding|Upgrade|Via|Warning)$/i; var REQUEST_KNOWN_HEADERS = /^(Accept(-(Charset|Encoding|Language))?|Authorization|Expect|From|If-(Match|Modified-Since|None-Match|Range|Unmodified-Since)|Max-Forwards|Proxy-Authorization|Range|Referer|TE|User-Agent)$/i; var RESPONSE_KNOWN_HEADERS = /^(Accept-Ranges|Age|ETag|Location|Proxy-Authenticate|Retry-After|Server|Vary|WWW-Authenticate)$/i; var CONTENT_KNOWN_HEADERS = /^(Allow|Content-(Disposition|Encoding|Language|Length|Location|MD5|Range|Type)|Expires|Last-Modified)$/i; /** * A Uri */ var Uri = (function () { function Uri() { var args = []; for (var _i = 0; _i < arguments.length; _i++) { args[_i - 0] = arguments[_i]; } /** * The protocol for the Uri (e.g. 'http:') * @type {String} */ this.protocol = ""; /** * The hostname for the Uri * @type {String} */ this.hostname = ""; /** * The port number for the Uri * @type {Number} */ this.port = null; /** * The path name for the Uri * @type {String} */ this.pathname = ""; /** * The search portion of the path, also known as the querystring * @type {String} */ this.search = ""; /** * The fragment portion of the path * @type {String} */ this.hash = ""; /** * A value indicating whether the Url is an absolute url * @type {Boolean} */ this.absolute = false; if (args.length === 0) throw new Error("Argument missing"); if (args.length === 1) { var m = UriParser.exec(args[0]); if (!m) throw new URIError(); for (var name_1 in UriParts) { var index = UriParts[name_1]; var part = m[index]; if (index === 5) { this.port = part ? parseInt(part) : UriPorts[this.protocol]; } else if (part) { if (index < 5) part = part.toLowerCase(); this[name_1] = part; } } this.absolute = !!m[1]; } else { var baseUri = args[0] instanceof Uri ? args[0] : Uri.parse(args[0]); var uri = args[0] instanceof Uri ? args[1] : Uri.parse(args[1]); this.hash = uri.hash; if (uri.protocol) { this.protocol = uri.protocol; this.hostname = uri.hostname; this.port = uri.port; this.pathname = uri.pathname; this.search = uri.search; this.absolute = uri.absolute; } else { this.protocol = baseUri.protocol; if (uri.hostname) { this.hostname = uri.hostname; this.port = uri.port; this.pathname = uri.pathname; this.search = uri.search; this.absolute = uri.absolute; } else { this.hostname = baseUri.hostname; this.port = baseUri.port; if (uri.pathname) { if (uri.pathname.charAt(0) === '/') { this.pathname = uri.pathname; } else { if ((baseUri.absolute && !baseUri.pathname) || baseUri.pathname === "/") { this.pathname = '/' + uri.pathname; } else if (baseUri.pathname) { var parts = baseUri.pathname.split('/'); parts[parts.length - 1] = uri.pathname; this.pathname = parts.join('/'); } } this.search = uri.search; } else { this.pathname = baseUri.pathname; if (uri.search) { this.search = uri.search; } else { this.search = baseUri.search; } } } } } Object.freeze(this); } Object.defineProperty(Uri.prototype, "origin", { /** * Gets the origin of the Uri */ get: function () { return this.toString("origin"); }, enumerable: true, configurable: true }); Object.defineProperty(Uri.prototype, "host", { /** * Gets the host for the uri, including the hostname and port */ get: function () { return this.toString("host"); }, enumerable: true, configurable: true }); Object.defineProperty(Uri.prototype, "scheme", { /** * Gets the scheme for the uri (e.g. 'http://'') */ get: function () { return this.toString("scheme"); }, enumerable: true, configurable: true }); /** * Tests whether the provided uri has the same origin as this uri * @param uri The uri to compare against * @returns True if the uri's have the same origin; otherwise, false */ Uri.prototype.isSameOrigin = function (uri) { var other; if (typeof uri === "string") { other = Uri.parse(uri); } else if (uri instanceof Uri) { other = uri; } else { throw new TypeError("Argument not optional."); } if (this.absolute) { return this.origin === other.origin; } return !other.absolute; }; /** * Gets the string representation of the Uri * @param format {String} A format specifier. * @returns {String} The string content of the Uri */ Uri.prototype.toString = function (format) { switch (format) { case "origin": if (this.protocol && this.hostname) { return String(this.protocol) + "//" + this.toString("host"); } return ""; case "authority": case "host": if (this.hostname) { if (this.port !== UriPorts[this.protocol]) { return String(this.hostname) + ":" + this.toString("port"); } return String(this.hostname); } return ""; case "path+search": return String(this.pathname) + String(this.search); case "scheme": return this.toString("protocol") + "//"; case "protocol": return String(this.protocol || ""); case "hostname": return String(this.hostname || ""); case "port": if (this.port) { return String(this.port); } if (this.protocol && UriPorts[this.protocol]) { return String(UriPorts[this.protocol]); } return ""; case "file": if (this.pathname) { var i = this.pathname.lastIndexOf("/") + 1; if (i > 0) { return this.pathname.substr(i); } } return ""; case "dir": if (this.pathname) { var i = this.pathname.lastIndexOf("/") + 1; if (i > 0) { return this.pathname.substr(0, i); } } return ""; case "ext": if (this.pathname) { var i = this.pathname.lastIndexOf("/") + 1; i = this.pathname.lastIndexOf(".", i); if (i > 0) { return this.pathname.substr(i); } } return ""; case "file-ext": if (this.pathname) { var i = this.pathname.lastIndexOf("/") + 1; if (i) { var j = this.pathname.lastIndexOf(".", i); if (j > 0) { return this.pathname.substring(i, j); } return this.pathname.substr(i); } } return ""; case "fragment": case "hash": var hash = String(this.hash || ""); if (hash.length > 0 && hash.charAt(0) != "#") { return "#" + hash; } return hash; case "path": case "pathname": return String(this.pathname || ""); case "search": case "query": var search = String(this.search || ""); if (search.length > 0 && search.charAt(0) != "?") { return "?" + search; } return search; default: return this.toString("origin") + this.toString("pathname") + this.toString("search") + this.toString("hash"); } }; /** * Parses the provided uri string * @param uri {String} The uri string to parse * @returns {Uri} The parsed uri */ Uri.parse = function (uri) { return new Uri(uri); }; /** * Combines two uris * @param baseUri The base uri * @param uri The relative uri * @returns The combined uri */ Uri.combine = function (baseUri, uri) { return new Uri(baseUri, uri); }; Uri.SCHEME_HTTP = "http://"; Uri.SCHEME_HTTPS = "https://"; return Uri; })(); exports.Uri = Uri; var QueryString; (function (QueryString) { var QueryStringParser = /(?:\?|&|^)([^=&]*)(?:=([^&]*))?/g; function fill(qs, name, value, replacer) { if (name != undefined && replacer != undefined) { value = replacer(name, value); } switch (typeof value) { case "function": case "undefined": case "symbol": break; case "object": if (value === null) { qs.push(encodeURIComponent(name) + "="); } else if (Array.isArray(value)) { var ar = value; for (var _i = 0; _i < ar.length; _i++) { var value_1 = ar[_i]; fill(qs, name, value_1, replacer); } } else { for (var _a = 0, _b = Object.getOwnPropertyNames(value); _a < _b.length; _a++) { var key = _b[_a]; var child = value[key]; var childName = name ? name + "." + key : key; fill(qs, childName, child, replacer); } } break; default: qs.push(encodeURIComponent(name) + "=" + encodeURIComponent(String(value))); break; } } function stringify(obj, replacer) { if (!obj) { return ""; } var filterCallback = typeof replacer === "function" ? replacer : Array.isArray(replacer) ? function (key, value) { return replacer.indexOf(key) >= 0 ? value : undefined; } : replacer instanceof RegExp ? function (key, value) { return replacer.test(key) ? value : undefined; } : undefined; var qs = []; fill(qs, undefined, obj, filterCallback); return qs.length ? "?" + qs.join("&") : ""; } QueryString.stringify = stringify; function parse(text) { var obj = {}; var part; while (part = QueryStringParser.exec(text)) { var key = decodeURIComponent(part[1]); if (key.length && key !== "__proto__") { var value = decodeURIComponent(part[2]); if (hasOwn.call(obj, key)) { var previous = obj[key]; if (Array.isArray(previous)) { var ar = previous; ar.push(value); } else { obj[key] = [previous, value]; } } else { obj[key] = value; } } } return obj; } QueryString.parse = parse; })(QueryString = exports.QueryString || (exports.QueryString = {})); /** * An HTTP request for an HttpClient */ var HttpRequest = (function () { /** * Creates an HTTP request for an HttpClient * @param method The HTTP method for the request * @param url The url for the request */ function HttpRequest(method, url) { if (method === void 0) { method = "GET"; } this._headers = {}; this.method = method; if (typeof url === "string") { this.url = Uri.parse(url); } else if (url instanceof Uri) { this.url = url; } } Object.defineProperty(HttpRequest.prototype, "headers", { get: function () { return this._headers; }, enumerable: true, configurable: true }); return HttpRequest; })(); exports.HttpRequest = HttpRequest; /** * A response from an HttpClient */ var HttpResponse = (function () { function HttpResponse(statusCode) { this._headers = {}; this.statusCode = statusCode; } Object.defineProperty(HttpResponse.prototype, "headers", { get: function () { return this._headers; }, enumerable: true, configurable: true }); return HttpResponse; })(); exports.HttpResponse = HttpResponse; /** * A client for HTTP requests */ var HttpClient = (function () { /** * Creates a client for HTTP requests * @param baseUrl The base url for the client */ function HttpClient(baseUrl) { this._headers = {}; this._cts = new async_promise_1.CancellationTokenSource(); this._closed = false; if (baseUrl) { if (typeof baseUrl === "string") { this.baseUrl = Uri.parse(baseUrl); } else if (baseUrl instanceof Uri) { this.baseUrl = baseUrl; } } } Object.defineProperty(HttpClient.prototype, "headers", { get: function () { return this._headers; }, enumerable: true, configurable: true }); /** * Closes the client and cancels all pending requests */ HttpClient.prototype.close = function () { if (this._closed) throw new Error("Object doesn't support this action"); this._closed = true; this._cts.cancel(); this._cts.close(); }; /** * Gets the response text from the requested url * @param url The url for the request * @returns A future result for the string */ HttpClient.prototype.getAsStringAsync = function (url) { return this.getAsync(url).then(function (r) { return r.content.readAsStringAsync(); }); }; /** * Gets the response from the requested url as JSON * @param url The url for the request * @returns A future result for the string */ HttpClient.prototype.getAsJsonAsync = function (url, reviver) { return this.getAsync(url).then(function (r) { return r.content.readAsJsonAsync(reviver); }); }; /** * Gets the response from issuing an HTTP GET to the requested url * @param url The url for the request * @param token A token that can be used to cancel the request * @returns A future result for the response */ HttpClient.prototype.getAsync = function (url, token) { return this.sendAsync(new HttpRequest("GET", url), token); }; /** * Gets the response from issuing an HTTP POST to the requested url * @param url The url for the request * @param body The body of the request * @param token A token that can be used to cancel the request * @returns A future result for the response */ HttpClient.prototype.postAsync = function (url, body, token) { var request = new HttpRequest("POST", url); request.content = body; return this.sendAsync(request, token); }; /** * Gets the response from issuing an HTTP POST of a JSON serialized value to the requested url * @param url The url for the request * @param value The value to serialize * @param jsonReplacer An array or callback used to replace values during serialization * @param token A token that can be used to cancel the request * @returns A future result for the response */ HttpClient.prototype.postJsonAsync = function (url, value, jsonReplacer, token) { var request = new HttpRequest("POST", url); request.content = new JsonContent(value, jsonReplacer); return this.sendAsync(request, token); }; /** * Gets the response from issuing an HTTP PUT to the requested url * @param url The url for the request * @param body The body of the request * @param token A token that can be used to cancel the request * @returns A future result for the response */ HttpClient.prototype.putAsync = function (url, content, token) { var request = new HttpRequest("PUT", url); request.content = content; return this.sendAsync(request, token); }; /** * Gets the response from issuing an HTTP PUT of a JSON serialized value to the requested url * @param url The url for the request * @param value The value to serialize * @param jsonReplacer An array or callback used to replace values during serialization * @param token A token that can be used to cancel the request * @returns A future result for the response */ HttpClient.prototype.putJsonAsync = function (url, value, jsonReplacer, token) { var request = new HttpRequest("PUT", url); request.content = new JsonContent(value, jsonReplacer); return this.sendAsync(request, token); }; /** * Gets the response from issuing an HTTP DELETE to the requested url * @param url The url for the request * @param token A token that can be used to cancel the request * @returns A future result for the response */ HttpClient.prototype.deleteAsync = function (url, token) { return this.sendAsync(new HttpRequest("DELETE", url), token); }; /** * Sends the provided request and returns the response * @param request {HttpRequest} An HTTP request to send * @param token {futures.CancellationToken} A token that can be used to cancel the request * @returns {futures.Promise<HttpResponse>} A future result for the response */ HttpClient.prototype.sendAsync = function (request, token) { var _this = this; if (this._closed) throw new Error("Object doesn't support this action"); return new async_promise_1.Promise(function (resolve, reject) { // create a linked token var cts = new async_promise_1.CancellationTokenSource([_this._cts.token, token]); // throw if we're already canceled, the promise will be rejected cts.token.throwIfCanceled(); // normalize the uri var url = null; if (!request.url) { url = _this.baseUrl; } else if (!request.url.absolute) { if (!_this.baseUrl) throw new Error("Invalid argument: request"); url = new Uri(_this.baseUrl, request.url); } if (url) { request.url = url; } var xhr = new xhr_1.XMLHttpRequest(); var response = new HttpResponse(); response.request = request; function updateResponse() { response.statusCode = xhr.status; response.statusText = xhr.statusText; response.content = new ResponseContent(xhr); var headers = xhr.getAllResponseHeaders(); var headerLines = headers.split(/\r\n|\r|\n/); for (var _i = 0; _i < headerLines.length; _i++) { var headerLine = headerLines[_i]; var index = headerLine.indexOf(":"); if (index > -1) { var name_2 = headerLine.substr(0, index); var value = headerLine.substr(index + 1); if (!CONTENT_KNOWN_HEADERS.test(name_2)) { response.headers[name_2] = value; } else { response.content.headers[name_2] = value; } } } } // create the onload callback var onload = function (ev) { cleanup(); if (cts.token.canceled) { reject(cts.token.reason); return; } updateResponse(); if (xhr.status >= 200 && xhr.status < 300) { resolve(response); } else { reject(createHttpError(_this, response)); } }; // create the onerror callback var onerror = function (ev) { cleanup(); if (cts.token.canceled) { reject(cts.token.reason); return; } updateResponse(); reject(createHttpError(_this, response)); }; // register a cleanup phase var registration = cts.token.register(function () { cleanup(); // abort the xhr xhr.abort(); }); var cleanup = function () { xhr.removeEventListener("load", onload, false); xhr.removeEventListener("error", onerror, false); registration.unregister(); onload = undefined; onerror = undefined; registration = undefined; }; // send the request xhr.responseType = "arraybuffer"; xhr.open(request.method, request.url.toString(), true, _this.username, _this.password); // add the headers from the client for (var _i = 0, _a = Object.getOwnPropertyNames(_this.headers); _i < _a.length; _i++) { var key = _a[_i]; xhr.setRequestHeader(key, String(_this.headers[key])); } // add the headers from the request for (var _b = 0, _c = Object.getOwnPropertyNames(request.headers); _b < _c.length; _b++) { var key = _c[_b]; xhr.setRequestHeader(key, String(request.headers[key])); } if (request.content) { for (var _d = 0, _e = Object.getOwnPropertyNames(request.content.headers); _d < _e.length; _d++) { var key = _e[_d]; xhr.setRequestHeader(key, String(request.content.headers[key])); } } // wire up the events xhr.addEventListener("load", onload, false); xhr.addEventListener("error", onerror, false); // enable credentials if requested if (_this.withCredentials) { xhr.withCredentials = true; } // attach a timeout if (_this.timeout > 0) { setTimeout(function () { return cts.cancel(new Error("Operation timed out.")); }, _this.timeout); xhr.timeout = _this.timeout; } if (request.content) { if (request.content.type === "arraybuffer") { request.content.readAsArrayBufferAsync().then(function (buffer) { xhr.send(new Uint8Array(buffer)); }); } else { request.content.readAsStringAsync().then(function (text) { xhr.send(text); }); } } else { xhr.send(null); } }); }; return HttpClient; })(); exports.HttpClient = HttpClient; var HttpContentWriter = (function () { function HttpContentWriter(limit, capacity) { if (limit === void 0) { limit = MAX_INT32; } if (capacity === void 0) { capacity = 0; } if (limit < 0 || limit > MAX_INT32) throw new TypeError(); if (capacity < 0 || capacity > MAX_INT32) throw new TypeError(); this._limit = limit; this._capacity = capacity; this._byteOffset = 0; this._buffer = new ArrayBuffer(capacity); } Object.defineProperty(HttpContentWriter.prototype, "size", { get: function () { return this._byteOffset; }, enumerable: true, configurable: true }); HttpContentWriter.prototype.write = function (buffer, byteOffset, byteLength) { if (this._buffer == undefined) throw new Error(); this.ensureCapacity(this._byteOffset + byteLength); copyBuffer(buffer, byteOffset, this._buffer, this._byteOffset, byteLength); this._byteOffset += byteLength; }; HttpContentWriter.prototype.toArrayBuffer = function () { if (this._buffer == undefined) throw new Error(); return this._buffer.slice(0); }; HttpContentWriter.prototype.close = function () { this._buffer = undefined; }; HttpContentWriter.prototype.ensureCapacity = function (capacity) { if (capacity < 0) throw new RangeError(); if (capacity > this._limit) throw new RangeError(); if (capacity > this._capacity) { if (capacity < 256) { capacity = 256; } if (capacity < this._capacity * 2) { capacity = this._capacity * 2; } var newBuffer = new ArrayBuffer(capacity); copyBuffer(this._buffer, 0, newBuffer, 0, this._buffer.byteLength); this._buffer = newBuffer; this._capacity = capacity; } }; return HttpContentWriter; })(); exports.HttpContentWriter = HttpContentWriter; var HttpContent = (function () { function HttpContent() { this._headers = {}; this._state = "open"; } Object.defineProperty(HttpContent.prototype, "type", { get: function () { return ""; }, enumerable: true, configurable: true }); Object.defineProperty(HttpContent.prototype, "headers", { get: function () { return this._headers; }, enumerable: true, configurable: true }); HttpContent.prototype.loadAsync = function (maxBufferSize) { var _this = this; if (maxBufferSize === void 0) { maxBufferSize = MAX_INT32; } this.throwIfClosed(); if (maxBufferSize < 0 || maxBufferSize > MAX_INT32) throw new RangeError(); if (this._loadingPromise == undefined) { var writer = this.createWriter(maxBufferSize); this._loadingPromise = async_promise_1.Promise.resolve(this.serialize(writer)).then(function () { _this._content = writer.toArrayBuffer(); writer.close(); }); } return this._loadingPromise; }; HttpContent.prototype.readAsStringAsync = function () { var _this = this; this.throwIfClosed(); return this.loadAsync().then(function () { return encoding.getString(getEncoding(_this.headers), _this._content); }); }; HttpContent.prototype.readAsArrayBufferAsync = function () { var _this = this; this.throwIfClosed(); return this.loadAsync().then(function () { return _this._content.slice(0); }); }; HttpContent.prototype.readAsJsonAsync = function (reviver) { this.throwIfClosed(); return this.readAsStringAsync().then(function (text) { return JSON.parse(text, reviver); }); }; HttpContent.prototype.close = function () { this._state = "closed"; this._content = undefined; }; HttpContent.prototype.serialize = function (writer) { throw new TypeError(); }; HttpContent.prototype.throwIfClosed = function () { if (this._state === "closed") throw new Error(); }; HttpContent.prototype.createWriter = function (maxBufferSize) { var contentLength = findHeader(this._headers, "Content-Length", parseInt) || 0; if (contentLength > maxBufferSize) throw new RangeError(); return new HttpContentWriter(maxBufferSize, contentLength); }; return HttpContent; })(); exports.HttpContent = HttpContent; var ArrayBufferContent = (function (_super) { __extends(ArrayBufferContent, _super); function ArrayBufferContent(buffer) { _super.call(this); this._buffer = buffer; } Object.defineProperty(ArrayBufferContent.prototype, "type", { get: function () { return "arraybuffer"; }, enumerable: true, configurable: true }); ArrayBufferContent.prototype.close = function () { this._buffer = undefined; _super.prototype.close.call(this); }; ArrayBufferContent.prototype.readAsArrayBufferAsync = function () { this.throwIfClosed(); return async_promise_1.Promise.resolve(this._buffer.slice(0)); }; ArrayBufferContent.prototype.serialize = function (writer) { writer.write(this._buffer, 0, this._buffer.byteLength); }; return ArrayBufferContent; })(HttpContent); exports.ArrayBufferContent = ArrayBufferContent; var StringContent = (function (_super) { __extends(StringContent, _super); function StringContent(text, encoding, mediaType) { _super.call(this); this._text = text; if (encoding) { if (mediaType == undefined) mediaType = "text/plain"; mediaType += ";charset=" + encoding; } if (mediaType) { this.headers["Content-Type"] = mediaType; } } Object.defineProperty(StringContent.prototype, "type", { get: function () { return "text"; }, enumerable: true, configurable: true }); StringContent.prototype.readAsStringAsync = function () { this.throwIfClosed(); return async_promise_1.Promise.resolve(this._text); }; StringContent.prototype.close = function () { this._text = undefined; _super.prototype.close.call(this); }; StringContent.prototype.serialize = function (writer) { var charset = getEncoding(this.headers); var byteLength = encoding.getByteLength(charset, this._text); var buffer = new ArrayBuffer(byteLength); encoding.getBytes(charset, this._text, buffer); writer.write(buffer, 0, byteLength); }; return StringContent; })(HttpContent); exports.StringContent = StringContent; var JsonContent = (function (_super) { __extends(JsonContent, _super); function JsonContent(value, replacer, space, mediaType) { _super.call(this); this._value = value; this._replacer = replacer; this._space = space; if (mediaType) { this.headers["Content-Type"] = mediaType; } } Object.defineProperty(JsonContent.prototype, "type", { get: function () { return "json"; }, enumerable: true, configurable: true }); JsonContent.prototype.readAsJsonAsync = function (reviver) { this.throwIfClosed(); return async_promise_1.Promise.resolve(this._value); }; JsonContent.prototype.close = function () { this._value = undefined; this._replacer = undefined; this._space = undefined; _super.prototype.close.call(this); }; JsonContent.prototype.serialize = function (writer) { var text = JSON.stringify(this._value, this._replacer, this._space); var charset = getEncoding(this.headers); var byteLength = encoding.getByteLength(charset, text); var buffer = new ArrayBuffer(byteLength); encoding.getBytes(charset, text, buffer); writer.write(buffer, 0, byteLength); }; return JsonContent; })(HttpContent); exports.JsonContent = JsonContent; var ResponseContent = (function (_super) { __extends(ResponseContent, _super); function ResponseContent(xhr) { _super.call(this); this._xhr = xhr; } Object.defineProperty(ResponseContent.prototype, "type", { get: function () { return this._xhr.responseType; }, enumerable: true, configurable: true }); ResponseContent.prototype.readAsStringAsync = function () { this.throwIfClosed(); return async_promise_1.Promise.resolve(this._xhr.responseText); }; ResponseContent.prototype.readAsArrayBufferAsync = function () { this.throwIfClosed(); if (this._xhr.responseType === "arraybuffer") { return async_promise_1.Promise.resolve(this._xhr.response); } return _super.prototype.readAsArrayBufferAsync.call(this); }; ResponseContent.prototype.readAsJsonAsync = function (reviver) { this.throwIfClosed(); if (this._xhr.responseType === "json") { return async_promise_1.Promise.resolve(this._xhr.response); } return _super.prototype.readAsJsonAsync.call(this); }; ResponseContent.prototype.close = function () { this._xhr = undefined; _super.prototype.close.call(this); }; ResponseContent.prototype.serialize = function (writer) { if (this._xhr.responseType === "arraybuffer") { var buffer = this._xhr.response; writer.write(buffer, 0, buffer.byteLength); } else { var charset = getEncoding(this.headers); var text = this._xhr.responseText; var byteLength = encoding.getByteLength(charset, text); var buffer = new ArrayBuffer(byteLength); encoding.getBytes(charset, text, buffer); writer.write(buffer, 0, byteLength); } }; return ResponseContent; })(HttpContent); function createHttpError(httpClient, response, message) { if (message === void 0) { message = "An error occurred while processing your request"; } var error = new Error(message); error.name = "HttpError"; error.httpClient = httpClient; error.response = response; error.message = message; return error; } function copyBuffer(source, sourceOffset, dest, destOffset, byteLength) { var sourceArray; var destArray; if (byteLength % 8 === 0) { sourceArray = new Float64Array(source, sourceOffset, byteLength); destArray = new Float64Array(dest, destOffset, byteLength); } else if (byteLength % 4 === 0) { sourceArray = new Uint32Array(source, sourceOffset, byteLength); destArray = new Uint32Array(dest, destOffset, byteLength); } else if (byteLength % 2 === 0) { sourceArray = new Uint16Array(source, sourceOffset, byteLength); destArray = new Uint16Array(dest, destOffset, byteLength); } else { sourceArray = new Uint8Array(source, sourceOffset, byteLength); destArray = new Uint8Array(dest, destOffset, byteLength); } var length = sourceArray.length; for (var i = 0; i < length; ++i) { destArray[i] = sourceArray[i]; } } function getEncoding(headers) { var charset = "utf8"; var contentType = findHeader(this.headers, "Content-Type"); if (contentType) { var match = /;charset=(.*)(;|$)/i.exec(contentType); if (match) { charset = match[1]; } } return charset; } function findHeader(headers, name, parse) { if (hasOwn.call(headers, name)) { return (parse ? parse(headers[name]) : headers[name]); } name = name.toLowerCase(); if (hasOwn.call(headers, name)) { return (parse ? parse(headers[name]) : headers[name]); } for (var key in headers) { if (hasOwn.call(headers, key) && key.toLowerCase() === name) { return (parse ? parse(headers[name]) : headers[name]); } } return undefined; } //# sourceMappingURL=httpclient.js.map