@chec/commerce.js
Version:
Easy to use JavaScript SDK for managing carts and selling products from your Chec store
1 lines • 60.2 kB
JavaScript
var Commerce=function(){"use strict";function _objectWithoutPropertiesLoose(source,excluded){if(source==null)return{};var target={};var sourceKeys=Object.keys(source);var key,i;for(i=0;i<sourceKeys.length;i++){key=sourceKeys[i];if(excluded.indexOf(key)>=0)continue;target[key]=source[key]}return target}var objectWithoutPropertiesLoose=_objectWithoutPropertiesLoose;function _objectWithoutProperties(source,excluded){if(source==null)return{};var target=objectWithoutPropertiesLoose(source,excluded);var key,i;if(Object.getOwnPropertySymbols){var sourceSymbolKeys=Object.getOwnPropertySymbols(source);for(i=0;i<sourceSymbolKeys.length;i++){key=sourceSymbolKeys[i];if(excluded.indexOf(key)>=0)continue;if(!Object.prototype.propertyIsEnumerable.call(source,key))continue;target[key]=source[key]}}return target}var objectWithoutProperties=_objectWithoutProperties;function _arrayLikeToArray(arr,len){if(len==null||len>arr.length)len=arr.length;for(var i=0,arr2=new Array(len);i<len;i++){arr2[i]=arr[i]}return arr2}var arrayLikeToArray=_arrayLikeToArray;function _arrayWithoutHoles(arr){if(Array.isArray(arr))return arrayLikeToArray(arr)}var arrayWithoutHoles=_arrayWithoutHoles;function _iterableToArray(iter){if(typeof Symbol!=="undefined"&&Symbol.iterator in Object(iter))return Array.from(iter)}var iterableToArray=_iterableToArray;function _unsupportedIterableToArray(o,minLen){if(!o)return;if(typeof o==="string")return arrayLikeToArray(o,minLen);var n=Object.prototype.toString.call(o).slice(8,-1);if(n==="Object"&&o.constructor)n=o.constructor.name;if(n==="Map"||n==="Set")return Array.from(o);if(n==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n))return arrayLikeToArray(o,minLen)}var unsupportedIterableToArray=_unsupportedIterableToArray;function _nonIterableSpread(){throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var nonIterableSpread=_nonIterableSpread;function _toConsumableArray(arr){return arrayWithoutHoles(arr)||iterableToArray(arr)||unsupportedIterableToArray(arr)||nonIterableSpread()}var toConsumableArray=_toConsumableArray;function createCommonjsModule(fn,module){return module={exports:{}},fn(module,module.exports),module.exports}var _typeof_1=createCommonjsModule((function(module){function _typeof(obj){"@babel/helpers - typeof";if(typeof Symbol==="function"&&typeof Symbol.iterator==="symbol"){module.exports=_typeof=function _typeof(obj){return typeof obj}}else{module.exports=_typeof=function _typeof(obj){return obj&&typeof Symbol==="function"&&obj.constructor===Symbol&&obj!==Symbol.prototype?"symbol":typeof obj}}return _typeof(obj)}module.exports=_typeof}));function _defineProperty(obj,key,value){if(key in obj){Object.defineProperty(obj,key,{value:value,enumerable:true,configurable:true,writable:true})}else{obj[key]=value}return obj}var defineProperty=_defineProperty;function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function")}}var classCallCheck=_classCallCheck;function _defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||false;descriptor.configurable=true;if("value"in descriptor)descriptor.writable=true;Object.defineProperty(target,descriptor.key,descriptor)}}function _createClass(Constructor,protoProps,staticProps){if(protoProps)_defineProperties(Constructor.prototype,protoProps);if(staticProps)_defineProperties(Constructor,staticProps);return Constructor}var createClass=_createClass;var Storage=function(){function Storage(commerce){classCallCheck(this,Storage);this.commerce=commerce}createClass(Storage,[{key:"set",value:function set(key,value,days){if(typeof document==="undefined"||this.commerce.options.disableStorage){return null}var path;var expires="";if(!this.commerce.options.config||typeof this.commerce.options.config.cookie_path==="undefined"){path="/"}else{path=this.commerce.options.config.cookie_path}if(days){var date=new Date;date.setTime(date.getTime()+days*24*60*60*1e3);expires="; expires="+date.toUTCString()}return document.cookie=key+"="+value+expires+"; path="+path}},{key:"get",value:function get(key){if(typeof document==="undefined"||this.commerce.options.disableStorage){return null}key=key+"=";for(var _i=0,_Array$from=Array.from(document.cookie.split(";"));_i<_Array$from.length;_i++){var c=_Array$from[_i];while(c.charAt(0)===" "){c=c.substring(1,c.length)}if(c.indexOf(key)===0){return c.substring(key.length,c.length)}}return null}},{key:"remove",value:function remove(key){return this.set(key,"",-1)}}]);return Storage}();var runtime_1=createCommonjsModule((function(module){var runtime=function(exports){var Op=Object.prototype;var hasOwn=Op.hasOwnProperty;var undefined$1;var $Symbol=typeof Symbol==="function"?Symbol:{};var iteratorSymbol=$Symbol.iterator||"@@iterator";var asyncIteratorSymbol=$Symbol.asyncIterator||"@@asyncIterator";var toStringTagSymbol=$Symbol.toStringTag||"@@toStringTag";function define(obj,key,value){Object.defineProperty(obj,key,{value:value,enumerable:true,configurable:true,writable:true});return obj[key]}try{define({},"")}catch(err){define=function(obj,key,value){return obj[key]=value}}function wrap(innerFn,outerFn,self,tryLocsList){var protoGenerator=outerFn&&outerFn.prototype instanceof Generator?outerFn:Generator;var generator=Object.create(protoGenerator.prototype);var context=new Context(tryLocsList||[]);generator._invoke=makeInvokeMethod(innerFn,self,context);return generator}exports.wrap=wrap;function tryCatch(fn,obj,arg){try{return{type:"normal",arg:fn.call(obj,arg)}}catch(err){return{type:"throw",arg:err}}}var GenStateSuspendedStart="suspendedStart";var GenStateSuspendedYield="suspendedYield";var GenStateExecuting="executing";var GenStateCompleted="completed";var ContinueSentinel={};function Generator(){}function GeneratorFunction(){}function GeneratorFunctionPrototype(){}var IteratorPrototype={};IteratorPrototype[iteratorSymbol]=function(){return this};var getProto=Object.getPrototypeOf;var NativeIteratorPrototype=getProto&&getProto(getProto(values([])));if(NativeIteratorPrototype&&NativeIteratorPrototype!==Op&&hasOwn.call(NativeIteratorPrototype,iteratorSymbol)){IteratorPrototype=NativeIteratorPrototype}var Gp=GeneratorFunctionPrototype.prototype=Generator.prototype=Object.create(IteratorPrototype);GeneratorFunction.prototype=Gp.constructor=GeneratorFunctionPrototype;GeneratorFunctionPrototype.constructor=GeneratorFunction;GeneratorFunction.displayName=define(GeneratorFunctionPrototype,toStringTagSymbol,"GeneratorFunction");function defineIteratorMethods(prototype){["next","throw","return"].forEach((function(method){define(prototype,method,(function(arg){return this._invoke(method,arg)}))}))}exports.isGeneratorFunction=function(genFun){var ctor=typeof genFun==="function"&&genFun.constructor;return ctor?ctor===GeneratorFunction||(ctor.displayName||ctor.name)==="GeneratorFunction":false};exports.mark=function(genFun){if(Object.setPrototypeOf){Object.setPrototypeOf(genFun,GeneratorFunctionPrototype)}else{genFun.__proto__=GeneratorFunctionPrototype;define(genFun,toStringTagSymbol,"GeneratorFunction")}genFun.prototype=Object.create(Gp);return genFun};exports.awrap=function(arg){return{__await:arg}};function AsyncIterator(generator,PromiseImpl){function invoke(method,arg,resolve,reject){var record=tryCatch(generator[method],generator,arg);if(record.type==="throw"){reject(record.arg)}else{var result=record.arg;var value=result.value;if(value&&typeof value==="object"&&hasOwn.call(value,"__await")){return PromiseImpl.resolve(value.__await).then((function(value){invoke("next",value,resolve,reject)}),(function(err){invoke("throw",err,resolve,reject)}))}return PromiseImpl.resolve(value).then((function(unwrapped){result.value=unwrapped;resolve(result)}),(function(error){return invoke("throw",error,resolve,reject)}))}}var previousPromise;function enqueue(method,arg){function callInvokeWithMethodAndArg(){return new PromiseImpl((function(resolve,reject){invoke(method,arg,resolve,reject)}))}return previousPromise=previousPromise?previousPromise.then(callInvokeWithMethodAndArg,callInvokeWithMethodAndArg):callInvokeWithMethodAndArg()}this._invoke=enqueue}defineIteratorMethods(AsyncIterator.prototype);AsyncIterator.prototype[asyncIteratorSymbol]=function(){return this};exports.AsyncIterator=AsyncIterator;exports.async=function(innerFn,outerFn,self,tryLocsList,PromiseImpl){if(PromiseImpl===void 0)PromiseImpl=Promise;var iter=new AsyncIterator(wrap(innerFn,outerFn,self,tryLocsList),PromiseImpl);return exports.isGeneratorFunction(outerFn)?iter:iter.next().then((function(result){return result.done?result.value:iter.next()}))};function makeInvokeMethod(innerFn,self,context){var state=GenStateSuspendedStart;return function invoke(method,arg){if(state===GenStateExecuting){throw new Error("Generator is already running")}if(state===GenStateCompleted){if(method==="throw"){throw arg}return doneResult()}context.method=method;context.arg=arg;while(true){var delegate=context.delegate;if(delegate){var delegateResult=maybeInvokeDelegate(delegate,context);if(delegateResult){if(delegateResult===ContinueSentinel)continue;return delegateResult}}if(context.method==="next"){context.sent=context._sent=context.arg}else if(context.method==="throw"){if(state===GenStateSuspendedStart){state=GenStateCompleted;throw context.arg}context.dispatchException(context.arg)}else if(context.method==="return"){context.abrupt("return",context.arg)}state=GenStateExecuting;var record=tryCatch(innerFn,self,context);if(record.type==="normal"){state=context.done?GenStateCompleted:GenStateSuspendedYield;if(record.arg===ContinueSentinel){continue}return{value:record.arg,done:context.done}}else if(record.type==="throw"){state=GenStateCompleted;context.method="throw";context.arg=record.arg}}}}function maybeInvokeDelegate(delegate,context){var method=delegate.iterator[context.method];if(method===undefined$1){context.delegate=null;if(context.method==="throw"){if(delegate.iterator["return"]){context.method="return";context.arg=undefined$1;maybeInvokeDelegate(delegate,context);if(context.method==="throw"){return ContinueSentinel}}context.method="throw";context.arg=new TypeError("The iterator does not provide a 'throw' method")}return ContinueSentinel}var record=tryCatch(method,delegate.iterator,context.arg);if(record.type==="throw"){context.method="throw";context.arg=record.arg;context.delegate=null;return ContinueSentinel}var info=record.arg;if(!info){context.method="throw";context.arg=new TypeError("iterator result is not an object");context.delegate=null;return ContinueSentinel}if(info.done){context[delegate.resultName]=info.value;context.next=delegate.nextLoc;if(context.method!=="return"){context.method="next";context.arg=undefined$1}}else{return info}context.delegate=null;return ContinueSentinel}defineIteratorMethods(Gp);define(Gp,toStringTagSymbol,"Generator");Gp[iteratorSymbol]=function(){return this};Gp.toString=function(){return"[object Generator]"};function pushTryEntry(locs){var entry={tryLoc:locs[0]};if(1 in locs){entry.catchLoc=locs[1]}if(2 in locs){entry.finallyLoc=locs[2];entry.afterLoc=locs[3]}this.tryEntries.push(entry)}function resetTryEntry(entry){var record=entry.completion||{};record.type="normal";delete record.arg;entry.completion=record}function Context(tryLocsList){this.tryEntries=[{tryLoc:"root"}];tryLocsList.forEach(pushTryEntry,this);this.reset(true)}exports.keys=function(object){var keys=[];for(var key in object){keys.push(key)}keys.reverse();return function next(){while(keys.length){var key=keys.pop();if(key in object){next.value=key;next.done=false;return next}}next.done=true;return next}};function values(iterable){if(iterable){var iteratorMethod=iterable[iteratorSymbol];if(iteratorMethod){return iteratorMethod.call(iterable)}if(typeof iterable.next==="function"){return iterable}if(!isNaN(iterable.length)){var i=-1,next=function next(){while(++i<iterable.length){if(hasOwn.call(iterable,i)){next.value=iterable[i];next.done=false;return next}}next.value=undefined$1;next.done=true;return next};return next.next=next}}return{next:doneResult}}exports.values=values;function doneResult(){return{value:undefined$1,done:true}}Context.prototype={constructor:Context,reset:function(skipTempReset){this.prev=0;this.next=0;this.sent=this._sent=undefined$1;this.done=false;this.delegate=null;this.method="next";this.arg=undefined$1;this.tryEntries.forEach(resetTryEntry);if(!skipTempReset){for(var name in this){if(name.charAt(0)==="t"&&hasOwn.call(this,name)&&!isNaN(+name.slice(1))){this[name]=undefined$1}}}},stop:function(){this.done=true;var rootEntry=this.tryEntries[0];var rootRecord=rootEntry.completion;if(rootRecord.type==="throw"){throw rootRecord.arg}return this.rval},dispatchException:function(exception){if(this.done){throw exception}var context=this;function handle(loc,caught){record.type="throw";record.arg=exception;context.next=loc;if(caught){context.method="next";context.arg=undefined$1}return!!caught}for(var i=this.tryEntries.length-1;i>=0;--i){var entry=this.tryEntries[i];var record=entry.completion;if(entry.tryLoc==="root"){return handle("end")}if(entry.tryLoc<=this.prev){var hasCatch=hasOwn.call(entry,"catchLoc");var hasFinally=hasOwn.call(entry,"finallyLoc");if(hasCatch&&hasFinally){if(this.prev<entry.catchLoc){return handle(entry.catchLoc,true)}else if(this.prev<entry.finallyLoc){return handle(entry.finallyLoc)}}else if(hasCatch){if(this.prev<entry.catchLoc){return handle(entry.catchLoc,true)}}else if(hasFinally){if(this.prev<entry.finallyLoc){return handle(entry.finallyLoc)}}else{throw new Error("try statement without catch or finally")}}}},abrupt:function(type,arg){for(var i=this.tryEntries.length-1;i>=0;--i){var entry=this.tryEntries[i];if(entry.tryLoc<=this.prev&&hasOwn.call(entry,"finallyLoc")&&this.prev<entry.finallyLoc){var finallyEntry=entry;break}}if(finallyEntry&&(type==="break"||type==="continue")&&finallyEntry.tryLoc<=arg&&arg<=finallyEntry.finallyLoc){finallyEntry=null}var record=finallyEntry?finallyEntry.completion:{};record.type=type;record.arg=arg;if(finallyEntry){this.method="next";this.next=finallyEntry.finallyLoc;return ContinueSentinel}return this.complete(record)},complete:function(record,afterLoc){if(record.type==="throw"){throw record.arg}if(record.type==="break"||record.type==="continue"){this.next=record.arg}else if(record.type==="return"){this.rval=this.arg=record.arg;this.method="return";this.next="end"}else if(record.type==="normal"&&afterLoc){this.next=afterLoc}return ContinueSentinel},finish:function(finallyLoc){for(var i=this.tryEntries.length-1;i>=0;--i){var entry=this.tryEntries[i];if(entry.finallyLoc===finallyLoc){this.complete(entry.completion,entry.afterLoc);resetTryEntry(entry);return ContinueSentinel}}},catch:function(tryLoc){for(var i=this.tryEntries.length-1;i>=0;--i){var entry=this.tryEntries[i];if(entry.tryLoc===tryLoc){var record=entry.completion;if(record.type==="throw"){var thrown=record.arg;resetTryEntry(entry)}return thrown}}throw new Error("illegal catch attempt")},delegateYield:function(iterable,resultName,nextLoc){this.delegate={iterator:values(iterable),resultName:resultName,nextLoc:nextLoc};if(this.method==="next"){this.arg=undefined$1}return ContinueSentinel}};return exports}(module.exports);try{regeneratorRuntime=runtime}catch(accidentalStrictMode){Function("r","regeneratorRuntime = r")(runtime)}}));var regenerator=runtime_1;function asyncGeneratorStep(gen,resolve,reject,_next,_throw,key,arg){try{var info=gen[key](arg);var value=info.value}catch(error){reject(error);return}if(info.done){resolve(value)}else{Promise.resolve(value).then(_next,_throw)}}function _asyncToGenerator(fn){return function(){var self=this,args=arguments;return new Promise((function(resolve,reject){var gen=fn.apply(self,args);function _next(value){asyncGeneratorStep(gen,resolve,reject,_next,_throw,"next",value)}function _throw(err){asyncGeneratorStep(gen,resolve,reject,_next,_throw,"throw",err)}_next(undefined)}))}}var asyncToGenerator=_asyncToGenerator;function ownKeys(object,enumerableOnly){var keys=Object.keys(object);if(Object.getOwnPropertySymbols){var symbols=Object.getOwnPropertySymbols(object);if(enumerableOnly)symbols=symbols.filter((function(sym){return Object.getOwnPropertyDescriptor(object,sym).enumerable}));keys.push.apply(keys,symbols)}return keys}function _objectSpread(target){for(var i=1;i<arguments.length;i++){var source=arguments[i]!=null?arguments[i]:{};if(i%2){ownKeys(source,true).forEach((function(key){defineProperty(target,key,source[key])}))}else if(Object.getOwnPropertyDescriptors){Object.defineProperties(target,Object.getOwnPropertyDescriptors(source))}else{ownKeys(source).forEach((function(key){Object.defineProperty(target,key,Object.getOwnPropertyDescriptor(source,key))}))}}return target}var Cart=function(){function Cart(commerce){classCallCheck(this,Cart);this.commerce=commerce;this.cartId=null}createClass(Cart,[{key:"refresh",value:function refresh(){var _this=this;return this.commerce.request("carts").then((function(cart){var id=cart.id;_this.commerce.storage.set("commercejs_cart_id",id,_this.commerce.options.cartLifetime);_this.cartId=id;return cart}))}},{key:"id",value:function id(){if(this.cartId!==null){return this.cartId}var storedCartId=this.commerce.storage.get("commercejs_cart_id");if(typeof storedCartId==="string"&&storedCartId.length){return storedCartId}return null}},{key:"request",value:function(){var _request=asyncToGenerator(regenerator.mark((function _callee(){var _this2=this;var endpoint,method,data,returnFullRequest,suffix,_args=arguments;return regenerator.wrap((function _callee$(_context){while(1){switch(_context.prev=_context.next){case 0:endpoint=_args.length>0&&_args[0]!==undefined?_args[0]:"";method=_args.length>1&&_args[1]!==undefined?_args[1]:"get";data=_args.length>2&&_args[2]!==undefined?_args[2]:null;returnFullRequest=_args.length>3&&_args[3]!==undefined?_args[3]:false;suffix=typeof endpoint==="string"&&endpoint.length?"/".concat(endpoint):"";if(this.id()){_context.next=8;break}_context.next=8;return this.refresh();case 8:return _context.abrupt("return",this.commerce.request("carts/".concat(this.id()).concat(suffix),method,data,returnFullRequest).catch((function(error){if(error.statusCode&&error.statusCode===404){return _this2.refresh().then((function(){return _this2.commerce.request("carts/".concat(_this2.id()).concat(suffix),method,data,returnFullRequest)}))}throw error})));case 9:case"end":return _context.stop()}}}),_callee,this)})));function request(){return _request.apply(this,arguments)}return request}()},{key:"add",value:function add(productId){var quantity=arguments.length>1&&arguments[1]!==undefined?arguments[1]:1;var variantData=arguments.length>2&&arguments[2]!==undefined?arguments[2]:null;var validatedVariant={};if(typeof variantData==="string"&&variantData.startsWith("vrnt")){validatedVariant.variant_id=variantData}else if(variantData&&_typeof_1(variantData)==="object"){var validKeys=Object.keys(variantData).every((function(key){return key.startsWith("vgrp")}));var validValues=Object.values(variantData).every((function(key){return key.startsWith("optn")}));if(!validKeys||!validValues){throw new Error("The variant options provided to cart.add do not appear to be a valid map of group IDs to option IDs")}validatedVariant.options=variantData}else if(variantData){throw new Error("Variant data provided to cart.add must be a variant ID, or a map of group IDs to option IDs")}var data=_objectSpread({id:_typeof_1(productId)==="object"?productId.id:productId,quantity:quantity},validatedVariant);return this.request("","post",data)}},{key:"retrieve",value:function retrieve(){var _this3=this;var cartId=arguments.length>0&&arguments[0]!==undefined?arguments[0]:null;if(cartId){this.cartId=cartId}return this.request().then((function(cart){_this3.cartId=cart&&cart.id||null;return cart}))}},{key:"checkQuantity",value:function checkQuantity(productId,quantity){return this.commerce.request("products/".concat(productId)).then((function(response){return quantity<=response.quantity}))}},{key:"remove",value:function remove(lineId){return this.request("items/".concat(lineId),"delete")}},{key:"delete",value:function _delete(){return this.request("","delete")}},{key:"update",value:function update(lineId,data){return this.request("items/".concat(lineId),"put",data)}},{key:"contents",value:function contents(){return this.request("items")}},{key:"empty",value:function empty(){return this.request("items","delete")}}]);return Cart}();var Categories=function(){function Categories(commerce){classCallCheck(this,Categories);this.commerce=commerce}createClass(Categories,[{key:"list",value:function list(){var params=arguments.length>0&&arguments[0]!==undefined?arguments[0]:null;if(typeof params==="function"){return this.commerce.request("categories")}return this.commerce.request("categories","get",params)}},{key:"retrieve",value:function retrieve(id){var data=arguments.length>1&&arguments[1]!==undefined?arguments[1]:{};return this.commerce.request("categories/".concat(id),"get",data)}}]);return Categories}();var Checkout=function(){function Checkout(commerce){classCallCheck(this,Checkout);this.commerce=commerce}createClass(Checkout,[{key:"protect",value:function protect(token){return this.commerce.request("checkouts/".concat(token,"/protect")).then((function(data){return eval(data.sift_js)}))}},{key:"generateToken",value:function generateToken(identifier,data){return this.commerce.request("checkouts/".concat(identifier),"get",data)}},{key:"generateTokenFrom",value:function generateTokenFrom(type,identifier){if(!["product_id","cart","permalink"].includes(type)){throw new Error('Cannot generate a token with unknown "'.concat(type,'" type'))}return this.generateToken(identifier,{type:type})}},{key:"capture",value:function capture(token,data){var _this=this;return this.commerce.request("checkouts/".concat(token),"post",data).then((function(response){_this.commerce.cart.refresh();return response}))}},{key:"receipt",value:function receipt(token){return this.commerce.request("checkouts/".concat(token,"/receipt"))}},{key:"checkPayWhatYouWant",value:function checkPayWhatYouWant(token,data){return this.commerce.request("checkouts/".concat(token,"/check/pay_what_you_want"),"get",data)}},{key:"fields",value:function fields(identifier){return this.commerce.request("checkouts/".concat(identifier,"/fields"))}},{key:"setTaxZone",value:function setTaxZone(identifier,data){return this.commerce.request("checkouts/".concat(identifier,"/helper/set_tax_zone"),"get",data)}},{key:"getLocationFromIP",value:function getLocationFromIP(token){var ipAddress=arguments.length>1&&arguments[1]!==undefined?arguments[1]:"";var urlSuffix=ipAddress&&ipAddress.length?"?ip_address=".concat(ipAddress):"";return this.commerce.request("checkouts/".concat(token,"/helper/location_from_ip").concat(urlSuffix))}},{key:"isFree",value:function isFree(token){return this.commerce.request("checkouts/".concat(token,"/check/is_free"))}},{key:"checkVariant",value:function checkVariant(token,lineItemId,data){return this.commerce.request("checkouts/".concat(token,"/check/").concat(lineItemId,"/variant"),"get",data)}},{key:"checkDiscount",value:function checkDiscount(token,data){return this.commerce.request("checkouts/".concat(token,"/check/discount"),"get",data)}},{key:"checkShippingOption",value:function checkShippingOption(token,data){return this.commerce.request("checkouts/".concat(token,"/check/shipping"),"get",data)}},{key:"getShippingOptions",value:function getShippingOptions(token,data){return this.commerce.request("checkouts/".concat(token,"/helper/shipping_options"),"get",data)}},{key:"checkQuantity",value:function checkQuantity(token,lineItem,data){return this.commerce.request("checkouts/".concat(token,"/check/").concat(lineItem,"/quantity"),"get",data)}},{key:"helperValidation",value:function helperValidation(token){return this.commerce.request("checkouts/".concat(token,"/helper/validation"))}},{key:"getLive",value:function getLive(token){return this.commerce.request("checkouts/".concat(token,"/live"))}},{key:"getToken",value:function getToken(token){return this.commerce.request("checkouts/tokens/".concat(token))}},{key:"checkGiftcard",value:function checkGiftcard(token,data){return this.commerce.request("checkouts/".concat(token,"/check/giftcard"),"get",data)}}]);return Checkout}();function ownKeys$1(object,enumerableOnly){var keys=Object.keys(object);if(Object.getOwnPropertySymbols){var symbols=Object.getOwnPropertySymbols(object);if(enumerableOnly)symbols=symbols.filter((function(sym){return Object.getOwnPropertyDescriptor(object,sym).enumerable}));keys.push.apply(keys,symbols)}return keys}function _objectSpread$1(target){for(var i=1;i<arguments.length;i++){var source=arguments[i]!=null?arguments[i]:{};if(i%2){ownKeys$1(source,true).forEach((function(key){defineProperty(target,key,source[key])}))}else if(Object.getOwnPropertyDescriptors){Object.defineProperties(target,Object.getOwnPropertyDescriptors(source))}else{ownKeys$1(source).forEach((function(key){Object.defineProperty(target,key,Object.getOwnPropertyDescriptor(source,key))}))}}return target}var Customer=function(){function Customer(commerce){classCallCheck(this,Customer);this.commerce=commerce;this.data={}}createClass(Customer,[{key:"login",value:function login(email,baseUrl){return this.commerce.request("customers/email-token","post",{email:email,base_url:baseUrl})}},{key:"getToken",value:function getToken(token){var _this=this;var save=arguments.length>1&&arguments[1]!==undefined?arguments[1]:true;return this.commerce.request("customers/exchange-token","post",{token:token}).then((function(result){if(save&&(result.customer_id||result.jwt)){_this.data={id:result.customer_id||null,token:result.jwt||null};window.localStorage.setItem("commercejs_customer_id",_this.data.id);window.localStorage.setItem("commercejs_customer_token",_this.data.token)}return result}))}},{key:"update",value:function update(){var data=arguments.length>0&&arguments[0]!==undefined?arguments[0]:{};var customerId=arguments.length>1&&arguments[1]!==undefined?arguments[1]:null;var token=arguments.length>2&&arguments[2]!==undefined?arguments[2]:null;this._assertArgsProvided(customerId,token);return this._request("customers/".concat(customerId||this.id()),"PUT",data,{},token)}},{key:"getOrders",value:function getOrders(){var customerId=arguments.length>0&&arguments[0]!==undefined?arguments[0]:null;var token=arguments.length>1&&arguments[1]!==undefined?arguments[1]:null;var params=arguments.length>2&&arguments[2]!==undefined?arguments[2]:{};this._assertArgsProvided(customerId,token);var requestParams=_objectSpread$1({sortBy:"created_at",sortDirection:"desc"},params);return this._request("customers/".concat(customerId||this.id(),"/orders"),"get",requestParams,{},token)}},{key:"getOrder",value:function getOrder(orderId){var customerId=arguments.length>1&&arguments[1]!==undefined?arguments[1]:null;var token=arguments.length>2&&arguments[2]!==undefined?arguments[2]:null;this._assertArgsProvided(customerId,token);return this._request("customers/".concat(customerId||this.id(),"/orders/").concat(orderId),"get",{},{},token)}},{key:"about",value:function about(){return this._request("customers/".concat(this.id()))}},{key:"id",value:function id(){return this._fromStorage("id")}},{key:"token",value:function token(){return this._fromStorage("token")}},{key:"isLoggedIn",value:function isLoggedIn(){return this.id()!==null&&this.token()!==null}},{key:"logout",value:function logout(){this.data={};window.localStorage.removeItem("commercejs_customer_id");window.localStorage.removeItem("commercejs_customer_token")}},{key:"_fromStorage",value:function _fromStorage(key){if(this.data[key]&&this.data[key].length){return this.data[key]}var storedValue=window.localStorage.getItem("commercejs_customer_".concat(key));if(typeof storedValue==="string"&&storedValue.length){return storedValue}return null}},{key:"_request",value:function _request(endpoint){var method=arguments.length>1&&arguments[1]!==undefined?arguments[1]:"get";var data=arguments.length>2&&arguments[2]!==undefined?arguments[2]:null;var extraHeaders=arguments.length>3&&arguments[3]!==undefined?arguments[3]:{};var token=arguments.length>4&&arguments[4]!==undefined?arguments[4]:null;var authToken=token||this.token();return this.commerce.request(endpoint,method,data,_objectSpread$1({"X-Authorization":undefined,Authorization:"Bearer ".concat(authToken)},extraHeaders))}},{key:"_assertArgsProvided",value:function _assertArgsProvided(){var customerId=arguments.length>0&&arguments[0]!==undefined?arguments[0]:null;var token=arguments.length>1&&arguments[1]!==undefined?arguments[1]:null;if(customerId===null&&!this.id()){throw new Error("A customer ID must be provided when customer is not logged in")}if(token===null&&!this.token()){throw new Error("A customer access token must be provided when customer is not logged in")}}}]);return Customer}();var Merchants=function(){function Merchants(commerce){classCallCheck(this,Merchants);this.commerce=commerce}createClass(Merchants,[{key:"about",value:function about(){return this.commerce.request("merchants")}}]);return Merchants}();var Products=function(){function Products(commerce){classCallCheck(this,Products);this.commerce=commerce}createClass(Products,[{key:"list",value:function list(){var params=arguments.length>0&&arguments[0]!==undefined?arguments[0]:null;return this.commerce.request("products","get",params)}},{key:"retrieve",value:function retrieve(id){var data=arguments.length>1&&arguments[1]!==undefined?arguments[1]:{};return this.commerce.request("products/".concat(id),"get",data)}},{key:"getVariants",value:function getVariants(productId){var params=arguments.length>1&&arguments[1]!==undefined?arguments[1]:null;return this.commerce.request("products/".concat(productId,"/variants"),"get",params)}},{key:"getVariant",value:function getVariant(productId,variantId){return this.commerce.request("products/".concat(productId,"/variants/").concat(variantId),"get")}}]);return Products}();var Services=function(){function Services(commerce){classCallCheck(this,Services);this.commerce=commerce}createClass(Services,[{key:"localeListCountries",value:function localeListCountries(){return this.commerce.request("services/locale/countries")}},{key:"localeListShippingCountries",value:function localeListShippingCountries(token){return this.commerce.request("services/locale/".concat(token,"/countries"))}},{key:"localeListShippingSubdivisions",value:function localeListShippingSubdivisions(token,countryCode){return this.commerce.request("services/locale/".concat(token,"/countries/").concat(countryCode,"/subdivisions"))}},{key:"localeListSubdivisions",value:function localeListSubdivisions(countryCode){return this.commerce.request("services/locale/".concat(countryCode,"/subdivisions"))}}]);return Services}();var Features={Cart:Cart,Categories:Categories,Checkout:Checkout,Customer:Customer,Merchants:Merchants,Products:Products,Services:Services};var consoleHelper=function consoleHelper(){var color=arguments.length>0&&arguments[0]!==undefined?arguments[0]:"black";var a=arguments.length>1?arguments[1]:undefined;var b=arguments.length>2?arguments[2]:undefined;var c=arguments.length>3?arguments[3]:undefined;var emoji;var isError=false;var messages;switch(color){case"success":color="#488f5a";emoji="✅ ";break;case"info":color="DodgerBlue";emoji="";break;case"error":color="rgba(244, 67, 54, 1)";if(c.error.type==="validation"||c.error.type==="unprocessable_entity"){emoji="🚫 Validation/missing fields";a=""}else{emoji="❌ HTTP ERROR "}isError=true;break;case"warning":color="rgba(208, 154, 35, 1)";emoji="⚠️ "}if(isError===true){console.log("%c"+emoji+a,"color:"+color+";display:block; width: 100%;padding:2px 2px 2px 0px;font-family: Open Sans, Helvetica, Sans-serif;font-weight:bold;background-color:rgba(244, 67, 54, 0.15);");if(_typeof_1(c.error.errors)==="object"){messages=c.error.errors;Object.keys(messages).forEach((function(key,index){Object.values(messages[key]).forEach((function(value){console.log("%c"+key+": %c"+value,"color:#515D6D;font-family: Open Sans, Helvetica, Sans-serif;font-weight:800;","color:#515D6D;font-family: Open Sans, Helvetica, Sans-serif;font-weight:400;")}))}));return}return console.log("%c"+c.error.message,"color:#515D6D;font-family: Open Sans, Helvetica, Sans-serif;font-weight:400;")}if(_typeof_1(color)==="object"){console.log("%c"+a,"color: PowderBlue;font-weight:bold;font-family: Open Sans, Helvetica, Sans-serif; background-color: RoyalBlue;");console.log(color);return}console.log("%c"+emoji+a,"color:"+color+";display:block;font-family: Open Sans, Helvetica, Sans-serif;line-height:28px; width: 100%;padding:2px 2px 2px 0px;font-weight:bold;");if(b){console.log("%c"+b,"color:#515D6D;line-height:22px;font-weight:400; font-family: Open Sans, Helvetica, Sans-serif;")}};var debuggerOnNotice=function debuggerOnNotice(){if(typeof window==="undefined"){return}var ascii="\r\n \r\n Che EcC\r\n c....c2 2c....:C\r\n c........c2 2c.....:C\r\n c............c2 2c.....:C\r\n c................c2 2c.....:C\r\n c....................c2 2c.....:C\r\n c........................c2 2c.....:C\r\n c............................c2 2c.....:C\r\n c.......:E2 2c..................c2 2c.....:C\r\n c........h $$ 2c..................c2 2c.....:C\r\n c.........:C $cc$ E....................c2 2c.....:C\r\n c............h $$ c......................c2 2c.....:C\r\n c...............:E E:.........................c2 2c.....:C\r\n E............................:C c..................h2 2c...:C\r\n E........................:C c..................h2 2hC\r\n E....................:C c..................h2\r\n E................:C c................:C\r\n E............:C c............:C\r\n E........:C c........:C\r\n E....:C c....:C\r\n EcC EcC\r\n \r\n \r\n \r\n";console.log("%c"+ascii,"font-family: Courier New, Courier, monospace; color: #788ba4; font-weight:bold; font-size: 11px;");console.log("%cCommerce.js console debugger is on! 🎉","text-align:center; display:block; font-family: Open Sans, Helvetica, Sans-serif; color: #488f5a; line-height:28px; font-size: 14px");console.log("%c💬 Need some help? Join our Slack channel - http://slack.commercejs.com \r\n","text-align:center; display:block; font-family: Open Sans, Helvetica, Sans-serif; color: #515D6D; line-height:20px; font-size: 12px")};var bind=function bind(fn,thisArg){return function wrap(){var args=new Array(arguments.length);for(var i=0;i<args.length;i++){args[i]=arguments[i]}return fn.apply(thisArg,args)}};var toString=Object.prototype.toString;function isArray(val){return toString.call(val)==="[object Array]"}function isUndefined(val){return typeof val==="undefined"}function isBuffer(val){return val!==null&&!isUndefined(val)&&val.constructor!==null&&!isUndefined(val.constructor)&&typeof val.constructor.isBuffer==="function"&&val.constructor.isBuffer(val)}function isArrayBuffer(val){return toString.call(val)==="[object ArrayBuffer]"}function isFormData(val){return typeof FormData!=="undefined"&&val instanceof FormData}function isArrayBufferView(val){var result;if(typeof ArrayBuffer!=="undefined"&&ArrayBuffer.isView){result=ArrayBuffer.isView(val)}else{result=val&&val.buffer&&val.buffer instanceof ArrayBuffer}return result}function isString(val){return typeof val==="string"}function isNumber(val){return typeof val==="number"}function isObject(val){return val!==null&&typeof val==="object"}function isPlainObject(val){if(toString.call(val)!=="[object Object]"){return false}var prototype=Object.getPrototypeOf(val);return prototype===null||prototype===Object.prototype}function isDate(val){return toString.call(val)==="[object Date]"}function isFile(val){return toString.call(val)==="[object File]"}function isBlob(val){return toString.call(val)==="[object Blob]"}function isFunction(val){return toString.call(val)==="[object Function]"}function isStream(val){return isObject(val)&&isFunction(val.pipe)}function isURLSearchParams(val){return typeof URLSearchParams!=="undefined"&&val instanceof URLSearchParams}function trim(str){return str.replace(/^\s*/,"").replace(/\s*$/,"")}function isStandardBrowserEnv(){if(typeof navigator!=="undefined"&&(navigator.product==="ReactNative"||navigator.product==="NativeScript"||navigator.product==="NS")){return false}return typeof window!=="undefined"&&typeof document!=="undefined"}function forEach(obj,fn){if(obj===null||typeof obj==="undefined"){return}if(typeof obj!=="object"){obj=[obj]}if(isArray(obj)){for(var i=0,l=obj.length;i<l;i++){fn.call(null,obj[i],i,obj)}}else{for(var key in obj){if(Object.prototype.hasOwnProperty.call(obj,key)){fn.call(null,obj[key],key,obj)}}}}function merge(){var result={};function assignValue(val,key){if(isPlainObject(result[key])&&isPlainObject(val)){result[key]=merge(result[key],val)}else if(isPlainObject(val)){result[key]=merge({},val)}else if(isArray(val)){result[key]=val.slice()}else{result[key]=val}}for(var i=0,l=arguments.length;i<l;i++){forEach(arguments[i],assignValue)}return result}function extend(a,b,thisArg){forEach(b,(function assignValue(val,key){if(thisArg&&typeof val==="function"){a[key]=bind(val,thisArg)}else{a[key]=val}}));return a}function stripBOM(content){if(content.charCodeAt(0)===65279){content=content.slice(1)}return content}var utils={isArray:isArray,isArrayBuffer:isArrayBuffer,isBuffer:isBuffer,isFormData:isFormData,isArrayBufferView:isArrayBufferView,isString:isString,isNumber:isNumber,isObject:isObject,isPlainObject:isPlainObject,isUndefined:isUndefined,isDate:isDate,isFile:isFile,isBlob:isBlob,isFunction:isFunction,isStream:isStream,isURLSearchParams:isURLSearchParams,isStandardBrowserEnv:isStandardBrowserEnv,forEach:forEach,merge:merge,extend:extend,trim:trim,stripBOM:stripBOM};function encode(val){return encodeURIComponent(val).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+").replace(/%5B/gi,"[").replace(/%5D/gi,"]")}var buildURL=function buildURL(url,params,paramsSerializer){if(!params){return url}var serializedParams;if(paramsSerializer){serializedParams=paramsSerializer(params)}else if(utils.isURLSearchParams(params)){serializedParams=params.toString()}else{var parts=[];utils.forEach(params,(function serialize(val,key){if(val===null||typeof val==="undefined"){return}if(utils.isArray(val)){key=key+"[]"}else{val=[val]}utils.forEach(val,(function parseValue(v){if(utils.isDate(v)){v=v.toISOString()}else if(utils.isObject(v)){v=JSON.stringify(v)}parts.push(encode(key)+"="+encode(v))}))}));serializedParams=parts.join("&")}if(serializedParams){var hashmarkIndex=url.indexOf("#");if(hashmarkIndex!==-1){url=url.slice(0,hashmarkIndex)}url+=(url.indexOf("?")===-1?"?":"&")+serializedParams}return url};function InterceptorManager(){this.handlers=[]}InterceptorManager.prototype.use=function use(fulfilled,rejected){this.handlers.push({fulfilled:fulfilled,rejected:rejected});return this.handlers.length-1};InterceptorManager.prototype.eject=function eject(id){if(this.handlers[id]){this.handlers[id]=null}};InterceptorManager.prototype.forEach=function forEach(fn){utils.forEach(this.handlers,(function forEachHandler(h){if(h!==null){fn(h)}}))};var InterceptorManager_1=InterceptorManager;var transformData=function transformData(data,headers,fns){utils.forEach(fns,(function transform(fn){data=fn(data,headers)}));return data};var isCancel=function isCancel(value){return!!(value&&value.__CANCEL__)};var normalizeHeaderName=function normalizeHeaderName(headers,normalizedName){utils.forEach(headers,(function processHeader(value,name){if(name!==normalizedName&&name.toUpperCase()===normalizedName.toUpperCase()){headers[normalizedName]=value;delete headers[name]}}))};var enhanceError=function enhanceError(error,config,code,request,response){error.config=config;if(code){error.code=code}error.request=request;error.response=response;error.isAxiosError=true;error.toJSON=function toJSON(){return{message:this.message,name:this.name,description:this.description,number:this.number,fileName:this.fileName,lineNumber:this.lineNumber,columnNumber:this.columnNumber,stack:this.stack,config:this.config,code:this.code}};return error};var createError=function createError(message,config,code,request,response){var error=new Error(message);return enhanceError(error,config,code,request,response)};var settle=function settle(resolve,reject,response){var validateStatus=response.config.validateStatus;if(!response.status||!validateStatus||validateStatus(response.status)){resolve(response)}else{reject(createError("Request failed with status code "+response.status,response.config,null,response.request,response))}};var cookies=utils.isStandardBrowserEnv()?function standardBrowserEnv(){return{write:function write(name,value,expires,path,domain,secure){var cookie=[];cookie.push(name+"="+encodeURIComponent(value));if(utils.isNumber(expires)){cookie.push("expires="+new Date(expires).toGMTString())}if(utils.isString(path)){cookie.push("path="+path)}if(utils.isString(domain)){cookie.push("domain="+domain)}if(secure===true){cookie.push("secure")}document.cookie=cookie.join("; ")},read:function read(name){var match=document.cookie.match(new RegExp("(^|;\\s*)("+name+")=([^;]*)"));return match?decodeURIComponent(match[3]):null},remove:function remove(name){this.write(name,"",Date.now()-864e5)}}}():function nonStandardBrowserEnv(){return{write:function write(){},read:function read(){return null},remove:function remove(){}}}();var isAbsoluteURL=function isAbsoluteURL(url){return/^([a-z][a-z\d\+\-\.]*:)?\/\//i.test(url)};var combineURLs=function combineURLs(baseURL,relativeURL){return relativeURL?baseURL.replace(/\/+$/,"")+"/"+relativeURL.replace(/^\/+/,""):baseURL};var buildFullPath=function buildFullPath(baseURL,requestedURL){if(baseURL&&!isAbsoluteURL(requestedURL)){return combineURLs(baseURL,requestedURL)}return requestedURL};var ignoreDuplicateOf=["age","authorization","content-length","content-type","etag","expires","from","host","if-modified-since","if-unmodified-since","last-modified","location","max-forwards","proxy-authorization","referer","retry-after","user-agent"];var parseHeaders=function parseHeaders(headers){var parsed={};var key;var val;var i;if(!headers){return parsed}utils.forEach(headers.split("\n"),(function parser(line){i=line.indexOf(":");key=utils.trim(line.substr(0,i)).toLowerCase();val=utils.trim(line.substr(i+1));if(key){if(parsed[key]&&ignoreDuplicateOf.indexOf(key)>=0){return}if(key==="set-cookie"){parsed[key]=(parsed[key]?parsed[key]:[]).concat([val])}else{parsed[key]=parsed[key]?parsed[key]+", "+val:val}}}));return parsed};var isURLSameOrigin=utils.isStandardBrowserEnv()?function standardBrowserEnv(){var msie=/(msie|trident)/i.test(navigator.userAgent);var urlParsingNode=document.createElement("a");var originURL;function resolveURL(url){var href=url;if(msie){urlParsingNode.setAttribute("href",href);href=urlParsingNode.href}urlParsingNode.setAttribute("href",href);return{href:urlParsingNode.href,protocol:urlParsingNode.protocol?urlParsingNode.protocol.replace(/:$/,""):"",host:urlParsingNode.host,search:urlParsingNode.search?urlParsingNode.search.replace(/^\?/,""):"",hash:urlParsingNode.hash?urlParsingNode.hash.replace(/^#/,""):"",hostname:urlParsingNode.hostname,port:urlParsingNode.port,pathname:urlParsingNode.pathname.charAt(0)==="/"?urlParsingNode.pathname:"/"+urlParsingNode.pathname}}originURL=resolveURL(window.location.href);return function isURLSameOrigin(requestURL){var parsed=utils.isString(requestURL)?resolveURL(requestURL):requestURL;return parsed.protocol===originURL.protocol&&parsed.host===originURL.host}}():function nonStandardBrowserEnv(){return function isURLSameOrigin(){return true}}();var xhr=function xhrAdapter(config){return new Promise((function dispatchXhrRequest(resolve,reject){var requestData=config.data;var requestHeaders=config.headers;if(utils.isFormData(requestData)){delete requestHeaders["Content-Type"]}var request=new XMLHttpRequest;if(config.auth){var username=config.auth.username||"";var password=config.auth.password?unescape(encodeURIComponent(config.auth.password)):"";requestHeaders.Authorization="Basic "+btoa(username+":"+password)}var fullPath=buildFullPath(config.baseURL,config.url);request.open(config.method.toUpperCase(),buildURL(fullPath,config.params,config.paramsSerializer),true);request.timeout=config.timeout;request.onreadystatechange=function handleLoad(){if(!request||request.readyState!==4){return}if(request.status===0&&!(request.responseURL&&request.responseURL.indexOf("file:")===0)){return}var responseHeaders="getAllResponseHeaders"in request?parseHeaders(request.getAllResponseHeaders()):null;var responseData=!config.responseType||config.responseType==="text"?request.responseText:request.response;var response={data:responseData,status:request.status,statusText:request.statusText,headers:responseHeaders,config:config,request:request};settle(resolve,reject,response);request=null};request.onabort=function handleAbort(){if(!request){return}reject(createError("Request aborted",config,"ECONNABORTED",request));request=null};request.onerror=function handleError(){reject(createError("Network Error",config,null,request));request=null};request.ontimeout=function handleTimeout(){var timeoutErrorMessage="timeout of "+config.timeout+"ms exceeded";if(config.timeoutErrorMessage){timeoutErrorMessage=config.timeoutErrorMessage}reject(createError(timeoutErrorMessage,config,"ECONNABORTED",request));request=null};if(utils.isStandardBrowserEnv()){var xsrfValue=(config.withCredentials||isURLSameOrigin(fullPath))&&config.xsrfCookieName?cookies.read(config.xsrfCookieName):undefined;if(xsrfValue){requestHeaders[config.xsrfHeaderName]=xsrfValue}}if("setRequestHeader"in request){utils.forEach(requestHeaders,(function setRequestHeader(val,key){if(typeof requestData==="undefined"&&key.toLowerCase()==="content-type"){delete requestHeaders[key]}else{request.setRequestHeader(key,val)}}))}if(!utils.isUndefined(config.withCredentials)){request.withCredentials=!!config.withCredentials}if(config.responseType){try{request.responseType=config.responseType}catch(e){if(config.responseType!=="json"){throw e}}}if(typeof config.onDownloadProgress==="function"){request.addEventListener("progress",config.onDownloadProgress)}if(typeof config.onUploadProgress==="function"&&request.upload){request.upload.addEventListener("progress",config.onUploadProgress)}if(config.cancelToken){config.cancelToken.promise.then((function onCanceled(cancel){if(!request){return}request.abort();reject(cancel);request=null}))}if(!requestData){requestData=null}request.send(requestData)}))};var DEFAULT_CONTENT_TYPE={"Content-Type":"application/x-www-form-urlencoded"};function setContentTypeIfUnset(headers,value){if(!utils.isUndefined(headers)&&utils.isUndefined(headers["Content-Type"])){headers["Content-Type"]=value}}function getDefaultAdapter(){var adapter;if(typeof XMLHttpRequest!=="undefined"){adapter=xhr}else if(typeof process!=="undefined"&&Object.prototype.toString.call(process)==="[object process]"){adapter=xhr}return adapter}var defaults={adapter:getDefaultAdapter(),transformRequest:[function transformRequest(data,headers){normalizeHeaderName(headers,"Accept");normalizeHeaderName(headers,"Content-Type");if(utils.isFormData(data)||utils.isArrayBuffer(data)||utils.isBuffer(data)||utils.isStream(data)||utils.isFile(data)||utils.isBlob(data)){return data}if(utils.isArrayBufferView(data)){return data.buffer}if(utils.isURLSearchParams(data)){setContentTypeIfUnset(headers,"application/x-www-form-urlencoded;charset=utf-8");return data.toString()}if(utils.isObject(data)){setContentTypeIfUnset(headers,"application/json;charset=utf-8");return JSON.stringify(data)}return data}],transformResponse:[function transformResponse(data){if(typeof data==="string"){try{data=JSON.parse(data)}catch(e){}}return data}],timeout:0,xsrfCookieName:"XSRF-TOKEN",xsrfHeaderName:"X-XSRF-TOKEN",maxContentLength:-1,maxBodyLength:-1,validateStatus:function validateStatus(status){return status>=200&&status<300}};defaults.headers={common:{Accept:"application/json, text/plain, */*"}};utils.forEach(["delete","get","head"],(function forEachMethodNoData(method){defaults.headers[method]={}}));utils.forEach(["post","put","patch"],(function forEachMethodWithData(method){defaults.headers[method]=utils.merge(DEFAULT_CONTENT_TYPE)}));var defaults_1=defaults;function throwIfCancellationRequested(config){if(config.cancelToken){config.cancelToken.throwIfRequested()}}var dispatchRequest=function dispatchRequest(config){throwIfCancellationRequested(config);config.headers=config.headers||{};config.data=transformData(config.data,config.headers,config.transformRequest);config.headers=utils.merge(config.headers.common||{},config.headers[config.method]||{},config.headers);utils.forEach(["delete","get","head","post","put","patch","common"],(function cleanHeaderConfig(method){delete config.headers[method]}));var adapter=config.adapter||defaults_1.adapter;return adapter(config).then((function onAdapterResolution(response){throwIfCancellationRequested(config);response.data=transformData(response.data,response.headers,config.transformResponse);return response}),(function onAdapterRejection(reason){if(!isCancel(reason)){throwIfCancellationRequested(config);if(reason&&reason.response){reason.response.data=transformData(reason.response