New Case Study:See how Anthropic automated 95% of dependency reviews with Socket.Learn More
Socket
Sign inDemoInstall
Socket

httpinvoke

Package Overview
Dependencies
Maintainers
1
Versions
30
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

httpinvoke - npm Package Compare versions

Comparing version 1.3.7 to 1.4.0

test/anonymous.js

2

bower.json
{
"name": "httpinvoke",
"version": "1.3.7",
"version": "1.4.0",
"main": "httpinvoke-browser.js",

@@ -5,0 +5,0 @@ "description": "A no-dependencies HTTP client library for browsers and Node.js with a promise-based or Node.js-style callback-based API to progress events, text and binary file upload and download, partial response body, request and response headers, status code.",

{
"name": "httpinvoke",
"repo": "jakutis/httpinvoke",
"version": "1.3.7",
"version": "1.4.0",
"description": "A no-dependencies HTTP client library for browsers and Node.js with a promise-based or Node.js-style callback-based API to progress events, text and binary file upload and download, partial response body, request and response headers, status code.",

@@ -6,0 +6,0 @@ "keywords": [

@@ -9,2 +9,3 @@ var http = require('http');

var sb = require('surfboard');
var cookie = require('cookie');
var open = sb.openUrl;

@@ -246,2 +247,4 @@

output(200, hello, false, 'text/plain; charset=UTF-8');
} else if(req.url === req.proxyPath + '/credentials') {
output(200, new Buffer('cookies=' + (cookie.parse(req.headers.cookie || '').httpinvokeAnonymousTest === '5' ? 'yes' : 'no')), false, 'text/plain; charset=UTF-8');
} else if(req.url === req.proxyPath + '/immediateEnd') {

@@ -248,0 +251,0 @@ req.socket.destroy();

@@ -19,3 +19,3 @@ var fs = require('fs');

}, {
from: 'var hook, promise, failWithoutRequest, uploadProgressCb, downloadProgressCb, inputLength, inputHeaders, statusCb, outputHeaders, exposedHeaders, status, outputBinary, input, outputLength, outputConverter, partialOutputMode, protocol;',
from: 'var hook, promise, failWithoutRequest, uploadProgressCb, downloadProgressCb, inputLength, inputHeaders, statusCb, outputHeaders, exposedHeaders, status, outputBinary, input, outputLength, outputConverter, partialOutputMode, protocol, anonymous, system;',
to: fs.readFileSync('./src/common/closures.js').toString()

@@ -22,0 +22,0 @@ }]);

@@ -204,7 +204,11 @@ (function (root, factory) {

var urlPartitioningRegExp = /^([\w.+-]+:)(?:\/\/([^\/?#:]*)(?::(\d+)|)|)/;
var urlPartitioningRegExp = /^(?:([a-z][a-z0-9.+-]*:)|)(?:\/\/([^\/?#:]*)(?::(\d+)|)|)/;
var isCrossDomain = function(location, url) {
if(!absoluteURLRegExp.test(url) && url.substr(0, 2) !== '//') {
return false;
}
url = urlPartitioningRegExp.exec(url.toLowerCase());
location = urlPartitioningRegExp.exec(location.toLowerCase()) || [];
return !!(url && (url[1] !== location[1] || url[2] !== location[2] || (url[3] || (url[1] === 'http:' ? '80' : '443')) !== (location[3] || (location[1] === 'http:' ? '80' : '443'))));
var locationPort = location[3] || (location[1] === 'http:' ? '80' : '443');
return !!((url[1] && url[1] !== location[1]) || url[2] !== location[2] || (url[3] || (url[1] ? (url[1] === 'http:' ? '80' : '443') : locationPort)) !== locationPort);
};

@@ -221,3 +225,3 @@

/* jshint -W020 */
var hook, promise, failWithoutRequest, uploadProgressCb, downloadProgressCb, inputLength, inputHeaders, statusCb, outputHeaders, exposedHeaders, status, outputBinary, input, outputLength, outputConverter, protocol;
var hook, promise, failWithoutRequest, uploadProgressCb, downloadProgressCb, inputLength, inputHeaders, statusCb, outputHeaders, exposedHeaders, status, outputBinary, input, outputLength, outputConverter, protocol, anonymous, system;
hook = function(type, args) {

@@ -368,3 +372,11 @@ var hooks = httpinvoke._hooks[type];

var inputConverter;
inputHeaders = options.headers || {};
inputHeaders = (function(input) {
var output = {};
for(var i in input) {
if(input.hasOwnProperty(i)) {
output[i] = input[i];
}
}
return output;
})(options.headers || {});
outputHeaders = {};

@@ -374,2 +386,25 @@ exposedHeaders = options.corsExposedHeaders || [];

/*************** COMMON convert and validate parameters **************/
var validateInputHeaders = function(headers) {
var noSec = httpinvoke.forbiddenInputHeaders.indexOf('sec-*') >= 0;
var noProxy = httpinvoke.forbiddenInputHeaders.indexOf('proxy-*') >= 0;
for(var header in headers) {
if(headers.hasOwnProperty(header)) {
var headerl = header.toLowerCase();
if(httpinvoke.forbiddenInputHeaders.indexOf(headerl) >= 0) {
throw [14, header];
}
if(noProxy && headerl.substr(0, 'proxy-'.length) === 'proxy-') {
throw [15, header];
}
if(noSec && headerl.substr(0, 'sec-'.length) === 'sec-') {
throw [16, header];
}
}
}
};
try {
validateInputHeaders(inputHeaders);
} catch(err) {
return failWithoutRequest(cb, err);
}
if(!httpinvoke.relativeURLs && !absoluteURLRegExp.test(url)) {

@@ -382,2 +417,7 @@ return failWithoutRequest(cb, [26, url]);

}
anonymous = typeof options.anonymous === 'undefined' ? httpinvoke.anonymousByDefault : options.anonymous;
system = typeof options.system === 'undefined' ? httpinvoke.systemByDefault : options.system;
if(typeof options.system !== 'undefined' && system) {
anonymous = true;
}
var partialOutputMode = options.partialOutputMode || 'disabled';

@@ -553,3 +593,6 @@ if(partialOutputMode.indexOf(',') >= 0 || ',disabled,chunked,joined,'.indexOf(',' + partialOutputMode + ',') < 0) {

}
xhr = createXHR(crossDomain);
xhr = createXHR(crossDomain, {
mozAnon: anonymous,
mozSystem: system
});
try {

@@ -560,4 +603,6 @@ xhr.open(method, url, true);

}
if(options.corsCredentials && httpinvoke.corsCredentials && typeof xhr.withCredentials === 'boolean') {
xhr.withCredentials = true;
if(httpinvoke.corsCredentials) {
if((typeof options.anonymous !== 'undefined' && !anonymous) || (options.corsCredentials && typeof xhr.withCredentials === 'boolean')) {
xhr.withCredentials = true;
}
}

@@ -1137,4 +1182,4 @@ if(crossDomain && options.corsOriginHeader) {

try {
createXHR = function() {
return new XMLHttpRequest();
createXHR = function(cors, xhrOptions) {
return new XMLHttpRequest(xhrOptions);
};

@@ -1158,9 +1203,9 @@ var tmpxhr = createXHR();

if(global.XDomainRequest === _undefined) {
createXHR = function() {
return new XMLHttpRequest();
createXHR = function(cors, xhrOptions) {
return new XMLHttpRequest(xhrOptions);
};
createXHR();
} else {
createXHR = function(cors) {
return cors ? new XDomainRequest() : new XMLHttpRequest();
createXHR = function(cors, xhrOptions) {
return cors ? new XDomainRequest() : new XMLHttpRequest(xhrOptions);
};

@@ -1206,2 +1251,26 @@ createXHR(true);

httpinvoke.hook = addHook;
httpinvoke.anonymousOption = (function() {
try {
return createXHR(true, {mozAnon: true}).mozAnon === true &&
createXHR(true, {mozAnon: false}).mozAnon === false &&
createXHR(false, {mozAnon: true}).mozAnon === true &&
createXHR(false, {mozAnon: false}).mozAnon === false;
} catch(_) {
return false;
}
})();
httpinvoke.anonymousByDefault = false;
httpinvoke.systemOption = (function() {
try {
return createXHR(true, {mozAnon: true, mozSystem: true}).mozSystem === true &&
createXHR(true, {mozAnon: true, mozSystem: false}).mozSystem === false &&
createXHR(false, {mozAnon: true, mozSystem: true}).mozSystem === true &&
createXHR(false, {mozAnon: true, mozSystem: false}).mozSystem === false;
} catch(_) {
return false;
}
})();
httpinvoke.systemByDefault = false;
// http://www.w3.org/TR/XMLHttpRequest/#the-setrequestheader()-method
httpinvoke.forbiddenInputHeaders = ['proxy-*', 'sec-*', 'accept-charset', 'accept-encoding', 'access-control-request-headers', 'access-control-request-method', 'connection', 'content-length', 'content-transfer-encoding', 'cookie', 'cookie2', 'date', 'dnt', 'expect', 'host', 'keep-alive', 'origin', 'referer', 'te', 'trailer', 'transfer-encoding', 'upgrade', 'user-agent', 'via'];

@@ -1208,0 +1277,0 @@ return httpinvoke;

@@ -1,1 +0,1 @@

(function(root,factory){if(typeof define==="function"&&define.amd){define(factory)}else if(typeof exports==="object"){module.exports=factory()}else{root.httpinvoke=factory()}})(this,function(){"use strict";var global;global=window;var resolve=0,reject=1,progress=2,chain=function(a,b){if(a&&a.then){a.then(function(){b[resolve].apply(null,arguments)},function(){b[reject].apply(null,arguments)},function(){b[progress].apply(null,arguments)})}else{b[resolve](a)}},nextTick=global.process&&global.process.nextTick||global.setImmediate||global.setTimeout,mixInPromise=function(o){var value,queue=[],state=progress;var makeState=function(newstate){o[newstate]=function(){var i,p;if(queue){value=[].slice.call(arguments);state=newstate;for(i=0;i<queue.length;i+=1){if(typeof queue[i][state]==="function"){try{p=queue[i][state].apply(null,value);if(state<progress){chain(p,queue[i]._)}}catch(err){queue[i]._[reject](err)}}else if(state<progress){queue[i]._[state].apply(null,value)}}if(state<progress){queue=null}}}};makeState(progress);makeState(resolve);makeState(reject);o.then=function(){var item=[].slice.call(arguments);item._=mixInPromise({});if(queue){queue.push(item)}else if(typeof item[state]==="function"){nextTick(function(){chain(item[state].apply(null,value),item._)})}return item._};return o},isArrayBufferView=function(input){return typeof input==="object"&&input!==null&&(global.ArrayBufferView&&input instanceof ArrayBufferView||global.Int8Array&&input instanceof Int8Array||global.Uint8Array&&input instanceof Uint8Array||global.Uint8ClampedArray&&input instanceof Uint8ClampedArray||global.Int16Array&&input instanceof Int16Array||global.Uint16Array&&input instanceof Uint16Array||global.Int32Array&&input instanceof Int32Array||global.Uint32Array&&input instanceof Uint32Array||global.Float32Array&&input instanceof Float32Array||global.Float64Array&&input instanceof Float64Array)},isArray=function(object){return Object.prototype.toString.call(object)==="[object Array]"},isFormData=function(input){return typeof input==="object"&&input!==null&&global.FormData&&input instanceof global.FormData},isByteArray=function(input){return typeof input==="object"&&input!==null&&(global.Buffer&&input instanceof Buffer||global.Blob&&input instanceof Blob||global.File&&input instanceof File||global.ArrayBuffer&&input instanceof ArrayBuffer||isArrayBufferView(input)||isArray(input))},supportedMethods=",GET,HEAD,PATCH,POST,PUT,DELETE,",pass=function(value){return value},_undefined,absoluteURLRegExp=/^[a-z][a-z0-9.+-]*:/i,addHook=function(type,hook){"use strict";if(typeof hook!=="function"){throw new Error("TODO error")}if(!this._hooks[type]){throw new Error("TODO error")}var httpinvoke=build();for(var i in this._hooks){if(this._hooks.hasOwnProperty(i)){httpinvoke._hooks[i].push.apply(httpinvoke._hooks[i],this._hooks[i])}}httpinvoke._hooks[type].push(hook);return httpinvoke},initHooks=function(){return{finished:[],downloading:[],uploading:[],gotStatus:[]}};var statusTextToCode=function(){for(var group=arguments.length,map={};group--;){for(var texts=arguments[group].split(","),index=texts.length;index--;){map[texts[index]]=(group+1)*100+index}}return map}("Continue,Switching Protocols","OK,Created,Accepted,Non-Authoritative Information,No Content,Reset Content,Partial Content","Multiple Choices,Moved Permanently,Found,See Other,Not Modified,Use Proxy,_,Temporary Redirect","Bad Request,Unauthorized,Payment Required,Forbidden,Not Found,Method Not Allowed,Not Acceptable,Proxy Authentication Required,Request Timeout,Conflict,Gone,Length Required,Precondition Failed,Request Entity Too Large,Request-URI Too Long,Unsupported Media Type,Requested Range Not Satisfiable,Expectation Failed","Internal Server Error,Not Implemented,Bad Gateway,Service Unavailable,Gateway Time-out,HTTP Version Not Supported");var upgradeByteArray=global.Uint8Array?function(array){return new Uint8Array(array)}:pass;var binaryStringToByteArray=function(str,bytearray){for(var i=bytearray.length;i<str.length;){bytearray.push(str.charCodeAt(i++)&255)}return bytearray};var countStringBytes=function(string){for(var c,n=0,i=string.length;i--;){c=string.charCodeAt(i);n+=c<128?1:c<2048?2:3}return n};var responseBodyToBytes,responseBodyLength;try{execScript("Function httpinvoke0(B,A,C)\r\nDim i\r\nFor i=C to LenB(B)\r\nA.push(AscB(MidB(B,i,1)))\r\nNext\r\nEnd Function\r\nFunction httpinvoke1(B)\r\nhttpinvoke1=LenB(B)\r\nEnd Function","vbscript");responseBodyToBytes=function(binary,bytearray){httpinvoke0(binary,bytearray,bytearray.length+1);return bytearray};responseBodyLength=function(binary){return httpinvoke1(binary)}}catch(err){}var responseByteArray=function(xhr,bytearray){return"responseBody"in xhr&&responseBodyToBytes?responseBodyToBytes(xhr.responseBody,bytearray):binaryStringToByteArray(xhr.responseText,bytearray)};var responseByteArrayLength=function(xhr){return"responseBody"in xhr&&responseBodyLength?responseBodyLength(xhr.responseBody):xhr.responseText.length};var fillOutputHeaders=function(xhr,outputHeaders){var headers=xhr.getAllResponseHeaders().split(/\r?\n/);var atLeastOne=false;for(var i=headers.length,colon,header;i--;){if((colon=headers[i].indexOf(":"))>=0){outputHeaders[headers[i].substr(0,colon).toLowerCase()]=headers[i].substr(colon+2);atLeastOne=true}}return atLeastOne};var urlPartitioningRegExp=/^([\w.+-]+:)(?:\/\/([^\/?#:]*)(?::(\d+)|)|)/;var isCrossDomain=function(location,url){url=urlPartitioningRegExp.exec(url.toLowerCase());location=urlPartitioningRegExp.exec(location.toLowerCase())||[];return!!(url&&(url[1]!==location[1]||url[2]!==location[2]||(url[3]||(url[1]==="http:"?"80":"443"))!==(location[3]||(location[1]==="http:"?"80":"443"))))};var build=function(){var createXHR;var httpinvoke=function(url,method,options,cb){var hook,promise,failWithoutRequest,uploadProgressCb,downloadProgressCb,inputLength,inputHeaders,statusCb,outputHeaders,exposedHeaders,status,outputBinary,input,outputLength,outputConverter,protocol;hook=function(type,args){var hooks=httpinvoke._hooks[type];for(var i=0;i<hooks.length;i+=1){args=hooks[i].apply(null,args)}return args};var downloadTimeout,uploadTimeout,timeout;if(!method){method="GET";options={}}else if(!options){if(typeof method==="string"){options={}}else if(typeof method==="object"){options=method;method="GET"}else{options={finished:method};method="GET"}}else if(!cb){if(typeof method==="object"){method.finished=options;options=method;method="GET"}else if(typeof options==="function"){options={finished:options}}}else{options.finished=cb}var safeCallback=function(name,aspectBefore,aspectAfter){return function(){var args=[],_cb,failedOnHook=false,fail=function(err,args){_cb=cb;cb=null;nextTick(function(){_cb&&_cb(err);promise();if(!_cb&&!failedOnHook){throw err}});return name==="finished"?[err]:args};aspectBefore.apply(null,args);try{args=hook(name,[].slice.call(arguments))}catch(err){failedOnHook=true;args=fail(err,args)}if(options[name]){try{options[name].apply(null,args)}catch(err){args=fail(err,args)}}aspectAfter.apply(null,args)}};failWithoutRequest=function(cb,err){if(!(err instanceof Error)){err=new Error("Error code #"+err+". See https://github.com/jakutis/httpinvoke#error-codes")}nextTick(function(){if(cb===null){return}cb(err)});promise=function(){};return mixInPromise(promise)};uploadProgressCb=safeCallback("uploading",pass,function(current,total){promise[progress]({type:"upload",current:current,total:total})});downloadProgressCb=safeCallback("downloading",pass,function(current,total,partial){promise[progress]({type:"download",current:current,total:total,partial:partial})});statusCb=safeCallback("gotStatus",function(){statusCb=null;if(downloadTimeout){setTimeout(function(){if(cb){cb(new Error("download timeout"));promise()}},downloadTimeout)}},function(statusCode,headers){promise[progress]({type:"headers",statusCode:statusCode,headers:headers})});cb=safeCallback("finished",function(){cb=null;promise()},function(err,body,statusCode,headers){var res={body:body,statusCode:statusCode,headers:headers};if(err){return promise[reject](err,res)}promise[resolve](res)});var converters=options.converters||{};var inputConverter;inputHeaders=options.headers||{};outputHeaders={};exposedHeaders=options.corsExposedHeaders||[];exposedHeaders.push.apply(exposedHeaders,["Cache-Control","Content-Language","Content-Type","Content-Length","Expires","Last-Modified","Pragma","Content-Range","Content-Encoding"]);if(!httpinvoke.relativeURLs&&!absoluteURLRegExp.test(url)){return failWithoutRequest(cb,[26,url])}protocol=url.substr(0,url.indexOf(":"));if(absoluteURLRegExp.test(url)&&protocol!=="http"&&protocol!=="https"){return failWithoutRequest(cb,[25,protocol])}var partialOutputMode=options.partialOutputMode||"disabled";if(partialOutputMode.indexOf(",")>=0||",disabled,chunked,joined,".indexOf(","+partialOutputMode+",")<0){return failWithoutRequest(cb,[3])}if(method.indexOf(",")>=0||!httpinvoke.anyMethod&&supportedMethods.indexOf(","+method+",")<0){return failWithoutRequest(cb,[4,method])}var optionsOutputType=options.outputType;outputBinary=optionsOutputType==="bytearray";if(!optionsOutputType||optionsOutputType==="text"||outputBinary){outputConverter=pass}else if(converters["text "+optionsOutputType]){outputConverter=converters["text "+optionsOutputType];outputBinary=false}else if(converters["bytearray "+optionsOutputType]){outputConverter=converters["bytearray "+optionsOutputType];outputBinary=true}else{return failWithoutRequest(cb,[5,optionsOutputType])}inputConverter=pass;var optionsInputType=options.inputType;input=options.input;if(input!==_undefined){if(!optionsInputType||optionsInputType==="auto"){if(typeof input!=="string"&&!isByteArray(input)&&!isFormData(input)){return failWithoutRequest(cb,[6])}}else if(optionsInputType==="text"){if(typeof input!=="string"){return failWithoutRequest(cb,[7])}}else if(optionsInputType==="formdata"){if(!isFormData(input)){return failWithoutRequest(cb,[8])}}else if(optionsInputType==="bytearray"){if(!isByteArray(input)){return failWithoutRequest(cb,[9])}}else if(converters[optionsInputType+" text"]){inputConverter=converters[optionsInputType+" text"]}else if(converters[optionsInputType+" bytearray"]){inputConverter=converters[optionsInputType+" bytearray"]}else if(converters[optionsInputType+" formdata"]){inputConverter=converters[optionsInputType+" formdata"]}else{return failWithoutRequest(cb,[10,optionsInputType])}if(typeof input==="object"&&!isFormData(input)){if(global.ArrayBuffer&&input instanceof global.ArrayBuffer){input=new global.Uint8Array(input)}else if(isArrayBufferView(input)){input=new global.Uint8Array(input.buffer,input.byteOffset,input.byteLength)}}try{input=inputConverter(input)}catch(err){return failWithoutRequest(cb,err)}}else{if(optionsInputType&&optionsInputType!=="auto"){return failWithoutRequest(cb,[11])}if(inputHeaders["Content-Type"]){return failWithoutRequest(cb,[12])}}var isValidTimeout=function(timeout){return timeout>0&&timeout<1073741824};var optionsTimeout=options.timeout;if(optionsTimeout!==_undefined){if(typeof optionsTimeout==="number"&&isValidTimeout(optionsTimeout)){timeout=optionsTimeout}else if(isArray(optionsTimeout)&&optionsTimeout.length===2&&isValidTimeout(optionsTimeout[0])&&isValidTimeout(optionsTimeout[1])){if(httpinvoke.corsFineGrainedTimeouts||!crossDomain){uploadTimeout=optionsTimeout[0];downloadTimeout=optionsTimeout[1]}else{timeout=optionsTimeout[0]+optionsTimeout[1]}}else{return failWithoutRequest(cb,[13])}}if(uploadTimeout){setTimeout(function(){if(statusCb){cb(new Error("upload timeout"));promise()}},uploadTimeout)}if(timeout){setTimeout(function(){if(cb){cb(new Error("timeout"));promise()}},timeout)}var xhr,i,j,currentLocation,crossDomain,output,uploadProgressCbCalled=false,partialPosition=0,partialBuffer=partialOutputMode==="disabled"?_undefined:outputBinary?[]:"",partial=partialBuffer,partialUpdate=function(){if(partialOutputMode==="disabled"){return}if(outputBinary){responseByteArray(xhr,partialBuffer)}else{partialBuffer=xhr.responseText}partial=partialOutputMode==="joined"?partialBuffer:partialBuffer.slice(partialPosition);partialPosition=partialBuffer.length};var uploadProgress=function(uploaded){if(!uploadProgressCb){return}if(!uploadProgressCbCalled){uploadProgressCbCalled=true;uploadProgressCb(0,inputLength);if(!cb){return}}uploadProgressCb(uploaded,inputLength);if(uploaded===inputLength){uploadProgressCb=null}};try{currentLocation=location.href}catch(_){currentLocation=document.createElement("a");currentLocation.href="";currentLocation=currentLocation.href}crossDomain=isCrossDomain(currentLocation,url);if(typeof input==="object"&&!isFormData(input)&&httpinvoke.requestTextOnly){return failWithoutRequest(cb,[17])}if(crossDomain&&!httpinvoke.cors){return failWithoutRequest(cb,[18])}for(j=["DELETE","PATCH","PUT","HEAD"],i=j.length;i-->0;){if(crossDomain&&method===j[i]&&!httpinvoke["cors"+j[i]]){return failWithoutRequest(cb,[19,method])}}if(method==="PATCH"&&!httpinvoke.PATCH){return failWithoutRequest(cb,[20])}if(!createXHR){return failWithoutRequest(cb,[21])}xhr=createXHR(crossDomain);try{xhr.open(method,url,true)}catch(e){return failWithoutRequest(cb,[22,url])}if(options.corsCredentials&&httpinvoke.corsCredentials&&typeof xhr.withCredentials==="boolean"){xhr.withCredentials=true}if(crossDomain&&options.corsOriginHeader){inputHeaders[options.corsOriginHeader]=location.protocol+"//"+location.host}var abOrZero=function(object,propertyA,propertyB){if(typeof object[propertyA]!=="undefined"){return object[propertyA]}if(typeof object[propertyB]!=="undefined"){return object[propertyB]}return 0};var onuploadprogress=function(progressEvent){if(cb&&progressEvent.lengthComputable){if(inputLength===_undefined){inputLength=abOrZero(progressEvent,"total","totalSize");uploadProgress(0)}uploadProgress(abOrZero(progressEvent,"loaded","position"))}};if("upload"in xhr){xhr.upload.onerror=function(){received.error=true;cb&&cb(new Error("network error"))};xhr.upload.onprogress=onuploadprogress}else if("onuploadprogress"in xhr){xhr.onuploadprogress=onuploadprogress}if("onerror"in xhr){xhr.onerror=function(){received.error=true;onLoad()}}var ondownloadprogress=function(progressEvent){onHeadersReceived(false);try{var current=abOrZero(progressEvent,"loaded","position");if(progressEvent.lengthComputable){outputLength=abOrZero(progressEvent,"total","totalSize")}cb&&current<=outputLength&&!statusCb&&(partialUpdate(),downloadProgressCb(current,outputLength,partial))}catch(_){}};if("onloadstart"in xhr){xhr.onloadstart=ondownloadprogress}if("onloadend"in xhr){xhr.onloadend=ondownloadprogress}if("onprogress"in xhr){xhr.onprogress=ondownloadprogress}var received={};var mustBeIdentity;var tryHeadersAndStatus=function(lastTry){try{if(xhr.status){received.status=true}}catch(_){}try{if(xhr.statusText){received.status=true}}catch(_){}try{if(xhr.responseText){received.entity=true}}catch(_){}try{if(xhr.response){received.entity=true}}catch(_){}try{if(responseBodyLength(xhr.responseBody)){received.entity=true}}catch(_){}if(!statusCb){return}if(received.status||received.entity||received.success||lastTry){if(typeof xhr.contentType==="string"&&xhr.contentType){if(xhr.contentType!=="text/html"||xhr.responseText!==""){outputHeaders["content-type"]=xhr.contentType;received.headers=true}}for(var i=0;i<exposedHeaders.length;i++){var header;try{if(header=xhr.getResponseHeader(exposedHeaders[i])){outputHeaders[exposedHeaders[i].toLowerCase()]=header;received.headers=true}}catch(err){}}try{if(fillOutputHeaders(xhr,outputHeaders)){received.headers=true}}catch(err){}mustBeIdentity=outputHeaders["content-encoding"]==="identity"||!crossDomain&&!outputHeaders["content-encoding"];if(mustBeIdentity&&"content-length"in outputHeaders){outputLength=Number(outputHeaders["content-length"])}if(!status&&(!crossDomain||httpinvoke.corsStatus)){try{if(xhr.status){status=xhr.status}}catch(_){}if(!status){try{status=statusTextToCode[xhr.statusText]}catch(_){}}if(status===1223){status=204}if(status>=12001&&status<=12156){status=_undefined}}}};var onHeadersReceived=function(lastTry){if(!cb){return}if(!lastTry){tryHeadersAndStatus(false)}if(!statusCb||!lastTry&&!(received.status&&received.headers)){return}if(inputLength===_undefined){inputLength=0;uploadProgress(0)}uploadProgress(inputLength);if(!cb){return}statusCb(status,outputHeaders);if(!cb){return}downloadProgressCb(0,outputLength,partial);if(!cb){return}if(method==="HEAD"){downloadProgressCb(0,0,partial);return cb&&cb(null,_undefined,status,outputHeaders)}};var onLoad=function(){if(!cb){return}tryHeadersAndStatus(true);var length;try{length=partialOutputMode!=="disabled"?responseByteArrayLength(xhr):outputBinary?"response"in xhr?xhr.response?xhr.response.byteLength:0:responseByteArrayLength(xhr):countStringBytes(xhr.responseText)}catch(_){length=0}if(outputLength!==_undefined){if(mustBeIdentity){if(length!==outputLength&&method!=="HEAD"){return cb(new Error("network error"))}}else{if(received.error){return cb(new Error("network error"))}}}else{outputLength=length}var noentity=!received.entity&&outputLength===0&&outputHeaders["content-type"]===_undefined;if(noentity&&status===200||!received.success&&!status&&(received.error||"onreadystatechange"in xhr&&!received.readyStateLOADING)){return cb(new Error("network error"))}onHeadersReceived(true);if(!cb){return}if(noentity){downloadProgressCb(0,0,partial);return cb(null,_undefined,status,outputHeaders)}partialUpdate();downloadProgressCb(outputLength,outputLength,partial);if(!cb){return}try{cb(null,outputConverter(partialBuffer||(outputBinary?upgradeByteArray("response"in xhr?xhr.response||[]:responseByteArray(xhr,[])):xhr.responseText)),status,outputHeaders)}catch(err){cb(err)}};var onloadBound="onload"in xhr;if(onloadBound){xhr.onload=function(){received.success=true;onLoad()}}if("onreadystatechange"in xhr){xhr.onreadystatechange=function(){if(xhr.readyState===2){onHeadersReceived(false)}else if(xhr.readyState===3){received.readyStateLOADING=true;onHeadersReceived(false)}else if(xhr.readyState===4&&!onloadBound){onLoad()}}}if(!crossDomain||httpinvoke.corsRequestHeaders){for(var inputHeaderName in inputHeaders){if(inputHeaders.hasOwnProperty(inputHeaderName)){try{xhr.setRequestHeader(inputHeaderName,inputHeaders[inputHeaderName])}catch(err){return failWithoutRequest(cb,[23,inputHeaderName])}}}}nextTick(function(){if(!cb){return}if(outputBinary){try{if(partialOutputMode==="disabled"&&"response"in xhr){xhr.responseType="arraybuffer"}else{xhr.overrideMimeType("text/plain; charset=x-user-defined")}}catch(_){}}if(isFormData(input)){try{xhr.send(input)}catch(err){return failWithoutRequest(cb,[24])}}else if(typeof input==="object"){var triedSendArrayBufferView=false;var triedSendBlob=false;var triedSendBinaryString=false;var BlobBuilder=global.BlobBuilder||global.WebKitBlobBuilder||global.MozBlobBuilder||global.MSBlobBuilder;if(isArray(input)){input=global.Uint8Array?new Uint8Array(input):String.fromCharCode.apply(String,input)}var toBlob=BlobBuilder?function(){var bb=new BlobBuilder;bb.append(input);input=bb.getBlob(inputHeaders["Content-Type"]||"application/octet-stream")}:function(){try{input=new Blob([input],{type:inputHeaders["Content-Type"]||"application/octet-stream"})}catch(_){triedSendBlob=true}};var go=function(){var reader;if(triedSendBlob&&triedSendArrayBufferView&&triedSendBinaryString){return failWithoutRequest(cb,[24])}if(isArrayBufferView(input)){if(triedSendArrayBufferView){if(!triedSendBinaryString){try{input=String.fromCharCode.apply(String,input)}catch(_){triedSendBinaryString=true}}else if(!triedSendBlob){toBlob()}}else{inputLength=input.byteLength;try{xhr.send(global.ArrayBufferView?input:input.byteOffset===0&&input.length===input.buffer.byteLength?input.buffer:input.buffer.slice?input.buffer.slice(input.byteOffset,input.byteOffset+input.length):new Uint8Array([].slice.call(new Uint8Array(input.buffer),input.byteOffset,input.byteOffset+input.length)).buffer);return}catch(_){}triedSendArrayBufferView=true}}else if(global.Blob&&input instanceof Blob){if(triedSendBlob){if(!triedSendArrayBufferView){try{reader=new FileReader;reader.onerror=function(){triedSendArrayBufferView=true;go()};reader.onload=function(){try{input=new Uint8Array(reader.result)}catch(_){triedSendArrayBufferView=true}go()};reader.readAsArrayBuffer(input);return}catch(_){triedSendArrayBufferView=true}}else if(!triedSendBinaryString){try{reader=new FileReader;reader.onerror=function(){triedSendBinaryString=true;go()};reader.onload=function(){input=reader.result;go()};reader.readAsBinaryString(input);return}catch(_){triedSendBinaryString=true}}}else{try{inputLength=input.size;xhr.send(input);return}catch(_){triedSendBlob=true}}}else{if(triedSendBinaryString){if(!triedSendArrayBufferView){try{input=binaryStringToByteArray(input,[])}catch(_){triedSendArrayBufferView=true}}else if(!triedSendBlob){toBlob()}}else{try{inputLength=input.length;xhr.sendAsBinary(input);return}catch(_){triedSendBinaryString=true}}}nextTick(go)};go();uploadProgress(0)}else{try{if(typeof input==="string"){inputLength=countStringBytes(input);xhr.send(input)}else{inputLength=0;xhr.send(null)}}catch(err){return failWithoutRequest(cb,[24])}uploadProgress(0)}});promise=function(){cb&&cb(new Error("abort"));try{xhr.abort()}catch(err){}};return mixInPromise(promise)};httpinvoke.corsResponseContentTypeOnly=false;httpinvoke.corsRequestHeaders=false;httpinvoke.corsCredentials=false;httpinvoke.cors=false;httpinvoke.corsDELETE=false;httpinvoke.corsHEAD=false;httpinvoke.corsPATCH=false;httpinvoke.corsPUT=false;httpinvoke.corsStatus=false;httpinvoke.corsResponseTextOnly=false;httpinvoke.corsFineGrainedTimeouts=true;httpinvoke.requestTextOnly=false;httpinvoke.anyMethod=false;httpinvoke.relativeURLs=true;(function(){try{createXHR=function(){return new XMLHttpRequest};var tmpxhr=createXHR();httpinvoke.requestTextOnly=!global.Uint8Array&&!tmpxhr.sendAsBinary;httpinvoke.cors="withCredentials"in tmpxhr;if(httpinvoke.cors){httpinvoke.corsRequestHeaders=true;httpinvoke.corsCredentials=true;httpinvoke.corsDELETE=true;httpinvoke.corsPATCH=true;httpinvoke.corsPUT=true;httpinvoke.corsHEAD=true;httpinvoke.corsStatus=true;return}}catch(err){}try{if(global.XDomainRequest===_undefined){createXHR=function(){return new XMLHttpRequest};createXHR()}else{createXHR=function(cors){return cors?new XDomainRequest:new XMLHttpRequest};createXHR(true);httpinvoke.cors=true;httpinvoke.corsResponseContentTypeOnly=true;httpinvoke.corsResponseTextOnly=true;httpinvoke.corsFineGrainedTimeouts=false}return}catch(err){}try{createXHR();return}catch(err){}var candidates=["Microsoft.XMLHTTP","Msxml2.XMLHTTP.6.0","Msxml2.XMLHTTP.3.0","Msxml2.XMLHTTP"];for(var i=candidates.length;i--;){try{createXHR=function(){return new ActiveXObject(candidates[i])};createXHR();httpinvoke.requestTextOnly=true;return}catch(err){}}createXHR=_undefined})();httpinvoke.PATCH=!!function(){try{createXHR().open("PATCH",location.href,true);return 1}catch(_){}}();httpinvoke._hooks=initHooks();httpinvoke.hook=addHook;return httpinvoke};return build()});
(function(root,factory){if(typeof define==="function"&&define.amd){define(factory)}else if(typeof exports==="object"){module.exports=factory()}else{root.httpinvoke=factory()}})(this,function(){"use strict";var global;global=window;var resolve=0,reject=1,progress=2,chain=function(a,b){if(a&&a.then){a.then(function(){b[resolve].apply(null,arguments)},function(){b[reject].apply(null,arguments)},function(){b[progress].apply(null,arguments)})}else{b[resolve](a)}},nextTick=global.process&&global.process.nextTick||global.setImmediate||global.setTimeout,mixInPromise=function(o){var value,queue=[],state=progress;var makeState=function(newstate){o[newstate]=function(){var i,p;if(queue){value=[].slice.call(arguments);state=newstate;for(i=0;i<queue.length;i+=1){if(typeof queue[i][state]==="function"){try{p=queue[i][state].apply(null,value);if(state<progress){chain(p,queue[i]._)}}catch(err){queue[i]._[reject](err)}}else if(state<progress){queue[i]._[state].apply(null,value)}}if(state<progress){queue=null}}}};makeState(progress);makeState(resolve);makeState(reject);o.then=function(){var item=[].slice.call(arguments);item._=mixInPromise({});if(queue){queue.push(item)}else if(typeof item[state]==="function"){nextTick(function(){chain(item[state].apply(null,value),item._)})}return item._};return o},isArrayBufferView=function(input){return typeof input==="object"&&input!==null&&(global.ArrayBufferView&&input instanceof ArrayBufferView||global.Int8Array&&input instanceof Int8Array||global.Uint8Array&&input instanceof Uint8Array||global.Uint8ClampedArray&&input instanceof Uint8ClampedArray||global.Int16Array&&input instanceof Int16Array||global.Uint16Array&&input instanceof Uint16Array||global.Int32Array&&input instanceof Int32Array||global.Uint32Array&&input instanceof Uint32Array||global.Float32Array&&input instanceof Float32Array||global.Float64Array&&input instanceof Float64Array)},isArray=function(object){return Object.prototype.toString.call(object)==="[object Array]"},isFormData=function(input){return typeof input==="object"&&input!==null&&global.FormData&&input instanceof global.FormData},isByteArray=function(input){return typeof input==="object"&&input!==null&&(global.Buffer&&input instanceof Buffer||global.Blob&&input instanceof Blob||global.File&&input instanceof File||global.ArrayBuffer&&input instanceof ArrayBuffer||isArrayBufferView(input)||isArray(input))},supportedMethods=",GET,HEAD,PATCH,POST,PUT,DELETE,",pass=function(value){return value},_undefined,absoluteURLRegExp=/^[a-z][a-z0-9.+-]*:/i,addHook=function(type,hook){"use strict";if(typeof hook!=="function"){throw new Error("TODO error")}if(!this._hooks[type]){throw new Error("TODO error")}var httpinvoke=build();for(var i in this._hooks){if(this._hooks.hasOwnProperty(i)){httpinvoke._hooks[i].push.apply(httpinvoke._hooks[i],this._hooks[i])}}httpinvoke._hooks[type].push(hook);return httpinvoke},initHooks=function(){return{finished:[],downloading:[],uploading:[],gotStatus:[]}};var statusTextToCode=function(){for(var group=arguments.length,map={};group--;){for(var texts=arguments[group].split(","),index=texts.length;index--;){map[texts[index]]=(group+1)*100+index}}return map}("Continue,Switching Protocols","OK,Created,Accepted,Non-Authoritative Information,No Content,Reset Content,Partial Content","Multiple Choices,Moved Permanently,Found,See Other,Not Modified,Use Proxy,_,Temporary Redirect","Bad Request,Unauthorized,Payment Required,Forbidden,Not Found,Method Not Allowed,Not Acceptable,Proxy Authentication Required,Request Timeout,Conflict,Gone,Length Required,Precondition Failed,Request Entity Too Large,Request-URI Too Long,Unsupported Media Type,Requested Range Not Satisfiable,Expectation Failed","Internal Server Error,Not Implemented,Bad Gateway,Service Unavailable,Gateway Time-out,HTTP Version Not Supported");var upgradeByteArray=global.Uint8Array?function(array){return new Uint8Array(array)}:pass;var binaryStringToByteArray=function(str,bytearray){for(var i=bytearray.length;i<str.length;){bytearray.push(str.charCodeAt(i++)&255)}return bytearray};var countStringBytes=function(string){for(var c,n=0,i=string.length;i--;){c=string.charCodeAt(i);n+=c<128?1:c<2048?2:3}return n};var responseBodyToBytes,responseBodyLength;try{execScript("Function httpinvoke0(B,A,C)\r\nDim i\r\nFor i=C to LenB(B)\r\nA.push(AscB(MidB(B,i,1)))\r\nNext\r\nEnd Function\r\nFunction httpinvoke1(B)\r\nhttpinvoke1=LenB(B)\r\nEnd Function","vbscript");responseBodyToBytes=function(binary,bytearray){httpinvoke0(binary,bytearray,bytearray.length+1);return bytearray};responseBodyLength=function(binary){return httpinvoke1(binary)}}catch(err){}var responseByteArray=function(xhr,bytearray){return"responseBody"in xhr&&responseBodyToBytes?responseBodyToBytes(xhr.responseBody,bytearray):binaryStringToByteArray(xhr.responseText,bytearray)};var responseByteArrayLength=function(xhr){return"responseBody"in xhr&&responseBodyLength?responseBodyLength(xhr.responseBody):xhr.responseText.length};var fillOutputHeaders=function(xhr,outputHeaders){var headers=xhr.getAllResponseHeaders().split(/\r?\n/);var atLeastOne=false;for(var i=headers.length,colon,header;i--;){if((colon=headers[i].indexOf(":"))>=0){outputHeaders[headers[i].substr(0,colon).toLowerCase()]=headers[i].substr(colon+2);atLeastOne=true}}return atLeastOne};var urlPartitioningRegExp=/^(?:([a-z][a-z0-9.+-]*:)|)(?:\/\/([^\/?#:]*)(?::(\d+)|)|)/;var isCrossDomain=function(location,url){if(!absoluteURLRegExp.test(url)&&url.substr(0,2)!=="//"){return false}url=urlPartitioningRegExp.exec(url.toLowerCase());location=urlPartitioningRegExp.exec(location.toLowerCase())||[];var locationPort=location[3]||(location[1]==="http:"?"80":"443");return!!(url[1]&&url[1]!==location[1]||url[2]!==location[2]||(url[3]||(url[1]?url[1]==="http:"?"80":"443":locationPort))!==locationPort)};var build=function(){var createXHR;var httpinvoke=function(url,method,options,cb){var hook,promise,failWithoutRequest,uploadProgressCb,downloadProgressCb,inputLength,inputHeaders,statusCb,outputHeaders,exposedHeaders,status,outputBinary,input,outputLength,outputConverter,protocol,anonymous,system;hook=function(type,args){var hooks=httpinvoke._hooks[type];for(var i=0;i<hooks.length;i+=1){args=hooks[i].apply(null,args)}return args};var downloadTimeout,uploadTimeout,timeout;if(!method){method="GET";options={}}else if(!options){if(typeof method==="string"){options={}}else if(typeof method==="object"){options=method;method="GET"}else{options={finished:method};method="GET"}}else if(!cb){if(typeof method==="object"){method.finished=options;options=method;method="GET"}else if(typeof options==="function"){options={finished:options}}}else{options.finished=cb}var safeCallback=function(name,aspectBefore,aspectAfter){return function(){var args=[],_cb,failedOnHook=false,fail=function(err,args){_cb=cb;cb=null;nextTick(function(){_cb&&_cb(err);promise();if(!_cb&&!failedOnHook){throw err}});return name==="finished"?[err]:args};aspectBefore.apply(null,args);try{args=hook(name,[].slice.call(arguments))}catch(err){failedOnHook=true;args=fail(err,args)}if(options[name]){try{options[name].apply(null,args)}catch(err){args=fail(err,args)}}aspectAfter.apply(null,args)}};failWithoutRequest=function(cb,err){if(!(err instanceof Error)){err=new Error("Error code #"+err+". See https://github.com/jakutis/httpinvoke#error-codes")}nextTick(function(){if(cb===null){return}cb(err)});promise=function(){};return mixInPromise(promise)};uploadProgressCb=safeCallback("uploading",pass,function(current,total){promise[progress]({type:"upload",current:current,total:total})});downloadProgressCb=safeCallback("downloading",pass,function(current,total,partial){promise[progress]({type:"download",current:current,total:total,partial:partial})});statusCb=safeCallback("gotStatus",function(){statusCb=null;if(downloadTimeout){setTimeout(function(){if(cb){cb(new Error("download timeout"));promise()}},downloadTimeout)}},function(statusCode,headers){promise[progress]({type:"headers",statusCode:statusCode,headers:headers})});cb=safeCallback("finished",function(){cb=null;promise()},function(err,body,statusCode,headers){var res={body:body,statusCode:statusCode,headers:headers};if(err){return promise[reject](err,res)}promise[resolve](res)});var converters=options.converters||{};var inputConverter;inputHeaders=function(input){var output={};for(var i in input){if(input.hasOwnProperty(i)){output[i]=input[i]}}return output}(options.headers||{});outputHeaders={};exposedHeaders=options.corsExposedHeaders||[];exposedHeaders.push.apply(exposedHeaders,["Cache-Control","Content-Language","Content-Type","Content-Length","Expires","Last-Modified","Pragma","Content-Range","Content-Encoding"]);var validateInputHeaders=function(headers){var noSec=httpinvoke.forbiddenInputHeaders.indexOf("sec-*")>=0;var noProxy=httpinvoke.forbiddenInputHeaders.indexOf("proxy-*")>=0;for(var header in headers){if(headers.hasOwnProperty(header)){var headerl=header.toLowerCase();if(httpinvoke.forbiddenInputHeaders.indexOf(headerl)>=0){throw[14,header]}if(noProxy&&headerl.substr(0,"proxy-".length)==="proxy-"){throw[15,header]}if(noSec&&headerl.substr(0,"sec-".length)==="sec-"){throw[16,header]}}}};try{validateInputHeaders(inputHeaders)}catch(err){return failWithoutRequest(cb,err)}if(!httpinvoke.relativeURLs&&!absoluteURLRegExp.test(url)){return failWithoutRequest(cb,[26,url])}protocol=url.substr(0,url.indexOf(":"));if(absoluteURLRegExp.test(url)&&protocol!=="http"&&protocol!=="https"){return failWithoutRequest(cb,[25,protocol])}anonymous=typeof options.anonymous==="undefined"?httpinvoke.anonymousByDefault:options.anonymous;system=typeof options.system==="undefined"?httpinvoke.systemByDefault:options.system;if(typeof options.system!=="undefined"&&system){anonymous=true}var partialOutputMode=options.partialOutputMode||"disabled";if(partialOutputMode.indexOf(",")>=0||",disabled,chunked,joined,".indexOf(","+partialOutputMode+",")<0){return failWithoutRequest(cb,[3])}if(method.indexOf(",")>=0||!httpinvoke.anyMethod&&supportedMethods.indexOf(","+method+",")<0){return failWithoutRequest(cb,[4,method])}var optionsOutputType=options.outputType;outputBinary=optionsOutputType==="bytearray";if(!optionsOutputType||optionsOutputType==="text"||outputBinary){outputConverter=pass}else if(converters["text "+optionsOutputType]){outputConverter=converters["text "+optionsOutputType];outputBinary=false}else if(converters["bytearray "+optionsOutputType]){outputConverter=converters["bytearray "+optionsOutputType];outputBinary=true}else{return failWithoutRequest(cb,[5,optionsOutputType])}inputConverter=pass;var optionsInputType=options.inputType;input=options.input;if(input!==_undefined){if(!optionsInputType||optionsInputType==="auto"){if(typeof input!=="string"&&!isByteArray(input)&&!isFormData(input)){return failWithoutRequest(cb,[6])}}else if(optionsInputType==="text"){if(typeof input!=="string"){return failWithoutRequest(cb,[7])}}else if(optionsInputType==="formdata"){if(!isFormData(input)){return failWithoutRequest(cb,[8])}}else if(optionsInputType==="bytearray"){if(!isByteArray(input)){return failWithoutRequest(cb,[9])}}else if(converters[optionsInputType+" text"]){inputConverter=converters[optionsInputType+" text"]}else if(converters[optionsInputType+" bytearray"]){inputConverter=converters[optionsInputType+" bytearray"]}else if(converters[optionsInputType+" formdata"]){inputConverter=converters[optionsInputType+" formdata"]}else{return failWithoutRequest(cb,[10,optionsInputType])}if(typeof input==="object"&&!isFormData(input)){if(global.ArrayBuffer&&input instanceof global.ArrayBuffer){input=new global.Uint8Array(input)}else if(isArrayBufferView(input)){input=new global.Uint8Array(input.buffer,input.byteOffset,input.byteLength)}}try{input=inputConverter(input)}catch(err){return failWithoutRequest(cb,err)}}else{if(optionsInputType&&optionsInputType!=="auto"){return failWithoutRequest(cb,[11])}if(inputHeaders["Content-Type"]){return failWithoutRequest(cb,[12])}}var isValidTimeout=function(timeout){return timeout>0&&timeout<1073741824};var optionsTimeout=options.timeout;if(optionsTimeout!==_undefined){if(typeof optionsTimeout==="number"&&isValidTimeout(optionsTimeout)){timeout=optionsTimeout}else if(isArray(optionsTimeout)&&optionsTimeout.length===2&&isValidTimeout(optionsTimeout[0])&&isValidTimeout(optionsTimeout[1])){if(httpinvoke.corsFineGrainedTimeouts||!crossDomain){uploadTimeout=optionsTimeout[0];downloadTimeout=optionsTimeout[1]}else{timeout=optionsTimeout[0]+optionsTimeout[1]}}else{return failWithoutRequest(cb,[13])}}if(uploadTimeout){setTimeout(function(){if(statusCb){cb(new Error("upload timeout"));promise()}},uploadTimeout)}if(timeout){setTimeout(function(){if(cb){cb(new Error("timeout"));promise()}},timeout)}var xhr,i,j,currentLocation,crossDomain,output,uploadProgressCbCalled=false,partialPosition=0,partialBuffer=partialOutputMode==="disabled"?_undefined:outputBinary?[]:"",partial=partialBuffer,partialUpdate=function(){if(partialOutputMode==="disabled"){return}if(outputBinary){responseByteArray(xhr,partialBuffer)}else{partialBuffer=xhr.responseText}partial=partialOutputMode==="joined"?partialBuffer:partialBuffer.slice(partialPosition);partialPosition=partialBuffer.length};var uploadProgress=function(uploaded){if(!uploadProgressCb){return}if(!uploadProgressCbCalled){uploadProgressCbCalled=true;uploadProgressCb(0,inputLength);if(!cb){return}}uploadProgressCb(uploaded,inputLength);if(uploaded===inputLength){uploadProgressCb=null}};try{currentLocation=location.href}catch(_){currentLocation=document.createElement("a");currentLocation.href="";currentLocation=currentLocation.href}crossDomain=isCrossDomain(currentLocation,url);if(typeof input==="object"&&!isFormData(input)&&httpinvoke.requestTextOnly){return failWithoutRequest(cb,[17])}if(crossDomain&&!httpinvoke.cors){return failWithoutRequest(cb,[18])}for(j=["DELETE","PATCH","PUT","HEAD"],i=j.length;i-->0;){if(crossDomain&&method===j[i]&&!httpinvoke["cors"+j[i]]){return failWithoutRequest(cb,[19,method])}}if(method==="PATCH"&&!httpinvoke.PATCH){return failWithoutRequest(cb,[20])}if(!createXHR){return failWithoutRequest(cb,[21])}xhr=createXHR(crossDomain,{mozAnon:anonymous,mozSystem:system});try{xhr.open(method,url,true)}catch(e){return failWithoutRequest(cb,[22,url])}if(httpinvoke.corsCredentials){if(typeof options.anonymous!=="undefined"&&!anonymous||options.corsCredentials&&typeof xhr.withCredentials==="boolean"){xhr.withCredentials=true}}if(crossDomain&&options.corsOriginHeader){inputHeaders[options.corsOriginHeader]=location.protocol+"//"+location.host}var abOrZero=function(object,propertyA,propertyB){if(typeof object[propertyA]!=="undefined"){return object[propertyA]}if(typeof object[propertyB]!=="undefined"){return object[propertyB]}return 0};var onuploadprogress=function(progressEvent){if(cb&&progressEvent.lengthComputable){if(inputLength===_undefined){inputLength=abOrZero(progressEvent,"total","totalSize");uploadProgress(0)}uploadProgress(abOrZero(progressEvent,"loaded","position"))}};if("upload"in xhr){xhr.upload.onerror=function(){received.error=true;cb&&cb(new Error("network error"))};xhr.upload.onprogress=onuploadprogress}else if("onuploadprogress"in xhr){xhr.onuploadprogress=onuploadprogress}if("onerror"in xhr){xhr.onerror=function(){received.error=true;onLoad()}}var ondownloadprogress=function(progressEvent){onHeadersReceived(false);try{var current=abOrZero(progressEvent,"loaded","position");if(progressEvent.lengthComputable){outputLength=abOrZero(progressEvent,"total","totalSize")}cb&&current<=outputLength&&!statusCb&&(partialUpdate(),downloadProgressCb(current,outputLength,partial))}catch(_){}};if("onloadstart"in xhr){xhr.onloadstart=ondownloadprogress}if("onloadend"in xhr){xhr.onloadend=ondownloadprogress}if("onprogress"in xhr){xhr.onprogress=ondownloadprogress}var received={};var mustBeIdentity;var tryHeadersAndStatus=function(lastTry){try{if(xhr.status){received.status=true}}catch(_){}try{if(xhr.statusText){received.status=true}}catch(_){}try{if(xhr.responseText){received.entity=true}}catch(_){}try{if(xhr.response){received.entity=true}}catch(_){}try{if(responseBodyLength(xhr.responseBody)){received.entity=true}}catch(_){}if(!statusCb){return}if(received.status||received.entity||received.success||lastTry){if(typeof xhr.contentType==="string"&&xhr.contentType){if(xhr.contentType!=="text/html"||xhr.responseText!==""){outputHeaders["content-type"]=xhr.contentType;received.headers=true}}for(var i=0;i<exposedHeaders.length;i++){var header;try{if(header=xhr.getResponseHeader(exposedHeaders[i])){outputHeaders[exposedHeaders[i].toLowerCase()]=header;received.headers=true}}catch(err){}}try{if(fillOutputHeaders(xhr,outputHeaders)){received.headers=true}}catch(err){}mustBeIdentity=outputHeaders["content-encoding"]==="identity"||!crossDomain&&!outputHeaders["content-encoding"];if(mustBeIdentity&&"content-length"in outputHeaders){outputLength=Number(outputHeaders["content-length"])}if(!status&&(!crossDomain||httpinvoke.corsStatus)){try{if(xhr.status){status=xhr.status}}catch(_){}if(!status){try{status=statusTextToCode[xhr.statusText]}catch(_){}}if(status===1223){status=204}if(status>=12001&&status<=12156){status=_undefined}}}};var onHeadersReceived=function(lastTry){if(!cb){return}if(!lastTry){tryHeadersAndStatus(false)}if(!statusCb||!lastTry&&!(received.status&&received.headers)){return}if(inputLength===_undefined){inputLength=0;uploadProgress(0)}uploadProgress(inputLength);if(!cb){return}statusCb(status,outputHeaders);if(!cb){return}downloadProgressCb(0,outputLength,partial);if(!cb){return}if(method==="HEAD"){downloadProgressCb(0,0,partial);return cb&&cb(null,_undefined,status,outputHeaders)}};var onLoad=function(){if(!cb){return}tryHeadersAndStatus(true);var length;try{length=partialOutputMode!=="disabled"?responseByteArrayLength(xhr):outputBinary?"response"in xhr?xhr.response?xhr.response.byteLength:0:responseByteArrayLength(xhr):countStringBytes(xhr.responseText)}catch(_){length=0}if(outputLength!==_undefined){if(mustBeIdentity){if(length!==outputLength&&method!=="HEAD"){return cb(new Error("network error"))}}else{if(received.error){return cb(new Error("network error"))}}}else{outputLength=length}var noentity=!received.entity&&outputLength===0&&outputHeaders["content-type"]===_undefined;if(noentity&&status===200||!received.success&&!status&&(received.error||"onreadystatechange"in xhr&&!received.readyStateLOADING)){return cb(new Error("network error"))}onHeadersReceived(true);if(!cb){return}if(noentity){downloadProgressCb(0,0,partial);return cb(null,_undefined,status,outputHeaders)}partialUpdate();downloadProgressCb(outputLength,outputLength,partial);if(!cb){return}try{cb(null,outputConverter(partialBuffer||(outputBinary?upgradeByteArray("response"in xhr?xhr.response||[]:responseByteArray(xhr,[])):xhr.responseText)),status,outputHeaders)}catch(err){cb(err)}};var onloadBound="onload"in xhr;if(onloadBound){xhr.onload=function(){received.success=true;onLoad()}}if("onreadystatechange"in xhr){xhr.onreadystatechange=function(){if(xhr.readyState===2){onHeadersReceived(false)}else if(xhr.readyState===3){received.readyStateLOADING=true;onHeadersReceived(false)}else if(xhr.readyState===4&&!onloadBound){onLoad()}}}if(!crossDomain||httpinvoke.corsRequestHeaders){for(var inputHeaderName in inputHeaders){if(inputHeaders.hasOwnProperty(inputHeaderName)){try{xhr.setRequestHeader(inputHeaderName,inputHeaders[inputHeaderName])}catch(err){return failWithoutRequest(cb,[23,inputHeaderName])}}}}nextTick(function(){if(!cb){return}if(outputBinary){try{if(partialOutputMode==="disabled"&&"response"in xhr){xhr.responseType="arraybuffer"}else{xhr.overrideMimeType("text/plain; charset=x-user-defined")}}catch(_){}}if(isFormData(input)){try{xhr.send(input)}catch(err){return failWithoutRequest(cb,[24])}}else if(typeof input==="object"){var triedSendArrayBufferView=false;var triedSendBlob=false;var triedSendBinaryString=false;var BlobBuilder=global.BlobBuilder||global.WebKitBlobBuilder||global.MozBlobBuilder||global.MSBlobBuilder;if(isArray(input)){input=global.Uint8Array?new Uint8Array(input):String.fromCharCode.apply(String,input)}var toBlob=BlobBuilder?function(){var bb=new BlobBuilder;bb.append(input);input=bb.getBlob(inputHeaders["Content-Type"]||"application/octet-stream")}:function(){try{input=new Blob([input],{type:inputHeaders["Content-Type"]||"application/octet-stream"})}catch(_){triedSendBlob=true}};var go=function(){var reader;if(triedSendBlob&&triedSendArrayBufferView&&triedSendBinaryString){return failWithoutRequest(cb,[24])}if(isArrayBufferView(input)){if(triedSendArrayBufferView){if(!triedSendBinaryString){try{input=String.fromCharCode.apply(String,input)}catch(_){triedSendBinaryString=true}}else if(!triedSendBlob){toBlob()}}else{inputLength=input.byteLength;try{xhr.send(global.ArrayBufferView?input:input.byteOffset===0&&input.length===input.buffer.byteLength?input.buffer:input.buffer.slice?input.buffer.slice(input.byteOffset,input.byteOffset+input.length):new Uint8Array([].slice.call(new Uint8Array(input.buffer),input.byteOffset,input.byteOffset+input.length)).buffer);return}catch(_){}triedSendArrayBufferView=true}}else if(global.Blob&&input instanceof Blob){if(triedSendBlob){if(!triedSendArrayBufferView){try{reader=new FileReader;reader.onerror=function(){triedSendArrayBufferView=true;go()};reader.onload=function(){try{input=new Uint8Array(reader.result)}catch(_){triedSendArrayBufferView=true}go()};reader.readAsArrayBuffer(input);return}catch(_){triedSendArrayBufferView=true}}else if(!triedSendBinaryString){try{reader=new FileReader;reader.onerror=function(){triedSendBinaryString=true;go()};reader.onload=function(){input=reader.result;go()};reader.readAsBinaryString(input);return}catch(_){triedSendBinaryString=true}}}else{try{inputLength=input.size;xhr.send(input);return}catch(_){triedSendBlob=true}}}else{if(triedSendBinaryString){if(!triedSendArrayBufferView){try{input=binaryStringToByteArray(input,[])}catch(_){triedSendArrayBufferView=true}}else if(!triedSendBlob){toBlob()}}else{try{inputLength=input.length;xhr.sendAsBinary(input);return}catch(_){triedSendBinaryString=true}}}nextTick(go)};go();uploadProgress(0)}else{try{if(typeof input==="string"){inputLength=countStringBytes(input);xhr.send(input)}else{inputLength=0;xhr.send(null)}}catch(err){return failWithoutRequest(cb,[24])}uploadProgress(0)}});promise=function(){cb&&cb(new Error("abort"));try{xhr.abort()}catch(err){}};return mixInPromise(promise)};httpinvoke.corsResponseContentTypeOnly=false;httpinvoke.corsRequestHeaders=false;httpinvoke.corsCredentials=false;httpinvoke.cors=false;httpinvoke.corsDELETE=false;httpinvoke.corsHEAD=false;httpinvoke.corsPATCH=false;httpinvoke.corsPUT=false;httpinvoke.corsStatus=false;httpinvoke.corsResponseTextOnly=false;httpinvoke.corsFineGrainedTimeouts=true;httpinvoke.requestTextOnly=false;httpinvoke.anyMethod=false;httpinvoke.relativeURLs=true;(function(){try{createXHR=function(cors,xhrOptions){return new XMLHttpRequest(xhrOptions)};var tmpxhr=createXHR();httpinvoke.requestTextOnly=!global.Uint8Array&&!tmpxhr.sendAsBinary;httpinvoke.cors="withCredentials"in tmpxhr;if(httpinvoke.cors){httpinvoke.corsRequestHeaders=true;httpinvoke.corsCredentials=true;httpinvoke.corsDELETE=true;httpinvoke.corsPATCH=true;httpinvoke.corsPUT=true;httpinvoke.corsHEAD=true;httpinvoke.corsStatus=true;return}}catch(err){}try{if(global.XDomainRequest===_undefined){createXHR=function(cors,xhrOptions){return new XMLHttpRequest(xhrOptions)};createXHR()}else{createXHR=function(cors,xhrOptions){return cors?new XDomainRequest:new XMLHttpRequest(xhrOptions)};createXHR(true);httpinvoke.cors=true;httpinvoke.corsResponseContentTypeOnly=true;httpinvoke.corsResponseTextOnly=true;httpinvoke.corsFineGrainedTimeouts=false}return}catch(err){}try{createXHR();return}catch(err){}var candidates=["Microsoft.XMLHTTP","Msxml2.XMLHTTP.6.0","Msxml2.XMLHTTP.3.0","Msxml2.XMLHTTP"];for(var i=candidates.length;i--;){try{createXHR=function(){return new ActiveXObject(candidates[i])};createXHR();httpinvoke.requestTextOnly=true;return}catch(err){}}createXHR=_undefined})();httpinvoke.PATCH=!!function(){try{createXHR().open("PATCH",location.href,true);return 1}catch(_){}}();httpinvoke._hooks=initHooks();httpinvoke.hook=addHook;httpinvoke.anonymousOption=function(){try{return createXHR(true,{mozAnon:true}).mozAnon===true&&createXHR(true,{mozAnon:false}).mozAnon===false&&createXHR(false,{mozAnon:true}).mozAnon===true&&createXHR(false,{mozAnon:false}).mozAnon===false}catch(_){return false}}();httpinvoke.anonymousByDefault=false;httpinvoke.systemOption=function(){try{return createXHR(true,{mozAnon:true,mozSystem:true}).mozSystem===true&&createXHR(true,{mozAnon:true,mozSystem:false}).mozSystem===false&&createXHR(false,{mozAnon:true,mozSystem:true}).mozSystem===true&&createXHR(false,{mozAnon:true,mozSystem:false}).mozSystem===false}catch(_){return false}}();httpinvoke.systemByDefault=false;httpinvoke.forbiddenInputHeaders=["proxy-*","sec-*","accept-charset","accept-encoding","access-control-request-headers","access-control-request-method","connection","content-length","content-transfer-encoding","cookie","cookie2","date","dnt","expect","host","keep-alive","origin","referer","te","trailer","transfer-encoding","upgrade","user-agent","via"];return httpinvoke};return build()});

@@ -124,22 +124,2 @@ var parseURL = require('url').parse;

// http://www.w3.org/TR/XMLHttpRequest/#the-setrequestheader()-method
var forbiddenInputHeaders = ['accept-charset', 'accept-encoding', 'access-control-request-headers', 'access-control-request-method', 'connection', 'content-length', 'content-transfer-encoding', 'cookie', 'cookie2', 'date', 'dnt', 'expect', 'host', 'keep-alive', 'origin', 'referer', 'te', 'trailer', 'transfer-encoding', 'upgrade', 'user-agent', 'via'];
var validateInputHeaders = function(headers) {
'use strict';
for(var header in headers) {
if(headers.hasOwnProperty(header)) {
var headerl = header.toLowerCase();
if(forbiddenInputHeaders.indexOf(headerl) >= 0) {
throw [14, header];
}
if(headerl.substr(0, 'proxy-'.length) === 'proxy-') {
throw [15, header];
}
if(headerl.substr(0, 'sec-'.length) === 'sec-') {
throw [16, header];
}
}
}
};
var copy = function(from, to) {

@@ -187,3 +167,3 @@ 'use strict';

/* jshint -W020 */
var hook, promise, failWithoutRequest, uploadProgressCb, downloadProgressCb, inputLength, inputHeaders, statusCb, outputHeaders, exposedHeaders, status, outputBinary, input, outputLength, outputConverter, protocol;
var hook, promise, failWithoutRequest, uploadProgressCb, downloadProgressCb, inputLength, inputHeaders, statusCb, outputHeaders, exposedHeaders, status, outputBinary, input, outputLength, outputConverter, protocol, anonymous, system;
hook = function(type, args) {

@@ -334,3 +314,11 @@ var hooks = httpinvoke._hooks[type];

var inputConverter;
inputHeaders = options.headers || {};
inputHeaders = (function(input) {
var output = {};
for(var i in input) {
if(input.hasOwnProperty(i)) {
output[i] = input[i];
}
}
return output;
})(options.headers || {});
outputHeaders = {};

@@ -340,2 +328,25 @@ exposedHeaders = options.corsExposedHeaders || [];

/*************** COMMON convert and validate parameters **************/
var validateInputHeaders = function(headers) {
var noSec = httpinvoke.forbiddenInputHeaders.indexOf('sec-*') >= 0;
var noProxy = httpinvoke.forbiddenInputHeaders.indexOf('proxy-*') >= 0;
for(var header in headers) {
if(headers.hasOwnProperty(header)) {
var headerl = header.toLowerCase();
if(httpinvoke.forbiddenInputHeaders.indexOf(headerl) >= 0) {
throw [14, header];
}
if(noProxy && headerl.substr(0, 'proxy-'.length) === 'proxy-') {
throw [15, header];
}
if(noSec && headerl.substr(0, 'sec-'.length) === 'sec-') {
throw [16, header];
}
}
}
};
try {
validateInputHeaders(inputHeaders);
} catch(err) {
return failWithoutRequest(cb, err);
}
if(!httpinvoke.relativeURLs && !absoluteURLRegExp.test(url)) {

@@ -348,2 +359,7 @@ return failWithoutRequest(cb, [26, url]);

}
anonymous = typeof options.anonymous === 'undefined' ? httpinvoke.anonymousByDefault : options.anonymous;
system = typeof options.system === 'undefined' ? httpinvoke.systemByDefault : options.system;
if(typeof options.system !== 'undefined' && system) {
anonymous = true;
}
var partialOutputMode = options.partialOutputMode || 'disabled';

@@ -456,7 +472,2 @@ if(partialOutputMode.indexOf(',') >= 0 || ',disabled,chunked,joined,'.indexOf(',' + partialOutputMode + ',') < 0) {

/*************** initialize helper variables **************/
try {
validateInputHeaders(inputHeaders);
} catch(err) {
return failWithoutRequest(cb, err);
}
inputHeaders = copy(inputHeaders, {});

@@ -659,2 +670,7 @@ if(typeof input !== 'undefined') {

httpinvoke.relativeURLs = false;
httpinvoke.anonymousOption = false;
httpinvoke.anonymousByDefault = true;
httpinvoke.systemOption = false;
httpinvoke.systemByDefault = true;
httpinvoke.forbiddenInputHeaders = [];
httpinvoke._hooks = initHooks();

@@ -661,0 +677,0 @@ httpinvoke.hook = addHook;

@@ -21,2 +21,8 @@ /* jshint -W020 */

host: location.hostname,
setCookie: function(cookie) {
'use strict';
if(global.document) {
global.document.cookie = cookie;
}
},
port: Number(location.port) || (location.protocol === 'https:' ? 443 : 80),

@@ -23,0 +29,0 @@ /* # Statuses from RFC 2616

{
"name": "httpinvoke",
"version": "1.3.7",
"version": "1.4.0",
"description": "A no-dependencies HTTP client library for browsers and Node.js with a promise-based or Node.js-style callback-based API to progress events, text and binary file upload and download, partial response body, request and response headers, status code.",

@@ -54,3 +54,4 @@ "license": "MIT",

"karma-mocha": "0.1.x",
"uglify-js": "2.4.x"
"uglify-js": "2.4.x",
"cookie": "0.1.x"
},

@@ -57,0 +58,0 @@ "scripts": {

@@ -84,7 +84,11 @@ /* jshint -W030 */

var urlPartitioningRegExp = /^([\w.+-]+:)(?:\/\/([^\/?#:]*)(?::(\d+)|)|)/;
var urlPartitioningRegExp = /^(?:([a-z][a-z0-9.+-]*:)|)(?:\/\/([^\/?#:]*)(?::(\d+)|)|)/;
var isCrossDomain = function(location, url) {
if(!absoluteURLRegExp.test(url) && url.substr(0, 2) !== '//') {
return false;
}
url = urlPartitioningRegExp.exec(url.toLowerCase());
location = urlPartitioningRegExp.exec(location.toLowerCase()) || [];
return !!(url && (url[1] !== location[1] || url[2] !== location[2] || (url[3] || (url[1] === 'http:' ? '80' : '443')) !== (location[3] || (location[1] === 'http:' ? '80' : '443'))));
var locationPort = location[3] || (location[1] === 'http:' ? '80' : '443');
return !!((url[1] && url[1] !== location[1]) || url[2] !== location[2] || (url[3] || (url[1] ? (url[1] === 'http:' ? '80' : '443') : locationPort)) !== locationPort);
};

@@ -96,3 +100,3 @@

/* jshint unused:true */
var hook, promise, failWithoutRequest, uploadProgressCb, downloadProgressCb, inputLength, inputHeaders, statusCb, outputHeaders, exposedHeaders, status, outputBinary, input, outputLength, outputConverter, partialOutputMode, protocol;
var hook, promise, failWithoutRequest, uploadProgressCb, downloadProgressCb, inputLength, inputHeaders, statusCb, outputHeaders, exposedHeaders, status, outputBinary, input, outputLength, outputConverter, partialOutputMode, protocol, anonymous, system;
/* jshint unused:false */

@@ -163,3 +167,6 @@ /*************** initialize helper variables **************/

}
xhr = createXHR(crossDomain);
xhr = createXHR(crossDomain, {
mozAnon: anonymous,
mozSystem: system
});
try {

@@ -170,4 +177,6 @@ xhr.open(method, url, true);

}
if(options.corsCredentials && httpinvoke.corsCredentials && typeof xhr.withCredentials === 'boolean') {
xhr.withCredentials = true;
if(httpinvoke.corsCredentials) {
if((typeof options.anonymous !== 'undefined' && !anonymous) || (options.corsCredentials && typeof xhr.withCredentials === 'boolean')) {
xhr.withCredentials = true;
}
}

@@ -747,4 +756,4 @@ if(crossDomain && options.corsOriginHeader) {

try {
createXHR = function() {
return new XMLHttpRequest();
createXHR = function(cors, xhrOptions) {
return new XMLHttpRequest(xhrOptions);
};

@@ -768,9 +777,9 @@ var tmpxhr = createXHR();

if(global.XDomainRequest === _undefined) {
createXHR = function() {
return new XMLHttpRequest();
createXHR = function(cors, xhrOptions) {
return new XMLHttpRequest(xhrOptions);
};
createXHR();
} else {
createXHR = function(cors) {
return cors ? new XDomainRequest() : new XMLHttpRequest();
createXHR = function(cors, xhrOptions) {
return cors ? new XDomainRequest() : new XMLHttpRequest(xhrOptions);
};

@@ -816,2 +825,26 @@ createXHR(true);

httpinvoke.hook = addHook;
httpinvoke.anonymousOption = (function() {
try {
return createXHR(true, {mozAnon: true}).mozAnon === true &&
createXHR(true, {mozAnon: false}).mozAnon === false &&
createXHR(false, {mozAnon: true}).mozAnon === true &&
createXHR(false, {mozAnon: false}).mozAnon === false;
} catch(_) {
return false;
}
})();
httpinvoke.anonymousByDefault = false;
httpinvoke.systemOption = (function() {
try {
return createXHR(true, {mozAnon: true, mozSystem: true}).mozSystem === true &&
createXHR(true, {mozAnon: true, mozSystem: false}).mozSystem === false &&
createXHR(false, {mozAnon: true, mozSystem: true}).mozSystem === true &&
createXHR(false, {mozAnon: true, mozSystem: false}).mozSystem === false;
} catch(_) {
return false;
}
})();
httpinvoke.systemByDefault = false;
// http://www.w3.org/TR/XMLHttpRequest/#the-setrequestheader()-method
httpinvoke.forbiddenInputHeaders = ['proxy-*', 'sec-*', 'accept-charset', 'accept-encoding', 'access-control-request-headers', 'access-control-request-method', 'connection', 'content-length', 'content-transfer-encoding', 'cookie', 'cookie2', 'date', 'dnt', 'expect', 'host', 'keep-alive', 'origin', 'referer', 'te', 'trailer', 'transfer-encoding', 'upgrade', 'user-agent', 'via'];

@@ -818,0 +851,0 @@ return httpinvoke;

@@ -6,3 +6,3 @@ /* global httpinvoke, url, method, options, cb */

/* jshint -W020 */
var hook, promise, failWithoutRequest, uploadProgressCb, downloadProgressCb, inputLength, inputHeaders, statusCb, outputHeaders, exposedHeaders, status, outputBinary, input, outputLength, outputConverter, protocol;
var hook, promise, failWithoutRequest, uploadProgressCb, downloadProgressCb, inputLength, inputHeaders, statusCb, outputHeaders, exposedHeaders, status, outputBinary, input, outputLength, outputConverter, protocol, anonymous, system;
hook = function(type, args) {

@@ -153,3 +153,11 @@ var hooks = httpinvoke._hooks[type];

var inputConverter;
inputHeaders = options.headers || {};
inputHeaders = (function(input) {
var output = {};
for(var i in input) {
if(input.hasOwnProperty(i)) {
output[i] = input[i];
}
}
return output;
})(options.headers || {});
outputHeaders = {};

@@ -159,2 +167,25 @@ exposedHeaders = options.corsExposedHeaders || [];

/*************** COMMON convert and validate parameters **************/
var validateInputHeaders = function(headers) {
var noSec = httpinvoke.forbiddenInputHeaders.indexOf('sec-*') >= 0;
var noProxy = httpinvoke.forbiddenInputHeaders.indexOf('proxy-*') >= 0;
for(var header in headers) {
if(headers.hasOwnProperty(header)) {
var headerl = header.toLowerCase();
if(httpinvoke.forbiddenInputHeaders.indexOf(headerl) >= 0) {
throw [14, header];
}
if(noProxy && headerl.substr(0, 'proxy-'.length) === 'proxy-') {
throw [15, header];
}
if(noSec && headerl.substr(0, 'sec-'.length) === 'sec-') {
throw [16, header];
}
}
}
};
try {
validateInputHeaders(inputHeaders);
} catch(err) {
return failWithoutRequest(cb, err);
}
if(!httpinvoke.relativeURLs && !absoluteURLRegExp.test(url)) {

@@ -167,2 +198,7 @@ return failWithoutRequest(cb, [26, url]);

}
anonymous = typeof options.anonymous === 'undefined' ? httpinvoke.anonymousByDefault : options.anonymous;
system = typeof options.system === 'undefined' ? httpinvoke.systemByDefault : options.system;
if(typeof options.system !== 'undefined' && system) {
anonymous = true;
}
var partialOutputMode = options.partialOutputMode || 'disabled';

@@ -169,0 +205,0 @@ if(partialOutputMode.indexOf(',') >= 0 || ',disabled,chunked,joined,'.indexOf(',' + partialOutputMode + ',') < 0) {

@@ -12,22 +12,2 @@ var parseURL = require('url').parse;

// http://www.w3.org/TR/XMLHttpRequest/#the-setrequestheader()-method
var forbiddenInputHeaders = ['accept-charset', 'accept-encoding', 'access-control-request-headers', 'access-control-request-method', 'connection', 'content-length', 'content-transfer-encoding', 'cookie', 'cookie2', 'date', 'dnt', 'expect', 'host', 'keep-alive', 'origin', 'referer', 'te', 'trailer', 'transfer-encoding', 'upgrade', 'user-agent', 'via'];
var validateInputHeaders = function(headers) {
'use strict';
for(var header in headers) {
if(headers.hasOwnProperty(header)) {
var headerl = header.toLowerCase();
if(forbiddenInputHeaders.indexOf(headerl) >= 0) {
throw [14, header];
}
if(headerl.substr(0, 'proxy-'.length) === 'proxy-') {
throw [15, header];
}
if(headerl.substr(0, 'sec-'.length) === 'sec-') {
throw [16, header];
}
}
}
};
var copy = function(from, to) {

@@ -70,10 +50,5 @@ 'use strict';

/* jshint unused:true */
var hook, promise, failWithoutRequest, uploadProgressCb, downloadProgressCb, inputLength, inputHeaders, statusCb, outputHeaders, exposedHeaders, status, outputBinary, input, outputLength, outputConverter, partialOutputMode, protocol;
var hook, promise, failWithoutRequest, uploadProgressCb, downloadProgressCb, inputLength, inputHeaders, statusCb, outputHeaders, exposedHeaders, status, outputBinary, input, outputLength, outputConverter, partialOutputMode, protocol, anonymous, system;
/* jshint unused:false */
/*************** initialize helper variables **************/
try {
validateInputHeaders(inputHeaders);
} catch(err) {
return failWithoutRequest(cb, err);
}
inputHeaders = copy(inputHeaders, {});

@@ -276,2 +251,7 @@ if(typeof input !== 'undefined') {

httpinvoke.relativeURLs = false;
httpinvoke.anonymousOption = false;
httpinvoke.anonymousByDefault = true;
httpinvoke.systemOption = false;
httpinvoke.systemByDefault = true;
httpinvoke.forbiddenInputHeaders = [];
httpinvoke._hooks = initHooks();

@@ -278,0 +258,0 @@ httpinvoke.hook = addHook;

@@ -11,4 +11,4 @@ var cfg = require('../dummyserver-config');

});
it('does not throw if relativeURLs flag is false and url is protocol-relative', function(done) {
httpinvoke(cfg.url.substr(0, cfg.url.indexOf(':') + 1), done);
it('does not throw if relativeURLs flag is true and url is protocol-relative', function(done) {
httpinvoke(cfg.url.substr(cfg.url.indexOf(':') + 1), done);
});

@@ -15,0 +15,0 @@ } else {

@@ -107,2 +107,9 @@ var cfg = require('../dummyserver-config');

});
if(httpinvoke.relativeURLs && !httpinvoke.cors) {
it('throws error #18 if given protocol-relative url with cross-domain hostname and cors flag is false', function(done) {
httpinvoke('//example.org/foo', function(err) {
done(err && err.message === 'Error code #18. See https://github.com/jakutis/httpinvoke#error-codes' ? null : new Error('expected error #18'));
});
});
}
});
var cfg = require('../dummyserver-config');
var httpinvoke = require('../httpinvoke-node');
// http://www.w3.org/TR/XMLHttpRequest/#the-setrequestheader()-method
var forbiddenInputHeaders = ['Accept-Charset', 'Accept-Encoding', 'Access-Control-Request-Headers', 'Access-Control-Request-Method', 'Connection', 'Content-Length', 'Content-Transfer-Encoding', 'Cookie', 'Cookie2', 'Date', 'DNT', 'Expect', 'Host', 'Keep-Alive', 'Origin', 'Referer', 'TE', 'Trailer', 'Transfer-Encoding', 'Upgrade', 'User-Agent', 'Via', 'Proxy-Authorization', 'Sec-From'];
describe('"headers" option', function() {

@@ -33,3 +30,3 @@ 'use strict';

});
forbiddenInputHeaders.forEach(function(header) {
httpinvoke.forbiddenInputHeaders.forEach(function(header) {
it('immediately finishes with error, when a "' + header + '" header is tried to be set', function(done) {

@@ -36,0 +33,0 @@ var headers = {};

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc