@tenminuteschool/auth-react 0.3.0 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.ts CHANGED
@@ -3,7 +3,7 @@
3
3
  * Public entrypoint for the @10minuteschool/auth browser SDK.
4
4
  */
5
5
  /** Current SDK version. */
6
- export declare const VERSION = "0.3.0";
6
+ export declare const VERSION = "0.4.0";
7
7
  export { TenMSAuth } from './core/TenMSAuth';
8
8
  /** Public types and error contract. */
9
9
  export type { AuthResponse, LoginButtonOptions, PopupOptions, Session, TenMSAuthConfig, TokenResponse, UserInfo, } from './core/types';
@@ -1,2 +1,2 @@
1
- "use strict";function e(e){var t=Object.create(null);return e&&Object.keys(e).forEach(function(n){if("default"!==n){var o=Object.getOwnPropertyDescriptor(e,n);Object.defineProperty(t,n,o.get?o:{enumerable:!0,get:function(){return e[n]}})}}),t.default=e,Object.freeze(t)}var t=e(require("react"));class n extends Error{constructor(e,t){super(e),this.name="TenMSAuthError",this.code=t,Object.setPrototypeOf(this,new.target.prototype)}}const o="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~";function i(e=64){a(e,43,128,"code_verifier length");const t=[];for(;t.length<e;){const n=new Uint8Array(e+16);crypto.getRandomValues(n);for(const i of n){if(t.length>=e)break;i<198&&t.push(o[i%66])}}return t.join("")}async function r(e){if(!e)throw new Error("codeVerifier is required to generate a code challenge");const t=(new TextEncoder).encode(e);return function(e){const t=new Uint8Array(e);let n="";for(const e of t)n+=String.fromCharCode(e);return btoa(n).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}(await crypto.subtle.digest("SHA-256",t))}function s(e=32){a(e,1,1024,"state byte length");const t=new Uint8Array(e);return crypto.getRandomValues(t),Array.from(t,e=>e.toString(16).padStart(2,"0")).join("")}function a(e,t,n,o){if(!Number.isInteger(e)||e<t||e>n)throw new RangeError(`${o} must be an integer between ${t} and ${n}`)}function c(e){d(e.width,"popup width"),d(e.height,"popup height");const t="number"==typeof window.screenX?window.screenX:window.screenLeft,n="number"==typeof window.screenY?window.screenY:window.screenTop,o=Math.round(t+Math.max(0,(window.innerWidth-e.width)/2)),i=Math.round(n+Math.max(0,(window.innerHeight-e.height)/2)),r=[`width=${e.width}`,`height=${e.height}`,`left=${o}`,`top=${i}`,"toolbar=no","menubar=no","scrollbars=yes","resizable=yes","status=no"].join(",");return window.open(e.url,"tenms_auth_popup",r)}function l(e,t,o,i=3e5){if(!t)throw new Error("redirectUri is required to monitor popup redirects");if(!o)throw new Error("expectedState is required to validate the popup callback");let r;d(i,"popup timeout");try{r=new URL(t)}catch(e){throw new n(`redirectUri is not a valid URL: "${t}"`,"invalid_redirect_uri")}return new Promise((t,s)=>{const a=Date.now(),c=window.setInterval(()=>{try{if(!e||e.closed)return window.clearInterval(c),void s(new n("Login popup was closed","popup_closed"));if(Date.now()-a>i)return window.clearInterval(c),e.close(),void s(new n("Login timed out while waiting for the redirect URI","popup_timeout"));const l=e.location.href;if(!l)return;let d;try{d=new URL(l)}catch(e){return}if(d.origin!==r.origin||d.pathname!==r.pathname)return;window.clearInterval(c),e.close();const h=d.searchParams.get("code"),u=d.searchParams.get("state"),g=d.searchParams.get("error"),f=d.searchParams.get("error_description");if(g)return void s(new n(f||g,"oauth_error"));if(!h)return void s(new n("No authorization code was returned to the redirect URI","missing_authorization_code"));if(u!==o)return void s(new n("State mismatch — possible CSRF attack","state_mismatch"));t({code:h,state:u})}catch(e){e instanceof DOMException||(window.clearInterval(c),s(e instanceof Error?e:new Error(String(e))))}},500)})}function d(e,t){if(!Number.isInteger(e)||e<=0)throw new RangeError(`${t} must be a positive integer`)}const h="[TenMSAuth]",u="color:#22c55e;font-weight:700",g="color:inherit;font-weight:normal";function f(e){return e?m:p}const p={info:()=>{},warn:()=>{},error:()=>{}},m={info(e,t){t&&Object.keys(t).length>0?(console.groupCollapsed(`%c${h}%c ${e}`,u,g),console.table(t),console.groupEnd()):console.log(`%c${h}%c ${e}`,u,g)},warn(e,t){console.warn(`%c${h}%c ⚠ ${e}`,u,g,null!=t?t:"")},error(e,t){console.error(`%c${h}%c ✕ ${e}`,u,g,null!=t?t:"")}};function w(e){return e?e.length>8?`${e.slice(0,8)}…`:e:"(empty)"}class b{get(e){const t=document.cookie.match(new RegExp("(?:^|; )"+e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")+"=([^;]*)"));return t?decodeURIComponent(t[1]):null}set(e,t,n){let o=`${e}=${encodeURIComponent(t)}; path=/; SameSite=Lax`;n&&(o+=`; expires=${new Date(1e3*n).toUTCString()}`),document.cookie=o}remove(e){document.cookie=`${e}=; path=/; expires=Thu, 01 Jan 1970 00:00:00 GMT; SameSite=Lax`}clear(e){e.forEach(e=>this.remove(e))}}class _{get(e){return localStorage.getItem(e)}set(e,t){localStorage.setItem(e,t)}remove(e){localStorage.removeItem(e)}clear(e){e.forEach(e=>this.remove(e))}}const v="https://api.10minuteschool.net/auth",k="https://10minuteschool.net/auth/login",y=["profile"],S={ACCESS_TOKEN:"_tenms_access_token",REFRESH_TOKEN:"_tenms_refresh_token",EXPIRES_AT:"_tenms_expires_at",USER:"_tenms_user"};class x{constructor(e){var t,o;this.config=function(e){var t,o;const i=null===(t=e.clientId)||void 0===t?void 0:t.trim();if(!i)throw new n("clientId is required","missing_client_id");const r=(null===(o=e.redirectUri)||void 0===o?void 0:o.trim())||void 0,s=E(v,"baseUrl","invalid_base_url"),a=E(k,"authorizeUrl","invalid_authorize_url"),c=function(e){if(!Array.isArray(e)||0===e.length)return y;const t=e.map(e=>e.trim()).filter(Boolean);return t.length>0?t:y}(e.scopes);return{clientId:i,redirectUri:r,scopes:c,baseUrl:s,authorizeUrl:a}}(e),this.log=f(!0===e.debug),this.storage="localStorage"===(null!==(t=e.storage)&&void 0!==t?t:"cookie")?new _:new b,this.log.info("init",{clientId:this.config.clientId,redirectUri:this.config.redirectUri,baseUrl:this.config.baseUrl,authorizeUrl:this.config.authorizeUrl,scopes:this.config.scopes.join(" "),storage:null!==(o=e.storage)&&void 0!==o?o:"cookie",debug:!0===e.debug})}async loginWithPopup(e={}){var t,o;const a=null!==(t=e.width)&&void 0!==t?t:500,d=null!==(o=e.height)&&void 0!==o?o:600;this.log.info("loginWithPopup:start",{width:a,height:d});const h=s(),u=i();this.log.info("loginWithPopup:pkce-generated",{state:w(h),codeVerifier:w(u)});const g=c({url:"about:blank",width:a,height:d});if(!g){const e=new n("Failed to open login popup. Please allow popups for this site.","popup_blocked");throw this.log.error("loginWithPopup:popup-blocked",e),e}if(g===window){const e=new n("The browser reused the current tab instead of opening a popup window.","popup_reused_opener");throw this.log.error("loginWithPopup:popup-reused-opener",e),e}this.log.info("loginWithPopup:popup-opened"),function(e){try{e.document.title="Signing in…",e.document.body.style.cssText="font-family:system-ui,sans-serif;padding:2rem;text-align:center",e.document.body.textContent="Signing in…"}catch(e){}}(g);try{const e=await r(u),t=this.buildAuthorizeUrl(h,e);this.log.info("loginWithPopup:navigating",{authorizeUrl:t,codeChallenge:w(e)}),g.location.href=t;const n=await l(g,this.requireRedirectUri(),h);return this.log.info("loginWithPopup:success",{code:w(n.code),state:w(n.state)}),{code:n.code,state:n.state,codeVerifier:u}}catch(e){throw g.closed||g.close(),this.log.error("loginWithPopup:error",e),e}}async loginWithRedirect(){this.log.info("loginWithRedirect:start");const e=s(),t=i(),n=await r(t);this.log.info("loginWithRedirect:pkce-generated",{state:w(e),codeVerifier:w(t),codeChallenge:w(n)}),function(e,t){sessionStorage.setItem(C("state"),e),sessionStorage.setItem(C("code_verifier"),t)}(e,t),this.log.info("loginWithRedirect:session-persisted",{storageKeys:[C("state"),C("code_verifier")]});const o=this.buildAuthorizeUrl(e,n);this.log.info("loginWithRedirect:navigating",{authorizeUrl:o}),window.location.href=o}handleRedirectCallback(){const e=new URLSearchParams(window.location.search),t=e.get("code"),o=e.get("state"),i=e.get("error"),r=e.get("error_description");if(!t&&!o&&!i)return this.log.info("handleRedirectCallback:not-a-callback"),null;this.log.info("handleRedirectCallback:callback-detected",{hasCode:Boolean(t),hasState:Boolean(o),error:null!=i?i:"(none)",errorDescription:null!=r?r:"(none)"});const s=sessionStorage.getItem(C("state")),a=sessionStorage.getItem(C("code_verifier"));if(!o||!s||o!==s){U();const e=new n("State mismatch — possible CSRF attack","state_mismatch");throw this.log.warn("handleRedirectCallback:state-mismatch",{receivedState:o?w(o):"(missing)",storedStatePresent:Boolean(s)}),e}if(U(),function(){const e=window.location.origin+window.location.pathname;window.history.replaceState({},document.title,e)}(),i)throw this.log.error("handleRedirectCallback:oauth-error",{error:i,errorDescription:r}),new n(r||i,i);if(!t){const e=new n("No authorization code was returned to the redirect URI","missing_authorization_code");throw this.log.error("handleRedirectCallback:missing-code",e),e}if(!a){const e=new n("No PKCE code verifier was found for the redirect callback","missing_code_verifier");throw this.log.error("handleRedirectCallback:missing-verifier",e),e}return this.log.info("handleRedirectCallback:success",{code:w(t),state:w(o)}),{code:t,state:o,codeVerifier:a}}async exchangeCode(e,t){if(!e||e.length>2048)throw new n("code is required and must be under 2048 characters","invalid_authorization_code");if(!t||t.length<43||t.length>128)throw new n("codeVerifier must be 43–128 characters (RFC 7636)","invalid_code_verifier");const o=`${this.config.baseUrl}/v1/oauth/token`;this.log.info("exchangeCode:start",{endpoint:o,code:w(e),codeVerifier:w(t),clientId:this.config.clientId,redirectUri:this.config.redirectUri});const i=await fetch(o,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({grant_type:"authorization_code",code:e,redirect_uri:this.requireRedirectUri(),client_id:this.config.clientId,code_verifier:t})});if(!i.ok){const e=await T(i),t=new n(I(e,"Token exchange failed"),"token_exchange_failed");throw this.log.error("exchangeCode:error",{status:i.status,message:t.message}),t}const r=R(await i.json());return this.log.info("exchangeCode:success",{token_type:r.token_type,expires_in:r.expires_in,scope:r.scope,access_token:w(r.access_token),has_refresh_token:Boolean(r.refresh_token)}),r}async refreshToken(e){if(!e)throw new n("refreshToken is required","missing_refresh_token");const t=`${this.config.baseUrl}/v1/oauth/token`;this.log.info("refreshToken:start",{endpoint:t,refreshToken:w(e),clientId:this.config.clientId});const o=await fetch(t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({grant_type:"refresh_token",refresh_token:e,client_id:this.config.clientId})});if(!o.ok){const e=await T(o),t=new n(I(e,"Token refresh failed"),"token_refresh_failed");throw this.log.error("refreshToken:error",{status:o.status,message:t.message}),t}const i=R(await o.json());return this.log.info("refreshToken:success",{token_type:i.token_type,expires_in:i.expires_in,access_token:w(i.access_token)}),i}async getUserInfo(e){var t,o;if(!e)throw new n("accessToken is required to fetch user info","missing_access_token");const i=`${this.config.baseUrl}/v1/oauth/userinfo`;this.log.info("getUserInfo:start",{endpoint:i,accessToken:w(e)});const r=await fetch(i,{headers:{Authorization:`Bearer ${e}`}});if(!r.ok){const e=await T(r),t=new n(I(e,"Failed to fetch user info"),"userinfo_failed");throw this.log.error("getUserInfo:error",{status:r.status,message:t.message}),t}const s=function(e){if(!e||"object"!=typeof e||"string"!=typeof e.sub||!e.sub)throw new n("Server returned an invalid userinfo response (missing sub)","invalid_userinfo_response");return e}(await r.json());return this.log.info("getUserInfo:success",{sub:s.sub,name:null!==(t=s.name)&&void 0!==t?t:"(not returned)",email:null!==(o=s.email)&&void 0!==o?o:"(not returned)"}),s}async revokeToken(e){if(!e)throw new n("token is required to revoke an OAuth token","missing_token");const t=`${this.config.baseUrl}/v1/oauth/revoke`;this.log.info("revokeToken:start",{endpoint:t,token:w(e),clientId:this.config.clientId});const o=await fetch(t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({token:e,client_id:this.config.clientId})});if(!o.ok){const e=await T(o),t=new n(I(e,"Failed to revoke token"),"revoke_failed");throw this.log.error("revokeToken:error",{status:o.status,message:t.message}),t}this.log.info("revokeToken:success")}async handleLoginSuccess(e){this.log.info("handleLoginSuccess:start",{code:w(e.code)});const t=await this.exchangeCode(e.code,e.codeVerifier),n=await this.getUserInfo(t.access_token),o=Math.floor(Date.now()/1e3)+t.expires_in;return this.storage.set(S.ACCESS_TOKEN,t.access_token,o),this.storage.set(S.EXPIRES_AT,String(o),o),t.refresh_token&&this.storage.set(S.REFRESH_TOKEN,t.refresh_token),this.storage.set(S.USER,JSON.stringify(n)),this.log.info("handleLoginSuccess:session-saved",{sub:n.sub,expiresAt:o,hasRefreshToken:Boolean(t.refresh_token)}),{user:n,accessToken:t.access_token}}async getAccessToken(){var e;const t=this.storage.get(S.ACCESS_TOKEN),n=Number(null!==(e=this.storage.get(S.EXPIRES_AT))&&void 0!==e?e:"0");if(!t)return null;if(!(n>0&&Math.floor(Date.now()/1e3)>=n))return t;this.log.info("getAccessToken:expired, attempting refresh");const o=this.storage.get(S.REFRESH_TOKEN);if(!o)return this.log.info("getAccessToken:no-refresh-token, clearing session"),this.clearSession(),null;try{const e=await this.refreshToken(o),t=Math.floor(Date.now()/1e3)+e.expires_in;return this.storage.set(S.ACCESS_TOKEN,e.access_token,t),this.storage.set(S.EXPIRES_AT,String(t),t),e.refresh_token&&this.storage.set(S.REFRESH_TOKEN,e.refresh_token),this.log.info("getAccessToken:refreshed",{newExpiresAt:t}),e.access_token}catch(e){return this.log.error("getAccessToken:refresh-failed",e),this.clearSession(),null}}getUser(){const e=this.storage.get(S.USER);if(!e)return null;try{return JSON.parse(e)}catch(e){return null}}isLoggedIn(){var e;if(!this.storage.get(S.ACCESS_TOKEN))return!1;const t=Number(null!==(e=this.storage.get(S.EXPIRES_AT))&&void 0!==e?e:"0");return 0===t||Math.floor(Date.now()/1e3)<t}async logout(){const e=this.storage.get(S.ACCESS_TOKEN);if(e)try{await this.revokeToken(e)}catch(e){this.log.error("logout:revoke-failed",e)}this.clearSession(),this.log.info("logout:done")}getBaseUrl(){return this.config.baseUrl}getClientId(){return this.config.clientId}clearSession(){this.storage.clear(Object.values(S))}requireRedirectUri(){if(this.config.redirectUri)return this.config.redirectUri;if("undefined"!=typeof window)return window.location.origin;throw new n("redirectUri is required — pass it in the TenMSAuth constructor or call from a browser context","missing_redirect_uri")}buildAuthorizeUrl(e,t){const n=new URL(this.config.authorizeUrl);return n.searchParams.set("client_id",this.config.clientId),n.searchParams.set("redirect_uri",this.requireRedirectUri()),n.searchParams.set("response_type","code"),n.searchParams.set("scope",this.config.scopes.join(" ")),n.searchParams.set("state",e),n.searchParams.set("code_challenge",t),n.searchParams.set("code_challenge_method","S256"),n.toString()}}function E(e,t,o){const i=e.trim();if(!i)throw new n(`${t} must not be empty`,o);const r=i.replace(/\/+$/,"");try{new URL(r)}catch(e){throw new n(`${t} is not a valid URL: "${r}"`,o)}return r}function C(e){return`tenms_auth_${e}`}function U(){sessionStorage.removeItem(C("state")),sessionStorage.removeItem(C("code_verifier"))}async function T(e){try{const t=await e.text();return t?JSON.parse(t):{}}catch(e){return{}}}function I(e,t){var n,o,i;return null!==(i=null!==(o=null!==(n=e.error_description)&&void 0!==n?n:e.message)&&void 0!==o?o:e.error)&&void 0!==i?i:t}function R(e){if(!e||"object"!=typeof e||"string"!=typeof e.access_token||!e.access_token)throw new n("Server returned an invalid token response (missing access_token)","invalid_token_response");return e}!function(e,t){void 0===t&&(t={});var n=t.insertAt;if("undefined"!=typeof document){var o=document.head||document.getElementsByTagName("head")[0],i=document.createElement("style");i.type="text/css","top"===n&&o.firstChild?o.insertBefore(i,o.firstChild):o.appendChild(i),i.styleSheet?i.styleSheet.cssText=e:i.appendChild(document.createTextNode(e))}}(".tenms-login-btn{-webkit-font-smoothing:antialiased;align-items:center;border:1px solid transparent;border-radius:6px;cursor:pointer;display:inline-flex;font-family:-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica Neue,Arial,sans-serif;font-size:14px;font-weight:500;gap:6px;height:36px;justify-content:center;line-height:1;padding:0 12px;text-decoration:none;transition:background .15s ease,border-color .15s ease,color .15s ease,opacity .15s ease;user-select:none;-webkit-user-select:none;white-space:nowrap;width:fit-content}.tenms-login-btn:focus-visible{outline:2px solid #0070f3;outline-offset:2px}.tenms-login-btn:disabled{cursor:not-allowed}.tenms-login-btn--dark.tenms-login-btn--fill{background:#000;border-color:#000;color:#fff}.tenms-login-btn--dark.tenms-login-btn--fill:hover:not(:disabled){background:#333;border-color:#333}.tenms-login-btn--dark.tenms-login-btn--outline{background:transparent;border-color:#000;color:#000}.tenms-login-btn--dark.tenms-login-btn--outline:hover:not(:disabled){background:#f5f5f5}.tenms-login-btn--light.tenms-login-btn--fill{background:#fff;border-color:#e5e7eb;color:#111}.tenms-login-btn--light.tenms-login-btn--fill:hover:not(:disabled){background:#f5f5f5}.tenms-login-btn--light.tenms-login-btn--outline{background:transparent;border-color:#e5e7eb;color:#111}.tenms-login-btn--light.tenms-login-btn--outline:hover:not(:disabled){background:#f5f5f5;border-color:#d1d5db}.tenms-login-btn--small{font-size:13px;gap:5px;height:32px;padding:0 10px}.tenms-login-btn--medium{font-size:14px;height:36px;padding:0 12px}.tenms-login-btn--large{font-size:14px;height:40px;padding:0 14px}.tenms-login-btn__logo{align-items:center;display:inline-flex;flex-shrink:0}.tenms-login-btn__logo svg{display:block;height:18px;width:18px}.tenms-login-btn--loading{opacity:.6;pointer-events:none}.tenms-login-btn__spinner{animation:tenms-spin .6s linear infinite;border:1.5px solid;border-radius:50%;border-top:1.5px solid transparent;height:14px;width:14px}@keyframes tenms-spin{to{transform:rotate(1turn)}}");function A(e){return"light"===e?'<svg width="20" height="20" viewBox="0 0 32 32" fill="none" xmlns="http://www.w3.org/2000/svg" aria-hidden="true" focusable="false">\n <path d="M21.9012 17.9947L28.8098 11.085C28.0544 7.39598 25.1207 4.50016 21.4039 4.03514C21.3338 4.02624 21.2626 4.01845 21.1925 4.01178V7.43714C22.8023 7.7097 24.1373 8.751 24.916 10.1839L19.5049 15.5939L21.9012 17.9947Z" fill="#EB2026"/>\n <path d="M9.47025 27.9927H6.0727V7.40489H3V4.00734H9.47025V27.9927Z" fill="#111827"/>\n <path d="M25.5835 16.7187L25.569 18.9771V18.9882C25.569 22.0776 23.2172 24.5907 20.3269 24.5907C17.4367 24.5907 15.0871 22.0798 15.0849 18.9938L15.126 12.9807V12.9696C15.126 10.224 16.9906 7.88999 19.4992 7.44388V4.01518L19.2767 4.04076C14.9703 4.60591 11.7263 8.44178 11.7229 12.9641L11.684 18.9771V18.9882C11.684 23.951 15.5599 27.9883 20.3236 27.9883C25.0873 27.9883 28.9599 23.9544 28.9621 18.9938L28.9999 13.2989L25.5835 16.7187Z" fill="#111827"/>\n</svg>':'<svg width="20" height="20" viewBox="0 0 32 32" fill="none" xmlns="http://www.w3.org/2000/svg" aria-hidden="true" focusable="false">\n <path d="M21.9012 17.9947L28.8098 11.085C28.0544 7.39598 25.1207 4.50016 21.4039 4.03514C21.3338 4.02624 21.2626 4.01845 21.1925 4.01178V7.43714C22.8023 7.7097 24.1373 8.751 24.916 10.1839L19.5049 15.5939L21.9012 17.9947Z" fill="#EB2026"/>\n <path d="M9.47025 27.9927H6.0727V7.40489H3V4.00734H9.47025V27.9927Z" fill="#F9FAFB"/>\n <path d="M25.5835 16.7187L25.569 18.9771V18.9882C25.569 22.0776 23.2172 24.5907 20.3269 24.5907C17.4367 24.5907 15.0871 22.0798 15.0849 18.9938L15.126 12.9807V12.9696C15.126 10.224 16.9906 7.88999 19.4992 7.44388V4.01518L19.2767 4.04076C14.9703 4.60591 11.7263 8.44178 11.7229 12.9641L11.684 18.9771V18.9882C11.684 23.951 15.5599 27.9883 20.3236 27.9883C25.0873 27.9883 28.9599 23.9544 28.9621 18.9938L28.9999 13.2989L25.5835 16.7187Z" fill="#F9FAFB"/>\n</svg>'}function $(e="dark"){return`<span class="tenms-login-btn__logo">${A(e)}</span>`}var L;const P="Login with 10MinuteSchool",z=null!==(L=globalThis.HTMLElement)&&void 0!==L?L:class{};class N extends z{constructor(){super(...arguments),this.auth=null,this.loading=!1}static get observedAttributes(){return["client-id","redirect-uri","scope","theme","variant","size","text"]}connectedCallback(){this.render()}attributeChangedCallback(){this.loading||this.render()}render(){var e;const t=j(this.getAttribute("theme")),n=B(this.getAttribute("variant")),o=q(this.getAttribute("size")),i=(null===(e=this.getAttribute("text"))||void 0===e?void 0:e.trim())||P;var r;this.innerHTML=`\n <button class="${V((r={loading:this.loading,text:i,theme:t,variant:n,size:o}).theme,r.variant,r.size,r.loading)}" type="button" ${r.loading?'disabled aria-busy="true"':""}>\n ${r.loading?'<span class="tenms-login-btn__spinner" aria-hidden="true"></span>':$(r.theme)}\n <span class="tenms-login-btn__label">${F(r.text)}</span>\n </button>\n `;const s=this.querySelector("button");s&&s.addEventListener("click",()=>{this.handleClick()})}async handleClick(){if(this.loading)return;const e=this.getConfig();if(e.clientId&&e.redirectUri){this.auth||(this.auth=new x(e)),this.loading=!0,this.render();try{const e=await this.auth.loginWithPopup();this.dispatchEvent(new CustomEvent("tenms-success",{detail:e,bubbles:!0,composed:!0}))}catch(e){this.dispatchError(W(e))}finally{this.loading=!1,this.render()}}else this.dispatchError(new n("client-id and redirect-uri attributes are required","invalid_login_button_config"))}getConfig(){const e=this.getAttribute("scope")||"profile";return{clientId:this.getAttribute("client-id")||"",redirectUri:this.getAttribute("redirect-uri")||"",scopes:e.split(" ").map(e=>e.trim()).filter(Boolean)}}dispatchError(e){this.dispatchEvent(new CustomEvent("tenms-error",{detail:e,bubbles:!0,composed:!0}))}}function O(){"undefined"==typeof window||"undefined"==typeof customElements||customElements.get("tenms-login-button")||customElements.define("tenms-login-button",N)}function M(e,t){e.className=V(t.theme,t.variant,t.size,t.loading),e.type="button",e.disabled=t.loading,e.setAttribute("aria-busy",String(t.loading)),e.innerHTML=t.loading?`<span class="tenms-login-btn__spinner" aria-hidden="true"></span><span class="tenms-login-btn__label">${F(t.text)}</span>`:`${$(t.theme)}<span class="tenms-login-btn__label">${F(t.text)}</span>`}function V(e,t,n,o){return["tenms-login-btn",`tenms-login-btn--${e}`,`tenms-login-btn--${t}`,`tenms-login-btn--${n}`,o?"tenms-login-btn--loading":""].filter(Boolean).join(" ")}function j(e){return"light"===e?e:"dark"}function B(e){return"outline"===e?e:"fill"}function q(e){return"small"===e||"medium"===e?e:"large"}function F(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;")}function W(e){return e instanceof Error?e:new Error(String(e))}const H="Login with 10MinuteSchool",K="dark",D="fill",J="large";function X(e){return"light"===e?e:K}function Z(e){return"small"===e||"medium"===e?e:J}O(),exports.LoginButton=function(e){const{clientId:n,redirectUri:o,scopes:i,theme:r=K,variant:s=D,size:a=J,text:c=H,onSuccess:l,onError:d,className:h=""}=e,[u,g]=t.useState(!1),f=t.useRef(l),p=t.useRef(d);t.useEffect(()=>{f.current=l},[l]),t.useEffect(()=>{p.current=d},[d]);const m=Array.isArray(i)?i.join("\0"):"",w=t.useMemo(()=>new x({clientId:n,redirectUri:o,scopes:i}),[n,o,m]),b=t.useCallback(async()=>{var e,t;g(!0);try{const t=await w.loginWithPopup();null===(e=f.current)||void 0===e||e.call(f,t)}catch(e){null===(t=p.current)||void 0===t||t.call(p,function(e){return e instanceof Error?e:new Error(String(e))}(e))}finally{g(!1)}},[w]),_=["tenms-login-btn",`tenms-login-btn--${X(r)}`,`tenms-login-btn--${v=s,"outline"===v?v:D}`,`tenms-login-btn--${Z(a)}`,u?"tenms-login-btn--loading":"",h].filter(Boolean).join(" ");var v;return t.createElement("button",{className:_,type:"button",onClick:()=>{b()},disabled:u,"aria-busy":u},u?t.createElement("span",{className:"tenms-login-btn__spinner","aria-hidden":"true"}):t.createElement("span",{className:"tenms-login-btn__logo",dangerouslySetInnerHTML:{__html:A(X(r))}}),t.createElement("span",{className:"tenms-login-btn__label"},c))},exports.TenMSAuth=x,exports.TenMSAuthError=n,exports.TenMSLoginButtonElement=N,exports.VERSION="0.3.0",exports.createLogger=f,exports.generateCodeChallenge=r,exports.generateCodeVerifier=i,exports.generateState=s,exports.openPopup=c,exports.registerLoginButton=O,exports.renderLoginButton=function(e,t){var o;const i="string"==typeof e?document.querySelector(e):e;if(!i)throw new n(`Container element not found: ${e}`,"container_not_found");const r=new x({clientId:t.clientId,redirectUri:t.redirectUri,scopes:t.scopes}),s=j(t.theme),a=B(t.variant),c=q(t.size),l=(null===(o=t.text)||void 0===o?void 0:o.trim())||P,d=document.createElement("button");M(d,{loading:!1,size:c,text:l,theme:s,variant:a}),d.addEventListener("click",async()=>{var e,n;if(!d.classList.contains("tenms-login-btn--loading")){M(d,{loading:!0,size:c,text:l,theme:s,variant:a});try{const n=await r.loginWithPopup();null===(e=t.onSuccess)||void 0===e||e.call(t,n)}catch(e){null===(n=t.onError)||void 0===n||n.call(t,W(e))}finally{M(d,{loading:!1,size:c,text:l,theme:s,variant:a})}}}),i.replaceChildren(d)},exports.truncate=w,exports.waitForPopupRedirect=l;
1
+ "use strict";function e(e){var t=Object.create(null);return e&&Object.keys(e).forEach(function(n){if("default"!==n){var o=Object.getOwnPropertyDescriptor(e,n);Object.defineProperty(t,n,o.get?o:{enumerable:!0,get:function(){return e[n]}})}}),t.default=e,Object.freeze(t)}var t=e(require("react"));class n extends Error{constructor(e,t){super(e),this.name="TenMSAuthError",this.code=t,Object.setPrototypeOf(this,new.target.prototype)}}const o="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~";function i(e=64){a(e,43,128,"code_verifier length");const t=[];for(;t.length<e;){const n=new Uint8Array(e+16);crypto.getRandomValues(n);for(const i of n){if(t.length>=e)break;i<198&&t.push(o[i%66])}}return t.join("")}async function r(e){if(!e)throw new Error("codeVerifier is required to generate a code challenge");const t=(new TextEncoder).encode(e);return function(e){const t=new Uint8Array(e);let n="";for(const e of t)n+=String.fromCharCode(e);return btoa(n).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}(await crypto.subtle.digest("SHA-256",t))}function s(e=32){a(e,1,1024,"state byte length");const t=new Uint8Array(e);return crypto.getRandomValues(t),Array.from(t,e=>e.toString(16).padStart(2,"0")).join("")}function a(e,t,n,o){if(!Number.isInteger(e)||e<t||e>n)throw new RangeError(`${o} must be an integer between ${t} and ${n}`)}function c(e){d(e.width,"popup width"),d(e.height,"popup height");const t="number"==typeof window.screenX?window.screenX:window.screenLeft,n="number"==typeof window.screenY?window.screenY:window.screenTop,o=Math.round(t+Math.max(0,(window.innerWidth-e.width)/2)),i=Math.round(n+Math.max(0,(window.innerHeight-e.height)/2)),r=[`width=${e.width}`,`height=${e.height}`,`left=${o}`,`top=${i}`,"toolbar=no","menubar=no","scrollbars=yes","resizable=yes","status=no"].join(",");return window.open(e.url,"tenms_auth_popup",r)}function l(e,t,o,i=3e5){if(!t)throw new Error("redirectUri is required to monitor popup redirects");if(!o)throw new Error("expectedState is required to validate the popup callback");let r;d(i,"popup timeout");try{r=new URL(t)}catch(e){throw new n(`redirectUri is not a valid URL: "${t}"`,"invalid_redirect_uri")}return new Promise((t,s)=>{const a=Date.now(),c=window.setInterval(()=>{try{if(!e||e.closed)return window.clearInterval(c),void s(new n("Login popup was closed","popup_closed"));if(Date.now()-a>i)return window.clearInterval(c),e.close(),void s(new n("Login timed out while waiting for the redirect URI","popup_timeout"));const l=e.location.href;if(!l)return;let d;try{d=new URL(l)}catch(e){return}if(d.origin!==r.origin||d.pathname!==r.pathname)return;window.clearInterval(c),e.close();const h=d.searchParams.get("code"),u=d.searchParams.get("state"),g=d.searchParams.get("error"),f=d.searchParams.get("error_description");if(g)return void s(new n(f||g,"oauth_error"));if(!h)return void s(new n("No authorization code was returned to the redirect URI","missing_authorization_code"));if(u!==o)return void s(new n("State mismatch — possible CSRF attack","state_mismatch"));t({code:h,state:u})}catch(e){e instanceof DOMException||(window.clearInterval(c),s(e instanceof Error?e:new Error(String(e))))}},500)})}function d(e,t){if(!Number.isInteger(e)||e<=0)throw new RangeError(`${t} must be a positive integer`)}const h="[TenMSAuth]",u="color:#22c55e;font-weight:700",g="color:inherit;font-weight:normal";function f(e){return e?m:p}const p={info:()=>{},warn:()=>{},error:()=>{}},m={info(e,t){t&&Object.keys(t).length>0?(console.groupCollapsed(`%c${h}%c ${e}`,u,g),console.table(t),console.groupEnd()):console.log(`%c${h}%c ${e}`,u,g)},warn(e,t){console.warn(`%c${h}%c ⚠ ${e}`,u,g,null!=t?t:"")},error(e,t){console.error(`%c${h}%c ✕ ${e}`,u,g,null!=t?t:"")}};function w(e){return e?e.length>8?`${e.slice(0,8)}…`:e:"(empty)"}class b{get(e){const t=document.cookie.match(new RegExp("(?:^|; )"+e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")+"=([^;]*)"));return t?decodeURIComponent(t[1]):null}set(e,t,n){let o=`${e}=${encodeURIComponent(t)}; path=/; SameSite=Lax`;n&&(o+=`; expires=${new Date(1e3*n).toUTCString()}`),document.cookie=o}remove(e){document.cookie=`${e}=; path=/; expires=Thu, 01 Jan 1970 00:00:00 GMT; SameSite=Lax`}clear(e){e.forEach(e=>this.remove(e))}}class _{get(e){return localStorage.getItem(e)}set(e,t){localStorage.setItem(e,t)}remove(e){localStorage.removeItem(e)}clear(e){e.forEach(e=>this.remove(e))}}const v="https://api.10minuteschool.com/auth",k="https://10minuteschool.com/auth/login",y=["profile"],S={ACCESS_TOKEN:"_tenms_access_token",REFRESH_TOKEN:"_tenms_refresh_token",EXPIRES_AT:"_tenms_expires_at",USER:"_tenms_user"};class x{constructor(e){var t,o;this.config=function(e){var t,o;const i=null===(t=e.clientId)||void 0===t?void 0:t.trim();if(!i)throw new n("clientId is required","missing_client_id");const r=(null===(o=e.redirectUri)||void 0===o?void 0:o.trim())||void 0,s=E(v,"baseUrl","invalid_base_url"),a=E(k,"authorizeUrl","invalid_authorize_url"),c=function(e){if(!Array.isArray(e)||0===e.length)return y;const t=e.map(e=>e.trim()).filter(Boolean);return t.length>0?t:y}(e.scopes);return{clientId:i,redirectUri:r,scopes:c,baseUrl:s,authorizeUrl:a}}(e),this.log=f(!0===e.debug),this.storage="localStorage"===(null!==(t=e.storage)&&void 0!==t?t:"cookie")?new _:new b,this.log.info("init",{clientId:this.config.clientId,redirectUri:this.config.redirectUri,baseUrl:this.config.baseUrl,authorizeUrl:this.config.authorizeUrl,scopes:this.config.scopes.join(" "),storage:null!==(o=e.storage)&&void 0!==o?o:"cookie",debug:!0===e.debug})}async loginWithPopup(e={}){var t,o;const a=null!==(t=e.width)&&void 0!==t?t:500,d=null!==(o=e.height)&&void 0!==o?o:600;this.log.info("loginWithPopup:start",{width:a,height:d});const h=s(),u=i();this.log.info("loginWithPopup:pkce-generated",{state:w(h),codeVerifier:w(u)});const g=c({url:"about:blank",width:a,height:d});if(!g){const e=new n("Failed to open login popup. Please allow popups for this site.","popup_blocked");throw this.log.error("loginWithPopup:popup-blocked",e),e}if(g===window){const e=new n("The browser reused the current tab instead of opening a popup window.","popup_reused_opener");throw this.log.error("loginWithPopup:popup-reused-opener",e),e}this.log.info("loginWithPopup:popup-opened"),function(e){try{e.document.title="Signing in…",e.document.body.style.cssText="font-family:system-ui,sans-serif;padding:2rem;text-align:center",e.document.body.textContent="Signing in…"}catch(e){}}(g);try{const e=await r(u),t=this.buildAuthorizeUrl(h,e);this.log.info("loginWithPopup:navigating",{authorizeUrl:t,codeChallenge:w(e)}),g.location.href=t;const n=await l(g,this.requireRedirectUri(),h);return this.log.info("loginWithPopup:success",{code:w(n.code),state:w(n.state)}),{code:n.code,state:n.state,codeVerifier:u}}catch(e){throw g.closed||g.close(),this.log.error("loginWithPopup:error",e),e}}async loginWithRedirect(){this.log.info("loginWithRedirect:start");const e=s(),t=i(),n=await r(t);this.log.info("loginWithRedirect:pkce-generated",{state:w(e),codeVerifier:w(t),codeChallenge:w(n)}),function(e,t){sessionStorage.setItem(C("state"),e),sessionStorage.setItem(C("code_verifier"),t)}(e,t),this.log.info("loginWithRedirect:session-persisted",{storageKeys:[C("state"),C("code_verifier")]});const o=this.buildAuthorizeUrl(e,n);this.log.info("loginWithRedirect:navigating",{authorizeUrl:o}),window.location.href=o}handleRedirectCallback(){const e=new URLSearchParams(window.location.search),t=e.get("code"),o=e.get("state"),i=e.get("error"),r=e.get("error_description");if(!t&&!o&&!i)return this.log.info("handleRedirectCallback:not-a-callback"),null;this.log.info("handleRedirectCallback:callback-detected",{hasCode:Boolean(t),hasState:Boolean(o),error:null!=i?i:"(none)",errorDescription:null!=r?r:"(none)"});const s=sessionStorage.getItem(C("state")),a=sessionStorage.getItem(C("code_verifier"));if(!o||!s||o!==s){U();const e=new n("State mismatch — possible CSRF attack","state_mismatch");throw this.log.warn("handleRedirectCallback:state-mismatch",{receivedState:o?w(o):"(missing)",storedStatePresent:Boolean(s)}),e}if(U(),function(){const e=window.location.origin+window.location.pathname;window.history.replaceState({},document.title,e)}(),i)throw this.log.error("handleRedirectCallback:oauth-error",{error:i,errorDescription:r}),new n(r||i,i);if(!t){const e=new n("No authorization code was returned to the redirect URI","missing_authorization_code");throw this.log.error("handleRedirectCallback:missing-code",e),e}if(!a){const e=new n("No PKCE code verifier was found for the redirect callback","missing_code_verifier");throw this.log.error("handleRedirectCallback:missing-verifier",e),e}return this.log.info("handleRedirectCallback:success",{code:w(t),state:w(o)}),{code:t,state:o,codeVerifier:a}}async exchangeCode(e,t){if(!e||e.length>2048)throw new n("code is required and must be under 2048 characters","invalid_authorization_code");if(!t||t.length<43||t.length>128)throw new n("codeVerifier must be 43–128 characters (RFC 7636)","invalid_code_verifier");const o=`${this.config.baseUrl}/v1/oauth/token`;this.log.info("exchangeCode:start",{endpoint:o,code:w(e),codeVerifier:w(t),clientId:this.config.clientId,redirectUri:this.config.redirectUri});const i=await fetch(o,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({grant_type:"authorization_code",code:e,redirect_uri:this.requireRedirectUri(),client_id:this.config.clientId,code_verifier:t})});if(!i.ok){const e=await T(i),t=new n(I(e,"Token exchange failed"),"token_exchange_failed");throw this.log.error("exchangeCode:error",{status:i.status,message:t.message}),t}const r=R(await i.json());return this.log.info("exchangeCode:success",{token_type:r.token_type,expires_in:r.expires_in,scope:r.scope,access_token:w(r.access_token),has_refresh_token:Boolean(r.refresh_token)}),r}async refreshToken(e){if(!e)throw new n("refreshToken is required","missing_refresh_token");const t=`${this.config.baseUrl}/v1/oauth/token`;this.log.info("refreshToken:start",{endpoint:t,refreshToken:w(e),clientId:this.config.clientId});const o=await fetch(t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({grant_type:"refresh_token",refresh_token:e,client_id:this.config.clientId})});if(!o.ok){const e=await T(o),t=new n(I(e,"Token refresh failed"),"token_refresh_failed");throw this.log.error("refreshToken:error",{status:o.status,message:t.message}),t}const i=R(await o.json());return this.log.info("refreshToken:success",{token_type:i.token_type,expires_in:i.expires_in,access_token:w(i.access_token)}),i}async getUserInfo(e){var t,o;if(!e)throw new n("accessToken is required to fetch user info","missing_access_token");const i=`${this.config.baseUrl}/v1/oauth/userinfo`;this.log.info("getUserInfo:start",{endpoint:i,accessToken:w(e)});const r=await fetch(i,{headers:{Authorization:`Bearer ${e}`}});if(!r.ok){const e=await T(r),t=new n(I(e,"Failed to fetch user info"),"userinfo_failed");throw this.log.error("getUserInfo:error",{status:r.status,message:t.message}),t}const s=function(e){if(!e||"object"!=typeof e||"string"!=typeof e.sub||!e.sub)throw new n("Server returned an invalid userinfo response (missing sub)","invalid_userinfo_response");return e}(await r.json());return this.log.info("getUserInfo:success",{sub:s.sub,name:null!==(t=s.name)&&void 0!==t?t:"(not returned)",email:null!==(o=s.email)&&void 0!==o?o:"(not returned)"}),s}async revokeToken(e){if(!e)throw new n("token is required to revoke an OAuth token","missing_token");const t=`${this.config.baseUrl}/v1/oauth/revoke`;this.log.info("revokeToken:start",{endpoint:t,token:w(e),clientId:this.config.clientId});const o=await fetch(t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({token:e,client_id:this.config.clientId})});if(!o.ok){const e=await T(o),t=new n(I(e,"Failed to revoke token"),"revoke_failed");throw this.log.error("revokeToken:error",{status:o.status,message:t.message}),t}this.log.info("revokeToken:success")}async handleLoginSuccess(e){this.log.info("handleLoginSuccess:start",{code:w(e.code)});const t=await this.exchangeCode(e.code,e.codeVerifier),n=await this.getUserInfo(t.access_token),o=Math.floor(Date.now()/1e3)+t.expires_in;return this.storage.set(S.ACCESS_TOKEN,t.access_token,o),this.storage.set(S.EXPIRES_AT,String(o),o),t.refresh_token&&this.storage.set(S.REFRESH_TOKEN,t.refresh_token),this.storage.set(S.USER,JSON.stringify(n)),this.log.info("handleLoginSuccess:session-saved",{sub:n.sub,expiresAt:o,hasRefreshToken:Boolean(t.refresh_token)}),{user:n,accessToken:t.access_token}}async getAccessToken(){var e;const t=this.storage.get(S.ACCESS_TOKEN),n=Number(null!==(e=this.storage.get(S.EXPIRES_AT))&&void 0!==e?e:"0");if(!t)return null;if(!(n>0&&Math.floor(Date.now()/1e3)>=n))return t;this.log.info("getAccessToken:expired, attempting refresh");const o=this.storage.get(S.REFRESH_TOKEN);if(!o)return this.log.info("getAccessToken:no-refresh-token, clearing session"),this.clearSession(),null;try{const e=await this.refreshToken(o),t=Math.floor(Date.now()/1e3)+e.expires_in;return this.storage.set(S.ACCESS_TOKEN,e.access_token,t),this.storage.set(S.EXPIRES_AT,String(t),t),e.refresh_token&&this.storage.set(S.REFRESH_TOKEN,e.refresh_token),this.log.info("getAccessToken:refreshed",{newExpiresAt:t}),e.access_token}catch(e){return this.log.error("getAccessToken:refresh-failed",e),this.clearSession(),null}}getUser(){const e=this.storage.get(S.USER);if(!e)return null;try{return JSON.parse(e)}catch(e){return null}}isLoggedIn(){var e;if(!this.storage.get(S.ACCESS_TOKEN))return!1;const t=Number(null!==(e=this.storage.get(S.EXPIRES_AT))&&void 0!==e?e:"0");return 0===t||Math.floor(Date.now()/1e3)<t}async logout(){const e=this.storage.get(S.ACCESS_TOKEN);if(e)try{await this.revokeToken(e)}catch(e){this.log.error("logout:revoke-failed",e)}this.clearSession(),this.log.info("logout:done")}getBaseUrl(){return this.config.baseUrl}getClientId(){return this.config.clientId}clearSession(){this.storage.clear(Object.values(S))}requireRedirectUri(){if(this.config.redirectUri)return this.config.redirectUri;if("undefined"!=typeof window)return window.location.origin;throw new n("redirectUri is required — pass it in the TenMSAuth constructor or call from a browser context","missing_redirect_uri")}buildAuthorizeUrl(e,t){const n=new URL(this.config.authorizeUrl);return n.searchParams.set("client_id",this.config.clientId),n.searchParams.set("redirect_uri",this.requireRedirectUri()),n.searchParams.set("response_type","code"),n.searchParams.set("scope",this.config.scopes.join(" ")),n.searchParams.set("state",e),n.searchParams.set("code_challenge",t),n.searchParams.set("code_challenge_method","S256"),n.toString()}}function E(e,t,o){const i=e.trim();if(!i)throw new n(`${t} must not be empty`,o);const r=i.replace(/\/+$/,"");try{new URL(r)}catch(e){throw new n(`${t} is not a valid URL: "${r}"`,o)}return r}function C(e){return`tenms_auth_${e}`}function U(){sessionStorage.removeItem(C("state")),sessionStorage.removeItem(C("code_verifier"))}async function T(e){try{const t=await e.text();return t?JSON.parse(t):{}}catch(e){return{}}}function I(e,t){var n,o,i;return null!==(i=null!==(o=null!==(n=e.error_description)&&void 0!==n?n:e.message)&&void 0!==o?o:e.error)&&void 0!==i?i:t}function R(e){if(!e||"object"!=typeof e||"string"!=typeof e.access_token||!e.access_token)throw new n("Server returned an invalid token response (missing access_token)","invalid_token_response");return e}!function(e,t){void 0===t&&(t={});var n=t.insertAt;if("undefined"!=typeof document){var o=document.head||document.getElementsByTagName("head")[0],i=document.createElement("style");i.type="text/css","top"===n&&o.firstChild?o.insertBefore(i,o.firstChild):o.appendChild(i),i.styleSheet?i.styleSheet.cssText=e:i.appendChild(document.createTextNode(e))}}(".tenms-login-btn{-webkit-font-smoothing:antialiased;align-items:center;border:1px solid transparent;border-radius:6px;cursor:pointer;display:inline-flex;font-family:-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica Neue,Arial,sans-serif;font-size:14px;font-weight:500;gap:6px;height:36px;justify-content:center;line-height:1;padding:0 12px;text-decoration:none;transition:background .15s ease,border-color .15s ease,color .15s ease,opacity .15s ease;user-select:none;-webkit-user-select:none;white-space:nowrap;width:fit-content}.tenms-login-btn:focus-visible{outline:2px solid #0070f3;outline-offset:2px}.tenms-login-btn:disabled{cursor:not-allowed}.tenms-login-btn--dark.tenms-login-btn--fill{background:#000;border-color:#000;color:#fff}.tenms-login-btn--dark.tenms-login-btn--fill:hover:not(:disabled){background:#333;border-color:#333}.tenms-login-btn--dark.tenms-login-btn--outline{background:transparent;border-color:#000;color:#000}.tenms-login-btn--dark.tenms-login-btn--outline:hover:not(:disabled){background:#f5f5f5}.tenms-login-btn--light.tenms-login-btn--fill{background:#fff;border-color:#e5e7eb;color:#111}.tenms-login-btn--light.tenms-login-btn--fill:hover:not(:disabled){background:#f5f5f5}.tenms-login-btn--light.tenms-login-btn--outline{background:transparent;border-color:#e5e7eb;color:#111}.tenms-login-btn--light.tenms-login-btn--outline:hover:not(:disabled){background:#f5f5f5;border-color:#d1d5db}.tenms-login-btn--small{font-size:13px;gap:5px;height:32px;padding:0 10px}.tenms-login-btn--medium{font-size:14px;height:36px;padding:0 12px}.tenms-login-btn--large{font-size:14px;height:40px;padding:0 14px}.tenms-login-btn__logo{align-items:center;display:inline-flex;flex-shrink:0}.tenms-login-btn__logo svg{display:block;height:18px;width:18px}.tenms-login-btn--loading{opacity:.6;pointer-events:none}.tenms-login-btn__spinner{animation:tenms-spin .6s linear infinite;border:1.5px solid;border-radius:50%;border-top:1.5px solid transparent;height:14px;width:14px}@keyframes tenms-spin{to{transform:rotate(1turn)}}");function A(e){return"light"===e?'<svg width="20" height="20" viewBox="0 0 32 32" fill="none" xmlns="http://www.w3.org/2000/svg" aria-hidden="true" focusable="false">\n <path d="M21.9012 17.9947L28.8098 11.085C28.0544 7.39598 25.1207 4.50016 21.4039 4.03514C21.3338 4.02624 21.2626 4.01845 21.1925 4.01178V7.43714C22.8023 7.7097 24.1373 8.751 24.916 10.1839L19.5049 15.5939L21.9012 17.9947Z" fill="#EB2026"/>\n <path d="M9.47025 27.9927H6.0727V7.40489H3V4.00734H9.47025V27.9927Z" fill="#111827"/>\n <path d="M25.5835 16.7187L25.569 18.9771V18.9882C25.569 22.0776 23.2172 24.5907 20.3269 24.5907C17.4367 24.5907 15.0871 22.0798 15.0849 18.9938L15.126 12.9807V12.9696C15.126 10.224 16.9906 7.88999 19.4992 7.44388V4.01518L19.2767 4.04076C14.9703 4.60591 11.7263 8.44178 11.7229 12.9641L11.684 18.9771V18.9882C11.684 23.951 15.5599 27.9883 20.3236 27.9883C25.0873 27.9883 28.9599 23.9544 28.9621 18.9938L28.9999 13.2989L25.5835 16.7187Z" fill="#111827"/>\n</svg>':'<svg width="20" height="20" viewBox="0 0 32 32" fill="none" xmlns="http://www.w3.org/2000/svg" aria-hidden="true" focusable="false">\n <path d="M21.9012 17.9947L28.8098 11.085C28.0544 7.39598 25.1207 4.50016 21.4039 4.03514C21.3338 4.02624 21.2626 4.01845 21.1925 4.01178V7.43714C22.8023 7.7097 24.1373 8.751 24.916 10.1839L19.5049 15.5939L21.9012 17.9947Z" fill="#EB2026"/>\n <path d="M9.47025 27.9927H6.0727V7.40489H3V4.00734H9.47025V27.9927Z" fill="#F9FAFB"/>\n <path d="M25.5835 16.7187L25.569 18.9771V18.9882C25.569 22.0776 23.2172 24.5907 20.3269 24.5907C17.4367 24.5907 15.0871 22.0798 15.0849 18.9938L15.126 12.9807V12.9696C15.126 10.224 16.9906 7.88999 19.4992 7.44388V4.01518L19.2767 4.04076C14.9703 4.60591 11.7263 8.44178 11.7229 12.9641L11.684 18.9771V18.9882C11.684 23.951 15.5599 27.9883 20.3236 27.9883C25.0873 27.9883 28.9599 23.9544 28.9621 18.9938L28.9999 13.2989L25.5835 16.7187Z" fill="#F9FAFB"/>\n</svg>'}function $(e="dark"){return`<span class="tenms-login-btn__logo">${A(e)}</span>`}var L;const P="Login with 10MinuteSchool",z=null!==(L=globalThis.HTMLElement)&&void 0!==L?L:class{};class N extends z{constructor(){super(...arguments),this.auth=null,this.loading=!1}static get observedAttributes(){return["client-id","redirect-uri","scope","theme","variant","size","text"]}connectedCallback(){this.render()}attributeChangedCallback(){this.loading||this.render()}render(){var e;const t=j(this.getAttribute("theme")),n=B(this.getAttribute("variant")),o=q(this.getAttribute("size")),i=(null===(e=this.getAttribute("text"))||void 0===e?void 0:e.trim())||P;var r;this.innerHTML=`\n <button class="${V((r={loading:this.loading,text:i,theme:t,variant:n,size:o}).theme,r.variant,r.size,r.loading)}" type="button" ${r.loading?'disabled aria-busy="true"':""}>\n ${r.loading?'<span class="tenms-login-btn__spinner" aria-hidden="true"></span>':$(r.theme)}\n <span class="tenms-login-btn__label">${F(r.text)}</span>\n </button>\n `;const s=this.querySelector("button");s&&s.addEventListener("click",()=>{this.handleClick()})}async handleClick(){if(this.loading)return;const e=this.getConfig();if(e.clientId&&e.redirectUri){this.auth||(this.auth=new x(e)),this.loading=!0,this.render();try{const e=await this.auth.loginWithPopup();this.dispatchEvent(new CustomEvent("tenms-success",{detail:e,bubbles:!0,composed:!0}))}catch(e){this.dispatchError(W(e))}finally{this.loading=!1,this.render()}}else this.dispatchError(new n("client-id and redirect-uri attributes are required","invalid_login_button_config"))}getConfig(){const e=this.getAttribute("scope")||"profile";return{clientId:this.getAttribute("client-id")||"",redirectUri:this.getAttribute("redirect-uri")||"",scopes:e.split(" ").map(e=>e.trim()).filter(Boolean)}}dispatchError(e){this.dispatchEvent(new CustomEvent("tenms-error",{detail:e,bubbles:!0,composed:!0}))}}function O(){"undefined"==typeof window||"undefined"==typeof customElements||customElements.get("tenms-login-button")||customElements.define("tenms-login-button",N)}function M(e,t){e.className=V(t.theme,t.variant,t.size,t.loading),e.type="button",e.disabled=t.loading,e.setAttribute("aria-busy",String(t.loading)),e.innerHTML=t.loading?`<span class="tenms-login-btn__spinner" aria-hidden="true"></span><span class="tenms-login-btn__label">${F(t.text)}</span>`:`${$(t.theme)}<span class="tenms-login-btn__label">${F(t.text)}</span>`}function V(e,t,n,o){return["tenms-login-btn",`tenms-login-btn--${e}`,`tenms-login-btn--${t}`,`tenms-login-btn--${n}`,o?"tenms-login-btn--loading":""].filter(Boolean).join(" ")}function j(e){return"light"===e?e:"dark"}function B(e){return"outline"===e?e:"fill"}function q(e){return"small"===e||"medium"===e?e:"large"}function F(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;")}function W(e){return e instanceof Error?e:new Error(String(e))}const H="Login with 10MinuteSchool",K="dark",D="fill",J="large";function X(e){return"light"===e?e:K}function Z(e){return"small"===e||"medium"===e?e:J}O(),exports.LoginButton=function(e){const{clientId:n,redirectUri:o,scopes:i,theme:r=K,variant:s=D,size:a=J,text:c=H,onSuccess:l,onError:d,className:h=""}=e,[u,g]=t.useState(!1),f=t.useRef(l),p=t.useRef(d);t.useEffect(()=>{f.current=l},[l]),t.useEffect(()=>{p.current=d},[d]);const m=Array.isArray(i)?i.join("\0"):"",w=t.useMemo(()=>new x({clientId:n,redirectUri:o,scopes:i}),[n,o,m]),b=t.useCallback(async()=>{var e,t;g(!0);try{const t=await w.loginWithPopup();null===(e=f.current)||void 0===e||e.call(f,t)}catch(e){null===(t=p.current)||void 0===t||t.call(p,function(e){return e instanceof Error?e:new Error(String(e))}(e))}finally{g(!1)}},[w]),_=["tenms-login-btn",`tenms-login-btn--${X(r)}`,`tenms-login-btn--${v=s,"outline"===v?v:D}`,`tenms-login-btn--${Z(a)}`,u?"tenms-login-btn--loading":"",h].filter(Boolean).join(" ");var v;return t.createElement("button",{className:_,type:"button",onClick:()=>{b()},disabled:u,"aria-busy":u},u?t.createElement("span",{className:"tenms-login-btn__spinner","aria-hidden":"true"}):t.createElement("span",{className:"tenms-login-btn__logo",dangerouslySetInnerHTML:{__html:A(X(r))}}),t.createElement("span",{className:"tenms-login-btn__label"},c))},exports.TenMSAuth=x,exports.TenMSAuthError=n,exports.TenMSLoginButtonElement=N,exports.VERSION="0.4.0",exports.createLogger=f,exports.generateCodeChallenge=r,exports.generateCodeVerifier=i,exports.generateState=s,exports.openPopup=c,exports.registerLoginButton=O,exports.renderLoginButton=function(e,t){var o;const i="string"==typeof e?document.querySelector(e):e;if(!i)throw new n(`Container element not found: ${e}`,"container_not_found");const r=new x({clientId:t.clientId,redirectUri:t.redirectUri,scopes:t.scopes}),s=j(t.theme),a=B(t.variant),c=q(t.size),l=(null===(o=t.text)||void 0===o?void 0:o.trim())||P,d=document.createElement("button");M(d,{loading:!1,size:c,text:l,theme:s,variant:a}),d.addEventListener("click",async()=>{var e,n;if(!d.classList.contains("tenms-login-btn--loading")){M(d,{loading:!0,size:c,text:l,theme:s,variant:a});try{const n=await r.loginWithPopup();null===(e=t.onSuccess)||void 0===e||e.call(t,n)}catch(e){null===(n=t.onError)||void 0===n||n.call(t,W(e))}finally{M(d,{loading:!1,size:c,text:l,theme:s,variant:a})}}}),i.replaceChildren(d)},exports.truncate=w,exports.waitForPopupRedirect=l;
2
2
  //# sourceMappingURL=tenms-auth.cjs.js.map
@@ -1,2 +1,2 @@
1
- import*as e from"react";class t extends Error{constructor(e,t){super(e),this.name="TenMSAuthError",this.code=t,Object.setPrototypeOf(this,new.target.prototype)}}const n="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~";function o(e=64){s(e,43,128,"code_verifier length");const t=[];for(;t.length<e;){const o=new Uint8Array(e+16);crypto.getRandomValues(o);for(const i of o){if(t.length>=e)break;i<198&&t.push(n[i%66])}}return t.join("")}async function i(e){if(!e)throw new Error("codeVerifier is required to generate a code challenge");const t=(new TextEncoder).encode(e);return function(e){const t=new Uint8Array(e);let n="";for(const e of t)n+=String.fromCharCode(e);return btoa(n).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}(await crypto.subtle.digest("SHA-256",t))}function r(e=32){s(e,1,1024,"state byte length");const t=new Uint8Array(e);return crypto.getRandomValues(t),Array.from(t,e=>e.toString(16).padStart(2,"0")).join("")}function s(e,t,n,o){if(!Number.isInteger(e)||e<t||e>n)throw new RangeError(`${o} must be an integer between ${t} and ${n}`)}function a(e){l(e.width,"popup width"),l(e.height,"popup height");const t="number"==typeof window.screenX?window.screenX:window.screenLeft,n="number"==typeof window.screenY?window.screenY:window.screenTop,o=Math.round(t+Math.max(0,(window.innerWidth-e.width)/2)),i=Math.round(n+Math.max(0,(window.innerHeight-e.height)/2)),r=[`width=${e.width}`,`height=${e.height}`,`left=${o}`,`top=${i}`,"toolbar=no","menubar=no","scrollbars=yes","resizable=yes","status=no"].join(",");return window.open(e.url,"tenms_auth_popup",r)}function c(e,n,o,i=3e5){if(!n)throw new Error("redirectUri is required to monitor popup redirects");if(!o)throw new Error("expectedState is required to validate the popup callback");let r;l(i,"popup timeout");try{r=new URL(n)}catch(e){throw new t(`redirectUri is not a valid URL: "${n}"`,"invalid_redirect_uri")}return new Promise((n,s)=>{const a=Date.now(),c=window.setInterval(()=>{try{if(!e||e.closed)return window.clearInterval(c),void s(new t("Login popup was closed","popup_closed"));if(Date.now()-a>i)return window.clearInterval(c),e.close(),void s(new t("Login timed out while waiting for the redirect URI","popup_timeout"));const l=e.location.href;if(!l)return;let d;try{d=new URL(l)}catch(e){return}if(d.origin!==r.origin||d.pathname!==r.pathname)return;window.clearInterval(c),e.close();const h=d.searchParams.get("code"),u=d.searchParams.get("state"),g=d.searchParams.get("error"),f=d.searchParams.get("error_description");if(g)return void s(new t(f||g,"oauth_error"));if(!h)return void s(new t("No authorization code was returned to the redirect URI","missing_authorization_code"));if(u!==o)return void s(new t("State mismatch — possible CSRF attack","state_mismatch"));n({code:h,state:u})}catch(e){e instanceof DOMException||(window.clearInterval(c),s(e instanceof Error?e:new Error(String(e))))}},500)})}function l(e,t){if(!Number.isInteger(e)||e<=0)throw new RangeError(`${t} must be a positive integer`)}const d="[TenMSAuth]",h="color:#22c55e;font-weight:700",u="color:inherit;font-weight:normal";function g(e){return e?p:f}const f={info:()=>{},warn:()=>{},error:()=>{}},p={info(e,t){t&&Object.keys(t).length>0?(console.groupCollapsed(`%c${d}%c ${e}`,h,u),console.table(t),console.groupEnd()):console.log(`%c${d}%c ${e}`,h,u)},warn(e,t){console.warn(`%c${d}%c ⚠ ${e}`,h,u,null!=t?t:"")},error(e,t){console.error(`%c${d}%c ✕ ${e}`,h,u,null!=t?t:"")}};function m(e){return e?e.length>8?`${e.slice(0,8)}…`:e:"(empty)"}class w{get(e){const t=document.cookie.match(new RegExp("(?:^|; )"+e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")+"=([^;]*)"));return t?decodeURIComponent(t[1]):null}set(e,t,n){let o=`${e}=${encodeURIComponent(t)}; path=/; SameSite=Lax`;n&&(o+=`; expires=${new Date(1e3*n).toUTCString()}`),document.cookie=o}remove(e){document.cookie=`${e}=; path=/; expires=Thu, 01 Jan 1970 00:00:00 GMT; SameSite=Lax`}clear(e){e.forEach(e=>this.remove(e))}}class b{get(e){return localStorage.getItem(e)}set(e,t){localStorage.setItem(e,t)}remove(e){localStorage.removeItem(e)}clear(e){e.forEach(e=>this.remove(e))}}const _="https://api.10minuteschool.net/auth",v="https://10minuteschool.net/auth/login",k=["profile"],y={ACCESS_TOKEN:"_tenms_access_token",REFRESH_TOKEN:"_tenms_refresh_token",EXPIRES_AT:"_tenms_expires_at",USER:"_tenms_user"};class S{constructor(e){var n,o;this.config=function(e){var n,o;const i=null===(n=e.clientId)||void 0===n?void 0:n.trim();if(!i)throw new t("clientId is required","missing_client_id");const r=(null===(o=e.redirectUri)||void 0===o?void 0:o.trim())||void 0,s=E(_,"baseUrl","invalid_base_url"),a=E(v,"authorizeUrl","invalid_authorize_url"),c=function(e){if(!Array.isArray(e)||0===e.length)return k;const t=e.map(e=>e.trim()).filter(Boolean);return t.length>0?t:k}(e.scopes);return{clientId:i,redirectUri:r,scopes:c,baseUrl:s,authorizeUrl:a}}(e),this.log=g(!0===e.debug),this.storage="localStorage"===(null!==(n=e.storage)&&void 0!==n?n:"cookie")?new b:new w,this.log.info("init",{clientId:this.config.clientId,redirectUri:this.config.redirectUri,baseUrl:this.config.baseUrl,authorizeUrl:this.config.authorizeUrl,scopes:this.config.scopes.join(" "),storage:null!==(o=e.storage)&&void 0!==o?o:"cookie",debug:!0===e.debug})}async loginWithPopup(e={}){var n,s;const l=null!==(n=e.width)&&void 0!==n?n:500,d=null!==(s=e.height)&&void 0!==s?s:600;this.log.info("loginWithPopup:start",{width:l,height:d});const h=r(),u=o();this.log.info("loginWithPopup:pkce-generated",{state:m(h),codeVerifier:m(u)});const g=a({url:"about:blank",width:l,height:d});if(!g){const e=new t("Failed to open login popup. Please allow popups for this site.","popup_blocked");throw this.log.error("loginWithPopup:popup-blocked",e),e}if(g===window){const e=new t("The browser reused the current tab instead of opening a popup window.","popup_reused_opener");throw this.log.error("loginWithPopup:popup-reused-opener",e),e}this.log.info("loginWithPopup:popup-opened"),function(e){try{e.document.title="Signing in…",e.document.body.style.cssText="font-family:system-ui,sans-serif;padding:2rem;text-align:center",e.document.body.textContent="Signing in…"}catch(e){}}(g);try{const e=await i(u),t=this.buildAuthorizeUrl(h,e);this.log.info("loginWithPopup:navigating",{authorizeUrl:t,codeChallenge:m(e)}),g.location.href=t;const n=await c(g,this.requireRedirectUri(),h);return this.log.info("loginWithPopup:success",{code:m(n.code),state:m(n.state)}),{code:n.code,state:n.state,codeVerifier:u}}catch(e){throw g.closed||g.close(),this.log.error("loginWithPopup:error",e),e}}async loginWithRedirect(){this.log.info("loginWithRedirect:start");const e=r(),t=o(),n=await i(t);this.log.info("loginWithRedirect:pkce-generated",{state:m(e),codeVerifier:m(t),codeChallenge:m(n)}),function(e,t){sessionStorage.setItem(x("state"),e),sessionStorage.setItem(x("code_verifier"),t)}(e,t),this.log.info("loginWithRedirect:session-persisted",{storageKeys:[x("state"),x("code_verifier")]});const s=this.buildAuthorizeUrl(e,n);this.log.info("loginWithRedirect:navigating",{authorizeUrl:s}),window.location.href=s}handleRedirectCallback(){const e=new URLSearchParams(window.location.search),n=e.get("code"),o=e.get("state"),i=e.get("error"),r=e.get("error_description");if(!n&&!o&&!i)return this.log.info("handleRedirectCallback:not-a-callback"),null;this.log.info("handleRedirectCallback:callback-detected",{hasCode:Boolean(n),hasState:Boolean(o),error:null!=i?i:"(none)",errorDescription:null!=r?r:"(none)"});const s=sessionStorage.getItem(x("state")),a=sessionStorage.getItem(x("code_verifier"));if(!o||!s||o!==s){C();const e=new t("State mismatch — possible CSRF attack","state_mismatch");throw this.log.warn("handleRedirectCallback:state-mismatch",{receivedState:o?m(o):"(missing)",storedStatePresent:Boolean(s)}),e}if(C(),function(){const e=window.location.origin+window.location.pathname;window.history.replaceState({},document.title,e)}(),i)throw this.log.error("handleRedirectCallback:oauth-error",{error:i,errorDescription:r}),new t(r||i,i);if(!n){const e=new t("No authorization code was returned to the redirect URI","missing_authorization_code");throw this.log.error("handleRedirectCallback:missing-code",e),e}if(!a){const e=new t("No PKCE code verifier was found for the redirect callback","missing_code_verifier");throw this.log.error("handleRedirectCallback:missing-verifier",e),e}return this.log.info("handleRedirectCallback:success",{code:m(n),state:m(o)}),{code:n,state:o,codeVerifier:a}}async exchangeCode(e,n){if(!e||e.length>2048)throw new t("code is required and must be under 2048 characters","invalid_authorization_code");if(!n||n.length<43||n.length>128)throw new t("codeVerifier must be 43–128 characters (RFC 7636)","invalid_code_verifier");const o=`${this.config.baseUrl}/v1/oauth/token`;this.log.info("exchangeCode:start",{endpoint:o,code:m(e),codeVerifier:m(n),clientId:this.config.clientId,redirectUri:this.config.redirectUri});const i=await fetch(o,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({grant_type:"authorization_code",code:e,redirect_uri:this.requireRedirectUri(),client_id:this.config.clientId,code_verifier:n})});if(!i.ok){const e=await U(i),n=new t(T(e,"Token exchange failed"),"token_exchange_failed");throw this.log.error("exchangeCode:error",{status:i.status,message:n.message}),n}const r=I(await i.json());return this.log.info("exchangeCode:success",{token_type:r.token_type,expires_in:r.expires_in,scope:r.scope,access_token:m(r.access_token),has_refresh_token:Boolean(r.refresh_token)}),r}async refreshToken(e){if(!e)throw new t("refreshToken is required","missing_refresh_token");const n=`${this.config.baseUrl}/v1/oauth/token`;this.log.info("refreshToken:start",{endpoint:n,refreshToken:m(e),clientId:this.config.clientId});const o=await fetch(n,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({grant_type:"refresh_token",refresh_token:e,client_id:this.config.clientId})});if(!o.ok){const e=await U(o),n=new t(T(e,"Token refresh failed"),"token_refresh_failed");throw this.log.error("refreshToken:error",{status:o.status,message:n.message}),n}const i=I(await o.json());return this.log.info("refreshToken:success",{token_type:i.token_type,expires_in:i.expires_in,access_token:m(i.access_token)}),i}async getUserInfo(e){var n,o;if(!e)throw new t("accessToken is required to fetch user info","missing_access_token");const i=`${this.config.baseUrl}/v1/oauth/userinfo`;this.log.info("getUserInfo:start",{endpoint:i,accessToken:m(e)});const r=await fetch(i,{headers:{Authorization:`Bearer ${e}`}});if(!r.ok){const e=await U(r),n=new t(T(e,"Failed to fetch user info"),"userinfo_failed");throw this.log.error("getUserInfo:error",{status:r.status,message:n.message}),n}const s=function(e){if(!e||"object"!=typeof e||"string"!=typeof e.sub||!e.sub)throw new t("Server returned an invalid userinfo response (missing sub)","invalid_userinfo_response");return e}(await r.json());return this.log.info("getUserInfo:success",{sub:s.sub,name:null!==(n=s.name)&&void 0!==n?n:"(not returned)",email:null!==(o=s.email)&&void 0!==o?o:"(not returned)"}),s}async revokeToken(e){if(!e)throw new t("token is required to revoke an OAuth token","missing_token");const n=`${this.config.baseUrl}/v1/oauth/revoke`;this.log.info("revokeToken:start",{endpoint:n,token:m(e),clientId:this.config.clientId});const o=await fetch(n,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({token:e,client_id:this.config.clientId})});if(!o.ok){const e=await U(o),n=new t(T(e,"Failed to revoke token"),"revoke_failed");throw this.log.error("revokeToken:error",{status:o.status,message:n.message}),n}this.log.info("revokeToken:success")}async handleLoginSuccess(e){this.log.info("handleLoginSuccess:start",{code:m(e.code)});const t=await this.exchangeCode(e.code,e.codeVerifier),n=await this.getUserInfo(t.access_token),o=Math.floor(Date.now()/1e3)+t.expires_in;return this.storage.set(y.ACCESS_TOKEN,t.access_token,o),this.storage.set(y.EXPIRES_AT,String(o),o),t.refresh_token&&this.storage.set(y.REFRESH_TOKEN,t.refresh_token),this.storage.set(y.USER,JSON.stringify(n)),this.log.info("handleLoginSuccess:session-saved",{sub:n.sub,expiresAt:o,hasRefreshToken:Boolean(t.refresh_token)}),{user:n,accessToken:t.access_token}}async getAccessToken(){var e;const t=this.storage.get(y.ACCESS_TOKEN),n=Number(null!==(e=this.storage.get(y.EXPIRES_AT))&&void 0!==e?e:"0");if(!t)return null;if(!(n>0&&Math.floor(Date.now()/1e3)>=n))return t;this.log.info("getAccessToken:expired, attempting refresh");const o=this.storage.get(y.REFRESH_TOKEN);if(!o)return this.log.info("getAccessToken:no-refresh-token, clearing session"),this.clearSession(),null;try{const e=await this.refreshToken(o),t=Math.floor(Date.now()/1e3)+e.expires_in;return this.storage.set(y.ACCESS_TOKEN,e.access_token,t),this.storage.set(y.EXPIRES_AT,String(t),t),e.refresh_token&&this.storage.set(y.REFRESH_TOKEN,e.refresh_token),this.log.info("getAccessToken:refreshed",{newExpiresAt:t}),e.access_token}catch(e){return this.log.error("getAccessToken:refresh-failed",e),this.clearSession(),null}}getUser(){const e=this.storage.get(y.USER);if(!e)return null;try{return JSON.parse(e)}catch(e){return null}}isLoggedIn(){var e;if(!this.storage.get(y.ACCESS_TOKEN))return!1;const t=Number(null!==(e=this.storage.get(y.EXPIRES_AT))&&void 0!==e?e:"0");return 0===t||Math.floor(Date.now()/1e3)<t}async logout(){const e=this.storage.get(y.ACCESS_TOKEN);if(e)try{await this.revokeToken(e)}catch(e){this.log.error("logout:revoke-failed",e)}this.clearSession(),this.log.info("logout:done")}getBaseUrl(){return this.config.baseUrl}getClientId(){return this.config.clientId}clearSession(){this.storage.clear(Object.values(y))}requireRedirectUri(){if(this.config.redirectUri)return this.config.redirectUri;if("undefined"!=typeof window)return window.location.origin;throw new t("redirectUri is required — pass it in the TenMSAuth constructor or call from a browser context","missing_redirect_uri")}buildAuthorizeUrl(e,t){const n=new URL(this.config.authorizeUrl);return n.searchParams.set("client_id",this.config.clientId),n.searchParams.set("redirect_uri",this.requireRedirectUri()),n.searchParams.set("response_type","code"),n.searchParams.set("scope",this.config.scopes.join(" ")),n.searchParams.set("state",e),n.searchParams.set("code_challenge",t),n.searchParams.set("code_challenge_method","S256"),n.toString()}}function E(e,n,o){const i=e.trim();if(!i)throw new t(`${n} must not be empty`,o);const r=i.replace(/\/+$/,"");try{new URL(r)}catch(e){throw new t(`${n} is not a valid URL: "${r}"`,o)}return r}function x(e){return`tenms_auth_${e}`}function C(){sessionStorage.removeItem(x("state")),sessionStorage.removeItem(x("code_verifier"))}async function U(e){try{const t=await e.text();return t?JSON.parse(t):{}}catch(e){return{}}}function T(e,t){var n,o,i;return null!==(i=null!==(o=null!==(n=e.error_description)&&void 0!==n?n:e.message)&&void 0!==o?o:e.error)&&void 0!==i?i:t}function I(e){if(!e||"object"!=typeof e||"string"!=typeof e.access_token||!e.access_token)throw new t("Server returned an invalid token response (missing access_token)","invalid_token_response");return e}!function(e,t){void 0===t&&(t={});var n=t.insertAt;if("undefined"!=typeof document){var o=document.head||document.getElementsByTagName("head")[0],i=document.createElement("style");i.type="text/css","top"===n&&o.firstChild?o.insertBefore(i,o.firstChild):o.appendChild(i),i.styleSheet?i.styleSheet.cssText=e:i.appendChild(document.createTextNode(e))}}(".tenms-login-btn{-webkit-font-smoothing:antialiased;align-items:center;border:1px solid transparent;border-radius:6px;cursor:pointer;display:inline-flex;font-family:-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica Neue,Arial,sans-serif;font-size:14px;font-weight:500;gap:6px;height:36px;justify-content:center;line-height:1;padding:0 12px;text-decoration:none;transition:background .15s ease,border-color .15s ease,color .15s ease,opacity .15s ease;user-select:none;-webkit-user-select:none;white-space:nowrap;width:fit-content}.tenms-login-btn:focus-visible{outline:2px solid #0070f3;outline-offset:2px}.tenms-login-btn:disabled{cursor:not-allowed}.tenms-login-btn--dark.tenms-login-btn--fill{background:#000;border-color:#000;color:#fff}.tenms-login-btn--dark.tenms-login-btn--fill:hover:not(:disabled){background:#333;border-color:#333}.tenms-login-btn--dark.tenms-login-btn--outline{background:transparent;border-color:#000;color:#000}.tenms-login-btn--dark.tenms-login-btn--outline:hover:not(:disabled){background:#f5f5f5}.tenms-login-btn--light.tenms-login-btn--fill{background:#fff;border-color:#e5e7eb;color:#111}.tenms-login-btn--light.tenms-login-btn--fill:hover:not(:disabled){background:#f5f5f5}.tenms-login-btn--light.tenms-login-btn--outline{background:transparent;border-color:#e5e7eb;color:#111}.tenms-login-btn--light.tenms-login-btn--outline:hover:not(:disabled){background:#f5f5f5;border-color:#d1d5db}.tenms-login-btn--small{font-size:13px;gap:5px;height:32px;padding:0 10px}.tenms-login-btn--medium{font-size:14px;height:36px;padding:0 12px}.tenms-login-btn--large{font-size:14px;height:40px;padding:0 14px}.tenms-login-btn__logo{align-items:center;display:inline-flex;flex-shrink:0}.tenms-login-btn__logo svg{display:block;height:18px;width:18px}.tenms-login-btn--loading{opacity:.6;pointer-events:none}.tenms-login-btn__spinner{animation:tenms-spin .6s linear infinite;border:1.5px solid;border-radius:50%;border-top:1.5px solid transparent;height:14px;width:14px}@keyframes tenms-spin{to{transform:rotate(1turn)}}");function R(e){return"light"===e?'<svg width="20" height="20" viewBox="0 0 32 32" fill="none" xmlns="http://www.w3.org/2000/svg" aria-hidden="true" focusable="false">\n <path d="M21.9012 17.9947L28.8098 11.085C28.0544 7.39598 25.1207 4.50016 21.4039 4.03514C21.3338 4.02624 21.2626 4.01845 21.1925 4.01178V7.43714C22.8023 7.7097 24.1373 8.751 24.916 10.1839L19.5049 15.5939L21.9012 17.9947Z" fill="#EB2026"/>\n <path d="M9.47025 27.9927H6.0727V7.40489H3V4.00734H9.47025V27.9927Z" fill="#111827"/>\n <path d="M25.5835 16.7187L25.569 18.9771V18.9882C25.569 22.0776 23.2172 24.5907 20.3269 24.5907C17.4367 24.5907 15.0871 22.0798 15.0849 18.9938L15.126 12.9807V12.9696C15.126 10.224 16.9906 7.88999 19.4992 7.44388V4.01518L19.2767 4.04076C14.9703 4.60591 11.7263 8.44178 11.7229 12.9641L11.684 18.9771V18.9882C11.684 23.951 15.5599 27.9883 20.3236 27.9883C25.0873 27.9883 28.9599 23.9544 28.9621 18.9938L28.9999 13.2989L25.5835 16.7187Z" fill="#111827"/>\n</svg>':'<svg width="20" height="20" viewBox="0 0 32 32" fill="none" xmlns="http://www.w3.org/2000/svg" aria-hidden="true" focusable="false">\n <path d="M21.9012 17.9947L28.8098 11.085C28.0544 7.39598 25.1207 4.50016 21.4039 4.03514C21.3338 4.02624 21.2626 4.01845 21.1925 4.01178V7.43714C22.8023 7.7097 24.1373 8.751 24.916 10.1839L19.5049 15.5939L21.9012 17.9947Z" fill="#EB2026"/>\n <path d="M9.47025 27.9927H6.0727V7.40489H3V4.00734H9.47025V27.9927Z" fill="#F9FAFB"/>\n <path d="M25.5835 16.7187L25.569 18.9771V18.9882C25.569 22.0776 23.2172 24.5907 20.3269 24.5907C17.4367 24.5907 15.0871 22.0798 15.0849 18.9938L15.126 12.9807V12.9696C15.126 10.224 16.9906 7.88999 19.4992 7.44388V4.01518L19.2767 4.04076C14.9703 4.60591 11.7263 8.44178 11.7229 12.9641L11.684 18.9771V18.9882C11.684 23.951 15.5599 27.9883 20.3236 27.9883C25.0873 27.9883 28.9599 23.9544 28.9621 18.9938L28.9999 13.2989L25.5835 16.7187Z" fill="#F9FAFB"/>\n</svg>'}function $(e="dark"){return`<span class="tenms-login-btn__logo">${R(e)}</span>`}var A;const L="Login with 10MinuteSchool",P=null!==(A=globalThis.HTMLElement)&&void 0!==A?A:class{};class z extends P{constructor(){super(...arguments),this.auth=null,this.loading=!1}static get observedAttributes(){return["client-id","redirect-uri","scope","theme","variant","size","text"]}connectedCallback(){this.render()}attributeChangedCallback(){this.loading||this.render()}render(){var e;const t=j(this.getAttribute("theme")),n=B(this.getAttribute("variant")),o=W(this.getAttribute("size")),i=(null===(e=this.getAttribute("text"))||void 0===e?void 0:e.trim())||L;var r;this.innerHTML=`\n <button class="${O((r={loading:this.loading,text:i,theme:t,variant:n,size:o}).theme,r.variant,r.size,r.loading)}" type="button" ${r.loading?'disabled aria-busy="true"':""}>\n ${r.loading?'<span class="tenms-login-btn__spinner" aria-hidden="true"></span>':$(r.theme)}\n <span class="tenms-login-btn__label">${q(r.text)}</span>\n </button>\n `;const s=this.querySelector("button");s&&s.addEventListener("click",()=>{this.handleClick()})}async handleClick(){if(this.loading)return;const e=this.getConfig();if(e.clientId&&e.redirectUri){this.auth||(this.auth=new S(e)),this.loading=!0,this.render();try{const e=await this.auth.loginWithPopup();this.dispatchEvent(new CustomEvent("tenms-success",{detail:e,bubbles:!0,composed:!0}))}catch(e){this.dispatchError(F(e))}finally{this.loading=!1,this.render()}}else this.dispatchError(new t("client-id and redirect-uri attributes are required","invalid_login_button_config"))}getConfig(){const e=this.getAttribute("scope")||"profile";return{clientId:this.getAttribute("client-id")||"",redirectUri:this.getAttribute("redirect-uri")||"",scopes:e.split(" ").map(e=>e.trim()).filter(Boolean)}}dispatchError(e){this.dispatchEvent(new CustomEvent("tenms-error",{detail:e,bubbles:!0,composed:!0}))}}function N(){"undefined"==typeof window||"undefined"==typeof customElements||customElements.get("tenms-login-button")||customElements.define("tenms-login-button",z)}function M(e,n){var o;const i="string"==typeof e?document.querySelector(e):e;if(!i)throw new t(`Container element not found: ${e}`,"container_not_found");const r=new S({clientId:n.clientId,redirectUri:n.redirectUri,scopes:n.scopes}),s=j(n.theme),a=B(n.variant),c=W(n.size),l=(null===(o=n.text)||void 0===o?void 0:o.trim())||L,d=document.createElement("button");V(d,{loading:!1,size:c,text:l,theme:s,variant:a}),d.addEventListener("click",async()=>{var e,t;if(!d.classList.contains("tenms-login-btn--loading")){V(d,{loading:!0,size:c,text:l,theme:s,variant:a});try{const t=await r.loginWithPopup();null===(e=n.onSuccess)||void 0===e||e.call(n,t)}catch(e){null===(t=n.onError)||void 0===t||t.call(n,F(e))}finally{V(d,{loading:!1,size:c,text:l,theme:s,variant:a})}}}),i.replaceChildren(d)}function V(e,t){e.className=O(t.theme,t.variant,t.size,t.loading),e.type="button",e.disabled=t.loading,e.setAttribute("aria-busy",String(t.loading)),e.innerHTML=t.loading?`<span class="tenms-login-btn__spinner" aria-hidden="true"></span><span class="tenms-login-btn__label">${q(t.text)}</span>`:`${$(t.theme)}<span class="tenms-login-btn__label">${q(t.text)}</span>`}function O(e,t,n,o){return["tenms-login-btn",`tenms-login-btn--${e}`,`tenms-login-btn--${t}`,`tenms-login-btn--${n}`,o?"tenms-login-btn--loading":""].filter(Boolean).join(" ")}function j(e){return"light"===e?e:"dark"}function B(e){return"outline"===e?e:"fill"}function W(e){return"small"===e||"medium"===e?e:"large"}function q(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;")}function F(e){return e instanceof Error?e:new Error(String(e))}const H="Login with 10MinuteSchool",K="dark",D="fill",J="large";function X(t){const{clientId:n,redirectUri:o,scopes:i,theme:r=K,variant:s=D,size:a=J,text:c=H,onSuccess:l,onError:d,className:h=""}=t,[u,g]=e.useState(!1),f=e.useRef(l),p=e.useRef(d);e.useEffect(()=>{f.current=l},[l]),e.useEffect(()=>{p.current=d},[d]);const m=Array.isArray(i)?i.join("\0"):"",w=e.useMemo(()=>new S({clientId:n,redirectUri:o,scopes:i}),[n,o,m]),b=e.useCallback(async()=>{var e,t;g(!0);try{const t=await w.loginWithPopup();null===(e=f.current)||void 0===e||e.call(f,t)}catch(e){null===(t=p.current)||void 0===t||t.call(p,function(e){return e instanceof Error?e:new Error(String(e))}(e))}finally{g(!1)}},[w]),_=["tenms-login-btn",`tenms-login-btn--${Z(r)}`,`tenms-login-btn--${v=s,"outline"===v?v:D}`,`tenms-login-btn--${Y(a)}`,u?"tenms-login-btn--loading":"",h].filter(Boolean).join(" ");var v;return e.createElement("button",{className:_,type:"button",onClick:()=>{b()},disabled:u,"aria-busy":u},u?e.createElement("span",{className:"tenms-login-btn__spinner","aria-hidden":"true"}):e.createElement("span",{className:"tenms-login-btn__logo",dangerouslySetInnerHTML:{__html:R(Z(r))}}),e.createElement("span",{className:"tenms-login-btn__label"},c))}function Z(e){return"light"===e?e:K}function Y(e){return"small"===e||"medium"===e?e:J}const G="0.3.0";N();export{X as LoginButton,S as TenMSAuth,t as TenMSAuthError,z as TenMSLoginButtonElement,G as VERSION,g as createLogger,i as generateCodeChallenge,o as generateCodeVerifier,r as generateState,a as openPopup,N as registerLoginButton,M as renderLoginButton,m as truncate,c as waitForPopupRedirect};
1
+ import*as e from"react";class t extends Error{constructor(e,t){super(e),this.name="TenMSAuthError",this.code=t,Object.setPrototypeOf(this,new.target.prototype)}}const n="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~";function o(e=64){s(e,43,128,"code_verifier length");const t=[];for(;t.length<e;){const o=new Uint8Array(e+16);crypto.getRandomValues(o);for(const i of o){if(t.length>=e)break;i<198&&t.push(n[i%66])}}return t.join("")}async function i(e){if(!e)throw new Error("codeVerifier is required to generate a code challenge");const t=(new TextEncoder).encode(e);return function(e){const t=new Uint8Array(e);let n="";for(const e of t)n+=String.fromCharCode(e);return btoa(n).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}(await crypto.subtle.digest("SHA-256",t))}function r(e=32){s(e,1,1024,"state byte length");const t=new Uint8Array(e);return crypto.getRandomValues(t),Array.from(t,e=>e.toString(16).padStart(2,"0")).join("")}function s(e,t,n,o){if(!Number.isInteger(e)||e<t||e>n)throw new RangeError(`${o} must be an integer between ${t} and ${n}`)}function a(e){l(e.width,"popup width"),l(e.height,"popup height");const t="number"==typeof window.screenX?window.screenX:window.screenLeft,n="number"==typeof window.screenY?window.screenY:window.screenTop,o=Math.round(t+Math.max(0,(window.innerWidth-e.width)/2)),i=Math.round(n+Math.max(0,(window.innerHeight-e.height)/2)),r=[`width=${e.width}`,`height=${e.height}`,`left=${o}`,`top=${i}`,"toolbar=no","menubar=no","scrollbars=yes","resizable=yes","status=no"].join(",");return window.open(e.url,"tenms_auth_popup",r)}function c(e,n,o,i=3e5){if(!n)throw new Error("redirectUri is required to monitor popup redirects");if(!o)throw new Error("expectedState is required to validate the popup callback");let r;l(i,"popup timeout");try{r=new URL(n)}catch(e){throw new t(`redirectUri is not a valid URL: "${n}"`,"invalid_redirect_uri")}return new Promise((n,s)=>{const a=Date.now(),c=window.setInterval(()=>{try{if(!e||e.closed)return window.clearInterval(c),void s(new t("Login popup was closed","popup_closed"));if(Date.now()-a>i)return window.clearInterval(c),e.close(),void s(new t("Login timed out while waiting for the redirect URI","popup_timeout"));const l=e.location.href;if(!l)return;let d;try{d=new URL(l)}catch(e){return}if(d.origin!==r.origin||d.pathname!==r.pathname)return;window.clearInterval(c),e.close();const h=d.searchParams.get("code"),u=d.searchParams.get("state"),g=d.searchParams.get("error"),f=d.searchParams.get("error_description");if(g)return void s(new t(f||g,"oauth_error"));if(!h)return void s(new t("No authorization code was returned to the redirect URI","missing_authorization_code"));if(u!==o)return void s(new t("State mismatch — possible CSRF attack","state_mismatch"));n({code:h,state:u})}catch(e){e instanceof DOMException||(window.clearInterval(c),s(e instanceof Error?e:new Error(String(e))))}},500)})}function l(e,t){if(!Number.isInteger(e)||e<=0)throw new RangeError(`${t} must be a positive integer`)}const d="[TenMSAuth]",h="color:#22c55e;font-weight:700",u="color:inherit;font-weight:normal";function g(e){return e?p:f}const f={info:()=>{},warn:()=>{},error:()=>{}},p={info(e,t){t&&Object.keys(t).length>0?(console.groupCollapsed(`%c${d}%c ${e}`,h,u),console.table(t),console.groupEnd()):console.log(`%c${d}%c ${e}`,h,u)},warn(e,t){console.warn(`%c${d}%c ⚠ ${e}`,h,u,null!=t?t:"")},error(e,t){console.error(`%c${d}%c ✕ ${e}`,h,u,null!=t?t:"")}};function m(e){return e?e.length>8?`${e.slice(0,8)}…`:e:"(empty)"}class w{get(e){const t=document.cookie.match(new RegExp("(?:^|; )"+e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")+"=([^;]*)"));return t?decodeURIComponent(t[1]):null}set(e,t,n){let o=`${e}=${encodeURIComponent(t)}; path=/; SameSite=Lax`;n&&(o+=`; expires=${new Date(1e3*n).toUTCString()}`),document.cookie=o}remove(e){document.cookie=`${e}=; path=/; expires=Thu, 01 Jan 1970 00:00:00 GMT; SameSite=Lax`}clear(e){e.forEach(e=>this.remove(e))}}class b{get(e){return localStorage.getItem(e)}set(e,t){localStorage.setItem(e,t)}remove(e){localStorage.removeItem(e)}clear(e){e.forEach(e=>this.remove(e))}}const _="https://api.10minuteschool.com/auth",v="https://10minuteschool.com/auth/login",k=["profile"],y={ACCESS_TOKEN:"_tenms_access_token",REFRESH_TOKEN:"_tenms_refresh_token",EXPIRES_AT:"_tenms_expires_at",USER:"_tenms_user"};class S{constructor(e){var n,o;this.config=function(e){var n,o;const i=null===(n=e.clientId)||void 0===n?void 0:n.trim();if(!i)throw new t("clientId is required","missing_client_id");const r=(null===(o=e.redirectUri)||void 0===o?void 0:o.trim())||void 0,s=E(_,"baseUrl","invalid_base_url"),a=E(v,"authorizeUrl","invalid_authorize_url"),c=function(e){if(!Array.isArray(e)||0===e.length)return k;const t=e.map(e=>e.trim()).filter(Boolean);return t.length>0?t:k}(e.scopes);return{clientId:i,redirectUri:r,scopes:c,baseUrl:s,authorizeUrl:a}}(e),this.log=g(!0===e.debug),this.storage="localStorage"===(null!==(n=e.storage)&&void 0!==n?n:"cookie")?new b:new w,this.log.info("init",{clientId:this.config.clientId,redirectUri:this.config.redirectUri,baseUrl:this.config.baseUrl,authorizeUrl:this.config.authorizeUrl,scopes:this.config.scopes.join(" "),storage:null!==(o=e.storage)&&void 0!==o?o:"cookie",debug:!0===e.debug})}async loginWithPopup(e={}){var n,s;const l=null!==(n=e.width)&&void 0!==n?n:500,d=null!==(s=e.height)&&void 0!==s?s:600;this.log.info("loginWithPopup:start",{width:l,height:d});const h=r(),u=o();this.log.info("loginWithPopup:pkce-generated",{state:m(h),codeVerifier:m(u)});const g=a({url:"about:blank",width:l,height:d});if(!g){const e=new t("Failed to open login popup. Please allow popups for this site.","popup_blocked");throw this.log.error("loginWithPopup:popup-blocked",e),e}if(g===window){const e=new t("The browser reused the current tab instead of opening a popup window.","popup_reused_opener");throw this.log.error("loginWithPopup:popup-reused-opener",e),e}this.log.info("loginWithPopup:popup-opened"),function(e){try{e.document.title="Signing in…",e.document.body.style.cssText="font-family:system-ui,sans-serif;padding:2rem;text-align:center",e.document.body.textContent="Signing in…"}catch(e){}}(g);try{const e=await i(u),t=this.buildAuthorizeUrl(h,e);this.log.info("loginWithPopup:navigating",{authorizeUrl:t,codeChallenge:m(e)}),g.location.href=t;const n=await c(g,this.requireRedirectUri(),h);return this.log.info("loginWithPopup:success",{code:m(n.code),state:m(n.state)}),{code:n.code,state:n.state,codeVerifier:u}}catch(e){throw g.closed||g.close(),this.log.error("loginWithPopup:error",e),e}}async loginWithRedirect(){this.log.info("loginWithRedirect:start");const e=r(),t=o(),n=await i(t);this.log.info("loginWithRedirect:pkce-generated",{state:m(e),codeVerifier:m(t),codeChallenge:m(n)}),function(e,t){sessionStorage.setItem(x("state"),e),sessionStorage.setItem(x("code_verifier"),t)}(e,t),this.log.info("loginWithRedirect:session-persisted",{storageKeys:[x("state"),x("code_verifier")]});const s=this.buildAuthorizeUrl(e,n);this.log.info("loginWithRedirect:navigating",{authorizeUrl:s}),window.location.href=s}handleRedirectCallback(){const e=new URLSearchParams(window.location.search),n=e.get("code"),o=e.get("state"),i=e.get("error"),r=e.get("error_description");if(!n&&!o&&!i)return this.log.info("handleRedirectCallback:not-a-callback"),null;this.log.info("handleRedirectCallback:callback-detected",{hasCode:Boolean(n),hasState:Boolean(o),error:null!=i?i:"(none)",errorDescription:null!=r?r:"(none)"});const s=sessionStorage.getItem(x("state")),a=sessionStorage.getItem(x("code_verifier"));if(!o||!s||o!==s){C();const e=new t("State mismatch — possible CSRF attack","state_mismatch");throw this.log.warn("handleRedirectCallback:state-mismatch",{receivedState:o?m(o):"(missing)",storedStatePresent:Boolean(s)}),e}if(C(),function(){const e=window.location.origin+window.location.pathname;window.history.replaceState({},document.title,e)}(),i)throw this.log.error("handleRedirectCallback:oauth-error",{error:i,errorDescription:r}),new t(r||i,i);if(!n){const e=new t("No authorization code was returned to the redirect URI","missing_authorization_code");throw this.log.error("handleRedirectCallback:missing-code",e),e}if(!a){const e=new t("No PKCE code verifier was found for the redirect callback","missing_code_verifier");throw this.log.error("handleRedirectCallback:missing-verifier",e),e}return this.log.info("handleRedirectCallback:success",{code:m(n),state:m(o)}),{code:n,state:o,codeVerifier:a}}async exchangeCode(e,n){if(!e||e.length>2048)throw new t("code is required and must be under 2048 characters","invalid_authorization_code");if(!n||n.length<43||n.length>128)throw new t("codeVerifier must be 43–128 characters (RFC 7636)","invalid_code_verifier");const o=`${this.config.baseUrl}/v1/oauth/token`;this.log.info("exchangeCode:start",{endpoint:o,code:m(e),codeVerifier:m(n),clientId:this.config.clientId,redirectUri:this.config.redirectUri});const i=await fetch(o,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({grant_type:"authorization_code",code:e,redirect_uri:this.requireRedirectUri(),client_id:this.config.clientId,code_verifier:n})});if(!i.ok){const e=await U(i),n=new t(T(e,"Token exchange failed"),"token_exchange_failed");throw this.log.error("exchangeCode:error",{status:i.status,message:n.message}),n}const r=I(await i.json());return this.log.info("exchangeCode:success",{token_type:r.token_type,expires_in:r.expires_in,scope:r.scope,access_token:m(r.access_token),has_refresh_token:Boolean(r.refresh_token)}),r}async refreshToken(e){if(!e)throw new t("refreshToken is required","missing_refresh_token");const n=`${this.config.baseUrl}/v1/oauth/token`;this.log.info("refreshToken:start",{endpoint:n,refreshToken:m(e),clientId:this.config.clientId});const o=await fetch(n,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({grant_type:"refresh_token",refresh_token:e,client_id:this.config.clientId})});if(!o.ok){const e=await U(o),n=new t(T(e,"Token refresh failed"),"token_refresh_failed");throw this.log.error("refreshToken:error",{status:o.status,message:n.message}),n}const i=I(await o.json());return this.log.info("refreshToken:success",{token_type:i.token_type,expires_in:i.expires_in,access_token:m(i.access_token)}),i}async getUserInfo(e){var n,o;if(!e)throw new t("accessToken is required to fetch user info","missing_access_token");const i=`${this.config.baseUrl}/v1/oauth/userinfo`;this.log.info("getUserInfo:start",{endpoint:i,accessToken:m(e)});const r=await fetch(i,{headers:{Authorization:`Bearer ${e}`}});if(!r.ok){const e=await U(r),n=new t(T(e,"Failed to fetch user info"),"userinfo_failed");throw this.log.error("getUserInfo:error",{status:r.status,message:n.message}),n}const s=function(e){if(!e||"object"!=typeof e||"string"!=typeof e.sub||!e.sub)throw new t("Server returned an invalid userinfo response (missing sub)","invalid_userinfo_response");return e}(await r.json());return this.log.info("getUserInfo:success",{sub:s.sub,name:null!==(n=s.name)&&void 0!==n?n:"(not returned)",email:null!==(o=s.email)&&void 0!==o?o:"(not returned)"}),s}async revokeToken(e){if(!e)throw new t("token is required to revoke an OAuth token","missing_token");const n=`${this.config.baseUrl}/v1/oauth/revoke`;this.log.info("revokeToken:start",{endpoint:n,token:m(e),clientId:this.config.clientId});const o=await fetch(n,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({token:e,client_id:this.config.clientId})});if(!o.ok){const e=await U(o),n=new t(T(e,"Failed to revoke token"),"revoke_failed");throw this.log.error("revokeToken:error",{status:o.status,message:n.message}),n}this.log.info("revokeToken:success")}async handleLoginSuccess(e){this.log.info("handleLoginSuccess:start",{code:m(e.code)});const t=await this.exchangeCode(e.code,e.codeVerifier),n=await this.getUserInfo(t.access_token),o=Math.floor(Date.now()/1e3)+t.expires_in;return this.storage.set(y.ACCESS_TOKEN,t.access_token,o),this.storage.set(y.EXPIRES_AT,String(o),o),t.refresh_token&&this.storage.set(y.REFRESH_TOKEN,t.refresh_token),this.storage.set(y.USER,JSON.stringify(n)),this.log.info("handleLoginSuccess:session-saved",{sub:n.sub,expiresAt:o,hasRefreshToken:Boolean(t.refresh_token)}),{user:n,accessToken:t.access_token}}async getAccessToken(){var e;const t=this.storage.get(y.ACCESS_TOKEN),n=Number(null!==(e=this.storage.get(y.EXPIRES_AT))&&void 0!==e?e:"0");if(!t)return null;if(!(n>0&&Math.floor(Date.now()/1e3)>=n))return t;this.log.info("getAccessToken:expired, attempting refresh");const o=this.storage.get(y.REFRESH_TOKEN);if(!o)return this.log.info("getAccessToken:no-refresh-token, clearing session"),this.clearSession(),null;try{const e=await this.refreshToken(o),t=Math.floor(Date.now()/1e3)+e.expires_in;return this.storage.set(y.ACCESS_TOKEN,e.access_token,t),this.storage.set(y.EXPIRES_AT,String(t),t),e.refresh_token&&this.storage.set(y.REFRESH_TOKEN,e.refresh_token),this.log.info("getAccessToken:refreshed",{newExpiresAt:t}),e.access_token}catch(e){return this.log.error("getAccessToken:refresh-failed",e),this.clearSession(),null}}getUser(){const e=this.storage.get(y.USER);if(!e)return null;try{return JSON.parse(e)}catch(e){return null}}isLoggedIn(){var e;if(!this.storage.get(y.ACCESS_TOKEN))return!1;const t=Number(null!==(e=this.storage.get(y.EXPIRES_AT))&&void 0!==e?e:"0");return 0===t||Math.floor(Date.now()/1e3)<t}async logout(){const e=this.storage.get(y.ACCESS_TOKEN);if(e)try{await this.revokeToken(e)}catch(e){this.log.error("logout:revoke-failed",e)}this.clearSession(),this.log.info("logout:done")}getBaseUrl(){return this.config.baseUrl}getClientId(){return this.config.clientId}clearSession(){this.storage.clear(Object.values(y))}requireRedirectUri(){if(this.config.redirectUri)return this.config.redirectUri;if("undefined"!=typeof window)return window.location.origin;throw new t("redirectUri is required — pass it in the TenMSAuth constructor or call from a browser context","missing_redirect_uri")}buildAuthorizeUrl(e,t){const n=new URL(this.config.authorizeUrl);return n.searchParams.set("client_id",this.config.clientId),n.searchParams.set("redirect_uri",this.requireRedirectUri()),n.searchParams.set("response_type","code"),n.searchParams.set("scope",this.config.scopes.join(" ")),n.searchParams.set("state",e),n.searchParams.set("code_challenge",t),n.searchParams.set("code_challenge_method","S256"),n.toString()}}function E(e,n,o){const i=e.trim();if(!i)throw new t(`${n} must not be empty`,o);const r=i.replace(/\/+$/,"");try{new URL(r)}catch(e){throw new t(`${n} is not a valid URL: "${r}"`,o)}return r}function x(e){return`tenms_auth_${e}`}function C(){sessionStorage.removeItem(x("state")),sessionStorage.removeItem(x("code_verifier"))}async function U(e){try{const t=await e.text();return t?JSON.parse(t):{}}catch(e){return{}}}function T(e,t){var n,o,i;return null!==(i=null!==(o=null!==(n=e.error_description)&&void 0!==n?n:e.message)&&void 0!==o?o:e.error)&&void 0!==i?i:t}function I(e){if(!e||"object"!=typeof e||"string"!=typeof e.access_token||!e.access_token)throw new t("Server returned an invalid token response (missing access_token)","invalid_token_response");return e}!function(e,t){void 0===t&&(t={});var n=t.insertAt;if("undefined"!=typeof document){var o=document.head||document.getElementsByTagName("head")[0],i=document.createElement("style");i.type="text/css","top"===n&&o.firstChild?o.insertBefore(i,o.firstChild):o.appendChild(i),i.styleSheet?i.styleSheet.cssText=e:i.appendChild(document.createTextNode(e))}}(".tenms-login-btn{-webkit-font-smoothing:antialiased;align-items:center;border:1px solid transparent;border-radius:6px;cursor:pointer;display:inline-flex;font-family:-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica Neue,Arial,sans-serif;font-size:14px;font-weight:500;gap:6px;height:36px;justify-content:center;line-height:1;padding:0 12px;text-decoration:none;transition:background .15s ease,border-color .15s ease,color .15s ease,opacity .15s ease;user-select:none;-webkit-user-select:none;white-space:nowrap;width:fit-content}.tenms-login-btn:focus-visible{outline:2px solid #0070f3;outline-offset:2px}.tenms-login-btn:disabled{cursor:not-allowed}.tenms-login-btn--dark.tenms-login-btn--fill{background:#000;border-color:#000;color:#fff}.tenms-login-btn--dark.tenms-login-btn--fill:hover:not(:disabled){background:#333;border-color:#333}.tenms-login-btn--dark.tenms-login-btn--outline{background:transparent;border-color:#000;color:#000}.tenms-login-btn--dark.tenms-login-btn--outline:hover:not(:disabled){background:#f5f5f5}.tenms-login-btn--light.tenms-login-btn--fill{background:#fff;border-color:#e5e7eb;color:#111}.tenms-login-btn--light.tenms-login-btn--fill:hover:not(:disabled){background:#f5f5f5}.tenms-login-btn--light.tenms-login-btn--outline{background:transparent;border-color:#e5e7eb;color:#111}.tenms-login-btn--light.tenms-login-btn--outline:hover:not(:disabled){background:#f5f5f5;border-color:#d1d5db}.tenms-login-btn--small{font-size:13px;gap:5px;height:32px;padding:0 10px}.tenms-login-btn--medium{font-size:14px;height:36px;padding:0 12px}.tenms-login-btn--large{font-size:14px;height:40px;padding:0 14px}.tenms-login-btn__logo{align-items:center;display:inline-flex;flex-shrink:0}.tenms-login-btn__logo svg{display:block;height:18px;width:18px}.tenms-login-btn--loading{opacity:.6;pointer-events:none}.tenms-login-btn__spinner{animation:tenms-spin .6s linear infinite;border:1.5px solid;border-radius:50%;border-top:1.5px solid transparent;height:14px;width:14px}@keyframes tenms-spin{to{transform:rotate(1turn)}}");function R(e){return"light"===e?'<svg width="20" height="20" viewBox="0 0 32 32" fill="none" xmlns="http://www.w3.org/2000/svg" aria-hidden="true" focusable="false">\n <path d="M21.9012 17.9947L28.8098 11.085C28.0544 7.39598 25.1207 4.50016 21.4039 4.03514C21.3338 4.02624 21.2626 4.01845 21.1925 4.01178V7.43714C22.8023 7.7097 24.1373 8.751 24.916 10.1839L19.5049 15.5939L21.9012 17.9947Z" fill="#EB2026"/>\n <path d="M9.47025 27.9927H6.0727V7.40489H3V4.00734H9.47025V27.9927Z" fill="#111827"/>\n <path d="M25.5835 16.7187L25.569 18.9771V18.9882C25.569 22.0776 23.2172 24.5907 20.3269 24.5907C17.4367 24.5907 15.0871 22.0798 15.0849 18.9938L15.126 12.9807V12.9696C15.126 10.224 16.9906 7.88999 19.4992 7.44388V4.01518L19.2767 4.04076C14.9703 4.60591 11.7263 8.44178 11.7229 12.9641L11.684 18.9771V18.9882C11.684 23.951 15.5599 27.9883 20.3236 27.9883C25.0873 27.9883 28.9599 23.9544 28.9621 18.9938L28.9999 13.2989L25.5835 16.7187Z" fill="#111827"/>\n</svg>':'<svg width="20" height="20" viewBox="0 0 32 32" fill="none" xmlns="http://www.w3.org/2000/svg" aria-hidden="true" focusable="false">\n <path d="M21.9012 17.9947L28.8098 11.085C28.0544 7.39598 25.1207 4.50016 21.4039 4.03514C21.3338 4.02624 21.2626 4.01845 21.1925 4.01178V7.43714C22.8023 7.7097 24.1373 8.751 24.916 10.1839L19.5049 15.5939L21.9012 17.9947Z" fill="#EB2026"/>\n <path d="M9.47025 27.9927H6.0727V7.40489H3V4.00734H9.47025V27.9927Z" fill="#F9FAFB"/>\n <path d="M25.5835 16.7187L25.569 18.9771V18.9882C25.569 22.0776 23.2172 24.5907 20.3269 24.5907C17.4367 24.5907 15.0871 22.0798 15.0849 18.9938L15.126 12.9807V12.9696C15.126 10.224 16.9906 7.88999 19.4992 7.44388V4.01518L19.2767 4.04076C14.9703 4.60591 11.7263 8.44178 11.7229 12.9641L11.684 18.9771V18.9882C11.684 23.951 15.5599 27.9883 20.3236 27.9883C25.0873 27.9883 28.9599 23.9544 28.9621 18.9938L28.9999 13.2989L25.5835 16.7187Z" fill="#F9FAFB"/>\n</svg>'}function $(e="dark"){return`<span class="tenms-login-btn__logo">${R(e)}</span>`}var A;const L="Login with 10MinuteSchool",P=null!==(A=globalThis.HTMLElement)&&void 0!==A?A:class{};class z extends P{constructor(){super(...arguments),this.auth=null,this.loading=!1}static get observedAttributes(){return["client-id","redirect-uri","scope","theme","variant","size","text"]}connectedCallback(){this.render()}attributeChangedCallback(){this.loading||this.render()}render(){var e;const t=j(this.getAttribute("theme")),n=B(this.getAttribute("variant")),o=W(this.getAttribute("size")),i=(null===(e=this.getAttribute("text"))||void 0===e?void 0:e.trim())||L;var r;this.innerHTML=`\n <button class="${O((r={loading:this.loading,text:i,theme:t,variant:n,size:o}).theme,r.variant,r.size,r.loading)}" type="button" ${r.loading?'disabled aria-busy="true"':""}>\n ${r.loading?'<span class="tenms-login-btn__spinner" aria-hidden="true"></span>':$(r.theme)}\n <span class="tenms-login-btn__label">${q(r.text)}</span>\n </button>\n `;const s=this.querySelector("button");s&&s.addEventListener("click",()=>{this.handleClick()})}async handleClick(){if(this.loading)return;const e=this.getConfig();if(e.clientId&&e.redirectUri){this.auth||(this.auth=new S(e)),this.loading=!0,this.render();try{const e=await this.auth.loginWithPopup();this.dispatchEvent(new CustomEvent("tenms-success",{detail:e,bubbles:!0,composed:!0}))}catch(e){this.dispatchError(F(e))}finally{this.loading=!1,this.render()}}else this.dispatchError(new t("client-id and redirect-uri attributes are required","invalid_login_button_config"))}getConfig(){const e=this.getAttribute("scope")||"profile";return{clientId:this.getAttribute("client-id")||"",redirectUri:this.getAttribute("redirect-uri")||"",scopes:e.split(" ").map(e=>e.trim()).filter(Boolean)}}dispatchError(e){this.dispatchEvent(new CustomEvent("tenms-error",{detail:e,bubbles:!0,composed:!0}))}}function N(){"undefined"==typeof window||"undefined"==typeof customElements||customElements.get("tenms-login-button")||customElements.define("tenms-login-button",z)}function M(e,n){var o;const i="string"==typeof e?document.querySelector(e):e;if(!i)throw new t(`Container element not found: ${e}`,"container_not_found");const r=new S({clientId:n.clientId,redirectUri:n.redirectUri,scopes:n.scopes}),s=j(n.theme),a=B(n.variant),c=W(n.size),l=(null===(o=n.text)||void 0===o?void 0:o.trim())||L,d=document.createElement("button");V(d,{loading:!1,size:c,text:l,theme:s,variant:a}),d.addEventListener("click",async()=>{var e,t;if(!d.classList.contains("tenms-login-btn--loading")){V(d,{loading:!0,size:c,text:l,theme:s,variant:a});try{const t=await r.loginWithPopup();null===(e=n.onSuccess)||void 0===e||e.call(n,t)}catch(e){null===(t=n.onError)||void 0===t||t.call(n,F(e))}finally{V(d,{loading:!1,size:c,text:l,theme:s,variant:a})}}}),i.replaceChildren(d)}function V(e,t){e.className=O(t.theme,t.variant,t.size,t.loading),e.type="button",e.disabled=t.loading,e.setAttribute("aria-busy",String(t.loading)),e.innerHTML=t.loading?`<span class="tenms-login-btn__spinner" aria-hidden="true"></span><span class="tenms-login-btn__label">${q(t.text)}</span>`:`${$(t.theme)}<span class="tenms-login-btn__label">${q(t.text)}</span>`}function O(e,t,n,o){return["tenms-login-btn",`tenms-login-btn--${e}`,`tenms-login-btn--${t}`,`tenms-login-btn--${n}`,o?"tenms-login-btn--loading":""].filter(Boolean).join(" ")}function j(e){return"light"===e?e:"dark"}function B(e){return"outline"===e?e:"fill"}function W(e){return"small"===e||"medium"===e?e:"large"}function q(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;")}function F(e){return e instanceof Error?e:new Error(String(e))}const H="Login with 10MinuteSchool",K="dark",D="fill",J="large";function X(t){const{clientId:n,redirectUri:o,scopes:i,theme:r=K,variant:s=D,size:a=J,text:c=H,onSuccess:l,onError:d,className:h=""}=t,[u,g]=e.useState(!1),f=e.useRef(l),p=e.useRef(d);e.useEffect(()=>{f.current=l},[l]),e.useEffect(()=>{p.current=d},[d]);const m=Array.isArray(i)?i.join("\0"):"",w=e.useMemo(()=>new S({clientId:n,redirectUri:o,scopes:i}),[n,o,m]),b=e.useCallback(async()=>{var e,t;g(!0);try{const t=await w.loginWithPopup();null===(e=f.current)||void 0===e||e.call(f,t)}catch(e){null===(t=p.current)||void 0===t||t.call(p,function(e){return e instanceof Error?e:new Error(String(e))}(e))}finally{g(!1)}},[w]),_=["tenms-login-btn",`tenms-login-btn--${Z(r)}`,`tenms-login-btn--${v=s,"outline"===v?v:D}`,`tenms-login-btn--${Y(a)}`,u?"tenms-login-btn--loading":"",h].filter(Boolean).join(" ");var v;return e.createElement("button",{className:_,type:"button",onClick:()=>{b()},disabled:u,"aria-busy":u},u?e.createElement("span",{className:"tenms-login-btn__spinner","aria-hidden":"true"}):e.createElement("span",{className:"tenms-login-btn__logo",dangerouslySetInnerHTML:{__html:R(Z(r))}}),e.createElement("span",{className:"tenms-login-btn__label"},c))}function Z(e){return"light"===e?e:K}function Y(e){return"small"===e||"medium"===e?e:J}const G="0.4.0";N();export{X as LoginButton,S as TenMSAuth,t as TenMSAuthError,z as TenMSLoginButtonElement,G as VERSION,g as createLogger,i as generateCodeChallenge,o as generateCodeVerifier,r as generateState,a as openPopup,N as registerLoginButton,M as renderLoginButton,m as truncate,c as waitForPopupRedirect};
2
2
  //# sourceMappingURL=tenms-auth.esm.js.map
@@ -1,2 +1,2 @@
1
- !function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports,require("react")):"function"==typeof define&&define.amd?define(["exports","react"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).TenMSAuth={},e.React)}(this,function(e,t){"use strict";function n(e){var t=Object.create(null);return e&&Object.keys(e).forEach(function(n){if("default"!==n){var o=Object.getOwnPropertyDescriptor(e,n);Object.defineProperty(t,n,o.get?o:{enumerable:!0,get:function(){return e[n]}})}}),t.default=e,Object.freeze(t)}var o=n(t);class i extends Error{constructor(e,t){super(e),this.name="TenMSAuthError",this.code=t,Object.setPrototypeOf(this,new.target.prototype)}}const r="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~";function s(e=64){l(e,43,128,"code_verifier length");const t=[];for(;t.length<e;){const n=new Uint8Array(e+16);crypto.getRandomValues(n);for(const o of n){if(t.length>=e)break;o<198&&t.push(r[o%66])}}return t.join("")}async function a(e){if(!e)throw new Error("codeVerifier is required to generate a code challenge");const t=(new TextEncoder).encode(e);return function(e){const t=new Uint8Array(e);let n="";for(const e of t)n+=String.fromCharCode(e);return btoa(n).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}(await crypto.subtle.digest("SHA-256",t))}function c(e=32){l(e,1,1024,"state byte length");const t=new Uint8Array(e);return crypto.getRandomValues(t),Array.from(t,e=>e.toString(16).padStart(2,"0")).join("")}function l(e,t,n,o){if(!Number.isInteger(e)||e<t||e>n)throw new RangeError(`${o} must be an integer between ${t} and ${n}`)}function d(e){u(e.width,"popup width"),u(e.height,"popup height");const t="number"==typeof window.screenX?window.screenX:window.screenLeft,n="number"==typeof window.screenY?window.screenY:window.screenTop,o=Math.round(t+Math.max(0,(window.innerWidth-e.width)/2)),i=Math.round(n+Math.max(0,(window.innerHeight-e.height)/2)),r=[`width=${e.width}`,`height=${e.height}`,`left=${o}`,`top=${i}`,"toolbar=no","menubar=no","scrollbars=yes","resizable=yes","status=no"].join(",");return window.open(e.url,"tenms_auth_popup",r)}function h(e,t,n,o=3e5){if(!t)throw new Error("redirectUri is required to monitor popup redirects");if(!n)throw new Error("expectedState is required to validate the popup callback");let r;u(o,"popup timeout");try{r=new URL(t)}catch(e){throw new i(`redirectUri is not a valid URL: "${t}"`,"invalid_redirect_uri")}return new Promise((t,s)=>{const a=Date.now(),c=window.setInterval(()=>{try{if(!e||e.closed)return window.clearInterval(c),void s(new i("Login popup was closed","popup_closed"));if(Date.now()-a>o)return window.clearInterval(c),e.close(),void s(new i("Login timed out while waiting for the redirect URI","popup_timeout"));const l=e.location.href;if(!l)return;let d;try{d=new URL(l)}catch(e){return}if(d.origin!==r.origin||d.pathname!==r.pathname)return;window.clearInterval(c),e.close();const h=d.searchParams.get("code"),u=d.searchParams.get("state"),g=d.searchParams.get("error"),f=d.searchParams.get("error_description");if(g)return void s(new i(f||g,"oauth_error"));if(!h)return void s(new i("No authorization code was returned to the redirect URI","missing_authorization_code"));if(u!==n)return void s(new i("State mismatch — possible CSRF attack","state_mismatch"));t({code:h,state:u})}catch(e){e instanceof DOMException||(window.clearInterval(c),s(e instanceof Error?e:new Error(String(e))))}},500)})}function u(e,t){if(!Number.isInteger(e)||e<=0)throw new RangeError(`${t} must be a positive integer`)}const g="[TenMSAuth]",f="color:#22c55e;font-weight:700",p="color:inherit;font-weight:normal";function m(e){return e?b:w}const w={info:()=>{},warn:()=>{},error:()=>{}},b={info(e,t){t&&Object.keys(t).length>0?(console.groupCollapsed(`%c${g}%c ${e}`,f,p),console.table(t),console.groupEnd()):console.log(`%c${g}%c ${e}`,f,p)},warn(e,t){console.warn(`%c${g}%c ⚠ ${e}`,f,p,null!=t?t:"")},error(e,t){console.error(`%c${g}%c ✕ ${e}`,f,p,null!=t?t:"")}};function _(e){return e?e.length>8?`${e.slice(0,8)}…`:e:"(empty)"}class v{get(e){const t=document.cookie.match(new RegExp("(?:^|; )"+e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")+"=([^;]*)"));return t?decodeURIComponent(t[1]):null}set(e,t,n){let o=`${e}=${encodeURIComponent(t)}; path=/; SameSite=Lax`;n&&(o+=`; expires=${new Date(1e3*n).toUTCString()}`),document.cookie=o}remove(e){document.cookie=`${e}=; path=/; expires=Thu, 01 Jan 1970 00:00:00 GMT; SameSite=Lax`}clear(e){e.forEach(e=>this.remove(e))}}class k{get(e){return localStorage.getItem(e)}set(e,t){localStorage.setItem(e,t)}remove(e){localStorage.removeItem(e)}clear(e){e.forEach(e=>this.remove(e))}}const y="https://api.10minuteschool.net/auth",S="https://10minuteschool.net/auth/login",E=["profile"],x={ACCESS_TOKEN:"_tenms_access_token",REFRESH_TOKEN:"_tenms_refresh_token",EXPIRES_AT:"_tenms_expires_at",USER:"_tenms_user"};class C{constructor(e){var t,n;this.config=function(e){var t,n;const o=null===(t=e.clientId)||void 0===t?void 0:t.trim();if(!o)throw new i("clientId is required","missing_client_id");const r=(null===(n=e.redirectUri)||void 0===n?void 0:n.trim())||void 0,s=T(y,"baseUrl","invalid_base_url"),a=T(S,"authorizeUrl","invalid_authorize_url"),c=function(e){if(!Array.isArray(e)||0===e.length)return E;const t=e.map(e=>e.trim()).filter(Boolean);return t.length>0?t:E}(e.scopes);return{clientId:o,redirectUri:r,scopes:c,baseUrl:s,authorizeUrl:a}}(e),this.log=m(!0===e.debug),this.storage="localStorage"===(null!==(t=e.storage)&&void 0!==t?t:"cookie")?new k:new v,this.log.info("init",{clientId:this.config.clientId,redirectUri:this.config.redirectUri,baseUrl:this.config.baseUrl,authorizeUrl:this.config.authorizeUrl,scopes:this.config.scopes.join(" "),storage:null!==(n=e.storage)&&void 0!==n?n:"cookie",debug:!0===e.debug})}async loginWithPopup(e={}){var t,n;const o=null!==(t=e.width)&&void 0!==t?t:500,r=null!==(n=e.height)&&void 0!==n?n:600;this.log.info("loginWithPopup:start",{width:o,height:r});const l=c(),u=s();this.log.info("loginWithPopup:pkce-generated",{state:_(l),codeVerifier:_(u)});const g=d({url:"about:blank",width:o,height:r});if(!g){const e=new i("Failed to open login popup. Please allow popups for this site.","popup_blocked");throw this.log.error("loginWithPopup:popup-blocked",e),e}if(g===window){const e=new i("The browser reused the current tab instead of opening a popup window.","popup_reused_opener");throw this.log.error("loginWithPopup:popup-reused-opener",e),e}this.log.info("loginWithPopup:popup-opened"),function(e){try{e.document.title="Signing in…",e.document.body.style.cssText="font-family:system-ui,sans-serif;padding:2rem;text-align:center",e.document.body.textContent="Signing in…"}catch(e){}}(g);try{const e=await a(u),t=this.buildAuthorizeUrl(l,e);this.log.info("loginWithPopup:navigating",{authorizeUrl:t,codeChallenge:_(e)}),g.location.href=t;const n=await h(g,this.requireRedirectUri(),l);return this.log.info("loginWithPopup:success",{code:_(n.code),state:_(n.state)}),{code:n.code,state:n.state,codeVerifier:u}}catch(e){throw g.closed||g.close(),this.log.error("loginWithPopup:error",e),e}}async loginWithRedirect(){this.log.info("loginWithRedirect:start");const e=c(),t=s(),n=await a(t);this.log.info("loginWithRedirect:pkce-generated",{state:_(e),codeVerifier:_(t),codeChallenge:_(n)}),function(e,t){sessionStorage.setItem(U("state"),e),sessionStorage.setItem(U("code_verifier"),t)}(e,t),this.log.info("loginWithRedirect:session-persisted",{storageKeys:[U("state"),U("code_verifier")]});const o=this.buildAuthorizeUrl(e,n);this.log.info("loginWithRedirect:navigating",{authorizeUrl:o}),window.location.href=o}handleRedirectCallback(){const e=new URLSearchParams(window.location.search),t=e.get("code"),n=e.get("state"),o=e.get("error"),r=e.get("error_description");if(!t&&!n&&!o)return this.log.info("handleRedirectCallback:not-a-callback"),null;this.log.info("handleRedirectCallback:callback-detected",{hasCode:Boolean(t),hasState:Boolean(n),error:null!=o?o:"(none)",errorDescription:null!=r?r:"(none)"});const s=sessionStorage.getItem(U("state")),a=sessionStorage.getItem(U("code_verifier"));if(!n||!s||n!==s){R();const e=new i("State mismatch — possible CSRF attack","state_mismatch");throw this.log.warn("handleRedirectCallback:state-mismatch",{receivedState:n?_(n):"(missing)",storedStatePresent:Boolean(s)}),e}if(R(),function(){const e=window.location.origin+window.location.pathname;window.history.replaceState({},document.title,e)}(),o)throw this.log.error("handleRedirectCallback:oauth-error",{error:o,errorDescription:r}),new i(r||o,o);if(!t){const e=new i("No authorization code was returned to the redirect URI","missing_authorization_code");throw this.log.error("handleRedirectCallback:missing-code",e),e}if(!a){const e=new i("No PKCE code verifier was found for the redirect callback","missing_code_verifier");throw this.log.error("handleRedirectCallback:missing-verifier",e),e}return this.log.info("handleRedirectCallback:success",{code:_(t),state:_(n)}),{code:t,state:n,codeVerifier:a}}async exchangeCode(e,t){if(!e||e.length>2048)throw new i("code is required and must be under 2048 characters","invalid_authorization_code");if(!t||t.length<43||t.length>128)throw new i("codeVerifier must be 43–128 characters (RFC 7636)","invalid_code_verifier");const n=`${this.config.baseUrl}/v1/oauth/token`;this.log.info("exchangeCode:start",{endpoint:n,code:_(e),codeVerifier:_(t),clientId:this.config.clientId,redirectUri:this.config.redirectUri});const o=await fetch(n,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({grant_type:"authorization_code",code:e,redirect_uri:this.requireRedirectUri(),client_id:this.config.clientId,code_verifier:t})});if(!o.ok){const e=await I(o),t=new i(A(e,"Token exchange failed"),"token_exchange_failed");throw this.log.error("exchangeCode:error",{status:o.status,message:t.message}),t}const r=$(await o.json());return this.log.info("exchangeCode:success",{token_type:r.token_type,expires_in:r.expires_in,scope:r.scope,access_token:_(r.access_token),has_refresh_token:Boolean(r.refresh_token)}),r}async refreshToken(e){if(!e)throw new i("refreshToken is required","missing_refresh_token");const t=`${this.config.baseUrl}/v1/oauth/token`;this.log.info("refreshToken:start",{endpoint:t,refreshToken:_(e),clientId:this.config.clientId});const n=await fetch(t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({grant_type:"refresh_token",refresh_token:e,client_id:this.config.clientId})});if(!n.ok){const e=await I(n),t=new i(A(e,"Token refresh failed"),"token_refresh_failed");throw this.log.error("refreshToken:error",{status:n.status,message:t.message}),t}const o=$(await n.json());return this.log.info("refreshToken:success",{token_type:o.token_type,expires_in:o.expires_in,access_token:_(o.access_token)}),o}async getUserInfo(e){var t,n;if(!e)throw new i("accessToken is required to fetch user info","missing_access_token");const o=`${this.config.baseUrl}/v1/oauth/userinfo`;this.log.info("getUserInfo:start",{endpoint:o,accessToken:_(e)});const r=await fetch(o,{headers:{Authorization:`Bearer ${e}`}});if(!r.ok){const e=await I(r),t=new i(A(e,"Failed to fetch user info"),"userinfo_failed");throw this.log.error("getUserInfo:error",{status:r.status,message:t.message}),t}const s=function(e){if(!e||"object"!=typeof e||"string"!=typeof e.sub||!e.sub)throw new i("Server returned an invalid userinfo response (missing sub)","invalid_userinfo_response");return e}(await r.json());return this.log.info("getUserInfo:success",{sub:s.sub,name:null!==(t=s.name)&&void 0!==t?t:"(not returned)",email:null!==(n=s.email)&&void 0!==n?n:"(not returned)"}),s}async revokeToken(e){if(!e)throw new i("token is required to revoke an OAuth token","missing_token");const t=`${this.config.baseUrl}/v1/oauth/revoke`;this.log.info("revokeToken:start",{endpoint:t,token:_(e),clientId:this.config.clientId});const n=await fetch(t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({token:e,client_id:this.config.clientId})});if(!n.ok){const e=await I(n),t=new i(A(e,"Failed to revoke token"),"revoke_failed");throw this.log.error("revokeToken:error",{status:n.status,message:t.message}),t}this.log.info("revokeToken:success")}async handleLoginSuccess(e){this.log.info("handleLoginSuccess:start",{code:_(e.code)});const t=await this.exchangeCode(e.code,e.codeVerifier),n=await this.getUserInfo(t.access_token),o=Math.floor(Date.now()/1e3)+t.expires_in;return this.storage.set(x.ACCESS_TOKEN,t.access_token,o),this.storage.set(x.EXPIRES_AT,String(o),o),t.refresh_token&&this.storage.set(x.REFRESH_TOKEN,t.refresh_token),this.storage.set(x.USER,JSON.stringify(n)),this.log.info("handleLoginSuccess:session-saved",{sub:n.sub,expiresAt:o,hasRefreshToken:Boolean(t.refresh_token)}),{user:n,accessToken:t.access_token}}async getAccessToken(){var e;const t=this.storage.get(x.ACCESS_TOKEN),n=Number(null!==(e=this.storage.get(x.EXPIRES_AT))&&void 0!==e?e:"0");if(!t)return null;if(!(n>0&&Math.floor(Date.now()/1e3)>=n))return t;this.log.info("getAccessToken:expired, attempting refresh");const o=this.storage.get(x.REFRESH_TOKEN);if(!o)return this.log.info("getAccessToken:no-refresh-token, clearing session"),this.clearSession(),null;try{const e=await this.refreshToken(o),t=Math.floor(Date.now()/1e3)+e.expires_in;return this.storage.set(x.ACCESS_TOKEN,e.access_token,t),this.storage.set(x.EXPIRES_AT,String(t),t),e.refresh_token&&this.storage.set(x.REFRESH_TOKEN,e.refresh_token),this.log.info("getAccessToken:refreshed",{newExpiresAt:t}),e.access_token}catch(e){return this.log.error("getAccessToken:refresh-failed",e),this.clearSession(),null}}getUser(){const e=this.storage.get(x.USER);if(!e)return null;try{return JSON.parse(e)}catch(e){return null}}isLoggedIn(){var e;if(!this.storage.get(x.ACCESS_TOKEN))return!1;const t=Number(null!==(e=this.storage.get(x.EXPIRES_AT))&&void 0!==e?e:"0");return 0===t||Math.floor(Date.now()/1e3)<t}async logout(){const e=this.storage.get(x.ACCESS_TOKEN);if(e)try{await this.revokeToken(e)}catch(e){this.log.error("logout:revoke-failed",e)}this.clearSession(),this.log.info("logout:done")}getBaseUrl(){return this.config.baseUrl}getClientId(){return this.config.clientId}clearSession(){this.storage.clear(Object.values(x))}requireRedirectUri(){if(this.config.redirectUri)return this.config.redirectUri;if("undefined"!=typeof window)return window.location.origin;throw new i("redirectUri is required — pass it in the TenMSAuth constructor or call from a browser context","missing_redirect_uri")}buildAuthorizeUrl(e,t){const n=new URL(this.config.authorizeUrl);return n.searchParams.set("client_id",this.config.clientId),n.searchParams.set("redirect_uri",this.requireRedirectUri()),n.searchParams.set("response_type","code"),n.searchParams.set("scope",this.config.scopes.join(" ")),n.searchParams.set("state",e),n.searchParams.set("code_challenge",t),n.searchParams.set("code_challenge_method","S256"),n.toString()}}function T(e,t,n){const o=e.trim();if(!o)throw new i(`${t} must not be empty`,n);const r=o.replace(/\/+$/,"");try{new URL(r)}catch(e){throw new i(`${t} is not a valid URL: "${r}"`,n)}return r}function U(e){return`tenms_auth_${e}`}function R(){sessionStorage.removeItem(U("state")),sessionStorage.removeItem(U("code_verifier"))}async function I(e){try{const t=await e.text();return t?JSON.parse(t):{}}catch(e){return{}}}function A(e,t){var n,o,i;return null!==(i=null!==(o=null!==(n=e.error_description)&&void 0!==n?n:e.message)&&void 0!==o?o:e.error)&&void 0!==i?i:t}function $(e){if(!e||"object"!=typeof e||"string"!=typeof e.access_token||!e.access_token)throw new i("Server returned an invalid token response (missing access_token)","invalid_token_response");return e}!function(e,t){void 0===t&&(t={});var n=t.insertAt;if("undefined"!=typeof document){var o=document.head||document.getElementsByTagName("head")[0],i=document.createElement("style");i.type="text/css","top"===n&&o.firstChild?o.insertBefore(i,o.firstChild):o.appendChild(i),i.styleSheet?i.styleSheet.cssText=e:i.appendChild(document.createTextNode(e))}}(".tenms-login-btn{-webkit-font-smoothing:antialiased;align-items:center;border:1px solid transparent;border-radius:6px;cursor:pointer;display:inline-flex;font-family:-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica Neue,Arial,sans-serif;font-size:14px;font-weight:500;gap:6px;height:36px;justify-content:center;line-height:1;padding:0 12px;text-decoration:none;transition:background .15s ease,border-color .15s ease,color .15s ease,opacity .15s ease;user-select:none;-webkit-user-select:none;white-space:nowrap;width:fit-content}.tenms-login-btn:focus-visible{outline:2px solid #0070f3;outline-offset:2px}.tenms-login-btn:disabled{cursor:not-allowed}.tenms-login-btn--dark.tenms-login-btn--fill{background:#000;border-color:#000;color:#fff}.tenms-login-btn--dark.tenms-login-btn--fill:hover:not(:disabled){background:#333;border-color:#333}.tenms-login-btn--dark.tenms-login-btn--outline{background:transparent;border-color:#000;color:#000}.tenms-login-btn--dark.tenms-login-btn--outline:hover:not(:disabled){background:#f5f5f5}.tenms-login-btn--light.tenms-login-btn--fill{background:#fff;border-color:#e5e7eb;color:#111}.tenms-login-btn--light.tenms-login-btn--fill:hover:not(:disabled){background:#f5f5f5}.tenms-login-btn--light.tenms-login-btn--outline{background:transparent;border-color:#e5e7eb;color:#111}.tenms-login-btn--light.tenms-login-btn--outline:hover:not(:disabled){background:#f5f5f5;border-color:#d1d5db}.tenms-login-btn--small{font-size:13px;gap:5px;height:32px;padding:0 10px}.tenms-login-btn--medium{font-size:14px;height:36px;padding:0 12px}.tenms-login-btn--large{font-size:14px;height:40px;padding:0 14px}.tenms-login-btn__logo{align-items:center;display:inline-flex;flex-shrink:0}.tenms-login-btn__logo svg{display:block;height:18px;width:18px}.tenms-login-btn--loading{opacity:.6;pointer-events:none}.tenms-login-btn__spinner{animation:tenms-spin .6s linear infinite;border:1.5px solid;border-radius:50%;border-top:1.5px solid transparent;height:14px;width:14px}@keyframes tenms-spin{to{transform:rotate(1turn)}}");function L(e){return"light"===e?'<svg width="20" height="20" viewBox="0 0 32 32" fill="none" xmlns="http://www.w3.org/2000/svg" aria-hidden="true" focusable="false">\n <path d="M21.9012 17.9947L28.8098 11.085C28.0544 7.39598 25.1207 4.50016 21.4039 4.03514C21.3338 4.02624 21.2626 4.01845 21.1925 4.01178V7.43714C22.8023 7.7097 24.1373 8.751 24.916 10.1839L19.5049 15.5939L21.9012 17.9947Z" fill="#EB2026"/>\n <path d="M9.47025 27.9927H6.0727V7.40489H3V4.00734H9.47025V27.9927Z" fill="#111827"/>\n <path d="M25.5835 16.7187L25.569 18.9771V18.9882C25.569 22.0776 23.2172 24.5907 20.3269 24.5907C17.4367 24.5907 15.0871 22.0798 15.0849 18.9938L15.126 12.9807V12.9696C15.126 10.224 16.9906 7.88999 19.4992 7.44388V4.01518L19.2767 4.04076C14.9703 4.60591 11.7263 8.44178 11.7229 12.9641L11.684 18.9771V18.9882C11.684 23.951 15.5599 27.9883 20.3236 27.9883C25.0873 27.9883 28.9599 23.9544 28.9621 18.9938L28.9999 13.2989L25.5835 16.7187Z" fill="#111827"/>\n</svg>':'<svg width="20" height="20" viewBox="0 0 32 32" fill="none" xmlns="http://www.w3.org/2000/svg" aria-hidden="true" focusable="false">\n <path d="M21.9012 17.9947L28.8098 11.085C28.0544 7.39598 25.1207 4.50016 21.4039 4.03514C21.3338 4.02624 21.2626 4.01845 21.1925 4.01178V7.43714C22.8023 7.7097 24.1373 8.751 24.916 10.1839L19.5049 15.5939L21.9012 17.9947Z" fill="#EB2026"/>\n <path d="M9.47025 27.9927H6.0727V7.40489H3V4.00734H9.47025V27.9927Z" fill="#F9FAFB"/>\n <path d="M25.5835 16.7187L25.569 18.9771V18.9882C25.569 22.0776 23.2172 24.5907 20.3269 24.5907C17.4367 24.5907 15.0871 22.0798 15.0849 18.9938L15.126 12.9807V12.9696C15.126 10.224 16.9906 7.88999 19.4992 7.44388V4.01518L19.2767 4.04076C14.9703 4.60591 11.7263 8.44178 11.7229 12.9641L11.684 18.9771V18.9882C11.684 23.951 15.5599 27.9883 20.3236 27.9883C25.0873 27.9883 28.9599 23.9544 28.9621 18.9938L28.9999 13.2989L25.5835 16.7187Z" fill="#F9FAFB"/>\n</svg>'}function P(e="dark"){return`<span class="tenms-login-btn__logo">${L(e)}</span>`}var z;const N="Login with 10MinuteSchool",O=null!==(z=globalThis.HTMLElement)&&void 0!==z?z:class{};class M extends O{constructor(){super(...arguments),this.auth=null,this.loading=!1}static get observedAttributes(){return["client-id","redirect-uri","scope","theme","variant","size","text"]}connectedCallback(){this.render()}attributeChangedCallback(){this.loading||this.render()}render(){var e;const t=q(this.getAttribute("theme")),n=F(this.getAttribute("variant")),o=W(this.getAttribute("size")),i=(null===(e=this.getAttribute("text"))||void 0===e?void 0:e.trim())||N;var r;this.innerHTML=`\n <button class="${B((r={loading:this.loading,text:i,theme:t,variant:n,size:o}).theme,r.variant,r.size,r.loading)}" type="button" ${r.loading?'disabled aria-busy="true"':""}>\n ${r.loading?'<span class="tenms-login-btn__spinner" aria-hidden="true"></span>':P(r.theme)}\n <span class="tenms-login-btn__label">${H(r.text)}</span>\n </button>\n `;const s=this.querySelector("button");s&&s.addEventListener("click",()=>{this.handleClick()})}async handleClick(){if(this.loading)return;const e=this.getConfig();if(e.clientId&&e.redirectUri){this.auth||(this.auth=new C(e)),this.loading=!0,this.render();try{const e=await this.auth.loginWithPopup();this.dispatchEvent(new CustomEvent("tenms-success",{detail:e,bubbles:!0,composed:!0}))}catch(e){this.dispatchError(K(e))}finally{this.loading=!1,this.render()}}else this.dispatchError(new i("client-id and redirect-uri attributes are required","invalid_login_button_config"))}getConfig(){const e=this.getAttribute("scope")||"profile";return{clientId:this.getAttribute("client-id")||"",redirectUri:this.getAttribute("redirect-uri")||"",scopes:e.split(" ").map(e=>e.trim()).filter(Boolean)}}dispatchError(e){this.dispatchEvent(new CustomEvent("tenms-error",{detail:e,bubbles:!0,composed:!0}))}}function V(){"undefined"==typeof window||"undefined"==typeof customElements||customElements.get("tenms-login-button")||customElements.define("tenms-login-button",M)}function j(e,t){e.className=B(t.theme,t.variant,t.size,t.loading),e.type="button",e.disabled=t.loading,e.setAttribute("aria-busy",String(t.loading)),e.innerHTML=t.loading?`<span class="tenms-login-btn__spinner" aria-hidden="true"></span><span class="tenms-login-btn__label">${H(t.text)}</span>`:`${P(t.theme)}<span class="tenms-login-btn__label">${H(t.text)}</span>`}function B(e,t,n,o){return["tenms-login-btn",`tenms-login-btn--${e}`,`tenms-login-btn--${t}`,`tenms-login-btn--${n}`,o?"tenms-login-btn--loading":""].filter(Boolean).join(" ")}function q(e){return"light"===e?e:"dark"}function F(e){return"outline"===e?e:"fill"}function W(e){return"small"===e||"medium"===e?e:"large"}function H(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;")}function K(e){return e instanceof Error?e:new Error(String(e))}const D="Login with 10MinuteSchool",J="dark",X="fill",Z="large";function Y(e){return"light"===e?e:J}function G(e){return"small"===e||"medium"===e?e:Z}V(),e.LoginButton=function(e){const{clientId:t,redirectUri:n,scopes:i,theme:r=J,variant:s=X,size:a=Z,text:c=D,onSuccess:l,onError:d,className:h=""}=e,[u,g]=o.useState(!1),f=o.useRef(l),p=o.useRef(d);o.useEffect(()=>{f.current=l},[l]),o.useEffect(()=>{p.current=d},[d]);const m=Array.isArray(i)?i.join("\0"):"",w=o.useMemo(()=>new C({clientId:t,redirectUri:n,scopes:i}),[t,n,m]),b=o.useCallback(async()=>{var e,t;g(!0);try{const t=await w.loginWithPopup();null===(e=f.current)||void 0===e||e.call(f,t)}catch(e){null===(t=p.current)||void 0===t||t.call(p,function(e){return e instanceof Error?e:new Error(String(e))}(e))}finally{g(!1)}},[w]),_=["tenms-login-btn",`tenms-login-btn--${Y(r)}`,`tenms-login-btn--${v=s,"outline"===v?v:X}`,`tenms-login-btn--${G(a)}`,u?"tenms-login-btn--loading":"",h].filter(Boolean).join(" ");var v;return o.createElement("button",{className:_,type:"button",onClick:()=>{b()},disabled:u,"aria-busy":u},u?o.createElement("span",{className:"tenms-login-btn__spinner","aria-hidden":"true"}):o.createElement("span",{className:"tenms-login-btn__logo",dangerouslySetInnerHTML:{__html:L(Y(r))}}),o.createElement("span",{className:"tenms-login-btn__label"},c))},e.TenMSAuth=C,e.TenMSAuthError=i,e.TenMSLoginButtonElement=M,e.VERSION="0.1.0",e.createLogger=m,e.generateCodeChallenge=a,e.generateCodeVerifier=s,e.generateState=c,e.openPopup=d,e.registerLoginButton=V,e.renderLoginButton=function(e,t){var n;const o="string"==typeof e?document.querySelector(e):e;if(!o)throw new i(`Container element not found: ${e}`,"container_not_found");const r=new C({clientId:t.clientId,redirectUri:t.redirectUri,scopes:t.scopes}),s=q(t.theme),a=F(t.variant),c=W(t.size),l=(null===(n=t.text)||void 0===n?void 0:n.trim())||N,d=document.createElement("button");j(d,{loading:!1,size:c,text:l,theme:s,variant:a}),d.addEventListener("click",async()=>{var e,n;if(!d.classList.contains("tenms-login-btn--loading")){j(d,{loading:!0,size:c,text:l,theme:s,variant:a});try{const n=await r.loginWithPopup();null===(e=t.onSuccess)||void 0===e||e.call(t,n)}catch(e){null===(n=t.onError)||void 0===n||n.call(t,K(e))}finally{j(d,{loading:!1,size:c,text:l,theme:s,variant:a})}}}),o.replaceChildren(d)},e.truncate=_,e.waitForPopupRedirect=h});
1
+ !function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports,require("react")):"function"==typeof define&&define.amd?define(["exports","react"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).TenMSAuth={},e.React)}(this,function(e,t){"use strict";function n(e){var t=Object.create(null);return e&&Object.keys(e).forEach(function(n){if("default"!==n){var o=Object.getOwnPropertyDescriptor(e,n);Object.defineProperty(t,n,o.get?o:{enumerable:!0,get:function(){return e[n]}})}}),t.default=e,Object.freeze(t)}var o=n(t);class i extends Error{constructor(e,t){super(e),this.name="TenMSAuthError",this.code=t,Object.setPrototypeOf(this,new.target.prototype)}}const r="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~";function s(e=64){l(e,43,128,"code_verifier length");const t=[];for(;t.length<e;){const n=new Uint8Array(e+16);crypto.getRandomValues(n);for(const o of n){if(t.length>=e)break;o<198&&t.push(r[o%66])}}return t.join("")}async function a(e){if(!e)throw new Error("codeVerifier is required to generate a code challenge");const t=(new TextEncoder).encode(e);return function(e){const t=new Uint8Array(e);let n="";for(const e of t)n+=String.fromCharCode(e);return btoa(n).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}(await crypto.subtle.digest("SHA-256",t))}function c(e=32){l(e,1,1024,"state byte length");const t=new Uint8Array(e);return crypto.getRandomValues(t),Array.from(t,e=>e.toString(16).padStart(2,"0")).join("")}function l(e,t,n,o){if(!Number.isInteger(e)||e<t||e>n)throw new RangeError(`${o} must be an integer between ${t} and ${n}`)}function d(e){u(e.width,"popup width"),u(e.height,"popup height");const t="number"==typeof window.screenX?window.screenX:window.screenLeft,n="number"==typeof window.screenY?window.screenY:window.screenTop,o=Math.round(t+Math.max(0,(window.innerWidth-e.width)/2)),i=Math.round(n+Math.max(0,(window.innerHeight-e.height)/2)),r=[`width=${e.width}`,`height=${e.height}`,`left=${o}`,`top=${i}`,"toolbar=no","menubar=no","scrollbars=yes","resizable=yes","status=no"].join(",");return window.open(e.url,"tenms_auth_popup",r)}function h(e,t,n,o=3e5){if(!t)throw new Error("redirectUri is required to monitor popup redirects");if(!n)throw new Error("expectedState is required to validate the popup callback");let r;u(o,"popup timeout");try{r=new URL(t)}catch(e){throw new i(`redirectUri is not a valid URL: "${t}"`,"invalid_redirect_uri")}return new Promise((t,s)=>{const a=Date.now(),c=window.setInterval(()=>{try{if(!e||e.closed)return window.clearInterval(c),void s(new i("Login popup was closed","popup_closed"));if(Date.now()-a>o)return window.clearInterval(c),e.close(),void s(new i("Login timed out while waiting for the redirect URI","popup_timeout"));const l=e.location.href;if(!l)return;let d;try{d=new URL(l)}catch(e){return}if(d.origin!==r.origin||d.pathname!==r.pathname)return;window.clearInterval(c),e.close();const h=d.searchParams.get("code"),u=d.searchParams.get("state"),g=d.searchParams.get("error"),f=d.searchParams.get("error_description");if(g)return void s(new i(f||g,"oauth_error"));if(!h)return void s(new i("No authorization code was returned to the redirect URI","missing_authorization_code"));if(u!==n)return void s(new i("State mismatch — possible CSRF attack","state_mismatch"));t({code:h,state:u})}catch(e){e instanceof DOMException||(window.clearInterval(c),s(e instanceof Error?e:new Error(String(e))))}},500)})}function u(e,t){if(!Number.isInteger(e)||e<=0)throw new RangeError(`${t} must be a positive integer`)}const g="[TenMSAuth]",f="color:#22c55e;font-weight:700",p="color:inherit;font-weight:normal";function m(e){return e?b:w}const w={info:()=>{},warn:()=>{},error:()=>{}},b={info(e,t){t&&Object.keys(t).length>0?(console.groupCollapsed(`%c${g}%c ${e}`,f,p),console.table(t),console.groupEnd()):console.log(`%c${g}%c ${e}`,f,p)},warn(e,t){console.warn(`%c${g}%c ⚠ ${e}`,f,p,null!=t?t:"")},error(e,t){console.error(`%c${g}%c ✕ ${e}`,f,p,null!=t?t:"")}};function _(e){return e?e.length>8?`${e.slice(0,8)}…`:e:"(empty)"}class v{get(e){const t=document.cookie.match(new RegExp("(?:^|; )"+e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")+"=([^;]*)"));return t?decodeURIComponent(t[1]):null}set(e,t,n){let o=`${e}=${encodeURIComponent(t)}; path=/; SameSite=Lax`;n&&(o+=`; expires=${new Date(1e3*n).toUTCString()}`),document.cookie=o}remove(e){document.cookie=`${e}=; path=/; expires=Thu, 01 Jan 1970 00:00:00 GMT; SameSite=Lax`}clear(e){e.forEach(e=>this.remove(e))}}class k{get(e){return localStorage.getItem(e)}set(e,t){localStorage.setItem(e,t)}remove(e){localStorage.removeItem(e)}clear(e){e.forEach(e=>this.remove(e))}}const y="https://api.10minuteschool.com/auth",S="https://10minuteschool.com/auth/login",E=["profile"],x={ACCESS_TOKEN:"_tenms_access_token",REFRESH_TOKEN:"_tenms_refresh_token",EXPIRES_AT:"_tenms_expires_at",USER:"_tenms_user"};class C{constructor(e){var t,n;this.config=function(e){var t,n;const o=null===(t=e.clientId)||void 0===t?void 0:t.trim();if(!o)throw new i("clientId is required","missing_client_id");const r=(null===(n=e.redirectUri)||void 0===n?void 0:n.trim())||void 0,s=T(y,"baseUrl","invalid_base_url"),a=T(S,"authorizeUrl","invalid_authorize_url"),c=function(e){if(!Array.isArray(e)||0===e.length)return E;const t=e.map(e=>e.trim()).filter(Boolean);return t.length>0?t:E}(e.scopes);return{clientId:o,redirectUri:r,scopes:c,baseUrl:s,authorizeUrl:a}}(e),this.log=m(!0===e.debug),this.storage="localStorage"===(null!==(t=e.storage)&&void 0!==t?t:"cookie")?new k:new v,this.log.info("init",{clientId:this.config.clientId,redirectUri:this.config.redirectUri,baseUrl:this.config.baseUrl,authorizeUrl:this.config.authorizeUrl,scopes:this.config.scopes.join(" "),storage:null!==(n=e.storage)&&void 0!==n?n:"cookie",debug:!0===e.debug})}async loginWithPopup(e={}){var t,n;const o=null!==(t=e.width)&&void 0!==t?t:500,r=null!==(n=e.height)&&void 0!==n?n:600;this.log.info("loginWithPopup:start",{width:o,height:r});const l=c(),u=s();this.log.info("loginWithPopup:pkce-generated",{state:_(l),codeVerifier:_(u)});const g=d({url:"about:blank",width:o,height:r});if(!g){const e=new i("Failed to open login popup. Please allow popups for this site.","popup_blocked");throw this.log.error("loginWithPopup:popup-blocked",e),e}if(g===window){const e=new i("The browser reused the current tab instead of opening a popup window.","popup_reused_opener");throw this.log.error("loginWithPopup:popup-reused-opener",e),e}this.log.info("loginWithPopup:popup-opened"),function(e){try{e.document.title="Signing in…",e.document.body.style.cssText="font-family:system-ui,sans-serif;padding:2rem;text-align:center",e.document.body.textContent="Signing in…"}catch(e){}}(g);try{const e=await a(u),t=this.buildAuthorizeUrl(l,e);this.log.info("loginWithPopup:navigating",{authorizeUrl:t,codeChallenge:_(e)}),g.location.href=t;const n=await h(g,this.requireRedirectUri(),l);return this.log.info("loginWithPopup:success",{code:_(n.code),state:_(n.state)}),{code:n.code,state:n.state,codeVerifier:u}}catch(e){throw g.closed||g.close(),this.log.error("loginWithPopup:error",e),e}}async loginWithRedirect(){this.log.info("loginWithRedirect:start");const e=c(),t=s(),n=await a(t);this.log.info("loginWithRedirect:pkce-generated",{state:_(e),codeVerifier:_(t),codeChallenge:_(n)}),function(e,t){sessionStorage.setItem(U("state"),e),sessionStorage.setItem(U("code_verifier"),t)}(e,t),this.log.info("loginWithRedirect:session-persisted",{storageKeys:[U("state"),U("code_verifier")]});const o=this.buildAuthorizeUrl(e,n);this.log.info("loginWithRedirect:navigating",{authorizeUrl:o}),window.location.href=o}handleRedirectCallback(){const e=new URLSearchParams(window.location.search),t=e.get("code"),n=e.get("state"),o=e.get("error"),r=e.get("error_description");if(!t&&!n&&!o)return this.log.info("handleRedirectCallback:not-a-callback"),null;this.log.info("handleRedirectCallback:callback-detected",{hasCode:Boolean(t),hasState:Boolean(n),error:null!=o?o:"(none)",errorDescription:null!=r?r:"(none)"});const s=sessionStorage.getItem(U("state")),a=sessionStorage.getItem(U("code_verifier"));if(!n||!s||n!==s){R();const e=new i("State mismatch — possible CSRF attack","state_mismatch");throw this.log.warn("handleRedirectCallback:state-mismatch",{receivedState:n?_(n):"(missing)",storedStatePresent:Boolean(s)}),e}if(R(),function(){const e=window.location.origin+window.location.pathname;window.history.replaceState({},document.title,e)}(),o)throw this.log.error("handleRedirectCallback:oauth-error",{error:o,errorDescription:r}),new i(r||o,o);if(!t){const e=new i("No authorization code was returned to the redirect URI","missing_authorization_code");throw this.log.error("handleRedirectCallback:missing-code",e),e}if(!a){const e=new i("No PKCE code verifier was found for the redirect callback","missing_code_verifier");throw this.log.error("handleRedirectCallback:missing-verifier",e),e}return this.log.info("handleRedirectCallback:success",{code:_(t),state:_(n)}),{code:t,state:n,codeVerifier:a}}async exchangeCode(e,t){if(!e||e.length>2048)throw new i("code is required and must be under 2048 characters","invalid_authorization_code");if(!t||t.length<43||t.length>128)throw new i("codeVerifier must be 43–128 characters (RFC 7636)","invalid_code_verifier");const n=`${this.config.baseUrl}/v1/oauth/token`;this.log.info("exchangeCode:start",{endpoint:n,code:_(e),codeVerifier:_(t),clientId:this.config.clientId,redirectUri:this.config.redirectUri});const o=await fetch(n,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({grant_type:"authorization_code",code:e,redirect_uri:this.requireRedirectUri(),client_id:this.config.clientId,code_verifier:t})});if(!o.ok){const e=await I(o),t=new i(A(e,"Token exchange failed"),"token_exchange_failed");throw this.log.error("exchangeCode:error",{status:o.status,message:t.message}),t}const r=$(await o.json());return this.log.info("exchangeCode:success",{token_type:r.token_type,expires_in:r.expires_in,scope:r.scope,access_token:_(r.access_token),has_refresh_token:Boolean(r.refresh_token)}),r}async refreshToken(e){if(!e)throw new i("refreshToken is required","missing_refresh_token");const t=`${this.config.baseUrl}/v1/oauth/token`;this.log.info("refreshToken:start",{endpoint:t,refreshToken:_(e),clientId:this.config.clientId});const n=await fetch(t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({grant_type:"refresh_token",refresh_token:e,client_id:this.config.clientId})});if(!n.ok){const e=await I(n),t=new i(A(e,"Token refresh failed"),"token_refresh_failed");throw this.log.error("refreshToken:error",{status:n.status,message:t.message}),t}const o=$(await n.json());return this.log.info("refreshToken:success",{token_type:o.token_type,expires_in:o.expires_in,access_token:_(o.access_token)}),o}async getUserInfo(e){var t,n;if(!e)throw new i("accessToken is required to fetch user info","missing_access_token");const o=`${this.config.baseUrl}/v1/oauth/userinfo`;this.log.info("getUserInfo:start",{endpoint:o,accessToken:_(e)});const r=await fetch(o,{headers:{Authorization:`Bearer ${e}`}});if(!r.ok){const e=await I(r),t=new i(A(e,"Failed to fetch user info"),"userinfo_failed");throw this.log.error("getUserInfo:error",{status:r.status,message:t.message}),t}const s=function(e){if(!e||"object"!=typeof e||"string"!=typeof e.sub||!e.sub)throw new i("Server returned an invalid userinfo response (missing sub)","invalid_userinfo_response");return e}(await r.json());return this.log.info("getUserInfo:success",{sub:s.sub,name:null!==(t=s.name)&&void 0!==t?t:"(not returned)",email:null!==(n=s.email)&&void 0!==n?n:"(not returned)"}),s}async revokeToken(e){if(!e)throw new i("token is required to revoke an OAuth token","missing_token");const t=`${this.config.baseUrl}/v1/oauth/revoke`;this.log.info("revokeToken:start",{endpoint:t,token:_(e),clientId:this.config.clientId});const n=await fetch(t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({token:e,client_id:this.config.clientId})});if(!n.ok){const e=await I(n),t=new i(A(e,"Failed to revoke token"),"revoke_failed");throw this.log.error("revokeToken:error",{status:n.status,message:t.message}),t}this.log.info("revokeToken:success")}async handleLoginSuccess(e){this.log.info("handleLoginSuccess:start",{code:_(e.code)});const t=await this.exchangeCode(e.code,e.codeVerifier),n=await this.getUserInfo(t.access_token),o=Math.floor(Date.now()/1e3)+t.expires_in;return this.storage.set(x.ACCESS_TOKEN,t.access_token,o),this.storage.set(x.EXPIRES_AT,String(o),o),t.refresh_token&&this.storage.set(x.REFRESH_TOKEN,t.refresh_token),this.storage.set(x.USER,JSON.stringify(n)),this.log.info("handleLoginSuccess:session-saved",{sub:n.sub,expiresAt:o,hasRefreshToken:Boolean(t.refresh_token)}),{user:n,accessToken:t.access_token}}async getAccessToken(){var e;const t=this.storage.get(x.ACCESS_TOKEN),n=Number(null!==(e=this.storage.get(x.EXPIRES_AT))&&void 0!==e?e:"0");if(!t)return null;if(!(n>0&&Math.floor(Date.now()/1e3)>=n))return t;this.log.info("getAccessToken:expired, attempting refresh");const o=this.storage.get(x.REFRESH_TOKEN);if(!o)return this.log.info("getAccessToken:no-refresh-token, clearing session"),this.clearSession(),null;try{const e=await this.refreshToken(o),t=Math.floor(Date.now()/1e3)+e.expires_in;return this.storage.set(x.ACCESS_TOKEN,e.access_token,t),this.storage.set(x.EXPIRES_AT,String(t),t),e.refresh_token&&this.storage.set(x.REFRESH_TOKEN,e.refresh_token),this.log.info("getAccessToken:refreshed",{newExpiresAt:t}),e.access_token}catch(e){return this.log.error("getAccessToken:refresh-failed",e),this.clearSession(),null}}getUser(){const e=this.storage.get(x.USER);if(!e)return null;try{return JSON.parse(e)}catch(e){return null}}isLoggedIn(){var e;if(!this.storage.get(x.ACCESS_TOKEN))return!1;const t=Number(null!==(e=this.storage.get(x.EXPIRES_AT))&&void 0!==e?e:"0");return 0===t||Math.floor(Date.now()/1e3)<t}async logout(){const e=this.storage.get(x.ACCESS_TOKEN);if(e)try{await this.revokeToken(e)}catch(e){this.log.error("logout:revoke-failed",e)}this.clearSession(),this.log.info("logout:done")}getBaseUrl(){return this.config.baseUrl}getClientId(){return this.config.clientId}clearSession(){this.storage.clear(Object.values(x))}requireRedirectUri(){if(this.config.redirectUri)return this.config.redirectUri;if("undefined"!=typeof window)return window.location.origin;throw new i("redirectUri is required — pass it in the TenMSAuth constructor or call from a browser context","missing_redirect_uri")}buildAuthorizeUrl(e,t){const n=new URL(this.config.authorizeUrl);return n.searchParams.set("client_id",this.config.clientId),n.searchParams.set("redirect_uri",this.requireRedirectUri()),n.searchParams.set("response_type","code"),n.searchParams.set("scope",this.config.scopes.join(" ")),n.searchParams.set("state",e),n.searchParams.set("code_challenge",t),n.searchParams.set("code_challenge_method","S256"),n.toString()}}function T(e,t,n){const o=e.trim();if(!o)throw new i(`${t} must not be empty`,n);const r=o.replace(/\/+$/,"");try{new URL(r)}catch(e){throw new i(`${t} is not a valid URL: "${r}"`,n)}return r}function U(e){return`tenms_auth_${e}`}function R(){sessionStorage.removeItem(U("state")),sessionStorage.removeItem(U("code_verifier"))}async function I(e){try{const t=await e.text();return t?JSON.parse(t):{}}catch(e){return{}}}function A(e,t){var n,o,i;return null!==(i=null!==(o=null!==(n=e.error_description)&&void 0!==n?n:e.message)&&void 0!==o?o:e.error)&&void 0!==i?i:t}function $(e){if(!e||"object"!=typeof e||"string"!=typeof e.access_token||!e.access_token)throw new i("Server returned an invalid token response (missing access_token)","invalid_token_response");return e}!function(e,t){void 0===t&&(t={});var n=t.insertAt;if("undefined"!=typeof document){var o=document.head||document.getElementsByTagName("head")[0],i=document.createElement("style");i.type="text/css","top"===n&&o.firstChild?o.insertBefore(i,o.firstChild):o.appendChild(i),i.styleSheet?i.styleSheet.cssText=e:i.appendChild(document.createTextNode(e))}}(".tenms-login-btn{-webkit-font-smoothing:antialiased;align-items:center;border:1px solid transparent;border-radius:6px;cursor:pointer;display:inline-flex;font-family:-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica Neue,Arial,sans-serif;font-size:14px;font-weight:500;gap:6px;height:36px;justify-content:center;line-height:1;padding:0 12px;text-decoration:none;transition:background .15s ease,border-color .15s ease,color .15s ease,opacity .15s ease;user-select:none;-webkit-user-select:none;white-space:nowrap;width:fit-content}.tenms-login-btn:focus-visible{outline:2px solid #0070f3;outline-offset:2px}.tenms-login-btn:disabled{cursor:not-allowed}.tenms-login-btn--dark.tenms-login-btn--fill{background:#000;border-color:#000;color:#fff}.tenms-login-btn--dark.tenms-login-btn--fill:hover:not(:disabled){background:#333;border-color:#333}.tenms-login-btn--dark.tenms-login-btn--outline{background:transparent;border-color:#000;color:#000}.tenms-login-btn--dark.tenms-login-btn--outline:hover:not(:disabled){background:#f5f5f5}.tenms-login-btn--light.tenms-login-btn--fill{background:#fff;border-color:#e5e7eb;color:#111}.tenms-login-btn--light.tenms-login-btn--fill:hover:not(:disabled){background:#f5f5f5}.tenms-login-btn--light.tenms-login-btn--outline{background:transparent;border-color:#e5e7eb;color:#111}.tenms-login-btn--light.tenms-login-btn--outline:hover:not(:disabled){background:#f5f5f5;border-color:#d1d5db}.tenms-login-btn--small{font-size:13px;gap:5px;height:32px;padding:0 10px}.tenms-login-btn--medium{font-size:14px;height:36px;padding:0 12px}.tenms-login-btn--large{font-size:14px;height:40px;padding:0 14px}.tenms-login-btn__logo{align-items:center;display:inline-flex;flex-shrink:0}.tenms-login-btn__logo svg{display:block;height:18px;width:18px}.tenms-login-btn--loading{opacity:.6;pointer-events:none}.tenms-login-btn__spinner{animation:tenms-spin .6s linear infinite;border:1.5px solid;border-radius:50%;border-top:1.5px solid transparent;height:14px;width:14px}@keyframes tenms-spin{to{transform:rotate(1turn)}}");function L(e){return"light"===e?'<svg width="20" height="20" viewBox="0 0 32 32" fill="none" xmlns="http://www.w3.org/2000/svg" aria-hidden="true" focusable="false">\n <path d="M21.9012 17.9947L28.8098 11.085C28.0544 7.39598 25.1207 4.50016 21.4039 4.03514C21.3338 4.02624 21.2626 4.01845 21.1925 4.01178V7.43714C22.8023 7.7097 24.1373 8.751 24.916 10.1839L19.5049 15.5939L21.9012 17.9947Z" fill="#EB2026"/>\n <path d="M9.47025 27.9927H6.0727V7.40489H3V4.00734H9.47025V27.9927Z" fill="#111827"/>\n <path d="M25.5835 16.7187L25.569 18.9771V18.9882C25.569 22.0776 23.2172 24.5907 20.3269 24.5907C17.4367 24.5907 15.0871 22.0798 15.0849 18.9938L15.126 12.9807V12.9696C15.126 10.224 16.9906 7.88999 19.4992 7.44388V4.01518L19.2767 4.04076C14.9703 4.60591 11.7263 8.44178 11.7229 12.9641L11.684 18.9771V18.9882C11.684 23.951 15.5599 27.9883 20.3236 27.9883C25.0873 27.9883 28.9599 23.9544 28.9621 18.9938L28.9999 13.2989L25.5835 16.7187Z" fill="#111827"/>\n</svg>':'<svg width="20" height="20" viewBox="0 0 32 32" fill="none" xmlns="http://www.w3.org/2000/svg" aria-hidden="true" focusable="false">\n <path d="M21.9012 17.9947L28.8098 11.085C28.0544 7.39598 25.1207 4.50016 21.4039 4.03514C21.3338 4.02624 21.2626 4.01845 21.1925 4.01178V7.43714C22.8023 7.7097 24.1373 8.751 24.916 10.1839L19.5049 15.5939L21.9012 17.9947Z" fill="#EB2026"/>\n <path d="M9.47025 27.9927H6.0727V7.40489H3V4.00734H9.47025V27.9927Z" fill="#F9FAFB"/>\n <path d="M25.5835 16.7187L25.569 18.9771V18.9882C25.569 22.0776 23.2172 24.5907 20.3269 24.5907C17.4367 24.5907 15.0871 22.0798 15.0849 18.9938L15.126 12.9807V12.9696C15.126 10.224 16.9906 7.88999 19.4992 7.44388V4.01518L19.2767 4.04076C14.9703 4.60591 11.7263 8.44178 11.7229 12.9641L11.684 18.9771V18.9882C11.684 23.951 15.5599 27.9883 20.3236 27.9883C25.0873 27.9883 28.9599 23.9544 28.9621 18.9938L28.9999 13.2989L25.5835 16.7187Z" fill="#F9FAFB"/>\n</svg>'}function P(e="dark"){return`<span class="tenms-login-btn__logo">${L(e)}</span>`}var z;const N="Login with 10MinuteSchool",O=null!==(z=globalThis.HTMLElement)&&void 0!==z?z:class{};class M extends O{constructor(){super(...arguments),this.auth=null,this.loading=!1}static get observedAttributes(){return["client-id","redirect-uri","scope","theme","variant","size","text"]}connectedCallback(){this.render()}attributeChangedCallback(){this.loading||this.render()}render(){var e;const t=q(this.getAttribute("theme")),n=F(this.getAttribute("variant")),o=W(this.getAttribute("size")),i=(null===(e=this.getAttribute("text"))||void 0===e?void 0:e.trim())||N;var r;this.innerHTML=`\n <button class="${B((r={loading:this.loading,text:i,theme:t,variant:n,size:o}).theme,r.variant,r.size,r.loading)}" type="button" ${r.loading?'disabled aria-busy="true"':""}>\n ${r.loading?'<span class="tenms-login-btn__spinner" aria-hidden="true"></span>':P(r.theme)}\n <span class="tenms-login-btn__label">${H(r.text)}</span>\n </button>\n `;const s=this.querySelector("button");s&&s.addEventListener("click",()=>{this.handleClick()})}async handleClick(){if(this.loading)return;const e=this.getConfig();if(e.clientId&&e.redirectUri){this.auth||(this.auth=new C(e)),this.loading=!0,this.render();try{const e=await this.auth.loginWithPopup();this.dispatchEvent(new CustomEvent("tenms-success",{detail:e,bubbles:!0,composed:!0}))}catch(e){this.dispatchError(K(e))}finally{this.loading=!1,this.render()}}else this.dispatchError(new i("client-id and redirect-uri attributes are required","invalid_login_button_config"))}getConfig(){const e=this.getAttribute("scope")||"profile";return{clientId:this.getAttribute("client-id")||"",redirectUri:this.getAttribute("redirect-uri")||"",scopes:e.split(" ").map(e=>e.trim()).filter(Boolean)}}dispatchError(e){this.dispatchEvent(new CustomEvent("tenms-error",{detail:e,bubbles:!0,composed:!0}))}}function V(){"undefined"==typeof window||"undefined"==typeof customElements||customElements.get("tenms-login-button")||customElements.define("tenms-login-button",M)}function j(e,t){e.className=B(t.theme,t.variant,t.size,t.loading),e.type="button",e.disabled=t.loading,e.setAttribute("aria-busy",String(t.loading)),e.innerHTML=t.loading?`<span class="tenms-login-btn__spinner" aria-hidden="true"></span><span class="tenms-login-btn__label">${H(t.text)}</span>`:`${P(t.theme)}<span class="tenms-login-btn__label">${H(t.text)}</span>`}function B(e,t,n,o){return["tenms-login-btn",`tenms-login-btn--${e}`,`tenms-login-btn--${t}`,`tenms-login-btn--${n}`,o?"tenms-login-btn--loading":""].filter(Boolean).join(" ")}function q(e){return"light"===e?e:"dark"}function F(e){return"outline"===e?e:"fill"}function W(e){return"small"===e||"medium"===e?e:"large"}function H(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;")}function K(e){return e instanceof Error?e:new Error(String(e))}const D="Login with 10MinuteSchool",J="dark",X="fill",Z="large";function Y(e){return"light"===e?e:J}function G(e){return"small"===e||"medium"===e?e:Z}V(),e.LoginButton=function(e){const{clientId:t,redirectUri:n,scopes:i,theme:r=J,variant:s=X,size:a=Z,text:c=D,onSuccess:l,onError:d,className:h=""}=e,[u,g]=o.useState(!1),f=o.useRef(l),p=o.useRef(d);o.useEffect(()=>{f.current=l},[l]),o.useEffect(()=>{p.current=d},[d]);const m=Array.isArray(i)?i.join("\0"):"",w=o.useMemo(()=>new C({clientId:t,redirectUri:n,scopes:i}),[t,n,m]),b=o.useCallback(async()=>{var e,t;g(!0);try{const t=await w.loginWithPopup();null===(e=f.current)||void 0===e||e.call(f,t)}catch(e){null===(t=p.current)||void 0===t||t.call(p,function(e){return e instanceof Error?e:new Error(String(e))}(e))}finally{g(!1)}},[w]),_=["tenms-login-btn",`tenms-login-btn--${Y(r)}`,`tenms-login-btn--${v=s,"outline"===v?v:X}`,`tenms-login-btn--${G(a)}`,u?"tenms-login-btn--loading":"",h].filter(Boolean).join(" ");var v;return o.createElement("button",{className:_,type:"button",onClick:()=>{b()},disabled:u,"aria-busy":u},u?o.createElement("span",{className:"tenms-login-btn__spinner","aria-hidden":"true"}):o.createElement("span",{className:"tenms-login-btn__logo",dangerouslySetInnerHTML:{__html:L(Y(r))}}),o.createElement("span",{className:"tenms-login-btn__label"},c))},e.TenMSAuth=C,e.TenMSAuthError=i,e.TenMSLoginButtonElement=M,e.VERSION="0.1.0",e.createLogger=m,e.generateCodeChallenge=a,e.generateCodeVerifier=s,e.generateState=c,e.openPopup=d,e.registerLoginButton=V,e.renderLoginButton=function(e,t){var n;const o="string"==typeof e?document.querySelector(e):e;if(!o)throw new i(`Container element not found: ${e}`,"container_not_found");const r=new C({clientId:t.clientId,redirectUri:t.redirectUri,scopes:t.scopes}),s=q(t.theme),a=F(t.variant),c=W(t.size),l=(null===(n=t.text)||void 0===n?void 0:n.trim())||N,d=document.createElement("button");j(d,{loading:!1,size:c,text:l,theme:s,variant:a}),d.addEventListener("click",async()=>{var e,n;if(!d.classList.contains("tenms-login-btn--loading")){j(d,{loading:!0,size:c,text:l,theme:s,variant:a});try{const n=await r.loginWithPopup();null===(e=t.onSuccess)||void 0===e||e.call(t,n)}catch(e){null===(n=t.onError)||void 0===n||n.call(t,K(e))}finally{j(d,{loading:!1,size:c,text:l,theme:s,variant:a})}}}),o.replaceChildren(d)},e.truncate=_,e.waitForPopupRedirect=h});
2
2
  //# sourceMappingURL=tenms-auth.umd.js.map
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tenminuteschool/auth-react",
3
- "version": "0.3.0",
3
+ "version": "0.4.0",
4
4
  "description": "OAuth 2.0 + PKCE browser client for Login with 10MinuteSchool",
5
5
  "license": "MIT",
6
6
  "author": "10 Minute School",