Skip to content

Instantly share code, notes, and snippets.

@dhritzkiv
Created August 19, 2015 19:53
Show Gist options
  • Save dhritzkiv/2a6910992b2fff56c570 to your computer and use it in GitHub Desktop.
Save dhritzkiv/2a6910992b2fff56c570 to your computer and use it in GitHub Desktop.
requirebin sketch
var sync = require("ampersand-sync");
var xhr = require("xhr");
var options = {
url: 'http://jsonplaceholder.typicode.com/posts',//a test endpoint
headers: {
"Content-Type": "application/json"
},
json: {
foo: "bar"
},
method: "POST"
};
var request = sync("create", null, options);
var request2 = xhr(options, function() {});
console.log(request.headers);//note the duplicate "Content-Type" headers (different cases)
//looking in the network tab, the request headers show the content-type as "application/json, application/json".
console.log(request2.headers);
//here, the headers are normalized
//looking in the network tab, the request headers show the content-type as "application/json; charset=utf-8"
require=function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s}({1:[function(require,module,exports){if(typeof window!=="undefined"){window.ampersand=window.ampersand||{};window.ampersand["ampersand-sync"]=window.ampersand["ampersand-sync"]||[];window.ampersand["ampersand-sync"].push("4.0.0")}var result=require("lodash.result");var defaults=require("lodash.defaults");var includes=require("lodash.includes");var assign=require("lodash.assign");var qs=require("qs");module.exports=function(xhr){var urlError=function(){throw new Error('A "url" property or function must be specified')};var methodMap={create:"POST",update:"PUT",patch:"PATCH","delete":"DELETE",read:"GET"};return function(method,model,optionsInput){var options=assign({},optionsInput);var type=methodMap[method];var headers={};defaults(options||(options={}),{emulateHTTP:false,emulateJSON:false,xhrImplementation:xhr});var params={type:type};var ajaxConfig=result(model,"ajaxConfig")||{};var key;if(ajaxConfig.headers){for(key in ajaxConfig.headers){headers[key.toLowerCase()]=ajaxConfig.headers[key]}}if(options.headers){for(key in options.headers){headers[key.toLowerCase()]=options.headers[key]}delete options.headers}assign(params,ajaxConfig);params.headers=headers;if(!options.url){options.url=result(model,"url")||urlError()}if(options.data==null&&model&&(method==="create"||method==="update"||method==="patch")){params.json=options.attrs||model.toJSON(options)}if(options.data&&type==="GET"){options.url+=includes(options.url,"?")?"&":"?";options.url+=qs.stringify(options.data);delete options.data}if(options.emulateJSON){params.headers["content-type"]="application/x-www-form-urlencoded";params.body=params.json?{model:params.json}:{};delete params.json}if(options.emulateHTTP&&(type==="PUT"||type==="DELETE"||type==="PATCH")){params.type="POST";if(options.emulateJSON)params.body._method=type;params.headers["x-http-method-override"]=type}if(options.emulateJSON){params.body=qs.stringify(params.body)}if(ajaxConfig.xhrFields){var beforeSend=ajaxConfig.beforeSend;params.beforeSend=function(req){assign(req,ajaxConfig.xhrFields);if(beforeSend)return beforeSend.apply(this,arguments)};params.xhrFields=ajaxConfig.xhrFields}params.method=params.type;var ajaxSettings=assign(params,options);var request=options.xhr=options.xhrImplementation(ajaxSettings,function(err,resp,body){if(err||resp.statusCode>=400){if(options.error){try{body=JSON.parse(body)}catch(e){}var message=err?err.message:body||"HTTP"+resp.statusCode;options.error(resp,"error",message)}}else{if(typeof body==="string"&&(!params.headers.accept||params.headers.accept.indexOf("application/json")===0)){try{body=JSON.parse(body)}catch(err){if(options.error)options.error(resp,"error",err.message);if(options.always)options.always(err,resp,body);return}}if(options.success)options.success(body,"success",resp)}if(options.always)options.always(err,resp,body)});if(model)model.trigger("request",model,request,optionsInput,ajaxSettings);request.ajaxSettings=ajaxSettings;return request}}},{"lodash.assign":2,"lodash.defaults":13,"lodash.includes":15,"lodash.result":24,qs:30}],2:[function(require,module,exports){var baseAssign=require("lodash._baseassign"),createAssigner=require("lodash._createassigner"),keys=require("lodash.keys");function assignWith(object,source,customizer){var index=-1,props=keys(source),length=props.length;while(++index<length){var key=props[index],value=object[key],result=customizer(value,source[key],key,object,source);if((result===result?result!==value:value===value)||value===undefined&&!(key in object)){object[key]=result}}return object}var assign=createAssigner(function(object,source,customizer){return customizer?assignWith(object,source,customizer):baseAssign(object,source)});module.exports=assign},{"lodash._baseassign":3,"lodash._createassigner":5,"lodash.keys":9}],3:[function(require,module,exports){var baseCopy=require("lodash._basecopy"),keys=require("lodash.keys");function baseAssign(object,source){return source==null?object:baseCopy(source,keys(source),object)}module.exports=baseAssign},{"lodash._basecopy":4,"lodash.keys":9}],4:[function(require,module,exports){function baseCopy(source,props,object){object||(object={});var index=-1,length=props.length;while(++index<length){var key=props[index];object[key]=source[key]}return object}module.exports=baseCopy},{}],5:[function(require,module,exports){var bindCallback=require("lodash._bindcallback"),isIterateeCall=require("lodash._isiterateecall"),restParam=require("lodash.restparam");function createAssigner(assigner){return restParam(function(object,sources){var index=-1,length=object==null?0:sources.length,customizer=length>2?sources[length-2]:undefined,guard=length>2?sources[2]:undefined,thisArg=length>1?sources[length-1]:undefined;if(typeof customizer=="function"){customizer=bindCallback(customizer,thisArg,5);length-=2}else{customizer=typeof thisArg=="function"?thisArg:undefined;length-=customizer?1:0}if(guard&&isIterateeCall(sources[0],sources[1],guard)){customizer=length<3?undefined:customizer;length=1}while(++index<length){var source=sources[index];if(source){assigner(object,source,customizer)}}return object})}module.exports=createAssigner},{"lodash._bindcallback":6,"lodash._isiterateecall":7,"lodash.restparam":8}],6:[function(require,module,exports){function bindCallback(func,thisArg,argCount){if(typeof func!="function"){return identity}if(thisArg===undefined){return func}switch(argCount){case 1:return function(value){return func.call(thisArg,value)};case 3:return function(value,index,collection){return func.call(thisArg,value,index,collection)};case 4:return function(accumulator,value,index,collection){return func.call(thisArg,accumulator,value,index,collection)};case 5:return function(value,other,key,object,source){return func.call(thisArg,value,other,key,object,source)}}return function(){return func.apply(thisArg,arguments)}}function identity(value){return value}module.exports=bindCallback},{}],7:[function(require,module,exports){var reIsUint=/^\d+$/;var MAX_SAFE_INTEGER=9007199254740991;function baseProperty(key){return function(object){return object==null?undefined:object[key]}}var getLength=baseProperty("length");function isArrayLike(value){return value!=null&&isLength(getLength(value))}function isIndex(value,length){value=typeof value=="number"||reIsUint.test(value)?+value:-1;length=length==null?MAX_SAFE_INTEGER:length;return value>-1&&value%1==0&&value<length}function isIterateeCall(value,index,object){if(!isObject(object)){return false}var type=typeof index;if(type=="number"?isArrayLike(object)&&isIndex(index,object.length):type=="string"&&index in object){var other=object[index];return value===value?value===other:other!==other}return false}function isLength(value){return typeof value=="number"&&value>-1&&value%1==0&&value<=MAX_SAFE_INTEGER}function isObject(value){var type=typeof value;return!!value&&(type=="object"||type=="function")}module.exports=isIterateeCall},{}],8:[function(require,module,exports){var FUNC_ERROR_TEXT="Expected a function";var nativeMax=Math.max;function restParam(func,start){if(typeof func!="function"){throw new TypeError(FUNC_ERROR_TEXT)}start=nativeMax(start===undefined?func.length-1:+start||0,0);return function(){var args=arguments,index=-1,length=nativeMax(args.length-start,0),rest=Array(length);while(++index<length){rest[index]=args[start+index]}switch(start){case 0:return func.call(this,rest);case 1:return func.call(this,args[0],rest);case 2:return func.call(this,args[0],args[1],rest)}var otherArgs=Array(start+1);index=-1;while(++index<start){otherArgs[index]=args[index]}otherArgs[start]=rest;return func.apply(this,otherArgs)}}module.exports=restParam},{}],9:[function(require,module,exports){var getNative=require("lodash._getnative"),isArguments=require("lodash.isarguments"),isArray=require("lodash.isarray");var reIsUint=/^\d+$/;var objectProto=Object.prototype;var hasOwnProperty=objectProto.hasOwnProperty;var nativeKeys=getNative(Object,"keys");var MAX_SAFE_INTEGER=9007199254740991;function baseProperty(key){return function(object){return object==null?undefined:object[key]}}var getLength=baseProperty("length");function isArrayLike(value){return value!=null&&isLength(getLength(value))}function isIndex(value,length){value=typeof value=="number"||reIsUint.test(value)?+value:-1;length=length==null?MAX_SAFE_INTEGER:length;return value>-1&&value%1==0&&value<length}function isLength(value){return typeof value=="number"&&value>-1&&value%1==0&&value<=MAX_SAFE_INTEGER}function shimKeys(object){var props=keysIn(object),propsLength=props.length,length=propsLength&&object.length;var allowIndexes=!!length&&isLength(length)&&(isArray(object)||isArguments(object));var index=-1,result=[];while(++index<propsLength){var key=props[index];if(allowIndexes&&isIndex(key,length)||hasOwnProperty.call(object,key)){result.push(key)}}return result}function isObject(value){var type=typeof value;return!!value&&(type=="object"||type=="function")}var keys=!nativeKeys?shimKeys:function(object){var Ctor=object==null?undefined:object.constructor;if(typeof Ctor=="function"&&Ctor.prototype===object||typeof object!="function"&&isArrayLike(object)){return shimKeys(object)}return isObject(object)?nativeKeys(object):[]};function keysIn(object){if(object==null){return[]}if(!isObject(object)){object=Object(object)}var length=object.length;length=length&&isLength(length)&&(isArray(object)||isArguments(object))&&length||0;var Ctor=object.constructor,index=-1,isProto=typeof Ctor=="function"&&Ctor.prototype===object,result=Array(length),skipIndexes=length>0;while(++index<length){result[index]=index+""}for(var key in object){if(!(skipIndexes&&isIndex(key,length))&&!(key=="constructor"&&(isProto||!hasOwnProperty.call(object,key)))){result.push(key)}}return result}module.exports=keys},{"lodash._getnative":10,"lodash.isarguments":11,"lodash.isarray":12}],10:[function(require,module,exports){var funcTag="[object Function]";var reIsHostCtor=/^\[object .+?Constructor\]$/;function isObjectLike(value){return!!value&&typeof value=="object"}var objectProto=Object.prototype;var fnToString=Function.prototype.toString;var hasOwnProperty=objectProto.hasOwnProperty;var objToString=objectProto.toString;var reIsNative=RegExp("^"+fnToString.call(hasOwnProperty).replace(/[\\^$.*+?()[\]{}|]/g,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");function getNative(object,key){var value=object==null?undefined:object[key];return isNative(value)?value:undefined}function isFunction(value){return isObject(value)&&objToString.call(value)==funcTag}function isObject(value){var type=typeof value;return!!value&&(type=="object"||type=="function")}function isNative(value){if(value==null){return false}if(isFunction(value)){return reIsNative.test(fnToString.call(value))}return isObjectLike(value)&&reIsHostCtor.test(value)}module.exports=getNative},{}],11:[function(require,module,exports){function isObjectLike(value){return!!value&&typeof value=="object"}var objectProto=Object.prototype;var hasOwnProperty=objectProto.hasOwnProperty;var propertyIsEnumerable=objectProto.propertyIsEnumerable;var MAX_SAFE_INTEGER=9007199254740991;function baseProperty(key){return function(object){return object==null?undefined:object[key]}}var getLength=baseProperty("length");function isArrayLike(value){return value!=null&&isLength(getLength(value))}function isLength(value){return typeof value=="number"&&value>-1&&value%1==0&&value<=MAX_SAFE_INTEGER}function isArguments(value){return isObjectLike(value)&&isArrayLike(value)&&hasOwnProperty.call(value,"callee")&&!propertyIsEnumerable.call(value,"callee")}module.exports=isArguments},{}],12:[function(require,module,exports){var arrayTag="[object Array]",funcTag="[object Function]";var reIsHostCtor=/^\[object .+?Constructor\]$/;function isObjectLike(value){return!!value&&typeof value=="object"}var objectProto=Object.prototype;var fnToString=Function.prototype.toString;var hasOwnProperty=objectProto.hasOwnProperty;var objToString=objectProto.toString;var reIsNative=RegExp("^"+fnToString.call(hasOwnProperty).replace(/[\\^$.*+?()[\]{}|]/g,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");var nativeIsArray=getNative(Array,"isArray");var MAX_SAFE_INTEGER=9007199254740991;function getNative(object,key){var value=object==null?undefined:object[key];return isNative(value)?value:undefined}function isLength(value){return typeof value=="number"&&value>-1&&value%1==0&&value<=MAX_SAFE_INTEGER}var isArray=nativeIsArray||function(value){return isObjectLike(value)&&isLength(value.length)&&objToString.call(value)==arrayTag};function isFunction(value){return isObject(value)&&objToString.call(value)==funcTag}function isObject(value){var type=typeof value;return!!value&&(type=="object"||type=="function")}function isNative(value){if(value==null){return false}if(isFunction(value)){return reIsNative.test(fnToString.call(value))}return isObjectLike(value)&&reIsHostCtor.test(value)}module.exports=isArray},{}],13:[function(require,module,exports){var assign=require("lodash.assign"),restParam=require("lodash.restparam");function assignDefaults(objectValue,sourceValue){return objectValue===undefined?sourceValue:objectValue}function createDefaults(assigner,customizer){return restParam(function(args){var object=args[0];if(object==null){return object}args.push(customizer);return assigner.apply(undefined,args)})}var defaults=createDefaults(assign,assignDefaults);module.exports=defaults},{"lodash.assign":2,"lodash.restparam":14}],14:[function(require,module,exports){arguments[4][8][0].apply(exports,arguments)},{dup:8}],15:[function(require,module,exports){var baseIndexOf=require("lodash._baseindexof"),baseValues=require("lodash._basevalues"),isIterateeCall=require("lodash._isiterateecall"),isArray=require("lodash.isarray"),isString=require("lodash.isstring"),keys=require("lodash.keys");var nativeMax=Math.max;var MAX_SAFE_INTEGER=9007199254740991;function baseProperty(key){return function(object){return object==null?undefined:object[key]}}var getLength=baseProperty("length");function isLength(value){return typeof value=="number"&&value>-1&&value%1==0&&value<=MAX_SAFE_INTEGER}function includes(collection,target,fromIndex,guard){var length=collection?getLength(collection):0;if(!isLength(length)){collection=values(collection);length=collection.length}if(typeof fromIndex!="number"||guard&&isIterateeCall(target,fromIndex,guard)){fromIndex=0}else{fromIndex=fromIndex<0?nativeMax(length+fromIndex,0):fromIndex||0}return typeof collection=="string"||!isArray(collection)&&isString(collection)?fromIndex<=length&&collection.indexOf(target,fromIndex)>-1:!!length&&baseIndexOf(collection,target,fromIndex)>-1}function values(object){return baseValues(object,keys(object))}module.exports=includes},{"lodash._baseindexof":16,"lodash._basevalues":17,"lodash._isiterateecall":18,"lodash.isarray":19,"lodash.isstring":20,"lodash.keys":21}],16:[function(require,module,exports){function baseIndexOf(array,value,fromIndex){if(value!==value){return indexOfNaN(array,fromIndex)}var index=fromIndex-1,length=array.length;while(++index<length){if(array[index]===value){return index}}return-1}function indexOfNaN(array,fromIndex,fromRight){var length=array.length,index=fromIndex+(fromRight?0:-1);while(fromRight?index--:++index<length){var other=array[index];if(other!==other){return index}}return-1}module.exports=baseIndexOf},{}],17:[function(require,module,exports){function baseValues(object,props){var index=-1,length=props.length,result=Array(length);while(++index<length){result[index]=object[props[index]]}return result}module.exports=baseValues},{}],18:[function(require,module,exports){arguments[4][7][0].apply(exports,arguments)},{dup:7}],19:[function(require,module,exports){arguments[4][12][0].apply(exports,arguments)},{dup:12}],20:[function(require,module,exports){var stringTag="[object String]";function isObjectLike(value){return!!value&&typeof value=="object"}var objectProto=Object.prototype;var objToString=objectProto.toString;function isString(value){return typeof value=="string"||isObjectLike(value)&&objToString.call(value)==stringTag}module.exports=isString},{}],21:[function(require,module,exports){arguments[4][9][0].apply(exports,arguments)},{dup:9,"lodash._getnative":22,"lodash.isarguments":23,"lodash.isarray":19}],22:[function(require,module,exports){arguments[4][10][0].apply(exports,arguments)},{dup:10}],23:[function(require,module,exports){arguments[4][11][0].apply(exports,arguments)},{dup:11}],24:[function(require,module,exports){var baseGet=require("lodash._baseget"),baseSlice=require("lodash._baseslice"),toPath=require("lodash._topath"),isArray=require("lodash.isarray"),isFunction=require("lodash.isfunction");var reIsDeepProp=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\n\\]|\\.)*?\1)\]/,reIsPlainProp=/^\w*$/;function isKey(value,object){var type=typeof value;if(type=="string"&&reIsPlainProp.test(value)||type=="number"){return true}if(isArray(value)){return false}var result=!reIsDeepProp.test(value);return result||object!=null&&value in toObject(object)}function toObject(value){return isObject(value)?value:Object(value)}function last(array){var length=array?array.length:0;return length?array[length-1]:undefined}function isObject(value){var type=typeof value;return!!value&&(type=="object"||type=="function")}function result(object,path,defaultValue){var result=object==null?undefined:object[path];if(result===undefined){if(object!=null&&!isKey(path,object)){path=toPath(path);object=path.length==1?object:baseGet(object,baseSlice(path,0,-1));result=object==null?undefined:object[last(path)]}result=result===undefined?defaultValue:result}return isFunction(result)?result.call(object):result}module.exports=result},{"lodash._baseget":25,"lodash._baseslice":26,"lodash._topath":27,"lodash.isarray":28,"lodash.isfunction":29}],25:[function(require,module,exports){function baseGet(object,path,pathKey){if(object==null){return}if(pathKey!==undefined&&pathKey in toObject(object)){path=[pathKey]}var index=0,length=path.length;while(object!=null&&index<length){object=object[path[index++]]}return index&&index==length?object:undefined}function toObject(value){return isObject(value)?value:Object(value)}function isObject(value){var type=typeof value;return!!value&&(type=="object"||type=="function")}module.exports=baseGet},{}],26:[function(require,module,exports){function baseSlice(array,start,end){var index=-1,length=array.length;start=start==null?0:+start||0;if(start<0){start=-start>length?0:length+start}end=end===undefined||end>length?length:+end||0;if(end<0){end+=length}length=start>end?0:end-start>>>0;start>>>=0;var result=Array(length);while(++index<length){result[index]=array[index+start]}return result}module.exports=baseSlice},{}],27:[function(require,module,exports){var isArray=require("lodash.isarray");var rePropName=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\n\\]|\\.)*?)\2)\]/g;var reEscapeChar=/\\(\\)?/g;function baseToString(value){return value==null?"":value+""}function toPath(value){if(isArray(value)){return value}var result=[];baseToString(value).replace(rePropName,function(match,number,quote,string){result.push(quote?string.replace(reEscapeChar,"$1"):number||match)});return result}module.exports=toPath},{"lodash.isarray":28}],28:[function(require,module,exports){arguments[4][12][0].apply(exports,arguments)},{dup:12}],29:[function(require,module,exports){var funcTag="[object Function]";var objectProto=Object.prototype;var objToString=objectProto.toString;function isFunction(value){return isObject(value)&&objToString.call(value)==funcTag}function isObject(value){var type=typeof value;return!!value&&(type=="object"||type=="function")}module.exports=isFunction},{}],30:[function(require,module,exports){var Stringify=require("./stringify");var Parse=require("./parse");var internals={};module.exports={stringify:Stringify,parse:Parse}},{"./parse":31,"./stringify":32}],31:[function(require,module,exports){var Utils=require("./utils");var internals={delimiter:"&",depth:5,arrayLimit:20,parameterLimit:1e3,strictNullHandling:false,plainObjects:false,allowPrototypes:false};internals.parseValues=function(str,options){var obj={};var parts=str.split(options.delimiter,options.parameterLimit===Infinity?undefined:options.parameterLimit);for(var i=0,il=parts.length;i<il;++i){var part=parts[i];var pos=part.indexOf("]=")===-1?part.indexOf("="):part.indexOf("]=")+1;if(pos===-1){obj[Utils.decode(part)]="";if(options.strictNullHandling){obj[Utils.decode(part)]=null}}else{var key=Utils.decode(part.slice(0,pos));var val=Utils.decode(part.slice(pos+1));if(!Object.prototype.hasOwnProperty.call(obj,key)){obj[key]=val}else{obj[key]=[].concat(obj[key]).concat(val)}}}return obj};internals.parseObject=function(chain,val,options){if(!chain.length){return val}var root=chain.shift();var obj;if(root==="[]"){obj=[];obj=obj.concat(internals.parseObject(chain,val,options))}else{obj=options.plainObjects?Object.create(null):{};var cleanRoot=root[0]==="["&&root[root.length-1]==="]"?root.slice(1,root.length-1):root;var index=parseInt(cleanRoot,10);var indexString=""+index;if(!isNaN(index)&&root!==cleanRoot&&indexString===cleanRoot&&index>=0&&(options.parseArrays&&index<=options.arrayLimit)){obj=[];obj[index]=internals.parseObject(chain,val,options)}else{obj[cleanRoot]=internals.parseObject(chain,val,options)}}return obj};internals.parseKeys=function(key,val,options){if(!key){return}if(options.allowDots){key=key.replace(/\.([^\.\[]+)/g,"[$1]")}var parent=/^([^\[\]]*)/;var child=/(\[[^\[\]]*\])/g;var segment=parent.exec(key);var keys=[];if(segment[1]){if(!options.plainObjects&&Object.prototype.hasOwnProperty(segment[1])){if(!options.allowPrototypes){return}}keys.push(segment[1])}var i=0;while((segment=child.exec(key))!==null&&i<options.depth){++i;if(!options.plainObjects&&Object.prototype.hasOwnProperty(segment[1].replace(/\[|\]/g,""))){if(!options.allowPrototypes){continue}}keys.push(segment[1])}if(segment){keys.push("["+key.slice(segment.index)+"]")}return internals.parseObject(keys,val,options)};module.exports=function(str,options){options=options||{};options.delimiter=typeof options.delimiter==="string"||Utils.isRegExp(options.delimiter)?options.delimiter:internals.delimiter;options.depth=typeof options.depth==="number"?options.depth:internals.depth;options.arrayLimit=typeof options.arrayLimit==="number"?options.arrayLimit:internals.arrayLimit;options.parseArrays=options.parseArrays!==false;options.allowDots=options.allowDots!==false;options.plainObjects=typeof options.plainObjects==="boolean"?options.plainObjects:internals.plainObjects;options.allowPrototypes=typeof options.allowPrototypes==="boolean"?options.allowPrototypes:internals.allowPrototypes;options.parameterLimit=typeof options.parameterLimit==="number"?options.parameterLimit:internals.parameterLimit;options.strictNullHandling=typeof options.strictNullHandling==="boolean"?options.strictNullHandling:internals.strictNullHandling;if(str===""||str===null||typeof str==="undefined"){return options.plainObjects?Object.create(null):{}}var tempObj=typeof str==="string"?internals.parseValues(str,options):str;var obj=options.plainObjects?Object.create(null):{};var keys=Object.keys(tempObj);for(var i=0,il=keys.length;i<il;++i){var key=keys[i];var newObj=internals.parseKeys(key,tempObj[key],options);obj=Utils.merge(obj,newObj,options)}return Utils.compact(obj)}},{"./utils":33}],32:[function(require,module,exports){var Utils=require("./utils");var internals={delimiter:"&",arrayPrefixGenerators:{brackets:function(prefix,key){return prefix+"[]"},indices:function(prefix,key){return prefix+"["+key+"]"},repeat:function(prefix,key){return prefix}},strictNullHandling:false};internals.stringify=function(obj,prefix,generateArrayPrefix,strictNullHandling,filter){if(typeof filter==="function"){obj=filter(prefix,obj)}else if(Utils.isBuffer(obj)){obj=obj.toString()}else if(obj instanceof Date){obj=obj.toISOString()}else if(obj===null){if(strictNullHandling){return Utils.encode(prefix)}obj=""}if(typeof obj==="string"||typeof obj==="number"||typeof obj==="boolean"){return[Utils.encode(prefix)+"="+Utils.encode(obj)]}var values=[];if(typeof obj==="undefined"){return values}var objKeys=Array.isArray(filter)?filter:Object.keys(obj);for(var i=0,il=objKeys.length;i<il;++i){var key=objKeys[i];if(Array.isArray(obj)){values=values.concat(internals.stringify(obj[key],generateArrayPrefix(prefix,key),generateArrayPrefix,strictNullHandling,filter))}else{values=values.concat(internals.stringify(obj[key],prefix+"["+key+"]",generateArrayPrefix,strictNullHandling,filter))}}return values};module.exports=function(obj,options){options=options||{};var delimiter=typeof options.delimiter==="undefined"?internals.delimiter:options.delimiter;var strictNullHandling=typeof options.strictNullHandling==="boolean"?options.strictNullHandling:internals.strictNullHandling;var objKeys;var filter;if(typeof options.filter==="function"){filter=options.filter;obj=filter("",obj)}else if(Array.isArray(options.filter)){objKeys=filter=options.filter}var keys=[];if(typeof obj!=="object"||obj===null){return""}var arrayFormat;if(options.arrayFormat in internals.arrayPrefixGenerators){arrayFormat=options.arrayFormat}else if("indices"in options){arrayFormat=options.indices?"indices":"repeat"}else{arrayFormat="indices"}var generateArrayPrefix=internals.arrayPrefixGenerators[arrayFormat];if(!objKeys){objKeys=Object.keys(obj)}for(var i=0,il=objKeys.length;i<il;++i){var key=objKeys[i];keys=keys.concat(internals.stringify(obj[key],key,generateArrayPrefix,strictNullHandling,filter))}return keys.join(delimiter)}},{"./utils":33}],33:[function(require,module,exports){var internals={};internals.hexTable=new Array(256);for(var h=0;h<256;++h){internals.hexTable[h]="%"+((h<16?"0":"")+h.toString(16)).toUpperCase()}exports.arrayToObject=function(source,options){var obj=options.plainObjects?Object.create(null):{};for(var i=0,il=source.length;i<il;++i){if(typeof source[i]!=="undefined"){obj[i]=source[i]}}return obj};exports.merge=function(target,source,options){if(!source){return target}if(typeof source!=="object"){if(Array.isArray(target)){target.push(source)}else if(typeof target==="object"){target[source]=true}else{target=[target,source]}return target}if(typeof target!=="object"){target=[target].concat(source);return target}if(Array.isArray(target)&&!Array.isArray(source)){target=exports.arrayToObject(target,options)}var keys=Object.keys(source);for(var k=0,kl=keys.length;k<kl;++k){var key=keys[k];var value=source[key];if(!Object.prototype.hasOwnProperty.call(target,key)){target[key]=value}else{target[key]=exports.merge(target[key],value,options)}}return target};exports.decode=function(str){try{return decodeURIComponent(str.replace(/\+/g," "))}catch(e){return str}};exports.encode=function(str){if(str.length===0){return str}if(typeof str!=="string"){str=""+str}var out="";for(var i=0,il=str.length;i<il;++i){var c=str.charCodeAt(i);if(c===45||c===46||c===95||c===126||c>=48&&c<=57||c>=65&&c<=90||c>=97&&c<=122){out+=str[i];continue}if(c<128){out+=internals.hexTable[c];continue}if(c<2048){out+=internals.hexTable[192|c>>6]+internals.hexTable[128|c&63];continue}if(c<55296||c>=57344){out+=internals.hexTable[224|c>>12]+internals.hexTable[128|c>>6&63]+internals.hexTable[128|c&63];continue}++i;c=65536+((c&1023)<<10|str.charCodeAt(i)&1023);out+=internals.hexTable[240|c>>18]+internals.hexTable[128|c>>12&63]+internals.hexTable[128|c>>6&63]+internals.hexTable[128|c&63]}return out};exports.compact=function(obj,refs){if(typeof obj!=="object"||obj===null){return obj}refs=refs||[];var lookup=refs.indexOf(obj);if(lookup!==-1){return refs[lookup]}refs.push(obj);if(Array.isArray(obj)){var compacted=[];for(var i=0,il=obj.length;i<il;++i){if(typeof obj[i]!=="undefined"){compacted.push(obj[i])}}return compacted}var keys=Object.keys(obj);for(i=0,il=keys.length;i<il;++i){var key=keys[i];obj[key]=exports.compact(obj[key],refs)}return obj};exports.isRegExp=function(obj){return Object.prototype.toString.call(obj)==="[object RegExp]"};exports.isBuffer=function(obj){if(obj===null||typeof obj==="undefined"){return false}return!!(obj.constructor&&obj.constructor.isBuffer&&obj.constructor.isBuffer(obj))}},{}],34:[function(require,module,exports){"use strict";var window=require("global/window");var once=require("once");var parseHeaders=require("parse-headers");module.exports=createXHR;createXHR.XMLHttpRequest=window.XMLHttpRequest||noop;createXHR.XDomainRequest="withCredentials"in new createXHR.XMLHttpRequest?createXHR.XMLHttpRequest:window.XDomainRequest;function isEmpty(obj){for(var i in obj){if(obj.hasOwnProperty(i))return false}return true}function createXHR(options,callback){function readystatechange(){if(xhr.readyState===4){loadFunc()}}function getBody(){var body=undefined;if(xhr.response){body=xhr.response}else if(xhr.responseType==="text"||!xhr.responseType){body=xhr.responseText||xhr.responseXML}if(isJson){try{body=JSON.parse(body)}catch(e){}}return body}var failureResponse={body:undefined,headers:{},statusCode:0,method:method,url:uri,rawRequest:xhr};function errorFunc(evt){clearTimeout(timeoutTimer);if(!(evt instanceof Error)){evt=new Error(""+(evt||"unknown"))}evt.statusCode=0;callback(evt,failureResponse)}function loadFunc(){if(aborted)return;var status;clearTimeout(timeoutTimer);if(options.useXDR&&xhr.status===undefined){status=200}else{status=xhr.status===1223?204:xhr.status}var response=failureResponse;var err=null;if(status!==0){response={body:getBody(),statusCode:status,method:method,headers:{},url:uri,rawRequest:xhr};if(xhr.getAllResponseHeaders){response.headers=parseHeaders(xhr.getAllResponseHeaders())}}else{err=new Error("Internal XMLHttpRequest Error")}callback(err,response,response.body)}if(typeof options==="string"){options={uri:options}}options=options||{};if(typeof callback==="undefined"){throw new Error("callback argument missing")}callback=once(callback);var xhr=options.xhr||null;if(!xhr){if(options.cors||options.useXDR){xhr=new createXHR.XDomainRequest}else{xhr=new createXHR.XMLHttpRequest}}var key;var aborted;var uri=xhr.url=options.uri||options.url;var method=xhr.method=options.method||"GET";var body=options.body||options.data;var headers=xhr.headers=options.headers||{};var sync=!!options.sync;var isJson=false;var timeoutTimer;if("json"in options){isJson=true;headers["accept"]||headers["Accept"]||(headers["Accept"]="application/json");if(method!=="GET"&&method!=="HEAD"){headers["Content-Type"]="application/json";body=JSON.stringify(options.json)}}xhr.onreadystatechange=readystatechange;xhr.onload=loadFunc;xhr.onerror=errorFunc;xhr.onprogress=function(){};xhr.ontimeout=errorFunc;xhr.open(method,uri,!sync,options.username,options.password);if(!sync){xhr.withCredentials=!!options.withCredentials}if(!sync&&options.timeout>0){timeoutTimer=setTimeout(function(){aborted=true;xhr.abort("timeout");errorFunc()},options.timeout)}if(xhr.setRequestHeader){for(key in headers){if(headers.hasOwnProperty(key)){xhr.setRequestHeader(key,headers[key])}}}else if(options.headers&&!isEmpty(options.headers)){throw new Error("Headers cannot be set on an XDomainRequest object")}if("responseType"in options){xhr.responseType=options.responseType}if("beforeSend"in options&&typeof options.beforeSend==="function"){options.beforeSend(xhr)}xhr.send(body);return xhr}function noop(){}},{"global/window":35,once:36,"parse-headers":40}],35:[function(require,module,exports){(function(global){if(typeof window!=="undefined"){module.exports=window}else if(typeof global!=="undefined"){
module.exports=global}else if(typeof self!=="undefined"){module.exports=self}else{module.exports={}}}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{}],36:[function(require,module,exports){module.exports=once;once.proto=once(function(){Object.defineProperty(Function.prototype,"once",{value:function(){return once(this)},configurable:true})});function once(fn){var called=false;return function(){if(called)return;called=true;return fn.apply(this,arguments)}}},{}],37:[function(require,module,exports){var isFunction=require("is-function");module.exports=forEach;var toString=Object.prototype.toString;var hasOwnProperty=Object.prototype.hasOwnProperty;function forEach(list,iterator,context){if(!isFunction(iterator)){throw new TypeError("iterator must be a function")}if(arguments.length<3){context=this}if(toString.call(list)==="[object Array]")forEachArray(list,iterator,context);else if(typeof list==="string")forEachString(list,iterator,context);else forEachObject(list,iterator,context)}function forEachArray(array,iterator,context){for(var i=0,len=array.length;i<len;i++){if(hasOwnProperty.call(array,i)){iterator.call(context,array[i],i,array)}}}function forEachString(string,iterator,context){for(var i=0,len=string.length;i<len;i++){iterator.call(context,string.charAt(i),i,string)}}function forEachObject(object,iterator,context){for(var k in object){if(hasOwnProperty.call(object,k)){iterator.call(context,object[k],k,object)}}}},{"is-function":38}],38:[function(require,module,exports){module.exports=isFunction;var toString=Object.prototype.toString;function isFunction(fn){var string=toString.call(fn);return string==="[object Function]"||typeof fn==="function"&&string!=="[object RegExp]"||typeof window!=="undefined"&&(fn===window.setTimeout||fn===window.alert||fn===window.confirm||fn===window.prompt)}},{}],39:[function(require,module,exports){exports=module.exports=trim;function trim(str){return str.replace(/^\s*|\s*$/g,"")}exports.left=function(str){return str.replace(/^\s*/,"")};exports.right=function(str){return str.replace(/\s*$/,"")}},{}],40:[function(require,module,exports){var trim=require("trim"),forEach=require("for-each"),isArray=function(arg){return Object.prototype.toString.call(arg)==="[object Array]"};module.exports=function(headers){if(!headers)return{};var result={};forEach(trim(headers).split("\n"),function(row){var index=row.indexOf(":"),key=trim(row.slice(0,index)).toLowerCase(),value=trim(row.slice(index+1));if(typeof result[key]==="undefined"){result[key]=value}else if(isArray(result[key])){result[key].push(value)}else{result[key]=[result[key],value]}});return result}},{"for-each":37,trim:39}],"ampersand-sync":[function(require,module,exports){var xhr=require("xhr");module.exports=require("./core")(xhr)},{"./core":1,xhr:34}]},{},[]);require=function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s}({1:[function(require,module,exports){(function(global){if(typeof window!=="undefined"){module.exports=window}else if(typeof global!=="undefined"){module.exports=global}else if(typeof self!=="undefined"){module.exports=self}else{module.exports={}}}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{}],2:[function(require,module,exports){module.exports=once;once.proto=once(function(){Object.defineProperty(Function.prototype,"once",{value:function(){return once(this)},configurable:true})});function once(fn){var called=false;return function(){if(called)return;called=true;return fn.apply(this,arguments)}}},{}],3:[function(require,module,exports){var isFunction=require("is-function");module.exports=forEach;var toString=Object.prototype.toString;var hasOwnProperty=Object.prototype.hasOwnProperty;function forEach(list,iterator,context){if(!isFunction(iterator)){throw new TypeError("iterator must be a function")}if(arguments.length<3){context=this}if(toString.call(list)==="[object Array]")forEachArray(list,iterator,context);else if(typeof list==="string")forEachString(list,iterator,context);else forEachObject(list,iterator,context)}function forEachArray(array,iterator,context){for(var i=0,len=array.length;i<len;i++){if(hasOwnProperty.call(array,i)){iterator.call(context,array[i],i,array)}}}function forEachString(string,iterator,context){for(var i=0,len=string.length;i<len;i++){iterator.call(context,string.charAt(i),i,string)}}function forEachObject(object,iterator,context){for(var k in object){if(hasOwnProperty.call(object,k)){iterator.call(context,object[k],k,object)}}}},{"is-function":4}],4:[function(require,module,exports){module.exports=isFunction;var toString=Object.prototype.toString;function isFunction(fn){var string=toString.call(fn);return string==="[object Function]"||typeof fn==="function"&&string!=="[object RegExp]"||typeof window!=="undefined"&&(fn===window.setTimeout||fn===window.alert||fn===window.confirm||fn===window.prompt)}},{}],5:[function(require,module,exports){exports=module.exports=trim;function trim(str){return str.replace(/^\s*|\s*$/g,"")}exports.left=function(str){return str.replace(/^\s*/,"")};exports.right=function(str){return str.replace(/\s*$/,"")}},{}],6:[function(require,module,exports){var trim=require("trim"),forEach=require("for-each"),isArray=function(arg){return Object.prototype.toString.call(arg)==="[object Array]"};module.exports=function(headers){if(!headers)return{};var result={};forEach(trim(headers).split("\n"),function(row){var index=row.indexOf(":"),key=trim(row.slice(0,index)).toLowerCase(),value=trim(row.slice(index+1));if(typeof result[key]==="undefined"){result[key]=value}else if(isArray(result[key])){result[key].push(value)}else{result[key]=[result[key],value]}});return result}},{"for-each":3,trim:5}],xhr:[function(require,module,exports){"use strict";var window=require("global/window");var once=require("once");var parseHeaders=require("parse-headers");module.exports=createXHR;createXHR.XMLHttpRequest=window.XMLHttpRequest||noop;createXHR.XDomainRequest="withCredentials"in new createXHR.XMLHttpRequest?createXHR.XMLHttpRequest:window.XDomainRequest;function isEmpty(obj){for(var i in obj){if(obj.hasOwnProperty(i))return false}return true}function createXHR(options,callback){function readystatechange(){if(xhr.readyState===4){loadFunc()}}function getBody(){var body=undefined;if(xhr.response){body=xhr.response}else if(xhr.responseType==="text"||!xhr.responseType){body=xhr.responseText||xhr.responseXML}if(isJson){try{body=JSON.parse(body)}catch(e){}}return body}var failureResponse={body:undefined,headers:{},statusCode:0,method:method,url:uri,rawRequest:xhr};function errorFunc(evt){clearTimeout(timeoutTimer);if(!(evt instanceof Error)){evt=new Error(""+(evt||"unknown"))}evt.statusCode=0;callback(evt,failureResponse)}function loadFunc(){if(aborted)return;var status;clearTimeout(timeoutTimer);if(options.useXDR&&xhr.status===undefined){status=200}else{status=xhr.status===1223?204:xhr.status}var response=failureResponse;var err=null;if(status!==0){response={body:getBody(),statusCode:status,method:method,headers:{},url:uri,rawRequest:xhr};if(xhr.getAllResponseHeaders){response.headers=parseHeaders(xhr.getAllResponseHeaders())}}else{err=new Error("Internal XMLHttpRequest Error")}callback(err,response,response.body)}if(typeof options==="string"){options={uri:options}}options=options||{};if(typeof callback==="undefined"){throw new Error("callback argument missing")}callback=once(callback);var xhr=options.xhr||null;if(!xhr){if(options.cors||options.useXDR){xhr=new createXHR.XDomainRequest}else{xhr=new createXHR.XMLHttpRequest}}var key;var aborted;var uri=xhr.url=options.uri||options.url;var method=xhr.method=options.method||"GET";var body=options.body||options.data;var headers=xhr.headers=options.headers||{};var sync=!!options.sync;var isJson=false;var timeoutTimer;if("json"in options){isJson=true;headers["accept"]||headers["Accept"]||(headers["Accept"]="application/json");if(method!=="GET"&&method!=="HEAD"){headers["Content-Type"]="application/json";body=JSON.stringify(options.json)}}xhr.onreadystatechange=readystatechange;xhr.onload=loadFunc;xhr.onerror=errorFunc;xhr.onprogress=function(){};xhr.ontimeout=errorFunc;xhr.open(method,uri,!sync,options.username,options.password);if(!sync){xhr.withCredentials=!!options.withCredentials}if(!sync&&options.timeout>0){timeoutTimer=setTimeout(function(){aborted=true;xhr.abort("timeout");errorFunc()},options.timeout)}if(xhr.setRequestHeader){for(key in headers){if(headers.hasOwnProperty(key)){xhr.setRequestHeader(key,headers[key])}}}else if(options.headers&&!isEmpty(options.headers)){throw new Error("Headers cannot be set on an XDomainRequest object")}if("responseType"in options){xhr.responseType=options.responseType}if("beforeSend"in options&&typeof options.beforeSend==="function"){options.beforeSend(xhr)}xhr.send(body);return xhr}function noop(){}},{"global/window":1,once:2,"parse-headers":6}]},{},[]);var sync=require("ampersand-sync");var xhr=require("xhr");var options={url:"http://jsonplaceholder.typicode.com/posts",headers:{"Content-Type":"application/json"},json:{foo:"bar"},method:"POST"};var request=sync("create",null,options);var request2=xhr(options,function(){});console.log(request.headers);console.log(request2.headers);
{
"name": "requirebin-sketch",
"version": "1.0.0",
"dependencies": {
"ampersand-sync": "4.0.0",
"xhr": "2.0.3"
}
}
<!-- contents of this file will be placed inside the <body> -->
<!-- contents of this file will be placed inside the <head> -->
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment