@hakit/core
Version:
A collection of React hooks and helpers for Home Assistant to easily communicate with the Home Assistant WebSocket API.
3 lines (2 loc) • 2.67 kB
JavaScript
;Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const r=require("home-assistant-js-websocket"),s=require("./token-storage.js");function i(t,n){const o=(()=>{switch(t){case r.ERR_INVALID_AUTH:return`ERR_INVALID_AUTH: Invalid authentication. ${n?'Check your "Long-Lived Access Token".':""}`;case r.ERR_CANNOT_CONNECT:return"ERR_CANNOT_CONNECT: Unable to connect";case r.ERR_CONNECTION_LOST:return"ERR_CONNECTION_LOST: Lost connection to home assistant.";case r.ERR_HASS_HOST_REQUIRED:return"ERR_HASS_HOST_REQUIRED: Please enter a Home Assistant URL.";case r.ERR_INVALID_HTTPS_TO_HTTP:return'ERR_INVALID_HTTPS_TO_HTTP: Cannot connect to Home Assistant instances over "http://".';default:return null}})();return o!==null?o:t?.error||t?.message||`Unknown Error (${t})`}function d(){try{return window.top?.hassConnection}catch(t){console.error("Error getting inherited connection",t);return}}function R(t,n){const c=location&&location.search.includes("auth_callback=1"),o=!!d(),a=!!n,u=!!s.loadTokens(t,!1);switch(!0){case c:return"auth-callback";case o:return"inherited-auth";case a:return"provided-token";case u:return"saved-tokens";default:return"user-request"}}const _=async(t,n)=>{const c=R(t,n);if(c==="inherited-auth")try{const{auth:e,conn:l}=await d();return{type:"success",connection:l,auth:e}}catch(e){return{type:"error",error:i(e,n)}}if(c==="provided-token"&&n)try{const e=await r.createLongLivedTokenAuth(t,n);return{type:"success",connection:await r.createConnection({auth:e}),auth:e}}catch(e){return{type:"error",error:i(e,n)}}const o={saveTokens:s.saveTokens,loadTokens:()=>Promise.resolve(s.loadTokens(t))};if(t&&c==="user-request"){if(o.hassUrl=t,o.hassUrl==="")return{type:"error",error:"Please enter a Home Assistant URL."};if(o.hassUrl.indexOf("://")===-1)return{type:"error",error:"Please enter your full URL, including the protocol part (https://)."};try{new URL(o.hassUrl)}catch(e){return console.error("Error:",e),{type:"error",error:"Invalid URL"}}}let a;try{a=await r.getAuth(o)}catch(e){return e?.error==="invalid_grant"?(s.clearTokens(),_(t,n)):c==="saved-tokens"&&e===r.ERR_CANNOT_CONNECT?{type:"failed",cannotConnect:!0}:{type:"error",error:i(e,n)}}finally{location&&location.search.includes("auth_callback=1")&&history.replaceState(null,"",location.pathname)}let u;try{u=await r.createConnection({auth:a})}catch(e){if(c==="saved-tokens"){if(e===r.ERR_CANNOT_CONNECT)return{type:"failed",cannotConnect:!0};e===r.ERR_INVALID_AUTH&&s.saveTokens(null)}return{type:"error",error:i(e,n)}}return{type:"success",connection:u,auth:a}};exports.handleError=i;exports.tryConnection=_;
//# sourceMappingURL=tryConnection.js.map