@chec/commerce.js
Version:
Easy to use JavaScript SDK for managing carts and selling products from your Chec store
109 lines (56 loc) • 37.8 kB
JavaScript
(function () {
'use strict';
function _objectWithoutPropertiesLoose(a,b){if(null==a)return {};var c,d,e={},f=Object.keys(a);for(d=0;d<f.length;d++)c=f[d],0<=b.indexOf(c)||(e[c]=a[c]);return e}var objectWithoutPropertiesLoose=_objectWithoutPropertiesLoose;
function _objectWithoutProperties(a,b){if(null==a)return {};var c,d,e=objectWithoutPropertiesLoose(a,b);if(Object.getOwnPropertySymbols){var f=Object.getOwnPropertySymbols(a);for(d=0;d<f.length;d++)c=f[d],!(0<=b.indexOf(c))&&Object.prototype.propertyIsEnumerable.call(a,c)&&(e[c]=a[c]);}return e}var objectWithoutProperties=_objectWithoutProperties;
function _arrayWithoutHoles(a){if(Array.isArray(a)){for(var b=0,c=Array(a.length);b<a.length;b++)c[b]=a[b];return c}}var arrayWithoutHoles=_arrayWithoutHoles;
function _iterableToArray(a){if(Symbol.iterator in Object(a)||"[object Arguments]"===Object.prototype.toString.call(a))return Array.from(a)}var iterableToArray=_iterableToArray;
function _nonIterableSpread(){throw new TypeError("Invalid attempt to spread non-iterable instance")}var nonIterableSpread=_nonIterableSpread;
function _toConsumableArray(a){return arrayWithoutHoles(a)||iterableToArray(a)||nonIterableSpread()}var toConsumableArray=_toConsumableArray;
function createCommonjsModule(fn, module) {
return module = { exports: {} }, fn(module, module.exports), module.exports;
}
var _typeof_1=createCommonjsModule(function(a){function b(a){return b="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(a){return typeof a}:function(a){return a&&"function"==typeof Symbol&&a.constructor===Symbol&&a!==Symbol.prototype?"symbol":typeof a},b(a)}function c(d){return a.exports="function"==typeof Symbol&&"symbol"===b(Symbol.iterator)?c=function(a){return b(a)}:c=function(a){return a&&"function"==typeof Symbol&&a.constructor===Symbol&&a!==Symbol.prototype?"symbol":b(a)},c(d)}a.exports=c;});
function _defineProperty(a,b,c){return b in a?Object.defineProperty(a,b,{value:c,enumerable:!0,configurable:!0,writable:!0}):a[b]=c,a}var defineProperty=_defineProperty;
function _classCallCheck(a,b){if(!(a instanceof b))throw new TypeError("Cannot call a class as a function")}var classCallCheck=_classCallCheck;
function _defineProperties(a,b){for(var c,d=0;d<b.length;d++)c=b[d],c.enumerable=c.enumerable||!1,c.configurable=!0,"value"in c&&(c.writable=!0),Object.defineProperty(a,c.key,c);}function _createClass(a,b,c){return b&&_defineProperties(a.prototype,b),c&&_defineProperties(a,c),a}var createClass=_createClass;
var Storage=function(){function a(b){classCallCheck(this,a),this.commerce=b;}return createClass(a,[{key:"set",value:function set(a,b,c){var d,e="";if(d=this.commerce.options.config&&"undefined"!=typeof this.commerce.options.config.cookie_path?this.commerce.options.config.cookie_path:"/",c){var f=new Date;f.setTime(f.getTime()+1e3*(60*(60*(24*c)))),e="; expires="+f.toGMTString();}return document.cookie=a+"="+b+e+"; path="+d}},{key:"get",value:function get(a){a+="=";for(var b,d=0,e=Array.from(document.cookie.split(";"));d<e.length;d++){for(b=e[d];" "===b.charAt(0);)b=b.substring(1,b.length);if(0===b.indexOf(a))return b.substring(a.length,b.length)}return null}},{key:"remove",value:function remove(a){return this.set(a,"",-1)}}]),a}();
var runtime_1=createCommonjsModule(function(a){var b=function(a){function b(a,b,c,e){var f=b&&b.prototype instanceof d?b:d,g=Object.create(f.prototype),h=new m(e||[]);return g._invoke=i(a,c,h),g}function c(a,b,c){try{return {type:"normal",arg:a.call(b,c)}}catch(a){return {type:"throw",arg:a}}}function d(){}function e(){}function f(){}function g(a){["next","throw","return"].forEach(function(b){a[b]=function(a){return this._invoke(b,a)};});}function h(a){function b(d,e,f,g){var h=c(a[d],a,e);if("throw"===h.type)g(h.arg);else{var i=h.arg,j=i.value;return j&&"object"==typeof j&&q.call(j,"__await")?Promise.resolve(j.__await).then(function(a){b("next",a,f,g);},function(a){b("throw",a,f,g);}):Promise.resolve(j).then(function(a){i.value=a,f(i);},function(a){return b("throw",a,f,g)})}}function d(a,c){function d(){return new Promise(function(d,e){b(a,c,d,e);})}return e=e?e.then(d,d):d()}var e;this._invoke=d;}function i(a,b,d){var e="suspendedStart";return function(f,g){if("executing"===e)throw new Error("Generator is already running");if("completed"===e){if("throw"===f)throw g;return o()}for(d.method=f,d.arg=g;;){var h=d.delegate;if(h){var i=j(h,d);if(i){if(i===v)continue;return i}}if("next"===d.method)d.sent=d._sent=d.arg;else if("throw"===d.method){if("suspendedStart"===e)throw e="completed",d.arg;d.dispatchException(d.arg);}else"return"===d.method&&d.abrupt("return",d.arg);e="executing";var k=c(a,b,d);if("normal"===k.type){if(e=d.done?"completed":"suspendedYield",k.arg===v)continue;return {value:k.arg,done:d.done}}"throw"===k.type&&(e="completed",d.method="throw",d.arg=k.arg);}}}function j(a,b){var d=a.iterator[b.method];if(void 0===d){if(b.delegate=null,"throw"===b.method){if(a.iterator["return"]&&(b.method="return",b.arg=void 0,j(a,b),"throw"===b.method))return v;b.method="throw",b.arg=new TypeError("The iterator does not provide a 'throw' method");}return v}var e=c(d,a.iterator,b.arg);if("throw"===e.type)return b.method="throw",b.arg=e.arg,b.delegate=null,v;var f=e.arg;if(!f)return b.method="throw",b.arg=new TypeError("iterator result is not an object"),b.delegate=null,v;if(f.done)b[a.resultName]=f.value,b.next=a.nextLoc,"return"!==b.method&&(b.method="next",b.arg=void 0);else return f;return b.delegate=null,v}function k(a){var b={tryLoc:a[0]};1 in a&&(b.catchLoc=a[1]),2 in a&&(b.finallyLoc=a[2],b.afterLoc=a[3]),this.tryEntries.push(b);}function l(a){var b=a.completion||{};b.type="normal",delete b.arg,a.completion=b;}function m(a){this.tryEntries=[{tryLoc:"root"}],a.forEach(k,this),this.reset(!0);}function n(a){if(a){var b=a[s];if(b)return b.call(a);if("function"==typeof a.next)return a;if(!isNaN(a.length)){var c=-1,d=function b(){for(;++c<a.length;)if(q.call(a,c))return b.value=a[c],b.done=!1,b;return b.value=void 0,b.done=!0,b};return d.next=d}}return {next:o}}function o(){return {value:void 0,done:!0}}var p=Object.prototype,q=p.hasOwnProperty,r="function"==typeof Symbol?Symbol:{},s=r.iterator||"@@iterator",t=r.asyncIterator||"@@asyncIterator",u=r.toStringTag||"@@toStringTag";a.wrap=b;var v={},w={};w[s]=function(){return this};var x=Object.getPrototypeOf,y=x&&x(x(n([])));y&&y!==p&&q.call(y,s)&&(w=y);var z=f.prototype=d.prototype=Object.create(w);return e.prototype=z.constructor=f,f.constructor=e,f[u]=e.displayName="GeneratorFunction",a.isGeneratorFunction=function(a){var b="function"==typeof a&&a.constructor;return !!b&&(b===e||"GeneratorFunction"===(b.displayName||b.name))},a.mark=function(a){return Object.setPrototypeOf?Object.setPrototypeOf(a,f):(a.__proto__=f,!(u in a)&&(a[u]="GeneratorFunction")),a.prototype=Object.create(z),a},a.awrap=function(a){return {__await:a}},g(h.prototype),h.prototype[t]=function(){return this},a.AsyncIterator=h,a.async=function(c,d,e,f){var g=new h(b(c,d,e,f));return a.isGeneratorFunction(d)?g:g.next().then(function(a){return a.done?a.value:g.next()})},g(z),z[u]="Generator",z[s]=function(){return this},z.toString=function(){return "[object Generator]"},a.keys=function(a){var b=[];for(var c in a)b.push(c);return b.reverse(),function c(){for(;b.length;){var d=b.pop();if(d in a)return c.value=d,c.done=!1,c}return c.done=!0,c}},a.values=n,m.prototype={constructor:m,reset:function(a){if(this.prev=0,this.next=0,this.sent=this._sent=void 0,this.done=!1,this.delegate=null,this.method="next",this.arg=void 0,this.tryEntries.forEach(l),!a)for(var b in this)"t"===b.charAt(0)&&q.call(this,b)&&!isNaN(+b.slice(1))&&(this[b]=void 0);},stop:function(){this.done=!0;var a=this.tryEntries[0],b=a.completion;if("throw"===b.type)throw b.arg;return this.rval},dispatchException:function(a){function b(b,d){return f.type="throw",f.arg=a,c.next=b,d&&(c.method="next",c.arg=void 0),!!d}if(this.done)throw a;for(var c=this,d=this.tryEntries.length-1;0<=d;--d){var e=this.tryEntries[d],f=e.completion;if("root"===e.tryLoc)return b("end");if(e.tryLoc<=this.prev){var g=q.call(e,"catchLoc"),h=q.call(e,"finallyLoc");if(g&&h){if(this.prev<e.catchLoc)return b(e.catchLoc,!0);if(this.prev<e.finallyLoc)return b(e.finallyLoc)}else if(g){if(this.prev<e.catchLoc)return b(e.catchLoc,!0);}else if(!h)throw new Error("try statement without catch or finally");else if(this.prev<e.finallyLoc)return b(e.finallyLoc)}}},abrupt:function(a,b){for(var c,d=this.tryEntries.length-1;0<=d;--d)if(c=this.tryEntries[d],c.tryLoc<=this.prev&&q.call(c,"finallyLoc")&&this.prev<c.finallyLoc){var e=c;break}e&&("break"===a||"continue"===a)&&e.tryLoc<=b&&b<=e.finallyLoc&&(e=null);var f=e?e.completion:{};return f.type=a,f.arg=b,e?(this.method="next",this.next=e.finallyLoc,v):this.complete(f)},complete:function(a,b){if("throw"===a.type)throw a.arg;return "break"===a.type||"continue"===a.type?this.next=a.arg:"return"===a.type?(this.rval=this.arg=a.arg,this.method="return",this.next="end"):"normal"===a.type&&b&&(this.next=b),v},finish:function(a){for(var b,c=this.tryEntries.length-1;0<=c;--c)if(b=this.tryEntries[c],b.finallyLoc===a)return this.complete(b.completion,b.afterLoc),l(b),v},catch:function(a){for(var b,c=this.tryEntries.length-1;0<=c;--c)if(b=this.tryEntries[c],b.tryLoc===a){var d=b.completion;if("throw"===d.type){var e=d.arg;l(b);}return e}throw new Error("illegal catch attempt")},delegateYield:function(a,b,c){return this.delegate={iterator:n(a),resultName:b,nextLoc:c},"next"===this.method&&(this.arg=void 0),v}},a}(a.exports);try{regeneratorRuntime=b;}catch(a){Function("r","regeneratorRuntime = r")(b);}});
var regenerator=runtime_1;
function asyncGeneratorStep(a,b,c,d,e,f,g){try{var h=a[f](g),i=h.value;}catch(a){return void c(a)}h.done?b(i):Promise.resolve(i).then(d,e);}function _asyncToGenerator(a){return function(){var b=this,c=arguments;return new Promise(function(d,e){function f(a){asyncGeneratorStep(h,d,e,f,g,"next",a);}function g(a){asyncGeneratorStep(h,d,e,f,g,"throw",a);}var h=a.apply(b,c);f(void 0);})}}var asyncToGenerator=_asyncToGenerator;
var Cart=function(){function a(b){classCallCheck(this,a),this.commerce=b,this.cart=null;}return createClass(a,[{key:"refresh",value:function refresh(){var a=this;return this.commerce.request("carts").then(function(b){var c=b.id;return a.commerce.storage.set("commercejs_cart_id",c,30),a.cart=b,c})}},{key:"id",value:function id(){if(null!==this.cart&&null!==this.cart.id)return this.cart.id;var a=this.commerce.storage.get("commercejs_cart_id");return "string"==typeof a&&a.length?a:null}},{key:"request",value:function(){var a=asyncToGenerator(regenerator.mark(function a(){var b,c,d,e,f,g=this,h=arguments;return regenerator.wrap(function(a){for(;;)switch(a.prev=a.next){case 0:if(b=0<h.length&&void 0!==h[0]?h[0]:"",c=1<h.length&&void 0!==h[1]?h[1]:"get",d=2<h.length&&void 0!==h[2]?h[2]:null,e=!!(3<h.length&&void 0!==h[3])&&h[3],f="string"==typeof b&&b.length?"/".concat(b):"",this.id()){a.next=8;break}return a.next=8,this.refresh();case 8:return a.abrupt("return",this.commerce.request("carts/".concat(this.id()).concat(f),c,d,e).catch(function(a){if(a.statusCode&&404===a.statusCode)return g.refresh().then(function(){return g.commerce.request("carts/".concat(g.id()).concat(f),c,d,e)});throw a}));case 9:case"end":return a.stop();}},a,this)}));return function request(){return a.apply(this,arguments)}}()},{key:"add",value:function add(a){var b=1<arguments.length&&void 0!==arguments[1]?arguments[1]:1,c=2<arguments.length&&void 0!==arguments[2]?arguments[2]:null,d={id:"object"===_typeof_1(a)?a.id:a,quantity:b,variant:c};return this.request("","post",d)}},{key:"retrieve",value:function retrieve(){var a=this;return this.request().then(function(b){return a.cart=b,b})}},{key:"remove",value:function remove(a){return this.request("items/".concat(a),"delete")}},{key:"delete",value:function _delete(){return this.request("","delete")}},{key:"update",value:function update(a,b){return this.request("items/".concat(a),"put",b)}},{key:"contents",value:function contents(){return this.request("items")}},{key:"empty",value:function empty(){return this.request("items","delete")}}]),a}();
var Categories=function(){function a(b){classCallCheck(this,a),this.commerce=b;}return createClass(a,[{key:"list",value:function list(){var a=0<arguments.length&&void 0!==arguments[0]?arguments[0]:null;return "function"==typeof a?this.commerce.request("categories"):this.commerce.request("categories","get",a)}},{key:"retrieve",value:function retrieve(a,b){return this.commerce.request("categories/".concat(a),"get",b)}}]),a}();
var Checkout=function(){function Checkout(a){classCallCheck(this,Checkout),this.commerce=a;}return 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(a,b){return this.commerce.request("checkouts/".concat(a),"get",b)}},{key:"capture",value:function capture(a,b){var c=this;return this.commerce.request("checkouts/".concat(a),"post",b).then(function(a){return c.commerce.cart.refresh(),a})}},{key:"checkPaypalStatus",value:function checkPaypalStatus(a){return this.commerce.request("checkouts/".concat(a,"/check/paypal/payment"))}},{key:"checkPaypalOrderCaptured",value:function checkPaypalOrderCaptured(a){return this.commerce.request("checkouts/".concat(a,"/check/paypal/captured"))}},{key:"receipt",value:function receipt(a){return this.commerce.request("checkouts/".concat(a,"/receipt"))}},{key:"checkPayWhatYouWant",value:function checkPayWhatYouWant(a,b){return this.commerce.request("checkouts/".concat(a,"/check/pay_what_you_want"),"get",b)}},{key:"fields",value:function fields(a){return this.commerce.request("checkouts/".concat(a,"/fields"))}},{key:"setTaxZone",value:function setTaxZone(a,b){return this.commerce.request("checkouts/".concat(a,"/helper/set_tax_zone"),"get",b)}},{key:"getLocationFromIP",value:function getLocationFromIP(a){var b=1<arguments.length&&void 0!==arguments[1]?arguments[1]:"",c=b.length?"?ip_address=".concat(b):"";return this.commerce.request("checkouts/".concat(a,"/helper/location_from_ip").concat(c))}},{key:"isFree",value:function isFree(a){return this.commerce.request("checkouts/".concat(a,"/check/is_free"))}},{key:"checkVariant",value:function checkVariant(a,b,c){return this.commerce.request("checkouts/".concat(a,"/check/").concat(b,"/variant"),"get",c)}},{key:"checkDiscount",value:function checkDiscount(a,b){return this.commerce.request("checkouts/".concat(a,"/check/discount"),"get",b)}},{key:"checkShippingOption",value:function checkShippingOption(a,b){return this.commerce.request("checkouts/".concat(a,"/check/shipping"),"get",b)}},{key:"getShippingOptions",value:function getShippingOptions(a,b){return this.commerce.request("checkouts/".concat(a,"/helper/shipping_options"),"get",b)}},{key:"checkQuantity",value:function checkQuantity(a,b,c){return this.commerce.request("checkouts/".concat(a,"/check/").concat(b,"/quantity"),"get",c)}},{key:"helperValidation",value:function helperValidation(a){return this.commerce.request("checkouts/".concat(a,"/helper/validation"))}},{key:"getLive",value:function getLive(a){return this.commerce.request("checkouts/".concat(a,"/live"))}},{key:"getToken",value:function getToken(a){return this.commerce.request("checkouts/tokens/".concat(a))}},{key:"checkGiftcard",value:function checkGiftcard(a,b){return this.commerce.request("checkouts/".concat(a,"/check/giftcard"),"get",b)}}]),Checkout}();
var Merchants=function(){function a(b){classCallCheck(this,a),this.commerce=b;}return createClass(a,[{key:"about",value:function about(){return this.commerce.request("merchants")}}]),a}();
var Products=function(){function a(b){classCallCheck(this,a),this.commerce=b;}return createClass(a,[{key:"list",value:function list(){var a=0<arguments.length&&void 0!==arguments[0]?arguments[0]:null;return this.commerce.request("products","get",a)}},{key:"retrieve",value:function retrieve(a,b){return this.commerce.request("products/".concat(a),"get",b)}}]),a}();
var Services=function(){function a(b){classCallCheck(this,a),this.commerce=b;}return createClass(a,[{key:"localeListCountries",value:function localeListCountries(){return this.commerce.request("services/locale/countries")}},{key:"localeListShippingCountries",value:function localeListShippingCountries(a){return this.commerce.request("services/locale/".concat(a,"/countries"))}},{key:"localeListShippingSubdivisions",value:function localeListShippingSubdivisions(a,b){return this.commerce.request("services/locale/".concat(a,"/countries/").concat(b,"/subdivisions"))}},{key:"localeListSubdivisions",value:function localeListSubdivisions(a){return this.commerce.request("services/locale/".concat(a,"/subdivisions"))}}]),a}();
var Features = {Cart:Cart,Categories:Categories,Checkout:Checkout,Merchants:Merchants,Products:Products,Services:Services};
var consoleHelper=function(){var d,e,f,g,h,j=0<arguments.length&&void 0!==arguments[0]?arguments[0]:"black",k=1<arguments.length?arguments[1]:void 0,l=2<arguments.length?arguments[2]:void 0,b=3<arguments.length?arguments[3]:void 0,c="White",m=!1;if("success"===j?(j="#488f5a",d="\u2705 "):"info"===j?(j="DodgerBlue",d=""):"error"===j?("validation"===b.error.type?(j="rgba(244, 67, 54, 1)",d="\uD83D\uDEAB Validation/Missing Fields",k=""):(j="rgba(244, 67, 54, 1)",d="\u274C HTTdP ERROR ",c="rgba(244, 67, 54, 0.15)"),m=!0):"warning"===j?(j="rgba(208, 154, 35, 1)",d="\u26A0\uFE0F "):void 0,!0===m){if(console.log("%c"+d+k,"color:"+j+";display:block; width: 100%;padding:2px 2px 2px 0px;font-family: Open Sans, Helvetica, Sans-serif;font-weight:bold;background-color:"+c+";"),"object"===_typeof_1(b.error.message)){for(g=b.error.message,e=0,f=g.length,h=[];e<f;)console.log("%c"+g[e].field+" %c"+g[e].error,"color:#515D6D;font-family: Open Sans, Helvetica, Sans-serif;font-weight:800;","color:#515D6D;font-family: Open Sans, Helvetica, Sans-serif;font-weight:400;"),h.push(e++);return h}return console.log("%c"+b.error.message,"color:#515D6D;font-family: Open Sans, Helvetica, Sans-serif;font-weight:400;")}return "object"===_typeof_1(j)?(console.log("%c"+k,"color: PowderBlue;font-weight:bold;font-family: Open Sans, Helvetica, Sans-serif; background-color: RoyalBlue;"),void console.log(j)):void(console.log("%c"+d+k,"color:"+j+";display:block;font-family: Open Sans, Helvetica, Sans-serif;line-height:28px; width: 100%;padding:2px 2px 2px 0px;font-weight:bold;background-color:"+c+";"),l&&console.log("%c"+l,"color:#515D6D;line-height:22px;font-weight:400; font-family: Open Sans, Helvetica, Sans-serif;"))},debuggerOnNotice=function(){console.log("%c\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","font-family: Courier New, Courier, monospace; color: #788ba4; font-weight:bold; font-size: 11px;"),console.log("%cCommerce.js console debugger is on! \uD83C\uDF89","text-align:center; display:block; font-family: Open Sans, Helvetica, Sans-serif; color: #488f5a; line-height:28px; font-size: 14px"),console.log("%c\uD83D\uDCAC Need some help? Join our Slack channel - https://chec-commercejs-community.herokuapp.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(a,b){return function(){for(var c=Array(arguments.length),d=0;d<c.length;d++)c[d]=arguments[d];return a.apply(b,c)}};
var isBuffer=function(a){return null!=a&&null!=a.constructor&&"function"==typeof a.constructor.isBuffer&&a.constructor.isBuffer(a)};
var toString=Object.prototype.toString;function isArray(a){return "[object Array]"===toString.call(a)}function isArrayBuffer(a){return "[object ArrayBuffer]"===toString.call(a)}function isFormData(a){return "undefined"!=typeof FormData&&a instanceof FormData}function isArrayBufferView(a){var b;return b="undefined"!=typeof ArrayBuffer&&ArrayBuffer.isView?ArrayBuffer.isView(a):a&&a.buffer&&a.buffer instanceof ArrayBuffer,b}function isString(a){return "string"==typeof a}function isNumber(a){return "number"==typeof a}function isUndefined(a){return "undefined"==typeof a}function isObject(a){return null!==a&&"object"==typeof a}function isDate(a){return "[object Date]"===toString.call(a)}function isFile(a){return "[object File]"===toString.call(a)}function isBlob(a){return "[object Blob]"===toString.call(a)}function isFunction(a){return "[object Function]"===toString.call(a)}function isStream(a){return isObject(a)&&isFunction(a.pipe)}function isURLSearchParams(a){return "undefined"!=typeof URLSearchParams&&a instanceof URLSearchParams}function trim(a){return a.replace(/^\s*/,"").replace(/\s*$/,"")}function isStandardBrowserEnv(){return ("undefined"==typeof navigator||"ReactNative"!==navigator.product&&"NativeScript"!==navigator.product&&"NS"!==navigator.product)&&"undefined"!=typeof window&&"undefined"!=typeof document}function forEach(a,b){if(null!==a&&"undefined"!=typeof a)if("object"!=typeof a&&(a=[a]),isArray(a))for(var c=0,d=a.length;c<d;c++)b.call(null,a[c],c,a);else for(var e in a)Object.prototype.hasOwnProperty.call(a,e)&&b.call(null,a[e],e,a);}function merge(){function a(a,c){b[c]="object"==typeof b[c]&&"object"==typeof a?merge(b[c],a):a;}for(var b={},c=0,d=arguments.length;c<d;c++)forEach(arguments[c],a);return b}function deepMerge(){function a(a,c){b[c]="object"==typeof b[c]&&"object"==typeof a?deepMerge(b[c],a):"object"==typeof a?deepMerge({},a):a;}for(var b={},c=0,d=arguments.length;c<d;c++)forEach(arguments[c],a);return b}function extend(c,a,b){return forEach(a,function(a,d){c[d]=b&&"function"==typeof a?bind(a,b):a;}),c}var utils={isArray:isArray,isArrayBuffer:isArrayBuffer,isBuffer:isBuffer,isFormData:isFormData,isArrayBufferView:isArrayBufferView,isString:isString,isNumber:isNumber,isObject:isObject,isUndefined:isUndefined,isDate:isDate,isFile:isFile,isBlob:isBlob,isFunction:isFunction,isStream:isStream,isURLSearchParams:isURLSearchParams,isStandardBrowserEnv:isStandardBrowserEnv,forEach:forEach,merge:merge,deepMerge:deepMerge,extend:extend,trim:trim};
function encode(a){return encodeURIComponent(a).replace(/%40/gi,"@").replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+").replace(/%5B/gi,"[").replace(/%5D/gi,"]")}var buildURL=function(a,b,c){if(!b)return a;var d;if(c)d=c(b);else if(utils.isURLSearchParams(b))d=b.toString();else{var e=[];utils.forEach(b,function(a,b){null===a||"undefined"==typeof a||(utils.isArray(a)?b+="[]":a=[a],utils.forEach(a,function(a){utils.isDate(a)?a=a.toISOString():utils.isObject(a)&&(a=JSON.stringify(a)),e.push(encode(b)+"="+encode(a));}));}),d=e.join("&");}if(d){var f=a.indexOf("#");-1!==f&&(a=a.slice(0,f)),a+=(-1===a.indexOf("?")?"?":"&")+d;}return a};
function InterceptorManager(){this.handlers=[];}InterceptorManager.prototype.use=function(a,b){return this.handlers.push({fulfilled:a,rejected:b}),this.handlers.length-1},InterceptorManager.prototype.eject=function(a){this.handlers[a]&&(this.handlers[a]=null);},InterceptorManager.prototype.forEach=function(a){utils.forEach(this.handlers,function(b){null!==b&&a(b);});};var InterceptorManager_1=InterceptorManager;
var transformData=function(a,b,c){return utils.forEach(c,function(c){a=c(a,b);}),a};
var isCancel=function(a){return !!(a&&a.__CANCEL__)};
var normalizeHeaderName=function(a,b){utils.forEach(a,function(c,d){d!==b&&d.toUpperCase()===b.toUpperCase()&&(a[b]=c,delete a[d]);});};
var enhanceError=function(a,b,c,d,e){return a.config=b,c&&(a.code=c),a.request=d,a.response=e,a.isAxiosError=!0,a.toJSON=function(){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}},a};
var createError=function(a,b,c,d,e){var f=new Error(a);return enhanceError(f,b,c,d,e)};
var settle=function(a,b,c){var d=c.config.validateStatus;!d||d(c.status)?a(c):b(createError("Request failed with status code "+c.status,c.config,null,c.request,c));};
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"],parseHeaders=function(a){var b,c,d,e={};return a?(utils.forEach(a.split("\n"),function(a){if(d=a.indexOf(":"),b=utils.trim(a.substr(0,d)).toLowerCase(),c=utils.trim(a.substr(d+1)),b){if(e[b]&&0<=ignoreDuplicateOf.indexOf(b))return;e[b]="set-cookie"===b?(e[b]?e[b]:[]).concat([c]):e[b]?e[b]+", "+c:c;}}),e):e};
var isURLSameOrigin=utils.isStandardBrowserEnv()?function(){function a(a){var b=a;return c&&(d.setAttribute("href",b),b=d.href),d.setAttribute("href",b),{href:d.href,protocol:d.protocol?d.protocol.replace(/:$/,""):"",host:d.host,search:d.search?d.search.replace(/^\?/,""):"",hash:d.hash?d.hash.replace(/^#/,""):"",hostname:d.hostname,port:d.port,pathname:"/"===d.pathname.charAt(0)?d.pathname:"/"+d.pathname}}var b,c=/(msie|trident)/i.test(navigator.userAgent),d=document.createElement("a");return b=a(window.location.href),function(c){var d=utils.isString(c)?a(c):c;return d.protocol===b.protocol&&d.host===b.host}}():function(){return function(){return !0}}();
var cookies=utils.isStandardBrowserEnv()?function(){return {write:function(a,b,c,d,e,f){var g=[];g.push(a+"="+encodeURIComponent(b)),utils.isNumber(c)&&g.push("expires="+new Date(c).toGMTString()),utils.isString(d)&&g.push("path="+d),utils.isString(e)&&g.push("domain="+e),!0===f&&g.push("secure"),document.cookie=g.join("; ");},read:function(a){var b=document.cookie.match(new RegExp("(^|;\\s*)("+a+")=([^;]*)"));return b?decodeURIComponent(b[3]):null},remove:function(a){this.write(a,"",Date.now()-864e5);}}}():function(){return {write:function(){},read:function(){return null},remove:function(){}}}();
var xhr=function(a){return new Promise(function(b,c){var d=a.data,e=a.headers;utils.isFormData(d)&&delete e["Content-Type"];var f=new XMLHttpRequest;if(a.auth){var g=a.auth.username||"",h=a.auth.password||"";e.Authorization="Basic "+btoa(g+":"+h);}if(f.open(a.method.toUpperCase(),buildURL(a.url,a.params,a.paramsSerializer),!0),f.timeout=a.timeout,f.onreadystatechange=function(){if(f&&4===f.readyState&&(0!==f.status||f.responseURL&&0===f.responseURL.indexOf("file:"))){var d="getAllResponseHeaders"in f?parseHeaders(f.getAllResponseHeaders()):null,e=a.responseType&&"text"!==a.responseType?f.response:f.responseText,g={data:e,status:f.status,statusText:f.statusText,headers:d,config:a,request:f};settle(b,c,g),f=null;}},f.onabort=function(){f&&(c(createError("Request aborted",a,"ECONNABORTED",f)),f=null);},f.onerror=function(){c(createError("Network Error",a,null,f)),f=null;},f.ontimeout=function(){c(createError("timeout of "+a.timeout+"ms exceeded",a,"ECONNABORTED",f)),f=null;},utils.isStandardBrowserEnv()){var i=(a.withCredentials||isURLSameOrigin(a.url))&&a.xsrfCookieName?cookies.read(a.xsrfCookieName):void 0;i&&(e[a.xsrfHeaderName]=i);}if("setRequestHeader"in f&&utils.forEach(e,function(a,b){"undefined"==typeof d&&"content-type"===b.toLowerCase()?delete e[b]:f.setRequestHeader(b,a);}),a.withCredentials&&(f.withCredentials=!0),a.responseType)try{f.responseType=a.responseType;}catch(b){if("json"!==a.responseType)throw b}"function"==typeof a.onDownloadProgress&&f.addEventListener("progress",a.onDownloadProgress),"function"==typeof a.onUploadProgress&&f.upload&&f.upload.addEventListener("progress",a.onUploadProgress),a.cancelToken&&a.cancelToken.promise.then(function(a){f&&(f.abort(),c(a),f=null);}),void 0===d&&(d=null),f.send(d);})};
var DEFAULT_CONTENT_TYPE={"Content-Type":"application/x-www-form-urlencoded"};function setContentTypeIfUnset(a,b){!utils.isUndefined(a)&&utils.isUndefined(a["Content-Type"])&&(a["Content-Type"]=b);}function getDefaultAdapter(){var a;return "undefined"!=typeof process&&"[object process]"===Object.prototype.toString.call(process)?a=xhr:"undefined"!=typeof XMLHttpRequest&&(a=xhr),a}var defaults={adapter:getDefaultAdapter(),transformRequest:[function(a,b){return normalizeHeaderName(b,"Accept"),normalizeHeaderName(b,"Content-Type"),utils.isFormData(a)||utils.isArrayBuffer(a)||utils.isBuffer(a)||utils.isStream(a)||utils.isFile(a)||utils.isBlob(a)?a:utils.isArrayBufferView(a)?a.buffer:utils.isURLSearchParams(a)?(setContentTypeIfUnset(b,"application/x-www-form-urlencoded;charset=utf-8"),a.toString()):utils.isObject(a)?(setContentTypeIfUnset(b,"application/json;charset=utf-8"),JSON.stringify(a)):a}],transformResponse:[function(a){if("string"==typeof a)try{a=JSON.parse(a);}catch(a){}return a}],timeout:0,xsrfCookieName:"XSRF-TOKEN",xsrfHeaderName:"X-XSRF-TOKEN",maxContentLength:-1,validateStatus:function(a){return 200<=a&&300>a}};defaults.headers={common:{Accept:"application/json, text/plain, */*"}},utils.forEach(["delete","get","head"],function(a){defaults.headers[a]={};}),utils.forEach(["post","put","patch"],function(a){defaults.headers[a]=utils.merge(DEFAULT_CONTENT_TYPE);});var defaults_1=defaults;
var isAbsoluteURL=function(a){return /^([a-z][a-z\d\+\-\.]*:)?\/\//i.test(a)};
var combineURLs=function(a,b){return b?a.replace(/\/+$/,"")+"/"+b.replace(/^\/+/,""):a};
function throwIfCancellationRequested(a){a.cancelToken&&a.cancelToken.throwIfRequested();}var dispatchRequest=function(a){throwIfCancellationRequested(a),a.baseURL&&!isAbsoluteURL(a.url)&&(a.url=combineURLs(a.baseURL,a.url)),a.headers=a.headers||{},a.data=transformData(a.data,a.headers,a.transformRequest),a.headers=utils.merge(a.headers.common||{},a.headers[a.method]||{},a.headers||{}),utils.forEach(["delete","get","head","post","put","patch","common"],function(b){delete a.headers[b];});var b=a.adapter||defaults_1.adapter;return b(a).then(function(b){return throwIfCancellationRequested(a),b.data=transformData(b.data,b.headers,a.transformResponse),b},function(b){return isCancel(b)||(throwIfCancellationRequested(a),b&&b.response&&(b.response.data=transformData(b.response.data,b.response.headers,a.transformResponse))),Promise.reject(b)})};
var mergeConfig=function(a,b){b=b||{};var c={};return utils.forEach(["url","method","params","data"],function(a){"undefined"!=typeof b[a]&&(c[a]=b[a]);}),utils.forEach(["headers","auth","proxy"],function(d){utils.isObject(b[d])?c[d]=utils.deepMerge(a[d],b[d]):"undefined"==typeof b[d]?utils.isObject(a[d])?c[d]=utils.deepMerge(a[d]):"undefined"!=typeof a[d]&&(c[d]=a[d]):c[d]=b[d];}),utils.forEach(["baseURL","transformRequest","transformResponse","paramsSerializer","timeout","withCredentials","adapter","responseType","xsrfCookieName","xsrfHeaderName","onUploadProgress","onDownloadProgress","maxContentLength","validateStatus","maxRedirects","httpAgent","httpsAgent","cancelToken","socketPath"],function(d){"undefined"==typeof b[d]?"undefined"!=typeof a[d]&&(c[d]=a[d]):c[d]=b[d];}),c};
function Axios(a){this.defaults=a,this.interceptors={request:new InterceptorManager_1,response:new InterceptorManager_1};}Axios.prototype.request=function(a){"string"==typeof a?(a=arguments[1]||{},a.url=arguments[0]):a=a||{},a=mergeConfig(this.defaults,a),a.method=a.method?a.method.toLowerCase():"get";var b=[dispatchRequest,void 0],c=Promise.resolve(a);for(this.interceptors.request.forEach(function(a){b.unshift(a.fulfilled,a.rejected);}),this.interceptors.response.forEach(function(a){b.push(a.fulfilled,a.rejected);});b.length;)c=c.then(b.shift(),b.shift());return c},Axios.prototype.getUri=function(a){return a=mergeConfig(this.defaults,a),buildURL(a.url,a.params,a.paramsSerializer).replace(/^\?/,"")},utils.forEach(["delete","get","head","options"],function(a){Axios.prototype[a]=function(b,c){return this.request(utils.merge(c||{},{method:a,url:b}))};}),utils.forEach(["post","put","patch"],function(a){Axios.prototype[a]=function(b,c,d){return this.request(utils.merge(d||{},{method:a,url:b,data:c}))};});var Axios_1=Axios;
function Cancel(a){this.message=a;}Cancel.prototype.toString=function(){return "Cancel"+(this.message?": "+this.message:"")},Cancel.prototype.__CANCEL__=!0;var Cancel_1=Cancel;
function CancelToken(a){if("function"!=typeof a)throw new TypeError("executor must be a function.");var b;this.promise=new Promise(function(a){b=a;});var c=this;a(function(a){c.reason||(c.reason=new Cancel_1(a),b(c.reason));});}CancelToken.prototype.throwIfRequested=function(){if(this.reason)throw this.reason},CancelToken.source=function(){var a,b=new CancelToken(function(b){a=b;});return {token:b,cancel:a}};var CancelToken_1=CancelToken;
var spread=function(a){return function(b){return a.apply(null,b)}};
function createInstance(a){var b=new Axios_1(a),c=bind(Axios_1.prototype.request,b);return utils.extend(c,Axios_1.prototype,b),utils.extend(c,b),c}var axios=createInstance(defaults_1);axios.Axios=Axios_1,axios.create=function(a){return createInstance(mergeConfig(axios.defaults,a))},axios.Cancel=Cancel_1,axios.CancelToken=CancelToken_1,axios.isCancel=isCancel,axios.all=function(a){return Promise.all(a)},axios.spread=spread;var axios_1=axios,default_1=axios;axios_1.default=default_1;
var axios$1=axios_1;
function ownKeys(a,b){var c=Object.keys(a);if(Object.getOwnPropertySymbols){var d=Object.getOwnPropertySymbols(a);b&&(d=d.filter(function(b){return Object.getOwnPropertyDescriptor(a,b).enumerable})),c.push.apply(c,d);}return c}function _objectSpread(a){for(var b,c=1;c<arguments.length;c++)b=null==arguments[c]?{}:arguments[c],c%2?ownKeys(b,!0).forEach(function(c){defineProperty(a,c,b[c]);}):Object.getOwnPropertyDescriptors?Object.defineProperties(a,Object.getOwnPropertyDescriptors(b)):ownKeys(b).forEach(function(c){Object.defineProperty(a,c,Object.getOwnPropertyDescriptor(b,c));});return a}var defaultEventCallback=function(a){var b=new CustomEvent("Commercejs.".concat(a),{bubbles:!1,cancelable:!1});return window.dispatchEvent(b)},Commerce=function(){function a(b){var c=!!(1<arguments.length&&void 0!==arguments[1])&&arguments[1],d=2<arguments.length&&void 0!==arguments[2]?arguments[2]:{};if(classCallCheck(this,a),this.options=_objectSpread({version:"v1",url:"https://api.chec.io/",eventCallback:defaultEventCallback},d,{publicKey:b,debug:c}),("string"!=typeof b||0===b.length)&&console.warn("\u26A0\uFE0F Invalid public key given to Commerce.js client"),"sk_"===b.toLowerCase().substring(0,3))throw new Error("Secret key provided. You must use a public key with Commerce.js!");this.storage=new Storage(this),this.cart=new Features.Cart(this),this.checkout=new Features.Checkout(this),this.products=new Features.Products(this),this.services=new Features.Services(this),this.categories=new Features.Categories(this),this.merchants=new Features.Merchants(this),c&&(this.consoleHelper=consoleHelper,debuggerOnNotice());}return createClass(a,[{key:"error",value:function error(a){if(this.consoleHelper&&this.options.debug){var b=a.response,c="[".concat(b.status,"] Type: ").concat(b.statusText),d="string"==typeof b.data?b.data:b.statusText;return this.consoleHelper("error",c,d,b.data)}}},{key:"request",value:function request(a){var b=this,c=1<arguments.length&&void 0!==arguments[1]?arguments[1]:"get",d=2<arguments.length&&void 0!==arguments[2]?arguments[2]:null,e=!!(3<arguments.length&&void 0!==arguments[3])&&arguments[3],f={"X-Authorization":this.options.publicKey,"X-Chec-Agent":"commerce.js/v2"},g="get"===c?d:null,h="get"===c?null:d,i=this.options.timeoutMs||6e4,j=this.options.axiosConfig||{},k=this.options.url;"/"!==k.substring(k.length-1)&&(k+="/");var l=axios$1(_objectSpread({url:a,method:c,baseURL:"".concat(k).concat(this.options.version,"/"),params:g,data:h,timeout:i},j,{headers:_objectSpread({},f,{},j.headers)}));if(e)return l;var m=this.options.eventCallback;return l.then(function(a){if(b.consoleHelper&&b.options.debug&&"object"===_typeof_1(a.data._console)&&b.consoleHelper.apply(b,toConsumableArray(a.data._console)),"object"!==_typeof_1(a.data)||Array.isArray(a.data))return a.data;var c=a.data,d=c._event,e=objectWithoutProperties(c,["_event"]);return "string"==typeof d&&"function"==typeof m&&m(d),e}).catch(function(a){throw b.error(a),{message:"Unsuccessful response (".concat(a.response.status,": ").concat(a.response.statusText,") received"),statusCode:a.response.status,statusText:a.response.statusText,data:a.response.data,originalError:a}})}}]),a}();
module.exports=Commerce;
}());