@leancodepl/kratos 9.7.4 → 10.0.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.
@@ -1 +1 @@
1
- (function(A,u){typeof exports=="object"&&typeof module<"u"?u(exports,require("react/jsx-runtime"),require("react")):typeof define=="function"&&define.amd?define(["exports","react/jsx-runtime","react"],u):(A=typeof globalThis<"u"?globalThis:A||self,u(A["@leancodepl/kratos"]={},A.jsxRuntime,A.React))})(this,(function(A,u,g){"use strict";function zi(e){const t=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(e){for(const n in e)if(n!=="default"){const i=Object.getOwnPropertyDescriptor(e,n);Object.defineProperty(t,n,i.get?i:{enumerable:!0,get:()=>e[n]})}}return t.default=e,Object.freeze(t)}const E=zi(g);var ie=(e=>(e[e.NoFlowId=0]="NoFlowId",e[e.FlowRestartRequired=1]="FlowRestartRequired",e))(ie||{});const cn=g.createContext(void 0);function St(){const e=g.useContext(cn);if(e===void 0)throw new Error("useKratosSessionContext must be used within a KratosSessionContextProvider");return e}function Gi({children:e,sessionManager:t}){const n=g.useMemo(()=>({sessionManager:t}),[t]);return u.jsx(cn.Provider,{value:n,children:e})}const be=({initialFlowId:e,currentFlowId:t,error:n,onFlowRestart:i,createFlow:r,setFlowId:o,waitForSession:s})=>{const[a,l]=g.useState(!1),[d,h]=g.useState(e),{sessionManager:c}=St(),{isLoading:f}=c.useSession();d!==e&&(l(!1),h(e));const m=!!s&&f;g.useEffect(()=>{t||m||(e&&!a?(o(e),l(!0)):r())},[r,t,e,a,o,m]),g.useEffect(()=>{n&&n.cause===ie.FlowRestartRequired&&(r(),i?.())},[r,n,i])},me="traits.";function un(e){return"type"in e&&e.type==="public-key"&&"id"in e&&"rawId"in e&&"response"in e}function Qi(e){return"attestationObject"in e&&"clientDataJSON"in e}function Hi(e){return"authenticatorData"in e&&"clientDataJSON"in e&&"signature"in e}function Ae(e){return Uint8Array.from(atob(e.replaceAll("-","+").replaceAll("_","/")),function(t){return t.charCodeAt(0)})}function re(e){return btoa(String.fromCharCode(...new Uint8Array(e))).replaceAll("+","-").replaceAll("/","_").replaceAll("=","")}function dn(e){if(!e||!un(e))return;const{response:t,id:n,rawId:i}=e;if(Qi(t))return JSON.stringify({id:n,rawId:re(i),type:e.type,response:{attestationObject:re(t.attestationObject),clientDataJSON:re(t.clientDataJSON)}})}async function fn({credentialOptions:e,signal:t,userName:n,userDisplayName:i}){return await navigator.credentials.create({signal:t,publicKey:{challenge:Ae(e.publicKey.challenge),timeout:e.publicKey.timeout,rp:{id:e.publicKey.rp.id,name:e.publicKey.rp.name},user:{id:Ae(e.publicKey.user.id),name:n,displayName:i},pubKeyCredParams:e.publicKey.pubKeyCredParams}})}function hn(e){if(!e||!un(e))return;const{response:t,id:n,rawId:i}=e;if(!Hi(t))return;const{userHandle:r,authenticatorData:o,clientDataJSON:s,signature:a}=t;return JSON.stringify({id:n,rawId:re(i),type:e.type,response:{authenticatorData:re(o),clientDataJSON:re(s),signature:re(a),userHandle:r?re(r):void 0}})}async function Xi({challengeOptions:e,signal:t}){return await navigator.credentials.get({signal:t,publicKey:{challenge:Ae(e.publicKey.challenge),timeout:e.publicKey.timeout,rpId:e.publicKey.rpId,userVerification:e.publicKey.userVerification}})}function Zi(){return!!globalThis.PublicKeyCredential}async function Yi(e,t){const n=JSON.parse(e);if(Zi()&&globalThis.PublicKeyCredential.isConditionalMediationAvailable&&await globalThis.PublicKeyCredential.isConditionalMediationAvailable())try{const i=await navigator.credentials.get({mediation:"conditional",signal:t,publicKey:{challenge:Ae(n.publicKey.challenge),timeout:n.publicKey.timeout,rpId:n.publicKey.rpId,userVerification:n.publicKey.userVerification}});return hn(i)}catch{return}}async function ji(e,t){const n=JSON.parse(e);try{return hn(await Xi({challengeOptions:n,signal:t}))}catch{return}}async function er(e,t,n){const{credentialOptions:i,displayNameFieldName:r}=JSON.parse(e),o=r.startsWith(me)?r.slice(me.length):r,s=typeof n?.[o]=="string"?n[o]:"";try{return dn(await fn({credentialOptions:i,signal:t,userName:s,userDisplayName:s}))}catch{return}}async function tr(e,t){const n=JSON.parse(e);try{return dn(await fn({credentialOptions:n,signal:t,userName:n.publicKey.user.name,userDisplayName:n.publicKey.user.displayName}))}catch{return}}const F=(e,t,n)=>e!==void 0&&t in e&&typeof e[t]===n,nr="https://playground.projects.oryapis.com".replace(/\/+$/,"");class pn{constructor(t={}){this.configuration=t}set config(t){this.configuration=t}get basePath(){return this.configuration.basePath!=null?this.configuration.basePath:nr}get fetchApi(){return this.configuration.fetchApi}get middleware(){return this.configuration.middleware||[]}get queryParamsStringify(){return this.configuration.queryParamsStringify||mn}get username(){return this.configuration.username}get password(){return this.configuration.password}get apiKey(){const t=this.configuration.apiKey;if(t)return typeof t=="function"?t:()=>t}get accessToken(){const t=this.configuration.accessToken;if(t)return typeof t=="function"?t:async()=>t}get headers(){return this.configuration.headers}get credentials(){return this.configuration.credentials}}const ir=new pn;class bt{constructor(t=ir){this.configuration=t,this.middleware=t.middleware}static jsonRegex=new RegExp("^(:?application/json|[^;/ ]+/[^;/ ]+[+]json)[ ]*(:?;.*)?$","i");middleware;withMiddleware(...t){const n=this.clone();return n.middleware=n.middleware.concat(...t),n}withPreMiddleware(...t){const n=t.map(i=>({pre:i}));return this.withMiddleware(...n)}withPostMiddleware(...t){const n=t.map(i=>({post:i}));return this.withMiddleware(...n)}isJsonMime(t){return t?bt.jsonRegex.test(t):!1}async request(t,n){const{url:i,init:r}=await this.createFetchParams(t,n),o=await this.fetchApi(i,r);if(o&&o.status>=200&&o.status<300)return o;throw new ge(o,"Response returned an error code")}async createFetchParams(t,n){let i=this.configuration.basePath+t.path;t.query!==void 0&&Object.keys(t.query).length!==0&&(i+="?"+this.configuration.queryParamsStringify(t.query));const r=Object.assign({},this.configuration.headers,t.headers);Object.keys(r).forEach(h=>r[h]===void 0?delete r[h]:{});const o=typeof n=="function"?n:async()=>n,s={method:t.method,headers:r,body:t.body,credentials:this.configuration.credentials},a={...s,...await o({init:s,context:t})};let l;or(a.body)||a.body instanceof URLSearchParams||rr(a.body)?l=a.body:this.isJsonMime(r["Content-Type"])?l=JSON.stringify(a.body):l=a.body;const d={...a,body:l};return{url:i,init:d}}fetchApi=async(t,n)=>{let i={url:t,init:n};for(const o of this.middleware)o.pre&&(i=await o.pre({fetch:this.fetchApi,...i})||i);let r;try{r=await(this.configuration.fetchApi||fetch)(i.url,i.init)}catch(o){for(const s of this.middleware)s.onError&&(r=await s.onError({fetch:this.fetchApi,url:i.url,init:i.init,error:o,response:r?r.clone():void 0})||r);if(r===void 0)throw o instanceof Error?new kt(o,"The request failed and the interceptors did not return an alternative response"):o}for(const o of this.middleware)o.post&&(r=await o.post({fetch:this.fetchApi,url:i.url,init:i.init,response:r.clone()})||r);return r};clone(){const t=this.constructor,n=new t(this.configuration);return n.middleware=this.middleware.slice(),n}}function rr(e){return typeof Blob<"u"&&e instanceof Blob}function or(e){return typeof FormData<"u"&&e instanceof FormData}class ge extends Error{constructor(t,n){super(n),this.response=t}name="ResponseError"}class kt extends Error{constructor(t,n){super(n),this.cause=t}name="FetchError"}class V extends Error{constructor(t,n){super(n),this.field=t}name="RequiredError"}function mn(e,t=""){return Object.keys(e).map(n=>gn(n,e[n],t)).filter(n=>n.length>0).join("&")}function gn(e,t,n=""){const i=n+(n.length?`[${e}]`:e);if(t instanceof Array){const r=t.map(o=>encodeURIComponent(String(o))).join(`&${encodeURIComponent(i)}=`);return`${encodeURIComponent(i)}=${r}`}if(t instanceof Set){const r=Array.from(t);return gn(e,r,n)}return t instanceof Date?`${encodeURIComponent(i)}=${encodeURIComponent(t.toISOString())}`:t instanceof Object?mn(t,i):`${encodeURIComponent(i)}=${encodeURIComponent(String(t))}`}function sr(e,t){return Object.keys(e).reduce((n,i)=>({...n,[i]:t(e[i])}),{})}class M{constructor(t,n=i=>i){this.raw=t,this.transformer=n}async value(){return this.transformer(await this.raw.json())}}class Ct{constructor(t){this.raw=t}async value(){}}class ar{constructor(t){this.raw=t}async value(){return await this.raw.text()}}function Tt(e){return lr(e)}function lr(e,t){return e}function cr(e){return ur(e)}function ur(e,t){return e==null?e:{id:e.id,url:e.url==null?void 0:e.url}}function dr(e,t){return e==null?e:{action:e.action,flow:cr(e.flow)}}function fr(e,t){return e==null?e:{action:e.action,redirect_browser_to:e.redirect_browser_to}}function hr(e,t){return e==null?e:{action:e.action,ory_session_token:e.ory_session_token}}function pr(e){return mr(e)}function mr(e,t){return e==null?e:{id:e.id,url:e.url==null?void 0:e.url}}function gr(e,t){return e==null?e:{action:e.action,flow:pr(e.flow)}}function wr(e){return yr(e)}function yr(e,t){return e==null?e:{id:e.id,url:e.url==null?void 0:e.url,verifiable_address:e.verifiable_address}}function _r(e,t){return e==null?e:{action:e.action,flow:wr(e.flow)}}function Pe(e){return vr(e)}function vr(e,t){if(e==null)return e;switch(e.action){case"redirect_browser_to":return Object.assign({},fr(e),{action:"redirect_browser_to"});case"set_ory_session_token":return Object.assign({},hr(e),{action:"set_ory_session_token"});case"show_recovery_ui":return Object.assign({},dr(e),{action:"show_recovery_ui"});case"show_settings_ui":return Object.assign({},gr(e),{action:"show_settings_ui"});case"show_verification_ui":return Object.assign({},_r(e),{action:"show_verification_ui"});default:throw new Error(`No variant of ContinueWith exists with 'action=${e.action}'`)}}function Fr(e){return Sr(e)}function Sr(e,t){return e==null?e:{client_id:e.client_id==null?void 0:e.client_id,config_url:e.config_url==null?void 0:e.config_url,domain_hint:e.domain_hint==null?void 0:e.domain_hint,fields:e.fields==null?void 0:e.fields,login_hint:e.login_hint==null?void 0:e.login_hint,nonce:e.nonce==null?void 0:e.nonce,parameters:e.parameters==null?void 0:e.parameters}}function br(e){return kr(e)}function kr(e,t){return e==null?e:{csrf_token:e.csrf_token==null?void 0:e.csrf_token,providers:e.providers==null?void 0:e.providers.map(Fr)}}function Cr(e){return Tr(e)}function Tr(e,t){return e==null?e:{created_at:e.created_at==null?void 0:new Date(e.created_at),id:e.id==null?void 0:e.id,status:e.status,updated_at:e.updated_at==null?void 0:new Date(e.updated_at),value:e.value,verified:e.verified,verified_at:e.verified_at==null?void 0:new Date(e.verified_at),via:e.via}}function Er(e){return Mr(e)}function Mr(e,t){return e==null?e:{created_at:e.created_at==null?void 0:new Date(e.created_at),id:e.id,updated_at:e.updated_at==null?void 0:new Date(e.updated_at),value:e.value,via:e.via}}function Or(e){return xr(e)}function xr(e,t){return e==null?e:{count:e.count==null?void 0:e.count}}function Vr(e){return Ir(e)}function Ir(e,t){return e==null?e:{created_at:e.created_at==null?void 0:new Date(e.created_at),error:e.error==null?void 0:e.error,id:e.id,updated_at:e.updated_at==null?void 0:new Date(e.updated_at)}}function Nr(e){return Lr(e)}function Lr(e,t){return e==null?e:{config:e.config==null?void 0:e.config,created_at:e.created_at==null?void 0:new Date(e.created_at),identifiers:e.identifiers==null?void 0:e.identifiers,type:e.type==null?void 0:e.type,updated_at:e.updated_at==null?void 0:new Date(e.updated_at),version:e.version==null?void 0:e.version}}function Et(e){return Dr(e)}function Dr(e,t){return e==null?e:{created_at:e.created_at==null?void 0:new Date(e.created_at),credentials:e.credentials==null?void 0:sr(e.credentials,Nr),id:e.id,metadata_admin:e.metadata_admin==null?void 0:e.metadata_admin,metadata_public:e.metadata_public==null?void 0:e.metadata_public,organization_id:e.organization_id==null?void 0:e.organization_id,recovery_addresses:e.recovery_addresses==null?void 0:e.recovery_addresses.map(Er),schema_id:e.schema_id,schema_url:e.schema_url,state:e.state==null?void 0:e.state,state_changed_at:e.state_changed_at==null?void 0:new Date(e.state_changed_at),traits:e.traits,updated_at:e.updated_at==null?void 0:new Date(e.updated_at),verifiable_addresses:e.verifiable_addresses==null?void 0:e.verifiable_addresses.map(Cr)}}function Ar(e){return Pr(e)}function Pr(e,t){return e==null?e:{acr_values:e.acr_values==null?void 0:e.acr_values,display:e.display==null?void 0:e.display,id_token_hint_claims:e.id_token_hint_claims==null?void 0:e.id_token_hint_claims,login_hint:e.login_hint==null?void 0:e.login_hint,ui_locales:e.ui_locales==null?void 0:e.ui_locales}}function Ur(e){return Rr(e)}function Rr(e,t){return e==null?e:{access_token_strategy:e.access_token_strategy==null?void 0:e.access_token_strategy,allowed_cors_origins:e.allowed_cors_origins==null?void 0:e.allowed_cors_origins,audience:e.audience==null?void 0:e.audience,authorization_code_grant_access_token_lifespan:e.authorization_code_grant_access_token_lifespan==null?void 0:e.authorization_code_grant_access_token_lifespan,authorization_code_grant_id_token_lifespan:e.authorization_code_grant_id_token_lifespan==null?void 0:e.authorization_code_grant_id_token_lifespan,authorization_code_grant_refresh_token_lifespan:e.authorization_code_grant_refresh_token_lifespan==null?void 0:e.authorization_code_grant_refresh_token_lifespan,backchannel_logout_session_required:e.backchannel_logout_session_required==null?void 0:e.backchannel_logout_session_required,backchannel_logout_uri:e.backchannel_logout_uri==null?void 0:e.backchannel_logout_uri,client_credentials_grant_access_token_lifespan:e.client_credentials_grant_access_token_lifespan==null?void 0:e.client_credentials_grant_access_token_lifespan,client_id:e.client_id==null?void 0:e.client_id,client_name:e.client_name==null?void 0:e.client_name,client_secret:e.client_secret==null?void 0:e.client_secret,client_secret_expires_at:e.client_secret_expires_at==null?void 0:e.client_secret_expires_at,client_uri:e.client_uri==null?void 0:e.client_uri,contacts:e.contacts==null?void 0:e.contacts,created_at:e.created_at==null?void 0:new Date(e.created_at),frontchannel_logout_session_required:e.frontchannel_logout_session_required==null?void 0:e.frontchannel_logout_session_required,frontchannel_logout_uri:e.frontchannel_logout_uri==null?void 0:e.frontchannel_logout_uri,grant_types:e.grant_types==null?void 0:e.grant_types,implicit_grant_access_token_lifespan:e.implicit_grant_access_token_lifespan==null?void 0:e.implicit_grant_access_token_lifespan,implicit_grant_id_token_lifespan:e.implicit_grant_id_token_lifespan==null?void 0:e.implicit_grant_id_token_lifespan,jwks:e.jwks==null?void 0:e.jwks,jwks_uri:e.jwks_uri==null?void 0:e.jwks_uri,jwt_bearer_grant_access_token_lifespan:e.jwt_bearer_grant_access_token_lifespan==null?void 0:e.jwt_bearer_grant_access_token_lifespan,logo_uri:e.logo_uri==null?void 0:e.logo_uri,metadata:e.metadata==null?void 0:e.metadata,owner:e.owner==null?void 0:e.owner,policy_uri:e.policy_uri==null?void 0:e.policy_uri,post_logout_redirect_uris:e.post_logout_redirect_uris==null?void 0:e.post_logout_redirect_uris,redirect_uris:e.redirect_uris==null?void 0:e.redirect_uris,refresh_token_grant_access_token_lifespan:e.refresh_token_grant_access_token_lifespan==null?void 0:e.refresh_token_grant_access_token_lifespan,refresh_token_grant_id_token_lifespan:e.refresh_token_grant_id_token_lifespan==null?void 0:e.refresh_token_grant_id_token_lifespan,refresh_token_grant_refresh_token_lifespan:e.refresh_token_grant_refresh_token_lifespan==null?void 0:e.refresh_token_grant_refresh_token_lifespan,registration_access_token:e.registration_access_token==null?void 0:e.registration_access_token,registration_client_uri:e.registration_client_uri==null?void 0:e.registration_client_uri,request_object_signing_alg:e.request_object_signing_alg==null?void 0:e.request_object_signing_alg,request_uris:e.request_uris==null?void 0:e.request_uris,response_types:e.response_types==null?void 0:e.response_types,scope:e.scope==null?void 0:e.scope,sector_identifier_uri:e.sector_identifier_uri==null?void 0:e.sector_identifier_uri,skip_consent:e.skip_consent==null?void 0:e.skip_consent,skip_logout_consent:e.skip_logout_consent==null?void 0:e.skip_logout_consent,subject_type:e.subject_type==null?void 0:e.subject_type,token_endpoint_auth_method:e.token_endpoint_auth_method==null?void 0:e.token_endpoint_auth_method,token_endpoint_auth_signing_alg:e.token_endpoint_auth_signing_alg==null?void 0:e.token_endpoint_auth_signing_alg,tos_uri:e.tos_uri==null?void 0:e.tos_uri,updated_at:e.updated_at==null?void 0:new Date(e.updated_at),userinfo_signed_response_alg:e.userinfo_signed_response_alg==null?void 0:e.userinfo_signed_response_alg}}function wn(e){return Jr(e)}function Jr(e,t){return e==null?e:{challenge:e.challenge,client:Ur(e.client),oidc_context:e.oidc_context==null?void 0:Ar(e.oidc_context),request_url:e.request_url,requested_access_token_audience:e.requested_access_token_audience==null?void 0:e.requested_access_token_audience,requested_scope:e.requested_scope==null?void 0:e.requested_scope,session_id:e.session_id==null?void 0:e.session_id,skip:e.skip,subject:e.subject}}const Wr={Error:"error"};function Br(e){return!(!("id"in e)||e.id===void 0||!("text"in e)||e.text===void 0||!("type"in e)||e.type===void 0)}function we(e){return $r(e)}function $r(e,t){return e==null?e:{context:e.context==null?void 0:e.context,id:e.id,text:e.text,type:e.type}}function qr(e){return Kr(e)}function Kr(e,t){return e==null?e:{label:e.label==null?void 0:we(e.label)}}function zr(e,t){return e==null?e:{href:e.href,id:e.id,node_type:e.node_type,title:we(e.title)}}function Gr(e,t){return e==null?e:{_class:e.class==null?void 0:e.class,data:e.data==null?void 0:e.data,id:e.id,node_type:e.node_type}}const yn={Text:"text",Img:"img"};function Qr(e,t){return e==null?e:{height:e.height,id:e.id,node_type:e.node_type,src:e.src,width:e.width}}function Hr(e,t){return e==null?e:{autocomplete:e.autocomplete==null?void 0:e.autocomplete,disabled:e.disabled,label:e.label==null?void 0:we(e.label),maxlength:e.maxlength==null?void 0:e.maxlength,name:e.name,node_type:e.node_type,onclick:e.onclick==null?void 0:e.onclick,onclickTrigger:e.onclickTrigger==null?void 0:e.onclickTrigger,onload:e.onload==null?void 0:e.onload,onloadTrigger:e.onloadTrigger==null?void 0:e.onloadTrigger,pattern:e.pattern==null?void 0:e.pattern,required:e.required==null?void 0:e.required,type:e.type,value:e.value==null?void 0:e.value}}const Xr={Input:"input"};function Zr(e,t){return e==null?e:{async:e.async,crossorigin:e.crossorigin,id:e.id,integrity:e.integrity,node_type:e.node_type,nonce:e.nonce,referrerpolicy:e.referrerpolicy,src:e.src,type:e.type}}function Yr(e,t){return e==null?e:{id:e.id,node_type:e.node_type,text:we(e.text)}}function jr(e){return eo(e)}function eo(e,t){if(e==null)return e;switch(e.node_type){case"a":return Object.assign({},zr(e),{node_type:"a"});case"div":return Object.assign({},Gr(e),{node_type:"div"});case"img":return Object.assign({},Qr(e),{node_type:"img"});case"input":return Object.assign({},Hr(e),{node_type:"input"});case"script":return Object.assign({},Zr(e),{node_type:"script"});case"text":return Object.assign({},Yr(e),{node_type:"text"});default:throw new Error(`No variant of UiNodeAttributes exists with 'node_type=${e.node_type}'`)}}const to={Passkey:"passkey"},no={Input:"input"};function io(e){return ro(e)}function ro(e,t){return e==null?e:{attributes:jr(e.attributes),group:e.group,messages:e.messages.map(we),meta:qr(e.meta),type:e.type}}function ke(e){return oo(e)}function oo(e,t){return e==null?e:{action:e.action,messages:e.messages==null?void 0:e.messages.map(we),method:e.method,nodes:e.nodes.map(io)}}function Mt(e){return so(e)}function so(e,t){return e==null?e:{active:e.active==null?void 0:e.active,created_at:e.created_at==null?void 0:new Date(e.created_at),expires_at:new Date(e.expires_at),id:e.id,issued_at:new Date(e.issued_at),oauth2_login_challenge:e.oauth2_login_challenge==null?void 0:e.oauth2_login_challenge,oauth2_login_request:e.oauth2_login_request==null?void 0:wn(e.oauth2_login_request),organization_id:e.organization_id==null?void 0:e.organization_id,refresh:e.refresh==null?void 0:e.refresh,request_url:e.request_url,requested_aal:e.requested_aal==null?void 0:Tt(e.requested_aal),return_to:e.return_to==null?void 0:e.return_to,session_token_exchange_code:e.session_token_exchange_code==null?void 0:e.session_token_exchange_code,state:e.state,transient_payload:e.transient_payload==null?void 0:e.transient_payload,type:e.type,ui:ke(e.ui),updated_at:e.updated_at==null?void 0:new Date(e.updated_at)}}function ao(e){return lo(e)}function lo(e,t){return e==null?e:{logout_token:e.logout_token,logout_url:e.logout_url}}function co(e){return uo(e,!1)}function uo(e,t=!1){return e==null?e:{session_token:e.session_token}}function Ue(e){return fo(e)}function fo(e,t){return e==null?e:{active:e.active==null?void 0:e.active,continue_with:e.continue_with==null?void 0:e.continue_with.map(Pe),expires_at:new Date(e.expires_at),id:e.id,issued_at:new Date(e.issued_at),request_url:e.request_url,return_to:e.return_to==null?void 0:e.return_to,state:e.state,transient_payload:e.transient_payload==null?void 0:e.transient_payload,type:e.type,ui:ke(e.ui)}}function Ot(e){return ho(e)}function ho(e,t){return e==null?e:{active:e.active==null?void 0:e.active,expires_at:new Date(e.expires_at),id:e.id,issued_at:new Date(e.issued_at),oauth2_login_challenge:e.oauth2_login_challenge==null?void 0:e.oauth2_login_challenge,oauth2_login_request:e.oauth2_login_request==null?void 0:wn(e.oauth2_login_request),organization_id:e.organization_id==null?void 0:e.organization_id,request_url:e.request_url,return_to:e.return_to==null?void 0:e.return_to,session_token_exchange_code:e.session_token_exchange_code==null?void 0:e.session_token_exchange_code,state:e.state,transient_payload:e.transient_payload==null?void 0:e.transient_payload,type:e.type,ui:ke(e.ui)}}const _n={ChooseMethod:"choose_method"};function po(e){return mo(e)}function mo(e,t){return e==null?e:{id:e.id,ip_address:e.ip_address==null?void 0:e.ip_address,location:e.location==null?void 0:e.location,user_agent:e.user_agent==null?void 0:e.user_agent}}function go(e){return wo(e)}function wo(e,t){return e==null?e:{aal:e.aal==null?void 0:Tt(e.aal),completed_at:e.completed_at==null?void 0:new Date(e.completed_at),method:e.method==null?void 0:e.method,organization:e.organization==null?void 0:e.organization,provider:e.provider==null?void 0:e.provider}}function Re(e){return yo(e)}function yo(e,t){return e==null?e:{active:e.active==null?void 0:e.active,authenticated_at:e.authenticated_at==null?void 0:new Date(e.authenticated_at),authentication_methods:e.authentication_methods==null?void 0:e.authentication_methods.map(go),authenticator_assurance_level:e.authenticator_assurance_level==null?void 0:Tt(e.authenticator_assurance_level),devices:e.devices==null?void 0:e.devices.map(po),expires_at:e.expires_at==null?void 0:new Date(e.expires_at),id:e.id,identity:e.identity==null?void 0:Et(e.identity),issued_at:e.issued_at==null?void 0:new Date(e.issued_at),tokenized:e.tokenized==null?void 0:e.tokenized}}function Je(e){return _o(e)}function _o(e,t){return e==null?e:{active:e.active==null?void 0:e.active,continue_with:e.continue_with==null?void 0:e.continue_with.map(Pe),expires_at:new Date(e.expires_at),id:e.id,identity:Et(e.identity),issued_at:new Date(e.issued_at),request_url:e.request_url,return_to:e.return_to==null?void 0:e.return_to,state:e.state,transient_payload:e.transient_payload==null?void 0:e.transient_payload,type:e.type,ui:ke(e.ui)}}const vo={Success:"success"};function We(e){return!(!("session"in e)||e.session===void 0)}function xt(e){return Fo(e)}function Fo(e,t){return e==null?e:{continue_with:e.continue_with==null?void 0:e.continue_with.map(Pe),session:Re(e.session),session_token:e.session_token==null?void 0:e.session_token}}function Vt(e){return!(!("identity"in e)||e.identity===void 0)}function So(e){return bo(e)}function bo(e,t){return e==null?e:{continue_with:e.continue_with==null?void 0:e.continue_with.map(Pe),identity:Et(e.identity),session:e.session==null?void 0:Re(e.session),session_token:e.session_token==null?void 0:e.session_token}}function ko(e){return Co(e,!1)}function Co(e,t=!1){return e==null?e:{csrf_token:e.csrf_token,nonce:e.nonce,token:e.token,transient_payload:e.transient_payload}}function To(e){return Eo(e,!1)}function Eo(e,t=!1){return e==null?e:{address:e.address,code:e.code,csrf_token:e.csrf_token,identifier:e.identifier,method:e.method,resend:e.resend,transient_payload:e.transient_payload}}function Mo(e){return Oo(e,!1)}function Oo(e,t=!1){return e==null?e:{csrf_token:e.csrf_token,identifier:e.identifier,method:e.method,transient_payload:e.transient_payload}}function xo(e){return Vo(e,!1)}function Vo(e,t=!1){return e==null?e:{csrf_token:e.csrf_token,lookup_secret:e.lookup_secret,method:e.method}}function Io(e){return No(e,!1)}function No(e,t=!1){return e==null?e:{csrf_token:e.csrf_token,id_token:e.id_token,id_token_nonce:e.id_token_nonce,method:e.method,provider:e.provider,traits:e.traits,transient_payload:e.transient_payload,upstream_parameters:e.upstream_parameters}}function Lo(e){return Do(e,!1)}function Do(e,t=!1){return e==null?e:{csrf_token:e.csrf_token,method:e.method,passkey_login:e.passkey_login}}function Ao(e){return Po(e,!1)}function Po(e,t=!1){return e==null?e:{csrf_token:e.csrf_token,identifier:e.identifier,method:e.method,password:e.password,password_identifier:e.password_identifier,transient_payload:e.transient_payload}}function Uo(e){return Ro(e,!1)}function Ro(e,t=!1){return e==null?e:{csrf_token:e.csrf_token,method:e.method,provider:e.provider,transient_payload:e.transient_payload}}function Jo(e){return Wo(e,!1)}function Wo(e,t=!1){return e==null?e:{csrf_token:e.csrf_token,method:e.method,totp_code:e.totp_code,transient_payload:e.transient_payload}}function Bo(e){return $o(e,!1)}function $o(e,t=!1){return e==null?e:{csrf_token:e.csrf_token,identifier:e.identifier,method:e.method,transient_payload:e.transient_payload,webauthn_login:e.webauthn_login}}function qo(e){return Ko(e,!1)}function Ko(e,t=!1){if(e==null)return e;switch(e.method){case"code":return Object.assign({},To(e),{method:"code"});case"identifier_first":return Object.assign({},Mo(e),{method:"identifier_first"});case"lookup_secret":return Object.assign({},xo(e),{method:"lookup_secret"});case"oidc":return Object.assign({},Io(e),{method:"oidc"});case"passkey":return Object.assign({},Lo(e),{method:"passkey"});case"password":return Object.assign({},Ao(e),{method:"password"});case"saml":return Object.assign({},Uo(e),{method:"saml"});case"totp":return Object.assign({},Jo(e),{method:"totp"});case"webauthn":return Object.assign({},Bo(e),{method:"webauthn"});default:throw new Error(`No variant of UpdateLoginFlowBody exists with 'method=${e.method}'`)}}function zo(e){return Go(e,!1)}function Go(e,t=!1){return e==null?e:{code:e.code,csrf_token:e.csrf_token,email:e.email,method:e.method,transient_payload:e.transient_payload}}function Qo(e){return Ho(e,!1)}function Ho(e,t=!1){return e==null?e:{csrf_token:e.csrf_token,email:e.email,method:e.method,transient_payload:e.transient_payload}}function Xo(e){return Zo(e,!1)}function Zo(e,t=!1){if(e==null)return e;switch(e.method){case"code":return Object.assign({},zo(e),{method:"code"});case"link":return Object.assign({},Qo(e),{method:"link"});default:throw new Error(`No variant of UpdateRecoveryFlowBody exists with 'method=${e.method}'`)}}function Yo(e){return jo(e,!1)}function jo(e,t=!1){return e==null?e:{code:e.code,csrf_token:e.csrf_token,method:e.method,resend:e.resend,traits:e.traits,transient_payload:e.transient_payload}}function es(e){return ts(e,!1)}function ts(e,t=!1){return e==null?e:{csrf_token:e.csrf_token,id_token:e.id_token,id_token_nonce:e.id_token_nonce,method:e.method,provider:e.provider,traits:e.traits,transient_payload:e.transient_payload,upstream_parameters:e.upstream_parameters}}function ns(e){return is(e,!1)}function is(e,t=!1){return e==null?e:{csrf_token:e.csrf_token,method:e.method,passkey_register:e.passkey_register,traits:e.traits,transient_payload:e.transient_payload}}function rs(e){return os(e,!1)}function os(e,t=!1){return e==null?e:{csrf_token:e.csrf_token,method:e.method,password:e.password,traits:e.traits,transient_payload:e.transient_payload}}function ss(e){return as(e,!1)}function as(e,t=!1){return e==null?e:{csrf_token:e.csrf_token,method:e.method,screen:e.screen,traits:e.traits,transient_payload:e.transient_payload}}function ls(e){return cs(e,!1)}function cs(e,t=!1){return e==null?e:{csrf_token:e.csrf_token,method:e.method,provider:e.provider,traits:e.traits,transient_payload:e.transient_payload}}function us(e){return ds(e,!1)}function ds(e,t=!1){return e==null?e:{csrf_token:e.csrf_token,method:e.method,traits:e.traits,transient_payload:e.transient_payload,webauthn_register:e.webauthn_register,webauthn_register_displayname:e.webauthn_register_displayname}}function fs(e){return hs(e,!1)}function hs(e,t=!1){if(e==null)return e;switch(e.method){case"code":return Object.assign({},Yo(e),{method:"code"});case"oidc":return Object.assign({},es(e),{method:"oidc"});case"passkey":return Object.assign({},ns(e),{method:"passkey"});case"password":return Object.assign({},rs(e),{method:"password"});case"profile":return Object.assign({},ss(e),{method:"profile"});case"saml":return Object.assign({},ls(e),{method:"saml"});case"webauthn":return Object.assign({},us(e),{method:"webauthn"});default:throw new Error(`No variant of UpdateRegistrationFlowBody exists with 'method=${e.method}'`)}}function ps(e){return ms(e,!1)}function ms(e,t=!1){return e==null?e:{csrf_token:e.csrf_token,lookup_secret_confirm:e.lookup_secret_confirm,lookup_secret_disable:e.lookup_secret_disable,lookup_secret_regenerate:e.lookup_secret_regenerate,lookup_secret_reveal:e.lookup_secret_reveal,method:e.method,transient_payload:e.transient_payload}}function gs(e){return ws(e,!1)}function ws(e,t=!1){return e==null?e:{flow:e.flow,link:e.link,method:e.method,traits:e.traits,transient_payload:e.transient_payload,unlink:e.unlink,upstream_parameters:e.upstream_parameters}}function ys(e){return _s(e,!1)}function _s(e,t=!1){return e==null?e:{csrf_token:e.csrf_token,method:e.method,passkey_remove:e.passkey_remove,passkey_settings_register:e.passkey_settings_register}}function vs(e){return Fs(e,!1)}function Fs(e,t=!1){return e==null?e:{csrf_token:e.csrf_token,method:e.method,password:e.password,transient_payload:e.transient_payload}}function Ss(e){return bs(e,!1)}function bs(e,t=!1){return e==null?e:{csrf_token:e.csrf_token,method:e.method,traits:e.traits,transient_payload:e.transient_payload}}function ks(e){return Cs(e,!1)}function Cs(e,t=!1){return e==null?e:{csrf_token:e.csrf_token,flow:e.flow,link:e.link,method:e.method,traits:e.traits,transient_payload:e.transient_payload,unlink:e.unlink}}function Ts(e){return Es(e,!1)}function Es(e,t=!1){return e==null?e:{csrf_token:e.csrf_token,method:e.method,totp_code:e.totp_code,totp_unlink:e.totp_unlink,transient_payload:e.transient_payload}}function Ms(e){return Os(e,!1)}function Os(e,t=!1){return e==null?e:{csrf_token:e.csrf_token,method:e.method,transient_payload:e.transient_payload,webauthn_register:e.webauthn_register,webauthn_register_displayname:e.webauthn_register_displayname,webauthn_remove:e.webauthn_remove}}function xs(e){return Vs(e,!1)}function Vs(e,t=!1){if(e==null)return e;switch(e.method){case"lookup_secret":return Object.assign({},ps(e),{method:"lookup_secret"});case"oidc":return Object.assign({},gs(e),{method:"oidc"});case"passkey":return Object.assign({},ys(e),{method:"passkey"});case"password":return Object.assign({},vs(e),{method:"password"});case"profile":return Object.assign({},Ss(e),{method:"profile"});case"saml":return Object.assign({},ks(e),{method:"saml"});case"totp":return Object.assign({},Ts(e),{method:"totp"});case"webauthn":return Object.assign({},Ms(e),{method:"webauthn"});default:throw new Error(`No variant of UpdateSettingsFlowBody exists with 'method=${e.method}'`)}}function Is(e){return Ns(e,!1)}function Ns(e,t=!1){return e==null?e:{code:e.code,csrf_token:e.csrf_token,email:e.email,method:e.method,transient_payload:e.transient_payload}}function Ls(e){return Ds(e,!1)}function Ds(e,t=!1){return e==null?e:{csrf_token:e.csrf_token,email:e.email,method:e.method,transient_payload:e.transient_payload}}function As(e){return Ps(e,!1)}function Ps(e,t=!1){if(e==null)return e;switch(e.method){case"code":return Object.assign({},Is(e),{method:"code"});case"link":return Object.assign({},Ls(e),{method:"link"});default:throw new Error(`No variant of UpdateVerificationFlowBody exists with 'method=${e.method}'`)}}function Be(e){return Us(e)}function Us(e,t){return e==null?e:{active:e.active==null?void 0:e.active,expires_at:e.expires_at==null?void 0:new Date(e.expires_at),id:e.id,issued_at:e.issued_at==null?void 0:new Date(e.issued_at),request_url:e.request_url==null?void 0:e.request_url,return_to:e.return_to==null?void 0:e.return_to,state:e.state,transient_payload:e.transient_payload==null?void 0:e.transient_payload,type:e.type,ui:ke(e.ui)}}const vn={ChooseMethod:"choose_method",SentEmail:"sent_email",PassedChallenge:"passed_challenge",UnknownDefaultOpenApi:"11184809"};class Rs extends bt{async createBrowserLoginFlowRaw(t,n){const i={};t.refresh!=null&&(i.refresh=t.refresh),t.aal!=null&&(i.aal=t.aal),t.returnTo!=null&&(i.return_to=t.returnTo),t.loginChallenge!=null&&(i.login_challenge=t.loginChallenge),t.organization!=null&&(i.organization=t.organization),t.via!=null&&(i.via=t.via);const r={};t.cookie!=null&&(r.Cookie=String(t.cookie));const o=await this.request({path:"/self-service/login/browser",method:"GET",headers:r,query:i},n);return new M(o,s=>Mt(s))}async createBrowserLoginFlow(t={},n){return await(await this.createBrowserLoginFlowRaw(t,n)).value()}async createBrowserLogoutFlowRaw(t,n){const i={};t.returnTo!=null&&(i.return_to=t.returnTo);const r={};t.cookie!=null&&(r.cookie=String(t.cookie));const o=await this.request({path:"/self-service/logout/browser",method:"GET",headers:r,query:i},n);return new M(o,s=>ao(s))}async createBrowserLogoutFlow(t={},n){return await(await this.createBrowserLogoutFlowRaw(t,n)).value()}async createBrowserRecoveryFlowRaw(t,n){const i={};t.returnTo!=null&&(i.return_to=t.returnTo);const r={},o=await this.request({path:"/self-service/recovery/browser",method:"GET",headers:r,query:i},n);return new M(o,s=>Ue(s))}async createBrowserRecoveryFlow(t={},n){return await(await this.createBrowserRecoveryFlowRaw(t,n)).value()}async createBrowserRegistrationFlowRaw(t,n){const i={};t.returnTo!=null&&(i.return_to=t.returnTo),t.loginChallenge!=null&&(i.login_challenge=t.loginChallenge),t.afterVerificationReturnTo!=null&&(i.after_verification_return_to=t.afterVerificationReturnTo),t.organization!=null&&(i.organization=t.organization);const r={},o=await this.request({path:"/self-service/registration/browser",method:"GET",headers:r,query:i},n);return new M(o,s=>Ot(s))}async createBrowserRegistrationFlow(t={},n){return await(await this.createBrowserRegistrationFlowRaw(t,n)).value()}async createBrowserSettingsFlowRaw(t,n){const i={};t.returnTo!=null&&(i.return_to=t.returnTo);const r={};t.cookie!=null&&(r.Cookie=String(t.cookie));const o=await this.request({path:"/self-service/settings/browser",method:"GET",headers:r,query:i},n);return new M(o,s=>Je(s))}async createBrowserSettingsFlow(t={},n){return await(await this.createBrowserSettingsFlowRaw(t,n)).value()}async createBrowserVerificationFlowRaw(t,n){const i={};t.returnTo!=null&&(i.return_to=t.returnTo);const r={},o=await this.request({path:"/self-service/verification/browser",method:"GET",headers:r,query:i},n);return new M(o,s=>Be(s))}async createBrowserVerificationFlow(t={},n){return await(await this.createBrowserVerificationFlowRaw(t,n)).value()}async createFedcmFlowRaw(t){const n={},i={},r=await this.request({path:"/self-service/fed-cm/parameters",method:"GET",headers:i,query:n},t);return new M(r,o=>br(o))}async createFedcmFlow(t){return await(await this.createFedcmFlowRaw(t)).value()}async createNativeLoginFlowRaw(t,n){const i={};t.refresh!=null&&(i.refresh=t.refresh),t.aal!=null&&(i.aal=t.aal),t.returnSessionTokenExchangeCode!=null&&(i.return_session_token_exchange_code=t.returnSessionTokenExchangeCode),t.returnTo!=null&&(i.return_to=t.returnTo),t.organization!=null&&(i.organization=t.organization),t.via!=null&&(i.via=t.via);const r={};t.xSessionToken!=null&&(r["X-Session-Token"]=String(t.xSessionToken));const o=await this.request({path:"/self-service/login/api",method:"GET",headers:r,query:i},n);return new M(o,s=>Mt(s))}async createNativeLoginFlow(t={},n){return await(await this.createNativeLoginFlowRaw(t,n)).value()}async createNativeRecoveryFlowRaw(t){const n={},i={},r=await this.request({path:"/self-service/recovery/api",method:"GET",headers:i,query:n},t);return new M(r,o=>Ue(o))}async createNativeRecoveryFlow(t){return await(await this.createNativeRecoveryFlowRaw(t)).value()}async createNativeRegistrationFlowRaw(t,n){const i={};t.returnSessionTokenExchangeCode!=null&&(i.return_session_token_exchange_code=t.returnSessionTokenExchangeCode),t.returnTo!=null&&(i.return_to=t.returnTo),t.organization!=null&&(i.organization=t.organization);const r={},o=await this.request({path:"/self-service/registration/api",method:"GET",headers:r,query:i},n);return new M(o,s=>Ot(s))}async createNativeRegistrationFlow(t={},n){return await(await this.createNativeRegistrationFlowRaw(t,n)).value()}async createNativeSettingsFlowRaw(t,n){const i={},r={};t.xSessionToken!=null&&(r["X-Session-Token"]=String(t.xSessionToken));const o=await this.request({path:"/self-service/settings/api",method:"GET",headers:r,query:i},n);return new M(o,s=>Je(s))}async createNativeSettingsFlow(t={},n){return await(await this.createNativeSettingsFlowRaw(t,n)).value()}async createNativeVerificationFlowRaw(t,n){const i={};t.returnTo!=null&&(i.return_to=t.returnTo);const r={},o=await this.request({path:"/self-service/verification/api",method:"GET",headers:r,query:i},n);return new M(o,s=>Be(s))}async createNativeVerificationFlow(t={},n){return await(await this.createNativeVerificationFlowRaw(t,n)).value()}async disableMyOtherSessionsRaw(t,n){const i={},r={};t.xSessionToken!=null&&(r["X-Session-Token"]=String(t.xSessionToken)),t.cookie!=null&&(r.Cookie=String(t.cookie));const o=await this.request({path:"/sessions",method:"DELETE",headers:r,query:i},n);return new M(o,s=>Or(s))}async disableMyOtherSessions(t={},n){return await(await this.disableMyOtherSessionsRaw(t,n)).value()}async disableMySessionRaw(t,n){if(t.id==null)throw new V("id",'Required parameter "id" was null or undefined when calling disableMySession().');const i={},r={};t.xSessionToken!=null&&(r["X-Session-Token"]=String(t.xSessionToken)),t.cookie!=null&&(r.Cookie=String(t.cookie));const o=await this.request({path:"/sessions/{id}".replace("{id}",encodeURIComponent(String(t.id))),method:"DELETE",headers:r,query:i},n);return new Ct(o)}async disableMySession(t,n){await this.disableMySessionRaw(t,n)}async exchangeSessionTokenRaw(t,n){if(t.initCode==null)throw new V("initCode",'Required parameter "initCode" was null or undefined when calling exchangeSessionToken().');if(t.returnToCode==null)throw new V("returnToCode",'Required parameter "returnToCode" was null or undefined when calling exchangeSessionToken().');const i={};t.initCode!=null&&(i.init_code=t.initCode),t.returnToCode!=null&&(i.return_to_code=t.returnToCode);const r={},o=await this.request({path:"/sessions/token-exchange",method:"GET",headers:r,query:i},n);return new M(o,s=>xt(s))}async exchangeSessionToken(t,n){return await(await this.exchangeSessionTokenRaw(t,n)).value()}async getFlowErrorRaw(t,n){if(t.id==null)throw new V("id",'Required parameter "id" was null or undefined when calling getFlowError().');const i={};t.id!=null&&(i.id=t.id);const r={},o=await this.request({path:"/self-service/errors",method:"GET",headers:r,query:i},n);return new M(o,s=>Vr(s))}async getFlowError(t,n){return await(await this.getFlowErrorRaw(t,n)).value()}async getLoginFlowRaw(t,n){if(t.id==null)throw new V("id",'Required parameter "id" was null or undefined when calling getLoginFlow().');const i={};t.id!=null&&(i.id=t.id);const r={};t.cookie!=null&&(r.Cookie=String(t.cookie));const o=await this.request({path:"/self-service/login/flows",method:"GET",headers:r,query:i},n);return new M(o,s=>Mt(s))}async getLoginFlow(t,n){return await(await this.getLoginFlowRaw(t,n)).value()}async getRecoveryFlowRaw(t,n){if(t.id==null)throw new V("id",'Required parameter "id" was null or undefined when calling getRecoveryFlow().');const i={};t.id!=null&&(i.id=t.id);const r={};t.cookie!=null&&(r.Cookie=String(t.cookie));const o=await this.request({path:"/self-service/recovery/flows",method:"GET",headers:r,query:i},n);return new M(o,s=>Ue(s))}async getRecoveryFlow(t,n){return await(await this.getRecoveryFlowRaw(t,n)).value()}async getRegistrationFlowRaw(t,n){if(t.id==null)throw new V("id",'Required parameter "id" was null or undefined when calling getRegistrationFlow().');const i={};t.id!=null&&(i.id=t.id);const r={};t.cookie!=null&&(r.Cookie=String(t.cookie));const o=await this.request({path:"/self-service/registration/flows",method:"GET",headers:r,query:i},n);return new M(o,s=>Ot(s))}async getRegistrationFlow(t,n){return await(await this.getRegistrationFlowRaw(t,n)).value()}async getSettingsFlowRaw(t,n){if(t.id==null)throw new V("id",'Required parameter "id" was null or undefined when calling getSettingsFlow().');const i={};t.id!=null&&(i.id=t.id);const r={};t.xSessionToken!=null&&(r["X-Session-Token"]=String(t.xSessionToken)),t.cookie!=null&&(r.Cookie=String(t.cookie));const o=await this.request({path:"/self-service/settings/flows",method:"GET",headers:r,query:i},n);return new M(o,s=>Je(s))}async getSettingsFlow(t,n){return await(await this.getSettingsFlowRaw(t,n)).value()}async getVerificationFlowRaw(t,n){if(t.id==null)throw new V("id",'Required parameter "id" was null or undefined when calling getVerificationFlow().');const i={};t.id!=null&&(i.id=t.id);const r={};t.cookie!=null&&(r.cookie=String(t.cookie));const o=await this.request({path:"/self-service/verification/flows",method:"GET",headers:r,query:i},n);return new M(o,s=>Be(s))}async getVerificationFlow(t,n){return await(await this.getVerificationFlowRaw(t,n)).value()}async getWebAuthnJavaScriptRaw(t){const n={},i={},r=await this.request({path:"/.well-known/ory/webauthn.js",method:"GET",headers:i,query:n},t);return this.isJsonMime(r.headers.get("content-type"))?new M(r):new ar(r)}async getWebAuthnJavaScript(t){return await(await this.getWebAuthnJavaScriptRaw(t)).value()}async listMySessionsRaw(t,n){const i={};t.perPage!=null&&(i.per_page=t.perPage),t.page!=null&&(i.page=t.page),t.pageSize!=null&&(i.page_size=t.pageSize),t.pageToken!=null&&(i.page_token=t.pageToken);const r={};t.xSessionToken!=null&&(r["X-Session-Token"]=String(t.xSessionToken)),t.cookie!=null&&(r.Cookie=String(t.cookie));const o=await this.request({path:"/sessions",method:"GET",headers:r,query:i},n);return new M(o,s=>s.map(Re))}async listMySessions(t={},n){return await(await this.listMySessionsRaw(t,n)).value()}async performNativeLogoutRaw(t,n){if(t.performNativeLogoutBody==null)throw new V("performNativeLogoutBody",'Required parameter "performNativeLogoutBody" was null or undefined when calling performNativeLogout().');const i={},r={};r["Content-Type"]="application/json";const o=await this.request({path:"/self-service/logout/api",method:"DELETE",headers:r,query:i,body:co(t.performNativeLogoutBody)},n);return new Ct(o)}async performNativeLogout(t,n){await this.performNativeLogoutRaw(t,n)}async toSessionRaw(t,n){const i={};t.tokenizeAs!=null&&(i.tokenize_as=t.tokenizeAs);const r={};t.xSessionToken!=null&&(r["X-Session-Token"]=String(t.xSessionToken)),t.cookie!=null&&(r.Cookie=String(t.cookie));const o=await this.request({path:"/sessions/whoami",method:"GET",headers:r,query:i},n);return new M(o,s=>Re(s))}async toSession(t={},n){return await(await this.toSessionRaw(t,n)).value()}async updateFedcmFlowRaw(t,n){if(t.updateFedcmFlowBody==null)throw new V("updateFedcmFlowBody",'Required parameter "updateFedcmFlowBody" was null or undefined when calling updateFedcmFlow().');const i={},r={};r["Content-Type"]="application/json";const o=await this.request({path:"/self-service/fed-cm/token",method:"POST",headers:r,query:i,body:ko(t.updateFedcmFlowBody)},n);return new M(o,s=>xt(s))}async updateFedcmFlow(t,n){return await(await this.updateFedcmFlowRaw(t,n)).value()}async updateLoginFlowRaw(t,n){if(t.flow==null)throw new V("flow",'Required parameter "flow" was null or undefined when calling updateLoginFlow().');if(t.updateLoginFlowBody==null)throw new V("updateLoginFlowBody",'Required parameter "updateLoginFlowBody" was null or undefined when calling updateLoginFlow().');const i={};t.flow!=null&&(i.flow=t.flow);const r={};r["Content-Type"]="application/json",t.xSessionToken!=null&&(r["X-Session-Token"]=String(t.xSessionToken)),t.cookie!=null&&(r.Cookie=String(t.cookie));const o=await this.request({path:"/self-service/login",method:"POST",headers:r,query:i,body:qo(t.updateLoginFlowBody)},n);return new M(o,s=>xt(s))}async updateLoginFlow(t,n){return await(await this.updateLoginFlowRaw(t,n)).value()}async updateLogoutFlowRaw(t,n){const i={};t.token!=null&&(i.token=t.token),t.returnTo!=null&&(i.return_to=t.returnTo);const r={};t.cookie!=null&&(r.Cookie=String(t.cookie));const o=await this.request({path:"/self-service/logout",method:"GET",headers:r,query:i},n);return new Ct(o)}async updateLogoutFlow(t={},n){await this.updateLogoutFlowRaw(t,n)}async updateRecoveryFlowRaw(t,n){if(t.flow==null)throw new V("flow",'Required parameter "flow" was null or undefined when calling updateRecoveryFlow().');if(t.updateRecoveryFlowBody==null)throw new V("updateRecoveryFlowBody",'Required parameter "updateRecoveryFlowBody" was null or undefined when calling updateRecoveryFlow().');const i={};t.flow!=null&&(i.flow=t.flow),t.token!=null&&(i.token=t.token);const r={};r["Content-Type"]="application/json",t.cookie!=null&&(r.Cookie=String(t.cookie));const o=await this.request({path:"/self-service/recovery",method:"POST",headers:r,query:i,body:Xo(t.updateRecoveryFlowBody)},n);return new M(o,s=>Ue(s))}async updateRecoveryFlow(t,n){return await(await this.updateRecoveryFlowRaw(t,n)).value()}async updateRegistrationFlowRaw(t,n){if(t.flow==null)throw new V("flow",'Required parameter "flow" was null or undefined when calling updateRegistrationFlow().');if(t.updateRegistrationFlowBody==null)throw new V("updateRegistrationFlowBody",'Required parameter "updateRegistrationFlowBody" was null or undefined when calling updateRegistrationFlow().');const i={};t.flow!=null&&(i.flow=t.flow);const r={};r["Content-Type"]="application/json",t.cookie!=null&&(r.Cookie=String(t.cookie));const o=await this.request({path:"/self-service/registration",method:"POST",headers:r,query:i,body:fs(t.updateRegistrationFlowBody)},n);return new M(o,s=>So(s))}async updateRegistrationFlow(t,n){return await(await this.updateRegistrationFlowRaw(t,n)).value()}async updateSettingsFlowRaw(t,n){if(t.flow==null)throw new V("flow",'Required parameter "flow" was null or undefined when calling updateSettingsFlow().');if(t.updateSettingsFlowBody==null)throw new V("updateSettingsFlowBody",'Required parameter "updateSettingsFlowBody" was null or undefined when calling updateSettingsFlow().');const i={};t.flow!=null&&(i.flow=t.flow);const r={};r["Content-Type"]="application/json",t.xSessionToken!=null&&(r["X-Session-Token"]=String(t.xSessionToken)),t.cookie!=null&&(r.Cookie=String(t.cookie));const o=await this.request({path:"/self-service/settings",method:"POST",headers:r,query:i,body:xs(t.updateSettingsFlowBody)},n);return new M(o,s=>Je(s))}async updateSettingsFlow(t,n){return await(await this.updateSettingsFlowRaw(t,n)).value()}async updateVerificationFlowRaw(t,n){if(t.flow==null)throw new V("flow",'Required parameter "flow" was null or undefined when calling updateVerificationFlow().');if(t.updateVerificationFlowBody==null)throw new V("updateVerificationFlowBody",'Required parameter "updateVerificationFlowBody" was null or undefined when calling updateVerificationFlow().');const i={};t.flow!=null&&(i.flow=t.flow),t.token!=null&&(i.token=t.token);const r={};r["Content-Type"]="application/json",t.cookie!=null&&(r.Cookie=String(t.cookie));const o=await this.request({path:"/self-service/verification",method:"POST",headers:r,query:i,body:As(t.updateVerificationFlowBody)},n);return new M(o,s=>Be(s))}async updateVerificationFlow(t,n){return await(await this.updateVerificationFlowRaw(t,n)).value()}}function te(e){return typeof e=="object"&&!!e&&"error"in e&&typeof e.error=="object"&&!!e.error&&"id"in e.error}function Js(e){return te(e)&&e.error.id==="session_refresh_required"}function Fn(e){return te(e)&&e.error.id==="self_service_flow_expired"}function Ws(e){return te(e)&&te(e)&&e.error.id==="browser_location_change_required"}function $e(e){return te(e)&&e.error.id==="session_already_available"}function Bs(e){return te(e)&&e.error.id==="session_aal2_required"}function $s(e){return te(e)&&e.error.id==="security_csrf_violation"}const qs=e=>e instanceof ge?!0:typeof e=="object"&&!!e&&"name"in e&&e.name==="ResponseError",oe=e=>async t=>{if(qs(t))switch(t.response.status){case 404:e.onRestartFlow();return;case 410:{const n=await Sn(t.response);if(Fn(n)){e.onRestartFlow(n.use_flow_id);return}e.onRestartFlow();return}case 400:return e.onValidationError(await t.response.json());case 403:case 422:{const n=await Sn(t.response);if(Ws(n)&&n.redirect_browser_to){e.onRedirect(n.redirect_browser_to,!0);return}else if(Fn(n)){e.onRestartFlow(n.use_flow_id);return}else if(Js(n)){e.onRedirect(n.redirect_browser_to,!0);return}else if($s(n)){e.onRestartFlow();return}throw new ge(t.response,"The Ory API endpoint returned a response code the SDK does not know how to handle. Please check the network tab for more information:"+JSON.stringify(n))}default:throw new ge(t.response,"The Ory API endpoint returned a response code the SDK does not know how to handle. Please check the network tab for more information.")}else if(t instanceof kt)throw new kt(t,"Unable to call the API endpoint. Ensure that CORS is set up correctly and that you have provided a valid SDK URL to Ory Elements.");throw t};async function Sn(e){try{return await e.clone().json()}catch{throw new ge(e,"The Ory API endpoint returned a response the SDK does not know how to handle:"+await e.text())}}const bn=["show_settings_ui","show_recovery_ui","show_verification_ui","redirect_browser_to","set_ory_session_token"];function It(e,{onRedirect:t}){if(!e||e.length===0)return!1;const n=Ks(e);if(!n)return!1;const i=(r,o,s)=>s?(t(s,!0),!0):(t("/"+o+"?flow="+r,!1),!0);if(zs(n))throw new Error("Ory Elements does not support API flows yet.");if(Gs(n)&&n.redirect_browser_to)return t(n.redirect_browser_to,!0),!0;if(Xs(n))return i(n.flow.id,"verification",n.flow.url);if(Qs(n))return i(n.flow.id,"recovery",n.flow.url);if(Hs(n))return i(n.flow.id,"settings",n.flow.url);throw new Error("Unknown action: "+JSON.stringify(n))}function Ks(e){return!e||e.length===0?void 0:e.toSorted((n,i)=>bn.indexOf(n.action)-bn.indexOf(i.action))[0]}function zs(e){return e.action==="set_ory_session_token"}function Gs(e){return e.action==="redirect_browser_to"}function Qs(e){return e.action==="show_recovery_ui"}function Hs(e){return e.action==="show_settings_ui"}function Xs(e){return e.action==="show_verification_ui"}function Nt(e){return e.node_type==="input"}function kn({attributes:e}){return Nt(e)?e.name:e.id}const Cn=e=>!(typeof e!="object"||e===null||!Br(e)||e.type!==Wr.Error),Zs=e=>!(typeof e!="object"||e===null||!("id"in e)||typeof e.id!="string"||"context"in e&&(typeof e.context!="object"||e.context===null)||"originalError"in e&&!Cn(e.originalError)),Tn=e=>e?.filter(Cn).map(js)??[],L=({onSubmit:e,onChange:t,onBlur:n}={})=>{const i=[...Array.isArray(e)?e:[],...Array.isArray(t)?t:[],...Array.isArray(n)?n:[]].filter(Zs);return[...new Map(i.map(r=>[r.id,r])).values()]};var Ce=(e=>(e.FieldMismatch="FieldMismatch",e.FieldRequired="FieldRequired",e))(Ce||{});const qe=e=>({id:`AdditionalValidationError_${e}`}),Ys=e=>{const t=(p,y)=>({id:`${p}_${y}`,originalError:e}),n=(p,y,_)=>({id:`${p}_${y}_WithContext`,context:_,originalError:e});return{createGenericError:p=>t("Error",p),createGenericErrorWithContext:(p,y)=>n("Error",p,y),createLoginFlowError:p=>t("LoginFlowError",p),createLoginFlowErrorWithContext:(p,y)=>n("LoginFlowError",p,y),createRegisterFlowError:p=>t("RegisterFlowError",p),createRegisterFlowErrorWithContext:(p,y)=>n("RegisterFlowError",p,y),createSettingsFlowError:p=>t("SettingsFlowError",p),createSettingsFlowErrorWithContext:(p,y)=>n("SettingsFlowError",p,y),createRecoveryFlowError:p=>t("RecoveryFlowError",p),createRecoveryFlowErrorWithContext:(p,y)=>n("RecoveryFlowError",p,y),createVerificationFlowError:p=>t("VerificationFlowError",p),createVerificationFlowErrorWithContext:(p,y)=>n("VerificationFlowError",p,y)}},js=e=>{const{createGenericError:t,createGenericErrorWithContext:n,createLoginFlowError:i,createLoginFlowErrorWithContext:r,createRegisterFlowError:o,createRegisterFlowErrorWithContext:s,createSettingsFlowError:a,createSettingsFlowErrorWithContext:l,createRecoveryFlowError:d,createRecoveryFlowErrorWithContext:h,createVerificationFlowError:c,createVerificationFlowErrorWithContext:f}=Ys(e);switch(e.id){case 4000001:return F(e.context,"reason","string")?n("InvalidFormat",{reason:e.context.reason}):t("InvalidFormat");case 4000002:return F(e.context,"property","string")?n("MissingProperty",{property:e.context.property}):t("MissingProperty");case 4000003:return F(e.context,"min_length","number")&&F(e.context,"actual_length","number")?n("TooShort",{min_length:e.context.min_length,actual_length:e.context.actual_length}):t("TooShort");case 4000004:return F(e.context,"pattern","string")?n("InvalidPattern",{pattern:e.context.pattern}):t("InvalidPattern");case 4000005:return F(e.context,"reason","string")?n("PasswordPolicyViolation",{reason:e.context.reason}):t("PasswordPolicyViolation");case 4000006:return t("InvalidCredentials");case 4000007:return t("DuplicateCredentials");case 4000008:return t("TOTPVerifierWrong");case 4000009:return t("IdentifierMissing");case 4000010:return t("AddressNotVerified");case 4000011:return t("NoTOTPDeviceSetUp");case 4000012:return t("RecoveryCodeAlreadyUsed");case 4000013:return t("NoWebAuthnDeviceSetUp");case 4000014:return t("NoRecoveryCodesSetUp");case 4000015:return t("AccountNotExistsOrHasSecurityKey");case 4000016:return t("InvalidRecoveryCode");case 4000017:return F(e.context,"max_length","number")&&F(e.context,"actual_length","number")?n("TooLong",{max_length:e.context.max_length,actual_length:e.context.actual_length}):t("TooLong");case 4000018:return F(e.context,"actual","number")&&F(e.context,"minimum","number")?n("MustBeGreaterOrEqualThan",{actual:e.context.actual,minimum:e.context.minimum}):t("MustBeGreaterOrEqualThan");case 4000019:return F(e.context,"actual","number")&&F(e.context,"minimum","number")?n("MustBeGreaterThan",{actual:e.context.actual,minimum:e.context.minimum}):t("MustBeGreaterThan");case 4000020:return F(e.context,"actual","number")&&F(e.context,"maximum","number")?n("MustBeLessOrEqualThan",{actual:e.context.actual,maximum:e.context.maximum}):t("MustBeLessOrEqualThan");case 4000021:return F(e.context,"actual","number")&&F(e.context,"maximum","number")?n("MustBeLessThan",{actual:e.context.actual,maximum:e.context.maximum}):t("MustBeLessThan");case 4000022:return F(e.context,"actual","number")&&F(e.context,"base","number")?n("IsNotMultipleOf",{actual:e.context.actual,base:e.context.base}):t("IsNotMultipleOf");case 4000023:return F(e.context,"max_items","number")&&F(e.context,"actual_items","number")?n("TooManyItems",{max_items:e.context.max_items,actual_items:e.context.actual_items}):t("TooManyItems");case 4000024:return F(e.context,"min_items","number")&&F(e.context,"actual_items","number")?n("TooFewItems",{min_items:e.context.min_items,actual_items:e.context.actual_items}):t("TooFewItems");case 4000025:return F(e.context,"index_a","number")&&F(e.context,"index_b","number")?n("DuplicateItems",{index_a:e.context.index_a,index_b:e.context.index_b}):t("DuplicateItems");case 4000026:return F(e.context,"actual_type","string")&&F(e.context,"allowed_types","object")&&Array.isArray(e.context.allowed_types)&&e.context.allowed_types.every(m=>typeof m=="string")?n("InvalidType",{actual_type:e.context.actual_type,allowed_types:e.context.allowed_types}):t("InvalidType");case 4000027:return t("AccountAlreadyExists");case 4000028:return F(e.context,"credential_identifier_hint","string")&&F(e.context,"available_credential_types","object")&&Array.isArray(e.context.available_credential_types)&&e.context.available_credential_types.every(m=>typeof m=="string")&&F(e.context,"available_oidc_providers","object")&&Array.isArray(e.context.available_oidc_providers)&&e.context.available_oidc_providers.every(m=>typeof m=="string")?n("CredentialIdentifierHintAlreadyUsedByOtherAccount",{available_credential_types:e.context.available_credential_types,available_oidc_providers:e.context.available_oidc_providers,credential_identifier_hint:e.context.credential_identifier_hint}):t("CredentialIdentifierHintAlreadyUsedByOtherAccount");case 4000029:return F(e.context,"expected","string")?n("MustBeEqualTo",{expected:e.context.expected}):t("MustBeEqualTo");case 4000030:return t("ConstFailed");case 4000031:return t("PasswordAndIdentifierTooSimilar");case 4000032:return F(e.context,"min_length","number")&&F(e.context,"actual_length","number")?n("PasswordTooShort",{min_length:e.context.min_length,actual_length:e.context.actual_length}):t("PasswordTooShort");case 4000033:return F(e.context,"max_length","number")&&F(e.context,"actual_length","number")?n("PasswordTooLong",{max_length:e.context.max_length,actual_length:e.context.actual_length}):t("PasswordTooLong");case 4000034:return F(e.context,"breaches","number")?n("PasswordLeaked",{breaches:e.context.breaches}):t("PasswordLeaked");case 4000035:return t("AccountNotExistsOrWithoutCodeSignIn");case 4000036:return t("TraitsDoNotMatch");case 4000037:return t("AccountNotExistsOrWithoutLoginMethod");case 4000038:return t("CaptchaFailed");case 4010001:return F(e.context,"expired_at","string")&&F(e.context,"expired_at_unix","number")?r("LoginFlowExpired",{expired_at:e.context.expired_at,expired_at_unix:e.context.expired_at_unix}):i("LoginFlowExpired");case 4010002:return i("NoLogInStrategyFound");case 4010003:return i("NoSignUpStrategyFound");case 4010004:return i("NoSettingsStrategyFound");case 4010005:return i("NoRecoveryStrategyFound");case 4010006:return i("NoVerificationStrategyFound");case 4010007:return i("LoginRequestAlreadyCompletedSuccessfully");case 4010008:return i("InvalidLoginCodeOrAlreadyUsed");case 4010009:return i("MismatchedLinkedCretentials");case 4010010:return i("MismatchedAddress");case 4040001:return F(e.context,"expired_at","string")&&F(e.context,"expired_at_unix","number")?s("RegisterFlowExpired",{expired_at:e.context.expired_at,expired_at_unix:e.context.expired_at_unix}):o("RegisterFlowExpired");case 4040002:return o("RegisterRequestAlreadyCompletedSuccessfully");case 4040003:return o("InvalidRegisterCodeOrAlreadyUsed");case 4050001:return F(e.context,"expired_at","string")&&F(e.context,"expired_at_unix","number")?l("SettingsFlowExpired",{expired_at:e.context.expired_at,expired_at_unix:e.context.expired_at_unix}):a("SettingsFlowExpired");case 4060001:return d("RecoveryRequestAlreadyCompletedSuccessfully");case 4060002:return d("RecoveryFlowFailureState");case 4060004:return d("InvalidTokenOrAlreadyUsed");case 4060005:return F(e.context,"expired_at","string")&&F(e.context,"expired_at_unix","number")?h("RecoveryFlowExpired",{expired_at:e.context.expired_at,expired_at_unix:e.context.expired_at_unix}):d("RecoveryFlowExpired");case 4060006:return d("InvalidRecoveryCodeOrAlreadyUsed");case 4070001:return c("InvalidVerificationTokenOrAlreadyUsed");case 4070002:return c("VerificationRequestAlreadyCompletedSuccessfully");case 4070003:return c("VerificationFlowFailureState");case 4070005:return F(e.context,"expired_at","string")&&F(e.context,"expired_at_unix","number")?f("VerificationFlowExpired",{expired_at:e.context.expired_at,expired_at_unix:e.context.expired_at_unix}):c("VerificationFlowExpired");case 4070006:return c("InvalidVerificationCodeOrAlreadyUsed");default:return F(e.context,"reason","string")?n("Generic",{reason:e.context.reason}):t("Generic")}};function P(e,t){return e?.find(n=>kn(n)===t)}function ea(e,t){return e?.filter(n=>kn(n)===t)??[]}function le(e){if(e&&Nt(e.attributes))return e.attributes}function ta(e){if(e&&Nt(e.attributes))return e.messages}function I(e){const t=le(P(e.ui.nodes,"csrf_token"));if(!t||typeof t.value!="string")throw new Error("CSRF token not found");return t.value}const na=e=>{if(e.group!==to.Passkey||e.type!==no.Input||e.attributes.node_type!==Xr.Input||e.attributes.name!=="passkey_remove"||!e.meta?.label?.context)return!1;const{context:t}=e.meta.label;return"added_at"in t&&typeof t.added_at=="string"&&"display_name"in t&&typeof t.display_name=="string"&&"added_at_unix"in t&&typeof t.added_at_unix=="number"},En=["apple","facebook","google"],ia=e=>e.group==="oidc"&&e.attributes.node_type==="input"&&En.includes(e.attributes.value),Ke=(e,t)=>e?.find(n=>ia(n)&&n.attributes.value===t)??void 0,Te=async({error:e})=>await oe({onRedirect:(t,n)=>{globalThis.location.href=t},onRestartFlow:()=>{throw new Error("Needs to restart the flow",{cause:ie.FlowRestartRequired})},onValidationError:t=>t})(e),R=(e,t,n)=>{const i=Tn(e.ui.messages);i.length>0&&(t.setErrorMap({onSubmit:i}),n?.({target:"root",errors:i}));for(const r in t.fieldInfo){const o=r,s=Tn(ta(P(e.ui.nodes,o)));s.length>0&&(t.setFieldMeta(o,a=>({...a,errorMap:{onSubmit:s}})),n?.({target:o,errors:s}))}},Lt="leancode_kratos",ce=e=>[Lt,...e],ue=e=>`${Lt}_${e}`;function q(e){return g.useMemo(()=>L(e.state.errorMap),[e.state.errorMap])}const Mn=g.createContext(void 0);function D(){const e=g.useContext(Mn);if(e===void 0)throw new Error("useKratosClientContext must be used within a KratosClientContextProvider");return e}function ra({children:e,api:t}){const n=g.useMemo(()=>({kratosClient:t}),[t]);return u.jsx(Mn.Provider,{value:n,children:e})}function On(e,t){if(typeof e=="function")return e(t);e!=null&&(e.current=t)}function oa(...e){return t=>{let n=!1;const i=e.map(r=>{const o=On(r,t);return!n&&typeof o=="function"&&(n=!0),o});if(n)return()=>{for(let r=0;r<i.length;r++){const o=i[r];typeof o=="function"?o():On(e[r],null)}}}}function sa(e){const t=aa(e),n=E.forwardRef((i,r)=>{const{children:o,...s}=i,a=E.Children.toArray(o),l=a.find(ca);if(l){const d=l.props.children,h=a.map(c=>c===l?E.Children.count(d)>1?E.Children.only(null):E.isValidElement(d)?d.props.children:null:c);return u.jsx(t,{...s,ref:r,children:E.isValidElement(d)?E.cloneElement(d,void 0,h):null})}return u.jsx(t,{...s,ref:r,children:o})});return n.displayName=`${e}.Slot`,n}var O=sa("Slot");function aa(e){const t=E.forwardRef((n,i)=>{const{children:r,...o}=n;if(E.isValidElement(r)){const s=da(r),a=ua(o,r.props);return r.type!==E.Fragment&&(a.ref=i?oa(i,s):s),E.cloneElement(r,a)}return E.Children.count(r)>1?E.Children.only(null):null});return t.displayName=`${e}.SlotClone`,t}var la=Symbol("radix.slottable");function ca(e){return E.isValidElement(e)&&typeof e.type=="function"&&"__radixId"in e.type&&e.type.__radixId===la}function ua(e,t){const n={...t};for(const i in t){const r=e[i],o=t[i];/^on[A-Z]/.test(i)?r&&o?n[i]=(...a)=>{const l=o(...a);return r(...a),l}:r&&(n[i]=r):i==="style"?n[i]={...r,...o}:i==="className"&&(n[i]=[r,o].filter(Boolean).join(" "))}return{...e,...n}}function da(e){let t=Object.getOwnPropertyDescriptor(e.props,"ref")?.get,n=t&&"isReactWarning"in t&&t.isReactWarning;return n?e.ref:(t=Object.getOwnPropertyDescriptor(e,"ref")?.get,n=t&&"isReactWarning"in t&&t.isReactWarning,n?e.props.ref:e.props.ref||e.ref)}function W({children:e}){const t=O;return u.jsx(t,{type:"submit",children:e})}const xn=g.createContext(void 0);function fa({children:e,emailVerificationForm:t}){const n=g.useMemo(()=>({emailVerificationForm:t}),[t]);return u.jsx(xn.Provider,{value:n,children:e})}function ha(){const e=g.useContext(xn);if(e===void 0)throw new Error("useEmailVerificationFormContext must be used within a EmailVerificationFormProvider");return e}var ze=class{constructor(){this.listeners=new Set,this.subscribe=this.subscribe.bind(this)}subscribe(e){return this.listeners.add(e),this.onSubscribe(),()=>{this.listeners.delete(e),this.onUnsubscribe()}}hasListeners(){return this.listeners.size>0}onSubscribe(){}onUnsubscribe(){}},pa={setTimeout:(e,t)=>setTimeout(e,t),clearTimeout:e=>clearTimeout(e),setInterval:(e,t)=>setInterval(e,t),clearInterval:e=>clearInterval(e)},ma=class{#t=pa;#e=!1;setTimeoutProvider(e){process.env.NODE_ENV!=="production"&&this.#e&&e!==this.#t&&console.error("[timeoutManager]: Switching provider after calls to previous provider might result in unexpected behavior.",{previous:this.#t,provider:e}),this.#t=e,process.env.NODE_ENV!=="production"&&(this.#e=!1)}setTimeout(e,t){return process.env.NODE_ENV!=="production"&&(this.#e=!0),this.#t.setTimeout(e,t)}clearTimeout(e){this.#t.clearTimeout(e)}setInterval(e,t){return process.env.NODE_ENV!=="production"&&(this.#e=!0),this.#t.setInterval(e,t)}clearInterval(e){this.#t.clearInterval(e)}},Ge=new ma;function ga(e){setTimeout(e,0)}var Ee=typeof window>"u"||"Deno"in globalThis;function Qe(){}function Vn(e){return typeof e=="number"&&e>=0&&e!==1/0}function wa(e,t){return Math.max(e+(t||0)-Date.now(),0)}function Me(e,t){return typeof e=="function"?e(t):e}function K(e,t){return typeof e=="function"?e(t):e}function In(e){return JSON.stringify(e,(t,n)=>At(n)?Object.keys(n).sort().reduce((i,r)=>(i[r]=n[r],i),{}):n)}var ya=Object.prototype.hasOwnProperty;function Dt(e,t){if(e===t)return e;const n=Nn(e)&&Nn(t);if(!n&&!(At(e)&&At(t)))return t;const r=(n?e:Object.keys(e)).length,o=n?t:Object.keys(t),s=o.length,a=n?new Array(s):{};let l=0;for(let d=0;d<s;d++){const h=n?d:o[d],c=e[h],f=t[h];if(c===f){a[h]=c,(n?d<r:ya.call(e,h))&&l++;continue}if(c===null||f===null||typeof c!="object"||typeof f!="object"){a[h]=f;continue}const m=Dt(c,f);a[h]=m,m===c&&l++}return r===s&&l===r?e:a}function He(e,t){if(!t||Object.keys(e).length!==Object.keys(t).length)return!1;for(const n in e)if(e[n]!==t[n])return!1;return!0}function Nn(e){return Array.isArray(e)&&e.length===Object.keys(e).length}function At(e){if(!Ln(e))return!1;const t=e.constructor;if(t===void 0)return!0;const n=t.prototype;return!(!Ln(n)||!n.hasOwnProperty("isPrototypeOf")||Object.getPrototypeOf(e)!==Object.prototype)}function Ln(e){return Object.prototype.toString.call(e)==="[object Object]"}function Dn(e,t,n){if(typeof n.structuralSharing=="function")return n.structuralSharing(e,t);if(n.structuralSharing!==!1){if(process.env.NODE_ENV!=="production")try{return Dt(e,t)}catch(i){throw console.error(`Structural sharing requires data to be JSON serializable. To fix this, turn off structuralSharing or return JSON-serializable data from your queryFn. [${n.queryHash}]: ${i}`),i}return Dt(e,t)}return t}function An(e,t){return typeof e=="function"?e(...t):!!e}var _a=class extends ze{#t;#e;#n;constructor(){super(),this.#n=e=>{if(!Ee&&window.addEventListener){const t=()=>e();return window.addEventListener("visibilitychange",t,!1),()=>{window.removeEventListener("visibilitychange",t)}}}}onSubscribe(){this.#e||this.setEventListener(this.#n)}onUnsubscribe(){this.hasListeners()||(this.#e?.(),this.#e=void 0)}setEventListener(e){this.#n=e,this.#e?.(),this.#e=e(t=>{typeof t=="boolean"?this.setFocused(t):this.onFocus()})}setFocused(e){this.#t!==e&&(this.#t=e,this.onFocus())}onFocus(){const e=this.isFocused();this.listeners.forEach(t=>{t(e)})}isFocused(){return typeof this.#t=="boolean"?this.#t:globalThis.document?.visibilityState!=="hidden"}},va=new _a;function Pn(){let e,t;const n=new Promise((r,o)=>{e=r,t=o});n.status="pending",n.catch(()=>{});function i(r){Object.assign(n,r),delete n.resolve,delete n.reject}return n.resolve=r=>{i({status:"fulfilled",value:r}),e(r)},n.reject=r=>{i({status:"rejected",reason:r}),t(r)},n}var Fa=ga;function Sa(){let e=[],t=0,n=a=>{a()},i=a=>{a()},r=Fa;const o=a=>{t?e.push(a):r(()=>{n(a)})},s=()=>{const a=e;e=[],a.length&&r(()=>{i(()=>{a.forEach(l=>{n(l)})})})};return{batch:a=>{let l;t++;try{l=a()}finally{t--,t||s()}return l},batchCalls:a=>(...l)=>{o(()=>{a(...l)})},schedule:o,setNotifyFunction:a=>{n=a},setBatchNotifyFunction:a=>{i=a},setScheduler:a=>{r=a}}}var Xe=Sa(),ba=class extends ze{#t=!0;#e;#n;constructor(){super(),this.#n=e=>{if(!Ee&&window.addEventListener){const t=()=>e(!0),n=()=>e(!1);return window.addEventListener("online",t,!1),window.addEventListener("offline",n,!1),()=>{window.removeEventListener("online",t),window.removeEventListener("offline",n)}}}}onSubscribe(){this.#e||this.setEventListener(this.#n)}onUnsubscribe(){this.hasListeners()||(this.#e?.(),this.#e=void 0)}setEventListener(e){this.#n=e,this.#e?.(),this.#e=e(this.setOnline.bind(this))}setOnline(e){this.#t!==e&&(this.#t=e,this.listeners.forEach(n=>{n(e)}))}isOnline(){return this.#t}},ka=new ba;function Ca(e){return(e??"online")==="online"?ka.isOnline():!0}function Ta(e,t){return{fetchFailureCount:0,fetchFailureReason:null,fetchStatus:Ca(t.networkMode)?"fetching":"paused",...e===void 0&&{error:null,status:"pending"}}}var Ea=class extends ze{constructor(e,t){super(),this.options=t,this.#t=e,this.#a=null,this.#o=Pn(),this.bindMethods(),this.setOptions(t)}#t;#e=void 0;#n=void 0;#i=void 0;#r;#s;#o;#a;#u;#d;#c;#l;#h;#f;#m=new Set;bindMethods(){this.refetch=this.refetch.bind(this)}onSubscribe(){this.listeners.size===1&&(this.#e.addObserver(this),Un(this.#e,this.options)?this.#p():this.updateResult(),this.#_())}onUnsubscribe(){this.hasListeners()||this.destroy()}shouldFetchOnReconnect(){return Pt(this.#e,this.options,this.options.refetchOnReconnect)}shouldFetchOnWindowFocus(){return Pt(this.#e,this.options,this.options.refetchOnWindowFocus)}destroy(){this.listeners=new Set,this.#v(),this.#F(),this.#e.removeObserver(this)}setOptions(e){const t=this.options,n=this.#e;if(this.options=this.#t.defaultQueryOptions(e),this.options.enabled!==void 0&&typeof this.options.enabled!="boolean"&&typeof this.options.enabled!="function"&&typeof K(this.options.enabled,this.#e)!="boolean")throw new Error("Expected enabled to be a boolean or a callback that returns a boolean");this.#S(),this.#e.setOptions(this.options),t._defaulted&&!He(this.options,t)&&this.#t.getQueryCache().notify({type:"observerOptionsUpdated",query:this.#e,observer:this});const i=this.hasListeners();i&&Rn(this.#e,n,this.options,t)&&this.#p(),this.updateResult(),i&&(this.#e!==n||K(this.options.enabled,this.#e)!==K(t.enabled,this.#e)||Me(this.options.staleTime,this.#e)!==Me(t.staleTime,this.#e))&&this.#g();const r=this.#w();i&&(this.#e!==n||K(this.options.enabled,this.#e)!==K(t.enabled,this.#e)||r!==this.#f)&&this.#y(r)}getOptimisticResult(e){const t=this.#t.getQueryCache().build(this.#t,e),n=this.createResult(t,e);return Oa(this,n)&&(this.#i=n,this.#s=this.options,this.#r=this.#e.state),n}getCurrentResult(){return this.#i}trackResult(e,t){return new Proxy(e,{get:(n,i)=>(this.trackProp(i),t?.(i),i==="promise"&&!this.options.experimental_prefetchInRender&&this.#o.status==="pending"&&this.#o.reject(new Error("experimental_prefetchInRender feature flag is not enabled")),Reflect.get(n,i))})}trackProp(e){this.#m.add(e)}getCurrentQuery(){return this.#e}refetch({...e}={}){return this.fetch({...e})}fetchOptimistic(e){const t=this.#t.defaultQueryOptions(e),n=this.#t.getQueryCache().build(this.#t,t);return n.fetch().then(()=>this.createResult(n,t))}fetch(e){return this.#p({...e,cancelRefetch:e.cancelRefetch??!0}).then(()=>(this.updateResult(),this.#i))}#p(e){this.#S();let t=this.#e.fetch(this.options,e);return e?.throwOnError||(t=t.catch(Qe)),t}#g(){this.#v();const e=Me(this.options.staleTime,this.#e);if(Ee||this.#i.isStale||!Vn(e))return;const n=wa(this.#i.dataUpdatedAt,e)+1;this.#l=Ge.setTimeout(()=>{this.#i.isStale||this.updateResult()},n)}#w(){return(typeof this.options.refetchInterval=="function"?this.options.refetchInterval(this.#e):this.options.refetchInterval)??!1}#y(e){this.#F(),this.#f=e,!(Ee||K(this.options.enabled,this.#e)===!1||!Vn(this.#f)||this.#f===0)&&(this.#h=Ge.setInterval(()=>{(this.options.refetchIntervalInBackground||va.isFocused())&&this.#p()},this.#f))}#_(){this.#g(),this.#y(this.#w())}#v(){this.#l&&(Ge.clearTimeout(this.#l),this.#l=void 0)}#F(){this.#h&&(Ge.clearInterval(this.#h),this.#h=void 0)}createResult(e,t){const n=this.#e,i=this.options,r=this.#i,o=this.#r,s=this.#s,l=e!==n?e.state:this.#n,{state:d}=e;let h={...d},c=!1,f;if(t._optimisticResults){const k=this.hasListeners(),X=!k&&Un(e,t),$=k&&Rn(e,n,t,i);(X||$)&&(h={...h,...Ta(d.data,e.options)}),t._optimisticResults==="isRestoring"&&(h.fetchStatus="idle")}let{error:m,errorUpdatedAt:w,status:p}=h;f=h.data;let y=!1;if(t.placeholderData!==void 0&&f===void 0&&p==="pending"){let k;r?.isPlaceholderData&&t.placeholderData===s?.placeholderData?(k=r.data,y=!0):k=typeof t.placeholderData=="function"?t.placeholderData(this.#c?.state.data,this.#c):t.placeholderData,k!==void 0&&(p="success",f=Dn(r?.data,k,t),c=!0)}if(t.select&&f!==void 0&&!y)if(r&&f===o?.data&&t.select===this.#u)f=this.#d;else try{this.#u=t.select,f=t.select(f),f=Dn(r?.data,f,t),this.#d=f,this.#a=null}catch(k){this.#a=k}this.#a&&(m=this.#a,f=this.#d,w=Date.now(),p="error");const _=h.fetchStatus==="fetching",v=p==="pending",S=p==="error",C=v&&_,N=f!==void 0,T={status:p,fetchStatus:h.fetchStatus,isPending:v,isSuccess:p==="success",isError:S,isInitialLoading:C,isLoading:C,data:f,dataUpdatedAt:h.dataUpdatedAt,error:m,errorUpdatedAt:w,failureCount:h.fetchFailureCount,failureReason:h.fetchFailureReason,errorUpdateCount:h.errorUpdateCount,isFetched:h.dataUpdateCount>0||h.errorUpdateCount>0,isFetchedAfterMount:h.dataUpdateCount>l.dataUpdateCount||h.errorUpdateCount>l.errorUpdateCount,isFetching:_,isRefetching:_&&!v,isLoadingError:S&&!N,isPaused:h.fetchStatus==="paused",isPlaceholderData:c,isRefetchError:S&&N,isStale:Ut(e,t),refetch:this.refetch,promise:this.#o,isEnabled:K(t.enabled,e)!==!1};if(this.options.experimental_prefetchInRender){const k=ae=>{T.status==="error"?ae.reject(T.error):T.data!==void 0&&ae.resolve(T.data)},X=()=>{const ae=this.#o=T.promise=Pn();k(ae)},$=this.#o;switch($.status){case"pending":e.queryHash===n.queryHash&&k($);break;case"fulfilled":(T.status==="error"||T.data!==$.value)&&X();break;case"rejected":(T.status!=="error"||T.error!==$.reason)&&X();break}}return T}updateResult(){const e=this.#i,t=this.createResult(this.#e,this.options);if(this.#r=this.#e.state,this.#s=this.options,this.#r.data!==void 0&&(this.#c=this.#e),He(t,e))return;this.#i=t;const n=()=>{if(!e)return!0;const{notifyOnChangeProps:i}=this.options,r=typeof i=="function"?i():i;if(r==="all"||!r&&!this.#m.size)return!0;const o=new Set(r??this.#m);return this.options.throwOnError&&o.add("error"),Object.keys(this.#i).some(s=>{const a=s;return this.#i[a]!==e[a]&&o.has(a)})};this.#b({listeners:n()})}#S(){const e=this.#t.getQueryCache().build(this.#t,this.options);if(e===this.#e)return;const t=this.#e;this.#e=e,this.#n=e.state,this.hasListeners()&&(t?.removeObserver(this),e.addObserver(this))}onQueryUpdate(){this.updateResult(),this.hasListeners()&&this.#_()}#b(e){Xe.batch(()=>{e.listeners&&this.listeners.forEach(t=>{t(this.#i)}),this.#t.getQueryCache().notify({query:this.#e,type:"observerResultsUpdated"})})}};function Ma(e,t){return K(t.enabled,e)!==!1&&e.state.data===void 0&&!(e.state.status==="error"&&t.retryOnMount===!1)}function Un(e,t){return Ma(e,t)||e.state.data!==void 0&&Pt(e,t,t.refetchOnMount)}function Pt(e,t,n){if(K(t.enabled,e)!==!1&&Me(t.staleTime,e)!=="static"){const i=typeof n=="function"?n(e):n;return i==="always"||i!==!1&&Ut(e,t)}return!1}function Rn(e,t,n,i){return(e!==t||K(i.enabled,e)===!1)&&(!n.suspense||e.state.status!=="error")&&Ut(e,n)}function Ut(e,t){return K(t.enabled,e)!==!1&&e.isStaleByTime(Me(t.staleTime,e))}function Oa(e,t){return!He(e.getCurrentResult(),t)}function xa(){return{context:void 0,data:void 0,error:null,failureCount:0,failureReason:null,isPaused:!1,status:"idle",variables:void 0,submittedAt:0}}var Va=class extends ze{#t;#e=void 0;#n;#i;constructor(e,t){super(),this.#t=e,this.setOptions(t),this.bindMethods(),this.#r()}bindMethods(){this.mutate=this.mutate.bind(this),this.reset=this.reset.bind(this)}setOptions(e){const t=this.options;this.options=this.#t.defaultMutationOptions(e),He(this.options,t)||this.#t.getMutationCache().notify({type:"observerOptionsUpdated",mutation:this.#n,observer:this}),t?.mutationKey&&this.options.mutationKey&&In(t.mutationKey)!==In(this.options.mutationKey)?this.reset():this.#n?.state.status==="pending"&&this.#n.setOptions(this.options)}onUnsubscribe(){this.hasListeners()||this.#n?.removeObserver(this)}onMutationUpdate(e){this.#r(),this.#s(e)}getCurrentResult(){return this.#e}reset(){this.#n?.removeObserver(this),this.#n=void 0,this.#r(),this.#s()}mutate(e,t){return this.#i=t,this.#n?.removeObserver(this),this.#n=this.#t.getMutationCache().build(this.#t,this.options),this.#n.addObserver(this),this.#n.execute(e)}#r(){const e=this.#n?.state??xa();this.#e={...e,isPending:e.status==="pending",isSuccess:e.status==="success",isError:e.status==="error",isIdle:e.status==="idle",mutate:this.mutate,reset:this.reset}}#s(e){Xe.batch(()=>{if(this.#i&&this.hasListeners()){const t=this.#e.variables,n=this.#e.context,i={client:this.#t,meta:this.options.meta,mutationKey:this.options.mutationKey};e?.type==="success"?(this.#i.onSuccess?.(e.data,t,n,i),this.#i.onSettled?.(e.data,null,t,n,i)):e?.type==="error"&&(this.#i.onError?.(e.error,t,n,i),this.#i.onSettled?.(void 0,e.error,t,n,i))}this.listeners.forEach(t=>{t(this.#e)})})}},Ia=E.createContext(void 0),J=e=>{const t=E.useContext(Ia);if(!t)throw new Error("No QueryClient set, use QueryClientProvider to set one");return t},Jn=E.createContext(!1),Na=()=>E.useContext(Jn);Jn.Provider;function La(){let e=!1;return{clearReset:()=>{e=!1},reset:()=>{e=!0},isReset:()=>e}}var Da=E.createContext(La()),Aa=()=>E.useContext(Da),Pa=(e,t)=>{(e.suspense||e.throwOnError||e.experimental_prefetchInRender)&&(t.isReset()||(e.retryOnMount=!1))},Ua=e=>{E.useEffect(()=>{e.clearReset()},[e])},Ra=({result:e,errorResetBoundary:t,throwOnError:n,query:i,suspense:r})=>e.isError&&!t.isReset()&&!e.isFetching&&i&&(r&&e.data===void 0||An(n,[e.error,i])),Ja=e=>{if(e.suspense){const n=r=>r==="static"?r:Math.max(r??1e3,1e3),i=e.staleTime;e.staleTime=typeof i=="function"?(...r)=>n(i(...r)):n(i),typeof e.gcTime=="number"&&(e.gcTime=Math.max(e.gcTime,1e3))}},Wa=(e,t)=>e.isLoading&&e.isFetching&&!t,Ba=(e,t)=>e?.suspense&&t.isPending,Wn=(e,t,n)=>t.fetchOptimistic(e).catch(()=>{n.clearReset()});function $a(e,t,n){if(process.env.NODE_ENV!=="production"&&(typeof e!="object"||Array.isArray(e)))throw new Error('Bad argument type. Starting with v5, only the "Object" form is allowed when calling query related functions. Please use the error stack to find the culprit call. More info here: https://tanstack.com/query/latest/docs/react/guides/migrating-to-v5#supports-a-single-signature-one-object');const i=Na(),r=Aa(),o=J(),s=o.defaultQueryOptions(e);o.getDefaultOptions().queries?._experimental_beforeQuery?.(s),process.env.NODE_ENV!=="production"&&(s.queryFn||console.error(`[${s.queryHash}]: No queryFn was passed as an option, and no default queryFn was found. The queryFn parameter is only optional when using a default queryFn. More info here: https://tanstack.com/query/latest/docs/framework/react/guides/default-query-function`)),s._optimisticResults=i?"isRestoring":"optimistic",Ja(s),Pa(s,r),Ua(r);const a=!o.getQueryCache().get(s.queryHash),[l]=E.useState(()=>new t(o,s)),d=l.getOptimisticResult(s),h=!i&&e.subscribed!==!1;if(E.useSyncExternalStore(E.useCallback(c=>{const f=h?l.subscribe(Xe.batchCalls(c)):Qe;return l.updateResult(),f},[l,h]),()=>l.getCurrentResult(),()=>l.getCurrentResult()),E.useEffect(()=>{l.setOptions(s)},[s,l]),Ba(s,d))throw Wn(s,l,r);if(Ra({result:d,errorResetBoundary:r,throwOnError:s.throwOnError,query:o.getQueryCache().get(s.queryHash),suspense:s.suspense}))throw d.error;return o.getDefaultOptions().queries?._experimental_afterQuery?.(s,d),s.experimental_prefetchInRender&&!Ee&&Wa(d,i)&&(a?Wn(s,l,r):o.getQueryCache().get(s.queryHash)?.promise)?.catch(Qe).finally(()=>{l.updateResult()}),s.notifyOnChangeProps?d:l.trackResult(d)}function de(e,t){return $a(e,Ea)}function Z(e,t){const n=J(),[i]=E.useState(()=>new Va(n,e));E.useEffect(()=>{i.setOptions(e)},[i,e]);const r=E.useSyncExternalStore(E.useCallback(s=>i.subscribe(Xe.batchCalls(s)),[i]),()=>i.getCurrentResult(),()=>i.getCurrentResult()),o=E.useCallback((s,a)=>{i.mutate(s,a).catch(Qe)},[i]);if(r.error&&An(i.options.throwOnError,[r.error]))throw r.error;return{...r,mutate:o,mutateAsync:r.mutate}}const qa=ue("verification_flow"),Ze=(e="no_id")=>ce([qa,e]),Bn=g.createContext(void 0);function Ye({children:e}){const[t,n]=g.useState(),[i,r]=g.useState(),o=g.useCallback(()=>{n(void 0),r(void 0)},[]);return u.jsx(Bn.Provider,{value:{verificationFlowId:t,setVerificationFlowId:n,verifiableAddress:i,setVerifiableAddress:r,resetFlow:o},children:e})}function z(){const e=g.useContext(Bn);if(e===void 0)throw new Error("useVerificationFlow must be used within a VerificationFlowProvider");return e}function Ka({returnTo:e}={}){const{kratosClient:t}=D(),{setVerificationFlowId:n}=z(),i=J();return Z({mutationFn:()=>t.createBrowserVerificationFlow({returnTo:e},async({init:{headers:r}})=>({headers:{...r,Accept:"application/json"}})),onSuccess(r){i.setQueryDefaults(Ze(r.id),{staleTime:1/0}),i.setQueryData(Ze(r.id),r),n(r.id)}})}function Rt(){const{kratosClient:e}=D(),{verificationFlowId:t}=z();return de({queryKey:Ze(t),queryFn:async({signal:n})=>{if(!t)throw new Error("No verification flow ID provided",{cause:ie.NoFlowId});try{return await e.getVerificationFlow({id:t},async({init:{headers:i}})=>({signal:n,headers:{...i,Accept:"application/json"}}))}catch(i){throw await Te({error:i})}},enabled:!!t,staleTime:1/0})}function $n(){const{kratosClient:e}=D(),{verificationFlowId:t,resetFlow:n}=z(),i=J();return Z({mutationFn:async r=>{if(!t)throw new Error("Verification flow ID is not set");try{const o=await e.updateVerificationFlow({flow:t,updateVerificationFlowBody:r},{headers:{Accept:"application/json","Content-Type":"application/json"}});return o.state===vn.PassedChallenge&&o.return_to&&(globalThis.location.href=o.return_to),o}catch(o){return await oe({onRedirect:(s,a)=>{globalThis.location.href=s},onRestartFlow:n,onValidationError:s=>s})(o)}},onSuccess(r){r&&"id"in r&&i.setQueryData(Ze(r.id),r)}})}function za({children:e}){const{verifiableAddress:t}=z(),{mutate:n}=$n(),{data:i}=Rt(),r=g.useCallback(()=>{!i||!t||n({method:"code",csrf_token:I(i),email:t,code:""})},[i,t,n]),o=O;return u.jsx(o,{type:"button",onClick:r,children:e})}function Ga({children:e}){const{emailVerificationForm:t}=ha(),n=O;return u.jsx(t.Field,{name:"code",children:i=>u.jsx(n,{errors:L(i.state.meta.errorMap),name:i.name,type:"text",value:i.state.value,onChange:r=>i.handleChange(r.target.value),children:e})})}const ye=new WeakMap,je=new WeakMap,et={current:[]};let Jt=!1,Oe=0;const xe=new Set,tt=new Map;function qn(e){const t=Array.from(e).sort((n,i)=>n instanceof ne&&n.options.deps.includes(i)?1:i instanceof ne&&i.options.deps.includes(n)?-1:0);for(const n of t){if(et.current.includes(n))continue;et.current.push(n),n.recompute();const i=je.get(n);if(i)for(const r of i){const o=ye.get(r);o&&qn(o)}}}function Qa(e){const t={prevVal:e.prevState,currentVal:e.state};for(const n of e.listeners)n(t)}function Ha(e){const t={prevVal:e.prevState,currentVal:e.state};for(const n of e.listeners)n(t)}function Kn(e){if(Oe>0&&!tt.has(e)&&tt.set(e,e.prevState),xe.add(e),!(Oe>0)&&!Jt)try{for(Jt=!0;xe.size>0;){const t=Array.from(xe);xe.clear();for(const n of t){const i=tt.get(n)??n.prevState;n.prevState=i,Qa(n)}for(const n of t){const i=ye.get(n);i&&(et.current.push(n),qn(i))}for(const n of t){const i=ye.get(n);if(i)for(const r of i)Ha(r)}}}finally{Jt=!1,et.current=[],tt.clear()}}function Y(e){Oe++;try{e()}finally{if(Oe--,Oe===0){const t=xe.values().next().value;t&&Kn(t)}}}function Xa(e){return typeof e=="function"}class Wt{constructor(t,n){this.listeners=new Set,this.subscribe=i=>{var r,o;this.listeners.add(i);const s=(o=(r=this.options)==null?void 0:r.onSubscribe)==null?void 0:o.call(r,i,this);return()=>{this.listeners.delete(i),s?.()}},this.prevState=t,this.state=t,this.options=n}setState(t){var n,i,r;this.prevState=this.state,(n=this.options)!=null&&n.updateFn?this.state=this.options.updateFn(this.prevState)(t):Xa(t)?this.state=t(this.prevState):this.state=t,(r=(i=this.options)==null?void 0:i.onUpdate)==null||r.call(i),Kn(this)}}class ne{constructor(t){this.listeners=new Set,this._subscriptions=[],this.lastSeenDepValues=[],this.getDepVals=()=>{const n=this.options.deps.length,i=new Array(n),r=new Array(n);for(let o=0;o<n;o++){const s=this.options.deps[o];i[o]=s.prevState,r[o]=s.state}return this.lastSeenDepValues=r,{prevDepVals:i,currDepVals:r,prevVal:this.prevState??void 0}},this.recompute=()=>{var n,i;this.prevState=this.state;const r=this.getDepVals();this.state=this.options.fn(r),(i=(n=this.options).onUpdate)==null||i.call(n)},this.checkIfRecalculationNeededDeeply=()=>{for(const o of this.options.deps)o instanceof ne&&o.checkIfRecalculationNeededDeeply();let n=!1;const i=this.lastSeenDepValues,{currDepVals:r}=this.getDepVals();for(let o=0;o<r.length;o++)if(r[o]!==i[o]){n=!0;break}n&&this.recompute()},this.mount=()=>(this.registerOnGraph(),this.checkIfRecalculationNeededDeeply(),()=>{this.unregisterFromGraph();for(const n of this._subscriptions)n()}),this.subscribe=n=>{var i,r;this.listeners.add(n);const o=(r=(i=this.options).onSubscribe)==null?void 0:r.call(i,n,this);return()=>{this.listeners.delete(n),o?.()}},this.options=t,this.state=t.fn({prevDepVals:void 0,prevVal:void 0,currDepVals:this.getDepVals().currDepVals})}registerOnGraph(t=this.options.deps){for(const n of t)if(n instanceof ne)n.registerOnGraph(),this.registerOnGraph(n.options.deps);else if(n instanceof Wt){let i=ye.get(n);i||(i=new Set,ye.set(n,i)),i.add(this);let r=je.get(this);r||(r=new Set,je.set(this,r)),r.add(n)}}unregisterFromGraph(t=this.options.deps){for(const n of t)if(n instanceof ne)this.unregisterFromGraph(n.options.deps);else if(n instanceof Wt){const i=ye.get(n);i&&i.delete(this);const r=je.get(this);r&&r.delete(n)}}}function nt(e,t){return typeof e=="function"?e(t):e}function Ve(e,t){return $t(t).reduce((i,r)=>{if(i===null)return null;if(typeof i<"u")return i[r]},e)}function it(e,t,n){const i=$t(t);function r(o){if(!i.length)return nt(n,o);const s=i.shift();if(typeof s=="string"||typeof s=="number"&&!Array.isArray(o))return typeof o=="object"?(o===null&&(o={}),{...o,[s]:r(o[s])}):{[s]:r()};if(Array.isArray(o)&&typeof s=="number"){const a=o.slice(0,s);return[...a.length?a:new Array(s),r(o[s]),...o.slice(s+1)]}return[...new Array(s),r()]}return r(e)}function Za(e,t){const n=$t(t);function i(r){if(!r)return;if(n.length===1){const s=n[0];if(Array.isArray(r)&&typeof s=="number")return r.filter((d,h)=>h!==s);const{[s]:a,...l}=r;return l}const o=n.shift();if(typeof o=="string"&&typeof r=="object")return{...r,[o]:i(r[o])};if(typeof o=="number"&&Array.isArray(r)){if(o>=r.length)return r;const s=r.slice(0,o);return[...s.length?s:new Array(o),i(r[o]),...r.slice(o+1)]}throw new Error("It seems we have created an infinite loop in deleteBy. ")}return i(e)}const Ya=/^(\d+)$/gm,ja=/\.(\d+)(?=\.)/gm,el=/^(\d+)\./gm,tl=/\.(\d+$)/gm,nl=/\.{2,}/gm,Bt="__int__",rt=`${Bt}$1`;function $t(e){if(Array.isArray(e))return[...e];if(typeof e!="string")throw new Error("Path must be a string.");return e.replace(/(^\[)|]/gm,"").replace(/\[/g,".").replace(Ya,rt).replace(ja,`.${rt}.`).replace(el,`${rt}.`).replace(tl,`.${rt}`).replace(nl,".").split(".").map(t=>{if(t.startsWith(Bt)){const n=t.substring(Bt.length),i=parseInt(n,10);return String(i)===n?i:n}return t})}function il(e){return!(Array.isArray(e)&&e.length===0)}function qt(e,t){const n=i=>i.validators.filter(Boolean).map(r=>({cause:r.cause,validate:r.fn}));return t.validationLogic({form:t.form,validators:t.validators,event:{type:e,async:!1},runValidation:n})}function Kt(e,t){const{asyncDebounceMs:n}=t,{onBlurAsyncDebounceMs:i,onChangeAsyncDebounceMs:r,onDynamicAsyncDebounceMs:o}=t.validators||{},s=n??0,a=l=>l.validators.filter(Boolean).map(d=>{const h=d?.cause||e;let c=s;switch(h){case"change":c=r??s;break;case"blur":c=i??s;break;case"dynamic":c=o??s;break;case"submit":c=0;break}return e==="submit"&&(c=0),{cause:h,validate:d.fn,debounceMs:c}});return t.validationLogic({form:t.form,validators:t.validators,event:{type:e,async:!0},runValidation:a})}const zt=e=>!!e&&typeof e=="object"&&"fields"in e;function _e(e,t){if(Object.is(e,t))return!0;if(typeof e!="object"||e===null||typeof t!="object"||t===null)return!1;if(e instanceof Date&&t instanceof Date)return e.getTime()===t.getTime();if(e instanceof Map&&t instanceof Map){if(e.size!==t.size)return!1;for(const[r,o]of e)if(!t.has(r)||!Object.is(o,t.get(r)))return!1;return!0}if(e instanceof Set&&t instanceof Set){if(e.size!==t.size)return!1;for(const r of e)if(!t.has(r))return!1;return!0}const n=Object.keys(e),i=Object.keys(t);if(n.length!==i.length)return!1;for(const r of n)if(!i.includes(r)||!_e(e[r],t[r]))return!1;return!0}const zn=({newFormValidatorError:e,isPreviousErrorFromFormValidator:t,previousErrorValue:n})=>e?{newErrorValue:e,newSource:"form"}:t?{newErrorValue:void 0,newSource:void 0}:n?{newErrorValue:n,newSource:"field"}:{newErrorValue:void 0,newSource:void 0},Gn=({formLevelError:e,fieldLevelError:t})=>t?{newErrorValue:t,newSource:"field"}:e?{newErrorValue:e,newSource:"form"}:{newErrorValue:void 0,newSource:void 0};function U(e,t){return e==null?t:{...e,...t}}let fe=256;const ot=[];let st;for(;fe--;)ot[fe]=(fe+256).toString(16).substring(1);function rl(){let e=0,t,n="";if(!st||fe+16>256){for(st=new Array(256),e=256;e--;)st[e]=256*Math.random()|0;e=0,fe=0}for(;e<16;e++)t=st[fe+e],e===6?n+=ot[t&15|64]:e===8?n+=ot[t&63|128]:n+=ot[t],e&1&&e>1&&e<11&&(n+="-");return fe++,n}const ve=e=>{if(!e.validators)return e.runValidation({validators:[],form:e.form});const t=e.event.async,n=t?void 0:{fn:e.validators.onMount,cause:"mount"},i={fn:t?e.validators.onChangeAsync:e.validators.onChange,cause:"change"},r={fn:t?e.validators.onBlurAsync:e.validators.onBlur,cause:"blur"},o={fn:t?e.validators.onSubmitAsync:e.validators.onSubmit,cause:"submit"},s=t?void 0:{fn:()=>{},cause:"server"};switch(e.event.type){case"mount":return e.runValidation({validators:[n],form:e.form});case"submit":return e.runValidation({validators:[i,r,o,s],form:e.form});case"server":return e.runValidation({validators:[],form:e.form});case"blur":return e.runValidation({validators:[r,s],form:e.form});case"change":return e.runValidation({validators:[i,s],form:e.form});default:throw new Error(`Unknown validation event type: ${e.event.type}`)}};function ol(e,t){const n=new Map;for(const i of e){const r=i.path??[];let o=t,s="";for(let a=0;a<r.length;a++){const l=r[a];if(l===void 0)continue;const d=typeof l=="object"?l.key:l,h=Number(d);Array.isArray(o)&&!Number.isNaN(h)?s+=`[${h}]`:s+=(a>0?".":"")+String(d),typeof o=="object"&&o!==null?o=o[d]:o=void 0}n.set(s,(n.get(s)??[]).concat(i))}return Object.fromEntries(n)}const Qn=(e,t)=>{const n=ol(e,t);return{form:n,fields:n}},Fe={validate({value:e,validationSource:t},n){const i=n["~standard"].validate(e);if(i instanceof Promise)throw new Error("async function passed to sync validator");if(i.issues)return t==="field"?i.issues:Qn(i.issues,e)},async validateAsync({value:e,validationSource:t},n){const i=await n["~standard"].validate(e);if(i.issues)return t==="field"?i.issues:Qn(i.issues,e)}},Hn=e=>!!e&&"~standard"in e,at={isValidating:!1,isTouched:!1,isBlurred:!1,isDirty:!1,isPristine:!0,isValid:!0,isDefaultValue:!0,errors:[],errorMap:{},errorSourceMap:{}};function lt(e){function t(c,f,m,w){const p=i(c,f,m,w);({insert:()=>a(p,c,f),remove:()=>l(p),swap:()=>w!==void 0&&h(p,c,f,w),move:()=>w!==void 0&&d(p,c,f,w)})[m]()}function n(c,f){return`${c}[${f}]`}function i(c,f,m,w){const p=[n(c,f)];if(m==="swap")p.push(n(c,w));else if(m==="move"){const[y,_]=[Math.min(f,w),Math.max(f,w)];for(let v=y;v<=_;v++)p.push(n(c,v))}else{const y=e.getFieldValue(c),_=Array.isArray(y)?y.length:0;for(let v=f+1;v<_;v++)p.push(n(c,v))}return Object.keys(e.fieldInfo).filter(y=>p.some(_=>y.startsWith(_)))}function r(c,f){return c.replace(/\[(\d+)\]/,(m,w)=>{const p=parseInt(w,10);return`[${f==="up"?p+1:Math.max(0,p-1)}]`})}function o(c,f){(f==="up"?c:[...c].reverse()).forEach(w=>{const p=r(w.toString(),f),y=e.getFieldMeta(p);y?e.setFieldMeta(w,y):e.setFieldMeta(w,s())})}const s=()=>at,a=(c,f,m)=>{o(c,"down"),c.forEach(w=>{w.toString().startsWith(n(f,m))&&e.setFieldMeta(w,s())})},l=c=>{o(c,"up")},d=(c,f,m,w)=>{const p=new Map(Object.keys(e.fieldInfo).filter(y=>y.startsWith(n(f,m))).map(y=>[y,e.getFieldMeta(y)]));o(c,m<w?"up":"down"),Object.keys(e.fieldInfo).filter(y=>y.startsWith(n(f,w))).forEach(y=>{const _=y.replace(n(f,w),n(f,m)),v=p.get(_);v&&e.setFieldMeta(y,v)})},h=(c,f,m,w)=>{c.forEach(p=>{if(!p.toString().startsWith(n(f,m)))return;const y=p.toString().replace(n(f,m),n(f,w)),[_,v]=[e.getFieldMeta(p),e.getFieldMeta(y)];_&&e.setFieldMeta(y,_),v&&e.setFieldMeta(p,v)})};return{handleArrayFieldMetaShift:t}}class sl{#t=!0;#e;#n;#i;#r;#s;#o;#a;#u=0;#d=5;#c=()=>{this.debugLog("Connected to event bus"),this.#s=!0,this.debugLog("Emitting queued events",this.#r),this.#r.forEach(t=>this.emitEventToBus(t)),this.#r=[],this.stopConnectLoop(),this.#n().removeEventListener("tanstack-connect-success",this.#c)};#l=()=>{if(this.#n().addEventListener("tanstack-connect-success",this.#c),this.#u<this.#d){this.#u++,this.dispatchCustomEvent("tanstack-connect",{});return}this.#n().removeEventListener("tanstack-connect",this.#l),this.debugLog("Max retries reached, giving up on connection"),this.stopConnectLoop()};constructor({pluginId:t,debug:n=!1,enabled:i=!0}){this.#e=t,this.#t=i,this.#n=this.getGlobalTarget,this.#i=n,this.debugLog(" Initializing event subscription for plugin",this.#e),this.#r=[],this.#s=!1,this.#o=null,this.#a=500}startConnectLoop(){this.#o!==null||this.#s||(this.debugLog(`Starting connect loop (every ${this.#a}ms)`),this.#o=setInterval(this.#l,this.#a))}stopConnectLoop(){this.#o!==null&&(clearInterval(this.#o),this.#o=null,this.debugLog("Stopped connect loop"))}debugLog(...t){this.#i&&console.log(`🌴 [tanstack-devtools:${this.#e}-plugin]`,...t)}getGlobalTarget(){if(typeof globalThis<"u"&&globalThis.__TANSTACK_EVENT_TARGET__)return this.debugLog("Using global event target"),globalThis.__TANSTACK_EVENT_TARGET__;if(typeof window<"u"&&typeof window.addEventListener<"u")return this.debugLog("Using window as event target"),window;const t=typeof EventTarget<"u"?new EventTarget:void 0;return typeof t>"u"||typeof t.addEventListener>"u"?(this.debugLog("No event mechanism available, running in non-web environment"),{addEventListener:()=>{},removeEventListener:()=>{},dispatchEvent:()=>!1}):(this.debugLog("Using new EventTarget as fallback"),t)}getPluginId(){return this.#e}dispatchCustomEventShim(t,n){try{const i=new Event(t,{detail:n});this.#n().dispatchEvent(i)}catch{this.debugLog("Failed to dispatch shim event")}}dispatchCustomEvent(t,n){try{this.#n().dispatchEvent(new CustomEvent(t,{detail:n}))}catch{this.dispatchCustomEventShim(t,n)}}emitEventToBus(t){this.debugLog("Emitting event to client bus",t),this.dispatchCustomEvent("tanstack-dispatch-event",t)}emit(t,n){if(!this.#t){this.debugLog("Event bus client is disabled, not emitting event",t,n);return}if(!this.#s){this.debugLog("Bus not available, will be pushed as soon as connected"),this.#r.push({type:`${this.#e}:${t}`,payload:n,pluginId:this.#e}),typeof CustomEvent<"u"&&(this.#l(),this.startConnectLoop());return}return this.emitEventToBus({type:`${this.#e}:${t}`,payload:n,pluginId:this.#e})}on(t,n){const i=`${this.#e}:${t}`;if(!this.#t)return this.debugLog("Event bus client is disabled, not registering event",i),()=>{};const r=o=>{this.debugLog("Received event from bus",o.detail),n(o.detail)};return this.#n().addEventListener(i,r),this.debugLog("Registered event to bus",i),()=>{this.#n().removeEventListener(i,r)}}onAll(t){if(!this.#t)return this.debugLog("Event bus client is disabled, not registering event"),()=>{};const n=i=>{const r=i.detail;t(r)};return this.#n().addEventListener("tanstack-devtools-global",n),()=>this.#n().removeEventListener("tanstack-devtools-global",n)}onAllPluginEvents(t){if(!this.#t)return this.debugLog("Event bus client is disabled, not registering event"),()=>{};const n=i=>{const r=i.detail;this.#e&&r.pluginId!==this.#e||t(r)};return this.#n().addEventListener("tanstack-devtools-global",n),()=>this.#n().removeEventListener("tanstack-devtools-global",n)}}class al extends sl{constructor(){super({pluginId:"form-devtools"})}}const G=new al;function Gt(e){return{values:e.values??{},errorMap:e.errorMap??{},fieldMetaBase:e.fieldMetaBase??{},isSubmitted:e.isSubmitted??!1,isSubmitting:e.isSubmitting??!1,isValidating:e.isValidating??!1,submissionAttempts:e.submissionAttempts??0,isSubmitSuccessful:e.isSubmitSuccessful??!1,validationMetaMap:e.validationMetaMap??{onChange:void 0,onBlur:void 0,onSubmit:void 0,onMount:void 0,onServer:void 0,onDynamic:void 0}}}class ll{constructor(t){this.options={},this.fieldInfo={},this.prevTransformArray=[],this.mount=()=>{const n=this.fieldMetaDerived.mount(),i=this.store.mount(),r=()=>{n(),i(),G.emit("form-unmounted",{id:this._formId})};this.options.listeners?.onMount?.({formApi:this});const{onMount:o}=this.options.validators||{};return G.emit("form-state-change",{id:this._formId,state:this.store.state,options:this.options}),o&&this.validateSync("mount"),r},this.update=n=>{if(!n)return;const i=this.options;this.options=n;const r=!!n.transform?.deps?.some((a,l)=>a!==this.prevTransformArray[l]),o=n.defaultValues&&!_e(n.defaultValues,i.defaultValues)&&!this.state.isTouched,s=!_e(n.defaultState,i.defaultState)&&!this.state.isTouched;!o&&!s&&!r||Y(()=>{this.baseStore.setState(()=>Gt(Object.assign({},this.state,s?n.defaultState:{},o?{values:n.defaultValues}:{},r?{_force_re_eval:!this.state._force_re_eval}:{})))})},this.reset=(n,i)=>{const{fieldMeta:r}=this.state,o=this.resetFieldMeta(r);n&&!i?.keepDefaultValues&&(this.options={...this.options,defaultValues:n}),this.baseStore.setState(()=>Gt({...this.options.defaultState,values:n??this.options.defaultValues??this.options.defaultState?.values,fieldMetaBase:o}))},this.validateAllFields=async n=>{const i=[];return Y(()=>{Object.values(this.fieldInfo).forEach(o=>{if(!o.instance)return;const s=o.instance;i.push(Promise.resolve().then(()=>s.validate(n,{skipFormValidation:!0}))),o.instance.state.meta.isTouched||o.instance.setMeta(a=>({...a,isTouched:!0}))})}),(await Promise.all(i)).flat()},this.validateArrayFieldsStartingFrom=async(n,i,r)=>{const o=this.getFieldValue(n),s=Array.isArray(o)?Math.max(o.length-1,0):null,a=[`${n}[${i}]`];for(let c=i+1;c<=(s??0);c++)a.push(`${n}[${c}]`);const l=Object.keys(this.fieldInfo).filter(c=>a.some(f=>c.startsWith(f))),d=[];return Y(()=>{l.forEach(c=>{d.push(Promise.resolve().then(()=>this.validateField(c,r)))})}),(await Promise.all(d)).flat()},this.validateField=(n,i)=>{const r=this.fieldInfo[n]?.instance;return r?(r.state.meta.isTouched||r.setMeta(o=>({...o,isTouched:!0})),r.validate(i)):[]},this.validateSync=n=>{const i=qt(n,{...this.options,form:this,validationLogic:this.options.validationLogic||ve});let r=!1;const o={};return Y(()=>{for(const l of i){if(!l.validate)continue;const d=this.runValidator({validate:l.validate,value:{value:this.state.values,formApi:this,validationSource:"form"},type:"validate"}),{formError:h,fieldErrors:c}=ct(d),f=Ie(l.cause);for(const m of Object.keys(this.state.fieldMeta)){if(this.baseStore.state.fieldMetaBase[m]===void 0)continue;const w=this.getFieldMeta(m);if(!w)continue;const{errorMap:p,errorSourceMap:y}=w,_=c?.[m],{newErrorValue:v,newSource:S}=zn({newFormValidatorError:_,isPreviousErrorFromFormValidator:y?.[f]==="form",previousErrorValue:p?.[f]});S==="form"&&(o[m]={...o[m],[f]:_}),p?.[f]!==v&&this.setFieldMeta(m,C=>({...C,errorMap:{...C.errorMap,[f]:v},errorSourceMap:{...C.errorSourceMap,[f]:S}}))}this.state.errorMap?.[f]!==h&&this.baseStore.setState(m=>({...m,errorMap:{...m.errorMap,[f]:h}})),(h||c)&&(r=!0)}const s=Ie("submit");this.state.errorMap?.[s]&&n!=="submit"&&!r&&this.baseStore.setState(l=>({...l,errorMap:{...l.errorMap,[s]:void 0}}));const a=Ie("server");this.state.errorMap?.[a]&&n!=="server"&&!r&&this.baseStore.setState(l=>({...l,errorMap:{...l.errorMap,[a]:void 0}}))}),{hasErrored:r,fieldsErrorMap:o}},this.validateAsync=async n=>{const i=Kt(n,{...this.options,form:this,validationLogic:this.options.validationLogic||ve});this.state.isFormValidating||this.baseStore.setState(l=>({...l,isFormValidating:!0}));const r=[];let o;for(const l of i){if(!l.validate)continue;const d=Ie(l.cause);this.state.validationMetaMap[d]?.lastAbortController.abort();const c=new AbortController;this.state.validationMetaMap[d]={lastAbortController:c},r.push(new Promise(async f=>{let m;try{m=await new Promise((_,v)=>{setTimeout(async()=>{if(c.signal.aborted)return _(void 0);try{_(await this.runValidator({validate:l.validate,value:{value:this.state.values,formApi:this,validationSource:"form",signal:c.signal},type:"validateAsync"}))}catch(S){v(S)}},l.debounceMs)})}catch(_){m=_}const{formError:w,fieldErrors:p}=ct(m);p&&(o=o?{...o,...p}:p);const y=Ie(l.cause);for(const _ of Object.keys(this.state.fieldMeta)){if(this.baseStore.state.fieldMetaBase[_]===void 0)continue;const v=this.getFieldMeta(_);if(!v)continue;const{errorMap:S,errorSourceMap:C}=v,N=o?.[_],{newErrorValue:b,newSource:T}=zn({newFormValidatorError:N,isPreviousErrorFromFormValidator:C?.[y]==="form",previousErrorValue:S?.[y]});S?.[y]!==b&&this.setFieldMeta(_,k=>({...k,errorMap:{...k.errorMap,[y]:b},errorSourceMap:{...k.errorSourceMap,[y]:T}}))}this.baseStore.setState(_=>({..._,errorMap:{..._.errorMap,[y]:w}})),f(o?{fieldErrors:o,errorMapKey:y}:void 0)}))}let s=[];const a={};if(r.length){s=await Promise.all(r);for(const l of s)if(l?.fieldErrors){const{errorMapKey:d}=l;for(const[h,c]of Object.entries(l.fieldErrors)){const m={...a[h]||{},[d]:c};a[h]=m}}}return this.baseStore.setState(l=>({...l,isFormValidating:!1})),a},this.validate=n=>{const{hasErrored:i,fieldsErrorMap:r}=this.validateSync(n);return i&&!this.options.asyncAlways?r:this.validateAsync(n)},this.getFieldValue=n=>Ve(this.state.values,n),this.getFieldMeta=n=>this.state.fieldMeta[n],this.getFieldInfo=n=>this.fieldInfo[n]||={instance:null,validationMetaMap:{onChange:void 0,onBlur:void 0,onSubmit:void 0,onMount:void 0,onServer:void 0,onDynamic:void 0}},this.setFieldMeta=(n,i)=>{this.baseStore.setState(r=>({...r,fieldMetaBase:{...r.fieldMetaBase,[n]:nt(i,r.fieldMetaBase[n])}}))},this.resetFieldMeta=n=>Object.keys(n).reduce((i,r)=>{const o=r;return i[o]=at,i},{}),this.setFieldValue=(n,i,r)=>{const o=r?.dontUpdateMeta??!1,s=r?.dontRunListeners??!1,a=r?.dontValidate??!1;Y(()=>{o||this.setFieldMeta(n,l=>({...l,isTouched:!0,isDirty:!0,errorMap:{...l?.errorMap,onMount:void 0}})),this.baseStore.setState(l=>({...l,values:it(l.values,n,i)}))}),s||this.getFieldInfo(n).instance?.triggerOnChangeListener(),a||this.validateField(n,"change")},this.deleteField=n=>{const r=[...Object.keys(this.fieldInfo).filter(o=>{const s=n.toString();return o!==s&&o.startsWith(s)}),n];this.baseStore.setState(o=>{const s={...o};return r.forEach(a=>{s.values=Za(s.values,a),delete this.fieldInfo[a],delete s.fieldMetaBase[a]}),s})},this.pushFieldValue=(n,i,r)=>{this.setFieldValue(n,o=>[...Array.isArray(o)?o:[],i],r)},this.insertFieldValue=async(n,i,r,o)=>{this.setFieldValue(n,a=>[...a.slice(0,i),r,...a.slice(i)],U(o,{dontValidate:!0}));const s=o?.dontValidate??!1;s||await this.validateField(n,"change"),lt(this).handleArrayFieldMetaShift(n,i,"insert"),s||await this.validateArrayFieldsStartingFrom(n,i,"change")},this.replaceFieldValue=async(n,i,r,o)=>{this.setFieldValue(n,a=>a.map((l,d)=>d===i?r:l),U(o,{dontValidate:!0})),(o?.dontValidate??!1)||(await this.validateField(n,"change"),await this.validateArrayFieldsStartingFrom(n,i,"change"))},this.removeFieldValue=async(n,i,r)=>{const o=this.getFieldValue(n),s=Array.isArray(o)?Math.max(o.length-1,0):null;if(this.setFieldValue(n,l=>l.filter((d,h)=>h!==i),U(r,{dontValidate:!0})),lt(this).handleArrayFieldMetaShift(n,i,"remove"),s!==null){const l=`${n}[${s}]`;this.deleteField(l)}(r?.dontValidate??!1)||(await this.validateField(n,"change"),await this.validateArrayFieldsStartingFrom(n,i,"change"))},this.swapFieldValues=(n,i,r,o)=>{this.setFieldValue(n,a=>{const l=a[i],d=a[r];return it(it(a,`${i}`,d),`${r}`,l)},U(o,{dontValidate:!0})),lt(this).handleArrayFieldMetaShift(n,i,"swap",r),(o?.dontValidate??!1)||(this.validateField(n,"change"),this.validateField(`${n}[${i}]`,"change"),this.validateField(`${n}[${r}]`,"change"))},this.moveFieldValues=(n,i,r,o)=>{this.setFieldValue(n,a=>{const l=[...a];return l.splice(r,0,l.splice(i,1)[0]),l},U(o,{dontValidate:!0})),lt(this).handleArrayFieldMetaShift(n,i,"move",r),(o?.dontValidate??!1)||(this.validateField(n,"change"),this.validateField(`${n}[${i}]`,"change"),this.validateField(`${n}[${r}]`,"change"))},this.clearFieldValues=(n,i)=>{const r=this.getFieldValue(n),o=Array.isArray(r)?Math.max(r.length-1,0):null;if(this.setFieldValue(n,[],U(i,{dontValidate:!0})),o!==null)for(let a=0;a<=o;a++){const l=`${n}[${a}]`;this.deleteField(l)}(i?.dontValidate??!1)||this.validateField(n,"change")},this.resetField=n=>{this.baseStore.setState(i=>({...i,fieldMetaBase:{...i.fieldMetaBase,[n]:at},values:this.options.defaultValues?it(i.values,n,Ve(this.options.defaultValues,n)):i.values}))},this.getAllErrors=()=>({form:{errors:this.state.errors,errorMap:this.state.errorMap},fields:Object.entries(this.state.fieldMeta).reduce((n,[i,r])=>(Object.keys(r).length&&r.errors.length&&(n[i]={errors:r.errors,errorMap:r.errorMap}),n),{})}),this.parseValuesWithSchema=n=>Fe.validate({value:this.state.values,validationSource:"form"},n),this.parseValuesWithSchemaAsync=n=>Fe.validateAsync({value:this.state.values,validationSource:"form"},n),this.timeoutIds={validations:{},listeners:{},formListeners:{}},this._formId=t?.formId??rl(),this._devtoolsSubmissionOverride=!1,this.baseStore=new Wt(Gt({...t?.defaultState,values:t?.defaultValues??t?.defaultState?.values})),this.fieldMetaDerived=new ne({deps:[this.baseStore],fn:({prevDepVals:n,currDepVals:i,prevVal:r})=>{const o=r,s=n?.[0],a=i[0];let l=0;const d={};for(const h of Object.keys(a.fieldMetaBase)){const c=a.fieldMetaBase[h],f=s?.fieldMetaBase[h],m=o?.[h],w=Ve(a.values,h);let p=m?.errors;if(!f||c.errorMap!==f.errorMap){p=Object.values(c.errorMap??{}).filter(C=>C!==void 0);const S=this.getFieldInfo(h)?.instance;S&&!S.options.disableErrorFlat&&(p=p?.flat(1))}const y=!il(p??[]),_=!c.isDirty,v=_e(w,Ve(this.options.defaultValues,h))||_e(w,this.getFieldInfo(h)?.instance?.options.defaultValue);if(m&&m.isPristine===_&&m.isValid===y&&m.isDefaultValue===v&&m.errors===p&&c===f){d[h]=m,l++;continue}d[h]={...c,errors:p,isPristine:_,isValid:y,isDefaultValue:v}}return Object.keys(a.fieldMetaBase).length&&o&&l===Object.keys(a.fieldMetaBase).length?o:d}}),this.store=new ne({deps:[this.baseStore,this.fieldMetaDerived],fn:({prevDepVals:n,currDepVals:i,prevVal:r})=>{const o=r,s=n?.[0],a=i[0],l=i[1],d=Object.values(l).filter(Boolean),h=d.some(x=>x.isValidating),c=d.every(x=>x.isValid),f=d.some(x=>x.isTouched),m=d.some(x=>x.isBlurred),w=d.every(x=>x.isDefaultValue),p=f&&a.errorMap?.onMount,y=d.some(x=>x.isDirty),_=!y,v=!!(a.errorMap?.onMount||d.some(x=>x?.errorMap?.onMount)),S=!!h;let C=o?.errors??[];(!s||a.errorMap!==s.errorMap)&&(C=Object.values(a.errorMap).reduce((x,pe)=>pe===void 0?x:pe&&zt(pe)?(x.push(pe.form),x):(x.push(pe),x),[]));const N=C.length===0,b=c&&N,T=this.options.canSubmitWhenInvalid??!1,k=a.submissionAttempts===0&&!f&&!v||!S&&!a.isSubmitting&&b||T;let X=a.errorMap;if(p&&(C=C.filter(x=>x!==a.errorMap.onMount),X=Object.assign(X,{onMount:void 0})),o&&s&&o.errorMap===X&&o.fieldMeta===this.fieldMetaDerived.state&&o.errors===C&&o.isFieldsValidating===h&&o.isFieldsValid===c&&o.isFormValid===N&&o.isValid===b&&o.canSubmit===k&&o.isTouched===f&&o.isBlurred===m&&o.isPristine===_&&o.isDefaultValue===w&&o.isDirty===y&&_e(s,a))return o;let $={...a,errorMap:X,fieldMeta:this.fieldMetaDerived.state,errors:C,isFieldsValidating:h,isFieldsValid:c,isFormValid:N,isValid:b,canSubmit:k,isTouched:f,isBlurred:m,isPristine:_,isDefaultValue:w,isDirty:y};const ae=this.options.transform?.deps??[];if(ae.length!==this.prevTransformArray.length||ae.some((x,pe)=>x!==this.prevTransformArray[pe])){const x=Object.assign({},this,{state:$});this.options.transform?.fn(x),$=x.state,this.prevTransformArray=ae}return $}}),this.handleSubmit=this.handleSubmit.bind(this),this.update(t||{}),this.store.subscribe(()=>{G.emit("form-state-change",{id:this._formId,state:this.store.state,options:this.options})}),G.on("request-form-state",n=>{n.payload.id===this._formId&&G.emit("form-state-change",{id:this._formId,state:this.store.state,options:this.options})}),G.on("request-form-reset",n=>{n.payload.id===this._formId&&this.reset()}),G.on("request-form-force-submit",n=>{n.payload.id===this._formId&&(this._devtoolsSubmissionOverride=!0,this.handleSubmit(),this._devtoolsSubmissionOverride=!1)})}get state(){return this.store.state}get formId(){return this._formId}runValidator(t){return Hn(t.validate)?Fe[t.type](t.value,t.validate):t.validate(t.value)}async handleSubmit(t){this.baseStore.setState(r=>({...r,isSubmitted:!1,submissionAttempts:r.submissionAttempts+1,isSubmitSuccessful:!1})),Y(()=>{Object.values(this.fieldInfo).forEach(r=>{r.instance&&(r.instance.state.meta.isTouched||r.instance.setMeta(o=>({...o,isTouched:!0})))})});const n=t??this.options.onSubmitMeta;if(!this.state.canSubmit&&!this._devtoolsSubmissionOverride){this.options.onSubmitInvalid?.({value:this.state.values,formApi:this,meta:n});return}this.baseStore.setState(r=>({...r,isSubmitting:!0}));const i=()=>{this.baseStore.setState(r=>({...r,isSubmitting:!1}))};if(await this.validateAllFields("submit"),!this.state.isFieldsValid){i(),this.options.onSubmitInvalid?.({value:this.state.values,formApi:this,meta:n}),G.emit("form-submission-state-change",{id:this._formId,submissionAttempt:this.state.submissionAttempts,successful:!1,stage:"validateAllFields",errors:Object.values(this.state.fieldMeta).map(r=>r.errors).flat()});return}if(await this.validate("submit"),!this.state.isValid){i(),this.options.onSubmitInvalid?.({value:this.state.values,formApi:this,meta:n}),G.emit("form-submission-state-change",{id:this._formId,submissionAttempt:this.state.submissionAttempts,successful:!1,stage:"validate",errors:this.state.errors});return}Y(()=>{Object.values(this.fieldInfo).forEach(r=>{r.instance?.options.listeners?.onSubmit?.({value:r.instance.state.value,fieldApi:r.instance})})}),this.options.listeners?.onSubmit?.({formApi:this,meta:n});try{await this.options.onSubmit?.({value:this.state.values,formApi:this,meta:n}),Y(()=>{this.baseStore.setState(r=>({...r,isSubmitted:!0,isSubmitSuccessful:!0})),G.emit("form-submission-state-change",{id:this._formId,submissionAttempt:this.state.submissionAttempts,successful:!0}),i()})}catch(r){throw this.baseStore.setState(o=>({...o,isSubmitSuccessful:!1})),G.emit("form-submission-state-change",{id:this._formId,submissionAttempt:this.state.submissionAttempts,successful:!1,stage:"inflight",onError:r}),i(),r}}setErrorMap(t){Y(()=>{Object.entries(t).forEach(([n,i])=>{const r=n;if(zt(i)){const{formError:o,fieldErrors:s}=ct(i);for(const a of Object.keys(this.fieldInfo))this.getFieldMeta(a)&&this.setFieldMeta(a,d=>({...d,errorMap:{...d.errorMap,[r]:s?.[a]},errorSourceMap:{...d.errorSourceMap,[r]:"form"}}));this.baseStore.setState(a=>({...a,errorMap:{...a.errorMap,[r]:o}}))}else this.baseStore.setState(o=>({...o,errorMap:{...o.errorMap,[r]:i}}))})})}}function ct(e){if(e){if(zt(e)){const t=ct(e.form).formError,n=e.fields;return{formError:t,fieldErrors:n}}return{formError:e}}return{formError:void 0}}function Ie(e){switch(e){case"submit":return"onSubmit";case"blur":return"onBlur";case"mount":return"onMount";case"server":return"onServer";case"dynamic":return"onDynamic";default:return"onChange"}}class cl{constructor(t){this.options={},this.mount=()=>{const n=this.store.mount();this.options.defaultValue!==void 0&&this.form.setFieldValue(this.name,this.options.defaultValue,{dontUpdateMeta:!0});const i=this.getInfo();i.instance=this,this.update(this.options);const{onMount:r}=this.options.validators||{};if(r){const o=this.runValidator({validate:r,value:{value:this.state.value,fieldApi:this,validationSource:"field"},type:"validate"});o&&this.setMeta(s=>({...s,errorMap:{...s?.errorMap,onMount:o},errorSourceMap:{...s?.errorSourceMap,onMount:"field"}}))}return this.options.listeners?.onMount?.({value:this.state.value,fieldApi:this}),n},this.update=n=>{this.options=n;const i=this.name!==n.name;if(this.name=n.name,this.state.value===void 0){const r=Ve(n.form.options.defaultValues,n.name),o=n.defaultValue??r;i?this.setValue(s=>s||o,{dontUpdateMeta:!0}):o!==void 0&&this.setValue(o,{dontUpdateMeta:!0})}this.form.getFieldMeta(this.name)===void 0&&this.setMeta(this.state.meta)},this.getValue=()=>this.form.getFieldValue(this.name),this.setValue=(n,i)=>{this.form.setFieldValue(this.name,n,U(i,{dontRunListeners:!0,dontValidate:!0})),i?.dontRunListeners||this.triggerOnChangeListener(),i?.dontValidate||this.validate("change")},this.getMeta=()=>this.store.state.meta,this.setMeta=n=>this.form.setFieldMeta(this.name,n),this.getInfo=()=>this.form.getFieldInfo(this.name),this.pushValue=(n,i)=>{this.form.pushFieldValue(this.name,n,U(i,{dontRunListeners:!0})),i?.dontRunListeners||this.triggerOnChangeListener()},this.insertValue=(n,i,r)=>{this.form.insertFieldValue(this.name,n,i,U(r,{dontRunListeners:!0})),r?.dontRunListeners||this.triggerOnChangeListener()},this.replaceValue=(n,i,r)=>{this.form.replaceFieldValue(this.name,n,i,U(r,{dontRunListeners:!0})),r?.dontRunListeners||this.triggerOnChangeListener()},this.removeValue=(n,i)=>{this.form.removeFieldValue(this.name,n,U(i,{dontRunListeners:!0})),i?.dontRunListeners||this.triggerOnChangeListener()},this.swapValues=(n,i,r)=>{this.form.swapFieldValues(this.name,n,i,U(r,{dontRunListeners:!0})),r?.dontRunListeners||this.triggerOnChangeListener()},this.moveValue=(n,i,r)=>{this.form.moveFieldValues(this.name,n,i,U(r,{dontRunListeners:!0})),r?.dontRunListeners||this.triggerOnChangeListener()},this.clearValues=n=>{this.form.clearFieldValues(this.name,U(n,{dontRunListeners:!0})),n?.dontRunListeners||this.triggerOnChangeListener()},this.getLinkedFields=n=>{const i=Object.values(this.form.fieldInfo),r=[];for(const o of i){if(!o.instance)continue;const{onChangeListenTo:s,onBlurListenTo:a}=o.instance.options.validators||{};n==="change"&&s?.includes(this.name)&&r.push(o.instance),n==="blur"&&a?.includes(this.name)&&r.push(o.instance)}return r},this.validateSync=(n,i)=>{const r=qt(n,{...this.options,form:this.form,validationLogic:this.form.options.validationLogic||ve}),s=this.getLinkedFields(n).reduce((d,h)=>{const c=qt(n,{...h.options,form:h.form,validationLogic:h.form.options.validationLogic||ve});return c.forEach(f=>{f.field=h}),d.concat(c)},[]);let a=!1;Y(()=>{const d=(h,c)=>{const f=ut(c.cause),m=c.validate?Xn(h.runValidator({validate:c.validate,value:{value:h.store.state.value,validationSource:"field",fieldApi:h},type:"validate"})):void 0,w=i[f],{newErrorValue:p,newSource:y}=Gn({formLevelError:w,fieldLevelError:m});h.state.meta.errorMap?.[f]!==p&&h.setMeta(_=>({..._,errorMap:{..._.errorMap,[f]:p},errorSourceMap:{..._.errorSourceMap,[f]:y}})),p&&(a=!0)};for(const h of r)d(this,h);for(const h of s)h.validate&&d(h.field,h)});const l=ut("submit");return this.state.meta.errorMap?.[l]&&n!=="submit"&&!a&&this.setMeta(d=>({...d,errorMap:{...d.errorMap,[l]:void 0},errorSourceMap:{...d.errorSourceMap,[l]:void 0}})),{hasErrored:a}},this.validateAsync=async(n,i)=>{const r=Kt(n,{...this.options,form:this.form,validationLogic:this.form.options.validationLogic||ve}),o=await i,s=this.getLinkedFields(n),a=s.reduce((f,m)=>{const w=Kt(n,{...m.options,form:m.form,validationLogic:m.form.options.validationLogic||ve});return w.forEach(p=>{p.field=m}),f.concat(w)},[]);this.state.meta.isValidating||this.setMeta(f=>({...f,isValidating:!0}));for(const f of s)f.setMeta(m=>({...m,isValidating:!0}));const l=[],d=[],h=(f,m,w)=>{const p=ut(m.cause);f.getInfo().validationMetaMap[p]?.lastAbortController.abort();const _=new AbortController;this.getInfo().validationMetaMap[p]={lastAbortController:_},w.push(new Promise(async v=>{let S;try{S=await new Promise((k,X)=>{this.timeoutIds.validations[m.cause]&&clearTimeout(this.timeoutIds.validations[m.cause]),this.timeoutIds.validations[m.cause]=setTimeout(async()=>{if(_.signal.aborted)return k(void 0);try{k(await this.runValidator({validate:m.validate,value:{value:f.store.state.value,fieldApi:f,signal:_.signal,validationSource:"field"},type:"validateAsync"}))}catch($){X($)}},m.debounceMs)})}catch(k){S=k}if(_.signal.aborted)return v(void 0);const C=Xn(S),N=o[this.name]?.[p],{newErrorValue:b,newSource:T}=Gn({formLevelError:N,fieldLevelError:C});f.setMeta(k=>({...k,errorMap:{...k?.errorMap,[p]:b},errorSourceMap:{...k.errorSourceMap,[p]:T}})),v(b)}))};for(const f of r)f.validate&&h(this,f,l);for(const f of a)f.validate&&h(f.field,f,d);let c=[];(l.length||d.length)&&(c=await Promise.all(l),await Promise.all(d)),this.setMeta(f=>({...f,isValidating:!1}));for(const f of s)f.setMeta(m=>({...m,isValidating:!1}));return c.filter(Boolean)},this.validate=(n,i)=>{if(!this.state.meta.isTouched)return[];const{fieldsErrorMap:r}=i?.skipFormValidation?{fieldsErrorMap:{}}:this.form.validateSync(n),{hasErrored:o}=this.validateSync(n,r[this.name]??{});if(o&&!this.options.asyncAlways)return this.getInfo().validationMetaMap[ut(n)]?.lastAbortController.abort(),this.state.meta.errors;const s=i?.skipFormValidation?Promise.resolve({}):this.form.validateAsync(n);return this.validateAsync(n,s)},this.handleChange=n=>{this.setValue(n)},this.handleBlur=()=>{this.state.meta.isTouched||this.setMeta(i=>({...i,isTouched:!0})),this.state.meta.isBlurred||this.setMeta(i=>({...i,isBlurred:!0})),this.validate("blur"),this.triggerOnBlurListener()},this.parseValueWithSchema=n=>Fe.validate({value:this.state.value,validationSource:"field"},n),this.parseValueWithSchemaAsync=n=>Fe.validateAsync({value:this.state.value,validationSource:"field"},n),this.form=t.form,this.name=t.name,this.timeoutIds={validations:{},listeners:{},formListeners:{}},this.store=new ne({deps:[this.form.store],fn:()=>{const n=this.form.getFieldValue(this.name),i=this.form.getFieldMeta(this.name)??{...at,...t.defaultMeta};return{value:n,meta:i}}}),this.options=t}get state(){return this.store.state}runValidator(t){return Hn(t.validate)?Fe[t.type](t.value,t.validate):t.validate(t.value)}setErrorMap(t){this.setMeta(n=>({...n,errorMap:{...n.errorMap,...t}}))}triggerOnBlurListener(){const t=this.form.options.listeners?.onBlurDebounceMs;t&&t>0?(this.timeoutIds.formListeners.blur&&clearTimeout(this.timeoutIds.formListeners.blur),this.timeoutIds.formListeners.blur=setTimeout(()=>{this.form.options.listeners?.onBlur?.({formApi:this.form,fieldApi:this})},t)):this.form.options.listeners?.onBlur?.({formApi:this.form,fieldApi:this});const n=this.options.listeners?.onBlurDebounceMs;n&&n>0?(this.timeoutIds.listeners.blur&&clearTimeout(this.timeoutIds.listeners.blur),this.timeoutIds.listeners.blur=setTimeout(()=>{this.options.listeners?.onBlur?.({value:this.state.value,fieldApi:this})},n)):this.options.listeners?.onBlur?.({value:this.state.value,fieldApi:this})}triggerOnChangeListener(){const t=this.form.options.listeners?.onChangeDebounceMs;t&&t>0?(this.timeoutIds.formListeners.change&&clearTimeout(this.timeoutIds.formListeners.change),this.timeoutIds.formListeners.change=setTimeout(()=>{this.form.options.listeners?.onChange?.({formApi:this.form,fieldApi:this})},t)):this.form.options.listeners?.onChange?.({formApi:this.form,fieldApi:this});const n=this.options.listeners?.onChangeDebounceMs;n&&n>0?(this.timeoutIds.listeners.change&&clearTimeout(this.timeoutIds.listeners.change),this.timeoutIds.listeners.change=setTimeout(()=>{this.options.listeners?.onChange?.({value:this.state.value,fieldApi:this})},n)):this.options.listeners?.onChange?.({value:this.state.value,fieldApi:this})}}function Xn(e){if(e)return e}function ut(e){switch(e){case"submit":return"onSubmit";case"blur":return"onBlur";case"mount":return"onMount";case"server":return"onServer";case"dynamic":return"onDynamic";default:return"onChange"}}var dt={exports:{}},Qt={},ft={exports:{}},Ht={};var Zn;function ul(){if(Zn)return Ht;Zn=1;var e=g;function t(c,f){return c===f&&(c!==0||1/c===1/f)||c!==c&&f!==f}var n=typeof Object.is=="function"?Object.is:t,i=e.useState,r=e.useEffect,o=e.useLayoutEffect,s=e.useDebugValue;function a(c,f){var m=f(),w=i({inst:{value:m,getSnapshot:f}}),p=w[0].inst,y=w[1];return o(function(){p.value=m,p.getSnapshot=f,l(p)&&y({inst:p})},[c,m,f]),r(function(){return l(p)&&y({inst:p}),c(function(){l(p)&&y({inst:p})})},[c]),s(m),m}function l(c){var f=c.getSnapshot;c=c.value;try{var m=f();return!n(c,m)}catch{return!0}}function d(c,f){return f()}var h=typeof window>"u"||typeof window.document>"u"||typeof window.document.createElement>"u"?d:a;return Ht.useSyncExternalStore=e.useSyncExternalStore!==void 0?e.useSyncExternalStore:h,Ht}var Xt={};var Yn;function dl(){return Yn||(Yn=1,process.env.NODE_ENV!=="production"&&(function(){function e(m,w){return m===w&&(m!==0||1/m===1/w)||m!==m&&w!==w}function t(m,w){h||r.startTransition===void 0||(h=!0,console.error("You are using an outdated, pre-release alpha of React 18 that does not support useSyncExternalStore. The use-sync-external-store shim will not work correctly. Upgrade to a newer pre-release."));var p=w();if(!c){var y=w();o(p,y)||(console.error("The result of getSnapshot should be cached to avoid an infinite loop"),c=!0)}y=s({inst:{value:p,getSnapshot:w}});var _=y[0].inst,v=y[1];return l(function(){_.value=p,_.getSnapshot=w,n(_)&&v({inst:_})},[m,p,w]),a(function(){return n(_)&&v({inst:_}),m(function(){n(_)&&v({inst:_})})},[m]),d(p),p}function n(m){var w=m.getSnapshot;m=m.value;try{var p=w();return!o(m,p)}catch{return!0}}function i(m,w){return w()}typeof __REACT_DEVTOOLS_GLOBAL_HOOK__<"u"&&typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart=="function"&&__REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart(Error());var r=g,o=typeof Object.is=="function"?Object.is:e,s=r.useState,a=r.useEffect,l=r.useLayoutEffect,d=r.useDebugValue,h=!1,c=!1,f=typeof window>"u"||typeof window.document>"u"||typeof window.document.createElement>"u"?i:t;Xt.useSyncExternalStore=r.useSyncExternalStore!==void 0?r.useSyncExternalStore:f,typeof __REACT_DEVTOOLS_GLOBAL_HOOK__<"u"&&typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop=="function"&&__REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop(Error())})()),Xt}var jn;function ei(){return jn||(jn=1,process.env.NODE_ENV==="production"?ft.exports=ul():ft.exports=dl()),ft.exports}var ti;function fl(){if(ti)return Qt;ti=1;var e=g,t=ei();function n(d,h){return d===h&&(d!==0||1/d===1/h)||d!==d&&h!==h}var i=typeof Object.is=="function"?Object.is:n,r=t.useSyncExternalStore,o=e.useRef,s=e.useEffect,a=e.useMemo,l=e.useDebugValue;return Qt.useSyncExternalStoreWithSelector=function(d,h,c,f,m){var w=o(null);if(w.current===null){var p={hasValue:!1,value:null};w.current=p}else p=w.current;w=a(function(){function _(b){if(!v){if(v=!0,S=b,b=f(b),m!==void 0&&p.hasValue){var T=p.value;if(m(T,b))return C=T}return C=b}if(T=C,i(S,b))return T;var k=f(b);return m!==void 0&&m(T,k)?(S=b,T):(S=b,C=k)}var v=!1,S,C,N=c===void 0?null:c;return[function(){return _(h())},N===null?void 0:function(){return _(N())}]},[h,c,f,m]);var y=r(d,w[0],w[1]);return s(function(){p.hasValue=!0,p.value=y},[y]),l(y),y},Qt}var Zt={};var ni;function hl(){return ni||(ni=1,process.env.NODE_ENV!=="production"&&(function(){function e(d,h){return d===h&&(d!==0||1/d===1/h)||d!==d&&h!==h}typeof __REACT_DEVTOOLS_GLOBAL_HOOK__<"u"&&typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart=="function"&&__REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart(Error());var t=g,n=ei(),i=typeof Object.is=="function"?Object.is:e,r=n.useSyncExternalStore,o=t.useRef,s=t.useEffect,a=t.useMemo,l=t.useDebugValue;Zt.useSyncExternalStoreWithSelector=function(d,h,c,f,m){var w=o(null);if(w.current===null){var p={hasValue:!1,value:null};w.current=p}else p=w.current;w=a(function(){function _(b){if(!v){if(v=!0,S=b,b=f(b),m!==void 0&&p.hasValue){var T=p.value;if(m(T,b))return C=T}return C=b}if(T=C,i(S,b))return T;var k=f(b);return m!==void 0&&m(T,k)?(S=b,T):(S=b,C=k)}var v=!1,S,C,N=c===void 0?null:c;return[function(){return _(h())},N===null?void 0:function(){return _(N())}]},[h,c,f,m]);var y=r(d,w[0],w[1]);return s(function(){p.hasValue=!0,p.value=y},[y]),l(y),y},typeof __REACT_DEVTOOLS_GLOBAL_HOOK__<"u"&&typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop=="function"&&__REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop(Error())})()),Zt}var ii;function pl(){return ii||(ii=1,process.env.NODE_ENV==="production"?dt.exports=fl():dt.exports=hl()),dt.exports}var ml=pl();function ri(e,t=n=>n){return ml.useSyncExternalStoreWithSelector(e.subscribe,()=>e.state,()=>e.state,t,gl)}function gl(e,t){if(Object.is(e,t))return!0;if(typeof e!="object"||e===null||typeof t!="object"||t===null)return!1;if(e instanceof Map&&t instanceof Map){if(e.size!==t.size)return!1;for(const[i,r]of e)if(!t.has(i)||!Object.is(r,t.get(i)))return!1;return!0}if(e instanceof Set&&t instanceof Set){if(e.size!==t.size)return!1;for(const i of e)if(!t.has(i))return!1;return!0}if(e instanceof Date&&t instanceof Date)return e.getTime()===t.getTime();const n=oi(e);if(n.length!==oi(t).length)return!1;for(let i=0;i<n.length;i++)if(!Object.prototype.hasOwnProperty.call(t,n[i])||!Object.is(e[n[i]],t[n[i]]))return!1;return!0}function oi(e){return Object.keys(e).concat(Object.getOwnPropertySymbols(e))}const ht=typeof window<"u"?g.useLayoutEffect:g.useEffect;function wl(e){const[t]=g.useState(()=>{const i=new cl({...e,form:e.form,name:e.name});return i.Field=si,i});return ht(t.mount,[t]),ht(()=>{t.update(e)}),ri(t.store,e.mode==="array"?n=>[n.meta,Object.keys(n.value??[]).length]:void 0),t}const si=(({children:e,...t})=>{const n=wl(t),i=g.useMemo(()=>nt(e,n),[e,n,n.state.value,n.state.meta]);return u.jsx(u.Fragment,{children:i})});function yl({form:e,selector:t,children:n}){const i=ri(e.store,t);return nt(n,i)}function Q(e){const[t]=g.useState(()=>{const n=new ll(e),i=n;return i.Field=function(o){return u.jsx(si,{...o,form:n})},i.Subscribe=function(o){return u.jsx(yl,{form:n,selector:o.selector,children:o.children})},i});return ht(t.mount,[]),ht(()=>{t.update(e)}),t}var ai=(e=>(e.Code="code",e))(ai||{});function _l({onError:e,onVerificationSuccess:t}){const{verifiableAddress:n}=z(),{mutateAsync:i}=$n(),{data:r}=Rt();return Q({defaultValues:{[ai.Code]:""},onSubmit:async({value:o,formApi:s})=>{if(!r||!n)return;const a=await i({csrf_token:I(r),method:"code",code:o.code,email:n});if(a){if(a.state==vn.PassedChallenge){t?.();return}R(a,s,e)}}})}function vl({emailVerificationForm:e,onError:t,onVerificationSuccess:n}){const i=_l({onError:t,onVerificationSuccess:n}),r=q(i);return u.jsx(fa,{emailVerificationForm:i,children:u.jsx("form",{onSubmit:o=>{o.preventDefault(),i.handleSubmit()},children:u.jsx(e,{Code:Ga,errors:r,isSubmitting:i.state.isSubmitting,isValidating:i.state.isValidating,Resend:za,Submit:W})})})}function li(e){return u.jsx(Ye,{children:u.jsx(pt,{...e})})}function pt({emailVerificationForm:e,initialFlowId:t,initialVerifiableAddress:n,returnTo:i,onError:r,onVerificationSuccess:o,onFlowRestart:s}){const{verificationFlowId:a,setVerificationFlowId:l,verifiableAddress:d,setVerifiableAddress:h}=z(),{error:c}=Rt(),{mutate:f}=Ka({returnTo:i});return be({initialFlowId:t,currentFlowId:a,error:c,onFlowRestart:s,createFlow:f,setFlowId:l}),!d&&n&&h(n),u.jsx(vl,{emailVerificationForm:e,onError:r,onVerificationSuccess:o})}const Fl=Object.freeze(Object.defineProperty({__proto__:null,VerificationFlow:li,VerificationFlowProvider:Ye,VerificationFlowWrapper:pt,useVerificationFlowContext:z},Symbol.toStringTag,{value:"Module"})),Sl=ue("login_flow"),mt=(e="no_id")=>ce([Sl,e]),ci=g.createContext(void 0);function bl({children:e}){const[t,n]=g.useState(),i=g.useCallback(()=>{n(void 0)},[]);return u.jsx(ci.Provider,{value:{loginFlowId:t,setLoginFlowId:n,resetFlow:i},children:e})}function gt(){const e=g.useContext(ci);if(e===void 0)throw new Error("useLoginFlowContext must be used within a LoginFlow");return e}function kl({aal:e,refresh:t,returnTo:n}={}){const{kratosClient:i}=D(),{setLoginFlowId:r}=gt(),o=J();return Z({mutationFn:async()=>{try{return await i.createBrowserLoginFlow({aal:e,refresh:t,returnTo:n},async({init:{headers:s}})=>({headers:{...s,Accept:"application/json"}}))}catch(s){throw await oe({onRestartFlow:()=>{},onRedirect:()=>{},onValidationError:a=>a})(s)}},onSuccess(s){o.setQueryDefaults(mt(s.id),{staleTime:1/0}),o.setQueryData(mt(s.id),s),r(s.id)}})}function H(){const{kratosClient:e}=D(),{loginFlowId:t}=gt();return de({queryKey:mt(t),queryFn:async({signal:n})=>{if(!t)throw new Error("No login flow ID provided",{cause:ie.NoFlowId});try{return await e.getLoginFlow({id:t},async({init:{headers:i}})=>({signal:n,headers:{...i,Accept:"application/json"}}))}catch(i){throw await Te({error:i})}},enabled:!!t,staleTime:1/0})}const ui=()=>{const{data:e}=H();return g.useMemo(()=>{if(!e)return;const t=P(e.ui.nodes,"identifier");if(!(!t||t.attributes.node_type!=="input"||typeof t.attributes.value!="string"))return t.attributes.value},[e])};function he(){const{kratosClient:e}=D(),{loginFlowId:t,resetFlow:n}=gt(),{setVerificationFlowId:i,setVerifiableAddress:r}=z(),o=J();return Z({mutationFn:async s=>{if(!t)throw new Error("Login flow ID is not set");try{const l=await(await e.updateLoginFlowRaw({flow:t,updateLoginFlowBody:s},{headers:{Accept:"application/json","Content-Type":"application/json"}})).value();if(l&&"continue_with"in l){const d=l.continue_with?.find(h=>h.action==="show_verification_ui");d!==void 0?(i(d.flow.id),r(d.flow.verifiable_address)):It(l.continue_with,{onRedirect:(h,c)=>{globalThis.location.href=h}})}return l}catch(a){return await oe({onRedirect:(l,d)=>{globalThis.location.href=l},onRestartFlow:n,onValidationError:l=>l})(a)}},onSuccess(s){s&&"id"in s&&o.setQueryData(mt(s.id),s)}})}const di=g.createContext(void 0);function Cl({children:e,passwordForm:t}){const n=g.useMemo(()=>({passwordForm:t}),[t]);return u.jsx(di.Provider,{value:n,children:e})}function Yt(){const e=g.useContext(di);if(e===void 0)throw new Error("useChooseMethodFormContext must be used within a ChooseMethodFormProvider");return e}function jt({children:e,provider:t}){const{mutate:n}=he(),{data:i}=H(),r=g.useCallback(()=>{i&&n({method:"oidc",csrf_token:I(i),provider:t})},[i,n,t]),o=O;return u.jsx(o,{type:"button",onClick:r,children:e})}function fi({children:e}){return u.jsx(jt,{provider:"apple",children:e})}function hi({children:e}){return u.jsx(jt,{provider:"facebook",children:e})}function pi({children:e}){return u.jsx(jt,{provider:"google",children:e})}function Tl({children:e}){const{passwordForm:t}=Yt(),n=O;return u.jsx(t.Field,{name:"identifier",children:i=>u.jsx(n,{errors:L(i.state.meta.errorMap),name:i.name,type:"text",value:i.state.value,onChange:r=>i.handleChange(r.target.value),children:e})})}function mi({children:e}){const{passwordForm:t}=Yt(),n=O;return u.jsx(t.Field,{name:"password",children:i=>u.jsx(n,{errors:L(i.state.meta.errorMap),name:i.name,type:"password",value:i.state.value,onChange:r=>i.handleChange(r.target.value),children:e})})}function El({children:e,onError:t,onLoginSuccess:n}){const{mutateAsync:i}=he(),{data:r}=H(),{passwordForm:o}=Yt(),s=g.useCallback(async c=>{if(!r)return;const f=await i({method:"passkey",csrf_token:I(r),passkey_login:c});if(f){if(We(f)){n?.();return}R(f,o,t)}},[r,t,n,o,i]),a=g.useMemo(()=>le(P(r?.ui.nodes,"passkey_challenge")),[r?.ui.nodes]),l=g.useMemo(()=>ce([ue("passkey"),a?.value]),[a?.value]);de({queryKey:l,queryFn:async({signal:c})=>{if(!a)throw new Error("No challenge provided");const f=await Yi(a.value,c);return f?await s(f):!1},enabled:!!a,retry:!1});const d=g.useCallback(async()=>{if(!a)return;const c=await ji(a.value);c&&s(c)},[a,s]),h=O;return u.jsx(h,{type:"button",onClick:d,children:e})}var Ne=(e=>(e.Identifier="identifier",e.Password="password",e))(Ne||{});function Ml({onError:e,onLoginSuccess:t}){const{mutateAsync:n}=he(),{data:i}=H(),r=ui();return Q({defaultValues:{[Ne.Identifier]:r??"",[Ne.Password]:""},onSubmit:async({value:o,formApi:s})=>{if(!i)return;const a=await n({csrf_token:I(i),method:"password",identifier:o[Ne.Identifier],password:o[Ne.Password]});if(a){if(We(a)){t?.();return}R(a,s,e)}}})}function Ol({chooseMethodForm:e,isRefresh:t,onError:n,onLoginSuccess:i}){const{data:r}=H(),o=Ml({onError:n,onLoginSuccess:i}),s=q(o),a=ui(),l=g.useCallback(d=>u.jsx(El,{...d,onError:n}),[n]);return r?u.jsx(Cl,{passwordForm:o,children:u.jsx("form",{onSubmit:d=>{d.preventDefault(),o.handleSubmit()},children:t?u.jsx(e,{isRefresh:!0,Apple:Ke(r.ui.nodes,"apple")?fi:void 0,errors:s,Facebook:Ke(r.ui.nodes,"facebook")?hi:void 0,Google:Ke(r.ui.nodes,"google")?pi:void 0,identifier:a,isSubmitting:o.state.isSubmitting,isValidating:o.state.isValidating,Passkey:P(r.ui.nodes,"passkey_login")&&l,passwordFields:P(r.ui.nodes,"password")&&{Password:mi,Submit:W}}):u.jsx(e,{Apple:fi,errors:s,Facebook:hi,Google:pi,isSubmitting:o.state.isSubmitting,isValidating:o.state.isValidating,Passkey:l,passwordFields:{Identifier:Tl,Password:mi,Submit:W}})})}):null}function xl({children:e}){const{mutate:t}=he(),{data:n}=H(),i=g.useCallback(()=>{if(!n)return;const o=le(P(n.ui.nodes,"identifier"))?.value;t({method:"code",csrf_token:I(n),resend:"code",identifier:o})},[n,t]),r=O;return u.jsx(r,{type:"button",onClick:i,children:e})}const gi=g.createContext(void 0);function Vl({children:e,codeForm:t}){const n=g.useMemo(()=>({codeForm:t}),[t]);return u.jsx(gi.Provider,{value:n,children:e})}function Il(){const e=g.useContext(gi);if(e===void 0)throw new Error("useSecondFactorEmailFormContext must be used within a SecondFactorEmailFormProvider");return e}function Nl({children:e}){const{codeForm:t}=Il(),n=O;return u.jsx(t.Field,{name:"code",children:i=>u.jsx(n,{errors:L(i.state.meta.errorMap),name:i.name,type:"text",value:i.state.value,onChange:r=>i.handleChange(r.target.value),children:e})})}var wi=(e=>(e.Code="code",e))(wi||{});function Ll({onError:e,onLoginSuccess:t}){const{mutateAsync:n}=he(),{data:i}=H();return Q({defaultValues:{[wi.Code]:""},onSubmit:async({value:r,formApi:o})=>{if(!i)return;const s=le(P(i.ui.nodes,"identifier"))?.value,a=await n({csrf_token:I(i),method:"code",code:r.code,identifier:s});if(a){if(We(a)){t?.();return}R(a,o,e)}}})}function Dl({secondFactorForm:e,onError:t,onLoginSuccess:n}){const i=Ll({onError:t,onLoginSuccess:n}),r=q(i);return u.jsx(Vl,{codeForm:i,children:u.jsx("form",{onSubmit:o=>{o.preventDefault(),i.handleSubmit()},children:u.jsx(e,{Code:Nl,errors:r,isSubmitting:i.state.isSubmitting,isValidating:i.state.isValidating,Resend:xl,Submit:W})})})}function Al({children:e}){const{mutate:t}=he(),{data:n}=H(),i=g.useCallback(()=>{if(!n)return;const o=le(P(n.ui.nodes,"address"))?.value;o&&t({method:"code",csrf_token:I(n),address:o})},[n,t]),r=O;return u.jsx(r,{type:"button",onClick:i,children:e})}const yi=g.createContext(void 0),Pl=({children:e,totpForm:t})=>{const n=g.useMemo(()=>({totpForm:t}),[t]);return u.jsx(yi.Provider,{value:n,children:e})};function Ul(){const e=g.useContext(yi);if(e===void 0)throw new Error("useSecondFactorFormContext must be used within a SecondFactorFormProvider");return e}function Rl({children:e}){const{totpForm:t}=Ul(),n=O;return u.jsx(t.Field,{name:"totp_code",children:i=>u.jsx(n,{errors:L(i.state.meta.errorMap),name:i.name,type:"text",value:i.state.value,onChange:r=>i.handleChange(r.target.value),children:e})})}var _i=(e=>(e.TotpCode="totp_code",e))(_i||{});function Jl({onError:e,onLoginSuccess:t}){const{mutateAsync:n}=he(),{data:i}=H();return Q({defaultValues:{[_i.TotpCode]:""},onSubmit:async({value:r,formApi:o})=>{if(!i)return;const s=await n({csrf_token:I(i),method:"totp",totp_code:r.totp_code});if(s){if(We(s)){t?.();return}R(s,o,e)}}})}function Wl({secondFactorForm:e,isRefresh:t,onError:n,onLoginSuccess:i}){const r=Jl({onError:n,onLoginSuccess:i}),o=q(r),{data:s}=H();return u.jsx(Pl,{totpForm:r,children:u.jsx("form",{onSubmit:a=>{a.preventDefault(),r.handleSubmit()},children:u.jsx(e,{Email:P(s?.ui.nodes,"address")&&Al,errors:o,isRefresh:t,isSubmitting:r.state.isSubmitting,isValidating:r.state.isValidating,Submit:W,Totp:Rl})})})}function Bl({loaderComponent:e,chooseMethodForm:t,secondFactorForm:n,secondFactorEmailForm:i,emailVerificationForm:r,initialFlowId:o,returnTo:s,onError:a,onLoginSuccess:l,onVerificationSuccess:d,onFlowRestart:h,onSessionAlreadyAvailable:c}){const{loginFlowId:f,setLoginFlowId:m}=gt(),{verificationFlowId:w}=z(),{sessionManager:p}=St(),{isAal2Required:y}=p.useIsAal2Required(),{mutate:_,error:v}=kl({returnTo:s,aal:y?"aal2":void 0}),{data:S,error:C}=H();be({initialFlowId:o,currentFlowId:f,error:C??void 0,onFlowRestart:h,createFlow:_,setFlowId:m,waitForSession:!0});const N=g.useMemo(()=>$e(v)||$e(C),[v,C]);g.useEffect(()=>{N&&c?.()},[N,c]);const b=g.useMemo(()=>{if(N)return"invalid";if(!S)return"loader";if(w)return"verifyEmail";if(S.state==="choose_method"){if(S.requested_aal==="aal1")return"chooseMethod";if(S.requested_aal==="aal2")return"secondFactor"}if(S.state==="sent_email")return"secondFactorEmail";throw new Error("Invalid login flow state")},[S,w,N]),T=g.useMemo(()=>S?.refresh,[S]);return u.jsxs(u.Fragment,{children:[b==="loader"&&e&&u.jsx(e,{}),b==="chooseMethod"&&u.jsx(Ol,{chooseMethodForm:t,isRefresh:T,onError:a,onLoginSuccess:l}),b==="secondFactor"&&u.jsx(Wl,{isRefresh:T,secondFactorForm:n,onError:a,onLoginSuccess:l}),b==="secondFactorEmail"&&u.jsx(Dl,{secondFactorForm:i,onError:a,onLoginSuccess:l}),b==="verifyEmail"&&u.jsx(pt,{emailVerificationForm:r,onError:a,onVerificationSuccess:d})]})}function vi(e){return u.jsx(Ye,{children:u.jsx(bl,{children:u.jsx(Bl,{...e})})})}const $l=Object.freeze(Object.defineProperty({__proto__:null,LoginFlow:vi},Symbol.toStringTag,{value:"Module"})),Fi=()=>{const{kratosClient:e}=D(),{sessionManager:t}=St(),n=J();return{logout:async({returnTo:r}={})=>{try{const o=await e.createBrowserLogoutFlow({returnTo:r},async({init:{headers:s}})=>({credentials:"include",headers:{...s,Accept:"application/json","Content-Type":"application/json"}}));return await e.updateLogoutFlow({token:o.logout_token},{headers:{Accept:"application/json","Content-Type":"application/json"}}),t.checkIfLoggedIn(),r&&(globalThis.location.href=r),n.removeQueries({queryKey:[Lt]}),{isSuccess:!0}}catch(o){return{isSuccess:!1,error:o}}}}},ql=Object.freeze(Object.defineProperty({__proto__:null,useLogout:Fi},Symbol.toStringTag,{value:"Module"})),Si=g.createContext(void 0);function Kl({children:e,chooseMethodForm:t}){const n=g.useMemo(()=>({chooseMethodForm:t}),[t]);return u.jsx(Si.Provider,{value:n,children:e})}function en(){const e=g.useContext(Si);if(e===void 0)throw new Error("useChooseMethodFormContext must be used within a ChooseMethodFormProvider");return e}const zl=ue("registration_flow"),wt=(e="no_id")=>ce([zl,e]),bi=g.createContext(void 0);function Gl({children:e}){const[t,n]=g.useState(),[i,r]=g.useState(!1),[o,s]=g.useState(),a=g.useCallback(()=>{n(void 0),r(!1),s(void 0)},[]);return u.jsx(bi.Provider,{value:{registrationFlowId:t,setRegistrationFlowId:n,traitsFormCompleted:i,setTraitsFormCompleted:r,traits:o,setTraits:s,resetFlow:a},children:e})}function se(){const e=g.useContext(bi);if(e===void 0)throw new Error("useRegistrationFlowContext must be used within a RegistrationFlow");return e}function Ql({returnTo:e}={}){const{kratosClient:t}=D(),{setRegistrationFlowId:n}=se(),i=J();return Z({mutationFn:async()=>{try{return await t.createBrowserRegistrationFlow({returnTo:e},async({init:{headers:r}})=>({headers:{...r,Accept:"application/json"}}))}catch(r){throw await oe({onRestartFlow:()=>{},onRedirect:()=>{},onValidationError:o=>o})(r)}},onSuccess(r){i.setQueryDefaults(wt(r.id),{staleTime:1/0}),i.setQueryData(wt(r.id),r),n(r.id)}})}function Le(){const{kratosClient:e}=D(),{registrationFlowId:t}=se();return de({queryKey:wt(t),queryFn:async({signal:n})=>{if(!t)throw new Error("No registration flow ID provided",{cause:ie.NoFlowId});try{return await e.getRegistrationFlow({id:t},async({init:{headers:i}})=>({signal:n,headers:{...i,Accept:"application/json"}}))}catch(i){throw await Te({error:i})}},enabled:!!t,staleTime:1/0})}function yt(){const{kratosClient:e}=D(),{resetFlow:t,registrationFlowId:n}=se(),{setVerificationFlowId:i,setVerifiableAddress:r}=z(),o=J();return Z({mutationFn:async s=>{if(!n)throw new Error("Registration flow ID is not set");try{const l=await(await e.updateRegistrationFlowRaw({flow:n,updateRegistrationFlowBody:s},{headers:{Accept:"application/json","Content-Type":"application/json"}})).value();if(l&&"continue_with"in l){const d=l.continue_with?.find(h=>h.action==="show_verification_ui");d!==void 0?(i(d.flow.id),r(d.flow.verifiable_address)):It(l.continue_with,{onRedirect:(h,c)=>{globalThis.location.href=h}})}return l}catch(a){return await oe({onRedirect:(l,d)=>{globalThis.location.href=l},onRestartFlow:t,onValidationError:l=>l})(a)}},onSuccess(s){s&&"id"in s&&o.setQueryData(wt(s.id),s)}})}function Hl({children:e}){const{setTraitsFormCompleted:t}=se(),n=g.useCallback(()=>{t(!1)},[t]),i=O;return u.jsx(i,{type:"button",onClick:n,children:e})}function Xl({children:e,onError:t,onRegistrationSuccess:n}){const{traits:i}=se(),{mutateAsync:r}=yt(),{data:o}=Le(),{chooseMethodForm:s}=en(),a=g.useCallback(async c=>{if(!o)return;const f=await r({method:"passkey",csrf_token:I(o),traits:i??{},passkey_register:c});if(f){if(Vt(f)){n?.();return}R(f,s,t)}},[t,n,o,i,s,r]),l=g.useMemo(()=>le(P(o?.ui.nodes,"passkey_create_data")),[o?.ui.nodes]),d=g.useCallback(async()=>{if(!l)return;const c=await er(l.value,void 0,i);c&&a(c)},[l,a,i]),h=O;return u.jsx(h,{type:"button",onClick:d,children:e})}function Zl({children:e}){const{chooseMethodForm:t}=en(),n=O;return u.jsx(t.Field,{name:"password",children:i=>u.jsx(n,{errors:L(i.state.meta.errorMap),name:i.name,type:"password",value:i.state.value,onChange:r=>i.handleChange(r.target.value),children:e})})}var j=(e=>(e.Password="password",e.PasswordConfirmation="password_confirmation",e))(j||{});const ki=({value:e,fieldApi:t})=>{const n=t.form.getFieldMeta(j.PasswordConfirmation);if(n?.isDirty&&n?.isTouched)return Ci(e,t.form.getFieldValue(j.Password))},Ci=(e,t)=>{if(!e)return[qe(Ce.FieldRequired)];if(e!==t)return[qe(Ce.FieldMismatch)]};function Yl({children:e}){const{chooseMethodForm:t}=en(),n=O;return u.jsx(t.Field,{listeners:{onChange:({fieldApi:i})=>{i.form.setFieldMeta(j.PasswordConfirmation,r=>({...r,errorMap:{...r.errorMap,onSubmit:void 0}}))}},name:"password_confirmation",validators:{onChangeListenTo:[j.Password],onChange:ki,onBlurListenTo:[j.PasswordConfirmation],onBlur:ki,onSubmit:({value:i,fieldApi:r})=>Ci(i,r.form.getFieldValue(j.Password))},children:i=>u.jsx(n,{errors:L(i.state.meta.errorMap),name:i.name,type:"password",value:i.state.value,onBlur:i.handleBlur,onChange:r=>i.handleChange(r.target.value),children:e})})}function jl({onError:e,onRegistrationSuccess:t}){const{setTraitsFormCompleted:n,traits:i}=se(),{mutateAsync:r}=yt(),{data:o}=Le();return Q({defaultValues:{[j.Password]:"",[j.PasswordConfirmation]:""},onSubmit:async({value:s,formApi:a})=>{if(!o)return;const l=await r({csrf_token:I(o),method:"password",traits:i??{},password:s[j.Password]});if(l){if(Vt(l)){t?.();return}l.state===_n.ChooseMethod&&n(!0),R(l,a,e)}}})}function ec({chooseMethodForm:e,onError:t,onRegistrationSuccess:n}){const i=jl({onError:t,onRegistrationSuccess:n}),r=q(i);return u.jsx(Kl,{chooseMethodForm:i,children:u.jsx("form",{onSubmit:o=>{o.preventDefault(),i.handleSubmit()},children:u.jsx(e,{errors:r,isSubmitting:i.state.isSubmitting,isValidating:i.state.isValidating,Passkey:Xl,passwordFields:{Password:Zl,PasswordConfirmation:Yl,Submit:W},ReturnToTraitsForm:Hl})})})}function tn({children:e,provider:t}){const{mutate:n}=yt(),{data:i}=Le(),r=g.useCallback(()=>{i&&n({method:"oidc",csrf_token:I(i),provider:t})},[i,n,t]),o=O;return u.jsx(o,{type:"button",onClick:r,children:e})}function tc({children:e}){return u.jsx(tn,{provider:"apple",children:e})}function nc({children:e}){return u.jsx(tn,{provider:"facebook",children:e})}function ic({children:e}){return u.jsx(tn,{provider:"google",children:e})}const Ti=g.createContext(void 0);function rc({children:e,traitsForm:t}){const n=g.useMemo(()=>({traitsForm:t}),[t]);return u.jsx(Ti.Provider,{value:n,children:e})}function Ei(){const e=g.useContext(Ti);if(e===void 0)throw new Error("useTraitsFormContext must be used within a TraitsFormProvider");return e}function oc({trait:e,children:t}){const{traitsForm:n}=Ei(),i=O;return u.jsx(n.Field,{name:`${me}${e}`,children:r=>{if(typeof r.state.value!="string")throw new TypeError("TraitInput: value is not string");return u.jsx(i,{errors:L(r.state.meta.errorMap),name:r.name,type:"text",value:r.state.value,onChange:o=>r.handleChange(o.target.value),children:t})}})}function sc({trait:e,children:t}){const{traitsForm:n}=Ei(),i=O;return u.jsx(n.Field,{name:`${me}${e}`,children:r=>{if(typeof r.state.value!="boolean")throw new TypeError("TraitCheckbox: value is not boolean");return u.jsx(i,{checked:r.state.value,errors:L(r.state.meta.errorMap),name:r.name,type:"checkbox",onChange:o=>r.handleChange(o.target.checked),children:t})}})}function ac({traitsConfig:e,onError:t,onRegistrationSuccess:n}){const{setTraitsFormCompleted:i,setTraits:r,traits:o}=se(),{mutateAsync:s}=yt(),{data:a}=Le();return Q({defaultValues:{traits:o??Object.fromEntries(Object.values(e).map(({trait:l,type:d})=>[l,d==="boolean"?!1:""]))},onSubmit:async({value:l,formApi:d})=>{if(!a)return;const h=await s({csrf_token:I(a),method:"profile",traits:l.traits??{}});if(h){if(Vt(h)){n?.();return}h.state===_n.ChooseMethod&&h.ui.messages?.some(({id:c})=>c===1040009)&&(r(l.traits),i(!0)),R(h,d,t)}}})}function lc({traitsConfig:e,traitsForm:t,onError:n,onRegistrationSuccess:i}){const r=ac({traitsConfig:e,onError:n,onRegistrationSuccess:i}),o=q(r),s=g.useMemo(()=>Object.fromEntries(Object.entries(e).map(([a,l])=>[a,l.type==="boolean"?({children:d})=>u.jsx(sc,{children:d,trait:l.trait}):({children:d})=>u.jsx(oc,{children:d,trait:l.trait})])),[e]);return u.jsx(rc,{traitsForm:r,children:u.jsx("form",{onSubmit:a=>{a.preventDefault(),r.handleSubmit()},children:u.jsx(t,{Apple:tc,errors:o,Facebook:nc,Google:ic,isSubmitting:r.state.isSubmitting,isValidating:r.state.isValidating,traitFields:{...s,Submit:W}})})})}function cc({traitsConfig:e,traitsForm:t,chooseMethodForm:n,emailVerificationForm:i,initialFlowId:r,returnTo:o,onError:s,onRegistrationSuccess:a,onVerificationSuccess:l,onFlowRestart:d,onSessionAlreadyAvailable:h}){const{verificationFlowId:c}=z(),{registrationFlowId:f,setRegistrationFlowId:m,traitsFormCompleted:w}=se(),{error:p}=Le(),{mutate:y,error:_}=Ql({returnTo:o});be({initialFlowId:r,currentFlowId:f,error:p??void 0,onFlowRestart:d,createFlow:y,setFlowId:m});const v=g.useMemo(()=>$e(p)||$e(_),[p,_]);g.useEffect(()=>{v&&h?.()},[v,h]);const S=g.useMemo(()=>v?"invalid":c?"emailVerification":w?"credentials":"traits",[w,c,v]);return u.jsxs(u.Fragment,{children:[S==="traits"&&u.jsx(lc,{traitsConfig:e,traitsForm:t,onError:s,onRegistrationSuccess:a}),S==="credentials"&&u.jsx(ec,{chooseMethodForm:n,onError:s,onRegistrationSuccess:a}),S==="emailVerification"&&u.jsx(pt,{emailVerificationForm:i,onError:s,onVerificationSuccess:l})]})}function Mi(e){return u.jsx(Ye,{children:u.jsx(Gl,{children:u.jsx(cc,{...e})})})}const uc=Object.freeze(Object.defineProperty({__proto__:null,RegistrationFlow:Mi},Symbol.toStringTag,{value:"Module"})),dc=ue("settings_flow"),_t=(e="no_id")=>ce([dc,e]),Oi=g.createContext(void 0);function nn({children:e}){const[t,n]=g.useState(),[i,r]=g.useState(!1),o=g.useCallback(()=>{n(void 0)},[]);return u.jsx(Oi.Provider,{value:{settingsFlowId:t,setSettingsFlowId:n,emailVerificationRequired:i,setEmailVerificationRequired:r,resetFlow:o},children:e})}function De(){const e=g.useContext(Oi);if(e===void 0)throw new Error("useSettingsFlow must be used within a SettingsFlowProvider");return e}function fc(){const{kratosClient:e}=D(),{setSettingsFlowId:t}=De(),n=J();return Z({mutationFn:()=>e.createBrowserSettingsFlow({},async({init:{headers:i}})=>({headers:{...i,Accept:"application/json"}})),onSuccess(i){n.setQueryDefaults(_t(i.id),{staleTime:1/0}),n.setQueryData(_t(i.id),i),t(i.id)}})}function B(){const{kratosClient:e}=D(),{settingsFlowId:t}=De();return de({queryKey:_t(t),queryFn:async({signal:n})=>{if(!t)throw new Error("No settings flow ID provided",{cause:ie.NoFlowId});try{return await e.getSettingsFlow({id:t},async({init:{headers:i}})=>({signal:n,headers:{...i,Accept:"application/json"}}))}catch(i){throw await Te({error:i})}},enabled:!!t,staleTime:1/0})}function Se(){const{kratosClient:e}=D(),{settingsFlowId:t,resetFlow:n,setEmailVerificationRequired:i}=De(),r=J();return Z({mutationFn:async o=>{if(!t)throw new Error("Settings flow ID is not set");try{const s=await e.updateSettingsFlow({flow:t,updateSettingsFlowBody:o},{headers:{Accept:"application/json","Content-Type":"application/json"}});return s&&"continue_with"in s&&(s.continue_with?.find(l=>l.action==="show_verification_ui")?i(!0):It(s.continue_with,{onRedirect:(l,d)=>{globalThis.location.href=l}})),s}catch(s){return await oe({onRedirect:(a,l)=>{globalThis.location.href=a},onRestartFlow:n,onValidationError:a=>a})(s)}},onSuccess(o){o&&"id"in o&&r.setQueryData(_t(o.id),o)}})}const xi=g.createContext(void 0);function hc({children:e,newPasswordForm:t}){const n=g.useMemo(()=>({newPasswordForm:t}),[t]);return u.jsx(xi.Provider,{value:n,children:e})}function Vi(){const e=g.useContext(xi);if(e===void 0)throw new Error("useNewPasswordFormContext must be used within a NewPasswordFormProvider");return e}function pc({children:e}){const{newPasswordForm:t}=Vi(),n=O;return u.jsx(t.Field,{name:"password",children:i=>u.jsx(n,{errors:L(i.state.meta.errorMap),name:i.name,type:"password",value:i.state.value,onChange:r=>i.handleChange(r.target.value),children:e})})}var ee=(e=>(e.Password="password",e.PasswordConfirmation="password_confirmation",e))(ee||{});const Ii=({value:e,fieldApi:t})=>{const n=t.form.getFieldMeta(ee.PasswordConfirmation);if(n?.isDirty&&n?.isTouched)return Ni(e,t.form.getFieldValue(ee.Password))},Ni=(e,t)=>{if(!e)return[qe(Ce.FieldRequired)];if(e!==t)return[qe(Ce.FieldMismatch)]};function mc({children:e}){const{newPasswordForm:t}=Vi(),n=O;return u.jsx(t.Field,{listeners:{onChange:({fieldApi:i})=>{i.form.setFieldMeta(ee.PasswordConfirmation,r=>({...r,errorMap:{...r.errorMap,onSubmit:void 0}}))}},name:"password_confirmation",validators:{onChangeListenTo:[ee.Password],onChange:Ii,onBlurListenTo:[ee.PasswordConfirmation],onBlur:Ii,onSubmit:({value:i,fieldApi:r})=>Ni(i,r.form.getFieldValue(ee.Password))},children:i=>u.jsx(n,{errors:L(i.state.meta.errorMap),name:i.name,type:"password",value:i.state.value,onBlur:i.handleBlur,onChange:r=>i.handleChange(r.target.value),children:e})})}function gc({onError:e,onChangePasswordSuccess:t}){const{mutateAsync:n}=Se(),{data:i}=B();return Q({defaultValues:{[ee.Password]:"",[ee.PasswordConfirmation]:""},onSubmit:async({value:r,formApi:o})=>{if(!i)return;const s=await n({csrf_token:I(i),method:"password",password:r[ee.Password]});if(s){if(s.state==="success"){t?.();return}R(s,o,e)}}})}function wc({newPasswordForm:e,emailVerificationRequired:t,onError:n,onChangePasswordSuccess:i}){const{data:r}=B(),o=gc({onError:n,onChangePasswordSuccess:i}),s=q(o);return u.jsx(hc,{newPasswordForm:o,children:u.jsx("form",{onSubmit:a=>{a.preventDefault(),o.handleSubmit()},children:u.jsx(e,{emailVerificationRequired:t,errors:s,isLoading:!r,isSubmitting:o.state.isSubmitting,isValidating:o.state.isValidating,Password:pc,PasswordConfirmation:mc,Submit:W})})})}process.env.NODE_ENV;function yc(e,t){return e.length===0?"":t(e[0])+e.slice(1)}function _c(e){return yc(e,t=>t.toUpperCase())}function vc({children:e,provider:t,type:n}){const{mutate:i}=Se(),{data:r}=B(),o=g.useCallback(()=>{r&&i({method:"oidc",[n]:t})},[r,i,n,t]),s=O;return u.jsx(s,{oidcType:n,type:"button",onClick:o,children:e})}const Fc=(e,t)=>{const n=Ke(t,e);if(n){if(n.attributes.name==="link")return"link";if(n.attributes.name==="unlink")return"unlink";throw new Error(`Unknown OIDC provider type for ${e}: ${n.attributes.name}`)}};function Sc({oidcForm:e}){const{data:t}=B(),n=g.useMemo(()=>t?En.reduce((i,r)=>{const o=_c(r),s=Fc(r,t.ui.nodes);return s&&(i[o]=({children:a})=>u.jsx(vc,{provider:r,type:s,children:a})),i},{}):{},[t]);return u.jsx(e,{...n,isLoading:!t})}const bc=()=>{const{mutateAsync:e,isPending:t}=Se(),{data:n}=B(),i=g.useCallback(async a=>{if(!t){if(!n)throw new Error("Settings flow is not available");await e({method:"passkey",csrf_token:I(n),passkey_remove:a})}},[t,n,e]),r=g.useCallback(async a=>{n&&await e({method:"passkey",csrf_token:I(n),passkey_settings_register:a})},[n,e]),o=g.useMemo(()=>le(P(n?.ui.nodes,"passkey_create_data")),[n?.ui.nodes]),s=g.useCallback(async()=>{if(t||!o)return;const a=await tr(o.value);a&&await r(a)},[t,o,r]);return{isPending:t,removePasskey:i,addNewPasskey:s}};function kc({passkeysForm:e}){const{data:t}=B(),{removePasskey:n,isPending:i,addNewPasskey:r}=bc(),o=t?ea(t.ui.nodes,"passkey_remove").filter(na).map(({meta:s,attributes:a})=>({addedAt:s.label.context.added_at,addedAtUnix:s.label.context.added_at_unix,id:String(a.value),name:s.label.context.display_name,removePasskey:()=>n(a.value)})):[];return u.jsx(e,{addNewPasskey:r,existingPasskeys:o,isLoading:!t,isPending:i})}const Li=g.createContext(void 0);function Cc({children:e,totpForm:t}){const n=g.useMemo(()=>({totpForm:t}),[t]);return u.jsx(Li.Provider,{value:n,children:e})}function Tc(){const e=g.useContext(Li);if(e===void 0)throw new Error("useTotpFormContext must be used within a TotpFormProvider");return e}function Ec({children:e}){const{totpForm:t}=Tc(),n=O;return u.jsx(t.Field,{name:"code",children:i=>u.jsx(n,{errors:L(i.state.meta.errorMap),name:i.name,type:"text",value:i.state.value,onChange:r=>i.handleChange(r.target.value),children:e})})}function Mc({children:e}){const{mutateAsync:t}=Se(),{data:n}=B(),i=g.useCallback(async()=>{n&&await t({method:"totp",csrf_token:I(n),totp_unlink:!0})},[n,t]),r=O;return u.jsx(r,{type:"button",onClick:i,children:e})}var rn=(e=>(e.Code="code",e))(rn||{});function Oc({onError:e,onTotpSuccess:t}){const{mutateAsync:n}=Se(),{data:i}=B();return Q({defaultValues:{[rn.Code]:""},onSubmit:async({value:r,formApi:o})=>{if(!i)return;const s=await n({csrf_token:I(i),method:"totp",totp_code:r[rn.Code]});if(s){if(s.state==="success"){t?.();return}R(s,o,e)}}})}function xc({totpForm:e,emailVerificationRequired:t,onError:n,onTotpSuccess:i}){const r=Oc({onError:n,onTotpSuccess:i}),o=q(r),{data:s}=B(),a=g.useMemo(()=>{if(!s)return;const c=P(s.ui.nodes,"totp_qr");if(!(!c||c.attributes.node_type!==yn.Img))return c.attributes.src},[s]),l=g.useMemo(()=>{if(!s)return;const c=P(s.ui.nodes,"totp_secret_key");if(!c||c.attributes.node_type!==yn.Text)return;const{text:f}=c.attributes;return f.context&&"secret"in f.context&&typeof f.context.secret=="string"?f.context.secret:f.text},[s]),d=g.useMemo(()=>{if(s)return!!P(s.ui.nodes,"totp_unlink")},[s]),h=!s||d===void 0;return u.jsx(Cc,{totpForm:r,children:u.jsx("form",{onSubmit:c=>{c.preventDefault(),r.handleSubmit()},children:h?u.jsx(e,{isLoading:!0}):d?u.jsx(e,{isTotpLinked:!0,emailVerificationRequired:t,Unlink:Mc}):u.jsx(e,{Code:Ec,emailVerificationRequired:t,errors:o,isSubmitting:r.state.isSubmitting,isValidating:r.state.isValidating,Submit:W,totpQrImageSrc:a,totpSecretKey:l})})})}const Di=g.createContext(void 0);function Vc({children:e,traitsForm:t}){const n=g.useMemo(()=>({traitsForm:t}),[t]);return u.jsx(Di.Provider,{value:n,children:e})}function Ai(){const e=g.useContext(Di);if(e===void 0)throw new Error("useTraitsFormContext must be used within a TraitsFormProvider");return e}function Ic({trait:e,children:t}){const{traitsForm:n}=Ai(),i=O;return u.jsx(n.Field,{name:`${me}${e}`,children:r=>{if(typeof r.state.value!="string")throw new TypeError("TraitInput: value is not string");return u.jsx(i,{errors:L(r.state.meta.errorMap),name:r.name,type:"text",value:r.state.value,onChange:o=>r.handleChange(o.target.value),children:t})}})}function Nc({trait:e,children:t}){const{traitsForm:n}=Ai(),i=O;return u.jsx(n.Field,{name:`${me}${e}`,children:r=>{if(typeof r.state.value!="boolean")throw new TypeError("TraitCheckbox: value is not boolean");return u.jsx(i,{checked:r.state.value,errors:L(r.state.meta.errorMap),name:r.name,type:"checkbox",onChange:o=>r.handleChange(o.target.checked),children:t})}})}function Lc({traitsConfig:e,onError:t,onChangeTraitsSuccess:n}){const{mutateAsync:i}=Se(),{data:r}=B();return Q({defaultValues:{traits:r?.identity.traits??Object.fromEntries(Object.values(e).map(({trait:o,type:s})=>[o,s==="boolean"?!1:""]))},onSubmit:async({value:o,formApi:s})=>{if(!r)return;const a=await i({csrf_token:I(r),method:"profile",traits:o.traits??{}});if(a){if(a.state===vo.Success){n?.();return}R(a,s,t)}}})}function Dc({traitsConfig:e,traitsForm:t,emailVerificationRequired:n,onError:i,onChangeTraitsSuccess:r}){const{data:o}=B(),s=Lc({traitsConfig:e,onError:i,onChangeTraitsSuccess:r}),a=q(s),l=g.useMemo(()=>Object.fromEntries(Object.entries(e).map(([d,h])=>[d,h.type==="boolean"?({children:c})=>u.jsx(Nc,{children:c,trait:h.trait}):({children:c})=>u.jsx(Ic,{children:c,trait:h.trait})])),[e]);return u.jsx(Vc,{traitsForm:s,children:u.jsx("form",{onSubmit:d=>{d.preventDefault(),s.handleSubmit()},children:u.jsx(t,{emailVerificationRequired:n,errors:a,isLoading:!o,isSubmitting:s.state.isSubmitting,isValidating:s.state.isValidating,Submit:W,...l})})})}function Pi(e){return u.jsx(nn,{children:u.jsx(on,{...e})})}function on({newPasswordForm:e,traitsForm:t,passkeysForm:n,totpForm:i,oidcForm:r,traitsConfig:o,settingsForm:s,initialFlowId:a,onError:l,onChangePasswordSuccess:d,onChangeTraitsSuccess:h,onFlowRestart:c}){const{settingsFlowId:f,setSettingsFlowId:m,emailVerificationRequired:w}=De(),{mutate:p}=fc(),{data:y,error:_}=B();return be({initialFlowId:a,currentFlowId:f,error:_,onFlowRestart:c,createFlow:p,setFlowId:m}),u.jsx(s,{emailVerificationRequired:w,isLoading:!y,newPasswordForm:e&&u.jsx(wc,{emailVerificationRequired:w,newPasswordForm:e,onChangePasswordSuccess:d,onError:l}),oidcForm:r&&u.jsx(Sc,{oidcForm:r}),passkeysForm:n&&u.jsx(kc,{passkeysForm:n}),totpForm:i&&u.jsx(xc,{emailVerificationRequired:w,totpForm:i,onError:l,onTotpSuccess:h}),traitsForm:o&&t&&u.jsx(Dc,{emailVerificationRequired:w,traitsConfig:o,traitsForm:t,onChangeTraitsSuccess:h,onError:l})})}const Ac=Object.freeze(Object.defineProperty({__proto__:null,SettingsFlow:Pi,SettingsFlowProvider:nn,SettingsFlowWrapper:on,useSettingsFlowContext:De},Symbol.toStringTag,{value:"Module"})),Ui=g.createContext(void 0);function Pc({children:e,codeForm:t}){const n=g.useMemo(()=>({codeForm:t}),[t]);return u.jsx(Ui.Provider,{value:n,children:e})}function Uc(){const e=g.useContext(Ui);if(e===void 0)throw new Error("useCodeFormContext must be used within a CodeFormProvider");return e}function Rc({children:e}){const{codeForm:t}=Uc(),n=O;return u.jsx(t.Field,{name:"code",children:i=>u.jsx(n,{errors:L(i.state.meta.errorMap),name:i.name,type:"text",value:i.state.value,onChange:r=>i.handleChange(r.target.value),children:e})})}const Jc=ue("recovery_flow"),vt=(e="no_id")=>ce([Jc,e]),Ri=g.createContext(void 0);function Wc({children:e}){const[t,n]=g.useState(),i=g.useCallback(()=>{n(void 0)},[]);return u.jsx(Ri.Provider,{value:{recoveryFlowId:t,setRecoveryFlowId:n,resetFlow:i},children:e})}function Ft(){const e=g.useContext(Ri);if(e===void 0)throw new Error("useRecoveryFlowContext must be used within a RecoveryFlow");return e}function Bc({returnTo:e}={}){const{kratosClient:t}=D(),{setRecoveryFlowId:n}=Ft(),i=J();return Z({mutationFn:()=>t.createBrowserRecoveryFlow({returnTo:e},async({init:{headers:r}})=>({headers:{...r,Accept:"application/json"}})),onSuccess(r){i.setQueryDefaults(vt(r.id),{staleTime:1/0}),i.setQueryData(vt(r.id),r),n(r.id)}})}function sn(){const{kratosClient:e}=D(),{recoveryFlowId:t}=Ft();return de({queryKey:vt(t),queryFn:async({signal:n})=>{if(!t)throw new Error("No recovery flow ID provided",{cause:ie.NoFlowId});try{return await e.getRecoveryFlow({id:t},async({init:{headers:i}})=>({signal:n,headers:{...i,Accept:"application/json"}}))}catch(i){throw await Te({error:i})}},enabled:!!t,staleTime:1/0})}function Ji(){const{kratosClient:e}=D(),{resetFlow:t,recoveryFlowId:n}=Ft(),i=J();return Z({mutationFn:async r=>{if(!n)throw new Error("Recovery flow ID is not set");try{return await e.updateRecoveryFlow({flow:n,updateRecoveryFlowBody:r},{headers:{Accept:"application/json","Content-Type":"application/json"}})}catch(o){return await oe({onRedirect:(s,a)=>{globalThis.location.href=s},onRestartFlow:t,onValidationError:s=>s})(o)}},onSuccess(r){r&&"id"in r&&i.setQueryData(vt(r.id),r)}})}var an=(e=>(e.Code="code",e))(an||{});function $c({onError:e}){const{mutateAsync:t}=Ji(),{data:n}=sn();return Q({defaultValues:{[an.Code]:""},onSubmit:async({value:i,formApi:r})=>{if(!n)return;const o=await t({csrf_token:I(n),method:"code",code:i[an.Code]});o&&R(o,r,e)}})}function qc({codeForm:e,onError:t}){const n=$c({onError:t}),i=q(n);return u.jsx(Pc,{codeForm:n,children:u.jsx("form",{onSubmit:r=>{r.preventDefault(),n.handleSubmit()},children:u.jsx(e,{Code:Rc,errors:i,isSubmitting:n.state.isSubmitting,isValidating:n.state.isValidating,Submit:W})})})}const Wi=g.createContext(void 0);function Kc({children:e,emailForm:t}){const n=g.useMemo(()=>({emailForm:t}),[t]);return u.jsx(Wi.Provider,{value:n,children:e})}function zc(){const e=g.useContext(Wi);if(e===void 0)throw new Error("useEmailFormContext must be used within a EmailFormProvider");return e}function Gc({children:e}){const{emailForm:t}=zc(),n=O;return u.jsx(t.Field,{name:"email",children:i=>u.jsx(n,{errors:L(i.state.meta.errorMap),name:i.name,type:"text",value:i.state.value,onChange:r=>i.handleChange(r.target.value),children:e})})}var ln=(e=>(e.Email="email",e))(ln||{});function Qc({onError:e}){const{mutateAsync:t}=Ji(),{data:n}=sn();return Q({defaultValues:{[ln.Email]:""},onSubmit:async({value:i,formApi:r})=>{if(!n)return;const o=await t({csrf_token:I(n),method:"code",email:i[ln.Email]});o&&R(o,r,e)}})}function Hc({emailForm:e,onError:t}){const n=Qc({onError:t}),i=q(n);return u.jsx(Kc,{emailForm:n,children:u.jsx("form",{onSubmit:r=>{r.preventDefault(),n.handleSubmit()},children:u.jsx(e,{Email:Gc,errors:i,isSubmitting:n.state.isSubmitting,isValidating:n.state.isValidating,Submit:W})})})}function Xc({emailForm:e,codeForm:t,newPasswordForm:n,initialFlowId:i,returnTo:r,onError:o,onRecoverySuccess:s,onFlowRestart:a}){const{recoveryFlowId:l,setRecoveryFlowId:d}=Ft(),{mutate:h}=Bc({returnTo:r}),{data:c,error:f}=sn(),m=g.useMemo(()=>c?.continue_with?.find(p=>p.action==="show_settings_ui")?.flow.id,[c]);be({initialFlowId:i,currentFlowId:l,error:f,onFlowRestart:a,createFlow:h,setFlowId:d});const w=g.useMemo(()=>m?"newPassword":c?.state==="sent_email"?"code":"email",[c?.state,m]);return u.jsxs(u.Fragment,{children:[w==="email"&&u.jsx(Hc,{emailForm:e,onError:o}),w==="code"&&u.jsx(qc,{codeForm:t,onError:o}),w==="newPassword"&&m&&u.jsx(on,{initialFlowId:m,newPasswordForm:n,settingsForm:({newPasswordForm:p})=>p,onChangePasswordSuccess:s,onError:o})]})}function Bi(e){return u.jsx(nn,{children:u.jsx(Wc,{children:u.jsx(Xc,{...e})})})}const Zc=Object.freeze(Object.defineProperty({__proto__:null,RecoveryFlow:Bi},Symbol.toStringTag,{value:"Module"})),$i=ce([ue("session_manager"),"session"]),qi=e=>({queryKey:$i,queryFn:async()=>{try{return await e.toSession()}catch(t){if(t instanceof ge){if(t.response.status===401)return null;const n=await t.response.json();if(te(n))throw new Error("Kratos error occurred while fetching session",{cause:n})}throw new Error("Unexpected error while fetching session")}},staleTime:1/0,retry:!1});class Ki{queryClient;api;getSession=async()=>{try{return await this.queryClient.fetchQuery(qi(this.api))??void 0}catch{return}};getIdentity=async()=>(await this.getSession())?.identity;getUserId=async()=>(await this.getIdentity())?.id;isLoggedIn=async()=>(await this.getSession())?.active??!1;useSession=()=>{const{data:t,isLoading:n,error:i}=de({...qi(this.api),retryOnMount:!1});return{session:t??void 0,isLoading:n,error:i}};useIdentity=()=>{const{session:t,...n}=this.useSession();return{identity:t?.identity,...n}};useUserId=()=>{const{identity:t,...n}=this.useIdentity();return{userId:t?.id,...n}};useIsLoggedIn=()=>{const{session:t,isLoading:n,error:i}=this.useSession();return{isLoggedIn:t?.active??(n?void 0:!1),isLoading:n,error:i}};useIsAal2Required=()=>{const t=this.useSession();return{isAal2Required:t.error?.cause?te(t.error.cause)&&Bs(t.error.cause):void 0,isLoading:t.isLoading}};checkIfLoggedIn=async()=>await this.queryClient.refetchQueries({queryKey:$i,exact:!0});constructor({queryClient:t,api:n}){this.api=n,this.queryClient=t}}function Yc({queryClient:e,basePath:t,traits:n={},SessionManager:i=Ki}){const r=new Rs(new pn({basePath:t,credentials:"include"})),o=new i({queryClient:e,api:r});return{flows:{useLogout:Fi,LoginFlow:vi,RecoveryFlow:Bi,RegistrationFlow:d=>u.jsx(Mi,{traitsConfig:n,...d}),SettingsFlow:d=>u.jsx(Pi,{traitsConfig:n,...d}),VerificationFlow:li},providers:{KratosProviders:({children:d})=>u.jsx(ra,{api:r,children:u.jsx(Gi,{sessionManager:o,children:d})})},session:{sessionManager:o}}}A.BaseSessionManager=Ki,A.loginFlow=$l,A.logoutFlow=ql,A.mkKratos=Yc,A.recoveryFlow=Zc,A.registrationFlow=uc,A.settingsFlow=Ac,A.verificationFlow=Fl,Object.defineProperty(A,Symbol.toStringTag,{value:"Module"})}));
1
+ (function(b,s){typeof exports=="object"&&typeof module<"u"?s(exports,require("react/jsx-runtime"),require("react"),require("@tanstack/react-query"),require("@tanstack/react-form"),require("@radix-ui/react-slot"),require("@leancodepl/utils")):typeof define=="function"&&define.amd?define(["exports","react/jsx-runtime","react","@tanstack/react-query","@tanstack/react-form","@radix-ui/react-slot","@leancodepl/utils"],s):(b=typeof globalThis<"u"?globalThis:b||self,s(b["@leancodepl/kratos"]={},b.jsxRuntime,b.react,b.reactQuery,b.reactForm,b.Slot,b.utils))})(this,(function(b,s,l,y,D,un,dn){"use strict";function fn(e){const t=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(e){for(const n in e)if(n!=="default"){const o=Object.getOwnPropertyDescriptor(e,n);Object.defineProperty(t,n,o.get?o:{enumerable:!0,get:()=>e[n]})}}return t.default=e,Object.freeze(t)}const m=fn(un);var P=(e=>(e[e.NoFlowId=0]="NoFlowId",e[e.FlowRestartRequired=1]="FlowRestartRequired",e))(P||{});const et=l.createContext(void 0);function Ne(){const e=l.useContext(et);if(e===void 0)throw new Error("useKratosSessionContext must be used within a KratosSessionContextProvider");return e}function pn({children:e,sessionManager:t}){const n=l.useMemo(()=>({sessionManager:t}),[t]);return s.jsx(et.Provider,{value:n,children:e})}const ee=({initialFlowId:e,currentFlowId:t,error:n,onFlowRestart:o,createFlow:i,setFlowId:r,waitForSession:a})=>{const[c,u]=l.useState(!1),[d,w]=l.useState(e),{sessionManager:f}=Ne(),{isLoading:g}=f.useSession();d!==e&&(u(!1),w(e));const k=!!a&&g;l.useEffect(()=>{t||k||(e&&!c?(r(e),u(!0)):i())},[i,t,e,c,r,k]),l.useEffect(()=>{n&&n.cause===P.FlowRestartRequired&&(i(),o?.())},[i,n,o])},X="traits.";function tt(e){return"type"in e&&e.type==="public-key"&&"id"in e&&"rawId"in e&&"response"in e}function wn(e){return"attestationObject"in e&&"clientDataJSON"in e}function hn(e){return"authenticatorData"in e&&"clientDataJSON"in e&&"signature"in e}function ce(e){return Uint8Array.from(atob(e.replaceAll("-","+").replaceAll("_","/")),function(t){return t.charCodeAt(0)})}function W(e){return btoa(String.fromCharCode(...new Uint8Array(e))).replaceAll("+","-").replaceAll("/","_").replaceAll("=","")}function nt(e){if(!e||!tt(e))return;const{response:t,id:n,rawId:o}=e;if(wn(t))return JSON.stringify({id:n,rawId:W(o),type:e.type,response:{attestationObject:W(t.attestationObject),clientDataJSON:W(t.clientDataJSON)}})}async function ot({credentialOptions:e,signal:t,userName:n,userDisplayName:o}){return await navigator.credentials.create({signal:t,publicKey:{challenge:ce(e.publicKey.challenge),timeout:e.publicKey.timeout,rp:{id:e.publicKey.rp.id,name:e.publicKey.rp.name},user:{id:ce(e.publicKey.user.id),name:n,displayName:o},pubKeyCredParams:e.publicKey.pubKeyCredParams}})}function it(e){if(!e||!tt(e))return;const{response:t,id:n,rawId:o}=e;if(!hn(t))return;const{userHandle:i,authenticatorData:r,clientDataJSON:a,signature:c}=t;return JSON.stringify({id:n,rawId:W(o),type:e.type,response:{authenticatorData:W(r),clientDataJSON:W(a),signature:W(c),userHandle:i?W(i):void 0}})}async function gn({challengeOptions:e,signal:t}){return await navigator.credentials.get({signal:t,publicKey:{challenge:ce(e.publicKey.challenge),timeout:e.publicKey.timeout,rpId:e.publicKey.rpId,userVerification:e.publicKey.userVerification}})}function _n(){return!!globalThis.PublicKeyCredential}async function yn(e,t){const n=JSON.parse(e);if(_n()&&globalThis.PublicKeyCredential.isConditionalMediationAvailable&&await globalThis.PublicKeyCredential.isConditionalMediationAvailable())try{const o=await navigator.credentials.get({mediation:"conditional",signal:t,publicKey:{challenge:ce(n.publicKey.challenge),timeout:n.publicKey.timeout,rpId:n.publicKey.rpId,userVerification:n.publicKey.userVerification}});return it(o)}catch{return}}async function mn(e,t){const n=JSON.parse(e);try{return it(await gn({challengeOptions:n,signal:t}))}catch{return}}async function Fn(e,t,n){const{credentialOptions:o,displayNameFieldName:i}=JSON.parse(e),r=i.startsWith(X)?i.slice(X.length):i,a=typeof n?.[r]=="string"?n[r]:"";try{return nt(await ot({credentialOptions:o,signal:t,userName:a,userDisplayName:a}))}catch{return}}async function vn(e,t){const n=JSON.parse(e);try{return nt(await ot({credentialOptions:n,signal:t,userName:n.publicKey.user.name,userDisplayName:n.publicKey.user.displayName}))}catch{return}}const p=(e,t,n)=>e!==void 0&&t in e&&typeof e[t]===n,Sn="https://playground.projects.oryapis.com".replace(/\/+$/,"");class rt{constructor(t={}){this.configuration=t}set config(t){this.configuration=t}get basePath(){return this.configuration.basePath!=null?this.configuration.basePath:Sn}get fetchApi(){return this.configuration.fetchApi}get middleware(){return this.configuration.middleware||[]}get queryParamsStringify(){return this.configuration.queryParamsStringify||at}get username(){return this.configuration.username}get password(){return this.configuration.password}get apiKey(){const t=this.configuration.apiKey;if(t)return typeof t=="function"?t:()=>t}get accessToken(){const t=this.configuration.accessToken;if(t)return typeof t=="function"?t:async()=>t}get headers(){return this.configuration.headers}get credentials(){return this.configuration.credentials}}const kn=new rt;class Ee{constructor(t=kn){this.configuration=t,this.middleware=t.middleware}static jsonRegex=new RegExp("^(:?application/json|[^;/ ]+/[^;/ ]+[+]json)[ ]*(:?;.*)?$","i");middleware;withMiddleware(...t){const n=this.clone();return n.middleware=n.middleware.concat(...t),n}withPreMiddleware(...t){const n=t.map(o=>({pre:o}));return this.withMiddleware(...n)}withPostMiddleware(...t){const n=t.map(o=>({post:o}));return this.withMiddleware(...n)}isJsonMime(t){return t?Ee.jsonRegex.test(t):!1}async request(t,n){const{url:o,init:i}=await this.createFetchParams(t,n),r=await this.fetchApi(o,i);if(r&&r.status>=200&&r.status<300)return r;throw new Y(r,"Response returned an error code")}async createFetchParams(t,n){let o=this.configuration.basePath+t.path;t.query!==void 0&&Object.keys(t.query).length!==0&&(o+="?"+this.configuration.queryParamsStringify(t.query));const i=Object.assign({},this.configuration.headers,t.headers);Object.keys(i).forEach(w=>i[w]===void 0?delete i[w]:{});const r=typeof n=="function"?n:async()=>n,a={method:t.method,headers:i,body:t.body,credentials:this.configuration.credentials},c={...a,...await r({init:a,context:t})};let u;Cn(c.body)||c.body instanceof URLSearchParams||bn(c.body)?u=c.body:this.isJsonMime(i["Content-Type"])?u=JSON.stringify(c.body):u=c.body;const d={...c,body:u};return{url:o,init:d}}fetchApi=async(t,n)=>{let o={url:t,init:n};for(const r of this.middleware)r.pre&&(o=await r.pre({fetch:this.fetchApi,...o})||o);let i;try{i=await(this.configuration.fetchApi||fetch)(o.url,o.init)}catch(r){for(const a of this.middleware)a.onError&&(i=await a.onError({fetch:this.fetchApi,url:o.url,init:o.init,error:r,response:i?i.clone():void 0})||i);if(i===void 0)throw r instanceof Error?new Me(r,"The request failed and the interceptors did not return an alternative response"):r}for(const r of this.middleware)r.post&&(i=await r.post({fetch:this.fetchApi,url:o.url,init:o.init,response:i.clone()})||i);return i};clone(){const t=this.constructor,n=new t(this.configuration);return n.middleware=this.middleware.slice(),n}}function bn(e){return typeof Blob<"u"&&e instanceof Blob}function Cn(e){return typeof FormData<"u"&&e instanceof FormData}class Y extends Error{constructor(t,n){super(n),this.response=t}name="ResponseError"}class Me extends Error{constructor(t,n){super(n),this.cause=t}name="FetchError"}class F extends Error{constructor(t,n){super(n),this.field=t}name="RequiredError"}function at(e,t=""){return Object.keys(e).map(n=>st(n,e[n],t)).filter(n=>n.length>0).join("&")}function st(e,t,n=""){const o=n+(n.length?`[${e}]`:e);if(t instanceof Array){const i=t.map(r=>encodeURIComponent(String(r))).join(`&${encodeURIComponent(o)}=`);return`${encodeURIComponent(o)}=${i}`}if(t instanceof Set){const i=Array.from(t);return st(e,i,n)}return t instanceof Date?`${encodeURIComponent(o)}=${encodeURIComponent(t.toISOString())}`:t instanceof Object?at(t,o):`${encodeURIComponent(o)}=${encodeURIComponent(String(t))}`}function xn(e,t){return Object.keys(e).reduce((n,o)=>({...n,[o]:t(e[o])}),{})}class _{constructor(t,n=o=>o){this.raw=t,this.transformer=n}async value(){return this.transformer(await this.raw.json())}}class Re{constructor(t){this.raw=t}async value(){}}class Tn{constructor(t){this.raw=t}async value(){return await this.raw.text()}}function De(e){return On(e)}function On(e,t){return e}function Nn(e){return En(e)}function En(e,t){return e==null?e:{id:e.id,url:e.url==null?void 0:e.url}}function Mn(e,t){return e==null?e:{action:e.action,flow:Nn(e.flow)}}function Rn(e,t){return e==null?e:{action:e.action,redirect_browser_to:e.redirect_browser_to}}function Dn(e,t){return e==null?e:{action:e.action,ory_session_token:e.ory_session_token}}function In(e){return Jn(e)}function Jn(e,t){return e==null?e:{id:e.id,url:e.url==null?void 0:e.url}}function An(e,t){return e==null?e:{action:e.action,flow:In(e.flow)}}function Un(e){return Ln(e)}function Ln(e,t){return e==null?e:{id:e.id,url:e.url==null?void 0:e.url,verifiable_address:e.verifiable_address}}function Vn(e,t){return e==null?e:{action:e.action,flow:Un(e.flow)}}function le(e){return Pn(e)}function Pn(e,t){if(e==null)return e;switch(e.action){case"redirect_browser_to":return Object.assign({},Rn(e),{action:"redirect_browser_to"});case"set_ory_session_token":return Object.assign({},Dn(e),{action:"set_ory_session_token"});case"show_recovery_ui":return Object.assign({},Mn(e),{action:"show_recovery_ui"});case"show_settings_ui":return Object.assign({},An(e),{action:"show_settings_ui"});case"show_verification_ui":return Object.assign({},Vn(e),{action:"show_verification_ui"});default:throw new Error(`No variant of ContinueWith exists with 'action=${e.action}'`)}}function Wn(e){return Bn(e)}function Bn(e,t){return e==null?e:{client_id:e.client_id==null?void 0:e.client_id,config_url:e.config_url==null?void 0:e.config_url,domain_hint:e.domain_hint==null?void 0:e.domain_hint,fields:e.fields==null?void 0:e.fields,login_hint:e.login_hint==null?void 0:e.login_hint,nonce:e.nonce==null?void 0:e.nonce,parameters:e.parameters==null?void 0:e.parameters}}function qn(e){return $n(e)}function $n(e,t){return e==null?e:{csrf_token:e.csrf_token==null?void 0:e.csrf_token,providers:e.providers==null?void 0:e.providers.map(Wn)}}function Kn(e){return zn(e)}function zn(e,t){return e==null?e:{created_at:e.created_at==null?void 0:new Date(e.created_at),id:e.id==null?void 0:e.id,status:e.status,updated_at:e.updated_at==null?void 0:new Date(e.updated_at),value:e.value,verified:e.verified,verified_at:e.verified_at==null?void 0:new Date(e.verified_at),via:e.via}}function Gn(e){return Qn(e)}function Qn(e,t){return e==null?e:{created_at:e.created_at==null?void 0:new Date(e.created_at),id:e.id,updated_at:e.updated_at==null?void 0:new Date(e.updated_at),value:e.value,via:e.via}}function Hn(e){return Xn(e)}function Xn(e,t){return e==null?e:{count:e.count==null?void 0:e.count}}function Yn(e){return Zn(e)}function Zn(e,t){return e==null?e:{created_at:e.created_at==null?void 0:new Date(e.created_at),error:e.error==null?void 0:e.error,id:e.id,updated_at:e.updated_at==null?void 0:new Date(e.updated_at)}}function jn(e){return eo(e)}function eo(e,t){return e==null?e:{config:e.config==null?void 0:e.config,created_at:e.created_at==null?void 0:new Date(e.created_at),identifiers:e.identifiers==null?void 0:e.identifiers,type:e.type==null?void 0:e.type,updated_at:e.updated_at==null?void 0:new Date(e.updated_at),version:e.version==null?void 0:e.version}}function Ie(e){return to(e)}function to(e,t){return e==null?e:{created_at:e.created_at==null?void 0:new Date(e.created_at),credentials:e.credentials==null?void 0:xn(e.credentials,jn),id:e.id,metadata_admin:e.metadata_admin==null?void 0:e.metadata_admin,metadata_public:e.metadata_public==null?void 0:e.metadata_public,organization_id:e.organization_id==null?void 0:e.organization_id,recovery_addresses:e.recovery_addresses==null?void 0:e.recovery_addresses.map(Gn),schema_id:e.schema_id,schema_url:e.schema_url,state:e.state==null?void 0:e.state,state_changed_at:e.state_changed_at==null?void 0:new Date(e.state_changed_at),traits:e.traits,updated_at:e.updated_at==null?void 0:new Date(e.updated_at),verifiable_addresses:e.verifiable_addresses==null?void 0:e.verifiable_addresses.map(Kn)}}function no(e){return oo(e)}function oo(e,t){return e==null?e:{acr_values:e.acr_values==null?void 0:e.acr_values,display:e.display==null?void 0:e.display,id_token_hint_claims:e.id_token_hint_claims==null?void 0:e.id_token_hint_claims,login_hint:e.login_hint==null?void 0:e.login_hint,ui_locales:e.ui_locales==null?void 0:e.ui_locales}}function io(e){return ro(e)}function ro(e,t){return e==null?e:{access_token_strategy:e.access_token_strategy==null?void 0:e.access_token_strategy,allowed_cors_origins:e.allowed_cors_origins==null?void 0:e.allowed_cors_origins,audience:e.audience==null?void 0:e.audience,authorization_code_grant_access_token_lifespan:e.authorization_code_grant_access_token_lifespan==null?void 0:e.authorization_code_grant_access_token_lifespan,authorization_code_grant_id_token_lifespan:e.authorization_code_grant_id_token_lifespan==null?void 0:e.authorization_code_grant_id_token_lifespan,authorization_code_grant_refresh_token_lifespan:e.authorization_code_grant_refresh_token_lifespan==null?void 0:e.authorization_code_grant_refresh_token_lifespan,backchannel_logout_session_required:e.backchannel_logout_session_required==null?void 0:e.backchannel_logout_session_required,backchannel_logout_uri:e.backchannel_logout_uri==null?void 0:e.backchannel_logout_uri,client_credentials_grant_access_token_lifespan:e.client_credentials_grant_access_token_lifespan==null?void 0:e.client_credentials_grant_access_token_lifespan,client_id:e.client_id==null?void 0:e.client_id,client_name:e.client_name==null?void 0:e.client_name,client_secret:e.client_secret==null?void 0:e.client_secret,client_secret_expires_at:e.client_secret_expires_at==null?void 0:e.client_secret_expires_at,client_uri:e.client_uri==null?void 0:e.client_uri,contacts:e.contacts==null?void 0:e.contacts,created_at:e.created_at==null?void 0:new Date(e.created_at),frontchannel_logout_session_required:e.frontchannel_logout_session_required==null?void 0:e.frontchannel_logout_session_required,frontchannel_logout_uri:e.frontchannel_logout_uri==null?void 0:e.frontchannel_logout_uri,grant_types:e.grant_types==null?void 0:e.grant_types,implicit_grant_access_token_lifespan:e.implicit_grant_access_token_lifespan==null?void 0:e.implicit_grant_access_token_lifespan,implicit_grant_id_token_lifespan:e.implicit_grant_id_token_lifespan==null?void 0:e.implicit_grant_id_token_lifespan,jwks:e.jwks==null?void 0:e.jwks,jwks_uri:e.jwks_uri==null?void 0:e.jwks_uri,jwt_bearer_grant_access_token_lifespan:e.jwt_bearer_grant_access_token_lifespan==null?void 0:e.jwt_bearer_grant_access_token_lifespan,logo_uri:e.logo_uri==null?void 0:e.logo_uri,metadata:e.metadata==null?void 0:e.metadata,owner:e.owner==null?void 0:e.owner,policy_uri:e.policy_uri==null?void 0:e.policy_uri,post_logout_redirect_uris:e.post_logout_redirect_uris==null?void 0:e.post_logout_redirect_uris,redirect_uris:e.redirect_uris==null?void 0:e.redirect_uris,refresh_token_grant_access_token_lifespan:e.refresh_token_grant_access_token_lifespan==null?void 0:e.refresh_token_grant_access_token_lifespan,refresh_token_grant_id_token_lifespan:e.refresh_token_grant_id_token_lifespan==null?void 0:e.refresh_token_grant_id_token_lifespan,refresh_token_grant_refresh_token_lifespan:e.refresh_token_grant_refresh_token_lifespan==null?void 0:e.refresh_token_grant_refresh_token_lifespan,registration_access_token:e.registration_access_token==null?void 0:e.registration_access_token,registration_client_uri:e.registration_client_uri==null?void 0:e.registration_client_uri,request_object_signing_alg:e.request_object_signing_alg==null?void 0:e.request_object_signing_alg,request_uris:e.request_uris==null?void 0:e.request_uris,response_types:e.response_types==null?void 0:e.response_types,scope:e.scope==null?void 0:e.scope,sector_identifier_uri:e.sector_identifier_uri==null?void 0:e.sector_identifier_uri,skip_consent:e.skip_consent==null?void 0:e.skip_consent,skip_logout_consent:e.skip_logout_consent==null?void 0:e.skip_logout_consent,subject_type:e.subject_type==null?void 0:e.subject_type,token_endpoint_auth_method:e.token_endpoint_auth_method==null?void 0:e.token_endpoint_auth_method,token_endpoint_auth_signing_alg:e.token_endpoint_auth_signing_alg==null?void 0:e.token_endpoint_auth_signing_alg,tos_uri:e.tos_uri==null?void 0:e.tos_uri,updated_at:e.updated_at==null?void 0:new Date(e.updated_at),userinfo_signed_response_alg:e.userinfo_signed_response_alg==null?void 0:e.userinfo_signed_response_alg}}function ct(e){return ao(e)}function ao(e,t){return e==null?e:{challenge:e.challenge,client:io(e.client),oidc_context:e.oidc_context==null?void 0:no(e.oidc_context),request_url:e.request_url,requested_access_token_audience:e.requested_access_token_audience==null?void 0:e.requested_access_token_audience,requested_scope:e.requested_scope==null?void 0:e.requested_scope,session_id:e.session_id==null?void 0:e.session_id,skip:e.skip,subject:e.subject}}const so={Error:"error"};function co(e){return!(!("id"in e)||e.id===void 0||!("text"in e)||e.text===void 0||!("type"in e)||e.type===void 0)}function Z(e){return lo(e)}function lo(e,t){return e==null?e:{context:e.context==null?void 0:e.context,id:e.id,text:e.text,type:e.type}}function uo(e){return fo(e)}function fo(e,t){return e==null?e:{label:e.label==null?void 0:Z(e.label)}}function po(e,t){return e==null?e:{href:e.href,id:e.id,node_type:e.node_type,title:Z(e.title)}}function wo(e,t){return e==null?e:{_class:e.class==null?void 0:e.class,data:e.data==null?void 0:e.data,id:e.id,node_type:e.node_type}}const lt={Text:"text",Img:"img"};function ho(e,t){return e==null?e:{height:e.height,id:e.id,node_type:e.node_type,src:e.src,width:e.width}}function go(e,t){return e==null?e:{autocomplete:e.autocomplete==null?void 0:e.autocomplete,disabled:e.disabled,label:e.label==null?void 0:Z(e.label),maxlength:e.maxlength==null?void 0:e.maxlength,name:e.name,node_type:e.node_type,onclick:e.onclick==null?void 0:e.onclick,onclickTrigger:e.onclickTrigger==null?void 0:e.onclickTrigger,onload:e.onload==null?void 0:e.onload,onloadTrigger:e.onloadTrigger==null?void 0:e.onloadTrigger,pattern:e.pattern==null?void 0:e.pattern,required:e.required==null?void 0:e.required,type:e.type,value:e.value==null?void 0:e.value}}const _o={Input:"input"};function yo(e,t){return e==null?e:{async:e.async,crossorigin:e.crossorigin,id:e.id,integrity:e.integrity,node_type:e.node_type,nonce:e.nonce,referrerpolicy:e.referrerpolicy,src:e.src,type:e.type}}function mo(e,t){return e==null?e:{id:e.id,node_type:e.node_type,text:Z(e.text)}}function Fo(e){return vo(e)}function vo(e,t){if(e==null)return e;switch(e.node_type){case"a":return Object.assign({},po(e),{node_type:"a"});case"div":return Object.assign({},wo(e),{node_type:"div"});case"img":return Object.assign({},ho(e),{node_type:"img"});case"input":return Object.assign({},go(e),{node_type:"input"});case"script":return Object.assign({},yo(e),{node_type:"script"});case"text":return Object.assign({},mo(e),{node_type:"text"});default:throw new Error(`No variant of UiNodeAttributes exists with 'node_type=${e.node_type}'`)}}const So={Passkey:"passkey"},ko={Input:"input"};function bo(e){return Co(e)}function Co(e,t){return e==null?e:{attributes:Fo(e.attributes),group:e.group,messages:e.messages.map(Z),meta:uo(e.meta),type:e.type}}function te(e){return xo(e)}function xo(e,t){return e==null?e:{action:e.action,messages:e.messages==null?void 0:e.messages.map(Z),method:e.method,nodes:e.nodes.map(bo)}}function Je(e){return To(e)}function To(e,t){return e==null?e:{active:e.active==null?void 0:e.active,created_at:e.created_at==null?void 0:new Date(e.created_at),expires_at:new Date(e.expires_at),id:e.id,issued_at:new Date(e.issued_at),oauth2_login_challenge:e.oauth2_login_challenge==null?void 0:e.oauth2_login_challenge,oauth2_login_request:e.oauth2_login_request==null?void 0:ct(e.oauth2_login_request),organization_id:e.organization_id==null?void 0:e.organization_id,refresh:e.refresh==null?void 0:e.refresh,request_url:e.request_url,requested_aal:e.requested_aal==null?void 0:De(e.requested_aal),return_to:e.return_to==null?void 0:e.return_to,session_token_exchange_code:e.session_token_exchange_code==null?void 0:e.session_token_exchange_code,state:e.state,transient_payload:e.transient_payload==null?void 0:e.transient_payload,type:e.type,ui:te(e.ui),updated_at:e.updated_at==null?void 0:new Date(e.updated_at)}}function Oo(e){return No(e)}function No(e,t){return e==null?e:{logout_token:e.logout_token,logout_url:e.logout_url}}function Eo(e){return Mo(e,!1)}function Mo(e,t=!1){return e==null?e:{session_token:e.session_token}}function ue(e){return Ro(e)}function Ro(e,t){return e==null?e:{active:e.active==null?void 0:e.active,continue_with:e.continue_with==null?void 0:e.continue_with.map(le),expires_at:new Date(e.expires_at),id:e.id,issued_at:new Date(e.issued_at),request_url:e.request_url,return_to:e.return_to==null?void 0:e.return_to,state:e.state,transient_payload:e.transient_payload==null?void 0:e.transient_payload,type:e.type,ui:te(e.ui)}}function Ae(e){return Do(e)}function Do(e,t){return e==null?e:{active:e.active==null?void 0:e.active,expires_at:new Date(e.expires_at),id:e.id,issued_at:new Date(e.issued_at),oauth2_login_challenge:e.oauth2_login_challenge==null?void 0:e.oauth2_login_challenge,oauth2_login_request:e.oauth2_login_request==null?void 0:ct(e.oauth2_login_request),organization_id:e.organization_id==null?void 0:e.organization_id,request_url:e.request_url,return_to:e.return_to==null?void 0:e.return_to,session_token_exchange_code:e.session_token_exchange_code==null?void 0:e.session_token_exchange_code,state:e.state,transient_payload:e.transient_payload==null?void 0:e.transient_payload,type:e.type,ui:te(e.ui)}}const ut={ChooseMethod:"choose_method"};function Io(e){return Jo(e)}function Jo(e,t){return e==null?e:{id:e.id,ip_address:e.ip_address==null?void 0:e.ip_address,location:e.location==null?void 0:e.location,user_agent:e.user_agent==null?void 0:e.user_agent}}function Ao(e){return Uo(e)}function Uo(e,t){return e==null?e:{aal:e.aal==null?void 0:De(e.aal),completed_at:e.completed_at==null?void 0:new Date(e.completed_at),method:e.method==null?void 0:e.method,organization:e.organization==null?void 0:e.organization,provider:e.provider==null?void 0:e.provider}}function de(e){return Lo(e)}function Lo(e,t){return e==null?e:{active:e.active==null?void 0:e.active,authenticated_at:e.authenticated_at==null?void 0:new Date(e.authenticated_at),authentication_methods:e.authentication_methods==null?void 0:e.authentication_methods.map(Ao),authenticator_assurance_level:e.authenticator_assurance_level==null?void 0:De(e.authenticator_assurance_level),devices:e.devices==null?void 0:e.devices.map(Io),expires_at:e.expires_at==null?void 0:new Date(e.expires_at),id:e.id,identity:e.identity==null?void 0:Ie(e.identity),issued_at:e.issued_at==null?void 0:new Date(e.issued_at),tokenized:e.tokenized==null?void 0:e.tokenized}}function fe(e){return Vo(e)}function Vo(e,t){return e==null?e:{active:e.active==null?void 0:e.active,continue_with:e.continue_with==null?void 0:e.continue_with.map(le),expires_at:new Date(e.expires_at),id:e.id,identity:Ie(e.identity),issued_at:new Date(e.issued_at),request_url:e.request_url,return_to:e.return_to==null?void 0:e.return_to,state:e.state,transient_payload:e.transient_payload==null?void 0:e.transient_payload,type:e.type,ui:te(e.ui)}}const Po={Success:"success"};function pe(e){return!(!("session"in e)||e.session===void 0)}function Ue(e){return Wo(e)}function Wo(e,t){return e==null?e:{continue_with:e.continue_with==null?void 0:e.continue_with.map(le),session:de(e.session),session_token:e.session_token==null?void 0:e.session_token}}function Le(e){return!(!("identity"in e)||e.identity===void 0)}function Bo(e){return qo(e)}function qo(e,t){return e==null?e:{continue_with:e.continue_with==null?void 0:e.continue_with.map(le),identity:Ie(e.identity),session:e.session==null?void 0:de(e.session),session_token:e.session_token==null?void 0:e.session_token}}function $o(e){return Ko(e,!1)}function Ko(e,t=!1){return e==null?e:{csrf_token:e.csrf_token,nonce:e.nonce,token:e.token,transient_payload:e.transient_payload}}function zo(e){return Go(e,!1)}function Go(e,t=!1){return e==null?e:{address:e.address,code:e.code,csrf_token:e.csrf_token,identifier:e.identifier,method:e.method,resend:e.resend,transient_payload:e.transient_payload}}function Qo(e){return Ho(e,!1)}function Ho(e,t=!1){return e==null?e:{csrf_token:e.csrf_token,identifier:e.identifier,method:e.method,transient_payload:e.transient_payload}}function Xo(e){return Yo(e,!1)}function Yo(e,t=!1){return e==null?e:{csrf_token:e.csrf_token,lookup_secret:e.lookup_secret,method:e.method}}function Zo(e){return jo(e,!1)}function jo(e,t=!1){return e==null?e:{csrf_token:e.csrf_token,id_token:e.id_token,id_token_nonce:e.id_token_nonce,method:e.method,provider:e.provider,traits:e.traits,transient_payload:e.transient_payload,upstream_parameters:e.upstream_parameters}}function ei(e){return ti(e,!1)}function ti(e,t=!1){return e==null?e:{csrf_token:e.csrf_token,method:e.method,passkey_login:e.passkey_login}}function ni(e){return oi(e,!1)}function oi(e,t=!1){return e==null?e:{csrf_token:e.csrf_token,identifier:e.identifier,method:e.method,password:e.password,password_identifier:e.password_identifier,transient_payload:e.transient_payload}}function ii(e){return ri(e,!1)}function ri(e,t=!1){return e==null?e:{csrf_token:e.csrf_token,method:e.method,provider:e.provider,transient_payload:e.transient_payload}}function ai(e){return si(e,!1)}function si(e,t=!1){return e==null?e:{csrf_token:e.csrf_token,method:e.method,totp_code:e.totp_code,transient_payload:e.transient_payload}}function ci(e){return li(e,!1)}function li(e,t=!1){return e==null?e:{csrf_token:e.csrf_token,identifier:e.identifier,method:e.method,transient_payload:e.transient_payload,webauthn_login:e.webauthn_login}}function ui(e){return di(e,!1)}function di(e,t=!1){if(e==null)return e;switch(e.method){case"code":return Object.assign({},zo(e),{method:"code"});case"identifier_first":return Object.assign({},Qo(e),{method:"identifier_first"});case"lookup_secret":return Object.assign({},Xo(e),{method:"lookup_secret"});case"oidc":return Object.assign({},Zo(e),{method:"oidc"});case"passkey":return Object.assign({},ei(e),{method:"passkey"});case"password":return Object.assign({},ni(e),{method:"password"});case"saml":return Object.assign({},ii(e),{method:"saml"});case"totp":return Object.assign({},ai(e),{method:"totp"});case"webauthn":return Object.assign({},ci(e),{method:"webauthn"});default:throw new Error(`No variant of UpdateLoginFlowBody exists with 'method=${e.method}'`)}}function fi(e){return pi(e,!1)}function pi(e,t=!1){return e==null?e:{code:e.code,csrf_token:e.csrf_token,email:e.email,method:e.method,transient_payload:e.transient_payload}}function wi(e){return hi(e,!1)}function hi(e,t=!1){return e==null?e:{csrf_token:e.csrf_token,email:e.email,method:e.method,transient_payload:e.transient_payload}}function gi(e){return _i(e,!1)}function _i(e,t=!1){if(e==null)return e;switch(e.method){case"code":return Object.assign({},fi(e),{method:"code"});case"link":return Object.assign({},wi(e),{method:"link"});default:throw new Error(`No variant of UpdateRecoveryFlowBody exists with 'method=${e.method}'`)}}function yi(e){return mi(e,!1)}function mi(e,t=!1){return e==null?e:{code:e.code,csrf_token:e.csrf_token,method:e.method,resend:e.resend,traits:e.traits,transient_payload:e.transient_payload}}function Fi(e){return vi(e,!1)}function vi(e,t=!1){return e==null?e:{csrf_token:e.csrf_token,id_token:e.id_token,id_token_nonce:e.id_token_nonce,method:e.method,provider:e.provider,traits:e.traits,transient_payload:e.transient_payload,upstream_parameters:e.upstream_parameters}}function Si(e){return ki(e,!1)}function ki(e,t=!1){return e==null?e:{csrf_token:e.csrf_token,method:e.method,passkey_register:e.passkey_register,traits:e.traits,transient_payload:e.transient_payload}}function bi(e){return Ci(e,!1)}function Ci(e,t=!1){return e==null?e:{csrf_token:e.csrf_token,method:e.method,password:e.password,traits:e.traits,transient_payload:e.transient_payload}}function xi(e){return Ti(e,!1)}function Ti(e,t=!1){return e==null?e:{csrf_token:e.csrf_token,method:e.method,screen:e.screen,traits:e.traits,transient_payload:e.transient_payload}}function Oi(e){return Ni(e,!1)}function Ni(e,t=!1){return e==null?e:{csrf_token:e.csrf_token,method:e.method,provider:e.provider,traits:e.traits,transient_payload:e.transient_payload}}function Ei(e){return Mi(e,!1)}function Mi(e,t=!1){return e==null?e:{csrf_token:e.csrf_token,method:e.method,traits:e.traits,transient_payload:e.transient_payload,webauthn_register:e.webauthn_register,webauthn_register_displayname:e.webauthn_register_displayname}}function Ri(e){return Di(e,!1)}function Di(e,t=!1){if(e==null)return e;switch(e.method){case"code":return Object.assign({},yi(e),{method:"code"});case"oidc":return Object.assign({},Fi(e),{method:"oidc"});case"passkey":return Object.assign({},Si(e),{method:"passkey"});case"password":return Object.assign({},bi(e),{method:"password"});case"profile":return Object.assign({},xi(e),{method:"profile"});case"saml":return Object.assign({},Oi(e),{method:"saml"});case"webauthn":return Object.assign({},Ei(e),{method:"webauthn"});default:throw new Error(`No variant of UpdateRegistrationFlowBody exists with 'method=${e.method}'`)}}function Ii(e){return Ji(e,!1)}function Ji(e,t=!1){return e==null?e:{csrf_token:e.csrf_token,lookup_secret_confirm:e.lookup_secret_confirm,lookup_secret_disable:e.lookup_secret_disable,lookup_secret_regenerate:e.lookup_secret_regenerate,lookup_secret_reveal:e.lookup_secret_reveal,method:e.method,transient_payload:e.transient_payload}}function Ai(e){return Ui(e,!1)}function Ui(e,t=!1){return e==null?e:{flow:e.flow,link:e.link,method:e.method,traits:e.traits,transient_payload:e.transient_payload,unlink:e.unlink,upstream_parameters:e.upstream_parameters}}function Li(e){return Vi(e,!1)}function Vi(e,t=!1){return e==null?e:{csrf_token:e.csrf_token,method:e.method,passkey_remove:e.passkey_remove,passkey_settings_register:e.passkey_settings_register}}function Pi(e){return Wi(e,!1)}function Wi(e,t=!1){return e==null?e:{csrf_token:e.csrf_token,method:e.method,password:e.password,transient_payload:e.transient_payload}}function Bi(e){return qi(e,!1)}function qi(e,t=!1){return e==null?e:{csrf_token:e.csrf_token,method:e.method,traits:e.traits,transient_payload:e.transient_payload}}function $i(e){return Ki(e,!1)}function Ki(e,t=!1){return e==null?e:{csrf_token:e.csrf_token,flow:e.flow,link:e.link,method:e.method,traits:e.traits,transient_payload:e.transient_payload,unlink:e.unlink}}function zi(e){return Gi(e,!1)}function Gi(e,t=!1){return e==null?e:{csrf_token:e.csrf_token,method:e.method,totp_code:e.totp_code,totp_unlink:e.totp_unlink,transient_payload:e.transient_payload}}function Qi(e){return Hi(e,!1)}function Hi(e,t=!1){return e==null?e:{csrf_token:e.csrf_token,method:e.method,transient_payload:e.transient_payload,webauthn_register:e.webauthn_register,webauthn_register_displayname:e.webauthn_register_displayname,webauthn_remove:e.webauthn_remove}}function Xi(e){return Yi(e,!1)}function Yi(e,t=!1){if(e==null)return e;switch(e.method){case"lookup_secret":return Object.assign({},Ii(e),{method:"lookup_secret"});case"oidc":return Object.assign({},Ai(e),{method:"oidc"});case"passkey":return Object.assign({},Li(e),{method:"passkey"});case"password":return Object.assign({},Pi(e),{method:"password"});case"profile":return Object.assign({},Bi(e),{method:"profile"});case"saml":return Object.assign({},$i(e),{method:"saml"});case"totp":return Object.assign({},zi(e),{method:"totp"});case"webauthn":return Object.assign({},Qi(e),{method:"webauthn"});default:throw new Error(`No variant of UpdateSettingsFlowBody exists with 'method=${e.method}'`)}}function Zi(e){return ji(e,!1)}function ji(e,t=!1){return e==null?e:{code:e.code,csrf_token:e.csrf_token,email:e.email,method:e.method,transient_payload:e.transient_payload}}function er(e){return tr(e,!1)}function tr(e,t=!1){return e==null?e:{csrf_token:e.csrf_token,email:e.email,method:e.method,transient_payload:e.transient_payload}}function nr(e){return or(e,!1)}function or(e,t=!1){if(e==null)return e;switch(e.method){case"code":return Object.assign({},Zi(e),{method:"code"});case"link":return Object.assign({},er(e),{method:"link"});default:throw new Error(`No variant of UpdateVerificationFlowBody exists with 'method=${e.method}'`)}}function we(e){return ir(e)}function ir(e,t){return e==null?e:{active:e.active==null?void 0:e.active,expires_at:e.expires_at==null?void 0:new Date(e.expires_at),id:e.id,issued_at:e.issued_at==null?void 0:new Date(e.issued_at),request_url:e.request_url==null?void 0:e.request_url,return_to:e.return_to==null?void 0:e.return_to,state:e.state,transient_payload:e.transient_payload==null?void 0:e.transient_payload,type:e.type,ui:te(e.ui)}}const dt={ChooseMethod:"choose_method",SentEmail:"sent_email",PassedChallenge:"passed_challenge",UnknownDefaultOpenApi:"11184809"};class rr extends Ee{async createBrowserLoginFlowRaw(t,n){const o={};t.refresh!=null&&(o.refresh=t.refresh),t.aal!=null&&(o.aal=t.aal),t.returnTo!=null&&(o.return_to=t.returnTo),t.loginChallenge!=null&&(o.login_challenge=t.loginChallenge),t.organization!=null&&(o.organization=t.organization),t.via!=null&&(o.via=t.via);const i={};t.cookie!=null&&(i.Cookie=String(t.cookie));const r=await this.request({path:"/self-service/login/browser",method:"GET",headers:i,query:o},n);return new _(r,a=>Je(a))}async createBrowserLoginFlow(t={},n){return await(await this.createBrowserLoginFlowRaw(t,n)).value()}async createBrowserLogoutFlowRaw(t,n){const o={};t.returnTo!=null&&(o.return_to=t.returnTo);const i={};t.cookie!=null&&(i.cookie=String(t.cookie));const r=await this.request({path:"/self-service/logout/browser",method:"GET",headers:i,query:o},n);return new _(r,a=>Oo(a))}async createBrowserLogoutFlow(t={},n){return await(await this.createBrowserLogoutFlowRaw(t,n)).value()}async createBrowserRecoveryFlowRaw(t,n){const o={};t.returnTo!=null&&(o.return_to=t.returnTo);const i={},r=await this.request({path:"/self-service/recovery/browser",method:"GET",headers:i,query:o},n);return new _(r,a=>ue(a))}async createBrowserRecoveryFlow(t={},n){return await(await this.createBrowserRecoveryFlowRaw(t,n)).value()}async createBrowserRegistrationFlowRaw(t,n){const o={};t.returnTo!=null&&(o.return_to=t.returnTo),t.loginChallenge!=null&&(o.login_challenge=t.loginChallenge),t.afterVerificationReturnTo!=null&&(o.after_verification_return_to=t.afterVerificationReturnTo),t.organization!=null&&(o.organization=t.organization);const i={},r=await this.request({path:"/self-service/registration/browser",method:"GET",headers:i,query:o},n);return new _(r,a=>Ae(a))}async createBrowserRegistrationFlow(t={},n){return await(await this.createBrowserRegistrationFlowRaw(t,n)).value()}async createBrowserSettingsFlowRaw(t,n){const o={};t.returnTo!=null&&(o.return_to=t.returnTo);const i={};t.cookie!=null&&(i.Cookie=String(t.cookie));const r=await this.request({path:"/self-service/settings/browser",method:"GET",headers:i,query:o},n);return new _(r,a=>fe(a))}async createBrowserSettingsFlow(t={},n){return await(await this.createBrowserSettingsFlowRaw(t,n)).value()}async createBrowserVerificationFlowRaw(t,n){const o={};t.returnTo!=null&&(o.return_to=t.returnTo);const i={},r=await this.request({path:"/self-service/verification/browser",method:"GET",headers:i,query:o},n);return new _(r,a=>we(a))}async createBrowserVerificationFlow(t={},n){return await(await this.createBrowserVerificationFlowRaw(t,n)).value()}async createFedcmFlowRaw(t){const n={},o={},i=await this.request({path:"/self-service/fed-cm/parameters",method:"GET",headers:o,query:n},t);return new _(i,r=>qn(r))}async createFedcmFlow(t){return await(await this.createFedcmFlowRaw(t)).value()}async createNativeLoginFlowRaw(t,n){const o={};t.refresh!=null&&(o.refresh=t.refresh),t.aal!=null&&(o.aal=t.aal),t.returnSessionTokenExchangeCode!=null&&(o.return_session_token_exchange_code=t.returnSessionTokenExchangeCode),t.returnTo!=null&&(o.return_to=t.returnTo),t.organization!=null&&(o.organization=t.organization),t.via!=null&&(o.via=t.via);const i={};t.xSessionToken!=null&&(i["X-Session-Token"]=String(t.xSessionToken));const r=await this.request({path:"/self-service/login/api",method:"GET",headers:i,query:o},n);return new _(r,a=>Je(a))}async createNativeLoginFlow(t={},n){return await(await this.createNativeLoginFlowRaw(t,n)).value()}async createNativeRecoveryFlowRaw(t){const n={},o={},i=await this.request({path:"/self-service/recovery/api",method:"GET",headers:o,query:n},t);return new _(i,r=>ue(r))}async createNativeRecoveryFlow(t){return await(await this.createNativeRecoveryFlowRaw(t)).value()}async createNativeRegistrationFlowRaw(t,n){const o={};t.returnSessionTokenExchangeCode!=null&&(o.return_session_token_exchange_code=t.returnSessionTokenExchangeCode),t.returnTo!=null&&(o.return_to=t.returnTo),t.organization!=null&&(o.organization=t.organization);const i={},r=await this.request({path:"/self-service/registration/api",method:"GET",headers:i,query:o},n);return new _(r,a=>Ae(a))}async createNativeRegistrationFlow(t={},n){return await(await this.createNativeRegistrationFlowRaw(t,n)).value()}async createNativeSettingsFlowRaw(t,n){const o={},i={};t.xSessionToken!=null&&(i["X-Session-Token"]=String(t.xSessionToken));const r=await this.request({path:"/self-service/settings/api",method:"GET",headers:i,query:o},n);return new _(r,a=>fe(a))}async createNativeSettingsFlow(t={},n){return await(await this.createNativeSettingsFlowRaw(t,n)).value()}async createNativeVerificationFlowRaw(t,n){const o={};t.returnTo!=null&&(o.return_to=t.returnTo);const i={},r=await this.request({path:"/self-service/verification/api",method:"GET",headers:i,query:o},n);return new _(r,a=>we(a))}async createNativeVerificationFlow(t={},n){return await(await this.createNativeVerificationFlowRaw(t,n)).value()}async disableMyOtherSessionsRaw(t,n){const o={},i={};t.xSessionToken!=null&&(i["X-Session-Token"]=String(t.xSessionToken)),t.cookie!=null&&(i.Cookie=String(t.cookie));const r=await this.request({path:"/sessions",method:"DELETE",headers:i,query:o},n);return new _(r,a=>Hn(a))}async disableMyOtherSessions(t={},n){return await(await this.disableMyOtherSessionsRaw(t,n)).value()}async disableMySessionRaw(t,n){if(t.id==null)throw new F("id",'Required parameter "id" was null or undefined when calling disableMySession().');const o={},i={};t.xSessionToken!=null&&(i["X-Session-Token"]=String(t.xSessionToken)),t.cookie!=null&&(i.Cookie=String(t.cookie));const r=await this.request({path:"/sessions/{id}".replace("{id}",encodeURIComponent(String(t.id))),method:"DELETE",headers:i,query:o},n);return new Re(r)}async disableMySession(t,n){await this.disableMySessionRaw(t,n)}async exchangeSessionTokenRaw(t,n){if(t.initCode==null)throw new F("initCode",'Required parameter "initCode" was null or undefined when calling exchangeSessionToken().');if(t.returnToCode==null)throw new F("returnToCode",'Required parameter "returnToCode" was null or undefined when calling exchangeSessionToken().');const o={};t.initCode!=null&&(o.init_code=t.initCode),t.returnToCode!=null&&(o.return_to_code=t.returnToCode);const i={},r=await this.request({path:"/sessions/token-exchange",method:"GET",headers:i,query:o},n);return new _(r,a=>Ue(a))}async exchangeSessionToken(t,n){return await(await this.exchangeSessionTokenRaw(t,n)).value()}async getFlowErrorRaw(t,n){if(t.id==null)throw new F("id",'Required parameter "id" was null or undefined when calling getFlowError().');const o={};t.id!=null&&(o.id=t.id);const i={},r=await this.request({path:"/self-service/errors",method:"GET",headers:i,query:o},n);return new _(r,a=>Yn(a))}async getFlowError(t,n){return await(await this.getFlowErrorRaw(t,n)).value()}async getLoginFlowRaw(t,n){if(t.id==null)throw new F("id",'Required parameter "id" was null or undefined when calling getLoginFlow().');const o={};t.id!=null&&(o.id=t.id);const i={};t.cookie!=null&&(i.Cookie=String(t.cookie));const r=await this.request({path:"/self-service/login/flows",method:"GET",headers:i,query:o},n);return new _(r,a=>Je(a))}async getLoginFlow(t,n){return await(await this.getLoginFlowRaw(t,n)).value()}async getRecoveryFlowRaw(t,n){if(t.id==null)throw new F("id",'Required parameter "id" was null or undefined when calling getRecoveryFlow().');const o={};t.id!=null&&(o.id=t.id);const i={};t.cookie!=null&&(i.Cookie=String(t.cookie));const r=await this.request({path:"/self-service/recovery/flows",method:"GET",headers:i,query:o},n);return new _(r,a=>ue(a))}async getRecoveryFlow(t,n){return await(await this.getRecoveryFlowRaw(t,n)).value()}async getRegistrationFlowRaw(t,n){if(t.id==null)throw new F("id",'Required parameter "id" was null or undefined when calling getRegistrationFlow().');const o={};t.id!=null&&(o.id=t.id);const i={};t.cookie!=null&&(i.Cookie=String(t.cookie));const r=await this.request({path:"/self-service/registration/flows",method:"GET",headers:i,query:o},n);return new _(r,a=>Ae(a))}async getRegistrationFlow(t,n){return await(await this.getRegistrationFlowRaw(t,n)).value()}async getSettingsFlowRaw(t,n){if(t.id==null)throw new F("id",'Required parameter "id" was null or undefined when calling getSettingsFlow().');const o={};t.id!=null&&(o.id=t.id);const i={};t.xSessionToken!=null&&(i["X-Session-Token"]=String(t.xSessionToken)),t.cookie!=null&&(i.Cookie=String(t.cookie));const r=await this.request({path:"/self-service/settings/flows",method:"GET",headers:i,query:o},n);return new _(r,a=>fe(a))}async getSettingsFlow(t,n){return await(await this.getSettingsFlowRaw(t,n)).value()}async getVerificationFlowRaw(t,n){if(t.id==null)throw new F("id",'Required parameter "id" was null or undefined when calling getVerificationFlow().');const o={};t.id!=null&&(o.id=t.id);const i={};t.cookie!=null&&(i.cookie=String(t.cookie));const r=await this.request({path:"/self-service/verification/flows",method:"GET",headers:i,query:o},n);return new _(r,a=>we(a))}async getVerificationFlow(t,n){return await(await this.getVerificationFlowRaw(t,n)).value()}async getWebAuthnJavaScriptRaw(t){const n={},o={},i=await this.request({path:"/.well-known/ory/webauthn.js",method:"GET",headers:o,query:n},t);return this.isJsonMime(i.headers.get("content-type"))?new _(i):new Tn(i)}async getWebAuthnJavaScript(t){return await(await this.getWebAuthnJavaScriptRaw(t)).value()}async listMySessionsRaw(t,n){const o={};t.perPage!=null&&(o.per_page=t.perPage),t.page!=null&&(o.page=t.page),t.pageSize!=null&&(o.page_size=t.pageSize),t.pageToken!=null&&(o.page_token=t.pageToken);const i={};t.xSessionToken!=null&&(i["X-Session-Token"]=String(t.xSessionToken)),t.cookie!=null&&(i.Cookie=String(t.cookie));const r=await this.request({path:"/sessions",method:"GET",headers:i,query:o},n);return new _(r,a=>a.map(de))}async listMySessions(t={},n){return await(await this.listMySessionsRaw(t,n)).value()}async performNativeLogoutRaw(t,n){if(t.performNativeLogoutBody==null)throw new F("performNativeLogoutBody",'Required parameter "performNativeLogoutBody" was null or undefined when calling performNativeLogout().');const o={},i={};i["Content-Type"]="application/json";const r=await this.request({path:"/self-service/logout/api",method:"DELETE",headers:i,query:o,body:Eo(t.performNativeLogoutBody)},n);return new Re(r)}async performNativeLogout(t,n){await this.performNativeLogoutRaw(t,n)}async toSessionRaw(t,n){const o={};t.tokenizeAs!=null&&(o.tokenize_as=t.tokenizeAs);const i={};t.xSessionToken!=null&&(i["X-Session-Token"]=String(t.xSessionToken)),t.cookie!=null&&(i.Cookie=String(t.cookie));const r=await this.request({path:"/sessions/whoami",method:"GET",headers:i,query:o},n);return new _(r,a=>de(a))}async toSession(t={},n){return await(await this.toSessionRaw(t,n)).value()}async updateFedcmFlowRaw(t,n){if(t.updateFedcmFlowBody==null)throw new F("updateFedcmFlowBody",'Required parameter "updateFedcmFlowBody" was null or undefined when calling updateFedcmFlow().');const o={},i={};i["Content-Type"]="application/json";const r=await this.request({path:"/self-service/fed-cm/token",method:"POST",headers:i,query:o,body:$o(t.updateFedcmFlowBody)},n);return new _(r,a=>Ue(a))}async updateFedcmFlow(t,n){return await(await this.updateFedcmFlowRaw(t,n)).value()}async updateLoginFlowRaw(t,n){if(t.flow==null)throw new F("flow",'Required parameter "flow" was null or undefined when calling updateLoginFlow().');if(t.updateLoginFlowBody==null)throw new F("updateLoginFlowBody",'Required parameter "updateLoginFlowBody" was null or undefined when calling updateLoginFlow().');const o={};t.flow!=null&&(o.flow=t.flow);const i={};i["Content-Type"]="application/json",t.xSessionToken!=null&&(i["X-Session-Token"]=String(t.xSessionToken)),t.cookie!=null&&(i.Cookie=String(t.cookie));const r=await this.request({path:"/self-service/login",method:"POST",headers:i,query:o,body:ui(t.updateLoginFlowBody)},n);return new _(r,a=>Ue(a))}async updateLoginFlow(t,n){return await(await this.updateLoginFlowRaw(t,n)).value()}async updateLogoutFlowRaw(t,n){const o={};t.token!=null&&(o.token=t.token),t.returnTo!=null&&(o.return_to=t.returnTo);const i={};t.cookie!=null&&(i.Cookie=String(t.cookie));const r=await this.request({path:"/self-service/logout",method:"GET",headers:i,query:o},n);return new Re(r)}async updateLogoutFlow(t={},n){await this.updateLogoutFlowRaw(t,n)}async updateRecoveryFlowRaw(t,n){if(t.flow==null)throw new F("flow",'Required parameter "flow" was null or undefined when calling updateRecoveryFlow().');if(t.updateRecoveryFlowBody==null)throw new F("updateRecoveryFlowBody",'Required parameter "updateRecoveryFlowBody" was null or undefined when calling updateRecoveryFlow().');const o={};t.flow!=null&&(o.flow=t.flow),t.token!=null&&(o.token=t.token);const i={};i["Content-Type"]="application/json",t.cookie!=null&&(i.Cookie=String(t.cookie));const r=await this.request({path:"/self-service/recovery",method:"POST",headers:i,query:o,body:gi(t.updateRecoveryFlowBody)},n);return new _(r,a=>ue(a))}async updateRecoveryFlow(t,n){return await(await this.updateRecoveryFlowRaw(t,n)).value()}async updateRegistrationFlowRaw(t,n){if(t.flow==null)throw new F("flow",'Required parameter "flow" was null or undefined when calling updateRegistrationFlow().');if(t.updateRegistrationFlowBody==null)throw new F("updateRegistrationFlowBody",'Required parameter "updateRegistrationFlowBody" was null or undefined when calling updateRegistrationFlow().');const o={};t.flow!=null&&(o.flow=t.flow);const i={};i["Content-Type"]="application/json",t.cookie!=null&&(i.Cookie=String(t.cookie));const r=await this.request({path:"/self-service/registration",method:"POST",headers:i,query:o,body:Ri(t.updateRegistrationFlowBody)},n);return new _(r,a=>Bo(a))}async updateRegistrationFlow(t,n){return await(await this.updateRegistrationFlowRaw(t,n)).value()}async updateSettingsFlowRaw(t,n){if(t.flow==null)throw new F("flow",'Required parameter "flow" was null or undefined when calling updateSettingsFlow().');if(t.updateSettingsFlowBody==null)throw new F("updateSettingsFlowBody",'Required parameter "updateSettingsFlowBody" was null or undefined when calling updateSettingsFlow().');const o={};t.flow!=null&&(o.flow=t.flow);const i={};i["Content-Type"]="application/json",t.xSessionToken!=null&&(i["X-Session-Token"]=String(t.xSessionToken)),t.cookie!=null&&(i.Cookie=String(t.cookie));const r=await this.request({path:"/self-service/settings",method:"POST",headers:i,query:o,body:Xi(t.updateSettingsFlowBody)},n);return new _(r,a=>fe(a))}async updateSettingsFlow(t,n){return await(await this.updateSettingsFlowRaw(t,n)).value()}async updateVerificationFlowRaw(t,n){if(t.flow==null)throw new F("flow",'Required parameter "flow" was null or undefined when calling updateVerificationFlow().');if(t.updateVerificationFlowBody==null)throw new F("updateVerificationFlowBody",'Required parameter "updateVerificationFlowBody" was null or undefined when calling updateVerificationFlow().');const o={};t.flow!=null&&(o.flow=t.flow),t.token!=null&&(o.token=t.token);const i={};i["Content-Type"]="application/json",t.cookie!=null&&(i.Cookie=String(t.cookie));const r=await this.request({path:"/self-service/verification",method:"POST",headers:i,query:o,body:nr(t.updateVerificationFlowBody)},n);return new _(r,a=>we(a))}async updateVerificationFlow(t,n){return await(await this.updateVerificationFlowRaw(t,n)).value()}}function V(e){return typeof e=="object"&&!!e&&"error"in e&&typeof e.error=="object"&&!!e.error&&"id"in e.error}function ar(e){return V(e)&&e.error.id==="session_refresh_required"}function ft(e){return V(e)&&e.error.id==="self_service_flow_expired"}function sr(e){return V(e)&&V(e)&&e.error.id==="browser_location_change_required"}function he(e){return V(e)&&e.error.id==="session_already_available"}function cr(e){return V(e)&&e.error.id==="session_aal2_required"}function lr(e){return V(e)&&e.error.id==="security_csrf_violation"}const ur=e=>e instanceof Y?!0:typeof e=="object"&&!!e&&"name"in e&&e.name==="ResponseError",B=e=>async t=>{if(ur(t))switch(t.response.status){case 404:e.onRestartFlow();return;case 410:{const n=await pt(t.response);if(ft(n)){e.onRestartFlow(n.use_flow_id);return}e.onRestartFlow();return}case 400:return e.onValidationError(await t.response.json());case 403:case 422:{const n=await pt(t.response);if(sr(n)&&n.redirect_browser_to){e.onRedirect(n.redirect_browser_to,!0);return}else if(ft(n)){e.onRestartFlow(n.use_flow_id);return}else if(ar(n)){e.onRedirect(n.redirect_browser_to,!0);return}else if(lr(n)){e.onRestartFlow();return}throw new Y(t.response,"The Ory API endpoint returned a response code the SDK does not know how to handle. Please check the network tab for more information:"+JSON.stringify(n))}default:throw new Y(t.response,"The Ory API endpoint returned a response code the SDK does not know how to handle. Please check the network tab for more information.")}else if(t instanceof Me)throw new Me(t,"Unable to call the API endpoint. Ensure that CORS is set up correctly and that you have provided a valid SDK URL to Ory Elements.");throw t};async function pt(e){try{return await e.clone().json()}catch{throw new Y(e,"The Ory API endpoint returned a response the SDK does not know how to handle:"+await e.text())}}const wt=["show_settings_ui","show_recovery_ui","show_verification_ui","redirect_browser_to","set_ory_session_token"];function Ve(e,{onRedirect:t}){if(!e||e.length===0)return!1;const n=dr(e);if(!n)return!1;const o=(i,r,a)=>a?(t(a,!0),!0):(t("/"+r+"?flow="+i,!1),!0);if(fr(n))throw new Error("Ory Elements does not support API flows yet.");if(pr(n)&&n.redirect_browser_to)return t(n.redirect_browser_to,!0),!0;if(gr(n))return o(n.flow.id,"verification",n.flow.url);if(wr(n))return o(n.flow.id,"recovery",n.flow.url);if(hr(n))return o(n.flow.id,"settings",n.flow.url);throw new Error("Unknown action: "+JSON.stringify(n))}function dr(e){return!e||e.length===0?void 0:e.toSorted((n,o)=>wt.indexOf(n.action)-wt.indexOf(o.action))[0]}function fr(e){return e.action==="set_ory_session_token"}function pr(e){return e.action==="redirect_browser_to"}function wr(e){return e.action==="show_recovery_ui"}function hr(e){return e.action==="show_settings_ui"}function gr(e){return e.action==="show_verification_ui"}function Pe(e){return e.node_type==="input"}function ht({attributes:e}){return Pe(e)?e.name:e.id}const gt=e=>!(typeof e!="object"||e===null||!co(e)||e.type!==so.Error),_r=e=>!(typeof e!="object"||e===null||!("id"in e)||typeof e.id!="string"||"context"in e&&(typeof e.context!="object"||e.context===null)||"originalError"in e&&!gt(e.originalError)),_t=e=>e?.filter(gt).map(mr)??[],C=({onSubmit:e,onChange:t,onBlur:n}={})=>{const o=[...Array.isArray(e)?e:[],...Array.isArray(t)?t:[],...Array.isArray(n)?n:[]].filter(_r);return[...new Map(o.map(i=>[i.id,i])).values()]};var ne=(e=>(e.FieldMismatch="FieldMismatch",e.FieldRequired="FieldRequired",e))(ne||{});const ge=e=>({id:`AdditionalValidationError_${e}`}),yr=e=>{const t=(h,S)=>({id:`${h}_${S}`,originalError:e}),n=(h,S,$)=>({id:`${h}_${S}_WithContext`,context:$,originalError:e});return{createGenericError:h=>t("Error",h),createGenericErrorWithContext:(h,S)=>n("Error",h,S),createLoginFlowError:h=>t("LoginFlowError",h),createLoginFlowErrorWithContext:(h,S)=>n("LoginFlowError",h,S),createRegisterFlowError:h=>t("RegisterFlowError",h),createRegisterFlowErrorWithContext:(h,S)=>n("RegisterFlowError",h,S),createSettingsFlowError:h=>t("SettingsFlowError",h),createSettingsFlowErrorWithContext:(h,S)=>n("SettingsFlowError",h,S),createRecoveryFlowError:h=>t("RecoveryFlowError",h),createRecoveryFlowErrorWithContext:(h,S)=>n("RecoveryFlowError",h,S),createVerificationFlowError:h=>t("VerificationFlowError",h),createVerificationFlowErrorWithContext:(h,S)=>n("VerificationFlowError",h,S)}},mr=e=>{const{createGenericError:t,createGenericErrorWithContext:n,createLoginFlowError:o,createLoginFlowErrorWithContext:i,createRegisterFlowError:r,createRegisterFlowErrorWithContext:a,createSettingsFlowError:c,createSettingsFlowErrorWithContext:u,createRecoveryFlowError:d,createRecoveryFlowErrorWithContext:w,createVerificationFlowError:f,createVerificationFlowErrorWithContext:g}=yr(e);switch(e.id){case 4000001:return p(e.context,"reason","string")?n("InvalidFormat",{reason:e.context.reason}):t("InvalidFormat");case 4000002:return p(e.context,"property","string")?n("MissingProperty",{property:e.context.property}):t("MissingProperty");case 4000003:return p(e.context,"min_length","number")&&p(e.context,"actual_length","number")?n("TooShort",{min_length:e.context.min_length,actual_length:e.context.actual_length}):t("TooShort");case 4000004:return p(e.context,"pattern","string")?n("InvalidPattern",{pattern:e.context.pattern}):t("InvalidPattern");case 4000005:return p(e.context,"reason","string")?n("PasswordPolicyViolation",{reason:e.context.reason}):t("PasswordPolicyViolation");case 4000006:return t("InvalidCredentials");case 4000007:return t("DuplicateCredentials");case 4000008:return t("TOTPVerifierWrong");case 4000009:return t("IdentifierMissing");case 4000010:return t("AddressNotVerified");case 4000011:return t("NoTOTPDeviceSetUp");case 4000012:return t("RecoveryCodeAlreadyUsed");case 4000013:return t("NoWebAuthnDeviceSetUp");case 4000014:return t("NoRecoveryCodesSetUp");case 4000015:return t("AccountNotExistsOrHasSecurityKey");case 4000016:return t("InvalidRecoveryCode");case 4000017:return p(e.context,"max_length","number")&&p(e.context,"actual_length","number")?n("TooLong",{max_length:e.context.max_length,actual_length:e.context.actual_length}):t("TooLong");case 4000018:return p(e.context,"actual","number")&&p(e.context,"minimum","number")?n("MustBeGreaterOrEqualThan",{actual:e.context.actual,minimum:e.context.minimum}):t("MustBeGreaterOrEqualThan");case 4000019:return p(e.context,"actual","number")&&p(e.context,"minimum","number")?n("MustBeGreaterThan",{actual:e.context.actual,minimum:e.context.minimum}):t("MustBeGreaterThan");case 4000020:return p(e.context,"actual","number")&&p(e.context,"maximum","number")?n("MustBeLessOrEqualThan",{actual:e.context.actual,maximum:e.context.maximum}):t("MustBeLessOrEqualThan");case 4000021:return p(e.context,"actual","number")&&p(e.context,"maximum","number")?n("MustBeLessThan",{actual:e.context.actual,maximum:e.context.maximum}):t("MustBeLessThan");case 4000022:return p(e.context,"actual","number")&&p(e.context,"base","number")?n("IsNotMultipleOf",{actual:e.context.actual,base:e.context.base}):t("IsNotMultipleOf");case 4000023:return p(e.context,"max_items","number")&&p(e.context,"actual_items","number")?n("TooManyItems",{max_items:e.context.max_items,actual_items:e.context.actual_items}):t("TooManyItems");case 4000024:return p(e.context,"min_items","number")&&p(e.context,"actual_items","number")?n("TooFewItems",{min_items:e.context.min_items,actual_items:e.context.actual_items}):t("TooFewItems");case 4000025:return p(e.context,"index_a","number")&&p(e.context,"index_b","number")?n("DuplicateItems",{index_a:e.context.index_a,index_b:e.context.index_b}):t("DuplicateItems");case 4000026:return p(e.context,"actual_type","string")&&p(e.context,"allowed_types","object")&&Array.isArray(e.context.allowed_types)&&e.context.allowed_types.every(k=>typeof k=="string")?n("InvalidType",{actual_type:e.context.actual_type,allowed_types:e.context.allowed_types}):t("InvalidType");case 4000027:return t("AccountAlreadyExists");case 4000028:return p(e.context,"credential_identifier_hint","string")&&p(e.context,"available_credential_types","object")&&Array.isArray(e.context.available_credential_types)&&e.context.available_credential_types.every(k=>typeof k=="string")&&p(e.context,"available_oidc_providers","object")&&Array.isArray(e.context.available_oidc_providers)&&e.context.available_oidc_providers.every(k=>typeof k=="string")?n("CredentialIdentifierHintAlreadyUsedByOtherAccount",{available_credential_types:e.context.available_credential_types,available_oidc_providers:e.context.available_oidc_providers,credential_identifier_hint:e.context.credential_identifier_hint}):t("CredentialIdentifierHintAlreadyUsedByOtherAccount");case 4000029:return p(e.context,"expected","string")?n("MustBeEqualTo",{expected:e.context.expected}):t("MustBeEqualTo");case 4000030:return t("ConstFailed");case 4000031:return t("PasswordAndIdentifierTooSimilar");case 4000032:return p(e.context,"min_length","number")&&p(e.context,"actual_length","number")?n("PasswordTooShort",{min_length:e.context.min_length,actual_length:e.context.actual_length}):t("PasswordTooShort");case 4000033:return p(e.context,"max_length","number")&&p(e.context,"actual_length","number")?n("PasswordTooLong",{max_length:e.context.max_length,actual_length:e.context.actual_length}):t("PasswordTooLong");case 4000034:return p(e.context,"breaches","number")?n("PasswordLeaked",{breaches:e.context.breaches}):t("PasswordLeaked");case 4000035:return t("AccountNotExistsOrWithoutCodeSignIn");case 4000036:return t("TraitsDoNotMatch");case 4000037:return t("AccountNotExistsOrWithoutLoginMethod");case 4000038:return t("CaptchaFailed");case 4010001:return p(e.context,"expired_at","string")&&p(e.context,"expired_at_unix","number")?i("LoginFlowExpired",{expired_at:e.context.expired_at,expired_at_unix:e.context.expired_at_unix}):o("LoginFlowExpired");case 4010002:return o("NoLogInStrategyFound");case 4010003:return o("NoSignUpStrategyFound");case 4010004:return o("NoSettingsStrategyFound");case 4010005:return o("NoRecoveryStrategyFound");case 4010006:return o("NoVerificationStrategyFound");case 4010007:return o("LoginRequestAlreadyCompletedSuccessfully");case 4010008:return o("InvalidLoginCodeOrAlreadyUsed");case 4010009:return o("MismatchedLinkedCretentials");case 4010010:return o("MismatchedAddress");case 4040001:return p(e.context,"expired_at","string")&&p(e.context,"expired_at_unix","number")?a("RegisterFlowExpired",{expired_at:e.context.expired_at,expired_at_unix:e.context.expired_at_unix}):r("RegisterFlowExpired");case 4040002:return r("RegisterRequestAlreadyCompletedSuccessfully");case 4040003:return r("InvalidRegisterCodeOrAlreadyUsed");case 4050001:return p(e.context,"expired_at","string")&&p(e.context,"expired_at_unix","number")?u("SettingsFlowExpired",{expired_at:e.context.expired_at,expired_at_unix:e.context.expired_at_unix}):c("SettingsFlowExpired");case 4060001:return d("RecoveryRequestAlreadyCompletedSuccessfully");case 4060002:return d("RecoveryFlowFailureState");case 4060004:return d("InvalidTokenOrAlreadyUsed");case 4060005:return p(e.context,"expired_at","string")&&p(e.context,"expired_at_unix","number")?w("RecoveryFlowExpired",{expired_at:e.context.expired_at,expired_at_unix:e.context.expired_at_unix}):d("RecoveryFlowExpired");case 4060006:return d("InvalidRecoveryCodeOrAlreadyUsed");case 4070001:return f("InvalidVerificationTokenOrAlreadyUsed");case 4070002:return f("VerificationRequestAlreadyCompletedSuccessfully");case 4070003:return f("VerificationFlowFailureState");case 4070005:return p(e.context,"expired_at","string")&&p(e.context,"expired_at_unix","number")?g("VerificationFlowExpired",{expired_at:e.context.expired_at,expired_at_unix:e.context.expired_at_unix}):f("VerificationFlowExpired");case 4070006:return f("InvalidVerificationCodeOrAlreadyUsed");default:return p(e.context,"reason","string")?n("Generic",{reason:e.context.reason}):t("Generic")}};function T(e,t){return e?.find(n=>ht(n)===t)}function Fr(e,t){return e?.filter(n=>ht(n)===t)??[]}function K(e){if(e&&Pe(e.attributes))return e.attributes}function vr(e){if(e&&Pe(e.attributes))return e.messages}function v(e){const t=K(T(e.ui.nodes,"csrf_token"));if(!t||typeof t.value!="string")throw new Error("CSRF token not found");return t.value}const Sr=e=>{if(e.group!==So.Passkey||e.type!==ko.Input||e.attributes.node_type!==_o.Input||e.attributes.name!=="passkey_remove"||!e.meta?.label?.context)return!1;const{context:t}=e.meta.label;return"added_at"in t&&typeof t.added_at=="string"&&"display_name"in t&&typeof t.display_name=="string"&&"added_at_unix"in t&&typeof t.added_at_unix=="number"},yt=["apple","facebook","google"],kr=e=>e.group==="oidc"&&e.attributes.node_type==="input"&&yt.includes(e.attributes.value),_e=(e,t)=>e?.find(n=>kr(n)&&n.attributes.value===t)??void 0,oe=async({error:e})=>await B({onRedirect:(t,n)=>{globalThis.location.href=t},onRestartFlow:()=>{throw new Error("Needs to restart the flow",{cause:P.FlowRestartRequired})},onValidationError:t=>t})(e),N=(e,t,n)=>{const o=_t(e.ui.messages);o.length>0&&(t.setErrorMap({onSubmit:o}),n?.({target:"root",errors:o}));for(const i in t.fieldInfo){const r=i,a=_t(vr(T(e.ui.nodes,r)));a.length>0&&(t.setFieldMeta(r,c=>({...c,errorMap:{onSubmit:a}})),n?.({target:r,errors:a}))}},We="leancode_kratos",z=e=>[We,...e],G=e=>`${We}_${e}`;function I(e){return l.useMemo(()=>C(e.state.errorMap),[e.state.errorMap])}const mt=l.createContext(void 0);function x(){const e=l.useContext(mt);if(e===void 0)throw new Error("useKratosClientContext must be used within a KratosClientContextProvider");return e}function br({children:e,api:t}){const n=l.useMemo(()=>({kratosClient:t}),[t]);return s.jsx(mt.Provider,{value:n,children:e})}function E({children:e}){const t=m.Root;return s.jsx(t,{type:"submit",children:e})}const Ft=l.createContext(void 0);function Cr({children:e,emailVerificationForm:t}){const n=l.useMemo(()=>({emailVerificationForm:t}),[t]);return s.jsx(Ft.Provider,{value:n,children:e})}function xr(){const e=l.useContext(Ft);if(e===void 0)throw new Error("useEmailVerificationFormContext must be used within a EmailVerificationFormProvider");return e}const Tr=G("verification_flow"),ye=(e="no_id")=>z([Tr,e]),vt=l.createContext(void 0);function me({children:e}){const[t,n]=l.useState(),[o,i]=l.useState(),r=l.useCallback(()=>{n(void 0),i(void 0)},[]);return s.jsx(vt.Provider,{value:{verificationFlowId:t,setVerificationFlowId:n,verifiableAddress:o,setVerifiableAddress:i,resetFlow:r},children:e})}function J(){const e=l.useContext(vt);if(e===void 0)throw new Error("useVerificationFlow must be used within a VerificationFlowProvider");return e}function Or({returnTo:e}={}){const{kratosClient:t}=x(),{setVerificationFlowId:n}=J(),o=y.useQueryClient();return y.useMutation({mutationFn:()=>t.createBrowserVerificationFlow({returnTo:e},async({init:{headers:i}})=>({headers:{...i,Accept:"application/json"}})),onSuccess(i){o.setQueryDefaults(ye(i.id),{staleTime:1/0}),o.setQueryData(ye(i.id),i),n(i.id)}})}function Be(){const{kratosClient:e}=x(),{verificationFlowId:t}=J();return y.useQuery({queryKey:ye(t),queryFn:async({signal:n})=>{if(!t)throw new Error("No verification flow ID provided",{cause:P.NoFlowId});try{return await e.getVerificationFlow({id:t},async({init:{headers:o}})=>({signal:n,headers:{...o,Accept:"application/json"}}))}catch(o){throw await oe({error:o})}},enabled:!!t,staleTime:1/0})}function St(){const{kratosClient:e}=x(),{verificationFlowId:t,resetFlow:n}=J(),o=y.useQueryClient();return y.useMutation({mutationFn:async i=>{if(!t)throw new Error("Verification flow ID is not set");try{const r=await e.updateVerificationFlow({flow:t,updateVerificationFlowBody:i},{headers:{Accept:"application/json","Content-Type":"application/json"}});return r.state===dt.PassedChallenge&&r.return_to&&(globalThis.location.href=r.return_to),r}catch(r){return await B({onRedirect:(a,c)=>{globalThis.location.href=a},onRestartFlow:n,onValidationError:a=>a})(r)}},onSuccess(i){i&&"id"in i&&o.setQueryData(ye(i.id),i)}})}function Nr({children:e}){const{verifiableAddress:t}=J(),{mutate:n}=St(),{data:o}=Be(),i=l.useCallback(()=>{!o||!t||n({method:"code",csrf_token:v(o),email:t,code:""})},[o,t,n]),r=m.Root;return s.jsx(r,{type:"button",onClick:i,children:e})}function Er({children:e}){const{emailVerificationForm:t}=xr(),n=m.Root;return s.jsx(t.Field,{name:"code",children:o=>s.jsx(n,{errors:C(o.state.meta.errorMap),name:o.name,type:"text",value:o.state.value,onChange:i=>o.handleChange(i.target.value),children:e})})}var kt=(e=>(e.Code="code",e))(kt||{});function Mr({onError:e,onVerificationSuccess:t}){const{verifiableAddress:n}=J(),{mutateAsync:o}=St(),{data:i}=Be();return D.useForm({defaultValues:{[kt.Code]:""},onSubmit:async({value:r,formApi:a})=>{if(!i||!n)return;const c=await o({csrf_token:v(i),method:"code",code:r.code,email:n});if(c){if(c.state==dt.PassedChallenge){t?.();return}N(c,a,e)}}})}function Rr({emailVerificationForm:e,onError:t,onVerificationSuccess:n}){const o=Mr({onError:t,onVerificationSuccess:n}),i=I(o);return s.jsx(Cr,{emailVerificationForm:o,children:s.jsx("form",{onSubmit:r=>{r.preventDefault(),o.handleSubmit()},children:s.jsx(e,{Code:Er,errors:i,isSubmitting:o.state.isSubmitting,isValidating:o.state.isValidating,Resend:Nr,Submit:E})})})}function bt(e){return s.jsx(me,{children:s.jsx(Fe,{...e})})}function Fe({emailVerificationForm:e,initialFlowId:t,initialVerifiableAddress:n,returnTo:o,onError:i,onVerificationSuccess:r,onFlowRestart:a}){const{verificationFlowId:c,setVerificationFlowId:u,verifiableAddress:d,setVerifiableAddress:w}=J(),{error:f}=Be(),{mutate:g}=Or({returnTo:o});return ee({initialFlowId:t,currentFlowId:c,error:f,onFlowRestart:a,createFlow:g,setFlowId:u}),!d&&n&&w(n),s.jsx(Rr,{emailVerificationForm:e,onError:i,onVerificationSuccess:r})}const Dr=Object.freeze(Object.defineProperty({__proto__:null,VerificationFlow:bt,VerificationFlowProvider:me,VerificationFlowWrapper:Fe,useVerificationFlowContext:J},Symbol.toStringTag,{value:"Module"})),Ir=G("login_flow"),ve=(e="no_id")=>z([Ir,e]),Ct=l.createContext(void 0);function Jr({children:e}){const[t,n]=l.useState(),o=l.useCallback(()=>{n(void 0)},[]);return s.jsx(Ct.Provider,{value:{loginFlowId:t,setLoginFlowId:n,resetFlow:o},children:e})}function Se(){const e=l.useContext(Ct);if(e===void 0)throw new Error("useLoginFlowContext must be used within a LoginFlow");return e}function Ar({aal:e,refresh:t,returnTo:n}={}){const{kratosClient:o}=x(),{setLoginFlowId:i}=Se(),r=y.useQueryClient();return y.useMutation({mutationFn:async()=>{try{return await o.createBrowserLoginFlow({aal:e,refresh:t,returnTo:n},async({init:{headers:a}})=>({headers:{...a,Accept:"application/json"}}))}catch(a){throw await B({onRestartFlow:()=>{},onRedirect:()=>{},onValidationError:c=>c})(a)}},onSuccess(a){r.setQueryDefaults(ve(a.id),{staleTime:1/0}),r.setQueryData(ve(a.id),a),i(a.id)}})}function A(){const{kratosClient:e}=x(),{loginFlowId:t}=Se();return y.useQuery({queryKey:ve(t),queryFn:async({signal:n})=>{if(!t)throw new Error("No login flow ID provided",{cause:P.NoFlowId});try{return await e.getLoginFlow({id:t},async({init:{headers:o}})=>({signal:n,headers:{...o,Accept:"application/json"}}))}catch(o){throw await oe({error:o})}},enabled:!!t,staleTime:1/0})}const xt=()=>{const{data:e}=A();return l.useMemo(()=>{if(!e)return;const t=T(e.ui.nodes,"identifier");if(!(!t||t.attributes.node_type!=="input"||typeof t.attributes.value!="string"))return t.attributes.value},[e])};function Q(){const{kratosClient:e}=x(),{loginFlowId:t,resetFlow:n}=Se(),{setVerificationFlowId:o,setVerifiableAddress:i}=J(),r=y.useQueryClient();return y.useMutation({mutationFn:async a=>{if(!t)throw new Error("Login flow ID is not set");try{const u=await(await e.updateLoginFlowRaw({flow:t,updateLoginFlowBody:a},{headers:{Accept:"application/json","Content-Type":"application/json"}})).value();if(u&&"continue_with"in u){const d=u.continue_with?.find(w=>w.action==="show_verification_ui");d!==void 0?(o(d.flow.id),i(d.flow.verifiable_address)):Ve(u.continue_with,{onRedirect:(w,f)=>{globalThis.location.href=w}})}return u}catch(c){return await B({onRedirect:(u,d)=>{globalThis.location.href=u},onRestartFlow:n,onValidationError:u=>u})(c)}},onSuccess(a){a&&"id"in a&&r.setQueryData(ve(a.id),a)}})}const Tt=l.createContext(void 0);function Ur({children:e,passwordForm:t}){const n=l.useMemo(()=>({passwordForm:t}),[t]);return s.jsx(Tt.Provider,{value:n,children:e})}function qe(){const e=l.useContext(Tt);if(e===void 0)throw new Error("useChooseMethodFormContext must be used within a ChooseMethodFormProvider");return e}function $e({children:e,provider:t}){const{mutate:n}=Q(),{data:o}=A(),i=l.useCallback(()=>{o&&n({method:"oidc",csrf_token:v(o),provider:t})},[o,n,t]),r=m.Root;return s.jsx(r,{type:"button",onClick:i,children:e})}function Ot({children:e}){return s.jsx($e,{provider:"apple",children:e})}function Nt({children:e}){return s.jsx($e,{provider:"facebook",children:e})}function Et({children:e}){return s.jsx($e,{provider:"google",children:e})}function Lr({children:e}){const{passwordForm:t}=qe(),n=m.Root;return s.jsx(t.Field,{name:"identifier",children:o=>s.jsx(n,{errors:C(o.state.meta.errorMap),name:o.name,type:"text",value:o.state.value,onChange:i=>o.handleChange(i.target.value),children:e})})}function Mt({children:e}){const{passwordForm:t}=qe(),n=m.Root;return s.jsx(t.Field,{name:"password",children:o=>s.jsx(n,{errors:C(o.state.meta.errorMap),name:o.name,type:"password",value:o.state.value,onChange:i=>o.handleChange(i.target.value),children:e})})}function Vr({children:e,onError:t,onLoginSuccess:n}){const{mutateAsync:o}=Q(),{data:i}=A(),{passwordForm:r}=qe(),a=l.useCallback(async f=>{if(!i)return;const g=await o({method:"passkey",csrf_token:v(i),passkey_login:f});if(g){if(pe(g)){n?.();return}N(g,r,t)}},[i,t,n,r,o]),c=l.useMemo(()=>K(T(i?.ui.nodes,"passkey_challenge")),[i?.ui.nodes]),u=l.useMemo(()=>z([G("passkey"),c?.value]),[c?.value]);y.useQuery({queryKey:u,queryFn:async({signal:f})=>{if(!c)throw new Error("No challenge provided");const g=await yn(c.value,f);return g?await a(g):!1},enabled:!!c,retry:!1});const d=l.useCallback(async()=>{if(!c)return;const f=await mn(c.value);f&&a(f)},[c,a]),w=m.Root;return s.jsx(w,{type:"button",onClick:d,children:e})}var ie=(e=>(e.Identifier="identifier",e.Password="password",e))(ie||{});function Pr({onError:e,onLoginSuccess:t}){const{mutateAsync:n}=Q(),{data:o}=A(),i=xt();return D.useForm({defaultValues:{[ie.Identifier]:i??"",[ie.Password]:""},onSubmit:async({value:r,formApi:a})=>{if(!o)return;const c=await n({csrf_token:v(o),method:"password",identifier:r[ie.Identifier],password:r[ie.Password]});if(c){if(pe(c)){t?.();return}N(c,a,e)}}})}function Wr({chooseMethodForm:e,isRefresh:t,onError:n,onLoginSuccess:o}){const{data:i}=A(),r=Pr({onError:n,onLoginSuccess:o}),a=I(r),c=xt(),u=l.useCallback(d=>s.jsx(Vr,{...d,onError:n}),[n]);return i?s.jsx(Ur,{passwordForm:r,children:s.jsx("form",{onSubmit:d=>{d.preventDefault(),r.handleSubmit()},children:t?s.jsx(e,{isRefresh:!0,Apple:_e(i.ui.nodes,"apple")?Ot:void 0,errors:a,Facebook:_e(i.ui.nodes,"facebook")?Nt:void 0,Google:_e(i.ui.nodes,"google")?Et:void 0,identifier:c,isSubmitting:r.state.isSubmitting,isValidating:r.state.isValidating,Passkey:T(i.ui.nodes,"passkey_login")&&u,passwordFields:T(i.ui.nodes,"password")&&{Password:Mt,Submit:E}}):s.jsx(e,{Apple:Ot,errors:a,Facebook:Nt,Google:Et,isSubmitting:r.state.isSubmitting,isValidating:r.state.isValidating,Passkey:u,passwordFields:{Identifier:Lr,Password:Mt,Submit:E}})})}):null}function Br({children:e}){const{mutate:t}=Q(),{data:n}=A(),o=l.useCallback(()=>{if(!n)return;const r=K(T(n.ui.nodes,"identifier"))?.value;t({method:"code",csrf_token:v(n),resend:"code",identifier:r})},[n,t]),i=m.Root;return s.jsx(i,{type:"button",onClick:o,children:e})}const Rt=l.createContext(void 0);function qr({children:e,codeForm:t}){const n=l.useMemo(()=>({codeForm:t}),[t]);return s.jsx(Rt.Provider,{value:n,children:e})}function $r(){const e=l.useContext(Rt);if(e===void 0)throw new Error("useSecondFactorEmailFormContext must be used within a SecondFactorEmailFormProvider");return e}function Kr({children:e}){const{codeForm:t}=$r(),n=m.Root;return s.jsx(t.Field,{name:"code",children:o=>s.jsx(n,{errors:C(o.state.meta.errorMap),name:o.name,type:"text",value:o.state.value,onChange:i=>o.handleChange(i.target.value),children:e})})}var Dt=(e=>(e.Code="code",e))(Dt||{});function zr({onError:e,onLoginSuccess:t}){const{mutateAsync:n}=Q(),{data:o}=A();return D.useForm({defaultValues:{[Dt.Code]:""},onSubmit:async({value:i,formApi:r})=>{if(!o)return;const a=K(T(o.ui.nodes,"identifier"))?.value,c=await n({csrf_token:v(o),method:"code",code:i.code,identifier:a});if(c){if(pe(c)){t?.();return}N(c,r,e)}}})}function Gr({secondFactorForm:e,onError:t,onLoginSuccess:n}){const o=zr({onError:t,onLoginSuccess:n}),i=I(o);return s.jsx(qr,{codeForm:o,children:s.jsx("form",{onSubmit:r=>{r.preventDefault(),o.handleSubmit()},children:s.jsx(e,{Code:Kr,errors:i,isSubmitting:o.state.isSubmitting,isValidating:o.state.isValidating,Resend:Br,Submit:E})})})}function Qr({children:e}){const{mutate:t}=Q(),{data:n}=A(),o=l.useCallback(()=>{if(!n)return;const r=K(T(n.ui.nodes,"address"))?.value;r&&t({method:"code",csrf_token:v(n),address:r})},[n,t]),i=m.Root;return s.jsx(i,{type:"button",onClick:o,children:e})}const It=l.createContext(void 0),Hr=({children:e,totpForm:t})=>{const n=l.useMemo(()=>({totpForm:t}),[t]);return s.jsx(It.Provider,{value:n,children:e})};function Xr(){const e=l.useContext(It);if(e===void 0)throw new Error("useSecondFactorFormContext must be used within a SecondFactorFormProvider");return e}function Yr({children:e}){const{totpForm:t}=Xr(),n=m.Root;return s.jsx(t.Field,{name:"totp_code",children:o=>s.jsx(n,{errors:C(o.state.meta.errorMap),name:o.name,type:"text",value:o.state.value,onChange:i=>o.handleChange(i.target.value),children:e})})}var Jt=(e=>(e.TotpCode="totp_code",e))(Jt||{});function Zr({onError:e,onLoginSuccess:t}){const{mutateAsync:n}=Q(),{data:o}=A();return D.useForm({defaultValues:{[Jt.TotpCode]:""},onSubmit:async({value:i,formApi:r})=>{if(!o)return;const a=await n({csrf_token:v(o),method:"totp",totp_code:i.totp_code});if(a){if(pe(a)){t?.();return}N(a,r,e)}}})}function jr({secondFactorForm:e,isRefresh:t,onError:n,onLoginSuccess:o}){const i=Zr({onError:n,onLoginSuccess:o}),r=I(i),{data:a}=A();return s.jsx(Hr,{totpForm:i,children:s.jsx("form",{onSubmit:c=>{c.preventDefault(),i.handleSubmit()},children:s.jsx(e,{Email:T(a?.ui.nodes,"address")&&Qr,errors:r,isRefresh:t,isSubmitting:i.state.isSubmitting,isValidating:i.state.isValidating,Submit:E,Totp:Yr})})})}function ea({loaderComponent:e,chooseMethodForm:t,secondFactorForm:n,secondFactorEmailForm:o,emailVerificationForm:i,initialFlowId:r,returnTo:a,onError:c,onLoginSuccess:u,onVerificationSuccess:d,onFlowRestart:w,onSessionAlreadyAvailable:f}){const{loginFlowId:g,setLoginFlowId:k}=Se(),{verificationFlowId:O}=J(),{sessionManager:h}=Ne(),{isAal2Required:S}=h.useIsAal2Required(),{mutate:$,error:H}=Ar({returnTo:a,aal:S?"aal2":void 0}),{data:R,error:je}=A();ee({initialFlowId:r,currentFlowId:g,error:je??void 0,onFlowRestart:w,createFlow:$,setFlowId:k,waitForSession:!0});const Oe=l.useMemo(()=>he(H)||he(je),[H,je]);l.useEffect(()=>{Oe&&f?.()},[Oe,f]);const se=l.useMemo(()=>{if(Oe)return"invalid";if(!R)return"loader";if(O)return"verifyEmail";if(R.state==="choose_method"){if(R.requested_aal==="aal1")return"chooseMethod";if(R.requested_aal==="aal2")return"secondFactor"}if(R.state==="sent_email")return"secondFactorEmail";throw new Error("Invalid login flow state")},[R,O,Oe]),ln=l.useMemo(()=>R?.refresh,[R]);return s.jsxs(s.Fragment,{children:[se==="loader"&&e&&s.jsx(e,{}),se==="chooseMethod"&&s.jsx(Wr,{chooseMethodForm:t,isRefresh:ln,onError:c,onLoginSuccess:u}),se==="secondFactor"&&s.jsx(jr,{isRefresh:ln,secondFactorForm:n,onError:c,onLoginSuccess:u}),se==="secondFactorEmail"&&s.jsx(Gr,{secondFactorForm:o,onError:c,onLoginSuccess:u}),se==="verifyEmail"&&s.jsx(Fe,{emailVerificationForm:i,onError:c,onVerificationSuccess:d})]})}function At(e){return s.jsx(me,{children:s.jsx(Jr,{children:s.jsx(ea,{...e})})})}const ta=Object.freeze(Object.defineProperty({__proto__:null,LoginFlow:At},Symbol.toStringTag,{value:"Module"})),Ut=()=>{const{kratosClient:e}=x(),{sessionManager:t}=Ne(),n=y.useQueryClient();return{logout:async({returnTo:i}={})=>{try{const r=await e.createBrowserLogoutFlow({returnTo:i},async({init:{headers:a}})=>({credentials:"include",headers:{...a,Accept:"application/json","Content-Type":"application/json"}}));return await e.updateLogoutFlow({token:r.logout_token},{headers:{Accept:"application/json","Content-Type":"application/json"}}),t.checkIfLoggedIn(),i&&(globalThis.location.href=i),n.removeQueries({queryKey:[We]}),{isSuccess:!0}}catch(r){return{isSuccess:!1,error:r}}}}},na=Object.freeze(Object.defineProperty({__proto__:null,useLogout:Ut},Symbol.toStringTag,{value:"Module"})),Lt=l.createContext(void 0);function oa({children:e,chooseMethodForm:t}){const n=l.useMemo(()=>({chooseMethodForm:t}),[t]);return s.jsx(Lt.Provider,{value:n,children:e})}function Ke(){const e=l.useContext(Lt);if(e===void 0)throw new Error("useChooseMethodFormContext must be used within a ChooseMethodFormProvider");return e}const ia=G("registration_flow"),ke=(e="no_id")=>z([ia,e]),Vt=l.createContext(void 0);function ra({children:e}){const[t,n]=l.useState(),[o,i]=l.useState(!1),[r,a]=l.useState(),c=l.useCallback(()=>{n(void 0),i(!1),a(void 0)},[]);return s.jsx(Vt.Provider,{value:{registrationFlowId:t,setRegistrationFlowId:n,traitsFormCompleted:o,setTraitsFormCompleted:i,traits:r,setTraits:a,resetFlow:c},children:e})}function q(){const e=l.useContext(Vt);if(e===void 0)throw new Error("useRegistrationFlowContext must be used within a RegistrationFlow");return e}function aa({returnTo:e}={}){const{kratosClient:t}=x(),{setRegistrationFlowId:n}=q(),o=y.useQueryClient();return y.useMutation({mutationFn:async()=>{try{return await t.createBrowserRegistrationFlow({returnTo:e},async({init:{headers:i}})=>({headers:{...i,Accept:"application/json"}}))}catch(i){throw await B({onRestartFlow:()=>{},onRedirect:()=>{},onValidationError:r=>r})(i)}},onSuccess(i){o.setQueryDefaults(ke(i.id),{staleTime:1/0}),o.setQueryData(ke(i.id),i),n(i.id)}})}function re(){const{kratosClient:e}=x(),{registrationFlowId:t}=q();return y.useQuery({queryKey:ke(t),queryFn:async({signal:n})=>{if(!t)throw new Error("No registration flow ID provided",{cause:P.NoFlowId});try{return await e.getRegistrationFlow({id:t},async({init:{headers:o}})=>({signal:n,headers:{...o,Accept:"application/json"}}))}catch(o){throw await oe({error:o})}},enabled:!!t,staleTime:1/0})}function be(){const{kratosClient:e}=x(),{resetFlow:t,registrationFlowId:n}=q(),{setVerificationFlowId:o,setVerifiableAddress:i}=J(),r=y.useQueryClient();return y.useMutation({mutationFn:async a=>{if(!n)throw new Error("Registration flow ID is not set");try{const u=await(await e.updateRegistrationFlowRaw({flow:n,updateRegistrationFlowBody:a},{headers:{Accept:"application/json","Content-Type":"application/json"}})).value();if(u&&"continue_with"in u){const d=u.continue_with?.find(w=>w.action==="show_verification_ui");d!==void 0?(o(d.flow.id),i(d.flow.verifiable_address)):Ve(u.continue_with,{onRedirect:(w,f)=>{globalThis.location.href=w}})}return u}catch(c){return await B({onRedirect:(u,d)=>{globalThis.location.href=u},onRestartFlow:t,onValidationError:u=>u})(c)}},onSuccess(a){a&&"id"in a&&r.setQueryData(ke(a.id),a)}})}function sa({children:e}){const{setTraitsFormCompleted:t}=q(),n=l.useCallback(()=>{t(!1)},[t]),o=m.Root;return s.jsx(o,{type:"button",onClick:n,children:e})}function ca({children:e,onError:t,onRegistrationSuccess:n}){const{traits:o}=q(),{mutateAsync:i}=be(),{data:r}=re(),{chooseMethodForm:a}=Ke(),c=l.useCallback(async f=>{if(!r)return;const g=await i({method:"passkey",csrf_token:v(r),traits:o??{},passkey_register:f});if(g){if(Le(g)){n?.();return}N(g,a,t)}},[t,n,r,o,a,i]),u=l.useMemo(()=>K(T(r?.ui.nodes,"passkey_create_data")),[r?.ui.nodes]),d=l.useCallback(async()=>{if(!u)return;const f=await Fn(u.value,void 0,o);f&&c(f)},[u,c,o]),w=m.Root;return s.jsx(w,{type:"button",onClick:d,children:e})}function la({children:e}){const{chooseMethodForm:t}=Ke(),n=m.Root;return s.jsx(t.Field,{name:"password",children:o=>s.jsx(n,{errors:C(o.state.meta.errorMap),name:o.name,type:"password",value:o.state.value,onChange:i=>o.handleChange(i.target.value),children:e})})}var U=(e=>(e.Password="password",e.PasswordConfirmation="password_confirmation",e))(U||{});const Pt=({value:e,fieldApi:t})=>{const n=t.form.getFieldMeta(U.PasswordConfirmation);if(n?.isDirty&&n?.isTouched)return Wt(e,t.form.getFieldValue(U.Password))},Wt=(e,t)=>{if(!e)return[ge(ne.FieldRequired)];if(e!==t)return[ge(ne.FieldMismatch)]};function ua({children:e}){const{chooseMethodForm:t}=Ke(),n=m.Root;return s.jsx(t.Field,{listeners:{onChange:({fieldApi:o})=>{o.form.setFieldMeta(U.PasswordConfirmation,i=>({...i,errorMap:{...i.errorMap,onSubmit:void 0}}))}},name:"password_confirmation",validators:{onChangeListenTo:[U.Password],onChange:Pt,onBlurListenTo:[U.PasswordConfirmation],onBlur:Pt,onSubmit:({value:o,fieldApi:i})=>Wt(o,i.form.getFieldValue(U.Password))},children:o=>s.jsx(n,{errors:C(o.state.meta.errorMap),name:o.name,type:"password",value:o.state.value,onBlur:o.handleBlur,onChange:i=>o.handleChange(i.target.value),children:e})})}function da({onError:e,onRegistrationSuccess:t}){const{setTraitsFormCompleted:n,traits:o}=q(),{mutateAsync:i}=be(),{data:r}=re();return D.useForm({defaultValues:{[U.Password]:"",[U.PasswordConfirmation]:""},onSubmit:async({value:a,formApi:c})=>{if(!r)return;const u=await i({csrf_token:v(r),method:"password",traits:o??{},password:a[U.Password]});if(u){if(Le(u)){t?.();return}u.state===ut.ChooseMethod&&n(!0),N(u,c,e)}}})}function fa({chooseMethodForm:e,onError:t,onRegistrationSuccess:n}){const o=da({onError:t,onRegistrationSuccess:n}),i=I(o);return s.jsx(oa,{chooseMethodForm:o,children:s.jsx("form",{onSubmit:r=>{r.preventDefault(),o.handleSubmit()},children:s.jsx(e,{errors:i,isSubmitting:o.state.isSubmitting,isValidating:o.state.isValidating,Passkey:ca,passwordFields:{Password:la,PasswordConfirmation:ua,Submit:E},ReturnToTraitsForm:sa})})})}function ze({children:e,provider:t}){const{mutate:n}=be(),{data:o}=re(),i=l.useCallback(()=>{o&&n({method:"oidc",csrf_token:v(o),provider:t})},[o,n,t]),r=m.Root;return s.jsx(r,{type:"button",onClick:i,children:e})}function pa({children:e}){return s.jsx(ze,{provider:"apple",children:e})}function wa({children:e}){return s.jsx(ze,{provider:"facebook",children:e})}function ha({children:e}){return s.jsx(ze,{provider:"google",children:e})}const Bt=l.createContext(void 0);function ga({children:e,traitsForm:t}){const n=l.useMemo(()=>({traitsForm:t}),[t]);return s.jsx(Bt.Provider,{value:n,children:e})}function qt(){const e=l.useContext(Bt);if(e===void 0)throw new Error("useTraitsFormContext must be used within a TraitsFormProvider");return e}function _a({trait:e,children:t}){const{traitsForm:n}=qt(),o=m.Root;return s.jsx(n.Field,{name:`${X}${e}`,children:i=>{if(typeof i.state.value!="string")throw new TypeError("TraitInput: value is not string");return s.jsx(o,{errors:C(i.state.meta.errorMap),name:i.name,type:"text",value:i.state.value,onChange:r=>i.handleChange(r.target.value),children:t})}})}function ya({trait:e,children:t}){const{traitsForm:n}=qt(),o=m.Root;return s.jsx(n.Field,{name:`${X}${e}`,children:i=>{if(typeof i.state.value!="boolean")throw new TypeError("TraitCheckbox: value is not boolean");return s.jsx(o,{checked:i.state.value,errors:C(i.state.meta.errorMap),name:i.name,type:"checkbox",onChange:r=>i.handleChange(r.target.checked),children:t})}})}function ma({traitsConfig:e,onError:t,onRegistrationSuccess:n}){const{setTraitsFormCompleted:o,setTraits:i,traits:r}=q(),{mutateAsync:a}=be(),{data:c}=re();return D.useForm({defaultValues:{traits:r??Object.fromEntries(Object.values(e).map(({trait:u,type:d})=>[u,d==="boolean"?!1:""]))},onSubmit:async({value:u,formApi:d})=>{if(!c)return;const w=await a({csrf_token:v(c),method:"profile",traits:u.traits??{}});if(w){if(Le(w)){n?.();return}w.state===ut.ChooseMethod&&w.ui.messages?.some(({id:f})=>f===1040009)&&(i(u.traits),o(!0)),N(w,d,t)}}})}function Fa({traitsConfig:e,traitsForm:t,onError:n,onRegistrationSuccess:o}){const i=ma({traitsConfig:e,onError:n,onRegistrationSuccess:o}),r=I(i),a=l.useMemo(()=>Object.fromEntries(Object.entries(e).map(([c,u])=>[c,u.type==="boolean"?({children:d})=>s.jsx(ya,{children:d,trait:u.trait}):({children:d})=>s.jsx(_a,{children:d,trait:u.trait})])),[e]);return s.jsx(ga,{traitsForm:i,children:s.jsx("form",{onSubmit:c=>{c.preventDefault(),i.handleSubmit()},children:s.jsx(t,{Apple:pa,errors:r,Facebook:wa,Google:ha,isSubmitting:i.state.isSubmitting,isValidating:i.state.isValidating,traitFields:{...a,Submit:E}})})})}function va({traitsConfig:e,traitsForm:t,chooseMethodForm:n,emailVerificationForm:o,initialFlowId:i,returnTo:r,onError:a,onRegistrationSuccess:c,onVerificationSuccess:u,onFlowRestart:d,onSessionAlreadyAvailable:w}){const{verificationFlowId:f}=J(),{registrationFlowId:g,setRegistrationFlowId:k,traitsFormCompleted:O}=q(),{error:h}=re(),{mutate:S,error:$}=aa({returnTo:r});ee({initialFlowId:i,currentFlowId:g,error:h??void 0,onFlowRestart:d,createFlow:S,setFlowId:k});const H=l.useMemo(()=>he(h)||he($),[h,$]);l.useEffect(()=>{H&&w?.()},[H,w]);const R=l.useMemo(()=>H?"invalid":f?"emailVerification":O?"credentials":"traits",[O,f,H]);return s.jsxs(s.Fragment,{children:[R==="traits"&&s.jsx(Fa,{traitsConfig:e,traitsForm:t,onError:a,onRegistrationSuccess:c}),R==="credentials"&&s.jsx(fa,{chooseMethodForm:n,onError:a,onRegistrationSuccess:c}),R==="emailVerification"&&s.jsx(Fe,{emailVerificationForm:o,onError:a,onVerificationSuccess:u})]})}function $t(e){return s.jsx(me,{children:s.jsx(ra,{children:s.jsx(va,{...e})})})}const Sa=Object.freeze(Object.defineProperty({__proto__:null,RegistrationFlow:$t},Symbol.toStringTag,{value:"Module"})),ka=G("settings_flow"),Ce=(e="no_id")=>z([ka,e]),Kt=l.createContext(void 0);function Ge({children:e}){const[t,n]=l.useState(),[o,i]=l.useState(!1),r=l.useCallback(()=>{n(void 0)},[]);return s.jsx(Kt.Provider,{value:{settingsFlowId:t,setSettingsFlowId:n,emailVerificationRequired:o,setEmailVerificationRequired:i,resetFlow:r},children:e})}function ae(){const e=l.useContext(Kt);if(e===void 0)throw new Error("useSettingsFlow must be used within a SettingsFlowProvider");return e}function ba(){const{kratosClient:e}=x(),{setSettingsFlowId:t}=ae(),n=y.useQueryClient();return y.useMutation({mutationFn:()=>e.createBrowserSettingsFlow({},async({init:{headers:o}})=>({headers:{...o,Accept:"application/json"}})),onSuccess(o){n.setQueryDefaults(Ce(o.id),{staleTime:1/0}),n.setQueryData(Ce(o.id),o),t(o.id)}})}function M(){const{kratosClient:e}=x(),{settingsFlowId:t}=ae();return y.useQuery({queryKey:Ce(t),queryFn:async({signal:n})=>{if(!t)throw new Error("No settings flow ID provided",{cause:P.NoFlowId});try{return await e.getSettingsFlow({id:t},async({init:{headers:o}})=>({signal:n,headers:{...o,Accept:"application/json"}}))}catch(o){throw await oe({error:o})}},enabled:!!t,staleTime:1/0})}function j(){const{kratosClient:e}=x(),{settingsFlowId:t,resetFlow:n,setEmailVerificationRequired:o}=ae(),i=y.useQueryClient();return y.useMutation({mutationFn:async r=>{if(!t)throw new Error("Settings flow ID is not set");try{const a=await e.updateSettingsFlow({flow:t,updateSettingsFlowBody:r},{headers:{Accept:"application/json","Content-Type":"application/json"}});return a&&"continue_with"in a&&(a.continue_with?.find(u=>u.action==="show_verification_ui")?o(!0):Ve(a.continue_with,{onRedirect:(u,d)=>{globalThis.location.href=u}})),a}catch(a){return await B({onRedirect:(c,u)=>{globalThis.location.href=c},onRestartFlow:n,onValidationError:c=>c})(a)}},onSuccess(r){r&&"id"in r&&i.setQueryData(Ce(r.id),r)}})}const zt=l.createContext(void 0);function Ca({children:e,newPasswordForm:t}){const n=l.useMemo(()=>({newPasswordForm:t}),[t]);return s.jsx(zt.Provider,{value:n,children:e})}function Gt(){const e=l.useContext(zt);if(e===void 0)throw new Error("useNewPasswordFormContext must be used within a NewPasswordFormProvider");return e}function xa({children:e}){const{newPasswordForm:t}=Gt(),n=m.Root;return s.jsx(t.Field,{name:"password",children:o=>s.jsx(n,{errors:C(o.state.meta.errorMap),name:o.name,type:"password",value:o.state.value,onChange:i=>o.handleChange(i.target.value),children:e})})}var L=(e=>(e.Password="password",e.PasswordConfirmation="password_confirmation",e))(L||{});const Qt=({value:e,fieldApi:t})=>{const n=t.form.getFieldMeta(L.PasswordConfirmation);if(n?.isDirty&&n?.isTouched)return Ht(e,t.form.getFieldValue(L.Password))},Ht=(e,t)=>{if(!e)return[ge(ne.FieldRequired)];if(e!==t)return[ge(ne.FieldMismatch)]};function Ta({children:e}){const{newPasswordForm:t}=Gt(),n=m.Root;return s.jsx(t.Field,{listeners:{onChange:({fieldApi:o})=>{o.form.setFieldMeta(L.PasswordConfirmation,i=>({...i,errorMap:{...i.errorMap,onSubmit:void 0}}))}},name:"password_confirmation",validators:{onChangeListenTo:[L.Password],onChange:Qt,onBlurListenTo:[L.PasswordConfirmation],onBlur:Qt,onSubmit:({value:o,fieldApi:i})=>Ht(o,i.form.getFieldValue(L.Password))},children:o=>s.jsx(n,{errors:C(o.state.meta.errorMap),name:o.name,type:"password",value:o.state.value,onBlur:o.handleBlur,onChange:i=>o.handleChange(i.target.value),children:e})})}function Oa({onError:e,onChangePasswordSuccess:t}){const{mutateAsync:n}=j(),{data:o}=M();return D.useForm({defaultValues:{[L.Password]:"",[L.PasswordConfirmation]:""},onSubmit:async({value:i,formApi:r})=>{if(!o)return;const a=await n({csrf_token:v(o),method:"password",password:i[L.Password]});if(a){if(a.state==="success"){t?.();return}N(a,r,e)}}})}function Na({newPasswordForm:e,emailVerificationRequired:t,onError:n,onChangePasswordSuccess:o}){const{data:i}=M(),r=Oa({onError:n,onChangePasswordSuccess:o}),a=I(r);return s.jsx(Ca,{newPasswordForm:r,children:s.jsx("form",{onSubmit:c=>{c.preventDefault(),r.handleSubmit()},children:s.jsx(e,{emailVerificationRequired:t,errors:a,isLoading:!i,isSubmitting:r.state.isSubmitting,isValidating:r.state.isValidating,Password:xa,PasswordConfirmation:Ta,Submit:E})})})}function Ea({children:e,provider:t,type:n}){const{mutate:o}=j(),{data:i}=M(),r=l.useCallback(()=>{i&&o({method:"oidc",[n]:t})},[i,o,n,t]),a=m.Root;return s.jsx(a,{oidcType:n,type:"button",onClick:r,children:e})}const Ma=(e,t)=>{const n=_e(t,e);if(n){if(n.attributes.name==="link")return"link";if(n.attributes.name==="unlink")return"unlink";throw new Error(`Unknown OIDC provider type for ${e}: ${n.attributes.name}`)}};function Ra({oidcForm:e}){const{data:t}=M(),n=l.useMemo(()=>t?yt.reduce((o,i)=>{const r=dn.toUpperFirst(i),a=Ma(i,t.ui.nodes);return a&&(o[r]=({children:c})=>s.jsx(Ea,{provider:i,type:a,children:c})),o},{}):{},[t]);return s.jsx(e,{...n,isLoading:!t})}const Da=()=>{const{mutateAsync:e,isPending:t}=j(),{data:n}=M(),o=l.useCallback(async c=>{if(!t){if(!n)throw new Error("Settings flow is not available");await e({method:"passkey",csrf_token:v(n),passkey_remove:c})}},[t,n,e]),i=l.useCallback(async c=>{n&&await e({method:"passkey",csrf_token:v(n),passkey_settings_register:c})},[n,e]),r=l.useMemo(()=>K(T(n?.ui.nodes,"passkey_create_data")),[n?.ui.nodes]),a=l.useCallback(async()=>{if(t||!r)return;const c=await vn(r.value);c&&await i(c)},[t,r,i]);return{isPending:t,removePasskey:o,addNewPasskey:a}};function Ia({passkeysForm:e}){const{data:t}=M(),{removePasskey:n,isPending:o,addNewPasskey:i}=Da(),r=t?Fr(t.ui.nodes,"passkey_remove").filter(Sr).map(({meta:a,attributes:c})=>({addedAt:a.label.context.added_at,addedAtUnix:a.label.context.added_at_unix,id:String(c.value),name:a.label.context.display_name,removePasskey:()=>n(c.value)})):[];return s.jsx(e,{addNewPasskey:i,existingPasskeys:r,isLoading:!t,isPending:o})}const Xt=l.createContext(void 0);function Ja({children:e,totpForm:t}){const n=l.useMemo(()=>({totpForm:t}),[t]);return s.jsx(Xt.Provider,{value:n,children:e})}function Aa(){const e=l.useContext(Xt);if(e===void 0)throw new Error("useTotpFormContext must be used within a TotpFormProvider");return e}function Ua({children:e}){const{totpForm:t}=Aa(),n=m.Root;return s.jsx(t.Field,{name:"code",children:o=>s.jsx(n,{errors:C(o.state.meta.errorMap),name:o.name,type:"text",value:o.state.value,onChange:i=>o.handleChange(i.target.value),children:e})})}function La({children:e}){const{mutateAsync:t}=j(),{data:n}=M(),o=l.useCallback(async()=>{n&&await t({method:"totp",csrf_token:v(n),totp_unlink:!0})},[n,t]),i=m.Root;return s.jsx(i,{type:"button",onClick:o,children:e})}var Qe=(e=>(e.Code="code",e))(Qe||{});function Va({onError:e,onTotpSuccess:t}){const{mutateAsync:n}=j(),{data:o}=M();return D.useForm({defaultValues:{[Qe.Code]:""},onSubmit:async({value:i,formApi:r})=>{if(!o)return;const a=await n({csrf_token:v(o),method:"totp",totp_code:i[Qe.Code]});if(a){if(a.state==="success"){t?.();return}N(a,r,e)}}})}function Pa({totpForm:e,emailVerificationRequired:t,onError:n,onTotpSuccess:o}){const i=Va({onError:n,onTotpSuccess:o}),r=I(i),{data:a}=M(),c=l.useMemo(()=>{if(!a)return;const f=T(a.ui.nodes,"totp_qr");if(!(!f||f.attributes.node_type!==lt.Img))return f.attributes.src},[a]),u=l.useMemo(()=>{if(!a)return;const f=T(a.ui.nodes,"totp_secret_key");if(!f||f.attributes.node_type!==lt.Text)return;const{text:g}=f.attributes;return g.context&&"secret"in g.context&&typeof g.context.secret=="string"?g.context.secret:g.text},[a]),d=l.useMemo(()=>{if(a)return!!T(a.ui.nodes,"totp_unlink")},[a]),w=!a||d===void 0;return s.jsx(Ja,{totpForm:i,children:s.jsx("form",{onSubmit:f=>{f.preventDefault(),i.handleSubmit()},children:w?s.jsx(e,{isLoading:!0}):d?s.jsx(e,{isTotpLinked:!0,emailVerificationRequired:t,Unlink:La}):s.jsx(e,{Code:Ua,emailVerificationRequired:t,errors:r,isSubmitting:i.state.isSubmitting,isValidating:i.state.isValidating,Submit:E,totpQrImageSrc:c,totpSecretKey:u})})})}const Yt=l.createContext(void 0);function Wa({children:e,traitsForm:t}){const n=l.useMemo(()=>({traitsForm:t}),[t]);return s.jsx(Yt.Provider,{value:n,children:e})}function Zt(){const e=l.useContext(Yt);if(e===void 0)throw new Error("useTraitsFormContext must be used within a TraitsFormProvider");return e}function Ba({trait:e,children:t}){const{traitsForm:n}=Zt(),o=m.Root;return s.jsx(n.Field,{name:`${X}${e}`,children:i=>{if(typeof i.state.value!="string")throw new TypeError("TraitInput: value is not string");return s.jsx(o,{errors:C(i.state.meta.errorMap),name:i.name,type:"text",value:i.state.value,onChange:r=>i.handleChange(r.target.value),children:t})}})}function qa({trait:e,children:t}){const{traitsForm:n}=Zt(),o=m.Root;return s.jsx(n.Field,{name:`${X}${e}`,children:i=>{if(typeof i.state.value!="boolean")throw new TypeError("TraitCheckbox: value is not boolean");return s.jsx(o,{checked:i.state.value,errors:C(i.state.meta.errorMap),name:i.name,type:"checkbox",onChange:r=>i.handleChange(r.target.checked),children:t})}})}function $a({traitsConfig:e,onError:t,onChangeTraitsSuccess:n}){const{mutateAsync:o}=j(),{data:i}=M();return D.useForm({defaultValues:{traits:i?.identity.traits??Object.fromEntries(Object.values(e).map(({trait:r,type:a})=>[r,a==="boolean"?!1:""]))},onSubmit:async({value:r,formApi:a})=>{if(!i)return;const c=await o({csrf_token:v(i),method:"profile",traits:r.traits??{}});if(c){if(c.state===Po.Success){n?.();return}N(c,a,t)}}})}function Ka({traitsConfig:e,traitsForm:t,emailVerificationRequired:n,onError:o,onChangeTraitsSuccess:i}){const{data:r}=M(),a=$a({traitsConfig:e,onError:o,onChangeTraitsSuccess:i}),c=I(a),u=l.useMemo(()=>Object.fromEntries(Object.entries(e).map(([d,w])=>[d,w.type==="boolean"?({children:f})=>s.jsx(qa,{children:f,trait:w.trait}):({children:f})=>s.jsx(Ba,{children:f,trait:w.trait})])),[e]);return s.jsx(Wa,{traitsForm:a,children:s.jsx("form",{onSubmit:d=>{d.preventDefault(),a.handleSubmit()},children:s.jsx(t,{emailVerificationRequired:n,errors:c,isLoading:!r,isSubmitting:a.state.isSubmitting,isValidating:a.state.isValidating,Submit:E,...u})})})}function jt(e){return s.jsx(Ge,{children:s.jsx(He,{...e})})}function He({newPasswordForm:e,traitsForm:t,passkeysForm:n,totpForm:o,oidcForm:i,traitsConfig:r,settingsForm:a,initialFlowId:c,onError:u,onChangePasswordSuccess:d,onChangeTraitsSuccess:w,onFlowRestart:f}){const{settingsFlowId:g,setSettingsFlowId:k,emailVerificationRequired:O}=ae(),{mutate:h}=ba(),{data:S,error:$}=M();return ee({initialFlowId:c,currentFlowId:g,error:$,onFlowRestart:f,createFlow:h,setFlowId:k}),s.jsx(a,{emailVerificationRequired:O,isLoading:!S,newPasswordForm:e&&s.jsx(Na,{emailVerificationRequired:O,newPasswordForm:e,onChangePasswordSuccess:d,onError:u}),oidcForm:i&&s.jsx(Ra,{oidcForm:i}),passkeysForm:n&&s.jsx(Ia,{passkeysForm:n}),totpForm:o&&s.jsx(Pa,{emailVerificationRequired:O,totpForm:o,onError:u,onTotpSuccess:w}),traitsForm:r&&t&&s.jsx(Ka,{emailVerificationRequired:O,traitsConfig:r,traitsForm:t,onChangeTraitsSuccess:w,onError:u})})}const za=Object.freeze(Object.defineProperty({__proto__:null,SettingsFlow:jt,SettingsFlowProvider:Ge,SettingsFlowWrapper:He,useSettingsFlowContext:ae},Symbol.toStringTag,{value:"Module"})),en=l.createContext(void 0);function Ga({children:e,codeForm:t}){const n=l.useMemo(()=>({codeForm:t}),[t]);return s.jsx(en.Provider,{value:n,children:e})}function Qa(){const e=l.useContext(en);if(e===void 0)throw new Error("useCodeFormContext must be used within a CodeFormProvider");return e}function Ha({children:e}){const{codeForm:t}=Qa(),n=m.Root;return s.jsx(t.Field,{name:"code",children:o=>s.jsx(n,{errors:C(o.state.meta.errorMap),name:o.name,type:"text",value:o.state.value,onChange:i=>o.handleChange(i.target.value),children:e})})}const Xa=G("recovery_flow"),xe=(e="no_id")=>z([Xa,e]),tn=l.createContext(void 0);function Ya({children:e}){const[t,n]=l.useState(),o=l.useCallback(()=>{n(void 0)},[]);return s.jsx(tn.Provider,{value:{recoveryFlowId:t,setRecoveryFlowId:n,resetFlow:o},children:e})}function Te(){const e=l.useContext(tn);if(e===void 0)throw new Error("useRecoveryFlowContext must be used within a RecoveryFlow");return e}function Za({returnTo:e}={}){const{kratosClient:t}=x(),{setRecoveryFlowId:n}=Te(),o=y.useQueryClient();return y.useMutation({mutationFn:()=>t.createBrowserRecoveryFlow({returnTo:e},async({init:{headers:i}})=>({headers:{...i,Accept:"application/json"}})),onSuccess(i){o.setQueryDefaults(xe(i.id),{staleTime:1/0}),o.setQueryData(xe(i.id),i),n(i.id)}})}function Xe(){const{kratosClient:e}=x(),{recoveryFlowId:t}=Te();return y.useQuery({queryKey:xe(t),queryFn:async({signal:n})=>{if(!t)throw new Error("No recovery flow ID provided",{cause:P.NoFlowId});try{return await e.getRecoveryFlow({id:t},async({init:{headers:o}})=>({signal:n,headers:{...o,Accept:"application/json"}}))}catch(o){throw await oe({error:o})}},enabled:!!t,staleTime:1/0})}function nn(){const{kratosClient:e}=x(),{resetFlow:t,recoveryFlowId:n}=Te(),o=y.useQueryClient();return y.useMutation({mutationFn:async i=>{if(!n)throw new Error("Recovery flow ID is not set");try{return await e.updateRecoveryFlow({flow:n,updateRecoveryFlowBody:i},{headers:{Accept:"application/json","Content-Type":"application/json"}})}catch(r){return await B({onRedirect:(a,c)=>{globalThis.location.href=a},onRestartFlow:t,onValidationError:a=>a})(r)}},onSuccess(i){i&&"id"in i&&o.setQueryData(xe(i.id),i)}})}var Ye=(e=>(e.Code="code",e))(Ye||{});function ja({onError:e}){const{mutateAsync:t}=nn(),{data:n}=Xe();return D.useForm({defaultValues:{[Ye.Code]:""},onSubmit:async({value:o,formApi:i})=>{if(!n)return;const r=await t({csrf_token:v(n),method:"code",code:o[Ye.Code]});r&&N(r,i,e)}})}function es({codeForm:e,onError:t}){const n=ja({onError:t}),o=I(n);return s.jsx(Ga,{codeForm:n,children:s.jsx("form",{onSubmit:i=>{i.preventDefault(),n.handleSubmit()},children:s.jsx(e,{Code:Ha,errors:o,isSubmitting:n.state.isSubmitting,isValidating:n.state.isValidating,Submit:E})})})}const on=l.createContext(void 0);function ts({children:e,emailForm:t}){const n=l.useMemo(()=>({emailForm:t}),[t]);return s.jsx(on.Provider,{value:n,children:e})}function ns(){const e=l.useContext(on);if(e===void 0)throw new Error("useEmailFormContext must be used within a EmailFormProvider");return e}function os({children:e}){const{emailForm:t}=ns(),n=m.Root;return s.jsx(t.Field,{name:"email",children:o=>s.jsx(n,{errors:C(o.state.meta.errorMap),name:o.name,type:"text",value:o.state.value,onChange:i=>o.handleChange(i.target.value),children:e})})}var Ze=(e=>(e.Email="email",e))(Ze||{});function is({onError:e}){const{mutateAsync:t}=nn(),{data:n}=Xe();return D.useForm({defaultValues:{[Ze.Email]:""},onSubmit:async({value:o,formApi:i})=>{if(!n)return;const r=await t({csrf_token:v(n),method:"code",email:o[Ze.Email]});r&&N(r,i,e)}})}function rs({emailForm:e,onError:t}){const n=is({onError:t}),o=I(n);return s.jsx(ts,{emailForm:n,children:s.jsx("form",{onSubmit:i=>{i.preventDefault(),n.handleSubmit()},children:s.jsx(e,{Email:os,errors:o,isSubmitting:n.state.isSubmitting,isValidating:n.state.isValidating,Submit:E})})})}function as({emailForm:e,codeForm:t,newPasswordForm:n,initialFlowId:o,returnTo:i,onError:r,onRecoverySuccess:a,onFlowRestart:c}){const{recoveryFlowId:u,setRecoveryFlowId:d}=Te(),{mutate:w}=Za({returnTo:i}),{data:f,error:g}=Xe(),k=l.useMemo(()=>f?.continue_with?.find(h=>h.action==="show_settings_ui")?.flow.id,[f]);ee({initialFlowId:o,currentFlowId:u,error:g,onFlowRestart:c,createFlow:w,setFlowId:d});const O=l.useMemo(()=>k?"newPassword":f?.state==="sent_email"?"code":"email",[f?.state,k]);return s.jsxs(s.Fragment,{children:[O==="email"&&s.jsx(rs,{emailForm:e,onError:r}),O==="code"&&s.jsx(es,{codeForm:t,onError:r}),O==="newPassword"&&k&&s.jsx(He,{initialFlowId:k,newPasswordForm:n,settingsForm:({newPasswordForm:h})=>h,onChangePasswordSuccess:a,onError:r})]})}function rn(e){return s.jsx(Ge,{children:s.jsx(Ya,{children:s.jsx(as,{...e})})})}const ss=Object.freeze(Object.defineProperty({__proto__:null,RecoveryFlow:rn},Symbol.toStringTag,{value:"Module"})),an=z([G("session_manager"),"session"]),sn=e=>({queryKey:an,queryFn:async()=>{try{return await e.toSession()}catch(t){if(t instanceof Y){if(t.response.status===401)return null;const n=await t.response.json();if(V(n))throw new Error("Kratos error occurred while fetching session",{cause:n})}throw new Error("Unexpected error while fetching session")}},staleTime:1/0,retry:!1});class cn{queryClient;api;getSession=async()=>{try{return await this.queryClient.fetchQuery(sn(this.api))??void 0}catch{return}};getIdentity=async()=>(await this.getSession())?.identity;getUserId=async()=>(await this.getIdentity())?.id;isLoggedIn=async()=>(await this.getSession())?.active??!1;useSession=()=>{const{data:t,isLoading:n,error:o}=y.useQuery({...sn(this.api),retryOnMount:!1});return{session:t??void 0,isLoading:n,error:o}};useIdentity=()=>{const{session:t,...n}=this.useSession();return{identity:t?.identity,...n}};useUserId=()=>{const{identity:t,...n}=this.useIdentity();return{userId:t?.id,...n}};useIsLoggedIn=()=>{const{session:t,isLoading:n,error:o}=this.useSession();return{isLoggedIn:t?.active??(n?void 0:!1),isLoading:n,error:o}};useIsAal2Required=()=>{const t=this.useSession();return{isAal2Required:t.error?.cause?V(t.error.cause)&&cr(t.error.cause):void 0,isLoading:t.isLoading}};checkIfLoggedIn=async()=>await this.queryClient.refetchQueries({queryKey:an,exact:!0});constructor({queryClient:t,api:n}){this.api=n,this.queryClient=t}}function cs({queryClient:e,basePath:t,traits:n={},SessionManager:o=cn}){const i=new rr(new rt({basePath:t,credentials:"include"})),r=new o({queryClient:e,api:i});return{flows:{useLogout:Ut,LoginFlow:At,RecoveryFlow:rn,RegistrationFlow:d=>s.jsx($t,{traitsConfig:n,...d}),SettingsFlow:d=>s.jsx(jt,{traitsConfig:n,...d}),VerificationFlow:bt},providers:{KratosProviders:({children:d})=>s.jsx(br,{api:i,children:s.jsx(pn,{sessionManager:r,children:d})})},session:{sessionManager:r}}}b.BaseSessionManager=cn,b.loginFlow=ta,b.logoutFlow=na,b.mkKratos=cs,b.recoveryFlow=ss,b.registrationFlow=Sa,b.settingsFlow=za,b.verificationFlow=Dr,Object.defineProperty(b,Symbol.toStringTag,{value:"Module"})}));