@genation/sdk 0.2.9 → 0.2.10
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/genation.cjs.js +1 -1
- package/dist/genation.cjs.js.map +1 -1
- package/dist/genation.es.js +1255 -194
- package/dist/genation.es.js.map +1 -1
- package/dist/genation.umd.js +1 -1
- package/dist/genation.umd.js.map +1 -1
- package/dist/index.d.ts +26 -0
- package/package.json +1 -1
package/dist/genation.umd.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
(function(s,d){typeof exports=="object"&&typeof module<"u"?d(exports):typeof define=="function"&&define.amd?define(["exports"],d):(s=typeof globalThis<"u"?globalThis:s||self,d(s.Genation={}))})(this,(function(s){"use strict";class d extends Error{code;cause;constructor(e,t,n){super(e),this.name="GenationError",this.code=t,this.cause=n}}class c extends d{constructor(e,t,n){super(e,t,n),this.name="AuthError"}static invalidGrant(e="Invalid authorization code or refresh token"){return new c(e,"invalid_grant")}static accessDenied(e="User denied access"){return new c(e,"access_denied")}static expiredToken(e="Token has expired"){return new c(e,"expired_token")}static invalidState(e="State mismatch, possible CSRF attack"){return new c(e,"invalid_state")}static pkceVerificationFailed(e="PKCE verification failed"){return new c(e,"pkce_verification_failed")}}class h extends d{status;constructor(e,t,n){super(e,"network_error",n),this.name="NetworkError",this.status=t}static fromResponse(e){return new h(`HTTP ${e.status}: ${e.statusText}`,e.status)}}class f extends d{constructor(e){super(e,"config_error"),this.name="ConfigError"}static missingField(e){return new f(`Missing required config field: ${e}`)}}class g{baseUrl;timeout;constructor(e){this.baseUrl=e.baseUrl.replace(/\/$/,""),this.timeout=e.timeout??3e4}async request(e,t={}){const{method:n="GET",headers:i={},body:o,params:u}=t;let l=`${this.baseUrl}${e}`;if(u){const a=new URLSearchParams(u);l+=`?${a.toString()}`}const C=new AbortController,E=setTimeout(()=>C.abort(),this.timeout);try{const a=await fetch(l,{method:n,headers:{"Content-Type":"application/json",...i},body:o?JSON.stringify(o):void 0,signal:C.signal});if(clearTimeout(E),!a.ok)throw h.fromResponse(a);return await a.json()}catch(a){throw clearTimeout(E),a instanceof h?a:a instanceof Error&&a.name==="AbortError"?new h("Request timeout",void 0,a):new h("Network request failed",void 0,a)}}async postForm(e,t,n={}){const i=`${this.baseUrl}${e}`,o=new AbortController,u=setTimeout(()=>o.abort(),this.timeout);try{const l=await fetch(i,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded",...n},body:new URLSearchParams(t).toString(),signal:o.signal});if(clearTimeout(u),!l.ok)throw h.fromResponse(l);return await l.json()}catch(l){throw clearTimeout(u),l instanceof h?l:new h("Network request failed",void 0,l)}}}function p(r){return btoa(String.fromCharCode(...r)).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function I(){const r=new Uint8Array(32);return crypto.getRandomValues(r),p(r)}async function U(r){const t=new TextEncoder().encode(r),n=await crypto.subtle.digest("SHA-256",t);return p(new Uint8Array(n))}async function A(){const r=I(),e=await U(r);return{codeVerifier:r,codeChallenge:e,codeChallengeMethod:"S256"}}function x(){const r=new Uint8Array(16);return crypto.getRandomValues(r),p(r)}const w="tokens",m="pkce",y="state";class M{storage;constructor(e){this.storage=e}async setTokens(e){await this.storage.set(w,JSON.stringify(e))}async getTokens(){const e=await this.storage.get(w);if(!e)return null;try{return JSON.parse(e)}catch{return null}}async clearTokens(){await this.storage.remove(w)}async isTokenExpired(){const e=await this.getTokens();if(!e)return!0;const t=e.issuedAt+e.expiresIn*1e3;return Date.now()>t-6e4}async setPKCE(e){await this.storage.set(m,e)}async consumePKCE(){const e=await this.storage.get(m);return e&&await this.storage.remove(m),e}async setState(e){await this.storage.set(y,e)}async consumeState(){const e=await this.storage.get(y);return e&&await this.storage.remove(y),e}async clearAll(){await this.storage.clear()}}const K="https://mnnoheowoowbtpuoguul.supabase.co/auth/v1";class ${config;http;tokenManager;constructor(e,t){this.config={clientId:e.clientId,clientSecret:e.clientSecret,redirectUri:e.redirectUri,scopes:e.scopes,authUrl:e.authUrl??K},this.http=new g({baseUrl:this.config.authUrl}),this.tokenManager=t}async getAuthorizationUrl(){const e=await A(),t=x();await this.tokenManager.setPKCE(e.codeVerifier),await this.tokenManager.setState(t);const n=new URLSearchParams({response_type:"code",client_id:this.config.clientId,redirect_uri:this.config.redirectUri,state:t,code_challenge:e.codeChallenge,code_challenge_method:e.codeChallengeMethod});return this.config.scopes&&this.config.scopes.length>0&&n.append("scope",this.config.scopes.join(" ")),`${this.config.authUrl}/oauth/authorize?${n.toString()}`}async exchangeCode(e,t){const n=await this.tokenManager.consumeState();if(!n||n!==t)throw c.invalidState();const i=await this.tokenManager.consumePKCE();if(!i)throw c.pkceVerificationFailed("Missing code verifier");const o=await this.http.postForm("/oauth/token",{grant_type:"authorization_code",code:e,redirect_uri:this.config.redirectUri,client_id:this.config.clientId,client_secret:this.config.clientSecret,code_verifier:i}),u=this.mapTokenResponse(o);return await this.tokenManager.setTokens(u),u}async refreshToken(){const e=await this.tokenManager.getTokens();if(!e?.refreshToken)throw c.invalidGrant("No refresh token available");const t=await this.http.postForm("/oauth/token",{grant_type:"refresh_token",refresh_token:e.refreshToken,client_id:this.config.clientId,client_secret:this.config.clientSecret}),n=this.mapTokenResponse(t);return await this.tokenManager.setTokens(n),n}async revokeToken(){const e=await this.tokenManager.getTokens();if(e)try{await this.http.postForm("/oauth/revoke",{token:e.accessToken,client_id:this.config.clientId,client_secret:this.config.clientSecret})}finally{await this.tokenManager.clearTokens()}}mapTokenResponse(e){return{accessToken:e.access_token,refreshToken:e.refresh_token,tokenType:e.token_type,expiresIn:e.expires_in,issuedAt:Date.now(),scope:e.scope}}}class T{store=new Map;async get(e){return this.store.get(e)??null}async set(e,t){this.store.set(e,t)}async remove(e){this.store.delete(e)}async clear(){this.store.clear()}}class k{prefix;constructor(e="genation"){this.prefix=e}getKey(e){return`${this.prefix}:${e}`}async get(e){return typeof window>"u"?null:localStorage.getItem(this.getKey(e))}async set(e,t){typeof window>"u"||localStorage.setItem(this.getKey(e),t)}async remove(e){typeof window>"u"||localStorage.removeItem(this.getKey(e))}async clear(){if(typeof window>"u")return;Object.keys(localStorage).filter(t=>t.startsWith(`${this.prefix}:`)).forEach(t=>localStorage.removeItem(t))}}class b{prefix;constructor(e="genation"){this.prefix=e}getKey(e){return`${this.prefix}:${e}`}async get(e){return typeof window>"u"?null:sessionStorage.getItem(this.getKey(e))}async set(e,t){typeof window>"u"||sessionStorage.setItem(this.getKey(e),t)}async remove(e){typeof window>"u"||sessionStorage.removeItem(this.getKey(e))}async clear(){if(typeof window>"u")return;Object.keys(sessionStorage).filter(t=>t.startsWith(`${this.prefix}:`)).forEach(t=>sessionStorage.removeItem(t))}}function _(r="localStorage"){switch(r){case"memory":return new T;case"localStorage":return new k;case"sessionStorage":return new b;default:return new k}}function S(r){return Array.isArray(r)?r.map(S):typeof r=="object"&&r!==null?Object.fromEntries(Object.entries(r).map(([e,t])=>[e.replace(/_([a-z])/g,(n,i)=>i.toUpperCase()),S(t)])):r}class v{oauth;tokenManager;http;httpServer;listeners=new Set;initialized=!1;constructor(e){this.validateConfig(e);const t=typeof e.storage=="object"?e.storage:_(e.storage);this.tokenManager=new M(t),this.oauth=new $(e,this.tokenManager),this.http=new g({baseUrl:e.authUrl??"https://mnnoheowoowbtpuoguul.supabase.co/auth/v1"}),this.httpServer=new g({baseUrl:"https://ff-api.genation.ai/api/v2/client"})}validateConfig(e){if(!e.clientId)throw f.missingField("clientId");if(!e.clientSecret)throw f.missingField("clientSecret");if(!e.redirectUri)throw f.missingField("redirectUri")}async emitAuthStateChange(e){const t=await this.getSession();this.listeners.forEach(n=>{try{n(e,t)}catch(i){console.error("Error in auth state change callback:",i)}})}onAuthStateChange(e){return this.listeners.add(e),this.initialized?setTimeout(()=>{this.emitAuthStateChange("INITIAL_SESSION")},0):(this.initialized=!0,setTimeout(()=>{this.emitAuthStateChange("INITIAL_SESSION")},0)),{subscription:{unsubscribe:()=>{this.listeners.delete(e)}}}}async signIn(){return this.oauth.getAuthorizationUrl()}async handleCallback(e){const t=new URL(e),n=t.searchParams.get("code"),i=t.searchParams.get("state");if(!n||!i)throw new Error("Missing code or state");const o=await this.oauth.exchangeCode(n,i);return await this.emitAuthStateChange("SIGNED_IN"),o}async getSession(){if(await this.tokenManager.isTokenExpired())try{await this.oauth.refreshToken()}catch{return null}const t=await this.tokenManager.getTokens();if(!t)return null;const n=await this.fetchUser(t.accessToken);return{accessToken:t.accessToken,refreshToken:t.refreshToken,expiresIn:t.expiresIn,expiresAt:t.issuedAt+t.expiresIn*1e3,user:n}}async getLicenses(e={}){const t=await this.getSession();if(!t)return null;const n=t.accessToken,{expiresAfter:i=new Date}=e,o=await this.httpServer.request("/licenses",{headers:{Authorization:`Bearer ${n}`},params:{expiresAfter:i.toISOString()}});return o.ok?S(o.data):(console.error("GenationClient: Error fetching licenses:",o.error),null)}async fetchUser(e){try{const t=await this.http.request("/oauth/userinfo",{headers:{Authorization:`Bearer ${e}`}});return{sub:t.sub,name:t.name,picture:t.picture,email:t.email,email_verified:t.email_verified,phone_number:t.phone_number,phone_number_verified:t.phone_number_verified}}catch(t){return console.error("GenationClient: Error fetching user:",t),null}}}function P(r){return new v(r)}s.AuthError=c,s.ConfigError=f,s.GenationClient=v,s.GenationError=d,s.LocalStorage=k,s.MemoryStorage=T,s.NetworkError=h,s.SessionStorage=b,s.createClient=P,s.createStorage=_,Object.defineProperty(s,Symbol.toStringTag,{value:"Module"})}));
|
|
1
|
+
(function(d,E){typeof exports=="object"&&typeof module<"u"?E(exports):typeof define=="function"&&define.amd?define(["exports"],E):(d=typeof globalThis<"u"?globalThis:d||self,E(d.Genation={}))})(this,(function(d){"use strict";class E extends Error{code;cause;constructor(e,r,n){super(e),this.name="GenationError",this.code=r,this.cause=n}}class m extends E{constructor(e,r,n){super(e,r,n),this.name="AuthError"}static invalidGrant(e="Invalid authorization code or refresh token"){return new m(e,"invalid_grant")}static accessDenied(e="User denied access"){return new m(e,"access_denied")}static expiredToken(e="Token has expired"){return new m(e,"expired_token")}static invalidState(e="State mismatch, possible CSRF attack"){return new m(e,"invalid_state")}static pkceVerificationFailed(e="PKCE verification failed"){return new m(e,"pkce_verification_failed")}}class w extends E{status;constructor(e,r,n){super(e,"network_error",n),this.name="NetworkError",this.status=r}static fromResponse(e){return new w(`HTTP ${e.status}: ${e.statusText}`,e.status)}}class T extends E{constructor(e){super(e,"config_error"),this.name="ConfigError"}static missingField(e){return new T(`Missing required config field: ${e}`)}}class W{baseUrl;timeout;constructor(e){this.baseUrl=e.baseUrl.replace(/\/$/,""),this.timeout=e.timeout??3e4}async request(e,r={}){const{method:n="GET",headers:s={},body:i,params:a}=r;let c=`${this.baseUrl}${e}`;if(a){const o=new URLSearchParams(a);c+=`?${o.toString()}`}const f=new AbortController,u=setTimeout(()=>f.abort(),this.timeout);try{const o=await fetch(c,{method:n,headers:{"Content-Type":"application/json",...s},body:i?JSON.stringify(i):void 0,signal:f.signal});if(clearTimeout(u),!o.ok)throw w.fromResponse(o);return await o.json()}catch(o){throw clearTimeout(u),o instanceof w?o:o instanceof Error&&o.name==="AbortError"?new w("Request timeout",void 0,o):new w("Network request failed",void 0,o)}}async postForm(e,r,n={}){const s=`${this.baseUrl}${e}`,i=new AbortController,a=setTimeout(()=>i.abort(),this.timeout);try{const c=await fetch(s,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded",...n},body:new URLSearchParams(r).toString(),signal:i.signal});if(clearTimeout(a),!c.ok)throw w.fromResponse(c);return await c.json()}catch(c){throw clearTimeout(a),c instanceof w?c:new w("Network request failed",void 0,c)}}}function I(t){return btoa(String.fromCharCode(...t)).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function pe(){const t=new Uint8Array(32);return crypto.getRandomValues(t),I(t)}async function ye(t){const r=new TextEncoder().encode(t),n=await crypto.subtle.digest("SHA-256",r);return I(new Uint8Array(n))}async function me(){const t=pe(),e=await ye(t);return{codeVerifier:t,codeChallenge:e,codeChallengeMethod:"S256"}}function we(){const t=new Uint8Array(16);return crypto.getRandomValues(t),I(t)}const J="tokens",U="pkce",D="state";class Se{storage;constructor(e){this.storage=e}async setTokens(e){await this.storage.set(J,JSON.stringify(e))}async getTokens(){const e=await this.storage.get(J);if(!e)return null;try{return JSON.parse(e)}catch{return null}}async clearTokens(){await this.storage.remove(J)}async isTokenExpired(){const e=await this.getTokens();if(!e)return!0;const r=e.issuedAt+e.expiresIn*1e3;return Date.now()>r-6e4}async setPKCE(e){await this.storage.set(U,e)}async consumePKCE(){const e=await this.storage.get(U);return e&&await this.storage.remove(U),e}async setState(e){await this.storage.set(D,e)}async consumeState(){const e=await this.storage.get(D);return e&&await this.storage.remove(D),e}async clearAll(){await this.storage.clear()}}const ge="https://mnnoheowoowbtpuoguul.supabase.co/auth/v1";class be{config;http;tokenManager;constructor(e,r){this.config={clientId:e.clientId,clientSecret:e.clientSecret,redirectUri:e.redirectUri,scopes:e.scopes,authUrl:e.authUrl??ge},this.http=new W({baseUrl:this.config.authUrl}),this.tokenManager=r}async getAuthorizationUrl(){const e=await me(),r=we();await this.tokenManager.setPKCE(e.codeVerifier),await this.tokenManager.setState(r);const n=new URLSearchParams({response_type:"code",client_id:this.config.clientId,redirect_uri:this.config.redirectUri,state:r,code_challenge:e.codeChallenge,code_challenge_method:e.codeChallengeMethod});return this.config.scopes&&this.config.scopes.length>0&&n.append("scope",this.config.scopes.join(" ")),`${this.config.authUrl}/oauth/authorize?${n.toString()}`}async exchangeCode(e,r){const n=await this.tokenManager.consumeState();if(!n||n!==r)throw m.invalidState();const s=await this.tokenManager.consumePKCE();if(!s)throw m.pkceVerificationFailed("Missing code verifier");const i=await this.http.postForm("/oauth/token",{grant_type:"authorization_code",code:e,redirect_uri:this.config.redirectUri,client_id:this.config.clientId,client_secret:this.config.clientSecret,code_verifier:s}),a=this.mapTokenResponse(i);return await this.tokenManager.setTokens(a),a}async refreshToken(){const e=await this.tokenManager.getTokens();if(!e?.refreshToken)throw m.invalidGrant("No refresh token available");const r=await this.http.postForm("/oauth/token",{grant_type:"refresh_token",refresh_token:e.refreshToken,client_id:this.config.clientId,client_secret:this.config.clientSecret}),n=this.mapTokenResponse(r);return await this.tokenManager.setTokens(n),n}async revokeToken(){const e=await this.tokenManager.getTokens();if(e)try{await this.http.postForm("/oauth/revoke",{token:e.accessToken,client_id:this.config.clientId,client_secret:this.config.clientSecret})}finally{await this.tokenManager.clearTokens()}}mapTokenResponse(e){return{accessToken:e.access_token,refreshToken:e.refresh_token,tokenType:e.token_type,expiresIn:e.expires_in,issuedAt:Date.now(),scope:e.scope}}}const z=new TextEncoder,R=new TextDecoder;function Ee(...t){const e=t.reduce((s,{length:i})=>s+i,0),r=new Uint8Array(e);let n=0;for(const s of t)r.set(s,n),n+=s.length;return r}function M(t){const e=new Uint8Array(t.length);for(let r=0;r<t.length;r++){const n=t.charCodeAt(r);if(n>127)throw new TypeError("non-ASCII string encountered in encode()");e[r]=n}return e}function Ae(t){if(Uint8Array.fromBase64)return Uint8Array.fromBase64(t);const e=atob(t),r=new Uint8Array(e.length);for(let n=0;n<e.length;n++)r[n]=e.charCodeAt(n);return r}function P(t){if(Uint8Array.fromBase64)return Uint8Array.fromBase64(typeof t=="string"?t:R.decode(t),{alphabet:"base64url"});let e=t;e instanceof Uint8Array&&(e=R.decode(e)),e=e.replace(/-/g,"+").replace(/_/g,"/");try{return Ae(e)}catch{throw new TypeError("The input to be decoded is not correctly encoded.")}}class l extends Error{static code="ERR_JOSE_GENERIC";code="ERR_JOSE_GENERIC";constructor(e,r){super(e,r),this.name=this.constructor.name,Error.captureStackTrace?.(this,this.constructor)}}class S extends l{static code="ERR_JWT_CLAIM_VALIDATION_FAILED";code="ERR_JWT_CLAIM_VALIDATION_FAILED";claim;reason;payload;constructor(e,r,n="unspecified",s="unspecified"){super(e,{cause:{claim:n,reason:s,payload:r}}),this.claim=n,this.reason=s,this.payload=r}}class B extends l{static code="ERR_JWT_EXPIRED";code="ERR_JWT_EXPIRED";claim;reason;payload;constructor(e,r,n="unspecified",s="unspecified"){super(e,{cause:{claim:n,reason:s,payload:r}}),this.claim=n,this.reason=s,this.payload=r}}class g extends l{static code="ERR_JOSE_NOT_SUPPORTED";code="ERR_JOSE_NOT_SUPPORTED"}class h extends l{static code="ERR_JWS_INVALID";code="ERR_JWS_INVALID"}class q extends l{static code="ERR_JWT_INVALID";code="ERR_JWT_INVALID"}class Y extends l{static code="ERR_JWKS_INVALID";code="ERR_JWKS_INVALID"}class X extends l{static code="ERR_JWKS_NO_MATCHING_KEY";code="ERR_JWKS_NO_MATCHING_KEY";constructor(e="no applicable key found in the JSON Web Key Set",r){super(e,r)}}class Ke extends l{[Symbol.asyncIterator];static code="ERR_JWKS_MULTIPLE_MATCHING_KEYS";code="ERR_JWKS_MULTIPLE_MATCHING_KEYS";constructor(e="multiple matching keys found in the JSON Web Key Set",r){super(e,r)}}class Te extends l{static code="ERR_JWKS_TIMEOUT";code="ERR_JWKS_TIMEOUT";constructor(e="request timed out",r){super(e,r)}}class ve extends l{static code="ERR_JWS_SIGNATURE_VERIFICATION_FAILED";code="ERR_JWS_SIGNATURE_VERIFICATION_FAILED";constructor(e="signature verification failed",r){super(e,r)}}const b=(t,e="algorithm.name")=>new TypeError(`CryptoKey does not support this operation, its ${e} must be ${t}`),v=(t,e)=>t.name===e;function O(t){return parseInt(t.name.slice(4),10)}function Ce(t){switch(t){case"ES256":return"P-256";case"ES384":return"P-384";case"ES512":return"P-521";default:throw new Error("unreachable")}}function _e(t,e){if(!t.usages.includes(e))throw new TypeError(`CryptoKey does not support this operation, its usages must include ${e}.`)}function Re(t,e,r){switch(e){case"HS256":case"HS384":case"HS512":{if(!v(t.algorithm,"HMAC"))throw b("HMAC");const n=parseInt(e.slice(2),10);if(O(t.algorithm.hash)!==n)throw b(`SHA-${n}`,"algorithm.hash");break}case"RS256":case"RS384":case"RS512":{if(!v(t.algorithm,"RSASSA-PKCS1-v1_5"))throw b("RSASSA-PKCS1-v1_5");const n=parseInt(e.slice(2),10);if(O(t.algorithm.hash)!==n)throw b(`SHA-${n}`,"algorithm.hash");break}case"PS256":case"PS384":case"PS512":{if(!v(t.algorithm,"RSA-PSS"))throw b("RSA-PSS");const n=parseInt(e.slice(2),10);if(O(t.algorithm.hash)!==n)throw b(`SHA-${n}`,"algorithm.hash");break}case"Ed25519":case"EdDSA":{if(!v(t.algorithm,"Ed25519"))throw b("Ed25519");break}case"ML-DSA-44":case"ML-DSA-65":case"ML-DSA-87":{if(!v(t.algorithm,e))throw b(e);break}case"ES256":case"ES384":case"ES512":{if(!v(t.algorithm,"ECDSA"))throw b("ECDSA");const n=Ce(e);if(t.algorithm.namedCurve!==n)throw b(n,"algorithm.namedCurve");break}default:throw new TypeError("CryptoKey does not support this operation")}_e(t,r)}function Q(t,e,...r){if(r=r.filter(Boolean),r.length>2){const n=r.pop();t+=`one of type ${r.join(", ")}, or ${n}.`}else r.length===2?t+=`one of type ${r[0]} or ${r[1]}.`:t+=`of type ${r[0]}.`;return e==null?t+=` Received ${e}`:typeof e=="function"&&e.name?t+=` Received function ${e.name}`:typeof e=="object"&&e!=null&&e.constructor?.name&&(t+=` Received an instance of ${e.constructor.name}`),t}const Pe=(t,...e)=>Q("Key must be ",t,...e),Z=(t,e,...r)=>Q(`Key for the ${t} algorithm must be `,e,...r),j=t=>{if(t?.[Symbol.toStringTag]==="CryptoKey")return!0;try{return t instanceof CryptoKey}catch{return!1}},ee=t=>t?.[Symbol.toStringTag]==="KeyObject",te=t=>j(t)||ee(t);function ke(...t){const e=t.filter(Boolean);if(e.length===0||e.length===1)return!0;let r;for(const n of e){const s=Object.keys(n);if(!r||r.size===0){r=new Set(s);continue}for(const i of s){if(r.has(i))return!1;r.add(i)}}return!0}const We=t=>typeof t=="object"&&t!==null;function A(t){if(!We(t)||Object.prototype.toString.call(t)!=="[object Object]")return!1;if(Object.getPrototypeOf(t)===null)return!0;let e=t;for(;Object.getPrototypeOf(e)!==null;)e=Object.getPrototypeOf(e);return Object.getPrototypeOf(t)===e}function Ie(t,e){if(t.startsWith("RS")||t.startsWith("PS")){const{modulusLength:r}=e.algorithm;if(typeof r!="number"||r<2048)throw new TypeError(`${t} requires key modulusLength to be 2048 bits or larger`)}}function Je(t){let e,r;switch(t.kty){case"AKP":{switch(t.alg){case"ML-DSA-44":case"ML-DSA-65":case"ML-DSA-87":e={name:t.alg},r=t.priv?["sign"]:["verify"];break;default:throw new g('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}break}case"RSA":{switch(t.alg){case"PS256":case"PS384":case"PS512":e={name:"RSA-PSS",hash:`SHA-${t.alg.slice(-3)}`},r=t.d?["sign"]:["verify"];break;case"RS256":case"RS384":case"RS512":e={name:"RSASSA-PKCS1-v1_5",hash:`SHA-${t.alg.slice(-3)}`},r=t.d?["sign"]:["verify"];break;case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":e={name:"RSA-OAEP",hash:`SHA-${parseInt(t.alg.slice(-3),10)||1}`},r=t.d?["decrypt","unwrapKey"]:["encrypt","wrapKey"];break;default:throw new g('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}break}case"EC":{switch(t.alg){case"ES256":e={name:"ECDSA",namedCurve:"P-256"},r=t.d?["sign"]:["verify"];break;case"ES384":e={name:"ECDSA",namedCurve:"P-384"},r=t.d?["sign"]:["verify"];break;case"ES512":e={name:"ECDSA",namedCurve:"P-521"},r=t.d?["sign"]:["verify"];break;case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":e={name:"ECDH",namedCurve:t.crv},r=t.d?["deriveBits"]:[];break;default:throw new g('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}break}case"OKP":{switch(t.alg){case"Ed25519":case"EdDSA":e={name:"Ed25519"},r=t.d?["sign"]:["verify"];break;case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":e={name:t.crv},r=t.d?["deriveBits"]:[];break;default:throw new g('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}break}default:throw new g('Invalid or unsupported JWK "kty" (Key Type) Parameter value')}return{algorithm:e,keyUsages:r}}async function k(t){if(!t.alg)throw new TypeError('"alg" argument is required when "jwk.alg" is not present');const{algorithm:e,keyUsages:r}=Je(t),n={...t};return n.kty!=="AKP"&&delete n.alg,delete n.use,crypto.subtle.importKey("jwk",n,e,t.ext??!(t.d||t.priv),t.key_ops??r)}async function Ue(t,e,r){if(!A(t))throw new TypeError("JWK must be an object");let n;switch(e??=t.alg,n??=t.ext,t.kty){case"oct":if(typeof t.k!="string"||!t.k)throw new TypeError('missing "k" (Key Value) Parameter value');return P(t.k);case"RSA":if("oth"in t&&t.oth!==void 0)throw new g('RSA JWK "oth" (Other Primes Info) Parameter value is not supported');return k({...t,alg:e,ext:n});case"AKP":{if(typeof t.alg!="string"||!t.alg)throw new TypeError('missing "alg" (Algorithm) Parameter value');if(e!==void 0&&e!==t.alg)throw new TypeError("JWK alg and alg option value mismatch");return k({...t,ext:n})}case"EC":case"OKP":return k({...t,alg:e,ext:n});default:throw new g('Unsupported "kty" (Key Type) Parameter value')}}function De(t,e,r,n,s){if(s.crit!==void 0&&n?.crit===void 0)throw new t('"crit" (Critical) Header Parameter MUST be integrity protected');if(!n||n.crit===void 0)return new Set;if(!Array.isArray(n.crit)||n.crit.length===0||n.crit.some(a=>typeof a!="string"||a.length===0))throw new t('"crit" (Critical) Header Parameter MUST be an array of non-empty strings when present');let i;i=e;for(const a of n.crit){if(!i.has(a))throw new g(`Extension Header Parameter "${a}" is not recognized`);if(s[a]===void 0)throw new t(`Extension Header Parameter "${a}" is missing`);if(i.get(a)&&n[a]===void 0)throw new t(`Extension Header Parameter "${a}" MUST be integrity protected`)}return new Set(n.crit)}const x=t=>A(t)&&typeof t.kty=="string",Me=t=>t.kty!=="oct"&&(t.kty==="AKP"&&typeof t.priv=="string"||typeof t.d=="string"),Oe=t=>t.kty!=="oct"&&t.d===void 0&&t.priv===void 0,xe=t=>t.kty==="oct"&&typeof t.k=="string";let C;const re=async(t,e,r,n=!1)=>{C||=new WeakMap;let s=C.get(t);if(s?.[r])return s[r];const i=await k({...e,alg:r});return n&&Object.freeze(t),s?s[r]=i:C.set(t,{[r]:i}),i},He=(t,e)=>{C||=new WeakMap;let r=C.get(t);if(r?.[e])return r[e];const n=t.type==="public",s=!!n;let i;if(t.asymmetricKeyType==="x25519"){switch(e){case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":break;default:throw new TypeError("given KeyObject instance cannot be used for this algorithm")}i=t.toCryptoKey(t.asymmetricKeyType,s,n?[]:["deriveBits"])}if(t.asymmetricKeyType==="ed25519"){if(e!=="EdDSA"&&e!=="Ed25519")throw new TypeError("given KeyObject instance cannot be used for this algorithm");i=t.toCryptoKey(t.asymmetricKeyType,s,[n?"verify":"sign"])}switch(t.asymmetricKeyType){case"ml-dsa-44":case"ml-dsa-65":case"ml-dsa-87":{if(e!==t.asymmetricKeyType.toUpperCase())throw new TypeError("given KeyObject instance cannot be used for this algorithm");i=t.toCryptoKey(t.asymmetricKeyType,s,[n?"verify":"sign"])}}if(t.asymmetricKeyType==="rsa"){let a;switch(e){case"RSA-OAEP":a="SHA-1";break;case"RS256":case"PS256":case"RSA-OAEP-256":a="SHA-256";break;case"RS384":case"PS384":case"RSA-OAEP-384":a="SHA-384";break;case"RS512":case"PS512":case"RSA-OAEP-512":a="SHA-512";break;default:throw new TypeError("given KeyObject instance cannot be used for this algorithm")}if(e.startsWith("RSA-OAEP"))return t.toCryptoKey({name:"RSA-OAEP",hash:a},s,n?["encrypt"]:["decrypt"]);i=t.toCryptoKey({name:e.startsWith("PS")?"RSA-PSS":"RSASSA-PKCS1-v1_5",hash:a},s,[n?"verify":"sign"])}if(t.asymmetricKeyType==="ec"){const c=new Map([["prime256v1","P-256"],["secp384r1","P-384"],["secp521r1","P-521"]]).get(t.asymmetricKeyDetails?.namedCurve);if(!c)throw new TypeError("given KeyObject instance cannot be used for this algorithm");e==="ES256"&&c==="P-256"&&(i=t.toCryptoKey({name:"ECDSA",namedCurve:c},s,[n?"verify":"sign"])),e==="ES384"&&c==="P-384"&&(i=t.toCryptoKey({name:"ECDSA",namedCurve:c},s,[n?"verify":"sign"])),e==="ES512"&&c==="P-521"&&(i=t.toCryptoKey({name:"ECDSA",namedCurve:c},s,[n?"verify":"sign"])),e.startsWith("ECDH-ES")&&(i=t.toCryptoKey({name:"ECDH",namedCurve:c},s,n?[]:["deriveBits"]))}if(!i)throw new TypeError("given KeyObject instance cannot be used for this algorithm");return r?r[e]=i:C.set(t,{[e]:i}),i};async function Ne(t,e){if(t instanceof Uint8Array||j(t))return t;if(ee(t)){if(t.type==="secret")return t.export();if("toCryptoKey"in t&&typeof t.toCryptoKey=="function")try{return He(t,e)}catch(n){if(n instanceof TypeError)throw n}let r=t.export({format:"jwk"});return re(t,r,e)}if(x(t))return t.k?P(t.k):re(t,t,e,!0);throw new Error("unreachable")}const _=t=>t?.[Symbol.toStringTag],H=(t,e,r)=>{if(e.use!==void 0){let n;switch(r){case"sign":case"verify":n="sig";break;case"encrypt":case"decrypt":n="enc";break}if(e.use!==n)throw new TypeError(`Invalid key for this operation, its "use" must be "${n}" when present`)}if(e.alg!==void 0&&e.alg!==t)throw new TypeError(`Invalid key for this operation, its "alg" must be "${t}" when present`);if(Array.isArray(e.key_ops)){let n;switch(!0){case r==="verify":case t==="dir":case t.includes("CBC-HS"):n=r;break;case t.startsWith("PBES2"):n="deriveBits";break;case/^A\d{3}(?:GCM)?(?:KW)?$/.test(t):!t.includes("GCM")&&t.endsWith("KW")?n="unwrapKey":n=r;break;case r==="encrypt":n="wrapKey";break;case r==="decrypt":n=t.startsWith("RSA")?"unwrapKey":"deriveBits";break}if(n&&e.key_ops?.includes?.(n)===!1)throw new TypeError(`Invalid key for this operation, its "key_ops" must include "${n}" when present`)}return!0},$e=(t,e,r)=>{if(!(e instanceof Uint8Array)){if(x(e)){if(xe(e)&&H(t,e,r))return;throw new TypeError('JSON Web Key for symmetric algorithms must have JWK "kty" (Key Type) equal to "oct" and the JWK "k" (Key Value) present')}if(!te(e))throw new TypeError(Z(t,e,"CryptoKey","KeyObject","JSON Web Key","Uint8Array"));if(e.type!=="secret")throw new TypeError(`${_(e)} instances for symmetric algorithms must be of type "secret"`)}},Le=(t,e,r)=>{if(x(e))switch(r){case"decrypt":case"sign":if(Me(e)&&H(t,e,r))return;throw new TypeError("JSON Web Key for this operation must be a private JWK");case"encrypt":case"verify":if(Oe(e)&&H(t,e,r))return;throw new TypeError("JSON Web Key for this operation must be a public JWK")}if(!te(e))throw new TypeError(Z(t,e,"CryptoKey","KeyObject","JSON Web Key"));if(e.type==="secret")throw new TypeError(`${_(e)} instances for asymmetric algorithms must not be of type "secret"`);if(e.type==="public")switch(r){case"sign":throw new TypeError(`${_(e)} instances for asymmetric algorithm signing must be of type "private"`);case"decrypt":throw new TypeError(`${_(e)} instances for asymmetric algorithm decryption must be of type "private"`)}if(e.type==="private")switch(r){case"verify":throw new TypeError(`${_(e)} instances for asymmetric algorithm verifying must be of type "public"`);case"encrypt":throw new TypeError(`${_(e)} instances for asymmetric algorithm encryption must be of type "public"`)}};function Fe(t,e,r){switch(t.substring(0,2)){case"A1":case"A2":case"di":case"HS":case"PB":$e(t,e,r);break;default:Le(t,e,r)}}function Ve(t,e){const r=`SHA-${t.slice(-3)}`;switch(t){case"HS256":case"HS384":case"HS512":return{hash:r,name:"HMAC"};case"PS256":case"PS384":case"PS512":return{hash:r,name:"RSA-PSS",saltLength:parseInt(t.slice(-3),10)>>3};case"RS256":case"RS384":case"RS512":return{hash:r,name:"RSASSA-PKCS1-v1_5"};case"ES256":case"ES384":case"ES512":return{hash:r,name:"ECDSA",namedCurve:e.namedCurve};case"Ed25519":case"EdDSA":return{name:"Ed25519"};case"ML-DSA-44":case"ML-DSA-65":case"ML-DSA-87":return{name:t};default:throw new g(`alg ${t} is not supported either by JOSE or your javascript runtime`)}}async function Ge(t,e,r){if(e instanceof Uint8Array){if(!t.startsWith("HS"))throw new TypeError(Pe(e,"CryptoKey","KeyObject","JSON Web Key"));return crypto.subtle.importKey("raw",e,{hash:`SHA-${t.slice(-3)}`,name:"HMAC"},!1,[r])}return Re(e,t,r),e}async function ze(t,e,r,n){const s=await Ge(t,e,"verify");Ie(t,s);const i=Ve(t,s.algorithm);try{return await crypto.subtle.verify(i,s,r,n)}catch{return!1}}async function Be(t,e,r){if(!A(t))throw new h("Flattened JWS must be an object");if(t.protected===void 0&&t.header===void 0)throw new h('Flattened JWS must have either of the "protected" or "header" members');if(t.protected!==void 0&&typeof t.protected!="string")throw new h("JWS Protected Header incorrect type");if(t.payload===void 0)throw new h("JWS Payload missing");if(typeof t.signature!="string")throw new h("JWS Signature missing or incorrect type");if(t.header!==void 0&&!A(t.header))throw new h("JWS Unprotected Header incorrect type");let n={};if(t.protected)try{const G=P(t.protected);n=JSON.parse(R.decode(G))}catch{throw new h("JWS Protected Header is invalid")}if(!ke(n,t.header))throw new h("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");const s={...n,...t.header},i=De(h,new Map([["b64",!0]]),r?.crit,n,s);let a=!0;if(i.has("b64")&&(a=n.b64,typeof a!="boolean"))throw new h('The "b64" (base64url-encode payload) Header Parameter must be a boolean');const{alg:c}=s;if(typeof c!="string"||!c)throw new h('JWS "alg" (Algorithm) Header Parameter missing or invalid');if(a){if(typeof t.payload!="string")throw new h("JWS Payload must be a string")}else if(typeof t.payload!="string"&&!(t.payload instanceof Uint8Array))throw new h("JWS Payload must be a string or an Uint8Array instance");let f=!1;typeof e=="function"&&(e=await e(n,t),f=!0),Fe(c,e,"verify");const u=Ee(t.protected!==void 0?M(t.protected):new Uint8Array,M("."),typeof t.payload=="string"?a?M(t.payload):z.encode(t.payload):t.payload);let o;try{o=P(t.signature)}catch{throw new h("Failed to base64url decode the signature")}const p=await Ne(e,c);if(!await ze(c,p,o,u))throw new ve;let K;if(a)try{K=P(t.payload)}catch{throw new h("Failed to base64url decode the payload")}else typeof t.payload=="string"?K=z.encode(t.payload):K=t.payload;const y={payload:K};return t.protected!==void 0&&(y.protectedHeader=n),t.header!==void 0&&(y.unprotectedHeader=t.header),f?{...y,key:p}:y}async function qe(t,e,r){if(t instanceof Uint8Array&&(t=R.decode(t)),typeof t!="string")throw new h("Compact JWS must be a string or Uint8Array");const{0:n,1:s,2:i,length:a}=t.split(".");if(a!==3)throw new h("Invalid Compact JWS");const c=await Be({payload:s,protected:n,signature:i},e,r),f={payload:c.payload,protectedHeader:c.protectedHeader};return typeof e=="function"?{...f,key:c.key}:f}const Ye=t=>Math.floor(t.getTime()/1e3),ne=60,se=ne*60,N=se*24,Xe=N*7,Qe=N*365.25,Ze=/^(\+|\-)? ?(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)(?: (ago|from now))?$/i;function ie(t){const e=Ze.exec(t);if(!e||e[4]&&e[1])throw new TypeError("Invalid time period format");const r=parseFloat(e[2]),n=e[3].toLowerCase();let s;switch(n){case"sec":case"secs":case"second":case"seconds":case"s":s=Math.round(r);break;case"minute":case"minutes":case"min":case"mins":case"m":s=Math.round(r*ne);break;case"hour":case"hours":case"hr":case"hrs":case"h":s=Math.round(r*se);break;case"day":case"days":case"d":s=Math.round(r*N);break;case"week":case"weeks":case"w":s=Math.round(r*Xe);break;default:s=Math.round(r*Qe);break}return e[1]==="-"||e[4]==="ago"?-s:s}const ae=t=>t.includes("/")?t.toLowerCase():`application/${t.toLowerCase()}`,je=(t,e)=>typeof t=="string"?e.includes(t):Array.isArray(t)?e.some(Set.prototype.has.bind(new Set(t))):!1;function et(t,e,r={}){let n;try{n=JSON.parse(R.decode(e))}catch{}if(!A(n))throw new q("JWT Claims Set must be a top-level JSON object");const{typ:s}=r;if(s&&(typeof t.typ!="string"||ae(t.typ)!==ae(s)))throw new S('unexpected "typ" JWT header value',n,"typ","check_failed");const{requiredClaims:i=[],issuer:a,subject:c,audience:f,maxTokenAge:u}=r,o=[...i];u!==void 0&&o.push("iat"),f!==void 0&&o.push("aud"),c!==void 0&&o.push("sub"),a!==void 0&&o.push("iss");for(const y of new Set(o.reverse()))if(!(y in n))throw new S(`missing required "${y}" claim`,n,y,"missing");if(a&&!(Array.isArray(a)?a:[a]).includes(n.iss))throw new S('unexpected "iss" claim value',n,"iss","check_failed");if(c&&n.sub!==c)throw new S('unexpected "sub" claim value',n,"sub","check_failed");if(f&&!je(n.aud,typeof f=="string"?[f]:f))throw new S('unexpected "aud" claim value',n,"aud","check_failed");let p;switch(typeof r.clockTolerance){case"string":p=ie(r.clockTolerance);break;case"number":p=r.clockTolerance;break;case"undefined":p=0;break;default:throw new TypeError("Invalid clockTolerance option type")}const{currentDate:le}=r,K=Ye(le||new Date);if((n.iat!==void 0||u)&&typeof n.iat!="number")throw new S('"iat" claim must be a number',n,"iat","invalid");if(n.nbf!==void 0){if(typeof n.nbf!="number")throw new S('"nbf" claim must be a number',n,"nbf","invalid");if(n.nbf>K+p)throw new S('"nbf" claim timestamp check failed',n,"nbf","check_failed")}if(n.exp!==void 0){if(typeof n.exp!="number")throw new S('"exp" claim must be a number',n,"exp","invalid");if(n.exp<=K-p)throw new B('"exp" claim timestamp check failed',n,"exp","check_failed")}if(u){const y=K-n.iat,G=typeof u=="number"?u:ie(u);if(y-p>G)throw new B('"iat" claim timestamp check failed (too far in the past)',n,"iat","check_failed");if(y<0-p)throw new S('"iat" claim timestamp check failed (it should be in the past)',n,"iat","check_failed")}return n}async function tt(t,e,r){const n=await qe(t,e,r);if(n.protectedHeader.crit?.includes("b64")&&n.protectedHeader.b64===!1)throw new q("JWTs MUST NOT use unencoded payload");const i={payload:et(n.protectedHeader,n.payload,r),protectedHeader:n.protectedHeader};return typeof e=="function"?{...i,key:n.key}:i}function rt(t){switch(typeof t=="string"&&t.slice(0,2)){case"RS":case"PS":return"RSA";case"ES":return"EC";case"Ed":return"OKP";case"ML":return"AKP";default:throw new g('Unsupported "alg" value for a JSON Web Key Set')}}function nt(t){return t&&typeof t=="object"&&Array.isArray(t.keys)&&t.keys.every(st)}function st(t){return A(t)}class it{#r;#a=new WeakMap;constructor(e){if(!nt(e))throw new Y("JSON Web Key Set malformed");this.#r=structuredClone(e)}jwks(){return this.#r}async getKey(e,r){const{alg:n,kid:s}={...e,...r?.header},i=rt(n),a=this.#r.keys.filter(u=>{let o=i===u.kty;if(o&&typeof s=="string"&&(o=s===u.kid),o&&(typeof u.alg=="string"||i==="AKP")&&(o=n===u.alg),o&&typeof u.use=="string"&&(o=u.use==="sig"),o&&Array.isArray(u.key_ops)&&(o=u.key_ops.includes("verify")),o)switch(n){case"ES256":o=u.crv==="P-256";break;case"ES384":o=u.crv==="P-384";break;case"ES512":o=u.crv==="P-521";break;case"Ed25519":case"EdDSA":o=u.crv==="Ed25519";break}return o}),{0:c,length:f}=a;if(f===0)throw new X;if(f!==1){const u=new Ke,o=this.#a;throw u[Symbol.asyncIterator]=async function*(){for(const p of a)try{yield await oe(o,p,n)}catch{}},u}return oe(this.#a,c,n)}}async function oe(t,e,r){const n=t.get(e)||t.set(e,{}).get(e);if(n[r]===void 0){const s=await Ue({...e,ext:!0},r);if(s instanceof Uint8Array||s.type!=="public")throw new Y("JSON Web Key Set members must be public keys");n[r]=s}return n[r]}function ce(t){const e=new it(t),r=async(n,s)=>e.getKey(n,s);return Object.defineProperties(r,{jwks:{value:()=>structuredClone(e.jwks()),enumerable:!1,configurable:!1,writable:!1}}),r}function at(){return typeof WebSocketPair<"u"||typeof navigator<"u"&&navigator.userAgent==="Cloudflare-Workers"||typeof EdgeRuntime<"u"&&EdgeRuntime==="vercel"}let $;(typeof navigator>"u"||!navigator.userAgent?.startsWith?.("Mozilla/5.0 "))&&($="jose/v6.1.3");const ot=Symbol();async function ct(t,e,r,n=fetch){const s=await n(t,{method:"GET",signal:r,redirect:"manual",headers:e}).catch(i=>{throw i.name==="TimeoutError"?new Te:i});if(s.status!==200)throw new l("Expected 200 OK from the JSON Web Key Set HTTP response");try{return await s.json()}catch{throw new l("Failed to parse the JSON Web Key Set HTTP response as JSON")}}const L=Symbol();function ut(t,e){return!(typeof t!="object"||t===null||!("uat"in t)||typeof t.uat!="number"||Date.now()-t.uat>=e||!("jwks"in t)||!A(t.jwks)||!Array.isArray(t.jwks.keys)||!Array.prototype.every.call(t.jwks.keys,A))}class ht{#r;#a;#c;#o;#n;#e;#t;#u;#s;#i;constructor(e,r){if(!(e instanceof URL))throw new TypeError("url must be an instance of URL");this.#r=new URL(e.href),this.#a=typeof r?.timeoutDuration=="number"?r?.timeoutDuration:5e3,this.#c=typeof r?.cooldownDuration=="number"?r?.cooldownDuration:3e4,this.#o=typeof r?.cacheMaxAge=="number"?r?.cacheMaxAge:6e5,this.#t=new Headers(r?.headers),$&&!this.#t.has("User-Agent")&&this.#t.set("User-Agent",$),this.#t.has("accept")||(this.#t.set("accept","application/json"),this.#t.append("accept","application/jwk-set+json")),this.#u=r?.[ot],r?.[L]!==void 0&&(this.#i=r?.[L],ut(r?.[L],this.#o)&&(this.#n=this.#i.uat,this.#s=ce(this.#i.jwks)))}pendingFetch(){return!!this.#e}coolingDown(){return typeof this.#n=="number"?Date.now()<this.#n+this.#c:!1}fresh(){return typeof this.#n=="number"?Date.now()<this.#n+this.#o:!1}jwks(){return this.#s?.jwks()}async getKey(e,r){(!this.#s||!this.fresh())&&await this.reload();try{return await this.#s(e,r)}catch(n){if(n instanceof X&&this.coolingDown()===!1)return await this.reload(),this.#s(e,r);throw n}}async reload(){this.#e&&at()&&(this.#e=void 0),this.#e||=ct(this.#r.href,this.#t,AbortSignal.timeout(this.#a),this.#u).then(e=>{this.#s=ce(e),this.#i&&(this.#i.uat=Date.now(),this.#i.jwks=e),this.#n=Date.now(),this.#e=void 0}).catch(e=>{throw this.#e=void 0,e}),await this.#e}}function ft(t,e){const r=new ht(t,e),n=async(s,i)=>r.getKey(s,i);return Object.defineProperties(n,{coolingDown:{get:()=>r.coolingDown(),enumerable:!0,configurable:!1},fresh:{get:()=>r.fresh(),enumerable:!0,configurable:!1},reload:{value:()=>r.reload(),enumerable:!0,configurable:!1,writable:!1},reloading:{get:()=>r.pendingFetch(),enumerable:!0,configurable:!1},jwks:{value:()=>r.jwks(),enumerable:!0,configurable:!1,writable:!1}}),n}class dt{jwksUrl;JWKS;constructor(e){this.jwksUrl=e,this.JWKS=ft(new URL(this.jwksUrl))}async verify(e){return tt(e,this.JWKS)}}class ue{store=new Map;async get(e){return this.store.get(e)??null}async set(e,r){this.store.set(e,r)}async remove(e){this.store.delete(e)}async clear(){this.store.clear()}}class F{prefix;constructor(e="genation"){this.prefix=e}getKey(e){return`${this.prefix}:${e}`}async get(e){return typeof window>"u"?null:localStorage.getItem(this.getKey(e))}async set(e,r){typeof window>"u"||localStorage.setItem(this.getKey(e),r)}async remove(e){typeof window>"u"||localStorage.removeItem(this.getKey(e))}async clear(){if(typeof window>"u")return;Object.keys(localStorage).filter(r=>r.startsWith(`${this.prefix}:`)).forEach(r=>localStorage.removeItem(r))}}class he{prefix;constructor(e="genation"){this.prefix=e}getKey(e){return`${this.prefix}:${e}`}async get(e){return typeof window>"u"?null:sessionStorage.getItem(this.getKey(e))}async set(e,r){typeof window>"u"||sessionStorage.setItem(this.getKey(e),r)}async remove(e){typeof window>"u"||sessionStorage.removeItem(this.getKey(e))}async clear(){if(typeof window>"u")return;Object.keys(sessionStorage).filter(r=>r.startsWith(`${this.prefix}:`)).forEach(r=>sessionStorage.removeItem(r))}}function fe(t="localStorage"){switch(t){case"memory":return new ue;case"localStorage":return new F;case"sessionStorage":return new he;default:return new F}}function V(t){return Array.isArray(t)?t.map(V):typeof t=="object"&&t!==null?Object.fromEntries(Object.entries(t).map(([e,r])=>[e.replace(/_([a-z])/g,(n,s)=>s.toUpperCase()),V(r)])):t}class de{oauth;tokenManager;tokenVerifier;http;httpServer;listeners=new Set;initialized=!1;constructor(e){this.validateConfig(e);const r=typeof e.storage=="object"?e.storage:fe(e.storage),n=e.authUrl??"https://mnnoheowoowbtpuoguul.supabase.co/auth/v1";this.tokenManager=new Se(r),this.oauth=new be(e,this.tokenManager),this.tokenVerifier=new dt(`${n}/.well-known/jwks.json`),this.http=new W({baseUrl:n}),this.httpServer=new W({baseUrl:"https://ff-api.genation.ai/api/v2/client"})}validateConfig(e){if(!e.clientId)throw T.missingField("clientId");if(!e.clientSecret)throw T.missingField("clientSecret");if(!e.redirectUri)throw T.missingField("redirectUri")}async emitAuthStateChange(e){const r=await this.getSession();this.listeners.forEach(n=>{try{n(e,r)}catch(s){console.error("Error in auth state change callback:",s)}})}onAuthStateChange(e){return this.listeners.add(e),this.initialized?setTimeout(()=>{this.emitAuthStateChange("INITIAL_SESSION")},0):(this.initialized=!0,setTimeout(()=>{this.emitAuthStateChange("INITIAL_SESSION")},0)),{subscription:{unsubscribe:()=>{this.listeners.delete(e)}}}}async signIn(){return this.oauth.getAuthorizationUrl()}async handleCallback(e){const r=new URL(e),n=r.searchParams.get("code"),s=r.searchParams.get("state");if(!n||!s)throw new Error("Missing code or state");const i=await this.oauth.exchangeCode(n,s);return await this.emitAuthStateChange("SIGNED_IN"),i}async signOut(){await this.tokenManager.clearTokens(),await this.emitAuthStateChange("SIGNED_OUT")}async getSession(){if(await this.tokenManager.isTokenExpired())try{await this.oauth.refreshToken()}catch{return null}const r=await this.tokenManager.getTokens();if(!r)return null;const n=await this.fetchUser(r.accessToken);return{accessToken:r.accessToken,refreshToken:r.refreshToken,expiresIn:r.expiresIn,expiresAt:r.issuedAt+r.expiresIn*1e3,user:n}}async verifyToken(e){const{payload:r}=await this.tokenVerifier.verify(e);return r}async getLicenses(e={}){const r=await this.getSession();if(!r)return null;const n=r.accessToken,{expiresAfter:s=new Date}=e,i=await this.httpServer.request("/licenses",{headers:{Authorization:`Bearer ${n}`},params:{expiresAfter:s.toISOString()}});return i.ok?V(i.data):(console.error("GenationClient: Error fetching licenses:",i.error),null)}async fetchUser(e){try{const r=await this.http.request("/oauth/userinfo",{headers:{Authorization:`Bearer ${e}`}});return{sub:r.sub,name:r.name,picture:r.picture,email:r.email,email_verified:r.email_verified,phone_number:r.phone_number,phone_number_verified:r.phone_number_verified}}catch(r){return console.error("GenationClient: Error fetching user:",r),null}}}function lt(t){return new de(t)}d.AuthError=m,d.ConfigError=T,d.GenationClient=de,d.GenationError=E,d.LocalStorage=F,d.MemoryStorage=ue,d.NetworkError=w,d.SessionStorage=he,d.createClient=lt,d.createStorage=fe,Object.defineProperty(d,Symbol.toStringTag,{value:"Module"})}));
|
|
2
2
|
//# sourceMappingURL=genation.umd.js.map
|