home-assistant-js-websocket
Advanced tools
Comparing version 3.3.0 to 3.4.0
@@ -1,2 +0,2 @@ | ||
function e(e,t,n,r){return new(n||(n=Promise))(function(s,i){function o(e){try{a(r.next(e))}catch(e){i(e)}}function c(e){try{a(r.throw(e))}catch(e){i(e)}}function a(e){e.done?s(e.value):new n(function(t){t(e.value)}).then(o,c)}a((r=r.apply(e,t||[])).next())})}function t(e,t){var n,r,s,i,o={label:0,sent:function(){if(1&s[0])throw s[1];return s[1]},trys:[],ops:[]};return i={next:c(0),throw:c(1),return:c(2)},"function"==typeof Symbol&&(i[Symbol.iterator]=function(){return this}),i;function c(i){return function(c){return function(i){if(n)throw new TypeError("Generator is already executing.");for(;o;)try{if(n=1,r&&(s=2&i[0]?r.return:i[0]?r.throw||((s=r.return)&&s.call(r),0):r.next)&&!(s=s.call(r,i[1])).done)return s;switch(r=0,s&&(i=[2&i[0],s.value]),i[0]){case 0:case 1:s=i;break;case 4:return o.label++,{value:i[1],done:!1};case 5:o.label++,r=i[1],i=[0];continue;case 7:i=o.ops.pop(),o.trys.pop();continue;default:if(!(s=(s=o.trys).length>0&&s[s.length-1])&&(6===i[0]||2===i[0])){o=0;continue}if(3===i[0]&&(!s||i[1]>s[0]&&i[1]<s[3])){o.label=i[1];break}if(6===i[0]&&o.label<s[1]){o.label=s[1],s=i;break}if(s&&o.label<s[2]){o.label=s[2],o.ops.push(i);break}s[2]&&o.ops.pop(),o.trys.pop();continue}i=t.call(e,o)}catch(e){i=[6,e],r=0}finally{n=s=0}if(5&i[0])throw i[1];return{value:i[0]?i[1]:void 0,done:!0}}([i,c])}}}var n=1,r=2,s=3,i=4;var o="auth_invalid",c="auth_ok";var a=function(){function n(e,t){this.options=t,this.commandId=1,this.commands={},this.eventListeners={},this.closeRequested=!1,this.setSocket(e)}return n.prototype.setSocket=function(e){var t=this,n=this.socket;if(this.socket=e,e.addEventListener("message",function(e){return t._handleMessage(e)}),e.addEventListener("close",function(e){return t._handleClose(e)}),n){var r=this.commands;this.commandId=1,this.commands={},Object.keys(r).forEach(function(e){var t=r[e];"subscribe"in t&&t.subscribe().then(function(e){t.unsubscribe=e,t.resolve()})}),this.fireEvent("ready")}},n.prototype.addEventListener=function(e,t){var n=this.eventListeners[e];n||(n=this.eventListeners[e]=[]),n.push(t)},n.prototype.removeEventListener=function(e,t){var n=this.eventListeners[e];if(n){var r=n.indexOf(t);-1!==r&&n.splice(r,1)}},n.prototype.fireEvent=function(e,t){var n=this;(this.eventListeners[e]||[]).forEach(function(e){return e(n,t)})},n.prototype.close=function(){this.closeRequested=!0,this.socket.close()},n.prototype.subscribeEvents=function(n,r){return e(this,void 0,void 0,function(){return t(this,function(e){return[2,this.subscribeMessage(n,function(e){var t={type:"subscribe_events"};return e&&(t.event_type=e),t}(r))]})})},n.prototype.ping=function(){return this.sendMessagePromise({type:"ping"})},n.prototype.sendMessage=function(e,t){t||(t=this._genCmdId()),e.id=t,this.socket.send(JSON.stringify(e))},n.prototype.sendMessagePromise=function(e){var t=this;return new Promise(function(n,r){var s=t._genCmdId();t.commands[s]={resolve:n,reject:r},t.sendMessage(e,s)})},n.prototype.subscribeMessage=function(n,r){return e(this,void 0,void 0,function(){var s,i,o=this;return t(this,function(c){switch(c.label){case 0:return s=this._genCmdId(),[4,new Promise(function(c,a){i=o.commands[s]={resolve:c,reject:a,callback:n,subscribe:function(){return o.subscribeMessage(n,r)},unsubscribe:function(){return e(o,void 0,void 0,function(){return t(this,function(e){switch(e.label){case 0:return[4,this.sendMessagePromise((t=s,{type:"unsubscribe_events",subscription:t}))];case 1:return e.sent(),delete this.commands[s],[2]}var t})})}};try{o.sendMessage(r,s)}catch(e){}})];case 1:return c.sent(),[2,function(){return i.unsubscribe()}]}})})},n.prototype._handleMessage=function(e){var t=JSON.parse(e.data);switch(t.type){case"event":this.commands[t.id].callback(t.event);break;case"result":if(t.id in this.commands){var n=this.commands[t.id];t.success?(n.resolve(t.result),"subscribe"in n||delete this.commands[t.id]):(n.reject(t.error),delete this.commands[t.id])}break;case"pong":this.commands[t.id].resolve(),delete this.commands[t.id]}},n.prototype._handleClose=function(n){var s=this;if(Object.keys(this.commands).forEach(function(e){var t=s.commands[e];"subscribe"in t||t.reject({type:"result",success:!1,error:{code:3,message:"Connection lost"}})}),!this.closeRequested){this.fireEvent("disconnected");var i=Object.assign({},this.options,{setupRetry:0}),o=function(n){setTimeout(function(){return e(s,void 0,void 0,function(){var e,s;return t(this,function(t){switch(t.label){case 0:t.label=1;case 1:return t.trys.push([1,3,,4]),[4,i.createSocket(i)];case 2:return e=t.sent(),this.setSocket(e),[3,4];case 3:return(s=t.sent())===r?this.fireEvent("reconnect-error",s):o(n+1),[3,4];case 4:return[2]}})})},1e3*Math.min(n,5))};o(0)}},n.prototype._genCmdId=function(){return++this.commandId},n}();var u=function(){return location.protocol+"//"+location.host+"/"},f=function(e){return 1e3*e+Date.now()};function d(e,t,n,r){n+=(n.includes("?")?"&":"?")+"auth_callback=1",document.location.href=function(e,t,n,r){var s=e+"/auth/authorize?response_type=code&client_id="+encodeURIComponent(t)+"&redirect_uri="+encodeURIComponent(n);return r&&(s+="&state="+encodeURIComponent(r)),s}(e,t,n,r)}function h(n,s,i){return e(this,void 0,void 0,function(){var e,o,c;return t(this,function(t){switch(t.label){case 0:return(e=new FormData).append("client_id",s),Object.keys(i).forEach(function(t){e.append(t,i[t])}),[4,fetch(n+"/auth/token",{method:"POST",credentials:"same-origin",body:e})];case 1:if(!(o=t.sent()).ok)throw 400===o.status||403===o.status?r:new Error("Unable to fetch tokens");return[4,o.json()];case 2:return(c=t.sent()).hassUrl=n,c.clientId=s,c.expires=f(c.expires_in),[2,c]}})})}var l=function(){function n(e,t){this.data=e,this._saveTokens=t}return Object.defineProperty(n.prototype,"wsUrl",{get:function(){return"ws"+this.data.hassUrl.substr(4)+"/api/websocket"},enumerable:!0,configurable:!0}),Object.defineProperty(n.prototype,"accessToken",{get:function(){return this.data.access_token},enumerable:!0,configurable:!0}),Object.defineProperty(n.prototype,"expired",{get:function(){return Date.now()>this.data.expires},enumerable:!0,configurable:!0}),n.prototype.refreshAccessToken=function(){return e(this,void 0,void 0,function(){var e;return t(this,function(t){switch(t.label){case 0:return[4,h(this.data.hassUrl,this.data.clientId,{grant_type:"refresh_token",refresh_token:this.data.refresh_token})];case 1:return(e=t.sent()).refresh_token=this.data.refresh_token,this.data=e,this._saveTokens&&this._saveTokens(e),[2]}})})},n.prototype.revoke=function(){return e(this,void 0,void 0,function(){var e;return t(this,function(t){switch(t.label){case 0:return(e=new FormData).append("action","revoke"),e.append("token",this.data.refresh_token),[4,fetch(this.data.hassUrl+"/auth/token",{method:"POST",credentials:"same-origin",body:e})];case 1:return t.sent(),this._saveTokens&&this._saveTokens(null),[2]}})})},n}();function v(n){return void 0===n&&(n={}),e(this,void 0,void 0,function(){var e,r,s,o,c,a,f;return t(this,function(t){switch(t.label){case 0:if(!("auth_callback"in(r=function(e){for(var t={},n=e.split("&"),r=0;r<n.length;r++){var s=n[r].split("="),i=decodeURIComponent(s[0]),o=s.length>1?decodeURIComponent(s[1]):void 0;t[i]=o}return t}(location.search.substr(1)))))return[3,4];s=JSON.parse(atob(r.state)),t.label=1;case 1:return t.trys.push([1,3,,4]),[4,function(e,t,n){return h(e,t,{code:n,grant_type:"authorization_code"})}(s.hassUrl,s.clientId,r.code)];case 2:return e=t.sent(),n.saveTokens&&n.saveTokens(e),[3,4];case 3:return o=t.sent(),console.log("Unable to fetch access token",o),[3,4];case 4:return e||!n.loadTokens?[3,6]:[4,n.loadTokens()];case 5:e=t.sent(),t.label=6;case 6:if(e)return[2,new l(e,n.saveTokens)];if(void 0===(c=n.hassUrl))throw i;return"/"===c[c.length-1]&&(c=c.substr(0,c.length-1)),a=n.clientId||u(),f=n.redirectUrl||location.protocol+"//"+location.host+location.pathname+location.search,d(c,a,f,function(e){return btoa(JSON.stringify(e))}({hassUrl:c,clientId:a})),[2,new Promise(function(){})]}})})}var p=function(e){var t=[];function n(n,r){e=r?n:Object.assign({},e,n);for(var s=t,i=0;i<s.length;i++)s[i](e)}return{get state(){return e},action:function(t){function r(e){n(e,!1)}return function(){for(var n=[e],s=0;s<arguments.length;s++)n.push(arguments[s]);var i=t.apply(this,n);if(null!=i)return i.then?i.then(r):r(i)}},setState:n,subscribe:function(e){return t.push(e),function(){!function(e){for(var n=[],r=0;r<t.length;r++)t[r]===e?e=null:n.push(t[r]);t=n}(e)}}}},b=function(e,t,n,r){if(e[t])return e[t];var s,i=0,o=p(),c=function(){return n(e).then(function(e){return o.setState(e,!0)})};return e[t]={get state(){return o.state},refresh:c,subscribe:function(t){i||(i++,r&&(s=r(e,o)),e.addEventListener("ready",c),c().catch(function(t){if(e.socket.readyState==e.socket.OPEN)throw t}));var n=o.subscribe(t);return void 0!==o.state&&t(o.state),function(){n(),--i||(s&&s.then(function(e){e()}),e.removeEventListener("ready",c))}}},e[t]},m=function(e,t,n,r,s){return b(r,e,t,n).subscribe(s)},y=function(e){return e.sendMessagePromise({type:"get_states"})},g=function(e){return e.sendMessagePromise({type:"get_services"})},k=function(e){return e.sendMessagePromise({type:"get_config"})},_=function(e){return e.sendMessagePromise({type:"auth/current_user"})},w=function(e,t,n,r){return e.sendMessagePromise(function(e,t,n){var r={type:"call_service",domain:e,service:t};return n&&(r.service_data=n),r}(t,n,r))};function E(e,t){return void 0===e?null:{components:e.components.concat(t.data.component)}}var S=function(e){return k(e)},O=function(e,t){return e.subscribeEvents(t.action(E),"component_loaded")},L=function(e,t){return function(e){return b(e,"_cnf",S,O)}(e).subscribe(t)};function P(e,t){var n,r;if(void 0===e)return null;var s=t.data,i=s.domain,o=Object.assign({},e[i],((n={})[s.service]={description:"",fields:{}},n));return(r={})[i]=o,r}function T(e,t){var n;if(void 0===e)return null;var r=t.data,s=r.domain,i=r.service,o=e[s];if(!(o&&i in o))return null;var c={};return Object.keys(o).forEach(function(e){e!==i&&(c[e]=o[e])}),(n={})[s]=c,n}var j=function(e){return g(e)},I=function(e,t){return Promise.all([e.subscribeEvents(t.action(P),"service_registered"),e.subscribeEvents(t.action(T),"service_removed")]).then(function(e){return function(){return e.forEach(function(e){return e()})}})},M=function(e,t){return function(e){return b(e,"_srv",j,I)}(e).subscribe(t)};function U(n){return e(this,void 0,void 0,function(){var e,r,s,i;return t(this,function(t){switch(t.label){case 0:return[4,y(n)];case 1:for(e=t.sent(),r={},s=0;s<e.length;s++)r[(i=e[s]).entity_id]=i;return[2,r]}})})}var x=function(e,t){return e.subscribeEvents(function(e){return function(e,t){var n,r=e.state;if(void 0!==r){var s=t.data,i=s.entity_id,o=s.new_state;if(o)e.setState(((n={})[o.entity_id]=o,n));else{var c=Object.assign({},r);delete c[i],e.setState(c,!0)}}}(t,e)},"state_changed")},C=function(e){return b(e,"_ent",U,x)},R=function(e,t){return C(e).subscribe(t)},N={setupRetry:0,createSocket:function(s){if(!s.auth)throw i;var a=s.auth,u=a.wsUrl;return new Promise(function(i,f){return function s(i,f,d){var h=this,l=new WebSocket(u),v=!1,p=function(){if(l.removeEventListener("close",p),v)d(r);else if(0!==i){var e=-1===i?-1:i-1;setTimeout(function(){return s(e,f,d)},1e3)}else d(n)},b=function(n){return e(h,void 0,void 0,function(){var e;return t(this,function(t){switch(t.label){case 0:return t.trys.push([0,3,,4]),a.expired?[4,a.refreshAccessToken()]:[3,2];case 1:t.sent(),t.label=2;case 2:return l.send(JSON.stringify({type:"auth",access_token:a.accessToken})),[3,4];case 3:return e=t.sent(),v=e===r,l.close(),[3,4];case 4:return[2]}})})},m=function(n){return e(h,void 0,void 0,function(){return t(this,function(e){switch(JSON.parse(n.data).type){case o:v=!0,l.close();break;case c:l.removeEventListener("open",b),l.removeEventListener("message",m),l.removeEventListener("close",p),l.removeEventListener("error",p),f(l)}return[2]})})};l.addEventListener("open",b),l.addEventListener("message",m),l.addEventListener("close",p),l.addEventListener("error",p)}(s.setupRetry,i,f)})}};function J(n){return e(this,void 0,void 0,function(){var e,r;return t(this,function(t){switch(t.label){case 0:return[4,(e=Object.assign({},N,n)).createSocket(e)];case 1:return r=t.sent(),[2,new a(r,e)]}})})}export{J as createConnection,u as genClientId,f as genExpires,l as Auth,v as getAuth,b as getCollection,m as createCollection,a as Connection,L as subscribeConfig,M as subscribeServices,C as entitiesColl,R as subscribeEntities,n as ERR_CANNOT_CONNECT,r as ERR_INVALID_AUTH,s as ERR_CONNECTION_LOST,i as ERR_HASS_HOST_REQUIRED,y as getStates,g as getServices,k as getConfig,_ as getUser,w as callService}; | ||
const e=function(){function e(){}return e.prototype.then=function(n,r){const o=new e,s=this.s;if(s){const e=1&s?n:r;if(e){try{t(o,1,e(this.v))}catch(e){t(o,2,e)}return o}return this}return this.o=function(e){try{const s=e.v;1&e.s?t(o,1,n?n(s):s):r?t(o,1,r(s)):t(o,2,s)}catch(e){t(o,2,e)}},o},e}();function t(n,r,o){if(!n.s){if(o instanceof e){if(!o.s)return void(o.o=t.bind(null,n,r));1&r&&(r=o.s),o=o.v}if(o&&o.then)return void o.then(t.bind(null,n,r),t.bind(null,n,2));n.s=r,n.v=o;const s=n.o;s&&s(n)}}function n(e,t){try{var n=e()}catch(e){return t(e)}return n&&n.then?n.then(void 0,t):n}const r={};!function(){function n(e){this._entry=e,this._pact=null,this._resolve=null,this._return=null,this._promise=null}function o(e){return{value:e,done:!0}}function s(e){return{value:e,done:!1}}n.prototype[Symbol.asyncIterator||(Symbol.asyncIterator=Symbol("Symbol.asyncIterator"))]=function(){return this},n.prototype._yield=function(t){return this._resolve(t&&t.then?t.then(s):s(t)),this._pact=new e},n.prototype.next=function(n){const s=this;return s._promise=new Promise(function(i){const c=s._pact;if(null===c){const t=s._entry;if(null===t)return i(s._promise);function u(e){s._resolve(e&&e.then?e.then(o):o(e)),s._pact=null,s._resolve=null}s._entry=null,s._resolve=i,t(s).then(u,function(t){if(t===r)u(s._return);else{const n=new e;s._resolve(n),s._pact=null,s._resolve=null,_resolve(n,2,t)}})}else s._pact=null,s._resolve=i,t(c,1,n)})},n.prototype.return=function(e){const n=this;return n._promise=new Promise(function(s){const i=n._pact;if(null===i)return null===n._entry?s(n._promise):(n._entry=null,s(e&&e.then?e.then(o):o(e)));n._return=e,n._resolve=s,n._pact=null,t(i,2,r)})},n.prototype.throw=function(e){const n=this;return n._promise=new Promise(function(r,o){const s=n._pact;if(null===s)return null===n._entry?r(n._promise):(n._entry=null,o(e));n._resolve=r,n._pact=null,t(s,2,e)})}}();var o=1,s=2,i=3,c=4,u=function(e,t){this.options=t,this.commandId=1,this.commands={},this.eventListeners={},this.closeRequested=!1,this.setSocket(e)};u.prototype.setSocket=function(e){var t=this,n=this.socket;if(this.socket=e,e.addEventListener("message",function(e){return t._handleMessage(e)}),e.addEventListener("close",function(e){return t._handleClose(e)}),n){var r=this.commands;this.commandId=1,this.commands={},Object.keys(r).forEach(function(e){var t=r[e];"subscribe"in t&&t.subscribe().then(function(e){t.unsubscribe=e,t.resolve()})}),this.fireEvent("ready")}},u.prototype.addEventListener=function(e,t){var n=this.eventListeners[e];n||(n=this.eventListeners[e]=[]),n.push(t)},u.prototype.removeEventListener=function(e,t){var n=this.eventListeners[e];if(n){var r=n.indexOf(t);-1!==r&&n.splice(r,1)}},u.prototype.fireEvent=function(e,t){var n=this;(this.eventListeners[e]||[]).forEach(function(e){return e(n,t)})},u.prototype.close=function(){this.closeRequested=!0,this.socket.close()},u.prototype.subscribeEvents=function(e,t){try{return this.subscribeMessage(e,function(e){var t={type:"subscribe_events"};return e&&(t.event_type=e),t}(t))}catch(e){return Promise.reject(e)}},u.prototype.ping=function(){return this.sendMessagePromise({type:"ping"})},u.prototype.sendMessage=function(e,t){t||(t=this._genCmdId()),e.id=t,this.socket.send(JSON.stringify(e))},u.prototype.sendMessagePromise=function(e){var t=this;return new Promise(function(n,r){var o=t._genCmdId();t.commands[o]={resolve:n,reject:r},t.sendMessage(e,o)})},u.prototype.subscribeMessage=function(e,t){try{var n,r=this,o=r._genCmdId();return Promise.resolve(new Promise(function(s,i){n=r.commands[o]={resolve:s,reject:i,callback:e,subscribe:function(){return r.subscribeMessage(e,t)},unsubscribe:function(){try{return Promise.resolve(r.sendMessagePromise((e=o,{type:"unsubscribe_events",subscription:e}))).then(function(){delete r.commands[o]})}catch(e){return Promise.reject(e)}var e}};try{r.sendMessage(t,o)}catch(e){}})).then(function(){return function(){return n.unsubscribe()}})}catch(e){return Promise.reject(e)}},u.prototype._handleMessage=function(e){var t=JSON.parse(e.data);switch(t.type){case"event":this.commands[t.id].callback(t.event);break;case"result":if(t.id in this.commands){var n=this.commands[t.id];t.success?(n.resolve(t.result),"subscribe"in n||delete this.commands[t.id]):(n.reject(t.error),delete this.commands[t.id])}break;case"pong":this.commands[t.id].resolve(),delete this.commands[t.id]}},u.prototype._handleClose=function(e){var t=this;if(Object.keys(this.commands).forEach(function(e){var n=t.commands[e];"subscribe"in n||n.reject({type:"result",success:!1,error:{code:3,message:"Connection lost"}})}),!this.closeRequested){this.fireEvent("disconnected");var r=Object.assign({},this.options,{setupRetry:0}),o=function(e){var s=t;setTimeout(function(){try{var t=n(function(){return Promise.resolve(r.createSocket(r)).then(function(e){s.setSocket(e)})},function(t){2===t?s.fireEvent("reconnect-error",t):o(e+1)});return Promise.resolve(t&&t.then?t.then(function(){}):void 0)}catch(e){return Promise.reject(e)}},1e3*Math.min(e,5))};o(0)}},u.prototype._genCmdId=function(){return++this.commandId};var a=function(e){void 0===e&&(e={});try{function t(){function t(){if(r)return new d(r,e.saveTokens);var t=e.hassUrl;if(void 0===t)throw c;"/"===t[t.length-1]&&(t=t.substr(0,t.length-1));var n=e.clientId||l();return function(e,t,n,r){n+=(n.includes("?")?"&":"?")+"auth_callback=1",document.location.href=function(e,t,n,r){var o=e+"/auth/authorize?response_type=code&client_id="+encodeURIComponent(t)+"&redirect_uri="+encodeURIComponent(n);return r&&(o+="&state="+encodeURIComponent(r)),o}(e,t,n,r)}(t,n,e.redirectUrl||location.protocol+"//"+location.host+location.pathname+location.search,btoa(JSON.stringify({hassUrl:t,clientId:n}))),new Promise(function(){})}var n=function(){if(!r&&e.loadTokens)return Promise.resolve(e.loadTokens()).then(function(e){r=e})}();return n&&n.then?n.then(t):t()}var r,o=function(e){for(var t={},n=location.search.substr(1).split("&"),r=0;r<n.length;r++){var o=n[r].split("="),s=decodeURIComponent(o[0]),i=o.length>1?decodeURIComponent(o[1]):void 0;t[s]=i}return t}(),s=function(){if("auth_callback"in o){var t=JSON.parse(atob(o.state)),s=n(function(){return Promise.resolve((n=t.hassUrl,s=t.clientId,i=o.code,f(n,s,{code:i,grant_type:"authorization_code"}))).then(function(t){r=t,e.saveTokens&&e.saveTokens(r)});var n,s,i},function(e){console.log("Unable to fetch access token",e)});if(s&&s.then)return s.then(function(){})}}();return Promise.resolve(s&&s.then?s.then(t):t())}catch(e){return Promise.reject(e)}},f=function(e,t,n){try{var r=new FormData;return r.append("client_id",t),Object.keys(n).forEach(function(e){r.append(e,n[e])}),Promise.resolve(fetch(e+"/auth/token",{method:"POST",credentials:"same-origin",body:r})).then(function(n){if(!n.ok)throw 400===n.status||403===n.status?2:new Error("Unable to fetch tokens");return Promise.resolve(n.json()).then(function(n){return n.hassUrl=e,n.clientId=t,n.expires=h(n.expires_in),n})})}catch(e){return Promise.reject(e)}},l=function(){return location.protocol+"//"+location.host+"/"},h=function(e){return 1e3*e+Date.now()},d=function(e,t){this.data=e,this._saveTokens=t},v={wsUrl:{configurable:!0},accessToken:{configurable:!0},expired:{configurable:!0}};v.wsUrl.get=function(){return"ws"+this.data.hassUrl.substr(4)+"/api/websocket"},v.accessToken.get=function(){return this.data.access_token},v.expired.get=function(){return Date.now()>this.data.expires},d.prototype.refreshAccessToken=function(){try{var e=this;return Promise.resolve(f(e.data.hassUrl,e.data.clientId,{grant_type:"refresh_token",refresh_token:e.data.refresh_token})).then(function(t){t.refresh_token=e.data.refresh_token,e.data=t,e._saveTokens&&e._saveTokens(t)})}catch(e){return Promise.reject(e)}},d.prototype.revoke=function(){try{var e=this,t=new FormData;return t.append("action","revoke"),t.append("token",e.data.refresh_token),Promise.resolve(fetch(e.data.hassUrl+"/auth/token",{method:"POST",credentials:"same-origin",body:t})).then(function(){e._saveTokens&&e._saveTokens(null)})}catch(e){return Promise.reject(e)}},Object.defineProperties(d.prototype,v);var p=function(e,t,n,r){if(e[t])return e[t];var o,s=0,i=function(e){var t=[];function n(n,r){e=r?n:Object.assign({},e,n);for(var o=t,s=0;s<o.length;s++)o[s](e)}return{get state(){return e},action:function(t){function r(e){n(e,!1)}return function(){for(var n=arguments,o=[e],s=0;s<arguments.length;s++)o.push(n[s]);var i=t.apply(this,o);if(null!=i)return i.then?i.then(r):r(i)}},setState:n,subscribe:function(e){return t.push(e),function(){!function(e){for(var n=[],r=0;r<t.length;r++)t[r]===e?e=null:n.push(t[r]);t=n}(e)}}}}(),c=function(){return n(e).then(function(e){return i.setState(e,!0)})};return e[t]={get state(){return i.state},refresh:c,subscribe:function(t){s||(s++,r&&(o=r(e,i)),e.addEventListener("ready",c),c().catch(function(t){if(e.socket.readyState==e.socket.OPEN)throw t}));var n=i.subscribe(t);return void 0!==i.state&&t(i.state),function(){n(),--s||(o&&o.then(function(e){e()}),e.removeEventListener("ready",c))}}},e[t]},m=function(e,t,n,r,o){return p(r,e,t,n).subscribe(o)},_=function(e){return e.sendMessagePromise({type:"get_states"})},b=function(e){return e.sendMessagePromise({type:"get_services"})},y=function(e){return e.sendMessagePromise({type:"get_config"})},g=function(e){return e.sendMessagePromise({type:"auth/current_user"})},k=function(e,t,n,r){return e.sendMessagePromise(function(e,t,n){var r={type:"call_service",domain:e,service:t};return n&&(r.service_data=n),r}(t,n,r))};function P(e,t){return void 0===e?null:{components:e.components.concat(t.data.component)}}var E=function(e){return y(e)},w=function(e,t){return e.subscribeEvents(t.action(P),"component_loaded")},j=function(e,t){return function(e){return p(e,"_cnf",E,w)}(e).subscribe(t)};function S(e,t){var n,r;if(void 0===e)return null;var o=t.data,s=o.domain,i=Object.assign({},e[s],((n={})[o.service]={description:"",fields:{}},n));return(r={})[s]=i,r}function I(e,t){var n;if(void 0===e)return null;var r=t.data,o=r.domain,s=r.service,i=e[o];if(!(i&&s in i))return null;var c={};return Object.keys(i).forEach(function(e){e!==s&&(c[e]=i[e])}),(n={})[o]=c,n}var L=function(e){return b(e)},O=function(e,t){return Promise.all([e.subscribeEvents(t.action(S),"service_registered"),e.subscribeEvents(t.action(I),"service_removed")]).then(function(e){return function(){return e.forEach(function(e){return e()})}})},T=function(e,t){return function(e){return p(e,"_srv",L,O)}(e).subscribe(t)},U=function(e){try{return Promise.resolve(_(e)).then(function(e){for(var t={},n=0;n<e.length;n++){var r=e[n];t[r.entity_id]=r}return t})}catch(e){return Promise.reject(e)}},M=function(e,t){return e.subscribeEvents(function(e){return function(t,n){var r,o=t.state;if(void 0!==o){var s=e.data,i=s.entity_id,c=s.new_state;if(c)t.setState(((r={})[c.entity_id]=c,r));else{var u=Object.assign({},o);delete u[i],t.setState(u,!0)}}}(t)},"state_changed")},C=function(e){return p(e,"_ent",U,M)},R=function(e,t){return C(e).subscribe(t)},x=function(e){try{var t=Object.assign({},N,e);return Promise.resolve(t.createSocket(t)).then(function(e){return new u(e,t)})}catch(e){return Promise.reject(e)}},N={setupRetry:0,createSocket:function(e){if(!e.auth)throw c;var t=e.auth,r=e.WebSocket||WebSocket,o=t.expired?t.refreshAccessToken().then(function(){o=void 0},function(){o=void 0}):void 0,s=t.wsUrl;return new Promise(function(i,c){return function e(i,c,u){var a=new r(s),f=!1,l=function(){if(a.removeEventListener("close",l),f)u(2);else if(0!==i){var t=-1===i?-1:i-1;setTimeout(function(){return e(t,c,u)},1e3)}else u(1)},h=function(e){try{var r=n(function(){function e(){a.send(JSON.stringify({type:"auth",access_token:t.accessToken}))}var n=function(){if(t.expired)return Promise.resolve(o||t.refreshAccessToken()).then(function(){})}();return n&&n.then?n.then(e):e()},function(e){f=2===e,a.close()});return Promise.resolve(r&&r.then?r.then(function(){}):void 0)}catch(e){return Promise.reject(e)}},d=function(e){try{switch(JSON.parse(e.data).type){case"auth_invalid":f=!0,a.close();break;case"auth_ok":a.removeEventListener("open",h),a.removeEventListener("message",d),a.removeEventListener("close",l),a.removeEventListener("error",l),c(a)}return}catch(e){return Promise.reject(e)}};a.addEventListener("open",h),a.addEventListener("message",d),a.addEventListener("close",l),a.addEventListener("error",l)}(e.setupRetry,i,c)})}};export{x as createConnection,a as getAuth,l as genClientId,h as genExpires,d as Auth,p as getCollection,m as createCollection,u as Connection,j as subscribeConfig,T as subscribeServices,C as entitiesColl,R as subscribeEntities,o as ERR_CANNOT_CONNECT,s as ERR_INVALID_AUTH,i as ERR_CONNECTION_LOST,c as ERR_HASS_HOST_REQUIRED,_ as getStates,b as getServices,y as getConfig,g as getUser,k as callService}; | ||
//# sourceMappingURL=haws.es.js.map |
@@ -1,2 +0,2 @@ | ||
function e(e,t,n,r){return new(n||(n=Promise))(function(s,o){function i(e){try{a(r.next(e))}catch(e){o(e)}}function c(e){try{a(r.throw(e))}catch(e){o(e)}}function a(e){e.done?s(e.value):new n(function(t){t(e.value)}).then(i,c)}a((r=r.apply(e,t||[])).next())})}function t(e,t){var n,r,s,o,i={label:0,sent:function(){if(1&s[0])throw s[1];return s[1]},trys:[],ops:[]};return o={next:c(0),throw:c(1),return:c(2)},"function"==typeof Symbol&&(o[Symbol.iterator]=function(){return this}),o;function c(o){return function(c){return function(o){if(n)throw new TypeError("Generator is already executing.");for(;i;)try{if(n=1,r&&(s=2&o[0]?r.return:o[0]?r.throw||((s=r.return)&&s.call(r),0):r.next)&&!(s=s.call(r,o[1])).done)return s;switch(r=0,s&&(o=[2&o[0],s.value]),o[0]){case 0:case 1:s=o;break;case 4:return i.label++,{value:o[1],done:!1};case 5:i.label++,r=o[1],o=[0];continue;case 7:o=i.ops.pop(),i.trys.pop();continue;default:if(!(s=(s=i.trys).length>0&&s[s.length-1])&&(6===o[0]||2===o[0])){i=0;continue}if(3===o[0]&&(!s||o[1]>s[0]&&o[1]<s[3])){i.label=o[1];break}if(6===o[0]&&i.label<s[1]){i.label=s[1],s=o;break}if(s&&i.label<s[2]){i.label=s[2],i.ops.push(o);break}s[2]&&i.ops.pop(),i.trys.pop();continue}o=t.call(e,i)}catch(e){o=[6,e],r=0}finally{n=s=0}if(5&o[0])throw o[1];return{value:o[0]?o[1]:void 0,done:!0}}([o,c])}}}var n=1,r=2,s=4;var o="auth_invalid",i="auth_ok";var c=function(){function n(e,t){this.options=t,this.commandId=1,this.commands={},this.eventListeners={},this.closeRequested=!1,this.setSocket(e)}return n.prototype.setSocket=function(e){var t=this,n=this.socket;if(this.socket=e,e.addEventListener("message",function(e){return t._handleMessage(e)}),e.addEventListener("close",function(e){return t._handleClose(e)}),n){var r=this.commands;this.commandId=1,this.commands={},Object.keys(r).forEach(function(e){var t=r[e];"subscribe"in t&&t.subscribe().then(function(e){t.unsubscribe=e,t.resolve()})}),this.fireEvent("ready")}},n.prototype.addEventListener=function(e,t){var n=this.eventListeners[e];n||(n=this.eventListeners[e]=[]),n.push(t)},n.prototype.removeEventListener=function(e,t){var n=this.eventListeners[e];if(n){var r=n.indexOf(t);-1!==r&&n.splice(r,1)}},n.prototype.fireEvent=function(e,t){var n=this;(this.eventListeners[e]||[]).forEach(function(e){return e(n,t)})},n.prototype.close=function(){this.closeRequested=!0,this.socket.close()},n.prototype.subscribeEvents=function(n,r){return e(this,void 0,void 0,function(){return t(this,function(e){return[2,this.subscribeMessage(n,function(e){var t={type:"subscribe_events"};return e&&(t.event_type=e),t}(r))]})})},n.prototype.ping=function(){return this.sendMessagePromise({type:"ping"})},n.prototype.sendMessage=function(e,t){t||(t=this._genCmdId()),e.id=t,this.socket.send(JSON.stringify(e))},n.prototype.sendMessagePromise=function(e){var t=this;return new Promise(function(n,r){var s=t._genCmdId();t.commands[s]={resolve:n,reject:r},t.sendMessage(e,s)})},n.prototype.subscribeMessage=function(n,r){return e(this,void 0,void 0,function(){var s,o,i=this;return t(this,function(c){switch(c.label){case 0:return s=this._genCmdId(),[4,new Promise(function(c,a){o=i.commands[s]={resolve:c,reject:a,callback:n,subscribe:function(){return i.subscribeMessage(n,r)},unsubscribe:function(){return e(i,void 0,void 0,function(){return t(this,function(e){switch(e.label){case 0:return[4,this.sendMessagePromise((t=s,{type:"unsubscribe_events",subscription:t}))];case 1:return e.sent(),delete this.commands[s],[2]}var t})})}};try{i.sendMessage(r,s)}catch(e){}})];case 1:return c.sent(),[2,function(){return o.unsubscribe()}]}})})},n.prototype._handleMessage=function(e){var t=JSON.parse(e.data);switch(t.type){case"event":this.commands[t.id].callback(t.event);break;case"result":if(t.id in this.commands){var n=this.commands[t.id];t.success?(n.resolve(t.result),"subscribe"in n||delete this.commands[t.id]):(n.reject(t.error),delete this.commands[t.id])}break;case"pong":this.commands[t.id].resolve(),delete this.commands[t.id]}},n.prototype._handleClose=function(n){var s=this;if(Object.keys(this.commands).forEach(function(e){var t=s.commands[e];"subscribe"in t||t.reject({type:"result",success:!1,error:{code:3,message:"Connection lost"}})}),!this.closeRequested){this.fireEvent("disconnected");var o=Object.assign({},this.options,{setupRetry:0}),i=function(n){setTimeout(function(){return e(s,void 0,void 0,function(){var e,s;return t(this,function(t){switch(t.label){case 0:t.label=1;case 1:return t.trys.push([1,3,,4]),[4,o.createSocket(o)];case 2:return e=t.sent(),this.setSocket(e),[3,4];case 3:return(s=t.sent())===r?this.fireEvent("reconnect-error",s):i(n+1),[3,4];case 4:return[2]}})})},1e3*Math.min(n,5))};i(0)}},n.prototype._genCmdId=function(){return++this.commandId},n}();var a=function(){return location.protocol+"//"+location.host+"/"},u=function(e){return 1e3*e+Date.now()};function f(e,t,n,r){n+=(n.includes("?")?"&":"?")+"auth_callback=1",document.location.href=function(e,t,n,r){var s=e+"/auth/authorize?response_type=code&client_id="+encodeURIComponent(t)+"&redirect_uri="+encodeURIComponent(n);return r&&(s+="&state="+encodeURIComponent(r)),s}(e,t,n,r)}function d(n,s,o){return e(this,void 0,void 0,function(){var e,i,c;return t(this,function(t){switch(t.label){case 0:return(e=new FormData).append("client_id",s),Object.keys(o).forEach(function(t){e.append(t,o[t])}),[4,fetch(n+"/auth/token",{method:"POST",credentials:"same-origin",body:e})];case 1:if(!(i=t.sent()).ok)throw 400===i.status||403===i.status?r:new Error("Unable to fetch tokens");return[4,i.json()];case 2:return(c=t.sent()).hassUrl=n,c.clientId=s,c.expires=u(c.expires_in),[2,c]}})})}var h=function(){function n(e,t){this.data=e,this._saveTokens=t}return Object.defineProperty(n.prototype,"wsUrl",{get:function(){return"ws"+this.data.hassUrl.substr(4)+"/api/websocket"},enumerable:!0,configurable:!0}),Object.defineProperty(n.prototype,"accessToken",{get:function(){return this.data.access_token},enumerable:!0,configurable:!0}),Object.defineProperty(n.prototype,"expired",{get:function(){return Date.now()>this.data.expires},enumerable:!0,configurable:!0}),n.prototype.refreshAccessToken=function(){return e(this,void 0,void 0,function(){var e;return t(this,function(t){switch(t.label){case 0:return[4,d(this.data.hassUrl,this.data.clientId,{grant_type:"refresh_token",refresh_token:this.data.refresh_token})];case 1:return(e=t.sent()).refresh_token=this.data.refresh_token,this.data=e,this._saveTokens&&this._saveTokens(e),[2]}})})},n.prototype.revoke=function(){return e(this,void 0,void 0,function(){var e;return t(this,function(t){switch(t.label){case 0:return(e=new FormData).append("action","revoke"),e.append("token",this.data.refresh_token),[4,fetch(this.data.hassUrl+"/auth/token",{method:"POST",credentials:"same-origin",body:e})];case 1:return t.sent(),this._saveTokens&&this._saveTokens(null),[2]}})})},n}();var l=function(e){var t=[];function n(n,r){e=r?n:Object.assign({},e,n);for(var s=t,o=0;o<s.length;o++)s[o](e)}return{get state(){return e},action:function(t){function r(e){n(e,!1)}return function(){for(var n=[e],s=0;s<arguments.length;s++)n.push(arguments[s]);var o=t.apply(this,n);if(null!=o)return o.then?o.then(r):r(o)}},setState:n,subscribe:function(e){return t.push(e),function(){!function(e){for(var n=[],r=0;r<t.length;r++)t[r]===e?e=null:n.push(t[r]);t=n}(e)}}}},v=function(e,t,n,r){if(e[t])return e[t];var s,o=0,i=l(),c=function(){return n(e).then(function(e){return i.setState(e,!0)})};return e[t]={get state(){return i.state},refresh:c,subscribe:function(t){o||(o++,r&&(s=r(e,i)),e.addEventListener("ready",c),c().catch(function(t){if(e.socket.readyState==e.socket.OPEN)throw t}));var n=i.subscribe(t);return void 0!==i.state&&t(i.state),function(){n(),--o||(s&&s.then(function(e){e()}),e.removeEventListener("ready",c))}}},e[t]},p=function(e){return e.sendMessagePromise({type:"get_states"})},b=function(e){return e.sendMessagePromise({type:"get_services"})},m=function(e){return e.sendMessagePromise({type:"get_config"})};function g(e,t){return void 0===e?null:{components:e.components.concat(t.data.component)}}var y=function(e){return m(e)},_=function(e,t){return e.subscribeEvents(t.action(g),"component_loaded")};function k(e,t){var n,r;if(void 0===e)return null;var s=t.data,o=s.domain,i=Object.assign({},e[o],((n={})[s.service]={description:"",fields:{}},n));return(r={})[o]=i,r}function w(e,t){var n;if(void 0===e)return null;var r=t.data,s=r.domain,o=r.service,i=e[s];if(!(i&&o in i))return null;var c={};return Object.keys(i).forEach(function(e){e!==o&&(c[e]=i[e])}),(n={})[s]=c,n}var E=function(e){return b(e)},x=function(e,t){return Promise.all([e.subscribeEvents(t.action(k),"service_registered"),e.subscribeEvents(t.action(w),"service_removed")]).then(function(e){return function(){return e.forEach(function(e){return e()})}})};function S(n){return e(this,void 0,void 0,function(){var e,r,s,o;return t(this,function(t){switch(t.label){case 0:return[4,p(n)];case 1:for(e=t.sent(),r={},s=0;s<e.length;s++)r[(o=e[s]).entity_id]=o;return[2,r]}})})}var O=function(e,t){return e.subscribeEvents(function(e){return function(e,t){var n,r=e.state;if(void 0!==r){var s=t.data,o=s.entity_id,i=s.new_state;if(i)e.setState(((n={})[i.entity_id]=i,n));else{var c=Object.assign({},r);delete c[o],e.setState(c,!0)}}}(t,e)},"state_changed")},C=function(e){return v(e,"_ent",S,O)},T={setupRetry:0,createSocket:function(c){if(!c.auth)throw s;var a=c.auth,u=a.wsUrl;return new Promise(function(s,f){return function s(c,f,d){var h=this,l=new WebSocket(u),v=!1,p=function(){if(l.removeEventListener("close",p),v)d(r);else if(0!==c){var e=-1===c?-1:c-1;setTimeout(function(){return s(e,f,d)},1e3)}else d(n)},b=function(n){return e(h,void 0,void 0,function(){var e;return t(this,function(t){switch(t.label){case 0:return t.trys.push([0,3,,4]),a.expired?[4,a.refreshAccessToken()]:[3,2];case 1:t.sent(),t.label=2;case 2:return l.send(JSON.stringify({type:"auth",access_token:a.accessToken})),[3,4];case 3:return e=t.sent(),v=e===r,l.close(),[3,4];case 4:return[2]}})})},m=function(n){return e(h,void 0,void 0,function(){return t(this,function(e){switch(JSON.parse(n.data).type){case o:v=!0,l.close();break;case i:l.removeEventListener("open",b),l.removeEventListener("message",m),l.removeEventListener("close",p),l.removeEventListener("error",p),f(l)}return[2]})})};l.addEventListener("open",b),l.addEventListener("message",m),l.addEventListener("close",p),l.addEventListener("error",p)}(c.setupRetry,s,f)})}};exports.createConnection=function(n){return e(this,void 0,void 0,function(){var e,r;return t(this,function(t){switch(t.label){case 0:return[4,(e=Object.assign({},T,n)).createSocket(e)];case 1:return r=t.sent(),[2,new c(r,e)]}})})},exports.genClientId=a,exports.genExpires=u,exports.Auth=h,exports.getAuth=function(n){return void 0===n&&(n={}),e(this,void 0,void 0,function(){var e,r,o,i,c,u,l;return t(this,function(t){switch(t.label){case 0:if(!("auth_callback"in(r=function(e){for(var t={},n=e.split("&"),r=0;r<n.length;r++){var s=n[r].split("="),o=decodeURIComponent(s[0]),i=s.length>1?decodeURIComponent(s[1]):void 0;t[o]=i}return t}(location.search.substr(1)))))return[3,4];o=JSON.parse(atob(r.state)),t.label=1;case 1:return t.trys.push([1,3,,4]),[4,function(e,t,n){return d(e,t,{code:n,grant_type:"authorization_code"})}(o.hassUrl,o.clientId,r.code)];case 2:return e=t.sent(),n.saveTokens&&n.saveTokens(e),[3,4];case 3:return i=t.sent(),console.log("Unable to fetch access token",i),[3,4];case 4:return e||!n.loadTokens?[3,6]:[4,n.loadTokens()];case 5:e=t.sent(),t.label=6;case 6:if(e)return[2,new h(e,n.saveTokens)];if(void 0===(c=n.hassUrl))throw s;return"/"===c[c.length-1]&&(c=c.substr(0,c.length-1)),u=n.clientId||a(),l=n.redirectUrl||location.protocol+"//"+location.host+location.pathname+location.search,f(c,u,l,function(e){return btoa(JSON.stringify(e))}({hassUrl:c,clientId:u})),[2,new Promise(function(){})]}})})},exports.getCollection=v,exports.createCollection=function(e,t,n,r,s){return v(r,e,t,n).subscribe(s)},exports.Connection=c,exports.subscribeConfig=function(e,t){return function(e){return v(e,"_cnf",y,_)}(e).subscribe(t)},exports.subscribeServices=function(e,t){return function(e){return v(e,"_srv",E,x)}(e).subscribe(t)},exports.entitiesColl=C,exports.subscribeEntities=function(e,t){return C(e).subscribe(t)},exports.ERR_CANNOT_CONNECT=n,exports.ERR_INVALID_AUTH=r,exports.ERR_CONNECTION_LOST=3,exports.ERR_HASS_HOST_REQUIRED=s,exports.getStates=p,exports.getServices=b,exports.getConfig=m,exports.getUser=function(e){return e.sendMessagePromise({type:"auth/current_user"})},exports.callService=function(e,t,n,r){return e.sendMessagePromise(function(e,t,n){var r={type:"call_service",domain:e,service:t};return n&&(r.service_data=n),r}(t,n,r))}; | ||
const e=function(){function e(){}return e.prototype.then=function(n,r){const o=new e,s=this.s;if(s){const e=1&s?n:r;if(e){try{t(o,1,e(this.v))}catch(e){t(o,2,e)}return o}return this}return this.o=function(e){try{const s=e.v;1&e.s?t(o,1,n?n(s):s):r?t(o,1,r(s)):t(o,2,s)}catch(e){t(o,2,e)}},o},e}();function t(n,r,o){if(!n.s){if(o instanceof e){if(!o.s)return void(o.o=t.bind(null,n,r));1&r&&(r=o.s),o=o.v}if(o&&o.then)return void o.then(t.bind(null,n,r),t.bind(null,n,2));n.s=r,n.v=o;const s=n.o;s&&s(n)}}function n(e,t){try{var n=e()}catch(e){return t(e)}return n&&n.then?n.then(void 0,t):n}const r={};!function(){function n(e){this._entry=e,this._pact=null,this._resolve=null,this._return=null,this._promise=null}function o(e){return{value:e,done:!0}}function s(e){return{value:e,done:!1}}n.prototype[Symbol.asyncIterator||(Symbol.asyncIterator=Symbol("Symbol.asyncIterator"))]=function(){return this},n.prototype._yield=function(t){return this._resolve(t&&t.then?t.then(s):s(t)),this._pact=new e},n.prototype.next=function(n){const s=this;return s._promise=new Promise(function(i){const c=s._pact;if(null===c){const t=s._entry;if(null===t)return i(s._promise);function u(e){s._resolve(e&&e.then?e.then(o):o(e)),s._pact=null,s._resolve=null}s._entry=null,s._resolve=i,t(s).then(u,function(t){if(t===r)u(s._return);else{const n=new e;s._resolve(n),s._pact=null,s._resolve=null,_resolve(n,2,t)}})}else s._pact=null,s._resolve=i,t(c,1,n)})},n.prototype.return=function(e){const n=this;return n._promise=new Promise(function(s){const i=n._pact;if(null===i)return null===n._entry?s(n._promise):(n._entry=null,s(e&&e.then?e.then(o):o(e)));n._return=e,n._resolve=s,n._pact=null,t(i,2,r)})},n.prototype.throw=function(e){const n=this;return n._promise=new Promise(function(r,o){const s=n._pact;if(null===s)return null===n._entry?r(n._promise):(n._entry=null,o(e));n._resolve=r,n._pact=null,t(s,2,e)})}}();var o=4,s=function(e,t){this.options=t,this.commandId=1,this.commands={},this.eventListeners={},this.closeRequested=!1,this.setSocket(e)};s.prototype.setSocket=function(e){var t=this,n=this.socket;if(this.socket=e,e.addEventListener("message",function(e){return t._handleMessage(e)}),e.addEventListener("close",function(e){return t._handleClose(e)}),n){var r=this.commands;this.commandId=1,this.commands={},Object.keys(r).forEach(function(e){var t=r[e];"subscribe"in t&&t.subscribe().then(function(e){t.unsubscribe=e,t.resolve()})}),this.fireEvent("ready")}},s.prototype.addEventListener=function(e,t){var n=this.eventListeners[e];n||(n=this.eventListeners[e]=[]),n.push(t)},s.prototype.removeEventListener=function(e,t){var n=this.eventListeners[e];if(n){var r=n.indexOf(t);-1!==r&&n.splice(r,1)}},s.prototype.fireEvent=function(e,t){var n=this;(this.eventListeners[e]||[]).forEach(function(e){return e(n,t)})},s.prototype.close=function(){this.closeRequested=!0,this.socket.close()},s.prototype.subscribeEvents=function(e,t){try{return this.subscribeMessage(e,function(e){var t={type:"subscribe_events"};return e&&(t.event_type=e),t}(t))}catch(e){return Promise.reject(e)}},s.prototype.ping=function(){return this.sendMessagePromise({type:"ping"})},s.prototype.sendMessage=function(e,t){t||(t=this._genCmdId()),e.id=t,this.socket.send(JSON.stringify(e))},s.prototype.sendMessagePromise=function(e){var t=this;return new Promise(function(n,r){var o=t._genCmdId();t.commands[o]={resolve:n,reject:r},t.sendMessage(e,o)})},s.prototype.subscribeMessage=function(e,t){try{var n,r=this,o=r._genCmdId();return Promise.resolve(new Promise(function(s,i){n=r.commands[o]={resolve:s,reject:i,callback:e,subscribe:function(){return r.subscribeMessage(e,t)},unsubscribe:function(){try{return Promise.resolve(r.sendMessagePromise((e=o,{type:"unsubscribe_events",subscription:e}))).then(function(){delete r.commands[o]})}catch(e){return Promise.reject(e)}var e}};try{r.sendMessage(t,o)}catch(e){}})).then(function(){return function(){return n.unsubscribe()}})}catch(e){return Promise.reject(e)}},s.prototype._handleMessage=function(e){var t=JSON.parse(e.data);switch(t.type){case"event":this.commands[t.id].callback(t.event);break;case"result":if(t.id in this.commands){var n=this.commands[t.id];t.success?(n.resolve(t.result),"subscribe"in n||delete this.commands[t.id]):(n.reject(t.error),delete this.commands[t.id])}break;case"pong":this.commands[t.id].resolve(),delete this.commands[t.id]}},s.prototype._handleClose=function(e){var t=this;if(Object.keys(this.commands).forEach(function(e){var n=t.commands[e];"subscribe"in n||n.reject({type:"result",success:!1,error:{code:3,message:"Connection lost"}})}),!this.closeRequested){this.fireEvent("disconnected");var r=Object.assign({},this.options,{setupRetry:0}),o=function(e){var s=t;setTimeout(function(){try{var t=n(function(){return Promise.resolve(r.createSocket(r)).then(function(e){s.setSocket(e)})},function(t){2===t?s.fireEvent("reconnect-error",t):o(e+1)});return Promise.resolve(t&&t.then?t.then(function(){}):void 0)}catch(e){return Promise.reject(e)}},1e3*Math.min(e,5))};o(0)}},s.prototype._genCmdId=function(){return++this.commandId};var i=function(e,t,n){try{var r=new FormData;return r.append("client_id",t),Object.keys(n).forEach(function(e){r.append(e,n[e])}),Promise.resolve(fetch(e+"/auth/token",{method:"POST",credentials:"same-origin",body:r})).then(function(n){if(!n.ok)throw 400===n.status||403===n.status?2:new Error("Unable to fetch tokens");return Promise.resolve(n.json()).then(function(n){return n.hassUrl=e,n.clientId=t,n.expires=u(n.expires_in),n})})}catch(e){return Promise.reject(e)}},c=function(){return location.protocol+"//"+location.host+"/"},u=function(e){return 1e3*e+Date.now()},a=function(e,t){this.data=e,this._saveTokens=t},f={wsUrl:{configurable:!0},accessToken:{configurable:!0},expired:{configurable:!0}};f.wsUrl.get=function(){return"ws"+this.data.hassUrl.substr(4)+"/api/websocket"},f.accessToken.get=function(){return this.data.access_token},f.expired.get=function(){return Date.now()>this.data.expires},a.prototype.refreshAccessToken=function(){try{var e=this;return Promise.resolve(i(e.data.hassUrl,e.data.clientId,{grant_type:"refresh_token",refresh_token:e.data.refresh_token})).then(function(t){t.refresh_token=e.data.refresh_token,e.data=t,e._saveTokens&&e._saveTokens(t)})}catch(e){return Promise.reject(e)}},a.prototype.revoke=function(){try{var e=this,t=new FormData;return t.append("action","revoke"),t.append("token",e.data.refresh_token),Promise.resolve(fetch(e.data.hassUrl+"/auth/token",{method:"POST",credentials:"same-origin",body:t})).then(function(){e._saveTokens&&e._saveTokens(null)})}catch(e){return Promise.reject(e)}},Object.defineProperties(a.prototype,f);var l=function(e,t,n,r){if(e[t])return e[t];var o,s=0,i=function(e){var t=[];function n(n,r){e=r?n:Object.assign({},e,n);for(var o=t,s=0;s<o.length;s++)o[s](e)}return{get state(){return e},action:function(t){function r(e){n(e,!1)}return function(){for(var n=arguments,o=[e],s=0;s<arguments.length;s++)o.push(n[s]);var i=t.apply(this,o);if(null!=i)return i.then?i.then(r):r(i)}},setState:n,subscribe:function(e){return t.push(e),function(){!function(e){for(var n=[],r=0;r<t.length;r++)t[r]===e?e=null:n.push(t[r]);t=n}(e)}}}}(),c=function(){return n(e).then(function(e){return i.setState(e,!0)})};return e[t]={get state(){return i.state},refresh:c,subscribe:function(t){s||(s++,r&&(o=r(e,i)),e.addEventListener("ready",c),c().catch(function(t){if(e.socket.readyState==e.socket.OPEN)throw t}));var n=i.subscribe(t);return void 0!==i.state&&t(i.state),function(){n(),--s||(o&&o.then(function(e){e()}),e.removeEventListener("ready",c))}}},e[t]},h=function(e){return e.sendMessagePromise({type:"get_states"})},d=function(e){return e.sendMessagePromise({type:"get_services"})},v=function(e){return e.sendMessagePromise({type:"get_config"})};function p(e,t){return void 0===e?null:{components:e.components.concat(t.data.component)}}var m=function(e){return v(e)},_=function(e,t){return e.subscribeEvents(t.action(p),"component_loaded")};function b(e,t){var n,r;if(void 0===e)return null;var o=t.data,s=o.domain,i=Object.assign({},e[s],((n={})[o.service]={description:"",fields:{}},n));return(r={})[s]=i,r}function y(e,t){var n;if(void 0===e)return null;var r=t.data,o=r.domain,s=r.service,i=e[o];if(!(i&&s in i))return null;var c={};return Object.keys(i).forEach(function(e){e!==s&&(c[e]=i[e])}),(n={})[o]=c,n}var g=function(e){return d(e)},k=function(e,t){return Promise.all([e.subscribeEvents(t.action(b),"service_registered"),e.subscribeEvents(t.action(y),"service_removed")]).then(function(e){return function(){return e.forEach(function(e){return e()})}})},P=function(e){try{return Promise.resolve(h(e)).then(function(e){for(var t={},n=0;n<e.length;n++){var r=e[n];t[r.entity_id]=r}return t})}catch(e){return Promise.reject(e)}},E=function(e,t){return e.subscribeEvents(function(e){return function(t,n){var r,o=t.state;if(void 0!==o){var s=e.data,i=s.entity_id,c=s.new_state;if(c)t.setState(((r={})[c.entity_id]=c,r));else{var u=Object.assign({},o);delete u[i],t.setState(u,!0)}}}(t)},"state_changed")},S=function(e){return l(e,"_ent",P,E)},w={setupRetry:0,createSocket:function(e){if(!e.auth)throw o;var t=e.auth,r=e.WebSocket||WebSocket,s=t.expired?t.refreshAccessToken().then(function(){s=void 0},function(){s=void 0}):void 0,i=t.wsUrl;return new Promise(function(o,c){return function e(o,c,u){var a=new r(i),f=!1,l=function(){if(a.removeEventListener("close",l),f)u(2);else if(0!==o){var t=-1===o?-1:o-1;setTimeout(function(){return e(t,c,u)},1e3)}else u(1)},h=function(e){try{var r=n(function(){function e(){a.send(JSON.stringify({type:"auth",access_token:t.accessToken}))}var n=function(){if(t.expired)return Promise.resolve(s||t.refreshAccessToken()).then(function(){})}();return n&&n.then?n.then(e):e()},function(e){f=2===e,a.close()});return Promise.resolve(r&&r.then?r.then(function(){}):void 0)}catch(e){return Promise.reject(e)}},d=function(e){try{switch(JSON.parse(e.data).type){case"auth_invalid":f=!0,a.close();break;case"auth_ok":a.removeEventListener("open",h),a.removeEventListener("message",d),a.removeEventListener("close",l),a.removeEventListener("error",l),c(a)}return}catch(e){return Promise.reject(e)}};a.addEventListener("open",h),a.addEventListener("message",d),a.addEventListener("close",l),a.addEventListener("error",l)}(e.setupRetry,o,c)})}};exports.createConnection=function(e){try{var t=Object.assign({},w,e);return Promise.resolve(t.createSocket(t)).then(function(e){return new s(e,t)})}catch(e){return Promise.reject(e)}},exports.getAuth=function(e){void 0===e&&(e={});try{function t(){function t(){if(r)return new a(r,e.saveTokens);var t=e.hassUrl;if(void 0===t)throw o;"/"===t[t.length-1]&&(t=t.substr(0,t.length-1));var n=e.clientId||c();return function(e,t,n,r){n+=(n.includes("?")?"&":"?")+"auth_callback=1",document.location.href=function(e,t,n,r){var o=e+"/auth/authorize?response_type=code&client_id="+encodeURIComponent(t)+"&redirect_uri="+encodeURIComponent(n);return r&&(o+="&state="+encodeURIComponent(r)),o}(e,t,n,r)}(t,n,e.redirectUrl||location.protocol+"//"+location.host+location.pathname+location.search,btoa(JSON.stringify({hassUrl:t,clientId:n}))),new Promise(function(){})}var n=function(){if(!r&&e.loadTokens)return Promise.resolve(e.loadTokens()).then(function(e){r=e})}();return n&&n.then?n.then(t):t()}var r,s=function(e){for(var t={},n=location.search.substr(1).split("&"),r=0;r<n.length;r++){var o=n[r].split("="),s=decodeURIComponent(o[0]),i=o.length>1?decodeURIComponent(o[1]):void 0;t[s]=i}return t}(),u=function(){if("auth_callback"in s){var t=JSON.parse(atob(s.state)),o=n(function(){return Promise.resolve((n=t.hassUrl,o=t.clientId,c=s.code,i(n,o,{code:c,grant_type:"authorization_code"}))).then(function(t){r=t,e.saveTokens&&e.saveTokens(r)});var n,o,c},function(e){console.log("Unable to fetch access token",e)});if(o&&o.then)return o.then(function(){})}}();return Promise.resolve(u&&u.then?u.then(t):t())}catch(e){return Promise.reject(e)}},exports.genClientId=c,exports.genExpires=u,exports.Auth=a,exports.getCollection=l,exports.createCollection=function(e,t,n,r,o){return l(r,e,t,n).subscribe(o)},exports.Connection=s,exports.subscribeConfig=function(e,t){return function(e){return l(e,"_cnf",m,_)}(e).subscribe(t)},exports.subscribeServices=function(e,t){return function(e){return l(e,"_srv",g,k)}(e).subscribe(t)},exports.entitiesColl=S,exports.subscribeEntities=function(e,t){return S(e).subscribe(t)},exports.ERR_CANNOT_CONNECT=1,exports.ERR_INVALID_AUTH=2,exports.ERR_CONNECTION_LOST=3,exports.ERR_HASS_HOST_REQUIRED=o,exports.getStates=h,exports.getServices=d,exports.getConfig=v,exports.getUser=function(e){return e.sendMessagePromise({type:"auth/current_user"})},exports.callService=function(e,t,n,r){return e.sendMessagePromise(function(e,t,n){var r={type:"call_service",domain:e,service:t};return n&&(r.service_data=n),r}(t,n,r))}; | ||
//# sourceMappingURL=haws.js.map |
@@ -1,2 +0,2 @@ | ||
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):t(e.HAWS={})}(this,function(e){function t(e,t,n,r){return new(n||(n=Promise))(function(s,i){function o(e){try{a(r.next(e))}catch(e){i(e)}}function c(e){try{a(r.throw(e))}catch(e){i(e)}}function a(e){e.done?s(e.value):new n(function(t){t(e.value)}).then(o,c)}a((r=r.apply(e,t||[])).next())})}function n(e,t){var n,r,s,i,o={label:0,sent:function(){if(1&s[0])throw s[1];return s[1]},trys:[],ops:[]};return i={next:c(0),throw:c(1),return:c(2)},"function"==typeof Symbol&&(i[Symbol.iterator]=function(){return this}),i;function c(i){return function(c){return function(i){if(n)throw new TypeError("Generator is already executing.");for(;o;)try{if(n=1,r&&(s=2&i[0]?r.return:i[0]?r.throw||((s=r.return)&&s.call(r),0):r.next)&&!(s=s.call(r,i[1])).done)return s;switch(r=0,s&&(i=[2&i[0],s.value]),i[0]){case 0:case 1:s=i;break;case 4:return o.label++,{value:i[1],done:!1};case 5:o.label++,r=i[1],i=[0];continue;case 7:i=o.ops.pop(),o.trys.pop();continue;default:if(!(s=(s=o.trys).length>0&&s[s.length-1])&&(6===i[0]||2===i[0])){o=0;continue}if(3===i[0]&&(!s||i[1]>s[0]&&i[1]<s[3])){o.label=i[1];break}if(6===i[0]&&o.label<s[1]){o.label=s[1],s=i;break}if(s&&o.label<s[2]){o.label=s[2],o.ops.push(i);break}s[2]&&o.ops.pop(),o.trys.pop();continue}i=t.call(e,o)}catch(e){i=[6,e],r=0}finally{n=s=0}if(5&i[0])throw i[1];return{value:i[0]?i[1]:void 0,done:!0}}([i,c])}}}var r=1,s=2,i=4;var o="auth_invalid",c="auth_ok";var a=function(){function e(e,t){this.options=t,this.commandId=1,this.commands={},this.eventListeners={},this.closeRequested=!1,this.setSocket(e)}return e.prototype.setSocket=function(e){var t=this,n=this.socket;if(this.socket=e,e.addEventListener("message",function(e){return t._handleMessage(e)}),e.addEventListener("close",function(e){return t._handleClose(e)}),n){var r=this.commands;this.commandId=1,this.commands={},Object.keys(r).forEach(function(e){var t=r[e];"subscribe"in t&&t.subscribe().then(function(e){t.unsubscribe=e,t.resolve()})}),this.fireEvent("ready")}},e.prototype.addEventListener=function(e,t){var n=this.eventListeners[e];n||(n=this.eventListeners[e]=[]),n.push(t)},e.prototype.removeEventListener=function(e,t){var n=this.eventListeners[e];if(n){var r=n.indexOf(t);-1!==r&&n.splice(r,1)}},e.prototype.fireEvent=function(e,t){var n=this;(this.eventListeners[e]||[]).forEach(function(e){return e(n,t)})},e.prototype.close=function(){this.closeRequested=!0,this.socket.close()},e.prototype.subscribeEvents=function(e,r){return t(this,void 0,void 0,function(){return n(this,function(t){return[2,this.subscribeMessage(e,function(e){var t={type:"subscribe_events"};return e&&(t.event_type=e),t}(r))]})})},e.prototype.ping=function(){return this.sendMessagePromise({type:"ping"})},e.prototype.sendMessage=function(e,t){t||(t=this._genCmdId()),e.id=t,this.socket.send(JSON.stringify(e))},e.prototype.sendMessagePromise=function(e){var t=this;return new Promise(function(n,r){var s=t._genCmdId();t.commands[s]={resolve:n,reject:r},t.sendMessage(e,s)})},e.prototype.subscribeMessage=function(e,r){return t(this,void 0,void 0,function(){var s,i,o=this;return n(this,function(c){switch(c.label){case 0:return s=this._genCmdId(),[4,new Promise(function(c,a){i=o.commands[s]={resolve:c,reject:a,callback:e,subscribe:function(){return o.subscribeMessage(e,r)},unsubscribe:function(){return t(o,void 0,void 0,function(){return n(this,function(e){switch(e.label){case 0:return[4,this.sendMessagePromise((t=s,{type:"unsubscribe_events",subscription:t}))];case 1:return e.sent(),delete this.commands[s],[2]}var t})})}};try{o.sendMessage(r,s)}catch(e){}})];case 1:return c.sent(),[2,function(){return i.unsubscribe()}]}})})},e.prototype._handleMessage=function(e){var t=JSON.parse(e.data);switch(t.type){case"event":this.commands[t.id].callback(t.event);break;case"result":if(t.id in this.commands){var n=this.commands[t.id];t.success?(n.resolve(t.result),"subscribe"in n||delete this.commands[t.id]):(n.reject(t.error),delete this.commands[t.id])}break;case"pong":this.commands[t.id].resolve(),delete this.commands[t.id]}},e.prototype._handleClose=function(e){var r=this;if(Object.keys(this.commands).forEach(function(e){var t=r.commands[e];"subscribe"in t||t.reject({type:"result",success:!1,error:{code:3,message:"Connection lost"}})}),!this.closeRequested){this.fireEvent("disconnected");var i=Object.assign({},this.options,{setupRetry:0}),o=function(e){setTimeout(function(){return t(r,void 0,void 0,function(){var t,r;return n(this,function(n){switch(n.label){case 0:n.label=1;case 1:return n.trys.push([1,3,,4]),[4,i.createSocket(i)];case 2:return t=n.sent(),this.setSocket(t),[3,4];case 3:return(r=n.sent())===s?this.fireEvent("reconnect-error",r):o(e+1),[3,4];case 4:return[2]}})})},1e3*Math.min(e,5))};o(0)}},e.prototype._genCmdId=function(){return++this.commandId},e}();var u=function(){return location.protocol+"//"+location.host+"/"},f=function(e){return 1e3*e+Date.now()};function d(e,t,n,r){n+=(n.includes("?")?"&":"?")+"auth_callback=1",document.location.href=function(e,t,n,r){var s=e+"/auth/authorize?response_type=code&client_id="+encodeURIComponent(t)+"&redirect_uri="+encodeURIComponent(n);return r&&(s+="&state="+encodeURIComponent(r)),s}(e,t,n,r)}function h(e,r,i){return t(this,void 0,void 0,function(){var t,o,c;return n(this,function(n){switch(n.label){case 0:return(t=new FormData).append("client_id",r),Object.keys(i).forEach(function(e){t.append(e,i[e])}),[4,fetch(e+"/auth/token",{method:"POST",credentials:"same-origin",body:t})];case 1:if(!(o=n.sent()).ok)throw 400===o.status||403===o.status?s:new Error("Unable to fetch tokens");return[4,o.json()];case 2:return(c=n.sent()).hassUrl=e,c.clientId=r,c.expires=f(c.expires_in),[2,c]}})})}var l=function(){function e(e,t){this.data=e,this._saveTokens=t}return Object.defineProperty(e.prototype,"wsUrl",{get:function(){return"ws"+this.data.hassUrl.substr(4)+"/api/websocket"},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"accessToken",{get:function(){return this.data.access_token},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"expired",{get:function(){return Date.now()>this.data.expires},enumerable:!0,configurable:!0}),e.prototype.refreshAccessToken=function(){return t(this,void 0,void 0,function(){var e;return n(this,function(t){switch(t.label){case 0:return[4,h(this.data.hassUrl,this.data.clientId,{grant_type:"refresh_token",refresh_token:this.data.refresh_token})];case 1:return(e=t.sent()).refresh_token=this.data.refresh_token,this.data=e,this._saveTokens&&this._saveTokens(e),[2]}})})},e.prototype.revoke=function(){return t(this,void 0,void 0,function(){var e;return n(this,function(t){switch(t.label){case 0:return(e=new FormData).append("action","revoke"),e.append("token",this.data.refresh_token),[4,fetch(this.data.hassUrl+"/auth/token",{method:"POST",credentials:"same-origin",body:e})];case 1:return t.sent(),this._saveTokens&&this._saveTokens(null),[2]}})})},e}();var v=function(e){var t=[];function n(n,r){e=r?n:Object.assign({},e,n);for(var s=t,i=0;i<s.length;i++)s[i](e)}return{get state(){return e},action:function(t){function r(e){n(e,!1)}return function(){for(var n=[e],s=0;s<arguments.length;s++)n.push(arguments[s]);var i=t.apply(this,n);if(null!=i)return i.then?i.then(r):r(i)}},setState:n,subscribe:function(e){return t.push(e),function(){!function(e){for(var n=[],r=0;r<t.length;r++)t[r]===e?e=null:n.push(t[r]);t=n}(e)}}}},p=function(e,t,n,r){if(e[t])return e[t];var s,i=0,o=v(),c=function(){return n(e).then(function(e){return o.setState(e,!0)})};return e[t]={get state(){return o.state},refresh:c,subscribe:function(t){i||(i++,r&&(s=r(e,o)),e.addEventListener("ready",c),c().catch(function(t){if(e.socket.readyState==e.socket.OPEN)throw t}));var n=o.subscribe(t);return void 0!==o.state&&t(o.state),function(){n(),--i||(s&&s.then(function(e){e()}),e.removeEventListener("ready",c))}}},e[t]},b=function(e){return e.sendMessagePromise({type:"get_states"})},m=function(e){return e.sendMessagePromise({type:"get_services"})},y=function(e){return e.sendMessagePromise({type:"get_config"})};function g(e,t){return void 0===e?null:{components:e.components.concat(t.data.component)}}var _=function(e){return y(e)},k=function(e,t){return e.subscribeEvents(t.action(g),"component_loaded")};function w(e,t){var n,r;if(void 0===e)return null;var s=t.data,i=s.domain,o=Object.assign({},e[i],((n={})[s.service]={description:"",fields:{}},n));return(r={})[i]=o,r}function E(e,t){var n;if(void 0===e)return null;var r=t.data,s=r.domain,i=r.service,o=e[s];if(!(o&&i in o))return null;var c={};return Object.keys(o).forEach(function(e){e!==i&&(c[e]=o[e])}),(n={})[s]=c,n}var S=function(e){return m(e)},O=function(e,t){return Promise.all([e.subscribeEvents(t.action(w),"service_registered"),e.subscribeEvents(t.action(E),"service_removed")]).then(function(e){return function(){return e.forEach(function(e){return e()})}})};function C(e){return t(this,void 0,void 0,function(){var t,r,s,i;return n(this,function(n){switch(n.label){case 0:return[4,b(e)];case 1:for(t=n.sent(),r={},s=0;s<t.length;s++)r[(i=t[s]).entity_id]=i;return[2,r]}})})}var T=function(e,t){return e.subscribeEvents(function(e){return function(e,t){var n,r=e.state;if(void 0!==r){var s=t.data,i=s.entity_id,o=s.new_state;if(o)e.setState(((n={})[o.entity_id]=o,n));else{var c=Object.assign({},r);delete c[i],e.setState(c,!0)}}}(t,e)},"state_changed")},I=function(e){return p(e,"_ent",C,T)},L={setupRetry:0,createSocket:function(e){if(!e.auth)throw i;var a=e.auth,u=a.wsUrl;return new Promise(function(i,f){return function e(i,f,d){var h=this,l=new WebSocket(u),v=!1,p=function(){if(l.removeEventListener("close",p),v)d(s);else if(0!==i){var t=-1===i?-1:i-1;setTimeout(function(){return e(t,f,d)},1e3)}else d(r)},b=function(e){return t(h,void 0,void 0,function(){var e;return n(this,function(t){switch(t.label){case 0:return t.trys.push([0,3,,4]),a.expired?[4,a.refreshAccessToken()]:[3,2];case 1:t.sent(),t.label=2;case 2:return l.send(JSON.stringify({type:"auth",access_token:a.accessToken})),[3,4];case 3:return e=t.sent(),v=e===s,l.close(),[3,4];case 4:return[2]}})})},m=function(e){return t(h,void 0,void 0,function(){return n(this,function(t){switch(JSON.parse(e.data).type){case o:v=!0,l.close();break;case c:l.removeEventListener("open",b),l.removeEventListener("message",m),l.removeEventListener("close",p),l.removeEventListener("error",p),f(l)}return[2]})})};l.addEventListener("open",b),l.addEventListener("message",m),l.addEventListener("close",p),l.addEventListener("error",p)}(e.setupRetry,i,f)})}};e.createConnection=function(e){return t(this,void 0,void 0,function(){var t,r;return n(this,function(n){switch(n.label){case 0:return[4,(t=Object.assign({},L,e)).createSocket(t)];case 1:return r=n.sent(),[2,new a(r,t)]}})})},e.genClientId=u,e.genExpires=f,e.Auth=l,e.getAuth=function(e){return void 0===e&&(e={}),t(this,void 0,void 0,function(){var t,r,s,o,c,a,f;return n(this,function(n){switch(n.label){case 0:if(!("auth_callback"in(r=function(e){for(var t={},n=e.split("&"),r=0;r<n.length;r++){var s=n[r].split("="),i=decodeURIComponent(s[0]),o=s.length>1?decodeURIComponent(s[1]):void 0;t[i]=o}return t}(location.search.substr(1)))))return[3,4];s=JSON.parse(atob(r.state)),n.label=1;case 1:return n.trys.push([1,3,,4]),[4,function(e,t,n){return h(e,t,{code:n,grant_type:"authorization_code"})}(s.hassUrl,s.clientId,r.code)];case 2:return t=n.sent(),e.saveTokens&&e.saveTokens(t),[3,4];case 3:return o=n.sent(),console.log("Unable to fetch access token",o),[3,4];case 4:return t||!e.loadTokens?[3,6]:[4,e.loadTokens()];case 5:t=n.sent(),n.label=6;case 6:if(t)return[2,new l(t,e.saveTokens)];if(void 0===(c=e.hassUrl))throw i;return"/"===c[c.length-1]&&(c=c.substr(0,c.length-1)),a=e.clientId||u(),f=e.redirectUrl||location.protocol+"//"+location.host+location.pathname+location.search,d(c,a,f,function(e){return btoa(JSON.stringify(e))}({hassUrl:c,clientId:a})),[2,new Promise(function(){})]}})})},e.getCollection=p,e.createCollection=function(e,t,n,r,s){return p(r,e,t,n).subscribe(s)},e.Connection=a,e.subscribeConfig=function(e,t){return function(e){return p(e,"_cnf",_,k)}(e).subscribe(t)},e.subscribeServices=function(e,t){return function(e){return p(e,"_srv",S,O)}(e).subscribe(t)},e.entitiesColl=I,e.subscribeEntities=function(e,t){return I(e).subscribe(t)},e.ERR_CANNOT_CONNECT=r,e.ERR_INVALID_AUTH=s,e.ERR_CONNECTION_LOST=3,e.ERR_HASS_HOST_REQUIRED=i,e.getStates=b,e.getServices=m,e.getConfig=y,e.getUser=function(e){return e.sendMessagePromise({type:"auth/current_user"})},e.callService=function(e,t,n,r){return e.sendMessagePromise(function(e,t,n){var r={type:"call_service",domain:e,service:t};return n&&(r.service_data=n),r}(t,n,r))}}); | ||
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):t(e.HAWS={})}(this,function(e){const t=function(){function e(){}return e.prototype.then=function(t,r){const o=new e,s=this.s;if(s){const e=1&s?t:r;if(e){try{n(o,1,e(this.v))}catch(e){n(o,2,e)}return o}return this}return this.o=function(e){try{const s=e.v;1&e.s?n(o,1,t?t(s):s):r?n(o,1,r(s)):n(o,2,s)}catch(e){n(o,2,e)}},o},e}();function n(e,r,o){if(!e.s){if(o instanceof t){if(!o.s)return void(o.o=n.bind(null,e,r));1&r&&(r=o.s),o=o.v}if(o&&o.then)return void o.then(n.bind(null,e,r),n.bind(null,e,2));e.s=r,e.v=o;const s=e.o;s&&s(e)}}function r(e,t){try{var n=e()}catch(e){return t(e)}return n&&n.then?n.then(void 0,t):n}const o={};!function(){function e(e){this._entry=e,this._pact=null,this._resolve=null,this._return=null,this._promise=null}function r(e){return{value:e,done:!0}}function s(e){return{value:e,done:!1}}e.prototype[Symbol.asyncIterator||(Symbol.asyncIterator=Symbol("Symbol.asyncIterator"))]=function(){return this},e.prototype._yield=function(e){return this._resolve(e&&e.then?e.then(s):s(e)),this._pact=new t},e.prototype.next=function(e){const s=this;return s._promise=new Promise(function(i){const c=s._pact;if(null===c){const e=s._entry;if(null===e)return i(s._promise);function u(e){s._resolve(e&&e.then?e.then(r):r(e)),s._pact=null,s._resolve=null}s._entry=null,s._resolve=i,e(s).then(u,function(e){if(e===o)u(s._return);else{const n=new t;s._resolve(n),s._pact=null,s._resolve=null,_resolve(n,2,e)}})}else s._pact=null,s._resolve=i,n(c,1,e)})},e.prototype.return=function(e){const t=this;return t._promise=new Promise(function(s){const i=t._pact;if(null===i)return null===t._entry?s(t._promise):(t._entry=null,s(e&&e.then?e.then(r):r(e)));t._return=e,t._resolve=s,t._pact=null,n(i,2,o)})},e.prototype.throw=function(e){const t=this;return t._promise=new Promise(function(r,o){const s=t._pact;if(null===s)return null===t._entry?r(t._promise):(t._entry=null,o(e));t._resolve=r,t._pact=null,n(s,2,e)})}}();var s=4,i=function(e,t){this.options=t,this.commandId=1,this.commands={},this.eventListeners={},this.closeRequested=!1,this.setSocket(e)};i.prototype.setSocket=function(e){var t=this,n=this.socket;if(this.socket=e,e.addEventListener("message",function(e){return t._handleMessage(e)}),e.addEventListener("close",function(e){return t._handleClose(e)}),n){var r=this.commands;this.commandId=1,this.commands={},Object.keys(r).forEach(function(e){var t=r[e];"subscribe"in t&&t.subscribe().then(function(e){t.unsubscribe=e,t.resolve()})}),this.fireEvent("ready")}},i.prototype.addEventListener=function(e,t){var n=this.eventListeners[e];n||(n=this.eventListeners[e]=[]),n.push(t)},i.prototype.removeEventListener=function(e,t){var n=this.eventListeners[e];if(n){var r=n.indexOf(t);-1!==r&&n.splice(r,1)}},i.prototype.fireEvent=function(e,t){var n=this;(this.eventListeners[e]||[]).forEach(function(e){return e(n,t)})},i.prototype.close=function(){this.closeRequested=!0,this.socket.close()},i.prototype.subscribeEvents=function(e,t){try{return this.subscribeMessage(e,function(e){var t={type:"subscribe_events"};return e&&(t.event_type=e),t}(t))}catch(e){return Promise.reject(e)}},i.prototype.ping=function(){return this.sendMessagePromise({type:"ping"})},i.prototype.sendMessage=function(e,t){t||(t=this._genCmdId()),e.id=t,this.socket.send(JSON.stringify(e))},i.prototype.sendMessagePromise=function(e){var t=this;return new Promise(function(n,r){var o=t._genCmdId();t.commands[o]={resolve:n,reject:r},t.sendMessage(e,o)})},i.prototype.subscribeMessage=function(e,t){try{var n,r=this,o=r._genCmdId();return Promise.resolve(new Promise(function(s,i){n=r.commands[o]={resolve:s,reject:i,callback:e,subscribe:function(){return r.subscribeMessage(e,t)},unsubscribe:function(){try{return Promise.resolve(r.sendMessagePromise((e=o,{type:"unsubscribe_events",subscription:e}))).then(function(){delete r.commands[o]})}catch(e){return Promise.reject(e)}var e}};try{r.sendMessage(t,o)}catch(e){}})).then(function(){return function(){return n.unsubscribe()}})}catch(e){return Promise.reject(e)}},i.prototype._handleMessage=function(e){var t=JSON.parse(e.data);switch(t.type){case"event":this.commands[t.id].callback(t.event);break;case"result":if(t.id in this.commands){var n=this.commands[t.id];t.success?(n.resolve(t.result),"subscribe"in n||delete this.commands[t.id]):(n.reject(t.error),delete this.commands[t.id])}break;case"pong":this.commands[t.id].resolve(),delete this.commands[t.id]}},i.prototype._handleClose=function(e){var t=this;if(Object.keys(this.commands).forEach(function(e){var n=t.commands[e];"subscribe"in n||n.reject({type:"result",success:!1,error:{code:3,message:"Connection lost"}})}),!this.closeRequested){this.fireEvent("disconnected");var n=Object.assign({},this.options,{setupRetry:0}),o=function(e){var s=t;setTimeout(function(){try{var t=r(function(){return Promise.resolve(n.createSocket(n)).then(function(e){s.setSocket(e)})},function(t){2===t?s.fireEvent("reconnect-error",t):o(e+1)});return Promise.resolve(t&&t.then?t.then(function(){}):void 0)}catch(e){return Promise.reject(e)}},1e3*Math.min(e,5))};o(0)}},i.prototype._genCmdId=function(){return++this.commandId};var c=function(e,t,n){try{var r=new FormData;return r.append("client_id",t),Object.keys(n).forEach(function(e){r.append(e,n[e])}),Promise.resolve(fetch(e+"/auth/token",{method:"POST",credentials:"same-origin",body:r})).then(function(n){if(!n.ok)throw 400===n.status||403===n.status?2:new Error("Unable to fetch tokens");return Promise.resolve(n.json()).then(function(n){return n.hassUrl=e,n.clientId=t,n.expires=a(n.expires_in),n})})}catch(e){return Promise.reject(e)}},u=function(){return location.protocol+"//"+location.host+"/"},a=function(e){return 1e3*e+Date.now()},f=function(e,t){this.data=e,this._saveTokens=t},l={wsUrl:{configurable:!0},accessToken:{configurable:!0},expired:{configurable:!0}};l.wsUrl.get=function(){return"ws"+this.data.hassUrl.substr(4)+"/api/websocket"},l.accessToken.get=function(){return this.data.access_token},l.expired.get=function(){return Date.now()>this.data.expires},f.prototype.refreshAccessToken=function(){try{var e=this;return Promise.resolve(c(e.data.hassUrl,e.data.clientId,{grant_type:"refresh_token",refresh_token:e.data.refresh_token})).then(function(t){t.refresh_token=e.data.refresh_token,e.data=t,e._saveTokens&&e._saveTokens(t)})}catch(e){return Promise.reject(e)}},f.prototype.revoke=function(){try{var e=this,t=new FormData;return t.append("action","revoke"),t.append("token",e.data.refresh_token),Promise.resolve(fetch(e.data.hassUrl+"/auth/token",{method:"POST",credentials:"same-origin",body:t})).then(function(){e._saveTokens&&e._saveTokens(null)})}catch(e){return Promise.reject(e)}},Object.defineProperties(f.prototype,l);var h=function(e,t,n,r){if(e[t])return e[t];var o,s=0,i=function(e){var t=[];function n(n,r){e=r?n:Object.assign({},e,n);for(var o=t,s=0;s<o.length;s++)o[s](e)}return{get state(){return e},action:function(t){function r(e){n(e,!1)}return function(){for(var n=arguments,o=[e],s=0;s<arguments.length;s++)o.push(n[s]);var i=t.apply(this,o);if(null!=i)return i.then?i.then(r):r(i)}},setState:n,subscribe:function(e){return t.push(e),function(){!function(e){for(var n=[],r=0;r<t.length;r++)t[r]===e?e=null:n.push(t[r]);t=n}(e)}}}}(),c=function(){return n(e).then(function(e){return i.setState(e,!0)})};return e[t]={get state(){return i.state},refresh:c,subscribe:function(t){s||(s++,r&&(o=r(e,i)),e.addEventListener("ready",c),c().catch(function(t){if(e.socket.readyState==e.socket.OPEN)throw t}));var n=i.subscribe(t);return void 0!==i.state&&t(i.state),function(){n(),--s||(o&&o.then(function(e){e()}),e.removeEventListener("ready",c))}}},e[t]},d=function(e){return e.sendMessagePromise({type:"get_states"})},v=function(e){return e.sendMessagePromise({type:"get_services"})},p=function(e){return e.sendMessagePromise({type:"get_config"})};function m(e,t){return void 0===e?null:{components:e.components.concat(t.data.component)}}var _=function(e){return p(e)},b=function(e,t){return e.subscribeEvents(t.action(m),"component_loaded")};function y(e,t){var n,r;if(void 0===e)return null;var o=t.data,s=o.domain,i=Object.assign({},e[s],((n={})[o.service]={description:"",fields:{}},n));return(r={})[s]=i,r}function g(e,t){var n;if(void 0===e)return null;var r=t.data,o=r.domain,s=r.service,i=e[o];if(!(i&&s in i))return null;var c={};return Object.keys(i).forEach(function(e){e!==s&&(c[e]=i[e])}),(n={})[o]=c,n}var k=function(e){return v(e)},P=function(e,t){return Promise.all([e.subscribeEvents(t.action(y),"service_registered"),e.subscribeEvents(t.action(g),"service_removed")]).then(function(e){return function(){return e.forEach(function(e){return e()})}})},E=function(e){try{return Promise.resolve(d(e)).then(function(e){for(var t={},n=0;n<e.length;n++){var r=e[n];t[r.entity_id]=r}return t})}catch(e){return Promise.reject(e)}},S=function(e,t){return e.subscribeEvents(function(e){return function(t,n){var r,o=t.state;if(void 0!==o){var s=e.data,i=s.entity_id,c=s.new_state;if(c)t.setState(((r={})[c.entity_id]=c,r));else{var u=Object.assign({},o);delete u[i],t.setState(u,!0)}}}(t)},"state_changed")},w=function(e){return h(e,"_ent",E,S)},j={setupRetry:0,createSocket:function(e){if(!e.auth)throw s;var t=e.auth,n=e.WebSocket||WebSocket,o=t.expired?t.refreshAccessToken().then(function(){o=void 0},function(){o=void 0}):void 0,i=t.wsUrl;return new Promise(function(s,c){return function e(s,c,u){var a=new n(i),f=!1,l=function(){if(a.removeEventListener("close",l),f)u(2);else if(0!==s){var t=-1===s?-1:s-1;setTimeout(function(){return e(t,c,u)},1e3)}else u(1)},h=function(e){try{var n=r(function(){function e(){a.send(JSON.stringify({type:"auth",access_token:t.accessToken}))}var n=function(){if(t.expired)return Promise.resolve(o||t.refreshAccessToken()).then(function(){})}();return n&&n.then?n.then(e):e()},function(e){f=2===e,a.close()});return Promise.resolve(n&&n.then?n.then(function(){}):void 0)}catch(e){return Promise.reject(e)}},d=function(e){try{switch(JSON.parse(e.data).type){case"auth_invalid":f=!0,a.close();break;case"auth_ok":a.removeEventListener("open",h),a.removeEventListener("message",d),a.removeEventListener("close",l),a.removeEventListener("error",l),c(a)}return}catch(e){return Promise.reject(e)}};a.addEventListener("open",h),a.addEventListener("message",d),a.addEventListener("close",l),a.addEventListener("error",l)}(e.setupRetry,s,c)})}};e.createConnection=function(e){try{var t=Object.assign({},j,e);return Promise.resolve(t.createSocket(t)).then(function(e){return new i(e,t)})}catch(e){return Promise.reject(e)}},e.getAuth=function(e){void 0===e&&(e={});try{function t(){function t(){if(n)return new f(n,e.saveTokens);var t=e.hassUrl;if(void 0===t)throw s;"/"===t[t.length-1]&&(t=t.substr(0,t.length-1));var r=e.clientId||u();return function(e,t,n,r){n+=(n.includes("?")?"&":"?")+"auth_callback=1",document.location.href=function(e,t,n,r){var o=e+"/auth/authorize?response_type=code&client_id="+encodeURIComponent(t)+"&redirect_uri="+encodeURIComponent(n);return r&&(o+="&state="+encodeURIComponent(r)),o}(e,t,n,r)}(t,r,e.redirectUrl||location.protocol+"//"+location.host+location.pathname+location.search,btoa(JSON.stringify({hassUrl:t,clientId:r}))),new Promise(function(){})}var r=function(){if(!n&&e.loadTokens)return Promise.resolve(e.loadTokens()).then(function(e){n=e})}();return r&&r.then?r.then(t):t()}var n,o=function(e){for(var t={},n=location.search.substr(1).split("&"),r=0;r<n.length;r++){var o=n[r].split("="),s=decodeURIComponent(o[0]),i=o.length>1?decodeURIComponent(o[1]):void 0;t[s]=i}return t}(),i=function(){if("auth_callback"in o){var t=JSON.parse(atob(o.state)),s=r(function(){return Promise.resolve((r=t.hassUrl,s=t.clientId,i=o.code,c(r,s,{code:i,grant_type:"authorization_code"}))).then(function(t){n=t,e.saveTokens&&e.saveTokens(n)});var r,s,i},function(e){console.log("Unable to fetch access token",e)});if(s&&s.then)return s.then(function(){})}}();return Promise.resolve(i&&i.then?i.then(t):t())}catch(e){return Promise.reject(e)}},e.genClientId=u,e.genExpires=a,e.Auth=f,e.getCollection=h,e.createCollection=function(e,t,n,r,o){return h(r,e,t,n).subscribe(o)},e.Connection=i,e.subscribeConfig=function(e,t){return function(e){return h(e,"_cnf",_,b)}(e).subscribe(t)},e.subscribeServices=function(e,t){return function(e){return h(e,"_srv",k,P)}(e).subscribe(t)},e.entitiesColl=w,e.subscribeEntities=function(e,t){return w(e).subscribe(t)},e.ERR_CANNOT_CONNECT=1,e.ERR_INVALID_AUTH=2,e.ERR_CONNECTION_LOST=3,e.ERR_HASS_HOST_REQUIRED=s,e.getStates=d,e.getServices=v,e.getConfig=p,e.getUser=function(e){return e.sendMessagePromise({type:"auth/current_user"})},e.callService=function(e,t,n,r){return e.sendMessagePromise(function(e,t,n){var r={type:"call_service",domain:e,service:t};return n&&(r.service_data=n),r}(t,n,r))}}); | ||
//# sourceMappingURL=haws.umd.js.map |
import { Auth } from "./auth"; | ||
declare type Constructor<T> = { | ||
new (...args: unknown[]): T; | ||
}; | ||
export declare type Error = 1 | 2 | 3 | 4; | ||
@@ -8,2 +11,3 @@ export declare type UnsubscribeFunc = () => void; | ||
createSocket: (options: ConnectionOptions) => Promise<WebSocket>; | ||
WebSocket?: Constructor<WebSocket>; | ||
}; | ||
@@ -103,1 +107,2 @@ export declare type MessageBase = { | ||
}; | ||
export {}; |
@@ -5,3 +5,3 @@ { | ||
"sideEffects": false, | ||
"version": "3.3.0", | ||
"version": "3.4.0", | ||
"description": "Home Assistant websocket client", | ||
@@ -25,9 +25,10 @@ "source": "lib/index.ts", | ||
"devDependencies": { | ||
"@types/mocha": "^5.2.5", | ||
"husky": "^1.1.3", | ||
"lint-staged": "^8.0.4", | ||
"microbundle": "^0.7.0", | ||
"mocha": "^5.1.1", | ||
"prettier": "^1.14.3", | ||
"ts-node": "^7.0.1" | ||
"@types/mocha": "^5.2.6", | ||
"husky": "^1.3.1", | ||
"lint-staged": "^8.1.5", | ||
"microbundle": "^0.11.0", | ||
"mocha": "^6.0.2", | ||
"prettier": "^1.16.4", | ||
"ts-node": "^8.0.3", | ||
"typescript": "^3.3.3333" | ||
}, | ||
@@ -34,0 +35,0 @@ "files": [ |
@@ -105,2 +105,3 @@ # :aerial_tramway: JavaScript websocket client for Home Assistant | ||
| createSocket | Override the createSocket method with your own. `(options) => Promise<WebSocket>`. Needs to return a connection that is already authenticated. | | ||
| WebSocket | Constructor to use to initialize the WebSocket connection inside the built-in createSocket method. | | ||
| setupRetry | Number of times to retry initial connection when it fails. Set to -1 for infinite retries. Default is 0 (no retries) | | ||
@@ -375,3 +376,3 @@ | ||
To use this package in NodeJS, you will want to define your own `createSocket` method for `createConnection` to use. Your createSocket function will need to set up the web socket connection with Home Assistant and handle the auth. | ||
NodeJS does not have a WebSocket client built-in, but there are some good ones on NPM. We recommend `ws`. You can pass the WebSocket constructor to use as part of the options. | ||
@@ -382,12 +383,4 @@ ```js | ||
createConnection({ | ||
createSocket() { | ||
// Open connection | ||
const ws = new WebSocket("ws://localhost:8123"); | ||
// Functions to handle authentication with Home Assistant | ||
// Implement yourself :) | ||
return ws; | ||
} | ||
WebSocket | ||
}); | ||
``` |
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
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
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
291408
455
8
384