Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

home-assistant-js-websocket

Package Overview
Dependencies
Maintainers
1
Versions
102
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

home-assistant-js-websocket - npm Package Compare versions

Comparing version 4.2.2 to 4.3.0

2

dist/commands.d.ts

@@ -7,2 +7,2 @@ import { Connection } from "./connection";

export declare const getUser: (connection: Connection) => Promise<HassUser>;
export declare const callService: (connection: Connection, domain: string, service: string, serviceData?: object | undefined) => Promise<{}>;
export declare const callService: (connection: Connection, domain: string, service: string, serviceData?: object | undefined) => Promise<unknown>;

@@ -38,3 +38,3 @@ import { ConnectionOptions, MessageBase } from "./types";

subscribeEvents<EventType>(callback: (ev: EventType) => void, eventType?: string): Promise<SubscriptionUnsubscribe>;
ping(): Promise<{}>;
ping(): Promise<unknown>;
sendMessage(message: MessageBase, commandId?: number): void;

@@ -41,0 +41,0 @@ sendMessagePromise<Result>(message: MessageBase): Promise<Result>;

@@ -5,1 +5,2 @@ export declare const ERR_CANNOT_CONNECT = 1;

export declare const ERR_HASS_HOST_REQUIRED = 4;
export declare const ERR_INVALID_HTTPS_TO_HTTP = 5;

@@ -1,2 +0,2 @@

function e(e,t){try{var n=e()}catch(e){return t(e)}return n&&n.then?n.then(void 0,t):n}var t=1,n=2,r=3,s=4;function o(e){return{type:"unsubscribe_events",subscription:e}}var i=function(e,t){this.options=t,this.commandId=1,this.commands=new Map,this.eventListeners=new Map,this.closeRequested=!1,this.setSocket(e)};i.prototype.setSocket=function(e){var t=this,n=this.socket;if(this.socket=e,e.addEventListener("message",function(e){return t._handleMessage(e)}),e.addEventListener("close",function(e){return t._handleClose(e)}),n){var r=this.commands;this.commandId=1,this.commands=new Map,r.forEach(function(e){"subscribe"in e&&e.subscribe().then(function(t){e.unsubscribe=t,e.resolve()})}),this.fireEvent("ready")}},i.prototype.addEventListener=function(e,t){var n=this.eventListeners.get(e);n||this.eventListeners.set(e,n=[]),n.push(t)},i.prototype.removeEventListener=function(e,t){var n=this.eventListeners.get(e);if(n){var r=n.indexOf(t);-1!==r&&n.splice(r,1)}},i.prototype.fireEvent=function(e,t){var n=this;(this.eventListeners.get(e)||[]).forEach(function(e){return e(n,t)})},i.prototype.close=function(){this.closeRequested=!0,this.socket.close()},i.prototype.subscribeEvents=function(e,t){try{return this.subscribeMessage(e,function(e){var t={type:"subscribe_events"};return e&&(t.event_type=e),t}(t))}catch(e){return Promise.reject(e)}},i.prototype.ping=function(){return this.sendMessagePromise({type:"ping"})},i.prototype.sendMessage=function(e,t){t||(t=this._genCmdId()),e.id=t,this.socket.send(JSON.stringify(e))},i.prototype.sendMessagePromise=function(e){var t=this;return new Promise(function(n,r){var s=t._genCmdId();t.commands.set(s,{resolve:n,reject:r}),t.sendMessage(e,s)})},i.prototype.subscribeMessage=function(e,t){try{var n,r=this,s=r._genCmdId();return Promise.resolve(new Promise(function(i,c){n={resolve:i,reject:c,callback:e,subscribe:function(){return r.subscribeMessage(e,t)},unsubscribe:function(){try{return Promise.resolve(r.sendMessagePromise(o(s))).then(function(){r.commands.delete(s)})}catch(e){return Promise.reject(e)}}},r.commands.set(s,n);try{r.sendMessage(t,s)}catch(e){}})).then(function(){return function(){return n.unsubscribe()}})}catch(e){return Promise.reject(e)}},i.prototype._handleMessage=function(e){var t=JSON.parse(e.data),n=this.commands.get(t.id);switch(t.type){case"event":n?n.callback(t.event):(console.warn("Received event for unknown subscription "+t.id+". Unsubscribing."),this.sendMessagePromise(o(t.id)));break;case"result":n&&(t.success?(n.resolve(t.result),"subscribe"in n||this.commands.delete(t.id)):(n.reject(t.error),this.commands.delete(t.id)));break;case"pong":n?(n.resolve(),this.commands.delete(t.id)):console.warn("Received unknown pong response "+t.id)}},i.prototype._handleClose=function(t){var n=this;if(this.commands.forEach(function(e){"subscribe"in e||e.reject({type:"result",success:!1,error:{code:3,message:"Connection lost"}})}),!this.closeRequested){this.fireEvent("disconnected");var r=Object.assign({},this.options,{setupRetry:0}),s=function(t){var o=n;setTimeout(function(){try{var n=e(function(){return Promise.resolve(r.createSocket(r)).then(function(e){o.setSocket(e)})},function(e){2===e?o.fireEvent("reconnect-error",e):s(t+1)});return Promise.resolve(n&&n.then?n.then(function(){}):void 0)}catch(e){return Promise.reject(e)}},1e3*Math.min(t,5))};s(0)}},i.prototype._genCmdId=function(){return++this.commandId};var c=function(t){void 0===t&&(t={});try{function n(){function n(){function e(){if(r)return new d(r,t.saveTokens);if(void 0===o)throw s;return function(e,t,n,r){n+=(n.includes("?")?"&":"?")+"auth_callback=1",document.location.href=function(e,t,n,r){var s=e+"/auth/authorize?response_type=code&client_id="+encodeURIComponent(t)+"&redirect_uri="+encodeURIComponent(n);return r&&(s+="&state="+encodeURIComponent(r)),s}(e,t,n,r)}(o,i,t.redirectUrl||location.protocol+"//"+location.host+location.pathname+location.search,btoa(JSON.stringify({hassUrl:o,clientId:i}))),new Promise(function(){})}var n=function(){if(!r&&t.loadTokens)return Promise.resolve(t.loadTokens()).then(function(e){r=e})}();return n&&n.then?n.then(e):e()}var c=function(){if(!r){var n=function(e){for(var t={},n=location.search.substr(1).split("&"),r=0;r<n.length;r++){var s=n[r].split("="),o=decodeURIComponent(s[0]),i=s.length>1?decodeURIComponent(s[1]):void 0;t[o]=i}return t}(),s=function(){if("auth_callback"in n){var s=JSON.parse(atob(n.state)),o=e(function(){return Promise.resolve(h(s.hassUrl,s.clientId,n.code)).then(function(e){r=e,t.saveTokens&&t.saveTokens(r)})},function(e){console.log("Unable to fetch access token",e)});if(o&&o.then)return o.then(function(){})}}();if(s&&s.then)return s.then(function(){})}}();return c&&c.then?c.then(n):n()}var r,o=t.hassUrl;o&&"/"===o[o.length-1]&&(o=o.substr(0,o.length-1));var i=t.clientId||a(),c=function(){if(!r&&t.authCode&&o&&i){var n=e(function(){return Promise.resolve(h(o,i,t.authCode)).then(function(e){r=e,t.saveTokens&&t.saveTokens(r)})},function(e){console.log("Unable to fetch access token",e)});if(n&&n.then)return n.then(function(){})}}();return Promise.resolve(c&&c.then?c.then(n):n())}catch(e){return Promise.reject(e)}},u=function(e,t,n){try{var r=new FormData;return r.append("client_id",t),Object.keys(n).forEach(function(e){r.append(e,n[e])}),Promise.resolve(fetch(e+"/auth/token",{method:"POST",credentials:"same-origin",body:r})).then(function(n){if(!n.ok)throw 400===n.status||403===n.status?2:new Error("Unable to fetch tokens");return Promise.resolve(n.json()).then(function(n){return n.hassUrl=e,n.clientId=t,n.expires=f(n.expires_in),n})})}catch(e){return Promise.reject(e)}},a=function(){return location.protocol+"//"+location.host+"/"},f=function(e){return 1e3*e+Date.now()};function h(e,t,n){return u(e,t,{code:n,grant_type:"authorization_code"})}var d=function(e,t){this.data=e,this._saveTokens=t},v={wsUrl:{configurable:!0},accessToken:{configurable:!0},expired:{configurable:!0}};v.wsUrl.get=function(){return"ws"+this.data.hassUrl.substr(4)+"/api/websocket"},v.accessToken.get=function(){return this.data.access_token},v.expired.get=function(){return Date.now()>this.data.expires},d.prototype.refreshAccessToken=function(){try{var e=this;return Promise.resolve(u(e.data.hassUrl,e.data.clientId,{grant_type:"refresh_token",refresh_token:e.data.refresh_token})).then(function(t){t.refresh_token=e.data.refresh_token,e.data=t,e._saveTokens&&e._saveTokens(t)})}catch(e){return Promise.reject(e)}},d.prototype.revoke=function(){try{var e=this,t=new FormData;return t.append("action","revoke"),t.append("token",e.data.refresh_token),Promise.resolve(fetch(e.data.hassUrl+"/auth/token",{method:"POST",credentials:"same-origin",body:t})).then(function(){e._saveTokens&&e._saveTokens(null)})}catch(e){return Promise.reject(e)}},Object.defineProperties(d.prototype,v);var l=function(e,t,n,r){if(e[t])return e[t];var s,o=0,i=function(e){var t=[];function n(n,r){e=r?n:Object.assign({},e,n);for(var s=t,o=0;o<s.length;o++)s[o](e)}return{get state(){return e},action:function(t){function r(e){n(e,!1)}return function(){for(var n=arguments,s=[e],o=0;o<arguments.length;o++)s.push(n[o]);var i=t.apply(this,s);if(null!=i)return i.then?i.then(r):r(i)}},setState:n,subscribe:function(e){return t.push(e),function(){!function(e){for(var n=[],r=0;r<t.length;r++)t[r]===e?e=null:n.push(t[r]);t=n}(e)}}}}(),c=function(){return n(e).then(function(e){return i.setState(e,!0)})},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==++o&&(r&&(s=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(),--o||(s&&s.then(function(e){e()}),e.removeEventListener("ready",c))}}},e[t]},m=function(e,t,n,r,s){return l(r,e,t,n).subscribe(s)},p=function(e){return e.sendMessagePromise({type:"get_states"})},b=function(e){return e.sendMessagePromise({type:"get_services"})},g=function(e){return e.sendMessagePromise({type:"get_config"})},y=function(e){return e.sendMessagePromise({type:"auth/current_user"})},k=function(e,t,n,r){return e.sendMessagePromise(function(e,t,n){var r={type:"call_service",domain:e,service:t};return n&&(r.service_data=n),r}(t,n,r))};function _(e,t){return void 0===e?null:{components:e.components.concat(t.data.component)}}var P=function(e){return g(e)},E=function(e,t){return Promise.all([e.subscribeEvents(t.action(_),"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()})}})},w=function(e,t){return function(e){return l(e,"_cnf",P,E)}(e).subscribe(t)};function j(e,t){var n,r;if(void 0===e)return null;var s=t.data,o=s.domain,i=Object.assign({},e[o],((n={})[s.service]={description:"",fields:{}},n));return(r={})[o]=i,r}function T(e,t){var n;if(void 0===e)return null;var r=t.data,s=r.domain,o=r.service,i=e[s];if(!(i&&o in i))return null;var c={};return Object.keys(i).forEach(function(e){e!==o&&(c[e]=i[e])}),(n={})[s]=c,n}var S=function(e){return b(e)},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 l(e,"_srv",S,M)}(e).subscribe(t)},U=function(e){try{return Promise.resolve(p(e)).then(function(e){for(var t={},n=0;n<e.length;n++){var r=e[n];t[r.entity_id]=r}return t})}catch(e){return Promise.reject(e)}},O=function(e,t){return e.subscribeEvents(function(e){return function(t,n){var r,s=t.state;if(void 0!==s){var o=e.data,i=o.entity_id,c=o.new_state;if(c)t.setState(((r={})[c.entity_id]=c,r));else{var u=Object.assign({},s);delete u[i],t.setState(u,!0)}}}(t)},"state_changed")},I=function(e){return l(e,"_ent",U,O)},C=function(e,t){return I(e).subscribe(t)},R=function(e){try{var t=Object.assign({},x,e);return Promise.resolve(t.createSocket(t)).then(function(e){return new i(e,t)})}catch(e){return Promise.reject(e)}},x={setupRetry:0,createSocket:function(t){if(!t.auth)throw s;var n=t.auth,r=n.expired?n.refreshAccessToken().then(function(){r=void 0},function(){r=void 0}):void 0,o=n.wsUrl;return new Promise(function(s,i){return function t(s,i,c){var u=new WebSocket(o),a=!1,f=function(){if(u.removeEventListener("close",f),a)c(2);else if(0!==s){var e=-1===s?-1:s-1;setTimeout(function(){return t(e,i,c)},1e3)}else c(1)},h=function(t){try{var s=e(function(){function e(){u.send(JSON.stringify({type:"auth",access_token:n.accessToken}))}var t=function(){if(n.expired)return Promise.resolve(r||n.refreshAccessToken()).then(function(){})}();return t&&t.then?t.then(e):e()},function(e){a=2===e,u.close()});return Promise.resolve(s&&s.then?s.then(function(){}):void 0)}catch(e){return Promise.reject(e)}},d=function(e){try{switch(JSON.parse(e.data).type){case"auth_invalid":a=!0,u.close();break;case"auth_ok":u.removeEventListener("open",h),u.removeEventListener("message",d),u.removeEventListener("close",f),u.removeEventListener("error",f),i(u)}return}catch(e){return Promise.reject(e)}};u.addEventListener("open",h),u.addEventListener("message",d),u.addEventListener("close",f),u.addEventListener("error",f)}(t.setupRetry,s,i)})}};export{R as createConnection,c as getAuth,a as genClientId,f as genExpires,d as Auth,l as getCollection,m as createCollection,i as Connection,w as subscribeConfig,L as subscribeServices,I as entitiesColl,C as subscribeEntities,t as ERR_CANNOT_CONNECT,n as ERR_INVALID_AUTH,r as ERR_CONNECTION_LOST,s as ERR_HASS_HOST_REQUIRED,p as getStates,b as getServices,g as getConfig,y as getUser,k as callService};
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(t){void 0===t&&(t={});try{function n(){function n(){function e(){if(r)return new v(r,t.saveTokens);if(void 0===s)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)}(s,i,t.redirectUrl||location.protocol+"//"+location.host+location.pathname+location.search,btoa(JSON.stringify({hassUrl:s,clientId:i}))),new Promise(function(){})}var n=function(){if(!r&&t.loadTokens)return Promise.resolve(t.loadTokens()).then(function(e){r=e})}();return n&&n.then?n.then(e):e()}var c=function(){if(!r){var n=function(e){for(var t={},n=location.search.substr(1).split("&"),r=0;r<n.length;r++){var o=n[r].split("="),s=decodeURIComponent(o[0]),i=o.length>1?decodeURIComponent(o[1]):void 0;t[s]=i}return t}(),o=function(){if("auth_callback"in n){var o=JSON.parse(atob(n.state)),s=e(function(){return Promise.resolve(d(o.hassUrl,o.clientId,n.code)).then(function(e){r=e,t.saveTokens&&t.saveTokens(r)})},function(e){console.log("Unable to fetch access token",e)});if(s&&s.then)return s.then(function(){})}}();if(o&&o.then)return o.then(function(){})}}();return c&&c.then?c.then(n):n()}var r,s=t.hassUrl;s&&"/"===s[s.length-1]&&(s=s.substr(0,s.length-1));var i=t.clientId||f(),c=function(){if(!r&&t.authCode&&s&&i){var n=e(function(){return Promise.resolve(d(s,i,t.authCode)).then(function(e){r=e,t.saveTokens&&t.saveTokens(r)})},function(e){console.log("Unable to fetch access token",e)});if(n&&n.then)return n.then(function(){})}}();return Promise.resolve(c&&c.then?c.then(n):n())}catch(e){return Promise.reject(e)}},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=h(n.expires_in),n})})}catch(e){return Promise.reject(e)}},f=function(){return location.protocol+"//"+location.host+"/"},h=function(e){return 1e3*e+Date.now()};function d(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)},U=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)}},O=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",U,O)},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)},h=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)}},d=function(e){try{switch(JSON.parse(e.data).type){case"auth_invalid":a=!0,u.close();break;case"auth_ok":u.removeEventListener("open",h),u.removeEventListener("message",d),u.removeEventListener("close",f),u.removeEventListener("error",f),i(u)}return Promise.resolve()}catch(e){return Promise.reject(e)}};u.addEventListener("open",h),u.addEventListener("message",d),u.addEventListener("close",f),u.addEventListener("error",f)}(t.setupRetry,o,i)})}};export{x as createConnection,u as getAuth,f as genClientId,h 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}var t=4;function n(e){return{type:"unsubscribe_events",subscription:e}}var r=function(e,t){this.options=t,this.commandId=1,this.commands=new Map,this.eventListeners=new Map,this.closeRequested=!1,this.setSocket(e)};r.prototype.setSocket=function(e){var t=this,n=this.socket;if(this.socket=e,e.addEventListener("message",function(e){return t._handleMessage(e)}),e.addEventListener("close",function(e){return t._handleClose(e)}),n){var r=this.commands;this.commandId=1,this.commands=new Map,r.forEach(function(e){"subscribe"in e&&e.subscribe().then(function(t){e.unsubscribe=t,e.resolve()})}),this.fireEvent("ready")}},r.prototype.addEventListener=function(e,t){var n=this.eventListeners.get(e);n||this.eventListeners.set(e,n=[]),n.push(t)},r.prototype.removeEventListener=function(e,t){var n=this.eventListeners.get(e);if(n){var r=n.indexOf(t);-1!==r&&n.splice(r,1)}},r.prototype.fireEvent=function(e,t){var n=this;(this.eventListeners.get(e)||[]).forEach(function(e){return e(n,t)})},r.prototype.close=function(){this.closeRequested=!0,this.socket.close()},r.prototype.subscribeEvents=function(e,t){try{return this.subscribeMessage(e,function(e){var t={type:"subscribe_events"};return e&&(t.event_type=e),t}(t))}catch(e){return Promise.reject(e)}},r.prototype.ping=function(){return this.sendMessagePromise({type:"ping"})},r.prototype.sendMessage=function(e,t){t||(t=this._genCmdId()),e.id=t,this.socket.send(JSON.stringify(e))},r.prototype.sendMessagePromise=function(e){var t=this;return new Promise(function(n,r){var s=t._genCmdId();t.commands.set(s,{resolve:n,reject:r}),t.sendMessage(e,s)})},r.prototype.subscribeMessage=function(e,t){try{var r,s=this,o=s._genCmdId();return Promise.resolve(new Promise(function(i,c){r={resolve:i,reject:c,callback:e,subscribe:function(){return s.subscribeMessage(e,t)},unsubscribe:function(){try{return Promise.resolve(s.sendMessagePromise(n(o))).then(function(){s.commands.delete(o)})}catch(e){return Promise.reject(e)}}},s.commands.set(o,r);try{s.sendMessage(t,o)}catch(e){}})).then(function(){return function(){return r.unsubscribe()}})}catch(e){return Promise.reject(e)}},r.prototype._handleMessage=function(e){var t=JSON.parse(e.data),r=this.commands.get(t.id);switch(t.type){case"event":r?r.callback(t.event):(console.warn("Received event for unknown subscription "+t.id+". Unsubscribing."),this.sendMessagePromise(n(t.id)));break;case"result":r&&(t.success?(r.resolve(t.result),"subscribe"in r||this.commands.delete(t.id)):(r.reject(t.error),this.commands.delete(t.id)));break;case"pong":r?(r.resolve(),this.commands.delete(t.id)):console.warn("Received unknown pong response "+t.id)}},r.prototype._handleClose=function(t){var n=this;if(this.commands.forEach(function(e){"subscribe"in e||e.reject({type:"result",success:!1,error:{code:3,message:"Connection lost"}})}),!this.closeRequested){this.fireEvent("disconnected");var r=Object.assign({},this.options,{setupRetry:0}),s=function(t){var o=n;setTimeout(function(){try{var n=e(function(){return Promise.resolve(r.createSocket(r)).then(function(e){o.setSocket(e)})},function(e){2===e?o.fireEvent("reconnect-error",e):s(t+1)});return Promise.resolve(n&&n.then?n.then(function(){}):void 0)}catch(e){return Promise.reject(e)}},1e3*Math.min(t,5))};s(0)}},r.prototype._genCmdId=function(){return++this.commandId};var s=function(e,t,n){try{var r=new FormData;return r.append("client_id",t),Object.keys(n).forEach(function(e){r.append(e,n[e])}),Promise.resolve(fetch(e+"/auth/token",{method:"POST",credentials:"same-origin",body:r})).then(function(n){if(!n.ok)throw 400===n.status||403===n.status?2:new Error("Unable to fetch tokens");return Promise.resolve(n.json()).then(function(n){return n.hassUrl=e,n.clientId=t,n.expires=i(n.expires_in),n})})}catch(e){return Promise.reject(e)}},o=function(){return location.protocol+"//"+location.host+"/"},i=function(e){return 1e3*e+Date.now()};function c(e,t,n){return s(e,t,{code:n,grant_type:"authorization_code"})}var u=function(e,t){this.data=e,this._saveTokens=t},a={wsUrl:{configurable:!0},accessToken:{configurable:!0},expired:{configurable:!0}};a.wsUrl.get=function(){return"ws"+this.data.hassUrl.substr(4)+"/api/websocket"},a.accessToken.get=function(){return this.data.access_token},a.expired.get=function(){return Date.now()>this.data.expires},u.prototype.refreshAccessToken=function(){try{var e=this;return Promise.resolve(s(e.data.hassUrl,e.data.clientId,{grant_type:"refresh_token",refresh_token:e.data.refresh_token})).then(function(t){t.refresh_token=e.data.refresh_token,e.data=t,e._saveTokens&&e._saveTokens(t)})}catch(e){return Promise.reject(e)}},u.prototype.revoke=function(){try{var e=this,t=new FormData;return t.append("action","revoke"),t.append("token",e.data.refresh_token),Promise.resolve(fetch(e.data.hassUrl+"/auth/token",{method:"POST",credentials:"same-origin",body:t})).then(function(){e._saveTokens&&e._saveTokens(null)})}catch(e){return Promise.reject(e)}},Object.defineProperties(u.prototype,a);var f=function(e,t,n,r){if(e[t])return e[t];var s,o=0,i=function(e){var t=[];function n(n,r){e=r?n:Object.assign({},e,n);for(var s=t,o=0;o<s.length;o++)s[o](e)}return{get state(){return e},action:function(t){function r(e){n(e,!1)}return function(){for(var n=arguments,s=[e],o=0;o<arguments.length;o++)s.push(n[o]);var i=t.apply(this,s);if(null!=i)return i.then?i.then(r):r(i)}},setState:n,subscribe:function(e){return t.push(e),function(){!function(e){for(var n=[],r=0;r<t.length;r++)t[r]===e?e=null:n.push(t[r]);t=n}(e)}}}}(),c=function(){return n(e).then(function(e){return i.setState(e,!0)})},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==++o&&(r&&(s=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(),--o||(s&&s.then(function(e){e()}),e.removeEventListener("ready",c))}}},e[t]},h=function(e){return e.sendMessagePromise({type:"get_states"})},d=function(e){return e.sendMessagePromise({type:"get_services"})},v=function(e){return e.sendMessagePromise({type:"get_config"})};function l(e,t){return void 0===e?null:{components:e.components.concat(t.data.component)}}var p=function(e){return v(e)},m=function(e,t){return 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 s=t.data,o=s.domain,i=Object.assign({},e[o],((n={})[s.service]={description:"",fields:{}},n));return(r={})[o]=i,r}function g(e,t){var n;if(void 0===e)return null;var r=t.data,s=r.domain,o=r.service,i=e[s];if(!(i&&o in i))return null;var c={};return Object.keys(i).forEach(function(e){e!==o&&(c[e]=i[e])}),(n={})[s]=c,n}var y=function(e){return d(e)},_=function(e,t){return Promise.all([e.subscribeEvents(t.action(b),"service_registered"),e.subscribeEvents(t.action(g),"service_removed")]).then(function(e){return function(){return e.forEach(function(e){return e()})}})},k=function(e){try{return Promise.resolve(h(e)).then(function(e){for(var t={},n=0;n<e.length;n++){var r=e[n];t[r.entity_id]=r}return t})}catch(e){return Promise.reject(e)}},P=function(e,t){return e.subscribeEvents(function(e){return function(t,n){var r,s=t.state;if(void 0!==s){var o=e.data,i=o.entity_id,c=o.new_state;if(c)t.setState(((r={})[c.entity_id]=c,r));else{var u=Object.assign({},s);delete u[i],t.setState(u,!0)}}}(t)},"state_changed")},E=function(e){return f(e,"_ent",k,P)},w={setupRetry:0,createSocket:function(n){if(!n.auth)throw t;var r=n.auth,s=r.expired?r.refreshAccessToken().then(function(){s=void 0},function(){s=void 0}):void 0,o=r.wsUrl;return new Promise(function(t,i){return function t(n,i,c){var u=new WebSocket(o),a=!1,f=function(){if(u.removeEventListener("close",f),a)c(2);else if(0!==n){var e=-1===n?-1:n-1;setTimeout(function(){return t(e,i,c)},1e3)}else c(1)},h=function(t){try{var n=e(function(){function e(){u.send(JSON.stringify({type:"auth",access_token:r.accessToken}))}var t=function(){if(r.expired)return Promise.resolve(s||r.refreshAccessToken()).then(function(){})}();return t&&t.then?t.then(e):e()},function(e){a=2===e,u.close()});return Promise.resolve(n&&n.then?n.then(function(){}):void 0)}catch(e){return Promise.reject(e)}},d=function(e){try{switch(JSON.parse(e.data).type){case"auth_invalid":a=!0,u.close();break;case"auth_ok":u.removeEventListener("open",h),u.removeEventListener("message",d),u.removeEventListener("close",f),u.removeEventListener("error",f),i(u)}return}catch(e){return Promise.reject(e)}};u.addEventListener("open",h),u.addEventListener("message",d),u.addEventListener("close",f),u.addEventListener("error",f)}(n.setupRetry,t,i)})}};exports.createConnection=function(e){try{var t=Object.assign({},w,e);return Promise.resolve(t.createSocket(t)).then(function(e){return new r(e,t)})}catch(e){return Promise.reject(e)}},exports.getAuth=function(n){void 0===n&&(n={});try{function r(){function r(){function e(){if(s)return new u(s,n.saveTokens);if(void 0===i)throw t;return function(e,t,n,r){n+=(n.includes("?")?"&":"?")+"auth_callback=1",document.location.href=function(e,t,n,r){var s=e+"/auth/authorize?response_type=code&client_id="+encodeURIComponent(t)+"&redirect_uri="+encodeURIComponent(n);return r&&(s+="&state="+encodeURIComponent(r)),s}(e,t,n,r)}(i,a,n.redirectUrl||location.protocol+"//"+location.host+location.pathname+location.search,btoa(JSON.stringify({hassUrl:i,clientId:a}))),new Promise(function(){})}var r=function(){if(!s&&n.loadTokens)return Promise.resolve(n.loadTokens()).then(function(e){s=e})}();return r&&r.then?r.then(e):e()}var o=function(){if(!s){var t=function(e){for(var t={},n=location.search.substr(1).split("&"),r=0;r<n.length;r++){var s=n[r].split("="),o=decodeURIComponent(s[0]),i=s.length>1?decodeURIComponent(s[1]):void 0;t[o]=i}return t}(),r=function(){if("auth_callback"in t){var r=JSON.parse(atob(t.state)),o=e(function(){return Promise.resolve(c(r.hassUrl,r.clientId,t.code)).then(function(e){s=e,n.saveTokens&&n.saveTokens(s)})},function(e){console.log("Unable to fetch access token",e)});if(o&&o.then)return o.then(function(){})}}();if(r&&r.then)return r.then(function(){})}}();return o&&o.then?o.then(r):r()}var s,i=n.hassUrl;i&&"/"===i[i.length-1]&&(i=i.substr(0,i.length-1));var a=n.clientId||o(),f=function(){if(!s&&n.authCode&&i&&a){var t=e(function(){return Promise.resolve(c(i,a,n.authCode)).then(function(e){s=e,n.saveTokens&&n.saveTokens(s)})},function(e){console.log("Unable to fetch access token",e)});if(t&&t.then)return t.then(function(){})}}();return Promise.resolve(f&&f.then?f.then(r):r())}catch(e){return Promise.reject(e)}},exports.genClientId=o,exports.genExpires=i,exports.Auth=u,exports.getCollection=f,exports.createCollection=function(e,t,n,r,s){return f(r,e,t,n).subscribe(s)},exports.Connection=r,exports.subscribeConfig=function(e,t){return function(e){return f(e,"_cnf",p,m)}(e).subscribe(t)},exports.subscribeServices=function(e,t){return function(e){return f(e,"_srv",y,_)}(e).subscribe(t)},exports.entitiesColl=E,exports.subscribeEntities=function(e,t){return E(e).subscribe(t)},exports.ERR_CANNOT_CONNECT=1,exports.ERR_INVALID_AUTH=2,exports.ERR_CONNECTION_LOST=3,exports.ERR_HASS_HOST_REQUIRED=t,exports.getStates=h,exports.getServices=d,exports.getConfig=v,exports.getUser=function(e){return e.sendMessagePromise({type:"auth/current_user"})},exports.callService=function(e,t,n,r){return e.sendMessagePromise(function(e,t,n){var r={type:"call_service",domain:e,service:t};return n&&(r.service_data=n),r}(t,n,r))};
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]},h=function(e){return e.sendMessagePromise({type:"get_states"})},d=function(e){return e.sendMessagePromise({type:"get_services"})},v=function(e){return e.sendMessagePromise({type:"get_config"})};function l(e,t){return void 0===e?null:{components:e.components.concat(t.data.component)}}var p=function(e){return v(e)},m=function(e,t){return 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 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 y=function(e){return d(e)},_=function(e,t){return Promise.all([e.subscribeEvents(t.action(b),"service_registered"),e.subscribeEvents(t.action(g),"service_removed")]).then(function(e){return function(){return e.forEach(function(e){return e()})}})},k=function(e){try{return Promise.resolve(h(e)).then(function(e){for(var t={},n=0;n<e.length;n++){var r=e[n];t[r.entity_id]=r}return t})}catch(e){return Promise.reject(e)}},P=function(e,t){return e.subscribeEvents(function(e){return function(t,n){var r,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)},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{switch(JSON.parse(e.data).type){case"auth_invalid":a=!0,u.close();break;case"auth_ok":u.removeEventListener("open",h),u.removeEventListener("message",d),u.removeEventListener("close",f),u.removeEventListener("error",f),i(u)}return 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({},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(n){void 0===n&&(n={});try{function r(){function r(){function e(){if(o)return new u(o,n.saveTokens);if(void 0===i)throw t;return function(e,t,n,r){n+=(n.includes("?")?"&":"?")+"auth_callback=1",document.location.href=function(e,t,n,r){var 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)}(i,a,n.redirectUrl||location.protocol+"//"+location.host+location.pathname+location.search,btoa(JSON.stringify({hassUrl:i,clientId:a}))),new Promise(function(){})}var r=function(){if(!o&&n.loadTokens)return Promise.resolve(n.loadTokens()).then(function(e){o=e})}();return r&&r.then?r.then(e):e()}var s=function(){if(!o){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)),s=e(function(){return Promise.resolve(c(r.hassUrl,r.clientId,t.code)).then(function(e){o=e,n.saveTokens&&n.saveTokens(o)})},function(e){console.log("Unable to fetch access token",e)});if(s&&s.then)return s.then(function(){})}}();if(r&&r.then)return r.then(function(){})}}();return s&&s.then?s.then(r):r()}var o,i=n.hassUrl;i&&"/"===i[i.length-1]&&(i=i.substr(0,i.length-1));var a=n.clientId||s(),f=function(){if(!o&&n.authCode&&i&&a){var t=e(function(){return Promise.resolve(c(i,a,n.authCode)).then(function(e){o=e,n.saveTokens&&n.saveTokens(o)})},function(e){console.log("Unable to fetch access token",e)});if(t&&t.then)return t.then(function(){})}}();return Promise.resolve(f&&f.then?f.then(r):r())}catch(e){return Promise.reject(e)}},exports.genClientId=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",y,_)}(e).subscribe(t)},exports.entitiesColl=E,exports.subscribeEntities=function(e,t){return E(e).subscribe(t)},exports.ERR_CANNOT_CONNECT=1,exports.ERR_INVALID_AUTH=2,exports.ERR_CONNECTION_LOST=3,exports.ERR_HASS_HOST_REQUIRED=t,exports.ERR_INVALID_HTTPS_TO_HTTP=5,exports.getStates=h,exports.getServices=d,exports.getConfig=v,exports.getUser=function(e){return e.sendMessagePromise({type:"auth/current_user"})},exports.callService=function(e,t,n,r){return e.sendMessagePromise(function(e,t,n){var r={type:"call_service",domain:e,service:t};return n&&(r.service_data=n),r}(t,n,r))};
//# sourceMappingURL=haws.js.map

@@ -1,2 +0,2 @@

!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):t(e.HAWS={})}(this,function(e){function t(e,t){try{var n=e()}catch(e){return t(e)}return n&&n.then?n.then(void 0,t):n}var n=4;function r(e){return{type:"unsubscribe_events",subscription:e}}var 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=new FormData;return r.append("client_id",t),Object.keys(n).forEach(function(e){r.append(e,n[e])}),Promise.resolve(fetch(e+"/auth/token",{method:"POST",credentials:"same-origin",body:r})).then(function(n){if(!n.ok)throw 400===n.status||403===n.status?2:new Error("Unable to fetch tokens");return Promise.resolve(n.json()).then(function(n){return n.hassUrl=e,n.clientId=t,n.expires=c(n.expires_in),n})})}catch(e){return Promise.reject(e)}},i=function(){return location.protocol+"//"+location.host+"/"},c=function(e){return 1e3*e+Date.now()};function u(e,t,n){return 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 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(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")},w=function(e){return d(e,"_ent",P,E)},S={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}catch(e){return Promise.reject(e)}};u.addEventListener("open",d),u.addEventListener("message",h),u.addEventListener("close",f),u.addEventListener("error",f)}(e.setupRetry,n,i)})}};e.createConnection=function(e){try{var t=Object.assign({},S,e);return Promise.resolve(t.createSocket(t)).then(function(e){return new o(e,t)})}catch(e){return Promise.reject(e)}},e.getAuth=function(e){void 0===e&&(e={});try{function r(){function r(){function t(){if(o)return new a(o,e.saveTokens);if(void 0===s)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)}(s,c,e.redirectUrl||location.protocol+"//"+location.host+location.pathname+location.search,btoa(JSON.stringify({hassUrl:s,clientId:c}))),new Promise(function(){})}var r=function(){if(!o&&e.loadTokens)return Promise.resolve(e.loadTokens()).then(function(e){o=e})}();return r&&r.then?r.then(t):t()}var i=function(){if(!o){var n=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 n){var r=JSON.parse(atob(n.state)),s=t(function(){return Promise.resolve(u(r.hassUrl,r.clientId,n.code)).then(function(t){o=t,e.saveTokens&&e.saveTokens(o)})},function(e){console.log("Unable to fetch access token",e)});if(s&&s.then)return s.then(function(){})}}();if(r&&r.then)return r.then(function(){})}}();return i&&i.then?i.then(r):r()}var o,s=e.hassUrl;s&&"/"===s[s.length-1]&&(s=s.substr(0,s.length-1));var c=e.clientId||i(),f=function(){if(!o&&e.authCode&&s&&c){var n=t(function(){return Promise.resolve(u(s,c,e.authCode)).then(function(t){o=t,e.saveTokens&&e.saveTokens(o)})},function(e){console.log("Unable to fetch access token",e)});if(n&&n.then)return n.then(function(){})}}();return Promise.resolve(f&&f.then?f.then(r):r())}catch(e){return Promise.reject(e)}},e.genClientId=i,e.genExpires=c,e.Auth=a,e.getCollection=d,e.createCollection=function(e,t,n,r,o){return d(r,e,t,n).subscribe(o)},e.Connection=o,e.subscribeConfig=function(e,t){return function(e){return d(e,"_cnf",m,b)}(e).subscribe(t)},e.subscribeServices=function(e,t){return function(e){return d(e,"_srv",_,k)}(e).subscribe(t)},e.entitiesColl=w,e.subscribeEntities=function(e,t){return w(e).subscribe(t)},e.ERR_CANNOT_CONNECT=1,e.ERR_INVALID_AUTH=2,e.ERR_CONNECTION_LOST=3,e.ERR_HASS_HOST_REQUIRED=n,e.getStates=h,e.getServices=v,e.getConfig=l,e.getUser=function(e){return e.sendMessagePromise({type:"auth/current_user"})},e.callService=function(e,t,n,r){return e.sendMessagePromise(function(e,t,n){var r={type:"call_service",domain:e,service:t};return n&&(r.service_data=n),r}(t,n,r))}});
!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 r(){function r(){function t(){if(o)return new a(o,e.saveTokens);if(void 0===s)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)}(s,c,e.redirectUrl||location.protocol+"//"+location.host+location.pathname+location.search,btoa(JSON.stringify({hassUrl:s,clientId:c}))),new Promise(function(){})}var r=function(){if(!o&&e.loadTokens)return Promise.resolve(e.loadTokens()).then(function(e){o=e})}();return r&&r.then?r.then(t):t()}var i=function(){if(!o){var n=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 n){var r=JSON.parse(atob(n.state)),s=t(function(){return Promise.resolve(u(r.hassUrl,r.clientId,n.code)).then(function(t){o=t,e.saveTokens&&e.saveTokens(o)})},function(e){console.log("Unable to fetch access token",e)});if(s&&s.then)return s.then(function(){})}}();if(r&&r.then)return r.then(function(){})}}();return i&&i.then?i.then(r):r()}var o,s=e.hassUrl;s&&"/"===s[s.length-1]&&(s=s.substr(0,s.length-1));var c=e.clientId||i(),f=function(){if(!o&&e.authCode&&s&&c){var n=t(function(){return Promise.resolve(u(s,c,e.authCode)).then(function(t){o=t,e.saveTokens&&e.saveTokens(o)})},function(e){console.log("Unable to fetch access token",e)});if(n&&n.then)return n.then(function(){})}}();return Promise.resolve(f&&f.then?f.then(r):r())}catch(e){return Promise.reject(e)}},e.genClientId=i,e.genExpires=c,e.Auth=a,e.getCollection=d,e.createCollection=function(e,t,n,r,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.2.2",
"version": "4.3.0",
"description": "Home Assistant websocket client",

@@ -25,10 +25,10 @@ "source": "lib/index.ts",

"devDependencies": {
"@types/mocha": "^5.2.6",
"husky": "^1.3.1",
"lint-staged": "^8.1.5",
"@types/mocha": "^5.2.7",
"husky": "^3.0.1",
"lint-staged": "^9.2.0",
"microbundle": "^0.11.0",
"mocha": "^6.1.4",
"prettier": "^1.17.0",
"ts-node": "^8.1.0",
"typescript": "^3.4.5"
"mocha": "^6.2.0",
"prettier": "^1.18.2",
"ts-node": "^8.3.0",
"typescript": "^3.5.3"
},

@@ -35,0 +35,0 @@ "files": [

@@ -88,7 +88,8 @@ # :aerial_tramway: JavaScript websocket client for Home Assistant

| Error | Description |
| ------------------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `ERR_HASS_HOST_REQUIRED` | You need to pass in `hassUrl` to `getAuth` to continue getting auth. This option is not needed when the user is redirected back after successfully logging in. |
| `ERR_INVALID_AUTH` | This error will be raised if the url contains an authorization code that is no longer valid. |
| Other errors | Unknown error! |
| Error | Description |
| --------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `ERR_HASS_HOST_REQUIRED` | You need to pass in `hassUrl` to `getAuth` to continue getting auth. This option is not needed when the user is redirected back after successfully logging in. |
| `ERR_INVALID_AUTH` | This error will be raised if the url contains an authorization code that is no longer valid. |
| `ERR_INVALID_HTTPS_TO_HTTP` | This error is raised if your code is being run from a secure context (hosted via https) and you're trying to fetch tokens from a Home Assistant instance via a non secure context (http). This is called [mixed active content](https://developer.mozilla.org/en-US/docs/Web/Security/Mixed_content#Mixed_active_content) and the browser forbids this. |
| Other errors | Unknown error! |

@@ -335,2 +336,12 @@ ### `createConnection()`

## Error Reference
| Error constant | Error number |
| ------------------------- | ------------ |
| ERR_CANNOT_CONNECT | 1 |
| ERR_INVALID_AUTH | 2 |
| ERR_CONNECTION_LOST | 3 |
| ERR_HASS_HOST_REQUIRED | 4 |
| ERR_INVALID_HTTPS_TO_HTTP | 5 |
## Other methods

@@ -337,0 +348,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

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc