Socket
Socket
Sign inDemoInstall

mappersmith

Package Overview
Dependencies
Maintainers
3
Versions
121
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

mappersmith - npm Package Compare versions

Comparing version 0.13.1 to 0.13.2

2

build/mappersmith-fixture.js
(function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.MappersmithFixture = f()}})(function(){var define,module,exports;return (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){
/*!
* Mappersmith 0.13.1, Fixture support
* Mappersmith 0.13.2, Fixture support
* https://github.com/tulios/mappersmith

@@ -6,0 +6,0 @@ */

(function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.Mappersmith = f()}})(function(){var define,module,exports;return (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){
/*!
* Mappersmith 0.13.1
* Mappersmith 0.13.2
* https://github.com/tulios/mappersmith

@@ -320,3 +320,3 @@ */

request.open('GET', this.url, true);
this._setHeaders(request);
this._setUserDefinedHeaders(request);
request.send();

@@ -345,2 +345,3 @@ },

var request = new XMLHttpRequest();
this._configureCallbacks(request);

@@ -356,5 +357,6 @@

if (emulateHTTP) request.setRequestHeader('X-HTTP-Method-Override', method);
request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8;');
this._setHeaders(request);
this._setContentTypeHeader(request);
this._setUserDefinedHeaders(request);
var args = [];

@@ -419,4 +421,4 @@ if (this.body !== undefined) {

_setHeaders: function(request) {
var headers = Utils.extend({}, this.opts.headers);
_setUserDefinedHeaders: function(request) {
var headers = this._getHeaders();
Object.keys(headers).forEach(function(headerName) {

@@ -429,2 +431,18 @@ request.setRequestHeader(headerName, headers[headerName]);

return /application\/json/.test(request.getResponseHeader('Content-Type'));
},
_setContentTypeHeader: function(request) {
var headers = this._getHeaders();
var contentType = null;
Object.keys(headers).forEach(function(headerName) {
if (/^content-type$/i.test(headerName)) contentType = headers[headerName];
});
if (!contentType) contentType = 'application/x-www-form-urlencoded; charset=UTF-8;';
request.setRequestHeader('Content-Type', contentType);
},
_getHeaders: function() {
return Utils.extend({}, this.opts.headers);
}

@@ -431,0 +449,0 @@

!function(f){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=f();else if("function"==typeof define&&define.amd)define([],f);else{var g;g="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:this,g.Mappersmith=f()}}(function(){var define,module,exports;return function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a="function"==typeof require&&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}for(var i="function"==typeof require&&require,o=0;o<r.length;o++)s(r[o]);return s}({1:[function(require,module,exports){/*!
* Mappersmith 0.13.1
* Mappersmith 0.13.2
* https://github.com/tulios/mappersmith
*/
module.exports={Env:require("./src/env"),Utils:require("./src/utils"),Gateway:require("./src/gateway"),Mapper:require("./src/mapper"),VanillaGateway:require("./src/gateway/vanilla-gateway"),JQueryGateway:require("./src/gateway/jquery-gateway"),forge:require("./src/forge"),createGateway:require("./src/create-gateway")}},{"./src/create-gateway":2,"./src/env":3,"./src/forge":4,"./src/gateway":5,"./src/gateway/jquery-gateway":6,"./src/gateway/vanilla-gateway":7,"./src/mapper":8,"./src/utils":9}],2:[function(require,module,exports){var Utils=require("./utils"),Gateway=require("./gateway");module.exports=function(methods){var newGateway=function(){return this.init&&this.init(),Gateway.apply(this,arguments)};return newGateway.prototype=Utils.extend({},Gateway.prototype,methods),newGateway}},{"./gateway":5,"./utils":9}],3:[function(require,module,exports){module.exports={USE_FIXTURES:!1,USE_PROMISES:!1,Fixture:null,Promise:"function"==typeof Promise?Promise:null}},{}],4:[function(require,module,exports){var Mapper=require("./mapper"),VanillaGateway=require("./gateway/vanilla-gateway");module.exports=function(manifest,gateway,bodyAttr){return new Mapper(manifest,gateway||VanillaGateway,bodyAttr||"body").build()}},{"./gateway/vanilla-gateway":7,"./mapper":8}],5:[function(require,module,exports){var Env=require("./env"),Utils=require("./utils"),Promise=require("./env").Promise,Gateway=function(args){this.url=args.url,this.host=args.host,this.path=args.path,this.params=args.params||{},this.method=args.method,this.body=args.body,this.processor=args.processor,this.opts=args.opts||{},this.timeStart=null,this.timeEnd=null,this.timeElapsed=null,this.success(Utils.noop),this.fail(Utils.noop),this.complete(Utils.noop)};Gateway.prototype={call:function(){return this.timeStart=Utils.performanceNow(),Env.USE_FIXTURES&&Env.Fixture?this.callWithFixture():this[this.method].apply(this,arguments),this},callWithFixture:function(){var resource=this.getRequestedResource(),entry=Env.Fixture.lookup(this.method,resource);if(!entry)throw new Utils.Exception("No fixture provided for "+JSON.stringify(resource));setTimeout(function(){entry.isSuccess()?this.successCallback(entry.callWith(resource)):this.failCallback(entry.callWith(resource))}.bind(this),1)},promisify:function(thenCallback){var promise=new Promise(function(resolve,reject){this.success(function(data,stats){resolve({data:data,stats:stats})}),this.fail(function(){for(var args=[],i=0;i<arguments.length;i++)args.push(arguments[i]);var request=args.shift();reject({request:request,err:args})}),this.call()}.bind(this));return void 0!==thenCallback?promise.then(thenCallback):promise},success:function(callback){return this.successCallback=function(data,extraStats){this.timeEnd=Utils.performanceNow(),this.timeElapsed=this.timeEnd-this.timeStart,this.processor&&(data=this.processor(data));var requestedResource=this.getRequestedResource(),stats=Utils.extend({timeElapsed:this.timeElapsed,timeElapsedHumanized:Utils.humanizeTimeElapsed(this.timeElapsed)},requestedResource,extraStats);this.successHandler&&this.successHandler.apply(this,[stats,data]),callback(data,stats)}.bind(this),this},fail:function(callback){return this.failCallback=function(errorObj){errorObj=errorObj||{status:400,args:[]};var gatewayArgs=Array.prototype.slice.call(errorObj.args),status=errorObj.status,resource=this.getRequestedResource(),errorResource=Utils.extend({status:status},resource),args=[errorResource].concat(gatewayArgs),proceed=!0;this.errorHandler&&(proceed=!(this.errorHandler.apply(this,args)===!0)),proceed&&callback.apply(this,args)}.bind(this),this},complete:function(callback){return this.completeCallback=callback,this},getRequestedResource:function(){return{url:this.url,host:this.host,path:this.path,params:this.params,headers:this.opts.headers}},setErrorHandler:function(errorHandler){this.errorHandler=errorHandler},setSuccessHandler:function(successHandler){this.successHandler=successHandler},shouldEmulateHTTP:function(method){return!(!this.opts.emulateHTTP||!/^(delete|put|patch)/i.test(method))},get:function(){throw new Utils.Exception("Gateway#get not implemented")},post:function(){throw new Utils.Exception("Gateway#post not implemented")},put:function(){throw new Utils.Exception("Gateway#put not implemented")},delete:function(){throw new Utils.Exception("Gateway#delete not implemented")},patch:function(){throw new Utils.Exception("Gateway#patch not implemented")}},module.exports=Gateway},{"./env":3,"./utils":9}],6:[function(require,module,exports){var Utils=require("../utils"),CreateGateway=require("../create-gateway"),JQueryGateway=CreateGateway({init:function(){if(void 0===window.jQuery)throw new Utils.Exception("JQueryGateway requires jQuery but it was not found! Change the gateway implementation or add jQuery on the page")},get:function(){return this._jQueryAjax(this.opts),this},post:function(){return this._performRequest("POST")},put:function(){return this._performRequest("PUT")},patch:function(){return this._performRequest("PATCH")},delete:function(){return this._performRequest("DELETE")},_performRequest:function(method){var requestMethod=method;this.shouldEmulateHTTP(method)&&(requestMethod="POST",this.body=this.body||{},"object"==typeof this.body&&(this.body._method=method),this.opts.headers=Utils.extend({"X-HTTP-Method-Override":method},this.opts.headers));var defaults={type:requestMethod,data:Utils.params(this.body)};return this._jQueryAjax(Utils.extend(defaults,this.opts)),this},_jQueryAjax:function(config){config.withCredentials&&(delete config.withCredentials,config=Utils.extend(config,{xhrFields:{withCredentials:!0}})),jQuery.ajax(Utils.extend({url:this.url},config)).done(function(data,textStatus,xhr){var headers=Utils.parseResponseHeaders(xhr.getAllResponseHeaders());this.successCallback(data,{status:xhr.status,responseHeaders:headers})}.bind(this)).fail(function(jqXHR){this.failCallback({status:jqXHR.status,args:arguments})}.bind(this)).always(function(){this.completeCallback.apply(this,arguments)}.bind(this))}});module.exports=JQueryGateway},{"../create-gateway":2,"../utils":9}],7:[function(require,module,exports){var Utils=require("../utils"),CreateGateway=require("../create-gateway"),VanillaGateway=CreateGateway({get:function(){var request=new XMLHttpRequest;this._configureCallbacks(request),request.open("GET",this.url,!0),this._setHeaders(request),request.send()},post:function(){this._performRequest("POST")},put:function(){this._performRequest("PUT")},patch:function(){this._performRequest("PATCH")},delete:function(){this._performRequest("DELETE")},_performRequest:function(method){var emulateHTTP=this.shouldEmulateHTTP(method),requestMethod=method,request=new XMLHttpRequest;this._configureCallbacks(request),emulateHTTP&&(this.body=this.body||{},"object"==typeof this.body&&(this.body._method=method),requestMethod="POST"),request.open(requestMethod,this.url,!0),emulateHTTP&&request.setRequestHeader("X-HTTP-Method-Override",method),request.setRequestHeader("Content-Type","application/x-www-form-urlencoded; charset=UTF-8;"),this._setHeaders(request);var args=[];void 0!==this.body&&args.push(Utils.params(this.body)),request.send.apply(request,args)},_configureCallbacks:function(request){request.onload=function(){var data=null,status=request.status;1223===status&&(status=204);try{if(status>=200&&400>status){data=this._isContentTypeJSON(request)?JSON.parse(request.responseText):request.responseText;var responseHeaders=request.getAllResponseHeaders(),extra={status:status,responseHeaders:Utils.parseResponseHeaders(responseHeaders)};this.successCallback(data,extra)}else this.failCallback({status:status,args:[request]})}catch(e){this.failCallback({status:status,args:[request]})}finally{this.completeCallback(data,request)}}.bind(this),request.onerror=function(){this.failCallback({status:400,args:[arguments]}),this.completeCallback.apply(this,arguments)}.bind(this),this.opts.withCredentials&&(request.withCredentials=!0),this.opts.configure&&this.opts.configure(request)},_setHeaders:function(request){var headers=Utils.extend({},this.opts.headers);Object.keys(headers).forEach(function(headerName){request.setRequestHeader(headerName,headers[headerName])})},_isContentTypeJSON:function(request){return/application\/json/.test(request.getResponseHeader("Content-Type"))}});module.exports=VanillaGateway},{"../create-gateway":2,"../utils":9}],8:[function(require,module,exports){var Utils=require("./utils"),Env=require("./env"),Mapper=function(manifest,Gateway,bodyAttr){this.manifest=manifest,this.rules=this.manifest.rules||[],this.Gateway=Gateway,this.bodyAttr=bodyAttr,this.globalErrorHandler=Utils.noop,this.globalSuccessHandler=Utils.noop};Mapper.prototype={build:function(){return Object.keys(this.manifest.resources||{}).map(function(name){return this.buildResource(name)}.bind(this)).reduce(function(context,resource){return context[resource.name]=resource.methods,context},this.createContext())},createContext:function(){return{onSuccess:function(handler){this.globalSuccessHandler=handler}.bind(this),onError:function(handler){this.globalErrorHandler=handler}.bind(this)}},buildResource:function(resourceName){var methods=this.manifest.resources[resourceName];return Object.keys(methods).reduce(function(context,methodName){var descriptor=methods[methodName];if("string"==typeof descriptor){var compactDefinitionMethod=descriptor.match(/^(get|post|delete|put|patch):(.*)/);descriptor=null!=compactDefinitionMethod?{method:compactDefinitionMethod[1],path:compactDefinitionMethod[2]}:{method:"get",path:descriptor}}return descriptor.method=(descriptor.method||"get").toLowerCase(),context.methods[methodName]=this.newGatewayRequest(descriptor),context}.bind(this),{name:resourceName,methods:{}})},resolvePath:function(pathDefinition,urlParams){var params=Utils.extend({},urlParams),resolvedPath=pathDefinition;delete params[this.bodyAttr],delete params.headers,Object.keys(params).forEach(function(key){var value=params[key],pattern="{"+key+"}";new RegExp(pattern).test(resolvedPath)&&(resolvedPath=resolvedPath.replace("{"+key+"}",value),delete params[key])});var paramsString=Utils.params(params);return 0!==paramsString.length&&(paramsString="?"+paramsString),resolvedPath+paramsString},resolveHost:function(value){return("undefined"==typeof value||null===value)&&(value=this.manifest.host),value===!1&&(value=""),value.replace(/\/$/,"")},resolveRules:function(descriptor,resolvedUrl){return this.rules.filter(function(rule){return void 0===rule.match||rule.match.test(resolvedUrl)}).reduce(function(context,rule){var mergedGateway=Utils.extend(context.gateway,rule.values.gateway);return context=Utils.extend(context,rule.values),context.gateway=mergedGateway,context},{})},newGatewayRequest:function(descriptor){return function(params,callback,opts){"function"==typeof params?(opts=callback,callback=params,params=void 0):callback&&"function"!=typeof callback&&(opts=callback,callback=Utils.noop),descriptor.params&&(params=Utils.extend({},descriptor.params,params));var host=this.resolveHost(descriptor.host),path=this.resolvePath(descriptor.path,params);""!==host&&(path=/^\//.test(path)?path:"/"+path);var fullUrl=host+path,rules=this.resolveRules(descriptor,fullUrl);opts=Utils.extend({},opts,rules.gateway),params&&params.headers&&(opts.headers=Utils.extend(opts.headers,params.headers),delete params.headers),Utils.isObjEmpty(opts)&&(opts=void 0);var body=(params||{})[this.bodyAttr],gatewayOpts=Utils.extend({},{url:fullUrl,host:host,path:path,params:params,body:body,method:descriptor.method,processor:descriptor.processor||rules.processor,opts:opts}),gateway=new this.Gateway(gatewayOpts);return gateway.setSuccessHandler(this.globalSuccessHandler),gateway.setErrorHandler(this.globalErrorHandler),Env.USE_PROMISES?gateway.promisify(callback):gateway.success(callback).call()}.bind(this)}},module.exports=Mapper},{"./env":3,"./utils":9}],9:[function(require,module,exports){function hasProcessHrtime(){return"undefined"!=typeof _process&&null!==_process&&_process.hrtime}function isObject(value){return"[object Object]"===Object.prototype.toString.call(value)}"undefined"!=typeof window&&null!==window&&(window.performance=window.performance||{},performance.now=function(){return performance.now||performance.mozNow||performance.msNow||performance.oNow||performance.webkitNow||function(){return(new Date).getTime()}}());var _process;try{_process=eval("process")}catch(e){}var getNanoSeconds,loadTime;hasProcessHrtime()&&(getNanoSeconds=function(){var hr=_process.hrtime();return 1e9*hr[0]+hr[1]},loadTime=getNanoSeconds());var Utils={r20:/%20/g,noop:function(){},isObjEmpty:function(obj){for(var key in obj)if(obj.hasOwnProperty(key))return!1;return!0},extend:function(out){var options,name,src,copy,clone,target=arguments[0]||{},length=arguments.length;"object"!=typeof target&&(target={});for(var i=1;length>i;i++)if(null!==(options=arguments[i]))for(name in options)src=target[name],copy=options[name],target!==copy&&(copy&&isObject(copy)?(clone=src&&isObject(src)?src:{},target[name]=this.extend(clone,copy)):void 0!==copy&&(target[name]=copy));return target},params:function(entry){if("object"!=typeof entry)return entry;var validKeys=function(entry){return Object.keys(entry).filter(function(key){return void 0!==entry[key]&&null!==entry[key]})},buildRecursive=function(key,value,suffix){suffix=suffix||"";var isArray=Array.isArray(value),isObject="object"==typeof value;return isArray||isObject?isArray?value.map(function(v){return buildRecursive(key,v,suffix+"[]")}).join("&"):validKeys(value).map(function(k){return buildRecursive(key,value[k],suffix+"["+k+"]")}).join("&"):encodeURIComponent(key+suffix)+"="+encodeURIComponent(value)};return validKeys(entry).map(function(key){return buildRecursive(key,entry[key])}).join("&").replace(Utils.r20,"+")},parseResponseHeaders:function(headerStr){var headers={};if(!headerStr)return headers;for(var headerPairs=headerStr.split("\r\n"),i=0;i<headerPairs.length;i++){var headerPair=headerPairs[i],index=headerPair.indexOf(": ");if(index>0){var key=headerPair.substring(0,index).toLowerCase(),val=headerPair.substring(index+2);headers[key]=val}}return headers},performanceNow:function(){return hasProcessHrtime()?(getNanoSeconds()-loadTime)/1e6:performance.now()},humanizeTimeElapsed:function(timeElapsed){return timeElapsed>=1e3?(timeElapsed/1e3).toFixed(2)+" s":timeElapsed.toFixed(2)+" ms"},Exception:function(message){var err=new Error("[Mappersmith] "+message);this.message=err.message,this.stack=err.stack,this.toString=function(){return this.message}}};module.exports=Utils},{}]},{},[1])(1)});
module.exports={Env:require("./src/env"),Utils:require("./src/utils"),Gateway:require("./src/gateway"),Mapper:require("./src/mapper"),VanillaGateway:require("./src/gateway/vanilla-gateway"),JQueryGateway:require("./src/gateway/jquery-gateway"),forge:require("./src/forge"),createGateway:require("./src/create-gateway")}},{"./src/create-gateway":2,"./src/env":3,"./src/forge":4,"./src/gateway":5,"./src/gateway/jquery-gateway":6,"./src/gateway/vanilla-gateway":7,"./src/mapper":8,"./src/utils":9}],2:[function(require,module,exports){var Utils=require("./utils"),Gateway=require("./gateway");module.exports=function(methods){var newGateway=function(){return this.init&&this.init(),Gateway.apply(this,arguments)};return newGateway.prototype=Utils.extend({},Gateway.prototype,methods),newGateway}},{"./gateway":5,"./utils":9}],3:[function(require,module,exports){module.exports={USE_FIXTURES:!1,USE_PROMISES:!1,Fixture:null,Promise:"function"==typeof Promise?Promise:null}},{}],4:[function(require,module,exports){var Mapper=require("./mapper"),VanillaGateway=require("./gateway/vanilla-gateway");module.exports=function(manifest,gateway,bodyAttr){return new Mapper(manifest,gateway||VanillaGateway,bodyAttr||"body").build()}},{"./gateway/vanilla-gateway":7,"./mapper":8}],5:[function(require,module,exports){var Env=require("./env"),Utils=require("./utils"),Promise=require("./env").Promise,Gateway=function(args){this.url=args.url,this.host=args.host,this.path=args.path,this.params=args.params||{},this.method=args.method,this.body=args.body,this.processor=args.processor,this.opts=args.opts||{},this.timeStart=null,this.timeEnd=null,this.timeElapsed=null,this.success(Utils.noop),this.fail(Utils.noop),this.complete(Utils.noop)};Gateway.prototype={call:function(){return this.timeStart=Utils.performanceNow(),Env.USE_FIXTURES&&Env.Fixture?this.callWithFixture():this[this.method].apply(this,arguments),this},callWithFixture:function(){var resource=this.getRequestedResource(),entry=Env.Fixture.lookup(this.method,resource);if(!entry)throw new Utils.Exception("No fixture provided for "+JSON.stringify(resource));setTimeout(function(){entry.isSuccess()?this.successCallback(entry.callWith(resource)):this.failCallback(entry.callWith(resource))}.bind(this),1)},promisify:function(thenCallback){var promise=new Promise(function(resolve,reject){this.success(function(data,stats){resolve({data:data,stats:stats})}),this.fail(function(){for(var args=[],i=0;i<arguments.length;i++)args.push(arguments[i]);var request=args.shift();reject({request:request,err:args})}),this.call()}.bind(this));return void 0!==thenCallback?promise.then(thenCallback):promise},success:function(callback){return this.successCallback=function(data,extraStats){this.timeEnd=Utils.performanceNow(),this.timeElapsed=this.timeEnd-this.timeStart,this.processor&&(data=this.processor(data));var requestedResource=this.getRequestedResource(),stats=Utils.extend({timeElapsed:this.timeElapsed,timeElapsedHumanized:Utils.humanizeTimeElapsed(this.timeElapsed)},requestedResource,extraStats);this.successHandler&&this.successHandler.apply(this,[stats,data]),callback(data,stats)}.bind(this),this},fail:function(callback){return this.failCallback=function(errorObj){errorObj=errorObj||{status:400,args:[]};var gatewayArgs=Array.prototype.slice.call(errorObj.args),status=errorObj.status,resource=this.getRequestedResource(),errorResource=Utils.extend({status:status},resource),args=[errorResource].concat(gatewayArgs),proceed=!0;this.errorHandler&&(proceed=!(this.errorHandler.apply(this,args)===!0)),proceed&&callback.apply(this,args)}.bind(this),this},complete:function(callback){return this.completeCallback=callback,this},getRequestedResource:function(){return{url:this.url,host:this.host,path:this.path,params:this.params,headers:this.opts.headers}},setErrorHandler:function(errorHandler){this.errorHandler=errorHandler},setSuccessHandler:function(successHandler){this.successHandler=successHandler},shouldEmulateHTTP:function(method){return!(!this.opts.emulateHTTP||!/^(delete|put|patch)/i.test(method))},get:function(){throw new Utils.Exception("Gateway#get not implemented")},post:function(){throw new Utils.Exception("Gateway#post not implemented")},put:function(){throw new Utils.Exception("Gateway#put not implemented")},delete:function(){throw new Utils.Exception("Gateway#delete not implemented")},patch:function(){throw new Utils.Exception("Gateway#patch not implemented")}},module.exports=Gateway},{"./env":3,"./utils":9}],6:[function(require,module,exports){var Utils=require("../utils"),CreateGateway=require("../create-gateway"),JQueryGateway=CreateGateway({init:function(){if(void 0===window.jQuery)throw new Utils.Exception("JQueryGateway requires jQuery but it was not found! Change the gateway implementation or add jQuery on the page")},get:function(){return this._jQueryAjax(this.opts),this},post:function(){return this._performRequest("POST")},put:function(){return this._performRequest("PUT")},patch:function(){return this._performRequest("PATCH")},delete:function(){return this._performRequest("DELETE")},_performRequest:function(method){var requestMethod=method;this.shouldEmulateHTTP(method)&&(requestMethod="POST",this.body=this.body||{},"object"==typeof this.body&&(this.body._method=method),this.opts.headers=Utils.extend({"X-HTTP-Method-Override":method},this.opts.headers));var defaults={type:requestMethod,data:Utils.params(this.body)};return this._jQueryAjax(Utils.extend(defaults,this.opts)),this},_jQueryAjax:function(config){config.withCredentials&&(delete config.withCredentials,config=Utils.extend(config,{xhrFields:{withCredentials:!0}})),jQuery.ajax(Utils.extend({url:this.url},config)).done(function(data,textStatus,xhr){var headers=Utils.parseResponseHeaders(xhr.getAllResponseHeaders());this.successCallback(data,{status:xhr.status,responseHeaders:headers})}.bind(this)).fail(function(jqXHR){this.failCallback({status:jqXHR.status,args:arguments})}.bind(this)).always(function(){this.completeCallback.apply(this,arguments)}.bind(this))}});module.exports=JQueryGateway},{"../create-gateway":2,"../utils":9}],7:[function(require,module,exports){var Utils=require("../utils"),CreateGateway=require("../create-gateway"),VanillaGateway=CreateGateway({get:function(){var request=new XMLHttpRequest;this._configureCallbacks(request),request.open("GET",this.url,!0),this._setUserDefinedHeaders(request),request.send()},post:function(){this._performRequest("POST")},put:function(){this._performRequest("PUT")},patch:function(){this._performRequest("PATCH")},delete:function(){this._performRequest("DELETE")},_performRequest:function(method){var emulateHTTP=this.shouldEmulateHTTP(method),requestMethod=method,request=new XMLHttpRequest;this._configureCallbacks(request),emulateHTTP&&(this.body=this.body||{},"object"==typeof this.body&&(this.body._method=method),requestMethod="POST"),request.open(requestMethod,this.url,!0),emulateHTTP&&request.setRequestHeader("X-HTTP-Method-Override",method),this._setContentTypeHeader(request),this._setUserDefinedHeaders(request);var args=[];void 0!==this.body&&args.push(Utils.params(this.body)),request.send.apply(request,args)},_configureCallbacks:function(request){request.onload=function(){var data=null,status=request.status;1223===status&&(status=204);try{if(status>=200&&400>status){data=this._isContentTypeJSON(request)?JSON.parse(request.responseText):request.responseText;var responseHeaders=request.getAllResponseHeaders(),extra={status:status,responseHeaders:Utils.parseResponseHeaders(responseHeaders)};this.successCallback(data,extra)}else this.failCallback({status:status,args:[request]})}catch(e){this.failCallback({status:status,args:[request]})}finally{this.completeCallback(data,request)}}.bind(this),request.onerror=function(){this.failCallback({status:400,args:[arguments]}),this.completeCallback.apply(this,arguments)}.bind(this),this.opts.withCredentials&&(request.withCredentials=!0),this.opts.configure&&this.opts.configure(request)},_setUserDefinedHeaders:function(request){var headers=this._getHeaders();Object.keys(headers).forEach(function(headerName){request.setRequestHeader(headerName,headers[headerName])})},_isContentTypeJSON:function(request){return/application\/json/.test(request.getResponseHeader("Content-Type"))},_setContentTypeHeader:function(request){var headers=this._getHeaders(),contentType=null;Object.keys(headers).forEach(function(headerName){/^content-type$/i.test(headerName)&&(contentType=headers[headerName])}),contentType||(contentType="application/x-www-form-urlencoded; charset=UTF-8;"),request.setRequestHeader("Content-Type",contentType)},_getHeaders:function(){return Utils.extend({},this.opts.headers)}});module.exports=VanillaGateway},{"../create-gateway":2,"../utils":9}],8:[function(require,module,exports){var Utils=require("./utils"),Env=require("./env"),Mapper=function(manifest,Gateway,bodyAttr){this.manifest=manifest,this.rules=this.manifest.rules||[],this.Gateway=Gateway,this.bodyAttr=bodyAttr,this.globalErrorHandler=Utils.noop,this.globalSuccessHandler=Utils.noop};Mapper.prototype={build:function(){return Object.keys(this.manifest.resources||{}).map(function(name){return this.buildResource(name)}.bind(this)).reduce(function(context,resource){return context[resource.name]=resource.methods,context},this.createContext())},createContext:function(){return{onSuccess:function(handler){this.globalSuccessHandler=handler}.bind(this),onError:function(handler){this.globalErrorHandler=handler}.bind(this)}},buildResource:function(resourceName){var methods=this.manifest.resources[resourceName];return Object.keys(methods).reduce(function(context,methodName){var descriptor=methods[methodName];if("string"==typeof descriptor){var compactDefinitionMethod=descriptor.match(/^(get|post|delete|put|patch):(.*)/);descriptor=null!=compactDefinitionMethod?{method:compactDefinitionMethod[1],path:compactDefinitionMethod[2]}:{method:"get",path:descriptor}}return descriptor.method=(descriptor.method||"get").toLowerCase(),context.methods[methodName]=this.newGatewayRequest(descriptor),context}.bind(this),{name:resourceName,methods:{}})},resolvePath:function(pathDefinition,urlParams){var params=Utils.extend({},urlParams),resolvedPath=pathDefinition;delete params[this.bodyAttr],delete params.headers,Object.keys(params).forEach(function(key){var value=params[key],pattern="{"+key+"}";new RegExp(pattern).test(resolvedPath)&&(resolvedPath=resolvedPath.replace("{"+key+"}",value),delete params[key])});var paramsString=Utils.params(params);return 0!==paramsString.length&&(paramsString="?"+paramsString),resolvedPath+paramsString},resolveHost:function(value){return("undefined"==typeof value||null===value)&&(value=this.manifest.host),value===!1&&(value=""),value.replace(/\/$/,"")},resolveRules:function(descriptor,resolvedUrl){return this.rules.filter(function(rule){return void 0===rule.match||rule.match.test(resolvedUrl)}).reduce(function(context,rule){var mergedGateway=Utils.extend(context.gateway,rule.values.gateway);return context=Utils.extend(context,rule.values),context.gateway=mergedGateway,context},{})},newGatewayRequest:function(descriptor){return function(params,callback,opts){"function"==typeof params?(opts=callback,callback=params,params=void 0):callback&&"function"!=typeof callback&&(opts=callback,callback=Utils.noop),descriptor.params&&(params=Utils.extend({},descriptor.params,params));var host=this.resolveHost(descriptor.host),path=this.resolvePath(descriptor.path,params);""!==host&&(path=/^\//.test(path)?path:"/"+path);var fullUrl=host+path,rules=this.resolveRules(descriptor,fullUrl);opts=Utils.extend({},opts,rules.gateway),params&&params.headers&&(opts.headers=Utils.extend(opts.headers,params.headers),delete params.headers),Utils.isObjEmpty(opts)&&(opts=void 0);var body=(params||{})[this.bodyAttr],gatewayOpts=Utils.extend({},{url:fullUrl,host:host,path:path,params:params,body:body,method:descriptor.method,processor:descriptor.processor||rules.processor,opts:opts}),gateway=new this.Gateway(gatewayOpts);return gateway.setSuccessHandler(this.globalSuccessHandler),gateway.setErrorHandler(this.globalErrorHandler),Env.USE_PROMISES?gateway.promisify(callback):gateway.success(callback).call()}.bind(this)}},module.exports=Mapper},{"./env":3,"./utils":9}],9:[function(require,module,exports){function hasProcessHrtime(){return"undefined"!=typeof _process&&null!==_process&&_process.hrtime}function isObject(value){return"[object Object]"===Object.prototype.toString.call(value)}"undefined"!=typeof window&&null!==window&&(window.performance=window.performance||{},performance.now=function(){return performance.now||performance.mozNow||performance.msNow||performance.oNow||performance.webkitNow||function(){return(new Date).getTime()}}());var _process;try{_process=eval("process")}catch(e){}var getNanoSeconds,loadTime;hasProcessHrtime()&&(getNanoSeconds=function(){var hr=_process.hrtime();return 1e9*hr[0]+hr[1]},loadTime=getNanoSeconds());var Utils={r20:/%20/g,noop:function(){},isObjEmpty:function(obj){for(var key in obj)if(obj.hasOwnProperty(key))return!1;return!0},extend:function(out){var options,name,src,copy,clone,target=arguments[0]||{},length=arguments.length;"object"!=typeof target&&(target={});for(var i=1;length>i;i++)if(null!==(options=arguments[i]))for(name in options)src=target[name],copy=options[name],target!==copy&&(copy&&isObject(copy)?(clone=src&&isObject(src)?src:{},target[name]=this.extend(clone,copy)):void 0!==copy&&(target[name]=copy));return target},params:function(entry){if("object"!=typeof entry)return entry;var validKeys=function(entry){return Object.keys(entry).filter(function(key){return void 0!==entry[key]&&null!==entry[key]})},buildRecursive=function(key,value,suffix){suffix=suffix||"";var isArray=Array.isArray(value),isObject="object"==typeof value;return isArray||isObject?isArray?value.map(function(v){return buildRecursive(key,v,suffix+"[]")}).join("&"):validKeys(value).map(function(k){return buildRecursive(key,value[k],suffix+"["+k+"]")}).join("&"):encodeURIComponent(key+suffix)+"="+encodeURIComponent(value)};return validKeys(entry).map(function(key){return buildRecursive(key,entry[key])}).join("&").replace(Utils.r20,"+")},parseResponseHeaders:function(headerStr){var headers={};if(!headerStr)return headers;for(var headerPairs=headerStr.split("\r\n"),i=0;i<headerPairs.length;i++){var headerPair=headerPairs[i],index=headerPair.indexOf(": ");if(index>0){var key=headerPair.substring(0,index).toLowerCase(),val=headerPair.substring(index+2);headers[key]=val}}return headers},performanceNow:function(){return hasProcessHrtime()?(getNanoSeconds()-loadTime)/1e6:performance.now()},humanizeTimeElapsed:function(timeElapsed){return timeElapsed>=1e3?(timeElapsed/1e3).toFixed(2)+" s":timeElapsed.toFixed(2)+" ms"},Exception:function(message){var err=new Error("[Mappersmith] "+message);this.message=err.message,this.stack=err.stack,this.toString=function(){return this.message}}};module.exports=Utils},{}]},{},[1])(1)});
# Changelog
# 0.13.2
- bugfix: prioritizes user-defined content-type header even for post/put/patch/delete methods. `application/x-www-form-urlencoded` is not forced if Content-Type header is defined.
## 0.13.1
- bugfix: wrong content-type on vanilla gateway, a semicolon was missing on `charset=UTF-8`
## 0.13.0

@@ -4,0 +12,0 @@

{
"name": "mappersmith",
"version": "0.13.1",
"version": "0.13.2",
"description": "It is a lightweight, isomorphic, dependency-free, rest client mapper for javascript",

@@ -5,0 +5,0 @@ "author": "Tulio Ornelas <ornelas.tulio@gmail.com>",

@@ -33,2 +33,7 @@ var Utils = require('../utils');

}, opts.headers);
if (opts.headers['content-type']) {
opts.headers['Content-Type'] = opts.headers['content-type'];
delete opts.headers['content-type'];
}
}

@@ -35,0 +40,0 @@

@@ -10,3 +10,3 @@ var Utils = require('../utils');

request.open('GET', this.url, true);
this._setHeaders(request);
this._setUserDefinedHeaders(request);
request.send();

@@ -35,2 +35,3 @@ },

var request = new XMLHttpRequest();
this._configureCallbacks(request);

@@ -46,5 +47,6 @@

if (emulateHTTP) request.setRequestHeader('X-HTTP-Method-Override', method);
request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8;');
this._setHeaders(request);
this._setContentTypeHeader(request);
this._setUserDefinedHeaders(request);
var args = [];

@@ -109,4 +111,4 @@ if (this.body !== undefined) {

_setHeaders: function(request) {
var headers = Utils.extend({}, this.opts.headers);
_setUserDefinedHeaders: function(request) {
var headers = this._getHeaders();
Object.keys(headers).forEach(function(headerName) {

@@ -119,2 +121,18 @@ request.setRequestHeader(headerName, headers[headerName]);

return /application\/json/.test(request.getResponseHeader('Content-Type'));
},
_setContentTypeHeader: function(request) {
var headers = this._getHeaders();
var contentType = null;
Object.keys(headers).forEach(function(headerName) {
if (/^content-type$/i.test(headerName)) contentType = headers[headerName];
});
if (!contentType) contentType = 'application/x-www-form-urlencoded; charset=UTF-8;';
request.setRequestHeader('Content-Type', contentType);
},
_getHeaders: function() {
return Utils.extend({}, this.opts.headers);
}

@@ -121,0 +139,0 @@

@@ -199,2 +199,28 @@ var $ = require('jquery');

});
it('prioritizes user-defined Content-Type header', function(done) {
var body = {val1: 1, val2: 2};
var headers = {'Content-Type': 'text/plain;charset=utf-8'}
var bodyData = Utils.params(body);
makeRequest({
status: 200,
rawData: 'OK',
gateway: newGateway({body: body, opts: {headers: headers}}),
assertHeader: headers
}, done);
});
it('accepts the lowercase variation of Content-Type', function(done) {
var body = {val1: 1, val2: 2};
var headers = {'content-type': 'text/plain;charset=utf-8'}
var bodyData = Utils.params(body);
makeRequest({
status: 200,
rawData: 'OK',
gateway: newGateway({body: body, opts: {headers: headers}}),
assertHeader: {'Content-Type': 'text/plain;charset=utf-8'}
}, done);
});
});

@@ -201,0 +227,0 @@ });

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