@livechat/accounts-sdk
Advanced tools
Comparing version 1.3.0 to 1.3.1
@@ -1,1 +0,1 @@ | ||
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t():"function"==typeof define&&define.amd?define(t):e.AccountsSDK=t()}(this,function(){"use strict";var u=function(e,t){if(null==e)throw new TypeError("Cannot convert undefined or null to object");for(var n=Object(e),o=1;o<arguments.length;o++){var i=arguments[o];if(null!=i)for(var r in i)Object.prototype.hasOwnProperty.call(i,r)&&(n[r]=i[r])}return n},a=function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")},i=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var o in n)Object.prototype.hasOwnProperty.call(n,o)&&(e[o]=n[o])}return e},c=function(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t},o=new function e(){a(this,e),this.submit=function(e,t){(t=u({},t)).headers=t.headers||[],t.success=t.success||function(){},t.error=t.error||function(){},t.method=t.method||"POST";var n=new XMLHttpRequest;n.open(t.method,e,!0),Object.keys(t.headers).forEach(function(e){return n.setRequestHeader(e,t.headers[e])}),n.onreadystatechange=function(){if(4!==n.readyState)return!1;n.status<200||299<n.status?t.error(n.responseText,n.status):t.success(n.responseText,n.status)},n.send(t.postData)},this.get=function(e,t){var n=new XMLHttpRequest;n.open("GET",e,!0),!0===t.withCredentials&&(n.withCredentials=!0),Object.keys(t.headers).forEach(function(e){return n.setRequestHeader(e,t.headers[e])}),n.onreadystatechange=function(){if(n.readyState!==XMLHttpRequest.DONE)return!1;200===n.status?t.success(n.responseText,n.status):t.error(n.responseText,n.status)},n.send(t.postData)}},e=function(){function o(e){var t=1<arguments.length&&void 0!==arguments[1]?arguments[1]:{},n=2<arguments.length&&void 0!==arguments[2]?arguments[2]:{};a(this,o),r.call(this),this.endpoint=e,this.headers=t,this.options=n}return o.prototype.setEndpoint=function(e){this.endpoint=e},o}(),r=function(){var c=this;this._promisify=function(e){if(null==e.success&&null==e.error)return new Promise(function(n,o){e.success=function(e,t){n({data:e,statusCode:t})},e.error=function(e,t){o({data:e,statusCode:t})}})},this._URL=function(e){return"function"==typeof c.endpoint?c.endpoint()+e:c.endpoint+e},this._finalOptions=function(n,o,i,r){var s,a,e=JSON.stringify(o),t=u({},i);return t.postData=e,t.headers=u(t.headers||{},c.headers),t.success&&(t.success=(s=t.success,function(t,e){try{t=JSON.parse(t)}catch(e){t={}}s(t,e)})),t.error&&(t.error=(a=t.error,function(t,e){try{t=JSON.parse(t)}catch(e){t={}}if("wrong region"===t.error)return c.options.onIncorrectRegion&&c.options.onIncorrectRegion(t.region),void c[r](n,o,i);a(t,e)})),t},this._get=function(e,t){o.get(c._URL(e),c._finalOptions(e,{},t,"_get"))},this._post=function(e,t,n){o.submit(c._URL(e),c._finalOptions(e,t,n,"_post"))},this._put=function(e,t,n){n.method="PUT",o.submit(c._URL(e),c._finalOptions(e,t,n,"_put"))},this._setDefaults=function(e){return(e=e||{}).headers=e.headers||{},e}},s=new(function(r){function s(){var e,n;a(this,s);for(var t=arguments.length,o=Array(t),i=0;i<t;i++)o[i]=arguments[i];return(e=n=c(this,r.call.apply(r,[this].concat(o)))).getInfoByCode=function(e){n._get("/info?code="+e+"&type=code",1<arguments.length&&void 0!==arguments[1]?arguments[1]:{})},n.getInfoByAccessToken=function(e){var t=1<arguments.length&&void 0!==arguments[1]?arguments[1]:{};t.headers=u({Authorization:"Bearer "+e},t.headers),n._get("/info",t)},c(n,e)}return function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}(s,r),s}(e))("https://accounts.livechatinc.com"),t=new(function(){function e(){a(this,e)}return e.prototype.set=function(e,t){var n=2<arguments.length&&void 0!==arguments[2]?arguments[2]:null,o={value:t,expires_in:(new Date).getTime()+1e3*n};try{localStorage.setItem(e,JSON.stringify(o))}catch(e){}},e.prototype.get=function(e){var t=void 0;try{t=JSON.parse(localStorage.getItem(e))}catch(e){return null}if(null!==t){if(null===t.expires_in||t.expires_in>=(new Date).getTime())return t.value;localStorage.removeItem(e)}return null},e.prototype.remove=function(e){try{localStorage.removeItem(e)}catch(e){}},e}());function d(t){return 0===Object.keys(t).length?"":"?"+Object.keys(t).map(function(e){return encodeURIComponent(e)+"="+encodeURIComponent(t[e])}).join("&")}var n={"popup-window-name":"livechat-login-popup","console-url":"https://developers.livechatinc.com/console/","login-button-class":"livechat-login-button","cache-prefix":"livechat_cache","text-button-product-name":"Live<span>Chat</span>"},l=function(e){return n[e]},p="https://accounts.livechatinc.com",h=function e(t){a(this,e),f.call(this),this._postMessageUniqueId=Math.random().toString(36).substr(2,9),this.updateOptions(t)},f=function(){var a=this;this._options={client_id:null,response_type:"token",linkLabel:null,onIdentityFetched:function(){},onSignedOut:function(){},queryStringParams:{utm_source:"accounts.livechatinc.com",utm_medium:"accounts-sdk"},popupRoute:""},this._postMessageUniqueId=null,this._listenerInited=!1,this._messageReceived=!1,this._lastIdentityError=null,this._lastIdentityData=null,this.updateOptions=function(e){a._options=u(a._options,e),e.backendAddress&&(p=e.backendAddress),s.setEndpoint(p)},this.openPopup=function(e){e&&e.preventDefault&&e.preventDefault();var t=screen.width/2-250,n=screen.height/2-325,o=a._getCurrentPath();a._startListening(),window.open(p+"/"+a._options.popupRoute+d(i({client_id:a._options.client_id,state:a._postMessageUniqueId,response_type:a._options.response_type,redirect_uri:o,flow:"button"},a._options.queryStringParams)),l("popup-window-name"),"resizable,scrollbars,width=500,height=650,left="+t+",top="+n)},this.signOut=function(e){return"function"==typeof e&&(a._options.onSignedOut=e),a._buildIframe("signout")},this.displayButtons=function(e){if(!0!==(e=e||{}).internalCall&&a._lastIdentityError&&"invalid_request"===a._lastIdentityError.oauth_exception)return a._displayError(["Button could not be displayed. Probably you are running this script on a domain that is not whitelisted in your app's settings.","Visit developers console to update your app's domain list: "+l("console-url")]),!1;var t=document.getElementsByClassName(l("login-button-class"));if(0<t.length){var n=document.createElement("link");n.id=l("login-button-class")+"-font",n.rel="stylesheet",n.href="//fonts.googleapis.com/css?family=Lato:300,400,700,900",document.head.appendChild(n),document.head.insertAdjacentHTML("beforeend","<style>."+l("login-button-class")+' a {color: #5a6976;display: inline-block;font-size: 16px;line-height: 1.5;font-family: "Lato", sans-serif;font-weight: 400;text-decoration: none;border: 1px solid #ddd;border-radius: 3px;padding: 8px 24px 9px}.'+l("login-button-class")+" a:hover {border-color: #888;color: #5a6976}."+l("login-button-class")+" span {color: #f56e21</style>");for(var o=0,i=t.length;o<i;o++){var r=t[o];if("1"!==r.getAttribute("data-inited")){r.setAttribute("data-inited","1");var s=document.createElement("a");s.href="",s.onclick=a.openPopup,a._options.linkLabel?s.text=a._options.linkLabel:s.innerHTML="Sign in with <strong>"+l("text-button-product-name")+"</strong>",r.appendChild(s)}}}},this._displayError=function(e){if(!window.console||!window.console.warn)return!1;e instanceof Array||(e=[e]),e.forEach(function(e){return window.console.warn("[accountsSdk] "+e)})},this._returnSuccessResponse=function(t){var n=1<arguments.length&&void 0!==arguments[1]?arguments[1]:{},o={};t.code?(o.code=t.code,s.getInfoByCode(t.code,{success:function(e){o.client_id=e.client_id,o.entity_id=e.entity_id,o.license=e.license_id,o.expires_in=e.expires_in,o.scopes=e.scope?e.scope.split(","):[],a._onIdentityFetched(null,o)},error:function(e){n.fromIframeCache?(a._removeCachedData(),a._buildIframe()):a._onIdentityFetched(e,null)}})):(o.access_token=t.access_token,s.getInfoByAccessToken(t.access_token,{success:function(e){o.client_id=e.client_id,o.entity_id=e.entity_id,o.license=e.license_id,o.expires_in=e.expires_in,o.scopes=e.scope?e.scope.split(","):[],a._onIdentityFetched(null,o),a._cacheData({access_token:t.access_token,expires_in:e.expires_in})},error:function(e){n.fromIframeCache?(a._removeCachedData(),a._buildIframe()):a._onIdentityFetched(e,null)}}))},this._removeIframe=function(){var e=document.getElementById(a._getIframeId());e&&e.parentNode&&e.parentNode.removeChild(e),a._stopListening()},this._receiveMessage=function(e){return e.origin===p&&((!e.data.state||e.data.state===a._postMessageUniqueId)&&(a._messageReceived=!0,a._removeIframe(),void(e.data.error?a._parseError(e.data.error):!0===e.data.signed_out?a._options.onSignedOut():e.data.data&&a._returnSuccessResponse(e.data.data))))},this._parseError=function(e){a._onIdentityFetched(e,null),a._lastIdentityError&&("invalid_request"===a._lastIdentityError.oauth_exception?a._displayError(["Authorization process returned 'invalid_request' error.","Probably you are running this script on a domain that is not whitelisted in your app's settings.","Visit developers console to update your app's domain list: "+l("console-url")]):"access_denied"===a._lastIdentityError.oauth_exception?a._displayError(["Authorization process returned 'access_denied' error.","Probably this application is installed on a different account and you do not have access to it."]):"invalid_request"===a._lastIdentityError.identity_exception&&a._displayError(["Authentication process returned 'invalid_request' error.","You may be loading accountsSdk on a domain that is not whitelisted."]))},this._onIdentityFetched=function(e,t){a._lastIdentityError=e,a._lastIdentityData=t,a.displayButtons({internalCall:!0}),a._options.onIdentityFetched(e,t)},this._buildIframe=function(){var e=0<arguments.length&&void 0!==arguments[0]?arguments[0]:"";a._startListening();var t=document.createElement("iframe");t.setAttribute("src",p+"/"+e+d(i({client_id:a._options.client_id,state:a._postMessageUniqueId,response_type:a._options.response_type,redirect_uri:a._getCurrentPath(),flow:"button"},a._options.queryStringParams))),t.setAttribute("id",a._getIframeId()),t.style.width="1px",t.style.height="1px",t.style.position="fixed",t.style.top="0",t.style.right="0",t.style.opacity="0",t.style.visibility="none",document.body.appendChild(t)},this._getCurrentPath=function(){return window.location.protocol+"//"+window.location.hostname+(window.location.port?":"+window.location.port:"")+window.location.pathname},this._getCacheKey=function(){return l("cache-prefix")+"."+a._options.client_id+"."+a._options.response_type},this._cacheData=function(e){t.set(a._getCacheKey(),e,e.expires_in)},this._getCachedData=function(){return t.get(a._getCacheKey())},this._removeCachedData=function(){return t.remove(a._getCacheKey())},this._getIframeId=function(){return l("login-button-class")+"-iframe."+a._options.client_id+"."+a._options.response_type},this._startListening=function(){if(a._listenerInited)return!1;a._listenerInited=!0,a._messageReceived=!1,window.addEventListener("message",a._receiveMessage,!1)},this._stopListening=function(){a._listenerInited=!1,window.removeEventListener("message",a._receiveMessage,!1)},this.initSDK=function(){if(!a._options.client_id)return window.console&&window.console.warn&&console.warn('[accountsSdk] Required "client_id" param is missing in init() method.'),!1;var e=a._getCachedData();e?a._returnSuccessResponse(e,{fromIframeCache:!0}):(a._buildIframe(),setTimeout(function(){a._messageReceived||a._parseError({identity_exception:"invalid_request"})},5e3))}};return{init:function(e){var t=new h(e);return t.initSDK(),t}}}); | ||
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t():"function"==typeof define&&define.amd?define(t):(e=e||self).AccountsSDK=t()}(this,function(){"use strict";var u=function(e,t){if(null==e)throw new TypeError("Cannot convert undefined or null to object");for(var n=Object(e),o=1;o<arguments.length;o++){var i=arguments[o];if(null!=i)for(var s in i)Object.prototype.hasOwnProperty.call(i,s)&&(n[s]=i[s])}return n};function i(){return(i=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var o in n)Object.prototype.hasOwnProperty.call(n,o)&&(e[o]=n[o])}return e}).apply(this,arguments)}var o=new function(){this.submit=function(e,t){(t=u({},t)).headers=t.headers||[],t.success=t.success||function(){},t.error=t.error||function(){},t.method=t.method||"POST";var n=new XMLHttpRequest;n.open(t.method,e,!0),Object.keys(t.headers).forEach(function(e){return n.setRequestHeader(e,t.headers[e])}),n.onreadystatechange=function(){if(4!==n.readyState)return!1;n.status<200||299<n.status?t.error(n.responseText,n.status):t.success(n.responseText,n.status)},n.send(t.postData)},this.get=function(e,t){var n=new XMLHttpRequest;n.open("GET",e,!0),!0===t.withCredentials&&(n.withCredentials=!0),Object.keys(t.headers).forEach(function(e){return n.setRequestHeader(e,t.headers[e])}),n.onreadystatechange=function(){if(n.readyState!==XMLHttpRequest.DONE)return!1;200===n.status?t.success(n.responseText,n.status):t.error(n.responseText,n.status)},n.send(t.postData)}},s=new(function(i){var e,t;function n(){for(var n,e=arguments.length,t=Array(e),o=0;o<e;o++)t[o]=arguments[o];return(n=i.call.apply(i,[this].concat(t))||this).getInfoByCode=function(e,t){void 0===t&&(t={}),n._get("/info?code="+e+"&type=code",t)},n.getInfoByAccessToken=function(e,t){void 0===t&&(t={}),t.headers=u({Authorization:"Bearer "+e},t.headers),n._get("/info",t)},n}return(e=n).prototype=Object.create((t=i).prototype),(e.prototype.constructor=e).__proto__=t,n}(function(){function e(e,t,n){var c=this;void 0===t&&(t={}),void 0===n&&(n={}),this._promisify=function(e){if(null==e.success&&null==e.error)return new Promise(function(n,o){e.success=function(e,t){n({data:e,statusCode:t})},e.error=function(e,t){o({data:e,statusCode:t})}})},this._URL=function(e){return"function"==typeof c.endpoint?c.endpoint()+e:c.endpoint+e},this._finalOptions=function(n,o,i,s){var r,a,e=JSON.stringify(o),t=u({},i);return t.postData=e,t.headers=u(t.headers||{},c.headers),t.success&&(t.success=(r=t.success,function(t,e){try{t=JSON.parse(t)}catch(e){t={}}r(t,e)})),t.error&&(t.error=(a=t.error,function(t,e){try{t=JSON.parse(t)}catch(e){t={}}if("wrong region"===t.error)return c.options.onIncorrectRegion&&c.options.onIncorrectRegion(t.region),void c[s](n,o,i);a(t,e)})),t},this._get=function(e,t){o.get(c._URL(e),c._finalOptions(e,{},t,"_get"))},this._post=function(e,t,n){o.submit(c._URL(e),c._finalOptions(e,t,n,"_post"))},this._put=function(e,t,n){n.method="PUT",o.submit(c._URL(e),c._finalOptions(e,t,n,"_put"))},this._setDefaults=function(e){return(e=e||{}).headers=e.headers||{},e},this.endpoint=e,this.headers=t,this.options=n}return e.prototype.setEndpoint=function(e){this.endpoint=e},e}()))("https://accounts.livechatinc.com"),t=new(function(){function e(){}var t=e.prototype;return t.set=function(e,t,n){void 0===n&&(n=null);var o={value:t,expires_in:(new Date).getTime()+1e3*n};try{localStorage.setItem(e,JSON.stringify(o))}catch(e){}},t.get=function(e){var t;try{t=JSON.parse(localStorage.getItem(e))}catch(e){return null}if(null!==t){if(null===t.expires_in||t.expires_in>=(new Date).getTime())return t.value;localStorage.removeItem(e)}return null},t.remove=function(e){try{localStorage.removeItem(e)}catch(e){}},e}());function r(t){return 0===Object.keys(t).length?"":"?"+Object.keys(t).map(function(e){return encodeURIComponent(e)+"="+encodeURIComponent(t[e])}).join("&")}var n={"popup-window-name":"livechat-login-popup","console-url":"https://developers.livechatinc.com/console/","login-button-class":"livechat-login-button","cache-prefix":"livechat_cache","text-button-product-name":"Live<span>Chat</span>"},c=function(e){return n[e]},d="https://accounts.livechatinc.com",a=function(e){var a=this;this._options={client_id:null,response_type:"token",linkLabel:null,onIdentityFetched:function(){},onSignedOut:function(){},queryStringParams:{utm_source:"accounts.livechatinc.com",utm_medium:"accounts-sdk"},popupRoute:""},this._postMessageUniqueId=null,this._listenerInited=!1,this._messageReceived=!1,this._lastIdentityError=null,this._lastIdentityData=null,this.updateOptions=function(e){a._options=u(a._options,e),e.backendAddress&&(d=e.backendAddress),s.setEndpoint(d)},this.openPopup=function(e){e&&e.preventDefault&&e.preventDefault();var t=screen.width/2-250,n=screen.height/2-325,o=a._getCurrentPath();a._startListening(),window.open(d+"/"+a._options.popupRoute+r(i({client_id:a._options.client_id,state:a._postMessageUniqueId,response_type:a._options.response_type,redirect_uri:o,flow:"button"},a._options.queryStringParams)),c("popup-window-name"),"resizable,scrollbars,width=500,height=650,left="+t+",top="+n)},this.signOut=function(e){return"function"==typeof e&&(a._options.onSignedOut=e),a._buildIframe("signout")},this.displayButtons=function(e){if(!0!==(e=e||{}).internalCall&&a._lastIdentityError&&"invalid_request"===a._lastIdentityError.oauth_exception)return a._displayError(["Button could not be displayed. Probably you are running this script on a domain that is not whitelisted in your app's settings.","Visit developers console to update your app's domain list: "+c("console-url")]),!1;var t=document.getElementsByClassName(c("login-button-class"));if(0<t.length){var n=document.createElement("link");n.id=c("login-button-class")+"-font",n.rel="stylesheet",n.href="//fonts.googleapis.com/css?family=Lato:300,400,700,900",document.head.appendChild(n),document.head.insertAdjacentHTML("beforeend","<style>."+c("login-button-class")+' a {color: #5a6976;display: inline-block;font-size: 16px;line-height: 1.5;font-family: "Lato", sans-serif;font-weight: 400;text-decoration: none;border: 1px solid #ddd;border-radius: 3px;padding: 8px 24px 9px}.'+c("login-button-class")+" a:hover {border-color: #888;color: #5a6976}."+c("login-button-class")+" span {color: #f56e21</style>");for(var o=0,i=t.length;o<i;o++){var s=t[o];if("1"!==s.getAttribute("data-inited")){s.setAttribute("data-inited","1");var r=document.createElement("a");r.href="",r.onclick=a.openPopup,a._options.linkLabel?r.text=a._options.linkLabel:r.innerHTML="Sign in with <strong>"+c("text-button-product-name")+"</strong>",s.appendChild(r)}}}},this._displayError=function(e){if(!window.console||!window.console.warn)return!1;e instanceof Array||(e=[e]),e.forEach(function(e){return window.console.warn("[accountsSdk] "+e)})},this._returnSuccessResponse=function(t,n){void 0===n&&(n={});var o={};t.code?(o.code=t.code,s.getInfoByCode(t.code,{success:function(e){o.client_id=e.client_id,o.entity_id=e.entity_id,o.license=e.license_id,o.expires_in=e.expires_in,o.scopes=e.scope?e.scope.split(","):[],a._onIdentityFetched(null,o)},error:function(e){n.fromIframeCache?(a._removeCachedData(),a._buildIframe()):a._onIdentityFetched(e,null)}})):(o.access_token=t.access_token,s.getInfoByAccessToken(t.access_token,{success:function(e){o.client_id=e.client_id,o.entity_id=e.entity_id,o.license=e.license_id,o.expires_in=e.expires_in,o.scopes=e.scope?e.scope.split(","):[],a._onIdentityFetched(null,o),a._cacheData({access_token:t.access_token,expires_in:e.expires_in})},error:function(e){n.fromIframeCache?(a._removeCachedData(),a._buildIframe()):a._onIdentityFetched(e,null)}}))},this._removeIframe=function(){var e=document.getElementById(a._getIframeId());e&&e.parentNode&&e.parentNode.removeChild(e),a._stopListening()},this._receiveMessage=function(e){e.origin===d&&e.data&&e.data.state&&e.data.state===a._postMessageUniqueId&&(a._messageReceived=!0,a._removeIframe(),e.data.error?a._parseError(e.data.error):!0===e.data.signed_out?a._options.onSignedOut():e.data.data&&a._returnSuccessResponse(e.data.data))},this._parseError=function(e){a._onIdentityFetched(e,null),a._lastIdentityError&&("invalid_request"===a._lastIdentityError.oauth_exception?a._displayError(["Authorization process returned 'invalid_request' error.","Probably you are running this script on a domain that is not whitelisted in your app's settings.","Visit developers console to update your app's domain list: "+c("console-url")]):"access_denied"===a._lastIdentityError.oauth_exception?a._displayError(["Authorization process returned 'access_denied' error.","Probably this application is installed on a different account and you do not have access to it."]):"invalid_request"===a._lastIdentityError.identity_exception&&a._displayError(["Authentication process returned 'invalid_request' error.","You may be loading accountsSdk on a domain that is not whitelisted."]))},this._onIdentityFetched=function(e,t){a._lastIdentityError=e,a._lastIdentityData=t,a.displayButtons({internalCall:!0}),a._options.onIdentityFetched(e,t)},this._buildIframe=function(e){void 0===e&&(e=""),a._startListening();var t=document.createElement("iframe");t.setAttribute("src",d+"/"+e+r(i({client_id:a._options.client_id,state:a._postMessageUniqueId,response_type:a._options.response_type,redirect_uri:a._getCurrentPath(),flow:"button"},a._options.queryStringParams))),t.setAttribute("id",a._getIframeId()),t.style.width="1px",t.style.height="1px",t.style.position="fixed",t.style.top="0",t.style.right="0",t.style.opacity="0",t.style.visibility="none",document.body.appendChild(t)},this._getCurrentPath=function(){return window.location.protocol+"//"+window.location.hostname+(window.location.port?":"+window.location.port:"")+window.location.pathname},this._getCacheKey=function(){return c("cache-prefix")+"."+a._options.client_id+"."+a._options.response_type},this._cacheData=function(e){t.set(a._getCacheKey(),e,e.expires_in)},this._getCachedData=function(){return t.get(a._getCacheKey())},this._removeCachedData=function(){return t.remove(a._getCacheKey())},this._getIframeId=function(){return c("login-button-class")+"-iframe."+a._options.client_id+"."+a._options.response_type},this._startListening=function(){if(a._listenerInited)return!1;a._listenerInited=!0,a._messageReceived=!1,window.addEventListener("message",a._receiveMessage,!1)},this._stopListening=function(){a._listenerInited=!1,window.removeEventListener("message",a._receiveMessage,!1)},this.initSDK=function(){if(!a._options.client_id)return window.console&&window.console.warn&&console.warn('[accountsSdk] Required "client_id" param is missing in init() method.'),!1;var e=a._getCachedData();e?a._returnSuccessResponse(e,{fromIframeCache:!0}):(a._buildIframe(),setTimeout(function(){a._messageReceived||a._parseError({identity_exception:"invalid_request"})},5e3))},this._postMessageUniqueId=Math.random().toString(36).substr(2,9),this.updateOptions(e)};return{init:function(e){var t=new a(e);return t.initSDK(),t}}}); |
@@ -39,59 +39,38 @@ 'use strict'; | ||
var classCallCheck = function (instance, Constructor) { | ||
if (!(instance instanceof Constructor)) { | ||
throw new TypeError("Cannot call a class as a function"); | ||
} | ||
}; | ||
function _extends() { | ||
_extends = Object.assign || function (target) { | ||
for (var i = 1; i < arguments.length; i++) { | ||
var source = arguments[i]; | ||
var _extends = Object.assign || function (target) { | ||
for (var i = 1; i < arguments.length; i++) { | ||
var source = arguments[i]; | ||
for (var key in source) { | ||
if (Object.prototype.hasOwnProperty.call(source, key)) { | ||
target[key] = source[key]; | ||
for (var key in source) { | ||
if (Object.prototype.hasOwnProperty.call(source, key)) { | ||
target[key] = source[key]; | ||
} | ||
} | ||
} | ||
} | ||
return target; | ||
}; | ||
return target; | ||
}; | ||
var inherits = function (subClass, superClass) { | ||
if (typeof superClass !== "function" && superClass !== null) { | ||
throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); | ||
} | ||
return _extends.apply(this, arguments); | ||
} | ||
subClass.prototype = Object.create(superClass && superClass.prototype, { | ||
constructor: { | ||
value: subClass, | ||
enumerable: false, | ||
writable: true, | ||
configurable: true | ||
} | ||
}); | ||
if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; | ||
}; | ||
function _inheritsLoose(subClass, superClass) { | ||
subClass.prototype = Object.create(superClass.prototype); | ||
subClass.prototype.constructor = subClass; | ||
subClass.__proto__ = superClass; | ||
} | ||
var possibleConstructorReturn = function (self, call) { | ||
if (!self) { | ||
throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); | ||
} | ||
return call && (typeof call === "object" || typeof call === "function") ? call : self; | ||
}; | ||
var Http = function Http() { | ||
classCallCheck(this, Http); | ||
this.submit = function (url, options) { | ||
options = LC_OBJECT_ASSIGN({}, options); | ||
options.headers = options.headers || []; | ||
options.success = options.success || function () {}; | ||
options.error = options.error || function () {}; | ||
options.method = options.method || "POST"; | ||
var http = new XMLHttpRequest(); | ||
http.open(options.method, url, true); | ||
Object.keys(options.headers).forEach(function (key) { | ||
@@ -112,2 +91,3 @@ return http.setRequestHeader(key, options.headers[key]); | ||
}; | ||
http.send(options.postData); | ||
@@ -139,2 +119,3 @@ }; | ||
}; | ||
http.send(options.postData); | ||
@@ -146,132 +127,153 @@ }; | ||
var HttpAPI = function () { | ||
function HttpAPI(endpoint) { | ||
var headers = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; | ||
var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; | ||
classCallCheck(this, HttpAPI); | ||
var HttpAPI = | ||
/*#__PURE__*/ | ||
function () { | ||
function HttpAPI(endpoint, headers, _options) { | ||
var _this = this; | ||
_initialiseProps.call(this); | ||
if (headers === void 0) { | ||
headers = {}; | ||
} | ||
this.endpoint = endpoint; | ||
this.headers = headers; | ||
this.options = options; | ||
} | ||
if (_options === void 0) { | ||
_options = {}; | ||
} | ||
HttpAPI.prototype.setEndpoint = function setEndpoint(endpoint) { | ||
this.endpoint = endpoint; | ||
}; | ||
this._promisify = function (options) { | ||
if (options.success == null && options.error == null) { | ||
return new Promise(function (resolve, reject) { | ||
options.success = function (data, statusCode) { | ||
resolve({ | ||
data: data, | ||
statusCode: statusCode | ||
}); | ||
}; | ||
return HttpAPI; | ||
}(); | ||
options.error = function (data, statusCode) { | ||
reject({ | ||
data: data, | ||
statusCode: statusCode | ||
}); | ||
}; | ||
}); | ||
} | ||
}; | ||
var _initialiseProps = function _initialiseProps() { | ||
var _this = this; | ||
this._URL = function (path) { | ||
if (typeof _this.endpoint === "function") { | ||
return _this.endpoint() + path; | ||
} else { | ||
return _this.endpoint + path; | ||
} | ||
}; | ||
this._promisify = function (options) { | ||
if (options.success == null && options.error == null) { | ||
return new Promise(function (resolve, reject) { | ||
options.success = function (data, statusCode) { | ||
resolve({ data: data, statusCode: statusCode }); | ||
}; | ||
options.error = function (data, statusCode) { | ||
reject({ data: data, statusCode: statusCode }); | ||
}; | ||
}); | ||
} | ||
}; | ||
this._finalOptions = function (path, data, options, method) { | ||
var parsedData = JSON.stringify(data); | ||
var finalOptions = LC_OBJECT_ASSIGN({}, options); | ||
finalOptions.postData = parsedData; | ||
finalOptions.headers = LC_OBJECT_ASSIGN(finalOptions.headers || {}, _this.headers); | ||
this._URL = function (path) { | ||
if (typeof _this.endpoint === "function") { | ||
return _this.endpoint() + path; | ||
} else { | ||
return _this.endpoint + path; | ||
} | ||
}; | ||
if (finalOptions.success) { | ||
finalOptions.success = function () { | ||
var oldCallback = finalOptions.success; | ||
return function (responseText, responseStatus) { | ||
try { | ||
responseText = JSON.parse(responseText); | ||
} catch (e) { | ||
responseText = {}; | ||
} | ||
this._finalOptions = function (path, data, options, method) { | ||
var parsedData = JSON.stringify(data); | ||
oldCallback(responseText, responseStatus); | ||
}; | ||
}(); | ||
} | ||
var finalOptions = LC_OBJECT_ASSIGN({}, options); | ||
finalOptions.postData = parsedData; | ||
finalOptions.headers = LC_OBJECT_ASSIGN(finalOptions.headers || {}, _this.headers); | ||
if (finalOptions.error) { | ||
finalOptions.error = function () { | ||
var oldCallback = finalOptions.error; | ||
return function (responseText, responseStatus) { | ||
try { | ||
responseText = JSON.parse(responseText); | ||
} catch (e) { | ||
responseText = {}; | ||
} | ||
if (finalOptions.success) { | ||
finalOptions.success = function () { | ||
var oldCallback = finalOptions.success; | ||
return function (responseText, responseStatus) { | ||
try { | ||
responseText = JSON.parse(responseText); | ||
} catch (e) { | ||
responseText = {}; | ||
} | ||
oldCallback(responseText, responseStatus); | ||
}; | ||
}(); | ||
} | ||
if (responseText.error === "wrong region") { | ||
if (_this.options.onIncorrectRegion) { | ||
_this.options.onIncorrectRegion(responseText.region); | ||
} | ||
if (finalOptions.error) { | ||
finalOptions.error = function () { | ||
var oldCallback = finalOptions.error; | ||
return function (responseText, responseStatus) { | ||
try { | ||
responseText = JSON.parse(responseText); | ||
} catch (e) { | ||
responseText = {}; | ||
} | ||
_this[method](path, data, options); | ||
if (responseText.error === "wrong region") { | ||
if (_this.options.onIncorrectRegion) { | ||
_this.options.onIncorrectRegion(responseText.region); | ||
return; | ||
} | ||
_this[method](path, data, options); | ||
return; | ||
} | ||
oldCallback(responseText, responseStatus); | ||
}; | ||
}(); | ||
} | ||
oldCallback(responseText, responseStatus); | ||
}; | ||
}(); | ||
} | ||
return finalOptions; | ||
}; | ||
return finalOptions; | ||
}; | ||
this._get = function (path, options) { | ||
Http$1.get(_this._URL(path), _this._finalOptions(path, {}, options, "_get")); | ||
}; | ||
this._get = function (path, options) { | ||
Http$1.get(_this._URL(path), _this._finalOptions(path, {}, options, "_get")); | ||
}; | ||
this._post = function (path, data, options) { | ||
Http$1.submit(_this._URL(path), _this._finalOptions(path, data, options, "_post")); | ||
}; | ||
this._post = function (path, data, options) { | ||
Http$1.submit(_this._URL(path), _this._finalOptions(path, data, options, "_post")); | ||
}; | ||
this._put = function (path, data, options) { | ||
options.method = "PUT"; | ||
Http$1.submit(_this._URL(path), _this._finalOptions(path, data, options, "_put")); | ||
}; | ||
this._put = function (path, data, options) { | ||
options.method = "PUT"; | ||
Http$1.submit(_this._URL(path), _this._finalOptions(path, data, options, "_put")); | ||
}; | ||
this._setDefaults = function (options) { | ||
options = options || {}; | ||
options.headers = options.headers || {}; | ||
return options; | ||
this._setDefaults = function (options) { | ||
options = options || {}; | ||
options.headers = options.headers || {}; | ||
return options; | ||
}; | ||
this.endpoint = endpoint; | ||
this.headers = headers; | ||
this.options = _options; | ||
} | ||
var _proto = HttpAPI.prototype; | ||
_proto.setEndpoint = function setEndpoint(endpoint) { | ||
this.endpoint = endpoint; | ||
}; | ||
}; | ||
var AccountsExternalAPI = function (_HttpAPI) { | ||
inherits(AccountsExternalAPI, _HttpAPI); | ||
return HttpAPI; | ||
}(); | ||
var AccountsExternalAPI = | ||
/*#__PURE__*/ | ||
function (_HttpAPI) { | ||
_inheritsLoose(AccountsExternalAPI, _HttpAPI); | ||
function AccountsExternalAPI() { | ||
var _temp, _this, _ret; | ||
var _this; | ||
classCallCheck(this, AccountsExternalAPI); | ||
for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { | ||
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { | ||
args[_key] = arguments[_key]; | ||
} | ||
return _ret = (_temp = (_this = possibleConstructorReturn(this, _HttpAPI.call.apply(_HttpAPI, [this].concat(args))), _this), _this.getInfoByCode = function (code) { | ||
var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; | ||
_this = _HttpAPI.call.apply(_HttpAPI, [this].concat(args)) || this; | ||
_this.getInfoByCode = function (code, options) { | ||
if (options === void 0) { | ||
options = {}; | ||
} | ||
_this._get("/info?code=" + code + "&type=code", options); | ||
}, _this.getInfoByAccessToken = function (accessToken) { | ||
var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; | ||
}; | ||
_this.getInfoByAccessToken = function (accessToken, options) { | ||
if (options === void 0) { | ||
options = {}; | ||
} | ||
options.headers = LC_OBJECT_ASSIGN({ | ||
@@ -282,3 +284,5 @@ Authorization: "Bearer " + accessToken | ||
_this._get("/info", options); | ||
}, _temp), possibleConstructorReturn(_this, _ret); | ||
}; | ||
return _this; | ||
} | ||
@@ -291,10 +295,14 @@ | ||
var LocalStorage = function () { | ||
function LocalStorage() { | ||
classCallCheck(this, LocalStorage); | ||
} | ||
var LocalStorage = | ||
/*#__PURE__*/ | ||
function () { | ||
function LocalStorage() {} | ||
LocalStorage.prototype.set = function set$$1(key, value) { | ||
var expirationInSeconds = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : null; | ||
var _proto = LocalStorage.prototype; | ||
_proto.set = function set(key, value, expirationInSeconds) { | ||
if (expirationInSeconds === void 0) { | ||
expirationInSeconds = null; | ||
} | ||
var data = { | ||
@@ -310,4 +318,5 @@ value: value, | ||
LocalStorage.prototype.get = function get$$1(key) { | ||
var data = void 0; | ||
_proto.get = function get(key) { | ||
var data; | ||
try { | ||
@@ -326,6 +335,7 @@ data = JSON.parse(localStorage.getItem(key)); | ||
} | ||
return null; | ||
}; | ||
LocalStorage.prototype.remove = function remove(key) { | ||
_proto.remove = function remove(key) { | ||
try { | ||
@@ -355,2 +365,3 @@ localStorage.removeItem(key); | ||
}; | ||
var _getVar = function _getVar(key) { | ||
@@ -362,24 +373,3 @@ return _variables[key]; | ||
var SDK = function SDK(options) { | ||
classCallCheck(this, SDK); | ||
_initialiseProps$1.call(this); | ||
this._postMessageUniqueId = Math.random().toString(36).substr(2, 9); | ||
this.updateOptions(options); | ||
} | ||
// returns current location path without a query string and hash | ||
; | ||
/** | ||
* If you wonder why there's no `export` keyword: | ||
* it's done by rollup's `legacy` plugin | ||
* so that we can support old `AccountsSDK` | ||
* nomenclature for UMD module | ||
* (see rollup.config.js) | ||
*/ | ||
var _initialiseProps$1 = function _initialiseProps() { | ||
var SDK = function SDK(_options) { | ||
var _this = this; | ||
@@ -407,5 +397,7 @@ | ||
_this._options = LC_OBJECT_ASSIGN(_this._options, options); | ||
if (options.backendAddress) { | ||
_postMessageDomain = options.backendAddress; | ||
} | ||
AccountsExternalAPI$1.setEndpoint(_postMessageDomain); | ||
@@ -427,2 +419,3 @@ }; | ||
_this._startListening(); | ||
window.open(_postMessageDomain + "/" + _this._options.popupRoute + buildQueryString(_extends({ | ||
@@ -450,7 +443,9 @@ client_id: _this._options.client_id, | ||
_this._displayError(["Button could not be displayed. Probably you are running this script on a domain that is not whitelisted in your app's settings.", "Visit developers console to update your app's domain list: " + _getVar("console-url")]); | ||
return false; | ||
} | ||
} // append ready-to-use buttons if developer used `livechat-login-button` class | ||
// append ready-to-use buttons if developer used `livechat-login-button` class | ||
var elements = document.getElementsByClassName(_getVar("login-button-class")); | ||
if (elements.length > 0) { | ||
@@ -462,8 +457,6 @@ // include Lato font | ||
link.href = "//fonts.googleapis.com/css?family=Lato:300,400,700,900"; | ||
document.head.appendChild(link); | ||
document.head.appendChild(link); // include CSS styles | ||
// include CSS styles | ||
document.head.insertAdjacentHTML("beforeend", "<style>" + ("." + _getVar("login-button-class") + " a {") + ["color: #5a6976", "display: inline-block", "font-size: 16px", "line-height: 1.5", 'font-family: "Lato", sans-serif', "font-weight: 400", "text-decoration: none", "border: 1px solid #ddd", "border-radius: 3px", "padding: 8px 24px 9px"].join(";") + "}" + ("." + _getVar("login-button-class") + " a:hover {") + ["border-color: #888", "color: #5a6976"].join(";") + "}" + ("." + _getVar("login-button-class") + " span {") + ["color: #f56e21"].join(";") + "</style>"); | ||
document.head.insertAdjacentHTML("beforeend", "<style>" + ("." + _getVar("login-button-class") + " a {") + ["color: #5a6976", "display: inline-block", "font-size: 16px", "line-height: 1.5", 'font-family: "Lato", sans-serif', "font-weight: 400", "text-decoration: none", "border: 1px solid #ddd", "border-radius: 3px", "padding: 8px 24px 9px"].join(";") + "}" + ("." + _getVar("login-button-class") + " a:hover {") + ["border-color: #888", "color: #5a6976"].join(";") + "}" + ("." + _getVar("login-button-class") + " span {") + ["color: #f56e21"].join(";") + "</style>"); // inject <a> link with button | ||
// inject <a> link with button | ||
for (var i = 0, len = elements.length; i < len; i++) { | ||
@@ -474,6 +467,6 @@ var element = elements[i]; | ||
element.setAttribute("data-inited", "1"); | ||
var a = document.createElement("a"); | ||
a.href = ""; | ||
a.onclick = _this.openPopup; | ||
if (_this._options.linkLabel) { | ||
@@ -484,2 +477,3 @@ a.text = _this._options.linkLabel; | ||
} | ||
element.appendChild(a); | ||
@@ -499,2 +493,3 @@ } | ||
} | ||
errorMessages.forEach(function (errorMessage) { | ||
@@ -505,4 +500,6 @@ return window.console.warn("[accountsSdk] " + errorMessage); | ||
this._returnSuccessResponse = function (data) { | ||
var opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; | ||
this._returnSuccessResponse = function (data, opts) { | ||
if (opts === void 0) { | ||
opts = {}; | ||
} | ||
@@ -513,3 +510,2 @@ var response = {}; | ||
response.code = data.code; | ||
AccountsExternalAPI$1.getInfoByCode(data.code, { | ||
@@ -528,2 +524,3 @@ success: function success(successResponse) { | ||
_this._removeCachedData(); | ||
_this._buildIframe(); | ||
@@ -537,3 +534,2 @@ } else { | ||
response.access_token = data.access_token; | ||
AccountsExternalAPI$1.getInfoByAccessToken(data.access_token, { | ||
@@ -557,2 +553,3 @@ success: function success(successResponse) { | ||
_this._removeCachedData(); | ||
_this._buildIframe(); | ||
@@ -569,2 +566,3 @@ } else { | ||
var iframeRef = document.getElementById(_this._getIframeId()); | ||
if (iframeRef && iframeRef.parentNode) { | ||
@@ -579,10 +577,11 @@ iframeRef.parentNode.removeChild(iframeRef); | ||
if (event.origin !== _postMessageDomain) { | ||
return false; | ||
return; | ||
} | ||
if (event.data.state && event.data.state !== _this._postMessageUniqueId) { | ||
return false; | ||
if (!event.data || !event.data.state || event.data.state !== _this._postMessageUniqueId) { | ||
return; | ||
} | ||
_this._messageReceived = true; | ||
_this._removeIframe(); | ||
@@ -620,7 +619,10 @@ | ||
}); | ||
_this._options.onIdentityFetched(error, data); | ||
}; | ||
this._buildIframe = function () { | ||
var endpoint = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : ""; | ||
this._buildIframe = function (endpoint) { | ||
if (endpoint === void 0) { | ||
endpoint = ""; | ||
} | ||
@@ -645,3 +647,2 @@ _this._startListening(); | ||
iframe.style.visibility = "none"; | ||
document.body.appendChild(iframe); | ||
@@ -678,2 +679,3 @@ }; | ||
} | ||
_this._listenerInited = true; | ||
@@ -694,2 +696,3 @@ _this._messageReceived = false; | ||
} | ||
return false; | ||
@@ -699,2 +702,3 @@ } | ||
var cachedData = _this._getCachedData(); | ||
if (cachedData) { | ||
@@ -706,2 +710,3 @@ _this._returnSuccessResponse(cachedData, { | ||
_this._buildIframe(); | ||
setTimeout(function () { | ||
@@ -716,2 +721,5 @@ if (!_this._messageReceived) { | ||
}; | ||
this._postMessageUniqueId = Math.random().toString(36).substr(2, 9); | ||
this.updateOptions(_options); | ||
}; | ||
@@ -718,0 +726,0 @@ |
@@ -35,59 +35,38 @@ var LC_OBJECT_ASSIGN = (function () { | ||
var classCallCheck = function (instance, Constructor) { | ||
if (!(instance instanceof Constructor)) { | ||
throw new TypeError("Cannot call a class as a function"); | ||
} | ||
}; | ||
function _extends() { | ||
_extends = Object.assign || function (target) { | ||
for (var i = 1; i < arguments.length; i++) { | ||
var source = arguments[i]; | ||
var _extends = Object.assign || function (target) { | ||
for (var i = 1; i < arguments.length; i++) { | ||
var source = arguments[i]; | ||
for (var key in source) { | ||
if (Object.prototype.hasOwnProperty.call(source, key)) { | ||
target[key] = source[key]; | ||
for (var key in source) { | ||
if (Object.prototype.hasOwnProperty.call(source, key)) { | ||
target[key] = source[key]; | ||
} | ||
} | ||
} | ||
} | ||
return target; | ||
}; | ||
return target; | ||
}; | ||
var inherits = function (subClass, superClass) { | ||
if (typeof superClass !== "function" && superClass !== null) { | ||
throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); | ||
} | ||
return _extends.apply(this, arguments); | ||
} | ||
subClass.prototype = Object.create(superClass && superClass.prototype, { | ||
constructor: { | ||
value: subClass, | ||
enumerable: false, | ||
writable: true, | ||
configurable: true | ||
} | ||
}); | ||
if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; | ||
}; | ||
function _inheritsLoose(subClass, superClass) { | ||
subClass.prototype = Object.create(superClass.prototype); | ||
subClass.prototype.constructor = subClass; | ||
subClass.__proto__ = superClass; | ||
} | ||
var possibleConstructorReturn = function (self, call) { | ||
if (!self) { | ||
throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); | ||
} | ||
return call && (typeof call === "object" || typeof call === "function") ? call : self; | ||
}; | ||
var Http = function Http() { | ||
classCallCheck(this, Http); | ||
this.submit = function (url, options) { | ||
options = LC_OBJECT_ASSIGN({}, options); | ||
options.headers = options.headers || []; | ||
options.success = options.success || function () {}; | ||
options.error = options.error || function () {}; | ||
options.method = options.method || "POST"; | ||
var http = new XMLHttpRequest(); | ||
http.open(options.method, url, true); | ||
Object.keys(options.headers).forEach(function (key) { | ||
@@ -108,2 +87,3 @@ return http.setRequestHeader(key, options.headers[key]); | ||
}; | ||
http.send(options.postData); | ||
@@ -135,2 +115,3 @@ }; | ||
}; | ||
http.send(options.postData); | ||
@@ -142,132 +123,153 @@ }; | ||
var HttpAPI = function () { | ||
function HttpAPI(endpoint) { | ||
var headers = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; | ||
var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; | ||
classCallCheck(this, HttpAPI); | ||
var HttpAPI = | ||
/*#__PURE__*/ | ||
function () { | ||
function HttpAPI(endpoint, headers, _options) { | ||
var _this = this; | ||
_initialiseProps.call(this); | ||
if (headers === void 0) { | ||
headers = {}; | ||
} | ||
this.endpoint = endpoint; | ||
this.headers = headers; | ||
this.options = options; | ||
} | ||
if (_options === void 0) { | ||
_options = {}; | ||
} | ||
HttpAPI.prototype.setEndpoint = function setEndpoint(endpoint) { | ||
this.endpoint = endpoint; | ||
}; | ||
this._promisify = function (options) { | ||
if (options.success == null && options.error == null) { | ||
return new Promise(function (resolve, reject) { | ||
options.success = function (data, statusCode) { | ||
resolve({ | ||
data: data, | ||
statusCode: statusCode | ||
}); | ||
}; | ||
return HttpAPI; | ||
}(); | ||
options.error = function (data, statusCode) { | ||
reject({ | ||
data: data, | ||
statusCode: statusCode | ||
}); | ||
}; | ||
}); | ||
} | ||
}; | ||
var _initialiseProps = function _initialiseProps() { | ||
var _this = this; | ||
this._URL = function (path) { | ||
if (typeof _this.endpoint === "function") { | ||
return _this.endpoint() + path; | ||
} else { | ||
return _this.endpoint + path; | ||
} | ||
}; | ||
this._promisify = function (options) { | ||
if (options.success == null && options.error == null) { | ||
return new Promise(function (resolve, reject) { | ||
options.success = function (data, statusCode) { | ||
resolve({ data: data, statusCode: statusCode }); | ||
}; | ||
options.error = function (data, statusCode) { | ||
reject({ data: data, statusCode: statusCode }); | ||
}; | ||
}); | ||
} | ||
}; | ||
this._finalOptions = function (path, data, options, method) { | ||
var parsedData = JSON.stringify(data); | ||
var finalOptions = LC_OBJECT_ASSIGN({}, options); | ||
finalOptions.postData = parsedData; | ||
finalOptions.headers = LC_OBJECT_ASSIGN(finalOptions.headers || {}, _this.headers); | ||
this._URL = function (path) { | ||
if (typeof _this.endpoint === "function") { | ||
return _this.endpoint() + path; | ||
} else { | ||
return _this.endpoint + path; | ||
} | ||
}; | ||
if (finalOptions.success) { | ||
finalOptions.success = function () { | ||
var oldCallback = finalOptions.success; | ||
return function (responseText, responseStatus) { | ||
try { | ||
responseText = JSON.parse(responseText); | ||
} catch (e) { | ||
responseText = {}; | ||
} | ||
this._finalOptions = function (path, data, options, method) { | ||
var parsedData = JSON.stringify(data); | ||
oldCallback(responseText, responseStatus); | ||
}; | ||
}(); | ||
} | ||
var finalOptions = LC_OBJECT_ASSIGN({}, options); | ||
finalOptions.postData = parsedData; | ||
finalOptions.headers = LC_OBJECT_ASSIGN(finalOptions.headers || {}, _this.headers); | ||
if (finalOptions.error) { | ||
finalOptions.error = function () { | ||
var oldCallback = finalOptions.error; | ||
return function (responseText, responseStatus) { | ||
try { | ||
responseText = JSON.parse(responseText); | ||
} catch (e) { | ||
responseText = {}; | ||
} | ||
if (finalOptions.success) { | ||
finalOptions.success = function () { | ||
var oldCallback = finalOptions.success; | ||
return function (responseText, responseStatus) { | ||
try { | ||
responseText = JSON.parse(responseText); | ||
} catch (e) { | ||
responseText = {}; | ||
} | ||
oldCallback(responseText, responseStatus); | ||
}; | ||
}(); | ||
} | ||
if (responseText.error === "wrong region") { | ||
if (_this.options.onIncorrectRegion) { | ||
_this.options.onIncorrectRegion(responseText.region); | ||
} | ||
if (finalOptions.error) { | ||
finalOptions.error = function () { | ||
var oldCallback = finalOptions.error; | ||
return function (responseText, responseStatus) { | ||
try { | ||
responseText = JSON.parse(responseText); | ||
} catch (e) { | ||
responseText = {}; | ||
} | ||
_this[method](path, data, options); | ||
if (responseText.error === "wrong region") { | ||
if (_this.options.onIncorrectRegion) { | ||
_this.options.onIncorrectRegion(responseText.region); | ||
return; | ||
} | ||
_this[method](path, data, options); | ||
return; | ||
} | ||
oldCallback(responseText, responseStatus); | ||
}; | ||
}(); | ||
} | ||
oldCallback(responseText, responseStatus); | ||
}; | ||
}(); | ||
} | ||
return finalOptions; | ||
}; | ||
return finalOptions; | ||
}; | ||
this._get = function (path, options) { | ||
Http$1.get(_this._URL(path), _this._finalOptions(path, {}, options, "_get")); | ||
}; | ||
this._get = function (path, options) { | ||
Http$1.get(_this._URL(path), _this._finalOptions(path, {}, options, "_get")); | ||
}; | ||
this._post = function (path, data, options) { | ||
Http$1.submit(_this._URL(path), _this._finalOptions(path, data, options, "_post")); | ||
}; | ||
this._post = function (path, data, options) { | ||
Http$1.submit(_this._URL(path), _this._finalOptions(path, data, options, "_post")); | ||
}; | ||
this._put = function (path, data, options) { | ||
options.method = "PUT"; | ||
Http$1.submit(_this._URL(path), _this._finalOptions(path, data, options, "_put")); | ||
}; | ||
this._put = function (path, data, options) { | ||
options.method = "PUT"; | ||
Http$1.submit(_this._URL(path), _this._finalOptions(path, data, options, "_put")); | ||
}; | ||
this._setDefaults = function (options) { | ||
options = options || {}; | ||
options.headers = options.headers || {}; | ||
return options; | ||
this._setDefaults = function (options) { | ||
options = options || {}; | ||
options.headers = options.headers || {}; | ||
return options; | ||
}; | ||
this.endpoint = endpoint; | ||
this.headers = headers; | ||
this.options = _options; | ||
} | ||
var _proto = HttpAPI.prototype; | ||
_proto.setEndpoint = function setEndpoint(endpoint) { | ||
this.endpoint = endpoint; | ||
}; | ||
}; | ||
var AccountsExternalAPI = function (_HttpAPI) { | ||
inherits(AccountsExternalAPI, _HttpAPI); | ||
return HttpAPI; | ||
}(); | ||
var AccountsExternalAPI = | ||
/*#__PURE__*/ | ||
function (_HttpAPI) { | ||
_inheritsLoose(AccountsExternalAPI, _HttpAPI); | ||
function AccountsExternalAPI() { | ||
var _temp, _this, _ret; | ||
var _this; | ||
classCallCheck(this, AccountsExternalAPI); | ||
for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { | ||
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { | ||
args[_key] = arguments[_key]; | ||
} | ||
return _ret = (_temp = (_this = possibleConstructorReturn(this, _HttpAPI.call.apply(_HttpAPI, [this].concat(args))), _this), _this.getInfoByCode = function (code) { | ||
var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; | ||
_this = _HttpAPI.call.apply(_HttpAPI, [this].concat(args)) || this; | ||
_this.getInfoByCode = function (code, options) { | ||
if (options === void 0) { | ||
options = {}; | ||
} | ||
_this._get("/info?code=" + code + "&type=code", options); | ||
}, _this.getInfoByAccessToken = function (accessToken) { | ||
var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; | ||
}; | ||
_this.getInfoByAccessToken = function (accessToken, options) { | ||
if (options === void 0) { | ||
options = {}; | ||
} | ||
options.headers = LC_OBJECT_ASSIGN({ | ||
@@ -278,3 +280,5 @@ Authorization: "Bearer " + accessToken | ||
_this._get("/info", options); | ||
}, _temp), possibleConstructorReturn(_this, _ret); | ||
}; | ||
return _this; | ||
} | ||
@@ -287,10 +291,14 @@ | ||
var LocalStorage = function () { | ||
function LocalStorage() { | ||
classCallCheck(this, LocalStorage); | ||
} | ||
var LocalStorage = | ||
/*#__PURE__*/ | ||
function () { | ||
function LocalStorage() {} | ||
LocalStorage.prototype.set = function set$$1(key, value) { | ||
var expirationInSeconds = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : null; | ||
var _proto = LocalStorage.prototype; | ||
_proto.set = function set(key, value, expirationInSeconds) { | ||
if (expirationInSeconds === void 0) { | ||
expirationInSeconds = null; | ||
} | ||
var data = { | ||
@@ -306,4 +314,5 @@ value: value, | ||
LocalStorage.prototype.get = function get$$1(key) { | ||
var data = void 0; | ||
_proto.get = function get(key) { | ||
var data; | ||
try { | ||
@@ -322,6 +331,7 @@ data = JSON.parse(localStorage.getItem(key)); | ||
} | ||
return null; | ||
}; | ||
LocalStorage.prototype.remove = function remove(key) { | ||
_proto.remove = function remove(key) { | ||
try { | ||
@@ -351,2 +361,3 @@ localStorage.removeItem(key); | ||
}; | ||
var _getVar = function _getVar(key) { | ||
@@ -358,24 +369,3 @@ return _variables[key]; | ||
var SDK = function SDK(options) { | ||
classCallCheck(this, SDK); | ||
_initialiseProps$1.call(this); | ||
this._postMessageUniqueId = Math.random().toString(36).substr(2, 9); | ||
this.updateOptions(options); | ||
} | ||
// returns current location path without a query string and hash | ||
; | ||
/** | ||
* If you wonder why there's no `export` keyword: | ||
* it's done by rollup's `legacy` plugin | ||
* so that we can support old `AccountsSDK` | ||
* nomenclature for UMD module | ||
* (see rollup.config.js) | ||
*/ | ||
var _initialiseProps$1 = function _initialiseProps() { | ||
var SDK = function SDK(_options) { | ||
var _this = this; | ||
@@ -403,5 +393,7 @@ | ||
_this._options = LC_OBJECT_ASSIGN(_this._options, options); | ||
if (options.backendAddress) { | ||
_postMessageDomain = options.backendAddress; | ||
} | ||
AccountsExternalAPI$1.setEndpoint(_postMessageDomain); | ||
@@ -423,2 +415,3 @@ }; | ||
_this._startListening(); | ||
window.open(_postMessageDomain + "/" + _this._options.popupRoute + buildQueryString(_extends({ | ||
@@ -446,7 +439,9 @@ client_id: _this._options.client_id, | ||
_this._displayError(["Button could not be displayed. Probably you are running this script on a domain that is not whitelisted in your app's settings.", "Visit developers console to update your app's domain list: " + _getVar("console-url")]); | ||
return false; | ||
} | ||
} // append ready-to-use buttons if developer used `livechat-login-button` class | ||
// append ready-to-use buttons if developer used `livechat-login-button` class | ||
var elements = document.getElementsByClassName(_getVar("login-button-class")); | ||
if (elements.length > 0) { | ||
@@ -458,8 +453,6 @@ // include Lato font | ||
link.href = "//fonts.googleapis.com/css?family=Lato:300,400,700,900"; | ||
document.head.appendChild(link); | ||
document.head.appendChild(link); // include CSS styles | ||
// include CSS styles | ||
document.head.insertAdjacentHTML("beforeend", "<style>" + ("." + _getVar("login-button-class") + " a {") + ["color: #5a6976", "display: inline-block", "font-size: 16px", "line-height: 1.5", 'font-family: "Lato", sans-serif', "font-weight: 400", "text-decoration: none", "border: 1px solid #ddd", "border-radius: 3px", "padding: 8px 24px 9px"].join(";") + "}" + ("." + _getVar("login-button-class") + " a:hover {") + ["border-color: #888", "color: #5a6976"].join(";") + "}" + ("." + _getVar("login-button-class") + " span {") + ["color: #f56e21"].join(";") + "</style>"); | ||
document.head.insertAdjacentHTML("beforeend", "<style>" + ("." + _getVar("login-button-class") + " a {") + ["color: #5a6976", "display: inline-block", "font-size: 16px", "line-height: 1.5", 'font-family: "Lato", sans-serif', "font-weight: 400", "text-decoration: none", "border: 1px solid #ddd", "border-radius: 3px", "padding: 8px 24px 9px"].join(";") + "}" + ("." + _getVar("login-button-class") + " a:hover {") + ["border-color: #888", "color: #5a6976"].join(";") + "}" + ("." + _getVar("login-button-class") + " span {") + ["color: #f56e21"].join(";") + "</style>"); // inject <a> link with button | ||
// inject <a> link with button | ||
for (var i = 0, len = elements.length; i < len; i++) { | ||
@@ -470,6 +463,6 @@ var element = elements[i]; | ||
element.setAttribute("data-inited", "1"); | ||
var a = document.createElement("a"); | ||
a.href = ""; | ||
a.onclick = _this.openPopup; | ||
if (_this._options.linkLabel) { | ||
@@ -480,2 +473,3 @@ a.text = _this._options.linkLabel; | ||
} | ||
element.appendChild(a); | ||
@@ -495,2 +489,3 @@ } | ||
} | ||
errorMessages.forEach(function (errorMessage) { | ||
@@ -501,4 +496,6 @@ return window.console.warn("[accountsSdk] " + errorMessage); | ||
this._returnSuccessResponse = function (data) { | ||
var opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; | ||
this._returnSuccessResponse = function (data, opts) { | ||
if (opts === void 0) { | ||
opts = {}; | ||
} | ||
@@ -509,3 +506,2 @@ var response = {}; | ||
response.code = data.code; | ||
AccountsExternalAPI$1.getInfoByCode(data.code, { | ||
@@ -524,2 +520,3 @@ success: function success(successResponse) { | ||
_this._removeCachedData(); | ||
_this._buildIframe(); | ||
@@ -533,3 +530,2 @@ } else { | ||
response.access_token = data.access_token; | ||
AccountsExternalAPI$1.getInfoByAccessToken(data.access_token, { | ||
@@ -553,2 +549,3 @@ success: function success(successResponse) { | ||
_this._removeCachedData(); | ||
_this._buildIframe(); | ||
@@ -565,2 +562,3 @@ } else { | ||
var iframeRef = document.getElementById(_this._getIframeId()); | ||
if (iframeRef && iframeRef.parentNode) { | ||
@@ -575,10 +573,11 @@ iframeRef.parentNode.removeChild(iframeRef); | ||
if (event.origin !== _postMessageDomain) { | ||
return false; | ||
return; | ||
} | ||
if (event.data.state && event.data.state !== _this._postMessageUniqueId) { | ||
return false; | ||
if (!event.data || !event.data.state || event.data.state !== _this._postMessageUniqueId) { | ||
return; | ||
} | ||
_this._messageReceived = true; | ||
_this._removeIframe(); | ||
@@ -616,7 +615,10 @@ | ||
}); | ||
_this._options.onIdentityFetched(error, data); | ||
}; | ||
this._buildIframe = function () { | ||
var endpoint = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : ""; | ||
this._buildIframe = function (endpoint) { | ||
if (endpoint === void 0) { | ||
endpoint = ""; | ||
} | ||
@@ -641,3 +643,2 @@ _this._startListening(); | ||
iframe.style.visibility = "none"; | ||
document.body.appendChild(iframe); | ||
@@ -674,2 +675,3 @@ }; | ||
} | ||
_this._listenerInited = true; | ||
@@ -690,2 +692,3 @@ _this._messageReceived = false; | ||
} | ||
return false; | ||
@@ -695,2 +698,3 @@ } | ||
var cachedData = _this._getCachedData(); | ||
if (cachedData) { | ||
@@ -702,2 +706,3 @@ _this._returnSuccessResponse(cachedData, { | ||
_this._buildIframe(); | ||
setTimeout(function () { | ||
@@ -712,2 +717,5 @@ if (!_this._messageReceived) { | ||
}; | ||
this._postMessageUniqueId = Math.random().toString(36).substr(2, 9); | ||
this.updateOptions(_options); | ||
}; | ||
@@ -714,0 +722,0 @@ |
@@ -1,1 +0,1 @@ | ||
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t():"function"==typeof define&&define.amd?define(t):e.AccountsSDK=t()}(this,function(){"use strict";var u=function(e,t){if(null==e)throw new TypeError("Cannot convert undefined or null to object");for(var n=Object(e),o=1;o<arguments.length;o++){var i=arguments[o];if(null!=i)for(var r in i)Object.prototype.hasOwnProperty.call(i,r)&&(n[r]=i[r])}return n},a=function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")},i=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var o in n)Object.prototype.hasOwnProperty.call(n,o)&&(e[o]=n[o])}return e},c=function(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t},o=new function e(){a(this,e),this.submit=function(e,t){(t=u({},t)).headers=t.headers||[],t.success=t.success||function(){},t.error=t.error||function(){},t.method=t.method||"POST";var n=new XMLHttpRequest;n.open(t.method,e,!0),Object.keys(t.headers).forEach(function(e){return n.setRequestHeader(e,t.headers[e])}),n.onreadystatechange=function(){if(4!==n.readyState)return!1;n.status<200||299<n.status?t.error(n.responseText,n.status):t.success(n.responseText,n.status)},n.send(t.postData)},this.get=function(e,t){var n=new XMLHttpRequest;n.open("GET",e,!0),!0===t.withCredentials&&(n.withCredentials=!0),Object.keys(t.headers).forEach(function(e){return n.setRequestHeader(e,t.headers[e])}),n.onreadystatechange=function(){if(n.readyState!==XMLHttpRequest.DONE)return!1;200===n.status?t.success(n.responseText,n.status):t.error(n.responseText,n.status)},n.send(t.postData)}},e=function(){function o(e){var t=1<arguments.length&&void 0!==arguments[1]?arguments[1]:{},n=2<arguments.length&&void 0!==arguments[2]?arguments[2]:{};a(this,o),r.call(this),this.endpoint=e,this.headers=t,this.options=n}return o.prototype.setEndpoint=function(e){this.endpoint=e},o}(),r=function(){var c=this;this._promisify=function(e){if(null==e.success&&null==e.error)return new Promise(function(n,o){e.success=function(e,t){n({data:e,statusCode:t})},e.error=function(e,t){o({data:e,statusCode:t})}})},this._URL=function(e){return"function"==typeof c.endpoint?c.endpoint()+e:c.endpoint+e},this._finalOptions=function(n,o,i,r){var s,a,e=JSON.stringify(o),t=u({},i);return t.postData=e,t.headers=u(t.headers||{},c.headers),t.success&&(t.success=(s=t.success,function(t,e){try{t=JSON.parse(t)}catch(e){t={}}s(t,e)})),t.error&&(t.error=(a=t.error,function(t,e){try{t=JSON.parse(t)}catch(e){t={}}if("wrong region"===t.error)return c.options.onIncorrectRegion&&c.options.onIncorrectRegion(t.region),void c[r](n,o,i);a(t,e)})),t},this._get=function(e,t){o.get(c._URL(e),c._finalOptions(e,{},t,"_get"))},this._post=function(e,t,n){o.submit(c._URL(e),c._finalOptions(e,t,n,"_post"))},this._put=function(e,t,n){n.method="PUT",o.submit(c._URL(e),c._finalOptions(e,t,n,"_put"))},this._setDefaults=function(e){return(e=e||{}).headers=e.headers||{},e}},s=new(function(r){function s(){var e,n;a(this,s);for(var t=arguments.length,o=Array(t),i=0;i<t;i++)o[i]=arguments[i];return(e=n=c(this,r.call.apply(r,[this].concat(o)))).getInfoByCode=function(e){n._get("/info?code="+e+"&type=code",1<arguments.length&&void 0!==arguments[1]?arguments[1]:{})},n.getInfoByAccessToken=function(e){var t=1<arguments.length&&void 0!==arguments[1]?arguments[1]:{};t.headers=u({Authorization:"Bearer "+e},t.headers),n._get("/info",t)},c(n,e)}return function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}(s,r),s}(e))("https://accounts.livechatinc.com"),t=new(function(){function e(){a(this,e)}return e.prototype.set=function(e,t){var n=2<arguments.length&&void 0!==arguments[2]?arguments[2]:null,o={value:t,expires_in:(new Date).getTime()+1e3*n};try{localStorage.setItem(e,JSON.stringify(o))}catch(e){}},e.prototype.get=function(e){var t=void 0;try{t=JSON.parse(localStorage.getItem(e))}catch(e){return null}if(null!==t){if(null===t.expires_in||t.expires_in>=(new Date).getTime())return t.value;localStorage.removeItem(e)}return null},e.prototype.remove=function(e){try{localStorage.removeItem(e)}catch(e){}},e}());function d(t){return 0===Object.keys(t).length?"":"?"+Object.keys(t).map(function(e){return encodeURIComponent(e)+"="+encodeURIComponent(t[e])}).join("&")}var n={"popup-window-name":"livechat-login-popup","console-url":"https://developers.livechatinc.com/console/","login-button-class":"livechat-login-button","cache-prefix":"livechat_cache","text-button-product-name":"Live<span>Chat</span>"},l=function(e){return n[e]},p="https://accounts.livechatinc.com",h=function e(t){a(this,e),f.call(this),this._postMessageUniqueId=Math.random().toString(36).substr(2,9),this.updateOptions(t)},f=function(){var a=this;this._options={client_id:null,response_type:"token",linkLabel:null,onIdentityFetched:function(){},onSignedOut:function(){},queryStringParams:{utm_source:"accounts.livechatinc.com",utm_medium:"accounts-sdk"},popupRoute:""},this._postMessageUniqueId=null,this._listenerInited=!1,this._messageReceived=!1,this._lastIdentityError=null,this._lastIdentityData=null,this.updateOptions=function(e){a._options=u(a._options,e),e.backendAddress&&(p=e.backendAddress),s.setEndpoint(p)},this.openPopup=function(e){e&&e.preventDefault&&e.preventDefault();var t=screen.width/2-250,n=screen.height/2-325,o=a._getCurrentPath();a._startListening(),window.open(p+"/"+a._options.popupRoute+d(i({client_id:a._options.client_id,state:a._postMessageUniqueId,response_type:a._options.response_type,redirect_uri:o,flow:"button"},a._options.queryStringParams)),l("popup-window-name"),"resizable,scrollbars,width=500,height=650,left="+t+",top="+n)},this.signOut=function(e){return"function"==typeof e&&(a._options.onSignedOut=e),a._buildIframe("signout")},this.displayButtons=function(e){if(!0!==(e=e||{}).internalCall&&a._lastIdentityError&&"invalid_request"===a._lastIdentityError.oauth_exception)return a._displayError(["Button could not be displayed. Probably you are running this script on a domain that is not whitelisted in your app's settings.","Visit developers console to update your app's domain list: "+l("console-url")]),!1;var t=document.getElementsByClassName(l("login-button-class"));if(0<t.length){var n=document.createElement("link");n.id=l("login-button-class")+"-font",n.rel="stylesheet",n.href="//fonts.googleapis.com/css?family=Lato:300,400,700,900",document.head.appendChild(n),document.head.insertAdjacentHTML("beforeend","<style>."+l("login-button-class")+' a {color: #5a6976;display: inline-block;font-size: 16px;line-height: 1.5;font-family: "Lato", sans-serif;font-weight: 400;text-decoration: none;border: 1px solid #ddd;border-radius: 3px;padding: 8px 24px 9px}.'+l("login-button-class")+" a:hover {border-color: #888;color: #5a6976}."+l("login-button-class")+" span {color: #f56e21</style>");for(var o=0,i=t.length;o<i;o++){var r=t[o];if("1"!==r.getAttribute("data-inited")){r.setAttribute("data-inited","1");var s=document.createElement("a");s.href="",s.onclick=a.openPopup,a._options.linkLabel?s.text=a._options.linkLabel:s.innerHTML="Sign in with <strong>"+l("text-button-product-name")+"</strong>",r.appendChild(s)}}}},this._displayError=function(e){if(!window.console||!window.console.warn)return!1;e instanceof Array||(e=[e]),e.forEach(function(e){return window.console.warn("[accountsSdk] "+e)})},this._returnSuccessResponse=function(t){var n=1<arguments.length&&void 0!==arguments[1]?arguments[1]:{},o={};t.code?(o.code=t.code,s.getInfoByCode(t.code,{success:function(e){o.client_id=e.client_id,o.entity_id=e.entity_id,o.license=e.license_id,o.expires_in=e.expires_in,o.scopes=e.scope?e.scope.split(","):[],a._onIdentityFetched(null,o)},error:function(e){n.fromIframeCache?(a._removeCachedData(),a._buildIframe()):a._onIdentityFetched(e,null)}})):(o.access_token=t.access_token,s.getInfoByAccessToken(t.access_token,{success:function(e){o.client_id=e.client_id,o.entity_id=e.entity_id,o.license=e.license_id,o.expires_in=e.expires_in,o.scopes=e.scope?e.scope.split(","):[],a._onIdentityFetched(null,o),a._cacheData({access_token:t.access_token,expires_in:e.expires_in})},error:function(e){n.fromIframeCache?(a._removeCachedData(),a._buildIframe()):a._onIdentityFetched(e,null)}}))},this._removeIframe=function(){var e=document.getElementById(a._getIframeId());e&&e.parentNode&&e.parentNode.removeChild(e),a._stopListening()},this._receiveMessage=function(e){return e.origin===p&&((!e.data.state||e.data.state===a._postMessageUniqueId)&&(a._messageReceived=!0,a._removeIframe(),void(e.data.error?a._parseError(e.data.error):!0===e.data.signed_out?a._options.onSignedOut():e.data.data&&a._returnSuccessResponse(e.data.data))))},this._parseError=function(e){a._onIdentityFetched(e,null),a._lastIdentityError&&("invalid_request"===a._lastIdentityError.oauth_exception?a._displayError(["Authorization process returned 'invalid_request' error.","Probably you are running this script on a domain that is not whitelisted in your app's settings.","Visit developers console to update your app's domain list: "+l("console-url")]):"access_denied"===a._lastIdentityError.oauth_exception?a._displayError(["Authorization process returned 'access_denied' error.","Probably this application is installed on a different account and you do not have access to it."]):"invalid_request"===a._lastIdentityError.identity_exception&&a._displayError(["Authentication process returned 'invalid_request' error.","You may be loading accountsSdk on a domain that is not whitelisted."]))},this._onIdentityFetched=function(e,t){a._lastIdentityError=e,a._lastIdentityData=t,a.displayButtons({internalCall:!0}),a._options.onIdentityFetched(e,t)},this._buildIframe=function(){var e=0<arguments.length&&void 0!==arguments[0]?arguments[0]:"";a._startListening();var t=document.createElement("iframe");t.setAttribute("src",p+"/"+e+d(i({client_id:a._options.client_id,state:a._postMessageUniqueId,response_type:a._options.response_type,redirect_uri:a._getCurrentPath(),flow:"button"},a._options.queryStringParams))),t.setAttribute("id",a._getIframeId()),t.style.width="1px",t.style.height="1px",t.style.position="fixed",t.style.top="0",t.style.right="0",t.style.opacity="0",t.style.visibility="none",document.body.appendChild(t)},this._getCurrentPath=function(){return window.location.protocol+"//"+window.location.hostname+(window.location.port?":"+window.location.port:"")+window.location.pathname},this._getCacheKey=function(){return l("cache-prefix")+"."+a._options.client_id+"."+a._options.response_type},this._cacheData=function(e){t.set(a._getCacheKey(),e,e.expires_in)},this._getCachedData=function(){return t.get(a._getCacheKey())},this._removeCachedData=function(){return t.remove(a._getCacheKey())},this._getIframeId=function(){return l("login-button-class")+"-iframe."+a._options.client_id+"."+a._options.response_type},this._startListening=function(){if(a._listenerInited)return!1;a._listenerInited=!0,a._messageReceived=!1,window.addEventListener("message",a._receiveMessage,!1)},this._stopListening=function(){a._listenerInited=!1,window.removeEventListener("message",a._receiveMessage,!1)},this.initSDK=function(){if(!a._options.client_id)return window.console&&window.console.warn&&console.warn('[accountsSdk] Required "client_id" param is missing in init() method.'),!1;var e=a._getCachedData();e?a._returnSuccessResponse(e,{fromIframeCache:!0}):(a._buildIframe(),setTimeout(function(){a._messageReceived||a._parseError({identity_exception:"invalid_request"})},5e3))}};return{init:function(e){var t=new h(e);return t.initSDK(),t}}}); | ||
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t():"function"==typeof define&&define.amd?define(t):(e=e||self).AccountsSDK=t()}(this,function(){"use strict";var u=function(e,t){if(null==e)throw new TypeError("Cannot convert undefined or null to object");for(var n=Object(e),o=1;o<arguments.length;o++){var i=arguments[o];if(null!=i)for(var s in i)Object.prototype.hasOwnProperty.call(i,s)&&(n[s]=i[s])}return n};function i(){return(i=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var o in n)Object.prototype.hasOwnProperty.call(n,o)&&(e[o]=n[o])}return e}).apply(this,arguments)}var o=new function(){this.submit=function(e,t){(t=u({},t)).headers=t.headers||[],t.success=t.success||function(){},t.error=t.error||function(){},t.method=t.method||"POST";var n=new XMLHttpRequest;n.open(t.method,e,!0),Object.keys(t.headers).forEach(function(e){return n.setRequestHeader(e,t.headers[e])}),n.onreadystatechange=function(){if(4!==n.readyState)return!1;n.status<200||299<n.status?t.error(n.responseText,n.status):t.success(n.responseText,n.status)},n.send(t.postData)},this.get=function(e,t){var n=new XMLHttpRequest;n.open("GET",e,!0),!0===t.withCredentials&&(n.withCredentials=!0),Object.keys(t.headers).forEach(function(e){return n.setRequestHeader(e,t.headers[e])}),n.onreadystatechange=function(){if(n.readyState!==XMLHttpRequest.DONE)return!1;200===n.status?t.success(n.responseText,n.status):t.error(n.responseText,n.status)},n.send(t.postData)}},s=new(function(i){var e,t;function n(){for(var n,e=arguments.length,t=Array(e),o=0;o<e;o++)t[o]=arguments[o];return(n=i.call.apply(i,[this].concat(t))||this).getInfoByCode=function(e,t){void 0===t&&(t={}),n._get("/info?code="+e+"&type=code",t)},n.getInfoByAccessToken=function(e,t){void 0===t&&(t={}),t.headers=u({Authorization:"Bearer "+e},t.headers),n._get("/info",t)},n}return(e=n).prototype=Object.create((t=i).prototype),(e.prototype.constructor=e).__proto__=t,n}(function(){function e(e,t,n){var c=this;void 0===t&&(t={}),void 0===n&&(n={}),this._promisify=function(e){if(null==e.success&&null==e.error)return new Promise(function(n,o){e.success=function(e,t){n({data:e,statusCode:t})},e.error=function(e,t){o({data:e,statusCode:t})}})},this._URL=function(e){return"function"==typeof c.endpoint?c.endpoint()+e:c.endpoint+e},this._finalOptions=function(n,o,i,s){var r,a,e=JSON.stringify(o),t=u({},i);return t.postData=e,t.headers=u(t.headers||{},c.headers),t.success&&(t.success=(r=t.success,function(t,e){try{t=JSON.parse(t)}catch(e){t={}}r(t,e)})),t.error&&(t.error=(a=t.error,function(t,e){try{t=JSON.parse(t)}catch(e){t={}}if("wrong region"===t.error)return c.options.onIncorrectRegion&&c.options.onIncorrectRegion(t.region),void c[s](n,o,i);a(t,e)})),t},this._get=function(e,t){o.get(c._URL(e),c._finalOptions(e,{},t,"_get"))},this._post=function(e,t,n){o.submit(c._URL(e),c._finalOptions(e,t,n,"_post"))},this._put=function(e,t,n){n.method="PUT",o.submit(c._URL(e),c._finalOptions(e,t,n,"_put"))},this._setDefaults=function(e){return(e=e||{}).headers=e.headers||{},e},this.endpoint=e,this.headers=t,this.options=n}return e.prototype.setEndpoint=function(e){this.endpoint=e},e}()))("https://accounts.livechatinc.com"),t=new(function(){function e(){}var t=e.prototype;return t.set=function(e,t,n){void 0===n&&(n=null);var o={value:t,expires_in:(new Date).getTime()+1e3*n};try{localStorage.setItem(e,JSON.stringify(o))}catch(e){}},t.get=function(e){var t;try{t=JSON.parse(localStorage.getItem(e))}catch(e){return null}if(null!==t){if(null===t.expires_in||t.expires_in>=(new Date).getTime())return t.value;localStorage.removeItem(e)}return null},t.remove=function(e){try{localStorage.removeItem(e)}catch(e){}},e}());function r(t){return 0===Object.keys(t).length?"":"?"+Object.keys(t).map(function(e){return encodeURIComponent(e)+"="+encodeURIComponent(t[e])}).join("&")}var n={"popup-window-name":"livechat-login-popup","console-url":"https://developers.livechatinc.com/console/","login-button-class":"livechat-login-button","cache-prefix":"livechat_cache","text-button-product-name":"Live<span>Chat</span>"},c=function(e){return n[e]},d="https://accounts.livechatinc.com",a=function(e){var a=this;this._options={client_id:null,response_type:"token",linkLabel:null,onIdentityFetched:function(){},onSignedOut:function(){},queryStringParams:{utm_source:"accounts.livechatinc.com",utm_medium:"accounts-sdk"},popupRoute:""},this._postMessageUniqueId=null,this._listenerInited=!1,this._messageReceived=!1,this._lastIdentityError=null,this._lastIdentityData=null,this.updateOptions=function(e){a._options=u(a._options,e),e.backendAddress&&(d=e.backendAddress),s.setEndpoint(d)},this.openPopup=function(e){e&&e.preventDefault&&e.preventDefault();var t=screen.width/2-250,n=screen.height/2-325,o=a._getCurrentPath();a._startListening(),window.open(d+"/"+a._options.popupRoute+r(i({client_id:a._options.client_id,state:a._postMessageUniqueId,response_type:a._options.response_type,redirect_uri:o,flow:"button"},a._options.queryStringParams)),c("popup-window-name"),"resizable,scrollbars,width=500,height=650,left="+t+",top="+n)},this.signOut=function(e){return"function"==typeof e&&(a._options.onSignedOut=e),a._buildIframe("signout")},this.displayButtons=function(e){if(!0!==(e=e||{}).internalCall&&a._lastIdentityError&&"invalid_request"===a._lastIdentityError.oauth_exception)return a._displayError(["Button could not be displayed. Probably you are running this script on a domain that is not whitelisted in your app's settings.","Visit developers console to update your app's domain list: "+c("console-url")]),!1;var t=document.getElementsByClassName(c("login-button-class"));if(0<t.length){var n=document.createElement("link");n.id=c("login-button-class")+"-font",n.rel="stylesheet",n.href="//fonts.googleapis.com/css?family=Lato:300,400,700,900",document.head.appendChild(n),document.head.insertAdjacentHTML("beforeend","<style>."+c("login-button-class")+' a {color: #5a6976;display: inline-block;font-size: 16px;line-height: 1.5;font-family: "Lato", sans-serif;font-weight: 400;text-decoration: none;border: 1px solid #ddd;border-radius: 3px;padding: 8px 24px 9px}.'+c("login-button-class")+" a:hover {border-color: #888;color: #5a6976}."+c("login-button-class")+" span {color: #f56e21</style>");for(var o=0,i=t.length;o<i;o++){var s=t[o];if("1"!==s.getAttribute("data-inited")){s.setAttribute("data-inited","1");var r=document.createElement("a");r.href="",r.onclick=a.openPopup,a._options.linkLabel?r.text=a._options.linkLabel:r.innerHTML="Sign in with <strong>"+c("text-button-product-name")+"</strong>",s.appendChild(r)}}}},this._displayError=function(e){if(!window.console||!window.console.warn)return!1;e instanceof Array||(e=[e]),e.forEach(function(e){return window.console.warn("[accountsSdk] "+e)})},this._returnSuccessResponse=function(t,n){void 0===n&&(n={});var o={};t.code?(o.code=t.code,s.getInfoByCode(t.code,{success:function(e){o.client_id=e.client_id,o.entity_id=e.entity_id,o.license=e.license_id,o.expires_in=e.expires_in,o.scopes=e.scope?e.scope.split(","):[],a._onIdentityFetched(null,o)},error:function(e){n.fromIframeCache?(a._removeCachedData(),a._buildIframe()):a._onIdentityFetched(e,null)}})):(o.access_token=t.access_token,s.getInfoByAccessToken(t.access_token,{success:function(e){o.client_id=e.client_id,o.entity_id=e.entity_id,o.license=e.license_id,o.expires_in=e.expires_in,o.scopes=e.scope?e.scope.split(","):[],a._onIdentityFetched(null,o),a._cacheData({access_token:t.access_token,expires_in:e.expires_in})},error:function(e){n.fromIframeCache?(a._removeCachedData(),a._buildIframe()):a._onIdentityFetched(e,null)}}))},this._removeIframe=function(){var e=document.getElementById(a._getIframeId());e&&e.parentNode&&e.parentNode.removeChild(e),a._stopListening()},this._receiveMessage=function(e){e.origin===d&&e.data&&e.data.state&&e.data.state===a._postMessageUniqueId&&(a._messageReceived=!0,a._removeIframe(),e.data.error?a._parseError(e.data.error):!0===e.data.signed_out?a._options.onSignedOut():e.data.data&&a._returnSuccessResponse(e.data.data))},this._parseError=function(e){a._onIdentityFetched(e,null),a._lastIdentityError&&("invalid_request"===a._lastIdentityError.oauth_exception?a._displayError(["Authorization process returned 'invalid_request' error.","Probably you are running this script on a domain that is not whitelisted in your app's settings.","Visit developers console to update your app's domain list: "+c("console-url")]):"access_denied"===a._lastIdentityError.oauth_exception?a._displayError(["Authorization process returned 'access_denied' error.","Probably this application is installed on a different account and you do not have access to it."]):"invalid_request"===a._lastIdentityError.identity_exception&&a._displayError(["Authentication process returned 'invalid_request' error.","You may be loading accountsSdk on a domain that is not whitelisted."]))},this._onIdentityFetched=function(e,t){a._lastIdentityError=e,a._lastIdentityData=t,a.displayButtons({internalCall:!0}),a._options.onIdentityFetched(e,t)},this._buildIframe=function(e){void 0===e&&(e=""),a._startListening();var t=document.createElement("iframe");t.setAttribute("src",d+"/"+e+r(i({client_id:a._options.client_id,state:a._postMessageUniqueId,response_type:a._options.response_type,redirect_uri:a._getCurrentPath(),flow:"button"},a._options.queryStringParams))),t.setAttribute("id",a._getIframeId()),t.style.width="1px",t.style.height="1px",t.style.position="fixed",t.style.top="0",t.style.right="0",t.style.opacity="0",t.style.visibility="none",document.body.appendChild(t)},this._getCurrentPath=function(){return window.location.protocol+"//"+window.location.hostname+(window.location.port?":"+window.location.port:"")+window.location.pathname},this._getCacheKey=function(){return c("cache-prefix")+"."+a._options.client_id+"."+a._options.response_type},this._cacheData=function(e){t.set(a._getCacheKey(),e,e.expires_in)},this._getCachedData=function(){return t.get(a._getCacheKey())},this._removeCachedData=function(){return t.remove(a._getCacheKey())},this._getIframeId=function(){return c("login-button-class")+"-iframe."+a._options.client_id+"."+a._options.response_type},this._startListening=function(){if(a._listenerInited)return!1;a._listenerInited=!0,a._messageReceived=!1,window.addEventListener("message",a._receiveMessage,!1)},this._stopListening=function(){a._listenerInited=!1,window.removeEventListener("message",a._receiveMessage,!1)},this.initSDK=function(){if(!a._options.client_id)return window.console&&window.console.warn&&console.warn('[accountsSdk] Required "client_id" param is missing in init() method.'),!1;var e=a._getCachedData();e?a._returnSuccessResponse(e,{fromIframeCache:!0}):(a._buildIframe(),setTimeout(function(){a._messageReceived||a._parseError({identity_exception:"invalid_request"})},5e3))},this._postMessageUniqueId=Math.random().toString(36).substr(2,9),this.updateOptions(e)};return{init:function(e){var t=new a(e);return t.initSDK(),t}}}); |
{ | ||
"name": "@livechat/accounts-sdk", | ||
"version": "1.3.0", | ||
"description": | ||
"SDK for 'Sign in with LiveChat'. Read more here: https://developers.livechatinc.com/docs/sign-in-with-livechat/", | ||
"version": "1.3.1", | ||
"description": "SDK for 'Sign in with LiveChat'. Read more here: https://developers.livechatinc.com/docs/sign-in-with-livechat/", | ||
"main": "./dist/index.cjs.js", | ||
@@ -11,3 +10,5 @@ "module": "./dist/index.esm.js", | ||
"license": "MIT", | ||
"files": ["dist"], | ||
"files": [ | ||
"dist" | ||
], | ||
"types": "./dist/index.d.ts", | ||
@@ -18,17 +19,15 @@ "scripts": { | ||
"prebuild": "rimraf dist && mkdir dist", | ||
"build": | ||
"cp src/index.d.ts dist/ && rollup -c && cp dist/index.js dist/accounts-sdk.min.js" | ||
"build": "cp src/index.d.ts dist/ && rollup -c && cp dist/index.js dist/accounts-sdk.min.js" | ||
}, | ||
"devDependencies": { | ||
"babel-core": "^6.26.3", | ||
"babel-plugin-external-helpers": "^6.22.0", | ||
"babel-preset-es2015": "^6.24.1", | ||
"babel-preset-stage-0": "^6.24.1", | ||
"@babel/core": "^7.4.4", | ||
"@babel/plugin-proposal-class-properties": "^7.4.4", | ||
"@babel/preset-env": "^7.4.4", | ||
"rimraf": "^2.6.2", | ||
"rollup": "^0.66.4", | ||
"rollup-plugin-babel": "^3.0.7", | ||
"rollup": "^1.12.3", | ||
"rollup-plugin-babel": "^4.3.2", | ||
"rollup-plugin-legacy": "^1.0.0", | ||
"rollup-plugin-replace": "^2.1.0", | ||
"rollup-plugin-replace": "^2.2.0", | ||
"rollup-plugin-uglify": "^6.0.0" | ||
} | ||
} |
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
New author
Supply chain riskA new npm collaborator published a version of the package for the first time. New collaborators are usually benign additions to a project, but do indicate a change to the security surface area of a package.
Found 1 instance in 1 package
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
9
64473
1217
1