home-assistant-js-websocket
Advanced tools
Comparing version 4.4.1 to 4.5.0
@@ -25,5 +25,5 @@ export declare type AuthData = { | ||
constructor(data: AuthData, saveTokens?: SaveTokensFunc); | ||
readonly wsUrl: string; | ||
readonly accessToken: string; | ||
readonly expired: boolean; | ||
get wsUrl(): string; | ||
get accessToken(): string; | ||
get expired(): boolean; | ||
/** | ||
@@ -30,0 +30,0 @@ * Refresh the access token. |
import { ConnectionOptions, MessageBase } from "./types"; | ||
import { HaWebSocket } from "./socket"; | ||
export declare type ConnectionEventListener = (conn: Connection, eventData?: any) => void; | ||
@@ -23,5 +24,6 @@ declare type Events = "ready" | "disconnected" | "reconnect-error"; | ||
closeRequested: boolean; | ||
socket: WebSocket; | ||
constructor(socket: WebSocket, options: ConnectionOptions); | ||
setSocket(socket: WebSocket): void; | ||
socket: HaWebSocket; | ||
constructor(socket: HaWebSocket, options: ConnectionOptions); | ||
get haVersion(): string; | ||
setSocket(socket: HaWebSocket): void; | ||
addEventListener(eventType: Events, callback: ConnectionEventListener): void; | ||
@@ -28,0 +30,0 @@ removeEventListener(eventType: Events, callback: ConnectionEventListener): void; |
@@ -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&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}; | ||
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)},u={haVersion:{configurable:!0}};u.haVersion.get=function(){return this.socket.haVersion},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 Promise.resolve(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},Object.defineProperties(c.prototype,u);var a=function(e){void 0===e&&(e={});try{function t(){function t(){function t(){if(n)return new l(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(v(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:d(),i=function(){if(!n&&e.authCode&&r)return Promise.resolve(v(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)}},f=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=h(n.expires_in),n})})}catch(e){return Promise.reject(e)}},d=function(){return location.protocol+"//"+location.host+"/"},h=function(e){return 1e3*e+Date.now()};function v(e,t,n){return f(e,t,{code:n,grant_type:"authorization_code"})}var l=function(e,t){this.data=e,this._saveTokens=t},m={wsUrl:{configurable:!0},accessToken:{configurable:!0},expired:{configurable:!0}};m.wsUrl.get=function(){return"ws"+this.data.hassUrl.substr(4)+"/api/websocket"},m.accessToken.get=function(){return this.data.access_token},m.expired.get=function(){return Date.now()>this.data.expires},l.prototype.refreshAccessToken=function(){try{var e=this;return Promise.resolve(f(e.data.hassUrl,e.data.clientId,{grant_type:"refresh_token",refresh_token:e.data.refresh_token})).then(function(t){t.refresh_token=e.data.refresh_token,e.data=t,e._saveTokens&&e._saveTokens(t)})}catch(e){return Promise.reject(e)}},l.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(l.prototype,m);var p=function(e,t,n,r){if(e[t])return e[t];var o,s=0,i=function(e){var t=[];function n(n,r){e=r?n:Object.assign({},e,n);for(var o=t,s=0;s<o.length;s++)o[s](e)}return{get state(){return e},action:function(t){function r(e){n(e,!1)}return function(){for(var n=arguments,o=[e],s=0;s<arguments.length;s++)o.push(n[s]);var i=t.apply(this,o);if(null!=i)return i.then?i.then(r):r(i)}},setState:n,subscribe:function(e){return t.push(e),function(){!function(e){for(var n=[],r=0;r<t.length;r++)t[r]===e?e=null:n.push(t[r]);t=n}(e)}}}}(),c=function(){return n(e).then(function(e){return i.setState(e,!0)})},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]},b=function(e,t,n,r,o){return p(r,e,t,n).subscribe(o)},y=function(e){return e.sendMessagePromise({type:"get_states"})},g=function(e){return e.sendMessagePromise({type:"get_services"})},k=function(e){return e.sendMessagePromise({type:"get_config"})},_=function(e){return e.sendMessagePromise({type:"auth/current_user"})},P=function(e,t,n,r){return e.sendMessagePromise(function(e,t,n){var r={type:"call_service",domain:e,service:t};return n&&(r.service_data=n),r}(t,n,r))};function E(e,t){return void 0===e?null:{components:e.components.concat(t.data.component)}}var w=function(e){return k(e)},S=function(e,t){return Promise.all([e.subscribeEvents(t.action(E),"component_loaded"),e.subscribeEvents(function(){return w(e).then(function(e){return t.setState(e,!0)})},"core_config_updated")]).then(function(e){return function(){return e.forEach(function(e){return e()})}})},j=function(e,t){return function(e){return p(e,"_cnf",w,S)}(e).subscribe(t)};function T(e,t){var n,r;if(void 0===e)return null;var o=t.data,s=o.domain,i=Object.assign({},e[s],((n={})[o.service]={description:"",fields:{}},n));return(r={})[s]=i,r}function I(e,t){var n;if(void 0===e)return null;var r=t.data,o=r.domain,s=r.service,i=e[o];if(!(i&&s in i))return null;var c={};return Object.keys(i).forEach(function(e){e!==s&&(c[e]=i[e])}),(n={})[o]=c,n}var M=function(e){return g(e)},L=function(e,t){return Promise.all([e.subscribeEvents(t.action(T),"service_registered"),e.subscribeEvents(t.action(I),"service_removed")]).then(function(e){return function(){return e.forEach(function(e){return e()})}})},O=function(e,t){return function(e){return p(e,"_srv",M,L)}(e).subscribe(t)},U=function(e){try{return Promise.resolve(y(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)}},C=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")},R=function(e){return p(e,"_ent",U,C)},x=function(e,t){return R(e).subscribe(t)},N=function(e){try{var t=Object.assign({},J,e);return Promise.resolve(t.createSocket(t)).then(function(e){return new c(e,t)})}catch(e){return Promise.reject(e)}},J={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{var t=JSON.parse(e.data);switch(t.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),u.haVersion=t.ha_version,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{N as createConnection,a as getAuth,d as genClientId,h as genExpires,l as Auth,p as getCollection,b as createCollection,c as Connection,j as subscribeConfig,O as subscribeServices,R as entitiesColl,x 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,y as getStates,g as getServices,k as getConfig,_ as getUser,P 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 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))}; | ||
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)},o={haVersion:{configurable:!0}};o.haVersion.get=function(){return this.socket.haVersion},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 Promise.resolve(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},Object.defineProperties(r.prototype,o);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 h=function(e,t,n,r){if(e[t])return e[t];var o,s=0,i=function(e){var t=[];function n(n,r){e=r?n:Object.assign({},e,n);for(var o=t,s=0;s<o.length;s++)o[s](e)}return{get state(){return e},action:function(t){function r(e){n(e,!1)}return function(){for(var n=arguments,o=[e],s=0;s<arguments.length;s++)o.push(n[s]);var i=t.apply(this,o);if(null!=i)return i.then?i.then(r):r(i)}},setState:n,subscribe:function(e){return t.push(e),function(){!function(e){for(var n=[],r=0;r<t.length;r++)t[r]===e?e=null:n.push(t[r]);t=n}(e)}}}}(),c=function(){return n(e).then(function(e){return i.setState(e,!0)})},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"})},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 Promise.all([e.subscribeEvents(t.action(p),"component_loaded"),e.subscribeEvents(function(){return m(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 g(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 _=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(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)}},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 h(e,"_ent",P,E)},T={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)},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(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)}},d=function(e){try{var t=JSON.parse(e.data);switch(t.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),u.haVersion=t.ha_version,i(u)}return Promise.resolve()}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({},T,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 a(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,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(n):n()}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(n):n()}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(n):n())}catch(e){return Promise.reject(e)}},exports.genClientId=i,exports.genExpires=c,exports.Auth=a,exports.getCollection=h,exports.createCollection=function(e,t,n,r,o){return h(r,e,t,n).subscribe(o)},exports.Connection=r,exports.subscribeConfig=function(e,t){return function(e){return h(e,"_cnf",m,b)}(e).subscribe(t)},exports.subscribeServices=function(e,t){return function(e){return h(e,"_srv",_,k)}(e).subscribe(t)},exports.entitiesColl=S,exports.subscribeEntities=function(e,t){return S(e).subscribe(t)},exports.ERR_CANNOT_CONNECT=1,exports.ERR_INVALID_AUTH=2,exports.ERR_CONNECTION_LOST=3,exports.ERR_HASS_HOST_REQUIRED=t,exports.ERR_INVALID_HTTPS_TO_HTTP=5,exports.getStates=d,exports.getServices=v,exports.getConfig=l,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 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))}}); | ||
!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)},s={haVersion:{configurable:!0}};s.haVersion.get=function(){return this.socket.haVersion},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 Promise.resolve(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},Object.defineProperties(o.prototype,s);var i=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=u(n.expires_in),n})})}catch(e){return Promise.reject(e)}},c=function(){return location.protocol+"//"+location.host+"/"},u=function(e){return 1e3*e+Date.now()};function a(e,t,n){return i(e,t,{code:n,grant_type:"authorization_code"})}var f=function(e,t){this.data=e,this._saveTokens=t},d={wsUrl:{configurable:!0},accessToken:{configurable:!0},expired:{configurable:!0}};d.wsUrl.get=function(){return"ws"+this.data.hassUrl.substr(4)+"/api/websocket"},d.accessToken.get=function(){return this.data.access_token},d.expired.get=function(){return Date.now()>this.data.expires},f.prototype.refreshAccessToken=function(){try{var e=this;return Promise.resolve(i(e.data.hassUrl,e.data.clientId,{grant_type:"refresh_token",refresh_token:e.data.refresh_token})).then(function(t){t.refresh_token=e.data.refresh_token,e.data=t,e._saveTokens&&e._saveTokens(t)})}catch(e){return Promise.reject(e)}},f.prototype.revoke=function(){try{var e=this,t=new FormData;return t.append("action","revoke"),t.append("token",e.data.refresh_token),Promise.resolve(fetch(e.data.hassUrl+"/auth/token",{method:"POST",credentials:"same-origin",body:t})).then(function(){e._saveTokens&&e._saveTokens(null)})}catch(e){return Promise.reject(e)}},Object.defineProperties(f.prototype,d);var h=function(e,t,n,r){if(e[t])return e[t];var o,s=0,i=function(e){var t=[];function n(n,r){e=r?n:Object.assign({},e,n);for(var o=t,s=0;s<o.length;s++)o[s](e)}return{get state(){return e},action:function(t){function r(e){n(e,!1)}return function(){for(var n=arguments,o=[e],s=0;s<arguments.length;s++)o.push(n[s]);var i=t.apply(this,o);if(null!=i)return i.then?i.then(r):r(i)}},setState:n,subscribe:function(e){return t.push(e),function(){!function(e){for(var n=[],r=0;r<t.length;r++)t[r]===e?e=null:n.push(t[r]);t=n}(e)}}}}(),c=function(){return n(e).then(function(e){return i.setState(e,!0)})},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]},v=function(e){return e.sendMessagePromise({type:"get_states"})},l=function(e){return e.sendMessagePromise({type:"get_services"})},m=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 b=function(e){return m(e)},y=function(e,t){return Promise.all([e.subscribeEvents(t.action(p),"component_loaded"),e.subscribeEvents(function(){return b(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 g(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 _(e,t){var n;if(void 0===e)return null;var r=t.data,o=r.domain,s=r.service,i=e[o];if(!(i&&s in i))return null;var c={};return Object.keys(i).forEach(function(e){e!==s&&(c[e]=i[e])}),(n={})[o]=c,n}var k=function(e){return l(e)},P=function(e,t){return Promise.all([e.subscribeEvents(t.action(g),"service_registered"),e.subscribeEvents(t.action(_),"service_removed")]).then(function(e){return function(){return e.forEach(function(e){return e()})}})},E=function(e){try{return Promise.resolve(v(e)).then(function(e){for(var t={},n=0;n<e.length;n++){var r=e[n];t[r.entity_id]=r}return t})}catch(e){return Promise.reject(e)}},S=function(e,t){return e.subscribeEvents(function(e){return function(t,n){var r,o=t.state;if(void 0!==o){var s=e.data,i=s.entity_id,c=s.new_state;if(c)t.setState(((r={})[c.entity_id]=c,r));else{var u=Object.assign({},o);delete u[i],t.setState(u,!0)}}}(t)},"state_changed")},T=function(e){return h(e,"_ent",E,S)},w={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{var t=JSON.parse(e.data);switch(t.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),u.haVersion=t.ha_version,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({},w,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 f(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(a(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:c(),i=function(){if(!r&&e.authCode&&o)return Promise.resolve(a(o,s,e.authCode)).then(function(t){r=t,e.saveTokens&&e.saveTokens(r)})}();return Promise.resolve(i&&i.then?i.then(t):t())}catch(e){return Promise.reject(e)}},e.genClientId=c,e.genExpires=u,e.Auth=f,e.getCollection=h,e.createCollection=function(e,t,n,r,o){return h(r,e,t,n).subscribe(o)},e.Connection=o,e.subscribeConfig=function(e,t){return function(e){return h(e,"_cnf",b,y)}(e).subscribe(t)},e.subscribeServices=function(e,t){return function(e){return h(e,"_srv",k,P)}(e).subscribe(t)},e.entitiesColl=T,e.subscribeEntities=function(e,t){return T(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=v,e.getServices=l,e.getConfig=m,e.getUser=function(e){return e.sendMessagePromise({type:"auth/current_user"})},e.callService=function(e,t,n,r){return e.sendMessagePromise(function(e,t,n){var r={type:"call_service",domain:e,service:t};return n&&(r.service_data=n),r}(t,n,r))}}); | ||
//# sourceMappingURL=haws.umd.js.map |
import { ConnectionOptions } from "./types"; | ||
export declare function createSocket(options: ConnectionOptions): Promise<WebSocket>; | ||
export interface HaWebSocket extends WebSocket { | ||
haVersion: string; | ||
} | ||
export declare function createSocket(options: ConnectionOptions): Promise<HaWebSocket>; |
import { Auth } from "./auth"; | ||
import { HaWebSocket } from "./socket"; | ||
export declare type Error = 1 | 2 | 3 | 4; | ||
@@ -7,3 +8,3 @@ export declare type UnsubscribeFunc = () => void; | ||
auth?: Auth; | ||
createSocket: (options: ConnectionOptions) => Promise<WebSocket>; | ||
createSocket: (options: ConnectionOptions) => Promise<HaWebSocket>; | ||
}; | ||
@@ -10,0 +11,0 @@ export declare type MessageBase = { |
@@ -5,3 +5,3 @@ { | ||
"sideEffects": false, | ||
"version": "4.4.1", | ||
"version": "4.5.0", | ||
"description": "Home Assistant websocket client", | ||
@@ -19,3 +19,3 @@ "source": "lib/index.ts", | ||
"build": "microbundle", | ||
"test": "mocha test/*.spec.ts", | ||
"test": "mocha", | ||
"prepublishOnly": "rm -rf dist && microbundle && npm test" | ||
@@ -26,10 +26,10 @@ }, | ||
"devDependencies": { | ||
"@types/mocha": "^5.2.7", | ||
"husky": "^3.0.1", | ||
"lint-staged": "^9.2.0", | ||
"@types/mocha": "^7.0.2", | ||
"husky": "^4.2.3", | ||
"lint-staged": "^10.0.8", | ||
"microbundle": "^0.11.0", | ||
"mocha": "^6.2.0", | ||
"prettier": "^1.18.2", | ||
"ts-node": "^8.3.0", | ||
"typescript": "^3.5.3" | ||
"mocha": "^7.1.0", | ||
"prettier": "^1.19.1", | ||
"ts-node": "^8.6.2", | ||
"typescript": "^3.8.3" | ||
}, | ||
@@ -47,6 +47,5 @@ "files": [ | ||
"*.{ts,js,json,css,md}": [ | ||
"prettier --write", | ||
"git add" | ||
"prettier --write" | ||
] | ||
} | ||
} |
@@ -291,2 +291,10 @@ # :aerial_tramway: JavaScript websocket client for Home Assistant | ||
##### `conn.haVersion` | ||
String containing the current version of Home Assistant. Examples: | ||
- `0.107.0` | ||
- `0.107.0b1` | ||
- `0.107.0.dev0` | ||
##### `conn.subscribeEvents(eventCallback[, eventType])` | ||
@@ -293,0 +301,0 @@ |
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
289991
448
410