home-assistant-js-websocket
Advanced tools
Comparing version 4.1.0 to 4.1.1
@@ -20,8 +20,4 @@ import { ConnectionOptions, MessageBase } from "./types"; | ||
commandId: number; | ||
commands: { | ||
[commandId: number]: CommandInFlight; | ||
}; | ||
eventListeners: { | ||
[eventType: string]: ConnectionEventListener[]; | ||
}; | ||
commands: Map<number, CommandInFlight>; | ||
eventListeners: Map<string, ConnectionEventListener[]>; | ||
closeRequested: boolean; | ||
@@ -28,0 +24,0 @@ socket: WebSocket; |
@@ -1,2 +0,2 @@ | ||
function e(e,t){try{var n=e()}catch(e){return t(e)}return n&&n.then?n.then(void 0,t):n}var t=1,n=2,r=3,s=4;function o(e){return{type:"unsubscribe_events",subscription:e}}var 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 s=t._genCmdId();t.commands[s]={resolve:n,reject:r},t.sendMessage(e,s)})},i.prototype.subscribeMessage=function(e,t){try{var n,r=this,s=r._genCmdId();return Promise.resolve(new Promise(function(i,c){n=r.commands[s]={resolve:i,reject:c,callback:e,subscribe:function(){return r.subscribeMessage(e,t)},unsubscribe:function(){try{return Promise.resolve(r.sendMessagePromise(o(s))).then(function(){delete r.commands[s]})}catch(e){return Promise.reject(e)}}};try{r.sendMessage(t,s)}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),n=this.commands[t.id];switch(t.type){case"event":n?n.callback(t.event):(console.warn("Received event for unknown subscription "+t.id+". Unsubscribing."),this.sendMessagePromise(o(t.id)));break;case"result":n&&(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":n?(n.resolve(),delete this.commands[t.id]):console.warn("Received unknown pong response "+t.id)}},i.prototype._handleClose=function(t){var n=this;if(Object.keys(this.commands).forEach(function(e){var t=n.commands[e];"subscribe"in t||t.reject({type:"result",success:!1,error:{code:3,message:"Connection lost"}})}),!this.closeRequested){this.fireEvent("disconnected");var r=Object.assign({},this.options,{setupRetry:0}),s=function(t){var o=n;setTimeout(function(){try{var n=e(function(){return Promise.resolve(r.createSocket(r)).then(function(e){o.setSocket(e)})},function(e){2===e?o.fireEvent("reconnect-error",e):s(t+1)});return Promise.resolve(n&&n.then?n.then(function(){}):void 0)}catch(e){return Promise.reject(e)}},1e3*Math.min(t,5))};s(0)}},i.prototype._genCmdId=function(){return++this.commandId};var c=function(t){void 0===t&&(t={});try{function n(){function n(){function e(){if(r)return new d(r,t.saveTokens);if(void 0===o)throw s;return function(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)}(o,i,t.redirectUrl||location.protocol+"//"+location.host+location.pathname+location.search,btoa(JSON.stringify({hassUrl:o,clientId:i}))),new Promise(function(){})}var n=function(){if(!r&&t.loadTokens)return Promise.resolve(t.loadTokens()).then(function(e){r=e})}();return n&&n.then?n.then(e):e()}var c=function(){if(!r){var n=function(e){for(var t={},n=location.search.substr(1).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}(),s=function(){if("auth_callback"in n){var s=JSON.parse(atob(n.state)),o=e(function(){return Promise.resolve(h(s.hassUrl,s.clientId,n.code)).then(function(e){r=e,t.saveTokens&&t.saveTokens(r)})},function(e){console.log("Unable to fetch access token",e)});if(o&&o.then)return o.then(function(){})}}();if(s&&s.then)return s.then(function(){})}}();return c&&c.then?c.then(n):n()}var r,o=t.hassUrl;o&&"/"===o[o.length-1]&&(o=o.substr(0,o.length-1));var i=t.clientId||a(),c=function(){if(!r&&t.authCode&&o&&i){var n=e(function(){return Promise.resolve(h(o,i,t.authCode)).then(function(e){r=e,t.saveTokens&&t.saveTokens(r)})},function(e){console.log("Unable to fetch access token",e)});if(n&&n.then)return n.then(function(){})}}();return Promise.resolve(c&&c.then?c.then(n):n())}catch(e){return Promise.reject(e)}},u=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=f(n.expires_in),n})})}catch(e){return Promise.reject(e)}},a=function(){return location.protocol+"//"+location.host+"/"},f=function(e){return 1e3*e+Date.now()};function h(e,t,n){return u(e,t,{code:n,grant_type:"authorization_code"})}var 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(u(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 l=function(e,t,n,r){if(e[t])return e[t];var s,o=0,i=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=arguments,s=[e],o=0;o<arguments.length;o++)s.push(n[o]);var i=t.apply(this,s);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){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]},m=function(e,t,n,r,s){return l(r,e,t,n).subscribe(s)},p=function(e){return e.sendMessagePromise({type:"get_states"})},b=function(e){return e.sendMessagePromise({type:"get_services"})},g=function(e){return e.sendMessagePromise({type:"get_config"})},y=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 _(e,t){return void 0===e?null:{components:e.components.concat(t.data.component)}}var P=function(e){return g(e)},E=function(e,t){return e.subscribeEvents(t.action(_),"component_loaded")},w=function(e,t){return function(e){return l(e,"_cnf",P,E)}(e).subscribe(t)};function j(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 T(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 S=function(e){return b(e)},L=function(e,t){return Promise.all([e.subscribeEvents(t.action(j),"service_registered"),e.subscribeEvents(t.action(T),"service_removed")]).then(function(e){return function(){return e.forEach(function(e){return e()})}})},O=function(e,t){return function(e){return l(e,"_srv",S,L)}(e).subscribe(t)},U=function(e){try{return Promise.resolve(p(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,s=t.state;if(void 0!==s){var o=e.data,i=o.entity_id,c=o.new_state;if(c)t.setState(((r={})[c.entity_id]=c,r));else{var u=Object.assign({},s);delete u[i],t.setState(u,!0)}}}(t)},"state_changed")},I=function(e){return l(e,"_ent",U,M)},C=function(e,t){return I(e).subscribe(t)},R=function(e){try{var t=Object.assign({},x,e);return Promise.resolve(t.createSocket(t)).then(function(e){return new i(e,t)})}catch(e){return Promise.reject(e)}},x={setupRetry:0,createSocket:function(t){if(!t.auth)throw s;var n=t.auth,r=n.expired?n.refreshAccessToken().then(function(){r=void 0},function(){r=void 0}):void 0,o=n.wsUrl;return new Promise(function(s,i){return function t(s,i,c){var u=new WebSocket(o),a=!1,f=function(){if(u.removeEventListener("close",f),a)c(2);else if(0!==s){var e=-1===s?-1:s-1;setTimeout(function(){return t(e,i,c)},1e3)}else c(1)},h=function(t){try{var s=e(function(){function e(){u.send(JSON.stringify({type:"auth",access_token:n.accessToken}))}var t=function(){if(n.expired)return Promise.resolve(r||n.refreshAccessToken()).then(function(){})}();return t&&t.then?t.then(e):e()},function(e){a=2===e,u.close()});return Promise.resolve(s&&s.then?s.then(function(){}):void 0)}catch(e){return Promise.reject(e)}},d=function(e){try{switch(JSON.parse(e.data).type){case"auth_invalid":a=!0,u.close();break;case"auth_ok":u.removeEventListener("open",h),u.removeEventListener("message",d),u.removeEventListener("close",f),u.removeEventListener("error",f),i(u)}return}catch(e){return Promise.reject(e)}};u.addEventListener("open",h),u.addEventListener("message",d),u.addEventListener("close",f),u.addEventListener("error",f)}(t.setupRetry,s,i)})}};export{R as createConnection,c as getAuth,a as genClientId,f as genExpires,d as Auth,l as getCollection,m as createCollection,i as Connection,w as subscribeConfig,O as subscribeServices,I as entitiesColl,C as subscribeEntities,t as ERR_CANNOT_CONNECT,n as ERR_INVALID_AUTH,r as ERR_CONNECTION_LOST,s as ERR_HASS_HOST_REQUIRED,p as getStates,b as getServices,g as getConfig,y as getUser,k as callService}; | ||
function e(e,t){try{var n=e()}catch(e){return t(e)}return n&&n.then?n.then(void 0,t):n}var t=1,n=2,r=3,s=4;function o(e){return{type:"unsubscribe_events",subscription:e}}var i=function(e,t){this.options=t,this.commandId=1,this.commands=new Map,this.eventListeners=new Map,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=new Map,r.forEach(function(e){"subscribe"in e&&e.subscribe().then(function(t){e.unsubscribe=t,e.resolve()})}),this.fireEvent("ready")}},i.prototype.addEventListener=function(e,t){var n=this.eventListeners.get(e);n||this.eventListeners.set(e,n=[]),n.push(t)},i.prototype.removeEventListener=function(e,t){var n=this.eventListeners.get(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.get(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 s=t._genCmdId();t.commands.set(s,{resolve:n,reject:r}),t.sendMessage(e,s)})},i.prototype.subscribeMessage=function(e,t){try{var n,r=this,s=r._genCmdId();return Promise.resolve(new Promise(function(i,c){n={resolve:i,reject:c,callback:e,subscribe:function(){return r.subscribeMessage(e,t)},unsubscribe:function(){try{return Promise.resolve(r.sendMessagePromise(o(s))).then(function(){r.commands.delete(s)})}catch(e){return Promise.reject(e)}}},r.commands.set(s,n);try{r.sendMessage(t,s)}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),n=this.commands.get(t.id);switch(t.type){case"event":n?n.callback(t.event):(console.warn("Received event for unknown subscription "+t.id+". Unsubscribing."),this.sendMessagePromise(o(t.id)));break;case"result":n&&(t.success?(n.resolve(t.result),"subscribe"in n||this.commands.delete(t.id)):(n.reject(t.error),this.commands.delete(t.id)));break;case"pong":n?(n.resolve(),this.commands.delete(t.id)):console.warn("Received unknown pong response "+t.id)}},i.prototype._handleClose=function(t){var n=this;if(this.commands.forEach(function(e){"subscribe"in e||e.reject({type:"result",success:!1,error:{code:3,message:"Connection lost"}})}),!this.closeRequested){this.fireEvent("disconnected");var r=Object.assign({},this.options,{setupRetry:0}),s=function(t){var o=n;setTimeout(function(){try{var n=e(function(){return Promise.resolve(r.createSocket(r)).then(function(e){o.setSocket(e)})},function(e){2===e?o.fireEvent("reconnect-error",e):s(t+1)});return Promise.resolve(n&&n.then?n.then(function(){}):void 0)}catch(e){return Promise.reject(e)}},1e3*Math.min(t,5))};s(0)}},i.prototype._genCmdId=function(){return++this.commandId};var c=function(t){void 0===t&&(t={});try{function n(){function n(){function e(){if(r)return new d(r,t.saveTokens);if(void 0===o)throw s;return function(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)}(o,i,t.redirectUrl||location.protocol+"//"+location.host+location.pathname+location.search,btoa(JSON.stringify({hassUrl:o,clientId:i}))),new Promise(function(){})}var n=function(){if(!r&&t.loadTokens)return Promise.resolve(t.loadTokens()).then(function(e){r=e})}();return n&&n.then?n.then(e):e()}var c=function(){if(!r){var n=function(e){for(var t={},n=location.search.substr(1).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}(),s=function(){if("auth_callback"in n){var s=JSON.parse(atob(n.state)),o=e(function(){return Promise.resolve(h(s.hassUrl,s.clientId,n.code)).then(function(e){r=e,t.saveTokens&&t.saveTokens(r)})},function(e){console.log("Unable to fetch access token",e)});if(o&&o.then)return o.then(function(){})}}();if(s&&s.then)return s.then(function(){})}}();return c&&c.then?c.then(n):n()}var r,o=t.hassUrl;o&&"/"===o[o.length-1]&&(o=o.substr(0,o.length-1));var i=t.clientId||a(),c=function(){if(!r&&t.authCode&&o&&i){var n=e(function(){return Promise.resolve(h(o,i,t.authCode)).then(function(e){r=e,t.saveTokens&&t.saveTokens(r)})},function(e){console.log("Unable to fetch access token",e)});if(n&&n.then)return n.then(function(){})}}();return Promise.resolve(c&&c.then?c.then(n):n())}catch(e){return Promise.reject(e)}},u=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=f(n.expires_in),n})})}catch(e){return Promise.reject(e)}},a=function(){return location.protocol+"//"+location.host+"/"},f=function(e){return 1e3*e+Date.now()};function h(e,t,n){return u(e,t,{code:n,grant_type:"authorization_code"})}var 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(u(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 l=function(e,t,n,r){if(e[t])return e[t];var s,o=0,i=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=arguments,s=[e],o=0;o<arguments.length;o++)s.push(n[o]);var i=t.apply(this,s);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){1==++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]},m=function(e,t,n,r,s){return l(r,e,t,n).subscribe(s)},p=function(e){return e.sendMessagePromise({type:"get_states"})},b=function(e){return e.sendMessagePromise({type:"get_services"})},g=function(e){return e.sendMessagePromise({type:"get_config"})},y=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 _(e,t){return void 0===e?null:{components:e.components.concat(t.data.component)}}var P=function(e){return g(e)},E=function(e,t){return e.subscribeEvents(t.action(_),"component_loaded")},w=function(e,t){return function(e){return l(e,"_cnf",P,E)}(e).subscribe(t)};function j(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 T(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 M=function(e){return b(e)},S=function(e,t){return Promise.all([e.subscribeEvents(t.action(j),"service_registered"),e.subscribeEvents(t.action(T),"service_removed")]).then(function(e){return function(){return e.forEach(function(e){return e()})}})},L=function(e,t){return function(e){return l(e,"_srv",M,S)}(e).subscribe(t)},U=function(e){try{return Promise.resolve(p(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)}},O=function(e,t){return e.subscribeEvents(function(e){return function(t,n){var r,s=t.state;if(void 0!==s){var o=e.data,i=o.entity_id,c=o.new_state;if(c)t.setState(((r={})[c.entity_id]=c,r));else{var u=Object.assign({},s);delete u[i],t.setState(u,!0)}}}(t)},"state_changed")},I=function(e){return l(e,"_ent",U,O)},C=function(e,t){return I(e).subscribe(t)},R=function(e){try{var t=Object.assign({},x,e);return Promise.resolve(t.createSocket(t)).then(function(e){return new i(e,t)})}catch(e){return Promise.reject(e)}},x={setupRetry:0,createSocket:function(t){if(!t.auth)throw s;var n=t.auth,r=n.expired?n.refreshAccessToken().then(function(){r=void 0},function(){r=void 0}):void 0,o=n.wsUrl;return new Promise(function(s,i){return function t(s,i,c){var u=new WebSocket(o),a=!1,f=function(){if(u.removeEventListener("close",f),a)c(2);else if(0!==s){var e=-1===s?-1:s-1;setTimeout(function(){return t(e,i,c)},1e3)}else c(1)},h=function(t){try{var s=e(function(){function e(){u.send(JSON.stringify({type:"auth",access_token:n.accessToken}))}var t=function(){if(n.expired)return Promise.resolve(r||n.refreshAccessToken()).then(function(){})}();return t&&t.then?t.then(e):e()},function(e){a=2===e,u.close()});return Promise.resolve(s&&s.then?s.then(function(){}):void 0)}catch(e){return Promise.reject(e)}},d=function(e){try{switch(JSON.parse(e.data).type){case"auth_invalid":a=!0,u.close();break;case"auth_ok":u.removeEventListener("open",h),u.removeEventListener("message",d),u.removeEventListener("close",f),u.removeEventListener("error",f),i(u)}return}catch(e){return Promise.reject(e)}};u.addEventListener("open",h),u.addEventListener("message",d),u.addEventListener("close",f),u.addEventListener("error",f)}(t.setupRetry,s,i)})}};export{R as createConnection,c as getAuth,a as genClientId,f as genExpires,d as Auth,l as getCollection,m as createCollection,i as Connection,w as subscribeConfig,L as subscribeServices,I as entitiesColl,C as subscribeEntities,t as ERR_CANNOT_CONNECT,n as ERR_INVALID_AUTH,r as ERR_CONNECTION_LOST,s as ERR_HASS_HOST_REQUIRED,p as getStates,b as getServices,g as getConfig,y as getUser,k as callService}; | ||
//# sourceMappingURL=haws.es.js.map |
@@ -1,2 +0,2 @@ | ||
function e(e,t){try{var n=e()}catch(e){return t(e)}return n&&n.then?n.then(void 0,t):n}var t=4;function n(e){return{type:"unsubscribe_events",subscription:e}}var r=function(e,t){this.options=t,this.commandId=1,this.commands={},this.eventListeners={},this.closeRequested=!1,this.setSocket(e)};r.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")}},r.prototype.addEventListener=function(e,t){var n=this.eventListeners[e];n||(n=this.eventListeners[e]=[]),n.push(t)},r.prototype.removeEventListener=function(e,t){var n=this.eventListeners[e];if(n){var r=n.indexOf(t);-1!==r&&n.splice(r,1)}},r.prototype.fireEvent=function(e,t){var n=this;(this.eventListeners[e]||[]).forEach(function(e){return e(n,t)})},r.prototype.close=function(){this.closeRequested=!0,this.socket.close()},r.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)}},r.prototype.ping=function(){return this.sendMessagePromise({type:"ping"})},r.prototype.sendMessage=function(e,t){t||(t=this._genCmdId()),e.id=t,this.socket.send(JSON.stringify(e))},r.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)})},r.prototype.subscribeMessage=function(e,t){try{var r,s=this,o=s._genCmdId();return Promise.resolve(new Promise(function(i,c){r=s.commands[o]={resolve:i,reject:c,callback:e,subscribe:function(){return s.subscribeMessage(e,t)},unsubscribe:function(){try{return Promise.resolve(s.sendMessagePromise(n(o))).then(function(){delete s.commands[o]})}catch(e){return Promise.reject(e)}}};try{s.sendMessage(t,o)}catch(e){}})).then(function(){return function(){return r.unsubscribe()}})}catch(e){return Promise.reject(e)}},r.prototype._handleMessage=function(e){var t=JSON.parse(e.data),r=this.commands[t.id];switch(t.type){case"event":r?r.callback(t.event):(console.warn("Received event for unknown subscription "+t.id+". Unsubscribing."),this.sendMessagePromise(n(t.id)));break;case"result":r&&(t.success?(r.resolve(t.result),"subscribe"in r||delete this.commands[t.id]):(r.reject(t.error),delete this.commands[t.id]));break;case"pong":r?(r.resolve(),delete this.commands[t.id]):console.warn("Received unknown pong response "+t.id)}},r.prototype._handleClose=function(t){var n=this;if(Object.keys(this.commands).forEach(function(e){var t=n.commands[e];"subscribe"in t||t.reject({type:"result",success:!1,error:{code:3,message:"Connection lost"}})}),!this.closeRequested){this.fireEvent("disconnected");var r=Object.assign({},this.options,{setupRetry:0}),s=function(t){var o=n;setTimeout(function(){try{var n=e(function(){return Promise.resolve(r.createSocket(r)).then(function(e){o.setSocket(e)})},function(e){2===e?o.fireEvent("reconnect-error",e):s(t+1)});return Promise.resolve(n&&n.then?n.then(function(){}):void 0)}catch(e){return Promise.reject(e)}},1e3*Math.min(t,5))};s(0)}},r.prototype._genCmdId=function(){return++this.commandId};var s=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=i(n.expires_in),n})})}catch(e){return Promise.reject(e)}},o=function(){return location.protocol+"//"+location.host+"/"},i=function(e){return 1e3*e+Date.now()};function c(e,t,n){return s(e,t,{code:n,grant_type:"authorization_code"})}var u=function(e,t){this.data=e,this._saveTokens=t},a={wsUrl:{configurable:!0},accessToken:{configurable:!0},expired:{configurable:!0}};a.wsUrl.get=function(){return"ws"+this.data.hassUrl.substr(4)+"/api/websocket"},a.accessToken.get=function(){return this.data.access_token},a.expired.get=function(){return Date.now()>this.data.expires},u.prototype.refreshAccessToken=function(){try{var e=this;return Promise.resolve(s(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)}},u.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(u.prototype,a);var f=function(e,t,n,r){if(e[t])return e[t];var s,o=0,i=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=arguments,s=[e],o=0;o<arguments.length;o++)s.push(n[o]);var i=t.apply(this,s);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){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]},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 l(e,t){return void 0===e?null:{components:e.components.concat(t.data.component)}}var p=function(e){return v(e)},m=function(e,t){return e.subscribeEvents(t.action(l),"component_loaded")};function b(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 g(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 y=function(e){return d(e)},k=function(e,t){return Promise.all([e.subscribeEvents(t.action(b),"service_registered"),e.subscribeEvents(t.action(g),"service_removed")]).then(function(e){return function(){return e.forEach(function(e){return e()})}})},_=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)}},P=function(e,t){return e.subscribeEvents(function(e){return function(t,n){var r,s=t.state;if(void 0!==s){var o=e.data,i=o.entity_id,c=o.new_state;if(c)t.setState(((r={})[c.entity_id]=c,r));else{var u=Object.assign({},s);delete u[i],t.setState(u,!0)}}}(t)},"state_changed")},E=function(e){return f(e,"_ent",_,P)},x={setupRetry:0,createSocket:function(n){if(!n.auth)throw t;var r=n.auth,s=r.expired?r.refreshAccessToken().then(function(){s=void 0},function(){s=void 0}):void 0,o=r.wsUrl;return new Promise(function(t,i){return function t(n,i,c){var u=new WebSocket(o),a=!1,f=function(){if(u.removeEventListener("close",f),a)c(2);else if(0!==n){var e=-1===n?-1:n-1;setTimeout(function(){return t(e,i,c)},1e3)}else c(1)},h=function(t){try{var n=e(function(){function e(){u.send(JSON.stringify({type:"auth",access_token:r.accessToken}))}var t=function(){if(r.expired)return Promise.resolve(s||r.refreshAccessToken()).then(function(){})}();return t&&t.then?t.then(e):e()},function(e){a=2===e,u.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":a=!0,u.close();break;case"auth_ok":u.removeEventListener("open",h),u.removeEventListener("message",d),u.removeEventListener("close",f),u.removeEventListener("error",f),i(u)}return}catch(e){return Promise.reject(e)}};u.addEventListener("open",h),u.addEventListener("message",d),u.addEventListener("close",f),u.addEventListener("error",f)}(n.setupRetry,t,i)})}};exports.createConnection=function(e){try{var t=Object.assign({},x,e);return Promise.resolve(t.createSocket(t)).then(function(e){return new r(e,t)})}catch(e){return Promise.reject(e)}},exports.getAuth=function(n){void 0===n&&(n={});try{function r(){function r(){function e(){if(s)return new u(s,n.saveTokens);if(void 0===i)throw t;return function(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)}(i,a,n.redirectUrl||location.protocol+"//"+location.host+location.pathname+location.search,btoa(JSON.stringify({hassUrl:i,clientId:a}))),new Promise(function(){})}var r=function(){if(!s&&n.loadTokens)return Promise.resolve(n.loadTokens()).then(function(e){s=e})}();return r&&r.then?r.then(e):e()}var o=function(){if(!s){var t=function(e){for(var t={},n=location.search.substr(1).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}(),r=function(){if("auth_callback"in t){var r=JSON.parse(atob(t.state)),o=e(function(){return Promise.resolve(c(r.hassUrl,r.clientId,t.code)).then(function(e){s=e,n.saveTokens&&n.saveTokens(s)})},function(e){console.log("Unable to fetch access token",e)});if(o&&o.then)return o.then(function(){})}}();if(r&&r.then)return r.then(function(){})}}();return o&&o.then?o.then(r):r()}var s,i=n.hassUrl;i&&"/"===i[i.length-1]&&(i=i.substr(0,i.length-1));var a=n.clientId||o(),f=function(){if(!s&&n.authCode&&i&&a){var t=e(function(){return Promise.resolve(c(i,a,n.authCode)).then(function(e){s=e,n.saveTokens&&n.saveTokens(s)})},function(e){console.log("Unable to fetch access token",e)});if(t&&t.then)return t.then(function(){})}}();return Promise.resolve(f&&f.then?f.then(r):r())}catch(e){return Promise.reject(e)}},exports.genClientId=o,exports.genExpires=i,exports.Auth=u,exports.getCollection=f,exports.createCollection=function(e,t,n,r,s){return f(r,e,t,n).subscribe(s)},exports.Connection=r,exports.subscribeConfig=function(e,t){return function(e){return f(e,"_cnf",p,m)}(e).subscribe(t)},exports.subscribeServices=function(e,t){return function(e){return f(e,"_srv",y,k)}(e).subscribe(t)},exports.entitiesColl=E,exports.subscribeEntities=function(e,t){return E(e).subscribe(t)},exports.ERR_CANNOT_CONNECT=1,exports.ERR_INVALID_AUTH=2,exports.ERR_CONNECTION_LOST=3,exports.ERR_HASS_HOST_REQUIRED=t,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))}; | ||
function e(e,t){try{var n=e()}catch(e){return t(e)}return n&&n.then?n.then(void 0,t):n}var t=4;function n(e){return{type:"unsubscribe_events",subscription:e}}var r=function(e,t){this.options=t,this.commandId=1,this.commands=new Map,this.eventListeners=new Map,this.closeRequested=!1,this.setSocket(e)};r.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=new Map,r.forEach(function(e){"subscribe"in e&&e.subscribe().then(function(t){e.unsubscribe=t,e.resolve()})}),this.fireEvent("ready")}},r.prototype.addEventListener=function(e,t){var n=this.eventListeners.get(e);n||this.eventListeners.set(e,n=[]),n.push(t)},r.prototype.removeEventListener=function(e,t){var n=this.eventListeners.get(e);if(n){var r=n.indexOf(t);-1!==r&&n.splice(r,1)}},r.prototype.fireEvent=function(e,t){var n=this;(this.eventListeners.get(e)||[]).forEach(function(e){return e(n,t)})},r.prototype.close=function(){this.closeRequested=!0,this.socket.close()},r.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)}},r.prototype.ping=function(){return this.sendMessagePromise({type:"ping"})},r.prototype.sendMessage=function(e,t){t||(t=this._genCmdId()),e.id=t,this.socket.send(JSON.stringify(e))},r.prototype.sendMessagePromise=function(e){var t=this;return new Promise(function(n,r){var s=t._genCmdId();t.commands.set(s,{resolve:n,reject:r}),t.sendMessage(e,s)})},r.prototype.subscribeMessage=function(e,t){try{var r,s=this,o=s._genCmdId();return Promise.resolve(new Promise(function(i,c){r={resolve:i,reject:c,callback:e,subscribe:function(){return s.subscribeMessage(e,t)},unsubscribe:function(){try{return Promise.resolve(s.sendMessagePromise(n(o))).then(function(){s.commands.delete(o)})}catch(e){return Promise.reject(e)}}},s.commands.set(o,r);try{s.sendMessage(t,o)}catch(e){}})).then(function(){return function(){return r.unsubscribe()}})}catch(e){return Promise.reject(e)}},r.prototype._handleMessage=function(e){var t=JSON.parse(e.data),r=this.commands.get(t.id);switch(t.type){case"event":r?r.callback(t.event):(console.warn("Received event for unknown subscription "+t.id+". Unsubscribing."),this.sendMessagePromise(n(t.id)));break;case"result":r&&(t.success?(r.resolve(t.result),"subscribe"in r||this.commands.delete(t.id)):(r.reject(t.error),this.commands.delete(t.id)));break;case"pong":r?(r.resolve(),this.commands.delete(t.id)):console.warn("Received unknown pong response "+t.id)}},r.prototype._handleClose=function(t){var n=this;if(this.commands.forEach(function(e){"subscribe"in e||e.reject({type:"result",success:!1,error:{code:3,message:"Connection lost"}})}),!this.closeRequested){this.fireEvent("disconnected");var r=Object.assign({},this.options,{setupRetry:0}),s=function(t){var o=n;setTimeout(function(){try{var n=e(function(){return Promise.resolve(r.createSocket(r)).then(function(e){o.setSocket(e)})},function(e){2===e?o.fireEvent("reconnect-error",e):s(t+1)});return Promise.resolve(n&&n.then?n.then(function(){}):void 0)}catch(e){return Promise.reject(e)}},1e3*Math.min(t,5))};s(0)}},r.prototype._genCmdId=function(){return++this.commandId};var s=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=i(n.expires_in),n})})}catch(e){return Promise.reject(e)}},o=function(){return location.protocol+"//"+location.host+"/"},i=function(e){return 1e3*e+Date.now()};function c(e,t,n){return s(e,t,{code:n,grant_type:"authorization_code"})}var u=function(e,t){this.data=e,this._saveTokens=t},a={wsUrl:{configurable:!0},accessToken:{configurable:!0},expired:{configurable:!0}};a.wsUrl.get=function(){return"ws"+this.data.hassUrl.substr(4)+"/api/websocket"},a.accessToken.get=function(){return this.data.access_token},a.expired.get=function(){return Date.now()>this.data.expires},u.prototype.refreshAccessToken=function(){try{var e=this;return Promise.resolve(s(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)}},u.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(u.prototype,a);var f=function(e,t,n,r){if(e[t])return e[t];var s,o=0,i=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=arguments,s=[e],o=0;o<arguments.length;o++)s.push(n[o]);var i=t.apply(this,s);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){1==++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]},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 l(e,t){return void 0===e?null:{components:e.components.concat(t.data.component)}}var p=function(e){return v(e)},m=function(e,t){return e.subscribeEvents(t.action(l),"component_loaded")};function b(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 g(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 y=function(e){return d(e)},_=function(e,t){return Promise.all([e.subscribeEvents(t.action(b),"service_registered"),e.subscribeEvents(t.action(g),"service_removed")]).then(function(e){return function(){return e.forEach(function(e){return e()})}})},k=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)}},P=function(e,t){return e.subscribeEvents(function(e){return function(t,n){var r,s=t.state;if(void 0!==s){var o=e.data,i=o.entity_id,c=o.new_state;if(c)t.setState(((r={})[c.entity_id]=c,r));else{var u=Object.assign({},s);delete u[i],t.setState(u,!0)}}}(t)},"state_changed")},E=function(e){return f(e,"_ent",k,P)},w={setupRetry:0,createSocket:function(n){if(!n.auth)throw t;var r=n.auth,s=r.expired?r.refreshAccessToken().then(function(){s=void 0},function(){s=void 0}):void 0,o=r.wsUrl;return new Promise(function(t,i){return function t(n,i,c){var u=new WebSocket(o),a=!1,f=function(){if(u.removeEventListener("close",f),a)c(2);else if(0!==n){var e=-1===n?-1:n-1;setTimeout(function(){return t(e,i,c)},1e3)}else c(1)},h=function(t){try{var n=e(function(){function e(){u.send(JSON.stringify({type:"auth",access_token:r.accessToken}))}var t=function(){if(r.expired)return Promise.resolve(s||r.refreshAccessToken()).then(function(){})}();return t&&t.then?t.then(e):e()},function(e){a=2===e,u.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":a=!0,u.close();break;case"auth_ok":u.removeEventListener("open",h),u.removeEventListener("message",d),u.removeEventListener("close",f),u.removeEventListener("error",f),i(u)}return}catch(e){return Promise.reject(e)}};u.addEventListener("open",h),u.addEventListener("message",d),u.addEventListener("close",f),u.addEventListener("error",f)}(n.setupRetry,t,i)})}};exports.createConnection=function(e){try{var t=Object.assign({},w,e);return Promise.resolve(t.createSocket(t)).then(function(e){return new r(e,t)})}catch(e){return Promise.reject(e)}},exports.getAuth=function(n){void 0===n&&(n={});try{function r(){function r(){function e(){if(s)return new u(s,n.saveTokens);if(void 0===i)throw t;return function(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)}(i,a,n.redirectUrl||location.protocol+"//"+location.host+location.pathname+location.search,btoa(JSON.stringify({hassUrl:i,clientId:a}))),new Promise(function(){})}var r=function(){if(!s&&n.loadTokens)return Promise.resolve(n.loadTokens()).then(function(e){s=e})}();return r&&r.then?r.then(e):e()}var o=function(){if(!s){var t=function(e){for(var t={},n=location.search.substr(1).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}(),r=function(){if("auth_callback"in t){var r=JSON.parse(atob(t.state)),o=e(function(){return Promise.resolve(c(r.hassUrl,r.clientId,t.code)).then(function(e){s=e,n.saveTokens&&n.saveTokens(s)})},function(e){console.log("Unable to fetch access token",e)});if(o&&o.then)return o.then(function(){})}}();if(r&&r.then)return r.then(function(){})}}();return o&&o.then?o.then(r):r()}var s,i=n.hassUrl;i&&"/"===i[i.length-1]&&(i=i.substr(0,i.length-1));var a=n.clientId||o(),f=function(){if(!s&&n.authCode&&i&&a){var t=e(function(){return Promise.resolve(c(i,a,n.authCode)).then(function(e){s=e,n.saveTokens&&n.saveTokens(s)})},function(e){console.log("Unable to fetch access token",e)});if(t&&t.then)return t.then(function(){})}}();return Promise.resolve(f&&f.then?f.then(r):r())}catch(e){return Promise.reject(e)}},exports.genClientId=o,exports.genExpires=i,exports.Auth=u,exports.getCollection=f,exports.createCollection=function(e,t,n,r,s){return f(r,e,t,n).subscribe(s)},exports.Connection=r,exports.subscribeConfig=function(e,t){return function(e){return f(e,"_cnf",p,m)}(e).subscribe(t)},exports.subscribeServices=function(e,t){return function(e){return f(e,"_srv",y,_)}(e).subscribe(t)},exports.entitiesColl=E,exports.subscribeEntities=function(e,t){return E(e).subscribe(t)},exports.ERR_CANNOT_CONNECT=1,exports.ERR_INVALID_AUTH=2,exports.ERR_CONNECTION_LOST=3,exports.ERR_HASS_HOST_REQUIRED=t,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){try{var n=e()}catch(e){return t(e)}return n&&n.then?n.then(void 0,t):n}var n=4;function r(e){return{type:"unsubscribe_events",subscription:e}}var 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 s=t._genCmdId();t.commands[s]={resolve:n,reject:r},t.sendMessage(e,s)})},s.prototype.subscribeMessage=function(e,t){try{var n,s=this,o=s._genCmdId();return Promise.resolve(new Promise(function(i,c){n=s.commands[o]={resolve:i,reject:c,callback:e,subscribe:function(){return s.subscribeMessage(e,t)},unsubscribe:function(){try{return Promise.resolve(s.sendMessagePromise(r(o))).then(function(){delete s.commands[o]})}catch(e){return Promise.reject(e)}}};try{s.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),n=this.commands[t.id];switch(t.type){case"event":n?n.callback(t.event):(console.warn("Received event for unknown subscription "+t.id+". Unsubscribing."),this.sendMessagePromise(r(t.id)));break;case"result":n&&(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":n?(n.resolve(),delete this.commands[t.id]):console.warn("Received unknown pong response "+t.id)}},s.prototype._handleClose=function(e){var n=this;if(Object.keys(this.commands).forEach(function(e){var t=n.commands[e];"subscribe"in t||t.reject({type:"result",success:!1,error:{code:3,message:"Connection lost"}})}),!this.closeRequested){this.fireEvent("disconnected");var r=Object.assign({},this.options,{setupRetry:0}),s=function(e){var o=n;setTimeout(function(){try{var n=t(function(){return Promise.resolve(r.createSocket(r)).then(function(e){o.setSocket(e)})},function(t){2===t?o.fireEvent("reconnect-error",t):s(e+1)});return Promise.resolve(n&&n.then?n.then(function(){}):void 0)}catch(e){return Promise.reject(e)}},1e3*Math.min(e,5))};s(0)}},s.prototype._genCmdId=function(){return++this.commandId};var o=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=c(n.expires_in),n})})}catch(e){return Promise.reject(e)}},i=function(){return location.protocol+"//"+location.host+"/"},c=function(e){return 1e3*e+Date.now()};function u(e,t,n){return o(e,t,{code:n,grant_type:"authorization_code"})}var 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(o(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 d=function(e,t,n,r){if(e[t])return e[t];var s,o=0,i=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=arguments,s=[e],o=0;o<arguments.length;o++)s.push(n[o]);var i=t.apply(this,s);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){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]},h=function(e){return e.sendMessagePromise({type:"get_states"})},v=function(e){return e.sendMessagePromise({type:"get_services"})},l=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 p=function(e){return l(e)},b=function(e,t){return e.subscribeEvents(t.action(m),"component_loaded")};function g(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 y(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 k=function(e){return v(e)},_=function(e,t){return Promise.all([e.subscribeEvents(t.action(g),"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,s=t.state;if(void 0!==s){var o=e.data,i=o.entity_id,c=o.new_state;if(c)t.setState(((r={})[c.entity_id]=c,r));else{var u=Object.assign({},s);delete u[i],t.setState(u,!0)}}}(t)},"state_changed")},S=function(e){return d(e,"_ent",P,E)},j={setupRetry:0,createSocket:function(e){if(!e.auth)throw n;var r=e.auth,s=r.expired?r.refreshAccessToken().then(function(){s=void 0},function(){s=void 0}):void 0,o=r.wsUrl;return new Promise(function(n,i){return function e(n,i,c){var u=new WebSocket(o),a=!1,f=function(){if(u.removeEventListener("close",f),a)c(2);else if(0!==n){var t=-1===n?-1:n-1;setTimeout(function(){return e(t,i,c)},1e3)}else c(1)},d=function(e){try{var n=t(function(){function e(){u.send(JSON.stringify({type:"auth",access_token:r.accessToken}))}var t=function(){if(r.expired)return Promise.resolve(s||r.refreshAccessToken()).then(function(){})}();return t&&t.then?t.then(e):e()},function(e){a=2===e,u.close()});return Promise.resolve(n&&n.then?n.then(function(){}):void 0)}catch(e){return Promise.reject(e)}},h=function(e){try{switch(JSON.parse(e.data).type){case"auth_invalid":a=!0,u.close();break;case"auth_ok":u.removeEventListener("open",d),u.removeEventListener("message",h),u.removeEventListener("close",f),u.removeEventListener("error",f),i(u)}return}catch(e){return Promise.reject(e)}};u.addEventListener("open",d),u.addEventListener("message",h),u.addEventListener("close",f),u.addEventListener("error",f)}(e.setupRetry,n,i)})}};e.createConnection=function(e){try{var t=Object.assign({},j,e);return Promise.resolve(t.createSocket(t)).then(function(e){return new s(e,t)})}catch(e){return Promise.reject(e)}},e.getAuth=function(e){void 0===e&&(e={});try{function r(){function r(){function t(){if(s)return new a(s,e.saveTokens);if(void 0===o)throw n;return function(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)}(o,c,e.redirectUrl||location.protocol+"//"+location.host+location.pathname+location.search,btoa(JSON.stringify({hassUrl:o,clientId:c}))),new Promise(function(){})}var r=function(){if(!s&&e.loadTokens)return Promise.resolve(e.loadTokens()).then(function(e){s=e})}();return r&&r.then?r.then(t):t()}var i=function(){if(!s){var n=function(e){for(var t={},n=location.search.substr(1).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}(),r=function(){if("auth_callback"in n){var r=JSON.parse(atob(n.state)),o=t(function(){return Promise.resolve(u(r.hassUrl,r.clientId,n.code)).then(function(t){s=t,e.saveTokens&&e.saveTokens(s)})},function(e){console.log("Unable to fetch access token",e)});if(o&&o.then)return o.then(function(){})}}();if(r&&r.then)return r.then(function(){})}}();return i&&i.then?i.then(r):r()}var s,o=e.hassUrl;o&&"/"===o[o.length-1]&&(o=o.substr(0,o.length-1));var c=e.clientId||i(),f=function(){if(!s&&e.authCode&&o&&c){var n=t(function(){return Promise.resolve(u(o,c,e.authCode)).then(function(t){s=t,e.saveTokens&&e.saveTokens(s)})},function(e){console.log("Unable to fetch access token",e)});if(n&&n.then)return n.then(function(){})}}();return Promise.resolve(f&&f.then?f.then(r):r())}catch(e){return Promise.reject(e)}},e.genClientId=i,e.genExpires=c,e.Auth=a,e.getCollection=d,e.createCollection=function(e,t,n,r,s){return d(r,e,t,n).subscribe(s)},e.Connection=s,e.subscribeConfig=function(e,t){return function(e){return d(e,"_cnf",p,b)}(e).subscribe(t)},e.subscribeServices=function(e,t){return function(e){return d(e,"_srv",k,_)}(e).subscribe(t)},e.entitiesColl=S,e.subscribeEntities=function(e,t){return S(e).subscribe(t)},e.ERR_CANNOT_CONNECT=1,e.ERR_INVALID_AUTH=2,e.ERR_CONNECTION_LOST=3,e.ERR_HASS_HOST_REQUIRED=n,e.getStates=h,e.getServices=v,e.getConfig=l,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){function t(e,t){try{var n=e()}catch(e){return t(e)}return n&&n.then?n.then(void 0,t):n}var n=4;function r(e){return{type:"unsubscribe_events",subscription:e}}var s=function(e,t){this.options=t,this.commandId=1,this.commands=new Map,this.eventListeners=new Map,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=new Map,r.forEach(function(e){"subscribe"in e&&e.subscribe().then(function(t){e.unsubscribe=t,e.resolve()})}),this.fireEvent("ready")}},s.prototype.addEventListener=function(e,t){var n=this.eventListeners.get(e);n||this.eventListeners.set(e,n=[]),n.push(t)},s.prototype.removeEventListener=function(e,t){var n=this.eventListeners.get(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.get(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 s=t._genCmdId();t.commands.set(s,{resolve:n,reject:r}),t.sendMessage(e,s)})},s.prototype.subscribeMessage=function(e,t){try{var n,s=this,o=s._genCmdId();return Promise.resolve(new Promise(function(i,c){n={resolve:i,reject:c,callback:e,subscribe:function(){return s.subscribeMessage(e,t)},unsubscribe:function(){try{return Promise.resolve(s.sendMessagePromise(r(o))).then(function(){s.commands.delete(o)})}catch(e){return Promise.reject(e)}}},s.commands.set(o,n);try{s.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),n=this.commands.get(t.id);switch(t.type){case"event":n?n.callback(t.event):(console.warn("Received event for unknown subscription "+t.id+". Unsubscribing."),this.sendMessagePromise(r(t.id)));break;case"result":n&&(t.success?(n.resolve(t.result),"subscribe"in n||this.commands.delete(t.id)):(n.reject(t.error),this.commands.delete(t.id)));break;case"pong":n?(n.resolve(),this.commands.delete(t.id)):console.warn("Received unknown pong response "+t.id)}},s.prototype._handleClose=function(e){var n=this;if(this.commands.forEach(function(e){"subscribe"in e||e.reject({type:"result",success:!1,error:{code:3,message:"Connection lost"}})}),!this.closeRequested){this.fireEvent("disconnected");var r=Object.assign({},this.options,{setupRetry:0}),s=function(e){var o=n;setTimeout(function(){try{var n=t(function(){return Promise.resolve(r.createSocket(r)).then(function(e){o.setSocket(e)})},function(t){2===t?o.fireEvent("reconnect-error",t):s(e+1)});return Promise.resolve(n&&n.then?n.then(function(){}):void 0)}catch(e){return Promise.reject(e)}},1e3*Math.min(e,5))};s(0)}},s.prototype._genCmdId=function(){return++this.commandId};var o=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=c(n.expires_in),n})})}catch(e){return Promise.reject(e)}},i=function(){return location.protocol+"//"+location.host+"/"},c=function(e){return 1e3*e+Date.now()};function u(e,t,n){return o(e,t,{code:n,grant_type:"authorization_code"})}var 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(o(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 d=function(e,t,n,r){if(e[t])return e[t];var s,o=0,i=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=arguments,s=[e],o=0;o<arguments.length;o++)s.push(n[o]);var i=t.apply(this,s);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){1==++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]},h=function(e){return e.sendMessagePromise({type:"get_states"})},v=function(e){return e.sendMessagePromise({type:"get_services"})},l=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 l(e)},b=function(e,t){return e.subscribeEvents(t.action(p),"component_loaded")};function g(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 y(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 _=function(e){return v(e)},k=function(e,t){return Promise.all([e.subscribeEvents(t.action(g),"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,s=t.state;if(void 0!==s){var o=e.data,i=o.entity_id,c=o.new_state;if(c)t.setState(((r={})[c.entity_id]=c,r));else{var u=Object.assign({},s);delete u[i],t.setState(u,!0)}}}(t)},"state_changed")},w=function(e){return d(e,"_ent",P,E)},S={setupRetry:0,createSocket:function(e){if(!e.auth)throw n;var r=e.auth,s=r.expired?r.refreshAccessToken().then(function(){s=void 0},function(){s=void 0}):void 0,o=r.wsUrl;return new Promise(function(n,i){return function e(n,i,c){var u=new WebSocket(o),a=!1,f=function(){if(u.removeEventListener("close",f),a)c(2);else if(0!==n){var t=-1===n?-1:n-1;setTimeout(function(){return e(t,i,c)},1e3)}else c(1)},d=function(e){try{var n=t(function(){function e(){u.send(JSON.stringify({type:"auth",access_token:r.accessToken}))}var t=function(){if(r.expired)return Promise.resolve(s||r.refreshAccessToken()).then(function(){})}();return t&&t.then?t.then(e):e()},function(e){a=2===e,u.close()});return Promise.resolve(n&&n.then?n.then(function(){}):void 0)}catch(e){return Promise.reject(e)}},h=function(e){try{switch(JSON.parse(e.data).type){case"auth_invalid":a=!0,u.close();break;case"auth_ok":u.removeEventListener("open",d),u.removeEventListener("message",h),u.removeEventListener("close",f),u.removeEventListener("error",f),i(u)}return}catch(e){return Promise.reject(e)}};u.addEventListener("open",d),u.addEventListener("message",h),u.addEventListener("close",f),u.addEventListener("error",f)}(e.setupRetry,n,i)})}};e.createConnection=function(e){try{var t=Object.assign({},S,e);return Promise.resolve(t.createSocket(t)).then(function(e){return new s(e,t)})}catch(e){return Promise.reject(e)}},e.getAuth=function(e){void 0===e&&(e={});try{function r(){function r(){function t(){if(s)return new a(s,e.saveTokens);if(void 0===o)throw n;return function(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)}(o,c,e.redirectUrl||location.protocol+"//"+location.host+location.pathname+location.search,btoa(JSON.stringify({hassUrl:o,clientId:c}))),new Promise(function(){})}var r=function(){if(!s&&e.loadTokens)return Promise.resolve(e.loadTokens()).then(function(e){s=e})}();return r&&r.then?r.then(t):t()}var i=function(){if(!s){var n=function(e){for(var t={},n=location.search.substr(1).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}(),r=function(){if("auth_callback"in n){var r=JSON.parse(atob(n.state)),o=t(function(){return Promise.resolve(u(r.hassUrl,r.clientId,n.code)).then(function(t){s=t,e.saveTokens&&e.saveTokens(s)})},function(e){console.log("Unable to fetch access token",e)});if(o&&o.then)return o.then(function(){})}}();if(r&&r.then)return r.then(function(){})}}();return i&&i.then?i.then(r):r()}var s,o=e.hassUrl;o&&"/"===o[o.length-1]&&(o=o.substr(0,o.length-1));var c=e.clientId||i(),f=function(){if(!s&&e.authCode&&o&&c){var n=t(function(){return Promise.resolve(u(o,c,e.authCode)).then(function(t){s=t,e.saveTokens&&e.saveTokens(s)})},function(e){console.log("Unable to fetch access token",e)});if(n&&n.then)return n.then(function(){})}}();return Promise.resolve(f&&f.then?f.then(r):r())}catch(e){return Promise.reject(e)}},e.genClientId=i,e.genExpires=c,e.Auth=a,e.getCollection=d,e.createCollection=function(e,t,n,r,s){return d(r,e,t,n).subscribe(s)},e.Connection=s,e.subscribeConfig=function(e,t){return function(e){return d(e,"_cnf",m,b)}(e).subscribe(t)},e.subscribeServices=function(e,t){return function(e){return d(e,"_srv",_,k)}(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=n,e.getStates=h,e.getServices=v,e.getConfig=l,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 |
@@ -5,3 +5,3 @@ { | ||
"sideEffects": false, | ||
"version": "4.1.0", | ||
"version": "4.1.1", | ||
"description": "Home Assistant websocket client", | ||
@@ -8,0 +8,0 @@ "source": "lib/index.ts", |
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
281219
432