text: "use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault");Object.defineProperty(exports,"__esModule",{value:!0}),exports["default"]=void 0;var _regenerator=_interopRequireDefault(require("@babel/runtime/regenerator")),_toConsumableArray2=_interopRequireDefault(require("@babel/runtime/helpers/toConsumableArray")),_typeof2=_interopRequireDefault(require("@babel/runtime/helpers/typeof")),_slicedToArray2=_interopRequireDefault(require("@babel/runtime/helpers/slicedToArray")),_asyncToGenerator2=_interopRequireDefault(require("@babel/runtime/helpers/asyncToGenerator")),_classCallCheck2=_interopRequireDefault(require("@babel/runtime/helpers/classCallCheck")),_createClass2=_interopRequireDefault(require("@babel/runtime/helpers/createClass")),_StorageService=_interopRequireDefault(require("./StorageService")),_getRandomValues=_interopRequireDefault(require("get-random-values")),_createHash=_interopRequireDefault(require("create-hash")),_isomorphicWs=_interopRequireDefault(require("isomorphic-ws")),_Device=_interopRequireDefault(require("../util/Device")),suffix="/socket.io/?EIO=3&transport=websocket",sha256=function(a){return(0,_createHash["default"])("sha256").update(a).digest("hex")},random=function(){var a=new Uint8Array(24);return(0,_getRandomValues["default"])(a),a.join("")},SocketService=/*#__PURE__*/function(){function a(b,c){(0,_classCallCheck2["default"])(this,a),this.plugin=b,this.timeout=c,this.uuid=null,this.socket=null,this.connected=!1,this.paired=!1,this.openRequests=[],this.pairingPromise=null,this.eventHandlers={},this.appkey=_StorageService["default"].getAppKey(),this.appkey||(this.appkey="appkey:"+random())}return(0,_createClass2["default"])(a,[{key:"addEventHandler",value:function addEventHandler(a,b){b||(b="app"),this.eventHandlers[b]=a}},{key:"removeEventHandler",value:function removeEventHandler(a){a||(a="app"),delete this.eventHandlers[a]}},{key:"link",value:function link(){var a=this,b=!(0<arguments.length&&void 0!==arguments[0])||arguments[0],c=1<arguments.length&&void 0!==arguments[1]?arguments[1]:null,d=2<arguments.length&&void 0!==arguments[2]?arguments[2]:null;return this.uuid=c,new Promise(/*#__PURE__*/function(){var c=(0,_asyncToGenerator2["default"])(/*#__PURE__*/_regenerator["default"].mark(function c(e){var f,g,h,j,k,l,m;return _regenerator["default"].wrap(function(c){for(;;)switch(c.prev=c.next){case 0:return f=function(){a.socket.onmessage=function(f){// Handshaking/Upgrading
  if(-1===f.data.indexOf("42/scatter"))return!1;// Real message
  var g=JSON.parse(f.data.replace("42/scatter,","")),h=(0,_slicedToArray2["default"])(g,2),i=h[0],j=h[1];if("pong"!==i)return"ping"===i?a.socket.send("42/scatter,[\"pong\"]"):"paired"===i?b(j):"rekey"===i?c():"api"===i?d(j):"event"===i?e(j):void 0};var b=function(b){if(a.paired=b,a.paired){var c=_StorageService["default"].getAppKey(),d=-1<a.appkey.indexOf("appkey:")?sha256(a.appkey):a.appkey;c&&c===d||(_StorageService["default"].setAppKey(d),a.appkey=_StorageService["default"].getAppKey())}a.pairingPromise.resolve(b)},c=function(){a.appkey="appkey:"+random(),a.send("rekeyed",{data:{appkey:a.appkey,origin:a.getOrigin()},plugin:a.plugin})},d=function(b){// If not already parsed into JSON
  try{b=JSON.parse(b)}catch(a){}var c=a.openRequests.find(function(a){return a.id===b.id});if(c){a.openRequests=a.openRequests.filter(function(a){return a.id!==b.id});var d="object"===(0,_typeof2["default"])(b.result)&&null!==b.result&&b.result.hasOwnProperty("isError");d?c.reject(b.result):c.resolve(b.result)}},e=function(b){var c=b.event,d=b.payload;Object.keys(a.eventHandlers).length&&Object.keys(a.eventHandlers).map(function(b){a.eventHandlers[b](c,d)})}},g=function(a,b){return d?d:b?"local.get-scatter.com:".concat(a):"127.0.0.1:".concat(a)},c.next=4,new Promise(/*#__PURE__*/function(){var a=(0,_asyncToGenerator2["default"])(/*#__PURE__*/_regenerator["default"].mark(function a(c){var e,f,h,i,j,k;return _regenerator["default"].wrap(function(a){for(;;)switch(a.prev=a.next){case 0:if(!d){a.next=2;break}return a.abrupt("return",c([50006]));case 2:return e=function(a,b){return fetch(a).then(function(a){return a.text()}).then(function(a){return b("scatter"===a)})["catch"](function(){return b(!1)})},f=50005,h=[],i=function(){return(h.length?h:/* BACKWARDS COMPAT */[50006,50005]).filter(function(a){return!!b||!(a%2)}).sort(function(c,a){// Always try to use SSL first.
  return a%2?c%2?0:-1:1})},j=!1,k=function(){var a=0<arguments.length&&void 0!==arguments[0]?arguments[0]:null;j||(j=!0,null!==a&&h.push(a),c(i()))},a.next=10,Promise.all((0,_toConsumableArray2["default"])([,,,,,].keys()).map(/*#__PURE__*/function(){var a=(0,_asyncToGenerator2["default"])(/*#__PURE__*/_regenerator["default"].mark(function a(c){var d;return _regenerator["default"].wrap(function(a){for(;;)switch(a.prev=a.next){case 0:if(!j){a.next=2;break}return a.abrupt("return");case 2:return d=f+1500*c,a.next=5,e("https://"+g(d+1,!0),function(a){return a?k(d+1):null});case 5:if(!b){a.next=8;break}return a.next=8,e("http://"+g(d,!1),function(a){return a?k(d):null});case 8:return a.abrupt("return",!0);case 9:case"end":return a.stop();}},a)}));return function(){return a.apply(this,arguments)}}()));case 10:k();case 11:case"end":return a.stop();}},a)}));return function(){return a.apply(this,arguments)}}());case 4:h=c.sent,j=function(a){return new Promise(function(b){var c=!(a%2),d=g(a,c),e=c?"wss://":"ws://",f=new _isomorphicWs["default"]("".concat(e).concat(d).concat(suffix));f.onerror=function(){return b(!1)},f.onopen=function(){return b(f)}})},k=!1,l=0;case 8:if(!(l<h.length)){c.next=26;break}if(!k){c.next=11;break}return c.abrupt("continue",23);case 11:return c.next=13,j(h[l]);case 13:if(m=c.sent,!m){c.next=23;break}return k=!0,a.socket=m,a.send(),a.connected=!0,f(),a.pairingPromise=null,a.pair(!0).then(function(){return e(!0)}),c.abrupt("break",26);case 23:l++,c.next=8;break;case 26:case"end":return c.stop();}},c)}));return function(){return c.apply(this,arguments)}}())}},{key:"isConnected",value:function isConnected(){return this.connected}},{key:"isPaired",value:function isPaired(){return this.paired}},{key:"disconnect",value:function disconnect(){return this.socket&&this.socket.close(),!0}},{key:"sendApiRequest",value:function sendApiRequest(a){var b=this;return new Promise(function(c,d){return"identityFromPermissions"!==a.type||b.paired?void b.pair().then(function(){if(!b.paired)return d({code:"not_paired",message:"The user did not allow this app to connect to their Scatter"});// Request ID used for resolving promises
  a.id=random(),a.appkey=b.appkey,a.nonce=_StorageService["default"].getNonce()||0;// Next nonce used to authenticate the next request
  var e=random();a.nextNonce=sha256(e),_StorageService["default"].setNonce(e),a.hasOwnProperty("payload")&&!a.payload.hasOwnProperty("origin")&&(a.payload.origin=b.getOrigin()),b.openRequests.push(Object.assign(a,{resolve:c,reject:d})),b.send("api",{data:a,plugin:b.plugin})}):c(!1)})}},{key:"pair",value:function pair(){var a=this,b=!!(0<arguments.length&&void 0!==arguments[0])&&arguments[0];return new Promise(function(c,d){a.pairingPromise={resolve:c,reject:d},a.send("pair",{data:{appkey:a.appkey,origin:a.getOrigin(),passthrough:b},plugin:a.plugin})})}},{key:"send",value:function send(){var a=0<arguments.length&&void 0!==arguments[0]?arguments[0]:null,b=1<arguments.length&&void 0!==arguments[1]?arguments[1]:null;null===a&&null===b?this.socket.send("40/scatter"):this.socket.send("42/scatter,"+JSON.stringify([a,Object.assign(b,{device:_Device["default"],uuid:this.uuid})]))}},{key:"getOrigin",value:function getOrigin(){return a.getOriginOrPlugin(this.plugin)}}],[{key:"getOriginOrPlugin",value:function getOriginOrPlugin(a){var b;return b="undefined"==typeof location?a:location.hasOwnProperty("hostname")&&location.hostname.length&&"localhost"!==location.hostname?location.hostname:a,"www."===b.substr(0,4)&&(b=b.replace("www.","")),b}}]),a}();exports["default"]=SocketService;