home-assistant-js-websocket
Advanced tools
Comparing version 4.3.1 to 4.4.0
export declare type AuthData = { | ||
hassUrl: string; | ||
clientId: string; | ||
clientId: string | null; | ||
expires: number; | ||
@@ -13,3 +13,3 @@ refresh_token: string; | ||
hassUrl?: string; | ||
clientId?: string; | ||
clientId?: string | null; | ||
redirectUrl?: string; | ||
@@ -16,0 +16,0 @@ authCode?: string; |
@@ -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}"undefined"!=typeof Symbol&&(Symbol.iterator||(Symbol.iterator=Symbol("Symbol.iterator"))),"undefined"!=typeof Symbol&&(Symbol.asyncIterator||(Symbol.asyncIterator=Symbol("Symbol.asyncIterator")));var t=1,n=2,r=3,o=4,s=5;function i(e){return{type:"unsubscribe_events",subscription:e}}var c=function(e,t){this.options=t,this.commandId=1,this.commands=new Map,this.eventListeners=new Map,this.closeRequested=!1,this.setSocket(e)};c.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")}},c.prototype.addEventListener=function(e,t){var n=this.eventListeners.get(e);n||this.eventListeners.set(e,n=[]),n.push(t)},c.prototype.removeEventListener=function(e,t){var n=this.eventListeners.get(e);if(n){var r=n.indexOf(t);-1!==r&&n.splice(r,1)}},c.prototype.fireEvent=function(e,t){var n=this;(this.eventListeners.get(e)||[]).forEach(function(e){return e(n,t)})},c.prototype.close=function(){this.closeRequested=!0,this.socket.close()},c.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)}},c.prototype.ping=function(){return this.sendMessagePromise({type:"ping"})},c.prototype.sendMessage=function(e,t){t||(t=this._genCmdId()),e.id=t,this.socket.send(JSON.stringify(e))},c.prototype.sendMessagePromise=function(e){var t=this;return new Promise(function(n,r){var o=t._genCmdId();t.commands.set(o,{resolve:n,reject:r}),t.sendMessage(e,o)})},c.prototype.subscribeMessage=function(e,t){try{var n,r=this,o=r._genCmdId();return Promise.resolve(new Promise(function(s,c){n={resolve:s,reject:c,callback:e,subscribe:function(){return r.subscribeMessage(e,t)},unsubscribe:function(){try{return Promise.resolve(r.sendMessagePromise(i(o))).then(function(){r.commands.delete(o)})}catch(e){return Promise.reject(e)}}},r.commands.set(o,n);try{r.sendMessage(t,o)}catch(e){}})).then(function(){return function(){return n.unsubscribe()}})}catch(e){return Promise.reject(e)}},c.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(i(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)}},c.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}),o=function(t){var s=n;setTimeout(function(){try{var n=e(function(){return Promise.resolve(r.createSocket(r)).then(function(e){s.setSocket(e)})},function(e){2===e?s.fireEvent("reconnect-error",e):o(t+1)});return Promise.resolve(n&&n.then?n.then(function(){}):void 0)}catch(e){return Promise.reject(e)}},1e3*Math.min(t,5))};o(0)}},c.prototype._genCmdId=function(){return++this.commandId};var u=function(e){void 0===e&&(e={});try{function t(){function t(){function t(){if(n)return new v(n,e.saveTokens);if(void 0===r)throw o;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)}(r,s,e.redirectUrl||location.protocol+"//"+location.host+location.pathname+location.search,btoa(JSON.stringify({hassUrl:r,clientId:s}))),new Promise(function(){})}var i=function(){if(!n&&e.loadTokens)return Promise.resolve(e.loadTokens()).then(function(e){n=e})}();return i&&i.then?i.then(t):t()}var i=function(){if(!n){var t=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}(),r=function(){if("auth_callback"in t){var r=JSON.parse(atob(t.state));return Promise.resolve(h(r.hassUrl,r.clientId,t.code)).then(function(t){n=t,e.saveTokens&&e.saveTokens(n)})}}();if(r&&r.then)return r.then(function(){})}}();return i&&i.then?i.then(t):t()}var n,r=e.hassUrl;r&&"/"===r[r.length-1]&&(r=r.substr(0,r.length-1));var s=e.clientId||f(),i=function(){if(!n&&e.authCode&&r&&s)return Promise.resolve(h(r,s,e.authCode)).then(function(t){n=t,e.saveTokens&&e.saveTokens(n)})}();return Promise.resolve(i&&i.then?i.then(t):t())}catch(e){return Promise.reject(e)}},a=function(e,t,n){try{var r="undefined"!=typeof location&&location;if(r&&"https:"===r.protocol){var o=document.createElement("a");if(o.href=e,"http:"===o.protocol&&"localhost"!==o.hostname)throw 5}var s=new FormData;return s.append("client_id",t),Object.keys(n).forEach(function(e){s.append(e,n[e])}),Promise.resolve(fetch(e+"/auth/token",{method:"POST",credentials:"same-origin",body:s})).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=d(n.expires_in),n})})}catch(e){return Promise.reject(e)}},f=function(){return location.protocol+"//"+location.host+"/"},d=function(e){return 1e3*e+Date.now()};function h(e,t,n){return a(e,t,{code:n,grant_type:"authorization_code"})}var v=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},v.prototype.refreshAccessToken=function(){try{var e=this;return Promise.resolve(a(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)}},v.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(v.prototype,l);var m=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)})},u=function(){return c().catch(function(t){if(e.socket.readyState==e.socket.OPEN)throw t})};return e[t]={get state(){return i.state},refresh:c,subscribe:function(t){1==++s&&(r&&(o=r(e,i)),e.addEventListener("ready",u),u());var n=i.subscribe(t);return void 0!==i.state&&setTimeout(function(){return t(i.state)},0),function(){n(),--s||(o&&o.then(function(e){e()}),e.removeEventListener("ready",c))}}},e[t]},p=function(e,t,n,r,o){return m(r,e,t,n).subscribe(o)},b=function(e){return e.sendMessagePromise({type:"get_states"})},y=function(e){return e.sendMessagePromise({type:"get_services"})},g=function(e){return e.sendMessagePromise({type:"get_config"})},k=function(e){return e.sendMessagePromise({type:"auth/current_user"})},_=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 g(e)},w=function(e,t){return Promise.all([e.subscribeEvents(t.action(P),"component_loaded"),e.subscribeEvents(function(){return E(e).then(function(e){return t.setState(e,!0)})},"core_config_updated")]).then(function(e){return function(){return e.forEach(function(e){return e()})}})},S=function(e,t){return function(e){return m(e,"_cnf",E,w)}(e).subscribe(t)};function j(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 T(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 M=function(e){return y(e)},I=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 m(e,"_srv",M,I)}(e).subscribe(t)},O=function(e){try{return Promise.resolve(b(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)}},U=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 m(e,"_ent",O,U)},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 c(e,t)})}catch(e){return Promise.reject(e)}},N={setupRetry:0,createSocket:function(t){if(!t.auth)throw o;var n=t.auth,r=n.expired?n.refreshAccessToken().then(function(){r=void 0},function(){r=void 0}):void 0,s=n.wsUrl;return new Promise(function(o,i){return function t(o,i,c){var u=new WebSocket(s),a=!1,f=function(){if(u.removeEventListener("close",f),a)c(2);else if(0!==o){var e=-1===o?-1:o-1;setTimeout(function(){return t(e,i,c)},1e3)}else c(1)},d=function(t){try{var o=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(o&&o.then?o.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 Promise.resolve()}catch(e){return Promise.reject(e)}};u.addEventListener("open",d),u.addEventListener("message",h),u.addEventListener("close",f),u.addEventListener("error",f)}(t.setupRetry,o,i)})}};export{x as createConnection,u as getAuth,f as genClientId,d as genExpires,v as Auth,m as getCollection,p as createCollection,c as Connection,S as subscribeConfig,L as subscribeServices,C as entitiesColl,R as subscribeEntities,t as ERR_CANNOT_CONNECT,n as ERR_INVALID_AUTH,r as ERR_CONNECTION_LOST,o as ERR_HASS_HOST_REQUIRED,s as ERR_INVALID_HTTPS_TO_HTTP,b as getStates,y as getServices,g as getConfig,k as getUser,_ 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}"undefined"!=typeof Symbol&&(Symbol.iterator||(Symbol.iterator=Symbol("Symbol.iterator"))),"undefined"!=typeof Symbol&&(Symbol.asyncIterator||(Symbol.asyncIterator=Symbol("Symbol.asyncIterator")));var t=1,n=2,r=3,o=4,s=5;function i(e){return{type:"unsubscribe_events",subscription:e}}var c=function(e,t){this.options=t,this.commandId=1,this.commands=new Map,this.eventListeners=new Map,this.closeRequested=!1,this.setSocket(e)};c.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")}},c.prototype.addEventListener=function(e,t){var n=this.eventListeners.get(e);n||this.eventListeners.set(e,n=[]),n.push(t)},c.prototype.removeEventListener=function(e,t){var n=this.eventListeners.get(e);if(n){var r=n.indexOf(t);-1!==r&&n.splice(r,1)}},c.prototype.fireEvent=function(e,t){var n=this;(this.eventListeners.get(e)||[]).forEach(function(e){return e(n,t)})},c.prototype.close=function(){this.closeRequested=!0,this.socket.close()},c.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)}},c.prototype.ping=function(){return this.sendMessagePromise({type:"ping"})},c.prototype.sendMessage=function(e,t){t||(t=this._genCmdId()),e.id=t,this.socket.send(JSON.stringify(e))},c.prototype.sendMessagePromise=function(e){var t=this;return new Promise(function(n,r){var o=t._genCmdId();t.commands.set(o,{resolve:n,reject:r}),t.sendMessage(e,o)})},c.prototype.subscribeMessage=function(e,t){try{var n,r=this,o=r._genCmdId();return Promise.resolve(new Promise(function(s,c){n={resolve:s,reject:c,callback:e,subscribe:function(){return r.subscribeMessage(e,t)},unsubscribe:function(){try{return Promise.resolve(r.sendMessagePromise(i(o))).then(function(){r.commands.delete(o)})}catch(e){return Promise.reject(e)}}},r.commands.set(o,n);try{r.sendMessage(t,o)}catch(e){}})).then(function(){return function(){return n.unsubscribe()}})}catch(e){return Promise.reject(e)}},c.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(i(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)}},c.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}),o=function(t){var s=n;setTimeout(function(){try{var n=e(function(){return Promise.resolve(r.createSocket(r)).then(function(e){s.setSocket(e)})},function(e){2===e?s.fireEvent("reconnect-error",e):o(t+1)});return Promise.resolve(n&&n.then?n.then(function(){}):void 0)}catch(e){return Promise.reject(e)}},1e3*Math.min(t,5))};o(0)}},c.prototype._genCmdId=function(){return++this.commandId};var u=function(e){void 0===e&&(e={});try{function t(){function t(){function t(){if(n)return new v(n,e.saveTokens);if(void 0===r)throw o;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&redirect_uri="+encodeURIComponent(n);return null!==t&&(o+="&client_id="+encodeURIComponent(t)),r&&(o+="&state="+encodeURIComponent(r)),o}(e,t,n,r)}(r,s,e.redirectUrl||location.protocol+"//"+location.host+location.pathname+location.search,btoa(JSON.stringify({hassUrl:r,clientId:s}))),new Promise(function(){})}var i=function(){if(!n&&e.loadTokens)return Promise.resolve(e.loadTokens()).then(function(e){n=e})}();return i&&i.then?i.then(t):t()}var i=function(){if(!n){var t=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}(),r=function(){if("auth_callback"in t){var r=JSON.parse(atob(t.state));return Promise.resolve(h(r.hassUrl,r.clientId,t.code)).then(function(t){n=t,e.saveTokens&&e.saveTokens(n)})}}();if(r&&r.then)return r.then(function(){})}}();return i&&i.then?i.then(t):t()}var n,r=e.hassUrl;r&&"/"===r[r.length-1]&&(r=r.substr(0,r.length-1));var s=void 0!==e.clientId?e.clientId:f(),i=function(){if(!n&&e.authCode&&r)return Promise.resolve(h(r,s,e.authCode)).then(function(t){n=t,e.saveTokens&&e.saveTokens(n)})}();return Promise.resolve(i&&i.then?i.then(t):t())}catch(e){return Promise.reject(e)}},a=function(e,t,n){try{var r="undefined"!=typeof location&&location;if(r&&"https:"===r.protocol){var o=document.createElement("a");if(o.href=e,"http:"===o.protocol&&"localhost"!==o.hostname)throw 5}var s=new FormData;return null!==t&&s.append("client_id",t),Object.keys(n).forEach(function(e){s.append(e,n[e])}),Promise.resolve(fetch(e+"/auth/token",{method:"POST",credentials:"same-origin",body:s})).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=d(n.expires_in),n})})}catch(e){return Promise.reject(e)}},f=function(){return location.protocol+"//"+location.host+"/"},d=function(e){return 1e3*e+Date.now()};function h(e,t,n){return a(e,t,{code:n,grant_type:"authorization_code"})}var v=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},v.prototype.refreshAccessToken=function(){try{var e=this;return Promise.resolve(a(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)}},v.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(v.prototype,l);var m=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)})},u=function(){return c().catch(function(t){if(e.socket.readyState==e.socket.OPEN)throw t})};return e[t]={get state(){return i.state},refresh:c,subscribe:function(t){1==++s&&(r&&(o=r(e,i)),e.addEventListener("ready",u),u());var n=i.subscribe(t);return void 0!==i.state&&setTimeout(function(){return t(i.state)},0),function(){n(),--s||(o&&o.then(function(e){e()}),e.removeEventListener("ready",c))}}},e[t]},p=function(e,t,n,r,o){return m(r,e,t,n).subscribe(o)},b=function(e){return e.sendMessagePromise({type:"get_states"})},y=function(e){return e.sendMessagePromise({type:"get_services"})},g=function(e){return e.sendMessagePromise({type:"get_config"})},k=function(e){return e.sendMessagePromise({type:"auth/current_user"})},_=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 g(e)},w=function(e,t){return Promise.all([e.subscribeEvents(t.action(P),"component_loaded"),e.subscribeEvents(function(){return E(e).then(function(e){return t.setState(e,!0)})},"core_config_updated")]).then(function(e){return function(){return e.forEach(function(e){return e()})}})},S=function(e,t){return function(e){return m(e,"_cnf",E,w)}(e).subscribe(t)};function j(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 T(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 I=function(e){return y(e)},M=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 m(e,"_srv",I,M)}(e).subscribe(t)},O=function(e){try{return Promise.resolve(b(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)}},U=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 m(e,"_ent",O,U)},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 c(e,t)})}catch(e){return Promise.reject(e)}},N={setupRetry:0,createSocket:function(t){if(!t.auth)throw o;var n=t.auth,r=n.expired?n.refreshAccessToken().then(function(){r=void 0},function(){r=void 0}):void 0,s=n.wsUrl;return new Promise(function(o,i){return function t(o,i,c){var u=new WebSocket(s),a=!1,f=function(){if(u.removeEventListener("close",f),a)c(2);else if(0!==o){var e=-1===o?-1:o-1;setTimeout(function(){return t(e,i,c)},1e3)}else c(1)},d=function(t){try{var o=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(o&&o.then?o.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 Promise.resolve()}catch(e){return Promise.reject(e)}};u.addEventListener("open",d),u.addEventListener("message",h),u.addEventListener("close",f),u.addEventListener("error",f)}(t.setupRetry,o,i)})}};export{x as createConnection,u as getAuth,f as genClientId,d as genExpires,v as Auth,m as getCollection,p as createCollection,c as Connection,S as subscribeConfig,L as subscribeServices,C as entitiesColl,R as subscribeEntities,t as ERR_CANNOT_CONNECT,n as ERR_INVALID_AUTH,r as ERR_CONNECTION_LOST,o as ERR_HASS_HOST_REQUIRED,s as ERR_INVALID_HTTPS_TO_HTTP,b as getStates,y as getServices,g as getConfig,k as getUser,_ 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}"undefined"!=typeof Symbol&&(Symbol.iterator||(Symbol.iterator=Symbol("Symbol.iterator"))),"undefined"!=typeof Symbol&&(Symbol.asyncIterator||(Symbol.asyncIterator=Symbol("Symbol.asyncIterator")));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 o=t._genCmdId();t.commands.set(o,{resolve:n,reject:r}),t.sendMessage(e,o)})},r.prototype.subscribeMessage=function(e,t){try{var r,o=this,s=o._genCmdId();return Promise.resolve(new Promise(function(i,c){r={resolve:i,reject:c,callback:e,subscribe:function(){return o.subscribeMessage(e,t)},unsubscribe:function(){try{return Promise.resolve(o.sendMessagePromise(n(s))).then(function(){o.commands.delete(s)})}catch(e){return Promise.reject(e)}}},o.commands.set(s,r);try{o.sendMessage(t,s)}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}),o=function(t){var s=n;setTimeout(function(){try{var n=e(function(){return Promise.resolve(r.createSocket(r)).then(function(e){s.setSocket(e)})},function(e){2===e?s.fireEvent("reconnect-error",e):o(t+1)});return Promise.resolve(n&&n.then?n.then(function(){}):void 0)}catch(e){return Promise.reject(e)}},1e3*Math.min(t,5))};o(0)}},r.prototype._genCmdId=function(){return++this.commandId};var o=function(e,t,n){try{var r="undefined"!=typeof location&&location;if(r&&"https:"===r.protocol){var o=document.createElement("a");if(o.href=e,"http:"===o.protocol&&"localhost"!==o.hostname)throw 5}var s=new FormData;return s.append("client_id",t),Object.keys(n).forEach(function(e){s.append(e,n[e])}),Promise.resolve(fetch(e+"/auth/token",{method:"POST",credentials:"same-origin",body:s})).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)}},s=function(){return location.protocol+"//"+location.host+"/"},i=function(e){return 1e3*e+Date.now()};function c(e,t,n){return o(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(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)}},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 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)})},u=function(){return c().catch(function(t){if(e.socket.readyState==e.socket.OPEN)throw t})};return e[t]={get state(){return i.state},refresh:c,subscribe:function(t){1==++s&&(r&&(o=r(e,i)),e.addEventListener("ready",u),u());var n=i.subscribe(t);return void 0!==i.state&&setTimeout(function(){return t(i.state)},0),function(){n(),--s||(o&&o.then(function(e){e()}),e.removeEventListener("ready",c))}}},e[t]},d=function(e){return e.sendMessagePromise({type:"get_states"})},h=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 Promise.all([e.subscribeEvents(t.action(l),"component_loaded"),e.subscribeEvents(function(){return p(e).then(function(e){return t.setState(e,!0)})},"core_config_updated")]).then(function(e){return function(){return e.forEach(function(e){return e()})}})};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 h(e)},_=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()})}})},k=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)}},P=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")},E=function(e){return f(e,"_ent",k,P)},S={setupRetry:0,createSocket:function(n){if(!n.auth)throw t;var r=n.auth,o=r.expired?r.refreshAccessToken().then(function(){o=void 0},function(){o=void 0}):void 0,s=r.wsUrl;return new Promise(function(t,i){return function t(n,i,c){var u=new WebSocket(s),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)},d=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(o||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 Promise.resolve()}catch(e){return Promise.reject(e)}};u.addEventListener("open",d),u.addEventListener("message",h),u.addEventListener("close",f),u.addEventListener("error",f)}(n.setupRetry,t,i)})}};exports.createConnection=function(e){try{var t=Object.assign({},S,e);return Promise.resolve(t.createSocket(t)).then(function(e){return new r(e,t)})}catch(e){return Promise.reject(e)}},exports.getAuth=function(e){void 0===e&&(e={});try{function n(){function n(){function n(){if(r)return new u(r,e.saveTokens);if(void 0===o)throw t;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)}(o,i,e.redirectUrl||location.protocol+"//"+location.host+location.pathname+location.search,btoa(JSON.stringify({hassUrl:o,clientId:i}))),new Promise(function(){})}var s=function(){if(!r&&e.loadTokens)return Promise.resolve(e.loadTokens()).then(function(e){r=e})}();return s&&s.then?s.then(n):n()}var s=function(){if(!r){var t=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}(),n=function(){if("auth_callback"in t){var n=JSON.parse(atob(t.state));return Promise.resolve(c(n.hassUrl,n.clientId,t.code)).then(function(t){r=t,e.saveTokens&&e.saveTokens(r)})}}();if(n&&n.then)return n.then(function(){})}}();return s&&s.then?s.then(n):n()}var r,o=e.hassUrl;o&&"/"===o[o.length-1]&&(o=o.substr(0,o.length-1));var i=e.clientId||s(),a=function(){if(!r&&e.authCode&&o&&i)return Promise.resolve(c(o,i,e.authCode)).then(function(t){r=t,e.saveTokens&&e.saveTokens(r)})}();return Promise.resolve(a&&a.then?a.then(n):n())}catch(e){return Promise.reject(e)}},exports.genClientId=s,exports.genExpires=i,exports.Auth=u,exports.getCollection=f,exports.createCollection=function(e,t,n,r,o){return f(r,e,t,n).subscribe(o)},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",g,_)}(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.ERR_INVALID_HTTPS_TO_HTTP=5,exports.getStates=d,exports.getServices=h,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}"undefined"!=typeof Symbol&&(Symbol.iterator||(Symbol.iterator=Symbol("Symbol.iterator"))),"undefined"!=typeof Symbol&&(Symbol.asyncIterator||(Symbol.asyncIterator=Symbol("Symbol.asyncIterator")));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 o=t._genCmdId();t.commands.set(o,{resolve:n,reject:r}),t.sendMessage(e,o)})},r.prototype.subscribeMessage=function(e,t){try{var r,o=this,s=o._genCmdId();return Promise.resolve(new Promise(function(i,c){r={resolve:i,reject:c,callback:e,subscribe:function(){return o.subscribeMessage(e,t)},unsubscribe:function(){try{return Promise.resolve(o.sendMessagePromise(n(s))).then(function(){o.commands.delete(s)})}catch(e){return Promise.reject(e)}}},o.commands.set(s,r);try{o.sendMessage(t,s)}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}),o=function(t){var s=n;setTimeout(function(){try{var n=e(function(){return Promise.resolve(r.createSocket(r)).then(function(e){s.setSocket(e)})},function(e){2===e?s.fireEvent("reconnect-error",e):o(t+1)});return Promise.resolve(n&&n.then?n.then(function(){}):void 0)}catch(e){return Promise.reject(e)}},1e3*Math.min(t,5))};o(0)}},r.prototype._genCmdId=function(){return++this.commandId};var o=function(e,t,n){try{var r="undefined"!=typeof location&&location;if(r&&"https:"===r.protocol){var o=document.createElement("a");if(o.href=e,"http:"===o.protocol&&"localhost"!==o.hostname)throw 5}var s=new FormData;return null!==t&&s.append("client_id",t),Object.keys(n).forEach(function(e){s.append(e,n[e])}),Promise.resolve(fetch(e+"/auth/token",{method:"POST",credentials:"same-origin",body:s})).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)}},s=function(){return location.protocol+"//"+location.host+"/"},i=function(e){return 1e3*e+Date.now()};function c(e,t,n){return o(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(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)}},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 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)})},u=function(){return c().catch(function(t){if(e.socket.readyState==e.socket.OPEN)throw t})};return e[t]={get state(){return i.state},refresh:c,subscribe:function(t){1==++s&&(r&&(o=r(e,i)),e.addEventListener("ready",u),u());var n=i.subscribe(t);return void 0!==i.state&&setTimeout(function(){return t(i.state)},0),function(){n(),--s||(o&&o.then(function(e){e()}),e.removeEventListener("ready",c))}}},e[t]},d=function(e){return e.sendMessagePromise({type:"get_states"})},h=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 Promise.all([e.subscribeEvents(t.action(l),"component_loaded"),e.subscribeEvents(function(){return p(e).then(function(e){return t.setState(e,!0)})},"core_config_updated")]).then(function(e){return function(){return e.forEach(function(e){return e()})}})};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 h(e)},_=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()})}})},k=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)}},P=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")},E=function(e){return f(e,"_ent",k,P)},S={setupRetry:0,createSocket:function(n){if(!n.auth)throw t;var r=n.auth,o=r.expired?r.refreshAccessToken().then(function(){o=void 0},function(){o=void 0}):void 0,s=r.wsUrl;return new Promise(function(t,i){return function t(n,i,c){var u=new WebSocket(s),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)},d=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(o||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 Promise.resolve()}catch(e){return Promise.reject(e)}};u.addEventListener("open",d),u.addEventListener("message",h),u.addEventListener("close",f),u.addEventListener("error",f)}(n.setupRetry,t,i)})}};exports.createConnection=function(e){try{var t=Object.assign({},S,e);return Promise.resolve(t.createSocket(t)).then(function(e){return new r(e,t)})}catch(e){return Promise.reject(e)}},exports.getAuth=function(e){void 0===e&&(e={});try{function n(){function n(){function n(){if(r)return new u(r,e.saveTokens);if(void 0===o)throw t;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&redirect_uri="+encodeURIComponent(n);return null!==t&&(o+="&client_id="+encodeURIComponent(t)),r&&(o+="&state="+encodeURIComponent(r)),o}(e,t,n,r)}(o,i,e.redirectUrl||location.protocol+"//"+location.host+location.pathname+location.search,btoa(JSON.stringify({hassUrl:o,clientId:i}))),new Promise(function(){})}var s=function(){if(!r&&e.loadTokens)return Promise.resolve(e.loadTokens()).then(function(e){r=e})}();return s&&s.then?s.then(n):n()}var s=function(){if(!r){var t=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}(),n=function(){if("auth_callback"in t){var n=JSON.parse(atob(t.state));return Promise.resolve(c(n.hassUrl,n.clientId,t.code)).then(function(t){r=t,e.saveTokens&&e.saveTokens(r)})}}();if(n&&n.then)return n.then(function(){})}}();return s&&s.then?s.then(n):n()}var r,o=e.hassUrl;o&&"/"===o[o.length-1]&&(o=o.substr(0,o.length-1));var i=void 0!==e.clientId?e.clientId:s(),a=function(){if(!r&&e.authCode&&o)return Promise.resolve(c(o,i,e.authCode)).then(function(t){r=t,e.saveTokens&&e.saveTokens(r)})}();return Promise.resolve(a&&a.then?a.then(n):n())}catch(e){return Promise.reject(e)}},exports.genClientId=s,exports.genExpires=i,exports.Auth=u,exports.getCollection=f,exports.createCollection=function(e,t,n,r,o){return f(r,e,t,n).subscribe(o)},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",g,_)}(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.ERR_INVALID_HTTPS_TO_HTTP=5,exports.getStates=d,exports.getServices=h,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}"undefined"!=typeof Symbol&&(Symbol.iterator||(Symbol.iterator=Symbol("Symbol.iterator"))),"undefined"!=typeof Symbol&&(Symbol.asyncIterator||(Symbol.asyncIterator=Symbol("Symbol.asyncIterator")));var n=4;function r(e){return{type:"unsubscribe_events",subscription:e}}var o=function(e,t){this.options=t,this.commandId=1,this.commands=new Map,this.eventListeners=new Map,this.closeRequested=!1,this.setSocket(e)};o.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")}},o.prototype.addEventListener=function(e,t){var n=this.eventListeners.get(e);n||this.eventListeners.set(e,n=[]),n.push(t)},o.prototype.removeEventListener=function(e,t){var n=this.eventListeners.get(e);if(n){var r=n.indexOf(t);-1!==r&&n.splice(r,1)}},o.prototype.fireEvent=function(e,t){var n=this;(this.eventListeners.get(e)||[]).forEach(function(e){return e(n,t)})},o.prototype.close=function(){this.closeRequested=!0,this.socket.close()},o.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)}},o.prototype.ping=function(){return this.sendMessagePromise({type:"ping"})},o.prototype.sendMessage=function(e,t){t||(t=this._genCmdId()),e.id=t,this.socket.send(JSON.stringify(e))},o.prototype.sendMessagePromise=function(e){var t=this;return new Promise(function(n,r){var o=t._genCmdId();t.commands.set(o,{resolve:n,reject:r}),t.sendMessage(e,o)})},o.prototype.subscribeMessage=function(e,t){try{var n,o=this,s=o._genCmdId();return Promise.resolve(new Promise(function(i,c){n={resolve:i,reject:c,callback:e,subscribe:function(){return o.subscribeMessage(e,t)},unsubscribe:function(){try{return Promise.resolve(o.sendMessagePromise(r(s))).then(function(){o.commands.delete(s)})}catch(e){return Promise.reject(e)}}},o.commands.set(s,n);try{o.sendMessage(t,s)}catch(e){}})).then(function(){return function(){return n.unsubscribe()}})}catch(e){return Promise.reject(e)}},o.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)}},o.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}),o=function(e){var s=n;setTimeout(function(){try{var n=t(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(n&&n.then?n.then(function(){}):void 0)}catch(e){return Promise.reject(e)}},1e3*Math.min(e,5))};o(0)}},o.prototype._genCmdId=function(){return++this.commandId};var s=function(e,t,n){try{var r="undefined"!=typeof location&&location;if(r&&"https:"===r.protocol){var o=document.createElement("a");if(o.href=e,"http:"===o.protocol&&"localhost"!==o.hostname)throw 5}var s=new FormData;return s.append("client_id",t),Object.keys(n).forEach(function(e){s.append(e,n[e])}),Promise.resolve(fetch(e+"/auth/token",{method:"POST",credentials:"same-origin",body:s})).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 s(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(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)}},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 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)})},u=function(){return c().catch(function(t){if(e.socket.readyState==e.socket.OPEN)throw t})};return e[t]={get state(){return i.state},refresh:c,subscribe:function(t){1==++s&&(r&&(o=r(e,i)),e.addEventListener("ready",u),u());var n=i.subscribe(t);return void 0!==i.state&&setTimeout(function(){return t(i.state)},0),function(){n(),--s||(o&&o.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 Promise.all([e.subscribeEvents(t.action(m),"component_loaded"),e.subscribeEvents(function(){return p(e).then(function(e){return t.setState(e,!0)})},"core_config_updated")]).then(function(e){return function(){return e.forEach(function(e){return e()})}})};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 _=function(e){return v(e)},k=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()})}})},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 d(e,"_ent",P,E)},T={setupRetry:0,createSocket:function(e){if(!e.auth)throw n;var r=e.auth,o=r.expired?r.refreshAccessToken().then(function(){o=void 0},function(){o=void 0}):void 0,s=r.wsUrl;return new Promise(function(n,i){return function e(n,i,c){var u=new WebSocket(s),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(o||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 Promise.resolve()}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({},T,e);return Promise.resolve(t.createSocket(t)).then(function(e){return new o(e,t)})}catch(e){return Promise.reject(e)}},e.getAuth=function(e){void 0===e&&(e={});try{function t(){function t(){function t(){if(r)return new a(r,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 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)}(o,s,e.redirectUrl||location.protocol+"//"+location.host+location.pathname+location.search,btoa(JSON.stringify({hassUrl:o,clientId:s}))),new Promise(function(){})}var i=function(){if(!r&&e.loadTokens)return Promise.resolve(e.loadTokens()).then(function(e){r=e})}();return i&&i.then?i.then(t):t()}var i=function(){if(!r){var t=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}(),n=function(){if("auth_callback"in t){var n=JSON.parse(atob(t.state));return Promise.resolve(u(n.hassUrl,n.clientId,t.code)).then(function(t){r=t,e.saveTokens&&e.saveTokens(r)})}}();if(n&&n.then)return n.then(function(){})}}();return i&&i.then?i.then(t):t()}var r,o=e.hassUrl;o&&"/"===o[o.length-1]&&(o=o.substr(0,o.length-1));var s=e.clientId||i(),c=function(){if(!r&&e.authCode&&o&&s)return Promise.resolve(u(o,s,e.authCode)).then(function(t){r=t,e.saveTokens&&e.saveTokens(r)})}();return Promise.resolve(c&&c.then?c.then(t):t())}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,o){return d(r,e,t,n).subscribe(o)},e.Connection=o,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.ERR_INVALID_HTTPS_TO_HTTP=5,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}"undefined"!=typeof Symbol&&(Symbol.iterator||(Symbol.iterator=Symbol("Symbol.iterator"))),"undefined"!=typeof Symbol&&(Symbol.asyncIterator||(Symbol.asyncIterator=Symbol("Symbol.asyncIterator")));var n=4;function r(e){return{type:"unsubscribe_events",subscription:e}}var o=function(e,t){this.options=t,this.commandId=1,this.commands=new Map,this.eventListeners=new Map,this.closeRequested=!1,this.setSocket(e)};o.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")}},o.prototype.addEventListener=function(e,t){var n=this.eventListeners.get(e);n||this.eventListeners.set(e,n=[]),n.push(t)},o.prototype.removeEventListener=function(e,t){var n=this.eventListeners.get(e);if(n){var r=n.indexOf(t);-1!==r&&n.splice(r,1)}},o.prototype.fireEvent=function(e,t){var n=this;(this.eventListeners.get(e)||[]).forEach(function(e){return e(n,t)})},o.prototype.close=function(){this.closeRequested=!0,this.socket.close()},o.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)}},o.prototype.ping=function(){return this.sendMessagePromise({type:"ping"})},o.prototype.sendMessage=function(e,t){t||(t=this._genCmdId()),e.id=t,this.socket.send(JSON.stringify(e))},o.prototype.sendMessagePromise=function(e){var t=this;return new Promise(function(n,r){var o=t._genCmdId();t.commands.set(o,{resolve:n,reject:r}),t.sendMessage(e,o)})},o.prototype.subscribeMessage=function(e,t){try{var n,o=this,s=o._genCmdId();return Promise.resolve(new Promise(function(i,c){n={resolve:i,reject:c,callback:e,subscribe:function(){return o.subscribeMessage(e,t)},unsubscribe:function(){try{return Promise.resolve(o.sendMessagePromise(r(s))).then(function(){o.commands.delete(s)})}catch(e){return Promise.reject(e)}}},o.commands.set(s,n);try{o.sendMessage(t,s)}catch(e){}})).then(function(){return function(){return n.unsubscribe()}})}catch(e){return Promise.reject(e)}},o.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)}},o.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}),o=function(e){var s=n;setTimeout(function(){try{var n=t(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(n&&n.then?n.then(function(){}):void 0)}catch(e){return Promise.reject(e)}},1e3*Math.min(e,5))};o(0)}},o.prototype._genCmdId=function(){return++this.commandId};var s=function(e,t,n){try{var r="undefined"!=typeof location&&location;if(r&&"https:"===r.protocol){var o=document.createElement("a");if(o.href=e,"http:"===o.protocol&&"localhost"!==o.hostname)throw 5}var s=new FormData;return null!==t&&s.append("client_id",t),Object.keys(n).forEach(function(e){s.append(e,n[e])}),Promise.resolve(fetch(e+"/auth/token",{method:"POST",credentials:"same-origin",body:s})).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 s(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(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)}},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 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)})},u=function(){return c().catch(function(t){if(e.socket.readyState==e.socket.OPEN)throw t})};return e[t]={get state(){return i.state},refresh:c,subscribe:function(t){1==++s&&(r&&(o=r(e,i)),e.addEventListener("ready",u),u());var n=i.subscribe(t);return void 0!==i.state&&setTimeout(function(){return t(i.state)},0),function(){n(),--s||(o&&o.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 Promise.all([e.subscribeEvents(t.action(m),"component_loaded"),e.subscribeEvents(function(){return p(e).then(function(e){return t.setState(e,!0)})},"core_config_updated")]).then(function(e){return function(){return e.forEach(function(e){return e()})}})};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 _=function(e){return v(e)},k=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()})}})},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 d(e,"_ent",P,E)},T={setupRetry:0,createSocket:function(e){if(!e.auth)throw n;var r=e.auth,o=r.expired?r.refreshAccessToken().then(function(){o=void 0},function(){o=void 0}):void 0,s=r.wsUrl;return new Promise(function(n,i){return function e(n,i,c){var u=new WebSocket(s),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(o||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 Promise.resolve()}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({},T,e);return Promise.resolve(t.createSocket(t)).then(function(e){return new o(e,t)})}catch(e){return Promise.reject(e)}},e.getAuth=function(e){void 0===e&&(e={});try{function t(){function t(){function t(){if(r)return new a(r,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 o=e+"/auth/authorize?response_type=code&redirect_uri="+encodeURIComponent(n);return null!==t&&(o+="&client_id="+encodeURIComponent(t)),r&&(o+="&state="+encodeURIComponent(r)),o}(e,t,n,r)}(o,s,e.redirectUrl||location.protocol+"//"+location.host+location.pathname+location.search,btoa(JSON.stringify({hassUrl:o,clientId:s}))),new Promise(function(){})}var i=function(){if(!r&&e.loadTokens)return Promise.resolve(e.loadTokens()).then(function(e){r=e})}();return i&&i.then?i.then(t):t()}var i=function(){if(!r){var t=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}(),n=function(){if("auth_callback"in t){var n=JSON.parse(atob(t.state));return Promise.resolve(u(n.hassUrl,n.clientId,t.code)).then(function(t){r=t,e.saveTokens&&e.saveTokens(r)})}}();if(n&&n.then)return n.then(function(){})}}();return i&&i.then?i.then(t):t()}var r,o=e.hassUrl;o&&"/"===o[o.length-1]&&(o=o.substr(0,o.length-1));var s=void 0!==e.clientId?e.clientId:i(),c=function(){if(!r&&e.authCode&&o)return Promise.resolve(u(o,s,e.authCode)).then(function(t){r=t,e.saveTokens&&e.saveTokens(r)})}();return Promise.resolve(c&&c.then?c.then(t):t())}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,o){return d(r,e,t,n).subscribe(o)},e.Connection=o,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.ERR_INVALID_HTTPS_TO_HTTP=5,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.3.1", | ||
"version": "4.4.0", | ||
"description": "Home Assistant websocket client", | ||
@@ -8,0 +8,0 @@ "source": "lib/index.ts", |
@@ -69,3 +69,3 @@ # :aerial_tramway: JavaScript websocket client for Home Assistant | ||
| hassUrl | The url where the Home Assistant instance can be reached. This option is needed so we know where to redirect the user for authentication. Once redirected back, it is not needed to pass this option in. | | ||
| clientId | Client ID to use. Client IDs for Home Assistant is the url of your application. Defaults to domain of current page. | | ||
| clientId | Client ID to use. Client IDs for Home Assistant is the url of your application. Defaults to domain of current page. Pass `null` if you are making requests on behalf of a system user. | | ||
| redirectUrl | The url to redirect back to when the user has logged in. Defaults to current page. | | ||
@@ -72,0 +72,0 @@ | saveTokens | Function to store an object containing the token information. | |
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
287970
440