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AhF,CAAK,EAAK,MAAMkB,EACtB,KAAK,MACL,SACA,GAAG,KAAK,GAAG,aAAaZ,EAAO,SAAS,GACxC,CACE,QAAS,KAAK,QACd,IAAKM,EAAQ,aACb,cAAe,GAChB,EAEH,OAAIZ,EACK,KAAK,cAAc,CAAE,KAAM,KAAM,MAAAA,CAAK,CAAE,EAE1C,KAAK,cAAc,CAAE,KAAM,KAAM,MAAO,IAAI,CAAE,CACvD,CAAC,CACH,OAASA,EAAO,CACd,GAAIc,EAAYd,CAAK,EACnB,OAAO,KAAK,cAAc,CAAE,KAAM,KAAM,MAAAA,CAAK,CAAE,EAEjD,MAAMA,CACR,CACF,GA52NelB,GAAA,eAAyC,CAAA,SADrCA,GC/OrB,IAAMkP,GAAeC,EAErBC,GAAeF,GCFf,IAAMG,GAAaC,GAEnBC,GAAeF","names":["version","AUTO_REFRESH_TICK_DURATION_MS","AUTO_REFRESH_TICK_THRESHOLD","EXPIRY_MARGIN_MS","REFRESH_FAILURE_COOLDOWN_MS","GOTRUE_URL","STORAGE_KEY","DEFAULT_HEADERS","version","API_VERSION_HEADER_NAME","API_VERSIONS","BASE64URL_REGEX","PKCE_FLOW_ID_PARAM","PKCE_MAX_CONCURRENT_FLOWS","JWKS_TTL","AuthError","message","status","code","isAuthError","error","AuthApiError","isAuthApiError","AuthUnknownError","originalError","CustomAuthError","name","AuthSessionMissingError","isAuthSessionMissingError","AuthInvalidTokenResponseError","AuthInvalidCredentialsError","AuthImplicitGrantRedirectError","details","isAuthImplicitGrantRedirectError","AuthPKCEGrantCodeExchangeError","AuthPKCECodeVerifierMissingError","isAuthPKCECodeVerifierMissingError","AuthRetryableFetchError","isAuthRetryableFetchError","AuthRefreshDiscardedError","isAuthRefreshDiscardedError","AuthWeakPasswordError","reasons","isAuthWeakPasswordError","AuthInvalidJwtError","TO_BASE64URL","IGNORE_BASE64URL","FROM_BASE64URL","charMap","i","byteToBase64URL","byte","state","emit","pos","byteFromBase64URL","charCode","bits","stringFromBase64URL","str","conv","utf8Emit","codepoint","utf8State","b64State","byteEmit","byte","stringFromUTF8","i","byteFromBase64URL","codepointToUTF8","emit","stringToUTF8","highSurrogate","state","leadingBit","base64UrlToUint8Array","result","onByte","stringToUint8Array","bytesToBase64URL","bytes","onChar","char","byteToBase64URL","expiresAt","expiresIn","generateCallbackId","isBrowser","localStorageWriteTests","supportsLocalStorage","randomKey","parseParametersFromURL","href","result","url","value","key","resolveFetch","customFetch","args","looksLikeFetchResponse","maybeResponse","setItemAsync","storage","data","getItemAsync","removeItemAsync","Deferred","_Deferred","res","rej","decodeJWT","token","parts","AuthInvalidJwtError","i","BASE64URL_REGEX","stringFromBase64URL","base64UrlToUint8Array","sleep","time","accept","retryable","fn","isRetryable","reject","attempt","e","dec2hex","dec","generatePKCEVerifier","array","charSet","charSetLen","verifier","sha256","randomString","encodedData","hash","bytes","c","generatePKCEChallenge","hashed","PKCE_FLOW_ID_PATTERN","validatePKCEFlowId","flowId","generatePKCEFlowId","pkceVerifierSlotKey","storageKey","pkceFlowIndexKey","getPKCEFlowIndex","index","id","storePKCEVerifier","onEvictFlow","PKCE_MAX_CONCURRENT_FLOWS","evicted","retrievePKCEVerifier","removePKCEVerifier","legacyKey","slotKey","slotValue","remaining","removeAllPKCEVerifiers","appendFlowIdToRedirectTo","redirectTo","hashIndex","base","fragment","queryIndex","path","pair","PKCE_FLOW_ID_PARAM","separator","getCodeChallengeAndMethod","isPasswordRecovery","codeVerifier","storedCodeVerifier","codeChallenge","API_VERSION_REGEX","parseResponseAPIVersion","response","apiVersion","API_VERSION_HEADER_NAME","validateExp","exp","timeNow","getAlgorithm","alg","UUID_REGEX","validateUUID","str","assertRecoveryCodesExperimentalEnabled","experimental","userNotAvailableProxy","proxyTarget","target","prop","sProp","_target","insecureUserWarningProxy","user","suppressWarningRef","receiver","deepClone","obj","_getErrorMessage","err","NETWORK_ERROR_CODES","handleError","error","looksLikeFetchResponse","AuthRetryableFetchError","data","e","AuthUnknownError","errorCode","responseAPIVersion","parseResponseAPIVersion","API_VERSIONS","AuthWeakPasswordError","_a","AuthSessionMissingError","a","i","AuthApiError","_getRequestParams","method","options","parameters","body","params","_request","fetcher","url","headers","API_VERSION_HEADER_NAME","qs","queryString","_handleRequest","requestParams","result","_sessionResponse","session","hasSession","expiresAt","user","_sessionResponsePassword","response","_userResponse","_ssoResponse","_generateLinkResponse","action_link","email_otp","hashed_token","redirect_to","verification_type","rest","__rest","properties","_noResolveJsonResponse","SIGN_OUT_SCOPES","GoTrueAdminApi","url","headers","fetch","experimental","resolveFetch","jwt","scope","SIGN_OUT_SCOPES","_request","error","isAuthError","email","options","_userResponse","params","rest","__rest","body","_generateLinkResponse","attributes","pagination","response","_b","_a","_d","_c","_noResolveJsonResponse","users","total","_e","links","_g","_f","link","page","rel","uid","validateUUID","id","shouldSoftDelete","data","factors","clients","client","clientId","query","provider","identifier","memoryLocalStorageAdapter","store","key","value","internals","supportsLocalStorage","LockAcquireTimeoutError","message","NavigatorLockAcquireTimeoutError","ProcessLockAcquireTimeoutError","navigatorLock","name","acquireTimeout","fn","abortController","acquireTimeoutTimer","lock","result","e","PROCESS_LOCKS","processLock","previousOperation","_a","previousOperationHandled","currentOperation","timeoutId","timeoutPromise","_","reject","x","polyfillGlobalThis","getAddress","address","fromHex","hex","toHex","value","bytes","byte","createSiweMessage","parameters","chainId","domain","expirationTime","issuedAt","nonce","notBefore","requestId","resources","scheme","uri","version","_a","origin","statement","prefix","suffix","content","resource","WebAuthnError","message","code","cause","name","_a","WebAuthnUnknownError","originalError","identifyRegistrationError","error","options","publicKey","WebAuthnError","_a","_b","_c","param","effectiveDomain","isValidDomain","identifyAuthenticationError","WebAuthnAbortService","abortError","newController","webAuthnAbortService","deserializeCredentialCreationOptions","options","challengeStr","userOpts","excludeCredentials","restOptions","__rest","challenge","base64UrlToUint8Array","user","result","i","cred","deserializeCredentialRequestOptions","allowCredentials","serializeCredentialCreationResponse","credential","credentialWithAttachment","bytesToBase64URL","_a","serializeCredentialRequestResponse","clientExtensionResults","assertionResponse","isValidDomain","hostname","browserSupportsWebAuthn","isBrowser","_b","createCredential","response","WebAuthnUnknownError","err","identifyRegistrationError","getCredential","identifyAuthenticationError","DEFAULT_CREATION_OPTIONS","DEFAULT_REQUEST_OPTIONS","deepMerge","sources","isObject","val","isArrayBufferLike","source","key","value","existing","mergeCredentialCreationOptions","baseOptions","overrides","mergeCredentialRequestOptions","WebAuthnApi","client","params","factorId","webauthn","friendlyName","signal","challengeResponse","challengeError","abortSignal","nameToUse","userData","fallbackName","data","error","isAuthError","AuthUnknownError","challengeId","rpId","rpOrigins","AuthError","factor","enrollError","factors","v","polyfillGlobalThis","DEFAULT_OPTIONS","GOTRUE_URL","STORAGE_KEY","DEFAULT_HEADERS","GLOBAL_JWKS","deprecatedLockWarned","GoTrueClient","_GoTrueClient","_b","_a","value","options","settings","DEFAULT_OPTIONS","isBrowser","message","GoTrueAdminApi","resolveFetch","WebAuthnApi","supportsLocalStorage","memoryLocalStorageAdapter","e","_c","event","error","result","version","args","queue","n","params","callbackUrlType","parseParametersFromURL","data","isAuthImplicitGrantRedirectError","errorCode","session","redirectType","isAuthError","AuthUnknownError","credentials","res","_request","_sessionResponse","user","flowId","email","password","codeChallenge","codeChallengeMethod","phone","AuthInvalidCredentialsError","removePKCEVerifier","_sessionResponsePassword","invalidTokenError","AuthInvalidTokenResponseError","_d","authCode","chain","signature","wallet","statement","resolvedWallet","windowAny","url","accounts","accs","address","getAddress","chainId","chainIdHex","fromHex","siweMessage","_f","_g","_h","_j","_k","createSiweMessage","toHex","_l","_m","output","outputToProcess","resource","maybeSignature","bytesToBase64URL","_o","hasExplicitFlowId","requestedFlowId","validatePKCEFlowId","PKCE_FLOW_ID_PARAM","storageItem","retrievePKCEVerifier","codeVerifier","AuthPKCECodeVerifierMissingError","provider","token","access_token","nonce","redirectTo","captchaToken","_ssoResponse","sessionError","AuthSessionMissingError","endpoint","type","acquireTimeout","fn","last","waitOn","currentSession","maybeSession","getItemAsync","hasExpired","EXPIRY_MARGIN_MS","stored","maybeUser","userNotAvailableProxy","suppressWarningRef","insecureUserWarningProxy","jwt","_userResponse","isAuthSessionMissingError","attributes","sessionData","userError","timeNow","expiresAt","payload","decodeJWT","refreshedSession","AuthImplicitGrantRedirectError","AuthPKCEGrantCodeExchangeError","provider_token","provider_refresh_token","refresh_token","expires_in","expires_at","token_type","expiresIn","actuallyExpiresIn","AUTO_REFRESH_TICK_DURATION_MS","issuedAt","pkceVerifierSlotKey","scope","removeCurrentSession","isAuthRetryableFetchError","accessToken","removeError","finish","thrown","isAuthApiError","callback","id","generateCallbackId","subscription","err","isAuthRefreshDiscardedError","urlFlowId","identity","refreshToken","debugName","startedAt","retryable","attempt","sleep","nextBackOffInterval","setItemAsync","separateUser","removeItemAsync","expiresWithMargin","getUserError","Deferred","storedAtStart","storedAfter","discarded","AuthRefreshDiscardedError","epochBeforeSave","storedNow","REFRESH_FAILURE_COOLDOWN_MS","broadcast","errors","promises","x","i","sessionToProcess","userIsProxy","mainSessionData","clonedMainSessionData","deepClone","clonedSession","removeAllPKCEVerifiers","ticker","timeout","now","expiresInTicks","AUTO_REFRESH_TICK_THRESHOLD","LockAcquireTimeoutError","calledFromInitialize","methodName","urlParams","flowParams","query","appendFlowIdToRedirectTo","isPasswordRecovery","getCodeChallengeAndMethod","evictedFlowId","body","run","serializeCredentialCreationResponse","serializeCredentialRequestResponse","response","deserializeCredentialCreationOptions","deserializeCredentialRequestOptions","challengeData","challengeError","factor","currentLevel","nextLevel","currentAuthenticationMethods","assertRecoveryCodesExperimentalEnabled","authorizationId","kid","jwks","jwk","key","JWKS_TTL","header","rawHeader","rawPayload","validateExp","AuthInvalidJwtError","signingKey","algorithm","getAlgorithm","publicKey","stringToUint8Array","browserSupportsWebAuthn","optionsError","publicKeyOptions","signal","webAuthnAbortService","credential","credentialError","getCredential","serialized","createCredential","AuthAdminApi","GoTrueAdminApi","AuthAdminApi_default","AuthClient","GoTrueClient_default","AuthClient_default"],"sources":["../esm/npm/@supabase/auth-js@2.119.0/node_modules/@supabase/auth-js/src/lib/version.ts","../esm/npm/@supabase/auth-js@2.119.0/node_modules/@supabase/auth-js/src/lib/constants.ts","../esm/npm/@supabase/auth-js@2.119.0/node_modules/@supabase/auth-js/src/lib/errors.ts","../esm/npm/@supabase/auth-js@2.119.0/node_modules/@supabase/auth-js/src/lib/base64url.ts","../esm/npm/@supabase/auth-js@2.119.0/node_modules/@supabase/auth-js/src/lib/helpers.ts","../esm/npm/@supabase/auth-js@2.119.0/node_modules/@supabase/auth-js/src/lib/fetch.ts","../esm/npm/@supabase/auth-js@2.119.0/node_modules/@supabase/auth-js/src/lib/types.ts","../esm/npm/@supabase/auth-js@2.119.0/node_modules/@supabase/auth-js/src/GoTrueAdminApi.ts","../esm/npm/@supabase/auth-js@2.119.0/node_modules/@supabase/auth-js/src/lib/local-storage.ts","../esm/npm/@supabase/auth-js@2.119.0/node_modules/@supabase/auth-js/src/lib/locks.ts","../esm/npm/@supabase/auth-js@2.119.0/node_modules/@supabase/auth-js/src/lib/polyfills.ts","../esm/npm/@supabase/auth-js@2.119.0/node_modules/@supabase/auth-js/src/lib/web3/ethereum.ts","../esm/npm/@supabase/auth-js@2.119.0/node_modules/@supabase/auth-js/src/lib/webauthn.errors.ts","../esm/npm/@supabase/auth-js@2.119.0/node_modules/@supabase/auth-js/src/lib/webauthn.ts","../esm/npm/@supabase/auth-js@2.119.0/node_modules/@supabase/auth-js/src/GoTrueClient.ts","../esm/npm/@supabase/auth-js@2.119.0/node_modules/@supabase/auth-js/src/AuthAdminApi.ts","../esm/npm/@supabase/auth-js@2.119.0/node_modules/@supabase/auth-js/src/AuthClient.ts"],"sourcesContent":["// Generated automatically during releases by scripts/update-version-files.ts\n// This file provides runtime access to the package version for:\n// - HTTP request headers (e.g., X-Client-Info header for API requests)\n// - Debugging and support (identifying which version is running)\n// - Telemetry and logging (version reporting in errors/analytics)\n// - Ensuring build artifacts match the published package version\nexport const version = '2.119.0'\n","import { version } from './version'\n\n/** Current session will be checked for refresh at this interval. */\nexport const AUTO_REFRESH_TICK_DURATION_MS = 30 * 1000\n\n/**\n * A token refresh will be attempted this many ticks before the current session expires. */\nexport const AUTO_REFRESH_TICK_THRESHOLD = 3\n\n/*\n * Earliest time before an access token expires that the session should be refreshed.\n */\nexport const EXPIRY_MARGIN_MS = AUTO_REFRESH_TICK_THRESHOLD * AUTO_REFRESH_TICK_DURATION_MS\n\n/**\n * After a refresh fails, serial callers (including the next auto-refresh\n * tick) within this window receive the cached failure instead of firing\n * another /token request. Two ticks: each outage burns at most one /token\n * call per cooldown window. Cleared on any successful refresh (locally or\n * via BroadcastChannel from another tab) and on `_removeSession`.\n */\nexport const REFRESH_FAILURE_COOLDOWN_MS = 2 * AUTO_REFRESH_TICK_DURATION_MS\n\nexport const GOTRUE_URL = 'http://localhost:9999'\nexport const STORAGE_KEY = 'supabase.auth.token'\nexport const AUDIENCE = ''\nexport const DEFAULT_HEADERS = { 'X-Client-Info': `gotrue-js/${version}` }\nexport const NETWORK_FAILURE = {\n  MAX_RETRIES: 10,\n  RETRY_INTERVAL: 2, // in deciseconds\n}\n\nexport const API_VERSION_HEADER_NAME = 'X-Supabase-Api-Version'\nexport const API_VERSIONS = {\n  '2024-01-01': {\n    timestamp: Date.parse('2024-01-01T00:00:00.0Z'),\n    name: '2024-01-01',\n  },\n}\n\nexport const BASE64URL_REGEX = /^([a-z0-9_-]{4})*($|[a-z0-9_-]{3}$|[a-z0-9_-]{2}$)$/i\n\n/**\n * Reserved query parameter appended to `redirectTo` URLs (behind\n * `experimental.appendPkceFlowIdToRedirects`) that correlates a PKCE callback\n * with the code verifier stored when its flow started. It round-trips through\n * the auth server untouched and identifies a verifier slot in storage — the\n * verifier itself never appears in a URL.\n */\nexport const PKCE_FLOW_ID_PARAM = 'sb_flow_id'\n\n/**\n * Maximum number of PKCE code verifiers kept in storage at once. Starting a\n * new flow beyond this evicts the oldest pending verifier.\n */\nexport const PKCE_MAX_CONCURRENT_FLOWS = 5\n\nexport const JWKS_TTL = 10 * 60 * 1000 // 10 minutes\n","import { WeakPasswordReasons } from './types'\nimport { ErrorCode } from './error-codes'\n\n/**\n * Base error thrown by Supabase Auth helpers.\n *\n * @example\n * ```ts\n * import { AuthError } from '@supabase/auth-js'\n *\n * throw new AuthError('Unexpected auth error', 500, 'unexpected')\n * ```\n */\nexport class AuthError extends Error {\n  /**\n   * Error code associated with the error. Most errors coming from\n   * HTTP responses will have a code, though some errors that occur\n   * before a response is received will not have one present. In that\n   * case {@link AuthError.status} will also be undefined.\n   */\n  code: ErrorCode | (string \u0026 {}) | undefined\n\n  /** HTTP status code that caused the error. */\n  status: number | undefined\n\n  protected __isAuthError = true\n\n  constructor(message: string, status?: number, code?: string) {\n    super(message)\n    this.name = 'AuthError'\n    this.status = status\n    this.code = code\n  }\n\n  toJSON(): {\n    name: string\n    message: string\n    status: number | undefined\n    code: ErrorCode | (string \u0026 {}) | undefined\n  } {\n    return {\n      name: this.name,\n      message: this.message,\n      status: this.status,\n      code: this.code,\n    }\n  }\n}\n\nexport function isAuthError(error: unknown): error is AuthError {\n  return typeof error === 'object' \u0026\u0026 error !== null \u0026\u0026 '__isAuthError' in error\n}\n\n/**\n * Error returned directly from the GoTrue REST API.\n *\n * @example\n * ```ts\n * import { AuthApiError } from '@supabase/auth-js'\n *\n * throw new AuthApiError('Invalid credentials', 400, 'invalid_credentials')\n * ```\n */\nexport class AuthApiError extends AuthError {\n  status: number\n\n  constructor(message: string, status: number, code: string | undefined) {\n    super(message, status, code)\n    this.name = 'AuthApiError'\n    this.status = status\n    this.code = code\n  }\n}\n\nexport function isAuthApiError(error: unknown): error is AuthApiError {\n  return isAuthError(error) \u0026\u0026 error.name === 'AuthApiError'\n}\n\n/**\n * Wraps non-standard errors so callers can inspect the root cause.\n *\n * @example\n * ```ts\n * import { AuthUnknownError } from '@supabase/auth-js'\n *\n * try {\n *   await someAuthCall()\n * } catch (err) {\n *   throw new AuthUnknownError('Auth failed', err)\n * }\n * ```\n */\nexport class AuthUnknownError extends AuthError {\n  originalError: unknown\n\n  constructor(message: string, originalError: unknown) {\n    super(message)\n    this.name = 'AuthUnknownError'\n    this.originalError = originalError\n  }\n}\n\n/**\n * Flexible error class used to create named auth errors at runtime.\n *\n * @example\n * ```ts\n * import { CustomAuthError } from '@supabase/auth-js'\n *\n * throw new CustomAuthError('My custom auth error', 'MyAuthError', 400, 'custom_code')\n * ```\n */\nexport class CustomAuthError extends AuthError {\n  name: string\n  status: number\n\n  constructor(message: string, name: string, status: number, code: string | undefined) {\n    super(message, status, code)\n    this.name = name\n    this.status = status\n  }\n}\n\n/**\n * Error thrown when an operation requires a session but none is present.\n *\n * @example\n * ```ts\n * import { AuthSessionMissingError } from '@supabase/auth-js'\n *\n * throw new AuthSessionMissingError()\n * ```\n */\nexport class AuthSessionMissingError extends CustomAuthError {\n  constructor() {\n    super('Auth session missing!', 'AuthSessionMissingError', 400, undefined)\n  }\n}\n\nexport function isAuthSessionMissingError(error: any): error is AuthSessionMissingError {\n  return isAuthError(error) \u0026\u0026 error.name === 'AuthSessionMissingError'\n}\n\n/**\n * Error thrown when the token response is malformed.\n *\n * @example\n * ```ts\n * import { AuthInvalidTokenResponseError } from '@supabase/auth-js'\n *\n * throw new AuthInvalidTokenResponseError()\n * ```\n */\nexport class AuthInvalidTokenResponseError extends CustomAuthError {\n  constructor() {\n    super('Auth session or user missing', 'AuthInvalidTokenResponseError', 500, undefined)\n  }\n}\n\n/**\n * Error thrown when email/password credentials are invalid.\n *\n * @example\n * ```ts\n * import { AuthInvalidCredentialsError } from '@supabase/auth-js'\n *\n * throw new AuthInvalidCredentialsError('Email or password is incorrect')\n * ```\n */\nexport class AuthInvalidCredentialsError extends CustomAuthError {\n  constructor(message: string) {\n    super(message, 'AuthInvalidCredentialsError', 400, undefined)\n  }\n}\n\n/**\n * Error thrown when implicit grant redirects contain an error.\n *\n * @example\n * ```ts\n * import { AuthImplicitGrantRedirectError } from '@supabase/auth-js'\n *\n * throw new AuthImplicitGrantRedirectError('OAuth redirect failed', {\n *   error: 'access_denied',\n *   code: 'oauth_error',\n * })\n * ```\n */\nexport class AuthImplicitGrantRedirectError extends CustomAuthError {\n  details: { error: string; code: string } | null = null\n  constructor(message: string, details: { error: string; code: string } | null = null) {\n    super(message, 'AuthImplicitGrantRedirectError', 500, undefined)\n    this.details = details\n  }\n\n  toJSON(): {\n    name: string\n    message: string\n    status: number | undefined\n    code: ErrorCode | (string \u0026 {}) | undefined\n    details: { error: string; code: string } | null\n  } {\n    return {\n      ...super.toJSON(),\n      details: this.details,\n    }\n  }\n}\n\nexport function isAuthImplicitGrantRedirectError(\n  error: any\n): error is AuthImplicitGrantRedirectError {\n  return isAuthError(error) \u0026\u0026 error.name === 'AuthImplicitGrantRedirectError'\n}\n\n/**\n * Error thrown during PKCE code exchanges.\n *\n * @example\n * ```ts\n * import { AuthPKCEGrantCodeExchangeError } from '@supabase/auth-js'\n *\n * throw new AuthPKCEGrantCodeExchangeError('PKCE exchange failed')\n * ```\n */\nexport class AuthPKCEGrantCodeExchangeError extends CustomAuthError {\n  details: { error: string; code: string } | null = null\n\n  constructor(message: string, details: { error: string; code: string } | null = null) {\n    super(message, 'AuthPKCEGrantCodeExchangeError', 500, undefined)\n    this.details = details\n  }\n\n  toJSON(): {\n    name: string\n    message: string\n    status: number | undefined\n    code: ErrorCode | (string \u0026 {}) | undefined\n    details: { error: string; code: string } | null\n  } {\n    return {\n      ...super.toJSON(),\n      details: this.details,\n    }\n  }\n}\n\n/**\n * Error thrown when the PKCE code verifier is not found in storage.\n * This typically happens when the auth flow was initiated in a different\n * browser, device, or the storage was cleared.\n *\n * @example\n * ```ts\n * import { AuthPKCECodeVerifierMissingError } from '@supabase/auth-js'\n *\n * throw new AuthPKCECodeVerifierMissingError()\n * ```\n */\nexport class AuthPKCECodeVerifierMissingError extends CustomAuthError {\n  constructor() {\n    super(\n      'PKCE code verifier not found in storage. ' +\n        'This can happen if the auth flow was initiated in a different browser or device, ' +\n        'or if the storage was cleared. For SSR frameworks (Next.js, SvelteKit, etc.), ' +\n        'use @supabase/ssr on both the server and client to store the code verifier in cookies.',\n      'AuthPKCECodeVerifierMissingError',\n      400,\n      'pkce_code_verifier_not_found'\n    )\n  }\n}\n\nexport function isAuthPKCECodeVerifierMissingError(\n  error: unknown\n): error is AuthPKCECodeVerifierMissingError {\n  return isAuthError(error) \u0026\u0026 error.name === 'AuthPKCECodeVerifierMissingError'\n}\n\n/**\n * Error thrown when a transient fetch issue occurs.\n *\n * @example\n * ```ts\n * import { AuthRetryableFetchError } from '@supabase/auth-js'\n *\n * throw new AuthRetryableFetchError('Service temporarily unavailable', 503)\n * ```\n */\nexport class AuthRetryableFetchError extends CustomAuthError {\n  constructor(message: string, status: number) {\n    super(message, 'AuthRetryableFetchError', status, undefined)\n  }\n}\n\nexport function isAuthRetryableFetchError(error: unknown): error is AuthRetryableFetchError {\n  return isAuthError(error) \u0026\u0026 error.name === 'AuthRetryableFetchError'\n}\n\n/**\n * Returned when the server rotated a refresh token successfully but the\n * client chose not to persist the rotated tokens because the local session\n * changed mid-flight. Usually means a concurrent `signOut` cleared storage\n * between when the refresh started and when it came back.\n *\n * Set on the `error` field of the refresh result so callers can tell \"we\n * got rotated tokens but threw them away\" apart from \"the refresh failed.\"\n * The rotated session on the server will be picked up on the next refresh\n * via GoTrue's parent-of-active path.\n *\n * @example\n * ```ts\n * import { isAuthRefreshDiscardedError } from '@supabase/auth-js'\n *\n * if (isAuthRefreshDiscardedError(error)) {\n *   // Concurrent signOut/sign-in raced our refresh. Treat as a no-op.\n * }\n * ```\n */\nexport class AuthRefreshDiscardedError extends CustomAuthError {\n  constructor(\n    message = 'Refresh result discarded: session state changed mid-flight (e.g., concurrent signOut)'\n  ) {\n    super(message, 'AuthRefreshDiscardedError', 409, undefined)\n  }\n}\n\nexport function isAuthRefreshDiscardedError(error: unknown): error is AuthRefreshDiscardedError {\n  return isAuthError(error) \u0026\u0026 error.name === 'AuthRefreshDiscardedError'\n}\n\n/**\n * This error is thrown on certain methods when the password used is deemed\n * weak. Inspect the reasons to identify what password strength rules are\n * inadequate.\n */\n/**\n * Error thrown when a supplied password is considered weak.\n *\n * @example\n * ```ts\n * import { AuthWeakPasswordError } from '@supabase/auth-js'\n *\n * throw new AuthWeakPasswordError('Password too short', 400, ['min_length'])\n * ```\n */\nexport class AuthWeakPasswordError extends CustomAuthError {\n  /**\n   * Reasons why the password is deemed weak.\n   */\n  reasons: WeakPasswordReasons[]\n\n  constructor(message: string, status: number, reasons: WeakPasswordReasons[]) {\n    super(message, 'AuthWeakPasswordError', status, 'weak_password')\n\n    this.reasons = reasons\n  }\n\n  toJSON(): {\n    name: string\n    message: string\n    status: number | undefined\n    code: ErrorCode | (string \u0026 {}) | undefined\n    reasons: WeakPasswordReasons[]\n  } {\n    return {\n      ...super.toJSON(),\n      reasons: this.reasons,\n    }\n  }\n}\n\nexport function isAuthWeakPasswordError(error: unknown): error is AuthWeakPasswordError {\n  return isAuthError(error) \u0026\u0026 error.name === 'AuthWeakPasswordError'\n}\n\n/**\n * Error thrown when a JWT cannot be verified or parsed.\n *\n * @example\n * ```ts\n * import { AuthInvalidJwtError } from '@supabase/auth-js'\n *\n * throw new AuthInvalidJwtError('Token signature is invalid')\n * ```\n */\nexport class AuthInvalidJwtError extends CustomAuthError {\n  constructor(message: string) {\n    super(message, 'AuthInvalidJwtError', 400, 'invalid_jwt')\n  }\n}\n","/**\n * Avoid modifying this file. It's part of\n * https://github.com/supabase-community/base64url-js.  Submit all fixes on\n * that repo!\n */\n\nimport { Uint8Array_ } from './webauthn.dom'\n\n/**\n * An array of characters that encode 6 bits into a Base64-URL alphabet\n * character.\n */\nconst TO_BASE64URL = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_'.split('')\n\n/**\n * An array of characters that can appear in a Base64-URL encoded string but\n * should be ignored.\n */\nconst IGNORE_BASE64URL = ' \\t\\n\\r='.split('')\n\n/**\n * An array of 128 numbers that map a Base64-URL character to 6 bits, or if -2\n * used to skip the character, or if -1 used to error out.\n */\nconst FROM_BASE64URL = (() =\u003e {\n  const charMap: number[] = new Array(128)\n\n  for (let i = 0; i \u003c charMap.length; i += 1) {\n    charMap[i] = -1\n  }\n\n  for (let i = 0; i \u003c IGNORE_BASE64URL.length; i += 1) {\n    charMap[IGNORE_BASE64URL[i].charCodeAt(0)] = -2\n  }\n\n  for (let i = 0; i \u003c TO_BASE64URL.length; i += 1) {\n    charMap[TO_BASE64URL[i].charCodeAt(0)] = i\n  }\n\n  return charMap\n})()\n\n/**\n * Converts a byte to a Base64-URL string.\n *\n * @param byte The byte to convert, or null to flush at the end of the byte sequence.\n * @param state The Base64 conversion state. Pass an initial value of `{ queue: 0, queuedBits: 0 }`.\n * @param emit A function called with the next Base64 character when ready.\n */\nexport function byteToBase64URL(\n  byte: number | null,\n  state: { queue: number; queuedBits: number },\n  emit: (char: string) =\u003e void\n) {\n  if (byte !== null) {\n    state.queue = (state.queue \u003c\u003c 8) | byte\n    state.queuedBits += 8\n\n    while (state.queuedBits \u003e= 6) {\n      const pos = (state.queue \u003e\u003e (state.queuedBits - 6)) \u0026 63\n      emit(TO_BASE64URL[pos])\n      state.queuedBits -= 6\n    }\n  } else if (state.queuedBits \u003e 0) {\n    state.queue = state.queue \u003c\u003c (6 - state.queuedBits)\n    state.queuedBits = 6\n\n    while (state.queuedBits \u003e= 6) {\n      const pos = (state.queue \u003e\u003e (state.queuedBits - 6)) \u0026 63\n      emit(TO_BASE64URL[pos])\n      state.queuedBits -= 6\n    }\n  }\n}\n\n/**\n * Converts a String char code (extracted using `string.charCodeAt(position)`) to a sequence of Base64-URL characters.\n *\n * @param charCode The char code of the JavaScript string.\n * @param state The Base64 state. Pass an initial value of `{ queue: 0, queuedBits: 0 }`.\n * @param emit A function called with the next byte.\n */\nexport function byteFromBase64URL(\n  charCode: number,\n  state: { queue: number; queuedBits: number },\n  emit: (byte: number) =\u003e void\n) {\n  const bits = FROM_BASE64URL[charCode]\n\n  if (bits \u003e -1) {\n    // valid Base64-URL character\n    state.queue = (state.queue \u003c\u003c 6) | bits\n    state.queuedBits += 6\n\n    while (state.queuedBits \u003e= 8) {\n      emit((state.queue \u003e\u003e (state.queuedBits - 8)) \u0026 0xff)\n      state.queuedBits -= 8\n    }\n  } else if (bits === -2) {\n    // ignore spaces, tabs, newlines, =\n    return\n  } else {\n    throw new Error(`Invalid Base64-URL character \"${String.fromCharCode(charCode)}\"`)\n  }\n}\n\n/**\n * Converts a JavaScript string (which may include any valid character) into a\n * Base64-URL encoded string. The string is first encoded in UTF-8 which is\n * then encoded as Base64-URL.\n *\n * @param str The string to convert.\n */\nexport function stringToBase64URL(str: string) {\n  const base64: string[] = []\n\n  const emitter = (char: string) =\u003e {\n    base64.push(char)\n  }\n\n  const state = { queue: 0, queuedBits: 0 }\n\n  stringToUTF8(str, (byte: number) =\u003e {\n    byteToBase64URL(byte, state, emitter)\n  })\n\n  byteToBase64URL(null, state, emitter)\n\n  return base64.join('')\n}\n\n/**\n * Converts a Base64-URL encoded string into a JavaScript string. It is assumed\n * that the underlying string has been encoded as UTF-8.\n *\n * @param str The Base64-URL encoded string.\n */\nexport function stringFromBase64URL(str: string) {\n  const conv: string[] = []\n\n  const utf8Emit = (codepoint: number) =\u003e {\n    conv.push(String.fromCodePoint(codepoint))\n  }\n\n  const utf8State = {\n    utf8seq: 0,\n    codepoint: 0,\n  }\n\n  const b64State = { queue: 0, queuedBits: 0 }\n\n  const byteEmit = (byte: number) =\u003e {\n    stringFromUTF8(byte, utf8State, utf8Emit)\n  }\n\n  for (let i = 0; i \u003c str.length; i += 1) {\n    byteFromBase64URL(str.charCodeAt(i), b64State, byteEmit)\n  }\n\n  return conv.join('')\n}\n\n/**\n * Converts a Unicode codepoint to a multi-byte UTF-8 sequence.\n *\n * @param codepoint The Unicode codepoint.\n * @param emit      Function which will be called for each UTF-8 byte that represents the codepoint.\n */\nexport function codepointToUTF8(codepoint: number, emit: (byte: number) =\u003e void) {\n  if (codepoint \u003c= 0x7f) {\n    emit(codepoint)\n    return\n  } else if (codepoint \u003c= 0x7ff) {\n    emit(0xc0 | (codepoint \u003e\u003e 6))\n    emit(0x80 | (codepoint \u0026 0x3f))\n    return\n  } else if (codepoint \u003c= 0xffff) {\n    emit(0xe0 | (codepoint \u003e\u003e 12))\n    emit(0x80 | ((codepoint \u003e\u003e 6) \u0026 0x3f))\n    emit(0x80 | (codepoint \u0026 0x3f))\n    return\n  } else if (codepoint \u003c= 0x10ffff) {\n    emit(0xf0 | (codepoint \u003e\u003e 18))\n    emit(0x80 | ((codepoint \u003e\u003e 12) \u0026 0x3f))\n    emit(0x80 | ((codepoint \u003e\u003e 6) \u0026 0x3f))\n    emit(0x80 | (codepoint \u0026 0x3f))\n    return\n  }\n\n  throw new Error(`Unrecognized Unicode codepoint: ${codepoint.toString(16)}`)\n}\n\n/**\n * Converts a JavaScript string to a sequence of UTF-8 bytes.\n *\n * @param str  The string to convert to UTF-8.\n * @param emit Function which will be called for each UTF-8 byte of the string.\n */\nexport function stringToUTF8(str: string, emit: (byte: number) =\u003e void) {\n  for (let i = 0; i \u003c str.length; i += 1) {\n    let codepoint = str.charCodeAt(i)\n\n    if (codepoint \u003e 0xd7ff \u0026\u0026 codepoint \u003c= 0xdbff) {\n      // most UTF-16 codepoints are Unicode codepoints, except values in this\n      // range where the next UTF-16 codepoint needs to be combined with the\n      // current one to get the Unicode codepoint\n      const highSurrogate = ((codepoint - 0xd800) * 0x400) \u0026 0xffff\n      const lowSurrogate = (str.charCodeAt(i + 1) - 0xdc00) \u0026 0xffff\n      codepoint = (lowSurrogate | highSurrogate) + 0x10000\n      i += 1\n    }\n\n    codepointToUTF8(codepoint, emit)\n  }\n}\n\n/**\n * Converts a UTF-8 byte to a Unicode codepoint.\n *\n * @param byte  The UTF-8 byte next in the sequence.\n * @param state The shared state between consecutive UTF-8 bytes in the\n *              sequence, an object with the shape `{ utf8seq: 0, codepoint: 0 }`.\n * @param emit  Function which will be called for each codepoint.\n */\nexport function stringFromUTF8(\n  byte: number,\n  state: { utf8seq: number; codepoint: number },\n  emit: (codepoint: number) =\u003e void\n) {\n  if (state.utf8seq === 0) {\n    if (byte \u003c= 0x7f) {\n      emit(byte)\n      return\n    }\n\n    // count the number of 1 leading bits until you reach 0\n    for (let leadingBit = 1; leadingBit \u003c 6; leadingBit += 1) {\n      if (((byte \u003e\u003e (7 - leadingBit)) \u0026 1) === 0) {\n        state.utf8seq = leadingBit\n        break\n      }\n    }\n\n    if (state.utf8seq === 2) {\n      state.codepoint = byte \u0026 31\n    } else if (state.utf8seq === 3) {\n      state.codepoint = byte \u0026 15\n    } else if (state.utf8seq === 4) {\n      state.codepoint = byte \u0026 7\n    } else {\n      throw new Error('Invalid UTF-8 sequence')\n    }\n\n    state.utf8seq -= 1\n  } else if (state.utf8seq \u003e 0) {\n    if (byte \u003c= 0x7f) {\n      throw new Error('Invalid UTF-8 sequence')\n    }\n\n    state.codepoint = (state.codepoint \u003c\u003c 6) | (byte \u0026 63)\n    state.utf8seq -= 1\n\n    if (state.utf8seq === 0) {\n      emit(state.codepoint)\n    }\n  }\n}\n\n/**\n * Helper functions to convert different types of strings to Uint8Array\n */\n\nexport function base64UrlToUint8Array(str: string): Uint8Array_ {\n  const result: number[] = []\n  const state = { queue: 0, queuedBits: 0 }\n\n  const onByte = (byte: number) =\u003e {\n    result.push(byte)\n  }\n\n  for (let i = 0; i \u003c str.length; i += 1) {\n    byteFromBase64URL(str.charCodeAt(i), state, onByte)\n  }\n\n  return new Uint8Array(result)\n}\n\nexport function stringToUint8Array(str: string): Uint8Array_ {\n  const result: number[] = []\n  stringToUTF8(str, (byte: number) =\u003e result.push(byte))\n  return new Uint8Array(result)\n}\n\nexport function bytesToBase64URL(bytes: Uint8Array) {\n  const result: string[] = []\n  const state = { queue: 0, queuedBits: 0 }\n\n  const onChar = (char: string) =\u003e {\n    result.push(char)\n  }\n\n  bytes.forEach((byte) =\u003e byteToBase64URL(byte, state, onChar))\n\n  // always call with `null` after processing all bytes\n  byteToBase64URL(null, state, onChar)\n\n  return result.join('')\n}\n","import {\n  API_VERSION_HEADER_NAME,\n  BASE64URL_REGEX,\n  PKCE_FLOW_ID_PARAM,\n  PKCE_MAX_CONCURRENT_FLOWS,\n} from './constants'\nimport { AuthInvalidJwtError } from './errors'\nimport { base64UrlToUint8Array, stringFromBase64URL } from './base64url'\nimport { JwtHeader, JwtPayload, SupportedStorage, User } from './types'\nimport { Uint8Array_ } from './webauthn.dom'\n\nexport function expiresAt(expiresIn: number) {\n  const timeNow = Math.round(Date.now() / 1000)\n  return timeNow + expiresIn\n}\n\n/**\n * Generates a unique identifier for internal callback subscriptions.\n *\n * This function uses JavaScript Symbols to create guaranteed-unique identifiers\n * for auth state change callbacks. Symbols are ideal for this use case because:\n * - They are guaranteed unique by the JavaScript runtime\n * - They work in all environments (browser, SSR, Node.js)\n * - They avoid issues with Next.js 16 deterministic rendering requirements\n * - They are perfect for internal, non-serializable identifiers\n *\n * Note: This function is only used for internal subscription management,\n * not for security-critical operations like session tokens.\n */\nexport function generateCallbackId(): symbol {\n  return Symbol('auth-callback')\n}\n\nexport const isBrowser = () =\u003e typeof window !== 'undefined' \u0026\u0026 typeof document !== 'undefined'\n\nconst localStorageWriteTests = {\n  tested: false,\n  writable: false,\n}\n\n/**\n * Checks whether localStorage is supported on this browser.\n */\nexport const supportsLocalStorage = () =\u003e {\n  if (!isBrowser()) {\n    return false\n  }\n\n  try {\n    if (typeof globalThis.localStorage !== 'object') {\n      return false\n    }\n  } catch (e) {\n    // DOM exception when accessing `localStorage`\n    return false\n  }\n\n  if (localStorageWriteTests.tested) {\n    return localStorageWriteTests.writable\n  }\n\n  const randomKey = `lswt-${Math.random()}${Math.random()}`\n\n  try {\n    globalThis.localStorage.setItem(randomKey, randomKey)\n    globalThis.localStorage.removeItem(randomKey)\n\n    localStorageWriteTests.tested = true\n    localStorageWriteTests.writable = true\n  } catch (e) {\n    // localStorage can't be written to\n    // https://www.chromium.org/for-testers/bug-reporting-guidelines/uncaught-securityerror-failed-to-read-the-localstorage-property-from-window-access-is-denied-for-this-document\n\n    localStorageWriteTests.tested = true\n    localStorageWriteTests.writable = false\n  }\n\n  return localStorageWriteTests.writable\n}\n\n/**\n * Extracts parameters encoded in the URL both in the query and fragment.\n */\nexport function parseParametersFromURL(href: string) {\n  const result: { [parameter: string]: string } = {}\n\n  const url = new URL(href)\n\n  if (url.hash \u0026\u0026 url.hash[0] === '#') {\n    try {\n      const hashSearchParams = new URLSearchParams(url.hash.substring(1))\n      hashSearchParams.forEach((value, key) =\u003e {\n        result[key] = value\n      })\n    } catch (_e) {\n      // hash is not a query string\n    }\n  }\n\n  // search parameters take precedence over hash parameters\n  url.searchParams.forEach((value, key) =\u003e {\n    result[key] = value\n  })\n\n  return result\n}\n\ntype Fetch = typeof fetch\n\nexport const resolveFetch = (customFetch?: Fetch): Fetch =\u003e {\n  if (customFetch) {\n    return (...args) =\u003e customFetch(...args)\n  }\n  return (...args) =\u003e fetch(...args)\n}\n\nexport const looksLikeFetchResponse = (maybeResponse: unknown): maybeResponse is Response =\u003e {\n  return (\n    typeof maybeResponse === 'object' \u0026\u0026\n    maybeResponse !== null \u0026\u0026\n    'status' in maybeResponse \u0026\u0026\n    'ok' in maybeResponse \u0026\u0026\n    'json' in maybeResponse \u0026\u0026\n    typeof (maybeResponse as any).json === 'function'\n  )\n}\n\n// Storage helpers\nexport const setItemAsync = async (\n  storage: SupportedStorage,\n  key: string,\n  data: any\n): Promise\u003cvoid\u003e =\u003e {\n  await storage.setItem(key, JSON.stringify(data))\n}\n\nexport const getItemAsync = async (storage: SupportedStorage, key: string): Promise\u003cunknown\u003e =\u003e {\n  const value = await storage.getItem(key)\n\n  if (!value) {\n    return null\n  }\n\n  try {\n    return JSON.parse(value)\n  } catch {\n    // Storage values are always written as JSON via setItemAsync. A non-JSON\n    // value means the entry is corrupted (e.g. mismatched chunked cookies in\n    // SSR contexts). Treat as absent so callers do not mutate or re-save the\n    // garbage, which would otherwise trigger a TypeError downstream and\n    // leak the raw value into error logs.\n    return null\n  }\n}\n\nexport const removeItemAsync = async (storage: SupportedStorage, key: string): Promise\u003cvoid\u003e =\u003e {\n  await storage.removeItem(key)\n}\n\n/**\n * A deferred represents some asynchronous work that is not yet finished, which\n * may or may not culminate in a value.\n * Taken from: https://github.com/mike-north/types/blob/master/src/async.ts\n */\nexport class Deferred\u003cT = any\u003e {\n  public static promiseConstructor: PromiseConstructor = Promise\n\n  public readonly promise!: PromiseLike\u003cT\u003e\n\n  public readonly resolve!: (value?: T | PromiseLike\u003cT\u003e) =\u003e void\n\n  public readonly reject!: (reason?: any) =\u003e any\n\n  public constructor() {\n    // eslint-disable-next-line @typescript-eslint/no-extra-semi\n    ;(this as any).promise = new Deferred.promiseConstructor((res, rej) =\u003e {\n      // eslint-disable-next-line @typescript-eslint/no-extra-semi\n      ;(this as any).resolve = res\n      // eslint-disable-next-line @typescript-eslint/no-extra-semi\n      ;(this as any).reject = rej\n    })\n  }\n}\n\nexport function decodeJWT(token: string): {\n  header: JwtHeader\n  payload: JwtPayload\n  signature: Uint8Array_\n  raw: {\n    header: string\n    payload: string\n  }\n} {\n  const parts = token.split('.')\n\n  if (parts.length !== 3) {\n    throw new AuthInvalidJwtError('Invalid JWT structure')\n  }\n\n  // Regex checks for base64url format\n  for (let i = 0; i \u003c parts.length; i++) {\n    if (!BASE64URL_REGEX.test(parts[i] as string)) {\n      throw new AuthInvalidJwtError('JWT not in base64url format')\n    }\n  }\n  const data = {\n    // using base64url lib\n    header: JSON.parse(stringFromBase64URL(parts[0])),\n    payload: JSON.parse(stringFromBase64URL(parts[1])),\n    signature: base64UrlToUint8Array(parts[2]),\n    raw: {\n      header: parts[0],\n      payload: parts[1],\n    },\n  }\n  return data\n}\n\n/**\n * Creates a promise that resolves to null after some time.\n */\nexport async function sleep(time: number): Promise\u003cnull\u003e {\n  return await new Promise((accept) =\u003e {\n    setTimeout(() =\u003e accept(null), time)\n  })\n}\n\n/**\n * Converts the provided async function into a retryable function. Each result\n * or thrown error is sent to the isRetryable function which should return true\n * if the function should run again.\n */\nexport function retryable\u003cT\u003e(\n  fn: (attempt: number) =\u003e Promise\u003cT\u003e,\n  isRetryable: (attempt: number, error: any | null, result?: T) =\u003e boolean\n): Promise\u003cT\u003e {\n  const promise = new Promise\u003cT\u003e((accept, reject) =\u003e {\n    // eslint-disable-next-line @typescript-eslint/no-extra-semi\n    ;(async () =\u003e {\n      for (let attempt = 0; attempt \u003c Infinity; attempt++) {\n        try {\n          const result = await fn(attempt)\n\n          if (!isRetryable(attempt, null, result)) {\n            accept(result)\n            return\n          }\n        } catch (e) {\n          if (!isRetryable(attempt, e)) {\n            reject(e)\n            return\n          }\n        }\n      }\n    })()\n  })\n\n  return promise\n}\n\nfunction dec2hex(dec: number) {\n  return ('0' + dec.toString(16)).substr(-2)\n}\n\n// Functions below taken from: https://stackoverflow.com/questions/63309409/creating-a-code-verifier-and-challenge-for-pkce-auth-on-spotify-api-in-reactjs\nexport function generatePKCEVerifier() {\n  const verifierLength = 56\n  const array = new Uint32Array(verifierLength)\n  if (typeof crypto === 'undefined') {\n    const charSet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~'\n    const charSetLen = charSet.length\n    let verifier = ''\n    for (let i = 0; i \u003c verifierLength; i++) {\n      verifier += charSet.charAt(Math.floor(Math.random() * charSetLen))\n    }\n    return verifier\n  }\n  crypto.getRandomValues(array)\n  return Array.from(array, dec2hex).join('')\n}\n\nasync function sha256(randomString: string) {\n  const encoder = new TextEncoder()\n  const encodedData = encoder.encode(randomString)\n  const hash = await crypto.subtle.digest('SHA-256', encodedData)\n  const bytes = new Uint8Array(hash)\n\n  return Array.from(bytes)\n    .map((c) =\u003e String.fromCharCode(c))\n    .join('')\n}\n\nexport async function generatePKCEChallenge(verifier: string) {\n  const hasCryptoSupport =\n    typeof crypto !== 'undefined' \u0026\u0026\n    typeof crypto.subtle !== 'undefined' \u0026\u0026\n    typeof TextEncoder !== 'undefined'\n\n  if (!hasCryptoSupport) {\n    console.warn(\n      'WebCrypto API is not supported. Code challenge method will default to use plain instead of sha256.'\n    )\n    return verifier\n  }\n  const hashed = await sha256(verifier)\n  return btoa(hashed).replace(/\\+/g, '-').replace(/\\//g, '_').replace(/=+$/, '')\n}\n\nconst PKCE_FLOW_ID_PATTERN = /^[a-zA-Z0-9_-]{8,64}$/\n\n/**\n * Returns the flow id if it is a plausible flow id, `null` otherwise. Flow\n * ids can arrive via URL parameters, so anything outside the expected shape\n * is discarded before it is used to build a storage key.\n */\nexport function validatePKCEFlowId(flowId: unknown): string | null {\n  return typeof flowId === 'string' \u0026\u0026 PKCE_FLOW_ID_PATTERN.test(flowId) ? flowId : null\n}\n\nexport function generatePKCEFlowId(): string {\n  if (typeof crypto !== 'undefined' \u0026\u0026 typeof crypto.getRandomValues === 'function') {\n    const bytes = new Uint8Array(16)\n    crypto.getRandomValues(bytes)\n    return Array.from(bytes, dec2hex).join('')\n  }\n  let flowId = ''\n  for (let i = 0; i \u003c 32; i++) {\n    flowId += Math.floor(Math.random() * 16).toString(16)\n  }\n  return flowId\n}\n\n// Slot keys deliberately end in `-code-verifier`: @supabase/ssr's server\n// cookie adapter only persists writes immediately for keys with that suffix\n// (no auth event fires when a verifier is stored). They also contain no dot,\n// because @supabase/ssr chunks oversized cookies as `\u003ckey\u003e.\u003cnumber\u003e` and a\n// dot-delimited key could be mistaken for a chunk of the fixed\n// `-code-verifier` cookie and clobbered by its chunk management.\nexport const pkceVerifierSlotKey = (storageKey: string, flowId: string) =\u003e\n  `${storageKey}-flow-${flowId}-code-verifier`\n\nconst pkceFlowIndexKey = (storageKey: string) =\u003e `${storageKey}-flows-code-verifier`\n\n/**\n * Storage adapters cannot enumerate keys, so the ids of pending verifier\n * slots are tracked in an index entry, oldest first. Index entries pass\n * through the same validation as URL-provided flow ids: with cookie-based\n * storage the index contents are no more trustworthy than a URL parameter.\n */\nasync function getPKCEFlowIndex(storage: SupportedStorage, storageKey: string): Promise\u003cstring[]\u003e {\n  const index = await getItemAsync(storage, pkceFlowIndexKey(storageKey))\n  return Array.isArray(index)\n    ? index.filter((id): id is string =\u003e validatePKCEFlowId(id) !== null)\n    : []\n}\n\n/**\n * The index is read-modify-write without a lock: two concurrent starts (e.g.\n * two tabs) can lose one index update. The losing flow still works — its slot\n * is addressed directly by key — but its entry is missing from the index, so\n * it escapes both ring eviction and removeAllPKCEVerifiers: the orphaned slot\n * persists for the storage medium's lifetime (up to the cookie max age in\n * cookie storage) and repeated races accumulate one orphan each. Accepted\n * trade-off: locking every flow start is far more intrusive than the leak.\n */\nexport async function storePKCEVerifier(\n  storage: SupportedStorage,\n  storageKey: string,\n  flowId: string,\n  verifier: string,\n  onEvictFlow?: (evictedFlowId: string) =\u003e void\n): Promise\u003cvoid\u003e {\n  await setItemAsync(storage, pkceVerifierSlotKey(storageKey, flowId), verifier)\n\n  const index = (await getPKCEFlowIndex(storage, storageKey)).filter((id) =\u003e id !== flowId)\n  index.push(flowId)\n  while (index.length \u003e PKCE_MAX_CONCURRENT_FLOWS) {\n    const evicted = index.shift()!\n    await removeItemAsync(storage, pkceVerifierSlotKey(storageKey, evicted))\n    onEvictFlow?.(evicted)\n  }\n  await setItemAsync(storage, pkceFlowIndexKey(storageKey), index)\n\n  // Deprecation-window dual write: exchanges that cannot identify their flow\n  // (older SDK versions, redirects without the flow id parameter) read the\n  // fixed key, which mirrors the most recently started flow.\n  await setItemAsync(storage, `${storageKey}-code-verifier`, verifier)\n}\n\n/**\n * Looks up the verifier for `flowId`. When a flow id is given, only that slot\n * is consulted — deliberately no fallback to the fixed legacy key: submitting\n * another flow's verifier would burn the single-use auth code, and the\n * subsequent cleanup would delete a pending flow's only fallback. The legacy\n * key is read only when no flow id is available at all.\n */\nexport async function retrievePKCEVerifier(\n  storage: SupportedStorage,\n  storageKey: string,\n  flowId: string | null\n): Promise\u003c{ verifier: string | null; flowId: string | null }\u003e {\n  if (flowId) {\n    const verifier = await getItemAsync(storage, pkceVerifierSlotKey(storageKey, flowId))\n    return { verifier: typeof verifier === 'string' ? verifier : null, flowId }\n  }\n  const verifier = await getItemAsync(storage, `${storageKey}-code-verifier`)\n  return { verifier: typeof verifier === 'string' ? verifier : null, flowId: null }\n}\n\n/**\n * Removes a single flow's verifier. Never clears other flows' slots: with a\n * `flowId` only that slot is deleted (plus the legacy fixed key when it holds\n * the same verifier); without one, only the legacy fixed key is deleted.\n */\nexport async function removePKCEVerifier(\n  storage: SupportedStorage,\n  storageKey: string,\n  flowId: string | null\n): Promise\u003cvoid\u003e {\n  const legacyKey = `${storageKey}-code-verifier`\n  if (!flowId) {\n    await removeItemAsync(storage, legacyKey)\n    return\n  }\n\n  const slotKey = pkceVerifierSlotKey(storageKey, flowId)\n  const slotValue = await getItemAsync(storage, slotKey)\n  await removeItemAsync(storage, slotKey)\n\n  // Skip the index rewrite when the flow was never indexed (e.g. a failed\n  // exchange for an absent slot): on cookie storage every write is a full\n  // Set-Cookie cycle.\n  const index = await getPKCEFlowIndex(storage, storageKey)\n  const remaining = index.filter((id) =\u003e id !== flowId)\n  if (remaining.length !== index.length) {\n    if (remaining.length \u003e 0) {\n      await setItemAsync(storage, pkceFlowIndexKey(storageKey), remaining)\n    } else {\n      await removeItemAsync(storage, pkceFlowIndexKey(storageKey))\n    }\n  }\n\n  if (slotValue != null \u0026\u0026 slotValue === (await getItemAsync(storage, legacyKey))) {\n    await removeItemAsync(storage, legacyKey)\n  }\n}\n\n/**\n * Removes every pending verifier: all slots in the index, the index itself\n * and the fixed legacy key. Used on session teardown (sign-out, invalid\n * session) — matches the pre-slot behavior where tearing down the session\n * deleted the only verifier, and prevents long-lived stale verifier cookies.\n */\nexport async function removeAllPKCEVerifiers(\n  storage: SupportedStorage,\n  storageKey: string\n): Promise\u003cvoid\u003e {\n  const index = await getPKCEFlowIndex(storage, storageKey)\n  for (const flowId of index) {\n    await removeItemAsync(storage, pkceVerifierSlotKey(storageKey, flowId))\n  }\n  await removeItemAsync(storage, pkceFlowIndexKey(storageKey))\n  await removeItemAsync(storage, `${storageKey}-code-verifier`)\n}\n\n/**\n * Appends the reserved flow id parameter to a `redirectTo` URL, replacing any\n * existing occurrence. String-based (no URL round-trip) so custom schemes\n * (native deep links) and the exact encoding of the app's own parameters\n * survive untouched; an existing fragment stays at the end of the URL.\n */\nexport function appendFlowIdToRedirectTo(redirectTo: string, flowId: string): string {\n  const hashIndex = redirectTo.indexOf('#')\n  let base = hashIndex === -1 ? redirectTo : redirectTo.slice(0, hashIndex)\n  const fragment = hashIndex === -1 ? '' : redirectTo.slice(hashIndex)\n\n  const queryIndex = base.indexOf('?')\n  if (queryIndex !== -1) {\n    const path = base.slice(0, queryIndex)\n    const remaining = base\n      .slice(queryIndex + 1)\n      .split('\u0026')\n      .filter(\n        (pair) =\u003e\n          pair !== '' \u0026\u0026 pair !== PKCE_FLOW_ID_PARAM \u0026\u0026 !pair.startsWith(`${PKCE_FLOW_ID_PARAM}=`)\n      )\n    base = remaining.length \u003e 0 ? `${path}?${remaining.join('\u0026')}` : path\n  }\n\n  const separator = base.includes('?') ? '\u0026' : '?'\n  return `${base}${separator}${PKCE_FLOW_ID_PARAM}=${encodeURIComponent(flowId)}${fragment}`\n}\n\nexport async function getCodeChallengeAndMethod(\n  storage: SupportedStorage,\n  storageKey: string,\n  isPasswordRecovery = false,\n  onEvictFlow?: (evictedFlowId: string) =\u003e void\n): Promise\u003c[string, string, string]\u003e {\n  const codeVerifier = generatePKCEVerifier()\n  let storedCodeVerifier = codeVerifier\n  if (isPasswordRecovery) {\n    storedCodeVerifier += '/recovery'\n  }\n  const flowId = generatePKCEFlowId()\n  await storePKCEVerifier(storage, storageKey, flowId, storedCodeVerifier, onEvictFlow)\n  const codeChallenge = await generatePKCEChallenge(codeVerifier)\n  const codeChallengeMethod = codeVerifier === codeChallenge ? 'plain' : 's256'\n  return [codeChallenge, codeChallengeMethod, flowId]\n}\n\n/** Parses the API version which is 2YYY-MM-DD. */\nconst API_VERSION_REGEX = /^2[0-9]{3}-(0[1-9]|1[0-2])-(0[1-9]|1[0-9]|2[0-9]|3[0-1])$/i\n\nexport function parseResponseAPIVersion(response: Response) {\n  const apiVersion = response.headers.get(API_VERSION_HEADER_NAME)\n\n  if (!apiVersion) {\n    return null\n  }\n\n  if (!apiVersion.match(API_VERSION_REGEX)) {\n    return null\n  }\n\n  try {\n    const date = new Date(`${apiVersion}T00:00:00.0Z`)\n    return date\n  } catch (_e) {\n    return null\n  }\n}\n\nexport function validateExp(exp: number) {\n  if (!exp) {\n    throw new Error('Missing exp claim')\n  }\n  const timeNow = Math.floor(Date.now() / 1000)\n  if (exp \u003c= timeNow) {\n    throw new Error('JWT has expired')\n  }\n}\n\nexport function getAlgorithm(\n  alg: 'HS256' | 'RS256' | 'ES256' | (string \u0026 {})\n): RsaHashedImportParams | EcKeyImportParams {\n  switch (alg) {\n    case 'RS256':\n      return {\n        name: 'RSASSA-PKCS1-v1_5',\n        hash: { name: 'SHA-256' },\n      }\n    case 'ES256':\n      return {\n        name: 'ECDSA',\n        namedCurve: 'P-256',\n        hash: { name: 'SHA-256' },\n      }\n    default:\n      throw new Error('Invalid alg claim')\n  }\n}\n\nconst UUID_REGEX = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i\n\nexport function validateUUID(str: string) {\n  if (!UUID_REGEX.test(str)) {\n    throw new Error('@supabase/auth-js: Expected parameter to be UUID but is not')\n  }\n}\n\nexport function assertRecoveryCodesExperimentalEnabled(experimental: {\n  recoveryCodes?: boolean\n}): void {\n  if (!experimental.recoveryCodes) {\n    throw new Error(\n      '@supabase/auth-js: the MFA recovery codes API is experimental and disabled by default. Enable it by passing `auth: { experimental: { recoveryCodes: true } }` to createClient (or to the GoTrueClient constructor).'\n    )\n  }\n}\n\nexport function userNotAvailableProxy(): User {\n  const proxyTarget = {} as User\n\n  return new Proxy(proxyTarget, {\n    get: (target: any, prop: string) =\u003e {\n      if (prop === '__isUserNotAvailableProxy') {\n        return true\n      }\n      // Preventative check for common problematic symbols during cloning/inspection\n      // These symbols might be accessed by structuredClone or other internal mechanisms.\n      if (typeof prop === 'symbol') {\n        const sProp = (prop as symbol).toString()\n        if (\n          sProp === 'Symbol(Symbol.toPrimitive)' ||\n          sProp === 'Symbol(Symbol.toStringTag)' ||\n          sProp === 'Symbol(util.inspect.custom)'\n        ) {\n          // Node.js util.inspect\n          return undefined\n        }\n      }\n      throw new Error(\n        `@supabase/auth-js: client was created with userStorage option and there was no user stored in the user storage. Accessing the \"${prop}\" property of the session object is not supported. Please use getUser() instead.`\n      )\n    },\n    set: (_target: any, prop: string) =\u003e {\n      throw new Error(\n        `@supabase/auth-js: client was created with userStorage option and there was no user stored in the user storage. Setting the \"${prop}\" property of the session object is not supported. Please use getUser() to fetch a user object you can manipulate.`\n      )\n    },\n    deleteProperty: (_target: any, prop: string) =\u003e {\n      throw new Error(\n        `@supabase/auth-js: client was created with userStorage option and there was no user stored in the user storage. Deleting the \"${prop}\" property of the session object is not supported. Please use getUser() to fetch a user object you can manipulate.`\n      )\n    },\n  })\n}\n\n/**\n * Creates a proxy around a user object that warns when properties are accessed on the server.\n * This is used to alert developers that using user data from getSession() on the server is insecure.\n *\n * @param user The actual user object to wrap\n * @param suppressWarningRef An object with a 'value' property that controls warning suppression\n * @returns A proxied user object that warns on property access\n */\nexport function insecureUserWarningProxy(user: User, suppressWarningRef: { value: boolean }): User {\n  return new Proxy(user, {\n    get: (target: any, prop: string | symbol, receiver: any) =\u003e {\n      // Allow internal checks without warning\n      if (prop === '__isInsecureUserWarningProxy') {\n        return true\n      }\n\n      // Preventative check for common problematic symbols during cloning/inspection\n      // These symbols might be accessed by structuredClone or other internal mechanisms\n      if (typeof prop === 'symbol') {\n        const sProp = prop.toString()\n        if (\n          sProp === 'Symbol(Symbol.toPrimitive)' ||\n          sProp === 'Symbol(Symbol.toStringTag)' ||\n          sProp === 'Symbol(util.inspect.custom)' ||\n          sProp === 'Symbol(nodejs.util.inspect.custom)'\n        ) {\n          // Return the actual value for these symbols to allow proper inspection\n          return Reflect.get(target, prop, receiver)\n        }\n      }\n\n      // Emit warning on first property access\n      if (!suppressWarningRef.value \u0026\u0026 typeof prop === 'string') {\n        console.warn(\n          'Using the user object as returned from supabase.auth.getSession() or from some supabase.auth.onAuthStateChange() events could be insecure! This value comes directly from the storage medium (usually cookies on the server) and may not be authentic. Use supabase.auth.getUser() instead which authenticates the data by contacting the Supabase Auth server.'\n        )\n        suppressWarningRef.value = true\n      }\n\n      return Reflect.get(target, prop, receiver)\n    },\n  })\n}\n\n/**\n * Deep clones a JSON-serializable object using JSON.parse(JSON.stringify(obj)).\n * Note: Only works for JSON-safe data.\n */\nexport function deepClone\u003cT\u003e(obj: T): T {\n  return JSON.parse(JSON.stringify(obj))\n}\n","import { API_VERSIONS, API_VERSION_HEADER_NAME } from './constants'\nimport { expiresAt, looksLikeFetchResponse, parseResponseAPIVersion } from './helpers'\nimport {\n  AuthResponse,\n  AuthResponsePassword,\n  Session,\n  SSOResponse,\n  GenerateLinkProperties,\n  GenerateLinkResponse,\n  User,\n  UserResponse,\n  WeakPassword,\n} from './types'\nimport {\n  AuthApiError,\n  AuthRetryableFetchError,\n  AuthWeakPasswordError,\n  AuthUnknownError,\n  AuthSessionMissingError,\n} from './errors'\n\nexport type Fetch = typeof fetch\n\n/** Raw session data from GoTrue server response. */\ninterface GoTrueSessionData {\n  access_token?: string\n  refresh_token?: string\n  expires_in?: number\n  expires_at?: number\n  user?: User\n  [key: string]: any // server returns additional fields (token_type, provider_token, etc.) copied into Session\n}\n\n/** Raw session data that includes weak password info (password sign-in endpoints). */\ninterface GoTrueSessionPasswordData extends GoTrueSessionData {\n  weak_password?: WeakPassword\n}\n\n/** Raw user data — either `{ user: User }` or the User object itself. */\ninterface GoTrueUserData {\n  user?: User\n  [key: string]: any // data may BE the User directly (fallback path)\n}\n\n/** Raw generate-link data — link properties + User fields flattened into one object. */\ntype GoTrueGenerateLinkData = GenerateLinkProperties \u0026 Record\u003cstring, any\u003e\n\nexport interface FetchOptions {\n  headers?: {\n    [key: string]: string\n  }\n  noResolveJson?: boolean\n}\n\nexport interface FetchParameters {\n  signal?: AbortSignal\n}\n\nexport type RequestMethodType = 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE'\n\nconst _getErrorMessage = (err: unknown): string =\u003e {\n  if (typeof err === 'object' \u0026\u0026 err !== null) {\n    const e = err as Record\u003cstring, unknown\u003e\n    if (typeof e.msg === 'string') return e.msg\n    if (typeof e.message === 'string') return e.message\n    if (typeof e.error_description === 'string') return e.error_description\n    if (typeof e.error === 'string') return e.error\n  }\n  return JSON.stringify(err)\n}\n\n// 500, 501, 502, 503, 504: Standard server/gateway errors\n// 520-529, 530: Cloudflare-specific error codes (web server down, connection timed out, etc.)\n// These are infrastructure errors and should not cause session invalidation.\nconst NETWORK_ERROR_CODES = [\n  500, 501, 502, 503, 504, 520, 521, 522, 523, 524, 525, 526, 527, 528, 529, 530,\n]\n\nexport async function handleError(error: unknown) {\n  if (!looksLikeFetchResponse(error)) {\n    throw new AuthRetryableFetchError(_getErrorMessage(error), 0)\n  }\n\n  let data: any\n  try {\n    data = await error.json()\n  } catch (e) {\n    if (NETWORK_ERROR_CODES.includes(error.status)) {\n      // statusText can be empty — HTTP/2 has no reason phrase\n      throw new AuthRetryableFetchError(error.statusText || `HTTP ${error.status}`, error.status)\n    }\n    throw new AuthUnknownError(_getErrorMessage(e), e)\n  }\n\n  if (NETWORK_ERROR_CODES.includes(error.status)) {\n    // status in 500...599 range - server had an error, request might be retryed.\n    throw new AuthRetryableFetchError(_getErrorMessage(data), error.status)\n  }\n\n  let errorCode: string | undefined = undefined\n\n  const responseAPIVersion = parseResponseAPIVersion(error)\n  if (\n    responseAPIVersion \u0026\u0026\n    responseAPIVersion.getTime() \u003e= API_VERSIONS['2024-01-01'].timestamp \u0026\u0026\n    typeof data === 'object' \u0026\u0026\n    data \u0026\u0026\n    typeof data.code === 'string'\n  ) {\n    errorCode = data.code\n  } else if (typeof data === 'object' \u0026\u0026 data \u0026\u0026 typeof data.error_code === 'string') {\n    errorCode = data.error_code\n  }\n\n  if (!errorCode) {\n    // Legacy support for weak password errors, when there were no error codes\n    if (\n      typeof data === 'object' \u0026\u0026\n      data \u0026\u0026\n      typeof data.weak_password === 'object' \u0026\u0026\n      data.weak_password \u0026\u0026\n      Array.isArray(data.weak_password.reasons) \u0026\u0026\n      data.weak_password.reasons.length \u0026\u0026\n      data.weak_password.reasons.reduce((a: boolean, i: any) =\u003e a \u0026\u0026 typeof i === 'string', true)\n    ) {\n      throw new AuthWeakPasswordError(\n        _getErrorMessage(data),\n        error.status,\n        data.weak_password.reasons\n      )\n    }\n  } else if (errorCode === 'weak_password') {\n    throw new AuthWeakPasswordError(\n      _getErrorMessage(data),\n      error.status,\n      data.weak_password?.reasons || []\n    )\n  } else if (errorCode === 'session_not_found') {\n    // The `session_id` inside the JWT does not correspond to a row in the\n    // `sessions` table. This usually means the user has signed out, has been\n    // deleted, or their session has somehow been terminated.\n    throw new AuthSessionMissingError()\n  }\n\n  throw new AuthApiError(_getErrorMessage(data), error.status || 500, errorCode)\n}\n\nconst _getRequestParams = (\n  method: RequestMethodType,\n  options?: FetchOptions,\n  parameters?: FetchParameters,\n  body?: object\n) =\u003e {\n  const params: { [k: string]: any } = { method, headers: options?.headers || {} }\n\n  if (method === 'GET') {\n    return params\n  }\n\n  params.headers = { 'Content-Type': 'application/json;charset=UTF-8', ...options?.headers }\n  params.body = JSON.stringify(body)\n  return { ...params, ...parameters }\n}\n\ninterface GotrueRequestOptions extends FetchOptions {\n  jwt?: string\n  redirectTo?: string\n  body?: object\n  query?: { [key: string]: string }\n  /**\n   * Function that transforms api response from gotrue into a desirable / standardised format\n   */\n  xform?: (data: any) =\u003e any\n}\n\nexport async function _request(\n  fetcher: Fetch,\n  method: RequestMethodType,\n  url: string,\n  options?: GotrueRequestOptions\n) {\n  const headers = {\n    ...options?.headers,\n  }\n\n  if (!headers[API_VERSION_HEADER_NAME]) {\n    headers[API_VERSION_HEADER_NAME] = API_VERSIONS['2024-01-01'].name\n  }\n\n  if (options?.jwt) {\n    headers['Authorization'] = `Bearer ${options.jwt}`\n  }\n\n  const qs = options?.query ?? {}\n  if (options?.redirectTo) {\n    qs['redirect_to'] = options.redirectTo\n  }\n\n  const queryString = Object.keys(qs).length ? '?' + new URLSearchParams(qs).toString() : ''\n  const data = await _handleRequest(\n    fetcher,\n    method,\n    url + queryString,\n    {\n      headers,\n      noResolveJson: options?.noResolveJson,\n    },\n    {},\n    options?.body\n  )\n  return options?.xform ? options?.xform(data) : { data: { ...data }, error: null }\n}\n\nasync function _handleRequest(\n  fetcher: Fetch,\n  method: RequestMethodType,\n  url: string,\n  options?: FetchOptions,\n  parameters?: FetchParameters,\n  body?: object\n): Promise\u003cany\u003e {\n  const requestParams = _getRequestParams(method, options, parameters, body)\n\n  let result: Response\n\n  try {\n    result = await fetcher(url, {\n      ...requestParams,\n    })\n  } catch (e) {\n    // fetch failed (network / CORS / aborted request) — surfaced to the\n    // caller as a retryable error below. Deliberately not logged here: an\n    // aborted in-flight request (e.g. a superseded page navigation) is a\n    // transient condition, and logging the raw error pollutes the console.\n    throw new AuthRetryableFetchError(_getErrorMessage(e), 0)\n  }\n\n  if (!result.ok) {\n    await handleError(result)\n  }\n\n  if (options?.noResolveJson) {\n    return result\n  }\n\n  try {\n    return await result.json()\n  } catch (e) {\n    await handleError(e)\n  }\n}\n\nexport function _sessionResponse(data: GoTrueSessionData): AuthResponse {\n  let session = null\n  if (hasSession(data)) {\n    session = { ...data } as Session\n\n    if (!data.expires_at) {\n      session.expires_at = expiresAt(data.expires_in!)\n    }\n  }\n\n  // Some /verify responses (e.g. secure email_change first-confirmation) return\n  // only `{ msg, code }` with no user and no session. Treat those as null user.\n  const user: User | null = data.user ?? (typeof data?.id === 'string' ? (data as User) : null)\n  return { data: { session, user }, error: null }\n}\n\nexport function _sessionResponsePassword(data: GoTrueSessionPasswordData): AuthResponsePassword {\n  const response = _sessionResponse(data) as AuthResponsePassword\n\n  if (\n    !response.error \u0026\u0026\n    data.weak_password \u0026\u0026\n    typeof data.weak_password === 'object' \u0026\u0026\n    Array.isArray(data.weak_password.reasons) \u0026\u0026\n    data.weak_password.reasons.length \u0026\u0026\n    data.weak_password.message \u0026\u0026\n    typeof data.weak_password.message === 'string' \u0026\u0026\n    data.weak_password.reasons.reduce((a: boolean, i: unknown) =\u003e a \u0026\u0026 typeof i === 'string', true)\n  ) {\n    response.data.weak_password = data.weak_password\n  }\n\n  return response\n}\n\nexport function _userResponse(data: GoTrueUserData): UserResponse {\n  const user: User = data.user ?? (data as User)\n  return { data: { user }, error: null }\n}\n\nexport function _ssoResponse(data: Record\u003cstring, any\u003e): SSOResponse {\n  return { data, error: null } as SSOResponse\n}\n\nexport function _generateLinkResponse(data: GoTrueGenerateLinkData): GenerateLinkResponse {\n  const { action_link, email_otp, hashed_token, redirect_to, verification_type, ...rest } = data\n\n  const properties: GenerateLinkProperties = {\n    action_link,\n    email_otp,\n    hashed_token,\n    redirect_to,\n    verification_type,\n  }\n\n  const user = { ...rest } as User\n  return {\n    data: {\n      properties,\n      user,\n    },\n    error: null,\n  }\n}\n\nexport function _noResolveJsonResponse(data: Response): Response {\n  return data\n}\n\n/**\n * hasSession checks if the response object contains a valid session\n * @param data A response object\n * @returns true if a session is in the response\n */\nfunction hasSession(data: GoTrueSessionData): boolean {\n  return !!data.access_token \u0026\u0026 !!data.refresh_token \u0026\u0026 !!data.expires_in\n}\n","import { AuthError } from './errors'\nimport { Fetch } from './fetch'\nimport { EIP1193Provider, EthereumSignInInput, Hex } from './web3/ethereum'\nimport type { SolanaSignInInput, SolanaSignInOutput } from './web3/solana'\nimport {\n  ServerCredentialCreationOptions,\n  ServerCredentialRequestOptions,\n  WebAuthnApi,\n  WebAuthnError,\n} from './webauthn'\nimport type {\n  RegistrationResponseJSON,\n  AuthenticationResponseJSON,\n  ServerCredentialResponse,\n} from './webauthn'\nimport {\n  AuthenticationCredential,\n  PublicKeyCredentialCreationOptionsFuture,\n  PublicKeyCredentialRequestOptionsFuture,\n  RegistrationCredential,\n} from './webauthn.dom'\n\n/** One of the providers supported by GoTrue. Use the `custom:` prefix for custom OIDC providers (e.g. `custom:my-oidc-provider`). */\nexport type Provider =\n  | 'apple'\n  | 'azure'\n  | 'bitbucket'\n  | 'discord'\n  | 'facebook'\n  | 'figma'\n  | 'github'\n  | 'gitlab'\n  | 'google'\n  | 'kakao'\n  | 'keycloak'\n  | 'linkedin'\n  | 'linkedin_oidc'\n  | 'notion'\n  | 'slack'\n  | 'slack_oidc'\n  | 'spotify'\n  | 'twitch'\n  /** Uses OAuth 1.0a */\n  | 'twitter'\n  /** Uses OAuth 2.0 */\n  | 'x'\n  | 'workos'\n  | 'zoom'\n  | 'fly'\n  | `custom:${string}`\n\nexport type AuthChangeEventMFA = 'MFA_CHALLENGE_VERIFIED'\n\nexport type AuthChangeEvent =\n  | 'INITIAL_SESSION'\n  | 'PASSWORD_RECOVERY'\n  | 'SIGNED_IN'\n  | 'SIGNED_OUT'\n  | 'TOKEN_REFRESHED'\n  | 'USER_UPDATED'\n  | AuthChangeEventMFA\n\n/**\n * Provide your own global lock implementation instead of the default\n * implementation. The function should acquire a lock for the duration of the\n * `fn` async function, such that no other client instances will be able to\n * hold it at the same time.\n *\n * @experimental\n *\n * @param name Name of the lock to be acquired.\n * @param acquireTimeout If negative, no timeout should occur. If positive it\n *                       should throw an Error with an `isAcquireTimeout`\n *                       property set to true if the operation fails to be\n *                       acquired after this much time (ms).\n * @param fn The operation to execute when the lock is acquired.\n */\nexport type LockFunc = \u003cR\u003e(name: string, acquireTimeout: number, fn: () =\u003e Promise\u003cR\u003e) =\u003e Promise\u003cR\u003e\n\nexport type GoTrueClientOptions = {\n  /* The URL of the GoTrue server. */\n  url?: string\n  /* Any additional headers to send to the GoTrue server. */\n  headers?: { [key: string]: string }\n  /* Optional key name used for storing tokens in local storage. */\n  storageKey?: string\n  /**\n   * Set to \"true\" if you want to automatically detect OAuth grants in the URL and sign in the user.\n   * Set to \"false\" to disable automatic detection.\n   * Set to a function to provide custom logic for determining if a URL contains a Supabase auth callback.\n   * The function receives the current URL and parsed parameters, and should return true if the URL\n   * should be processed as a Supabase auth callback, or false to ignore it.\n   *\n   * This is useful when your app uses other OAuth providers (e.g., Facebook Login) that also return\n   * access_token in the URL fragment, which would otherwise be incorrectly intercepted by Supabase Auth.\n   *\n   * @example\n   * ```ts\n   * detectSessionInUrl: (url, params) =\u003e {\n   *   // Ignore Facebook OAuth redirects\n   *   if (url.pathname === '/facebook/redirect') return false\n   *   // Use default detection for other URLs\n   *   return Boolean(params.access_token || params.error_description)\n   * }\n   * ```\n   */\n  detectSessionInUrl?: boolean | ((url: URL, params: { [parameter: string]: string }) =\u003e boolean)\n  /* Set to \"true\" if you want to automatically refresh the token before expiring. */\n  autoRefreshToken?: boolean\n  /* Set to \"true\" if you want to automatically save the user session into local storage. If set to false, session will just be saved in memory. */\n  persistSession?: boolean\n  /* Provide your own local storage implementation to use instead of the browser's local storage. */\n  storage?: SupportedStorage\n  /**\n   * Stores the user object in a separate storage location from the rest of the session data. When non-null, `storage` will only store a JSON object containing the access and refresh token and some adjacent metadata, while `userStorage` will only contain the user object under the key `storageKey + '-user'`.\n   *\n   * When this option is set and cookie storage is used, `getSession()` and other functions that load a session from the cookie store might not return back a user. It's very important to always use `getUser()` to fetch a user object in those scenarios.\n   *\n   * @experimental\n   */\n  userStorage?: SupportedStorage\n  /* A custom fetch implementation. */\n  fetch?: Fetch\n  /* If set to 'pkce' PKCE flow. Defaults to the 'implicit' flow otherwise */\n  flowType?: AuthFlowType\n  /* If debug messages are emitted. Can be used to inspect the behavior of the library. If set to a function, the provided function will be used instead of `console.log()` to perform the logging. */\n  debug?: boolean | ((message: string, ...args: any[]) =\u003e void)\n  /**\n   * Provide your own locking mechanism based on the environment. By default\n   * the client coordinates refreshes itself (single-flight via\n   * `refreshingDeferred` + commit guard) and relies on the GoTrue server to\n   * resolve cross-tab refresh races. Passing a custom lock opts into a\n   * legacy path that wraps every auth operation in your supplied lock — this\n   * path is preserved for backwards compatibility (typically React Native\n   * `processLock` or Node multi-process setups).\n   *\n   * @deprecated Custom locks still work in v2.x for backwards compatibility.\n   * The legacy lock path will be removed in v3 — drop this option from your\n   * constructor options before upgrading.\n   */\n  lock?: LockFunc\n  /**\n   * Set to \"true\" if there is a custom authorization header set globally.\n   * @experimental\n   */\n  hasCustomAuthorizationHeader?: boolean\n  /**\n   * If there is an error with the query, throwOnError will reject the promise by\n   * throwing the error instead of returning it as part of a successful response.\n   */\n  throwOnError?: boolean\n  /**\n   * The maximum time in milliseconds to wait for acquiring the custom lock\n   * supplied via the `lock` option. Only consulted when a custom `lock` is\n   * passed — the default lockless path doesn't use this timeout.\n   *\n   * @default 5000\n   *\n   * @deprecated Only used by the legacy lock path. Will be removed in v3\n   * along with the `lock` option.\n   */\n  lockAcquireTimeout?: number\n\n  /**\n   * If true, skips automatic initialization in constructor. Useful for SSR\n   * contexts where initialization timing must be controlled to prevent race\n   * conditions with HTTP response generation.\n   *\n   * @default false\n   */\n  skipAutoInitialize?: boolean\n\n  /**\n   * Opt-in flags for experimental features. These APIs may change without\n   * notice and are disabled by default.\n   *\n   * @experimental\n   */\n  experimental?: ExperimentalFeatureFlags\n}\n\nexport type ExperimentalFeatureFlags = {\n  /**\n   * Previously required to enable the passkey API (`auth.signInWithPasskey()`,\n   * `auth.registerPasskey()`, `auth.passkey.*`, `auth.admin.passkey.*`).\n   *\n   * Passkeys are now enabled by default and this flag is ignored. It is kept\n   * only so existing code that sets it keeps compiling and will be removed in\n   * the next major version.\n   *\n   * @deprecated Passkeys are enabled by default; this flag has no effect.\n   */\n  passkey?: boolean\n  /**\n   * Enables MFA recovery codes support:\n   *   - `auth.mfa.recoveryCodes.*`\n   *\n   * Defaults to `false`. Calling any recovery codes method while this flag is\n   * disabled throws a descriptive error at call time.\n   *\n   * @experimental\n   */\n  recoveryCodes?: boolean\n  /**\n   * Appends a reserved `sb_flow_id` query parameter to `redirectTo` URLs on\n   * PKCE flows. The parameter round-trips through the auth server back to\n   * your callback URL, where the client uses it to select the code verifier\n   * created by that specific flow — so multiple sign-in flows (e.g. two OAuth\n   * providers started in different tabs) can be in flight at the same time\n   * without overwriting each other.\n   *\n   * Before enabling, make sure your [redirect URL allow\n   * list](https://supabase.com/docs/guides/auth/redirect-urls) tolerates the\n   * extra query parameter: allow-list entries are matched against the full\n   * URL including the query string, so an exact entry (no wildcard) stops\n   * matching once the parameter is appended and the redirect falls back to\n   * your Site URL. Redirects to the Site URL's own origin always pass.\n   *\n   * Defaults to `false`. Without it, concurrent flows still keep separate\n   * verifiers in storage, but no flow id travels through the redirect: to\n   * match a callback to its verifier you must carry the `flowId` returned by\n   * `signInWithOAuth` (or `linkIdentity`) through your own channel and pass\n   * it to `exchangeCodeForSession`. Flows that offer no way to obtain the\n   * flow id (email OTP, password recovery, sign-up confirmation) can only be\n   * correlated via this flag.\n   */\n  appendPkceFlowIdToRedirects?: boolean\n}\n\nconst WeakPasswordReasons = ['length', 'characters', 'pwned'] as const\n\nexport type WeakPasswordReasons = (typeof WeakPasswordReasons)[number]\nexport type WeakPassword = {\n  reasons: WeakPasswordReasons[]\n  message: string\n}\n\n/**\n * Resolve mapped types and show the derived keys and their types when hovering in\n * VS Code, instead of just showing the names those mapped types are defined with.\n */\nexport type Prettify\u003cT\u003e = T extends Function ? T : { [K in keyof T]: T[K] }\n\n/**\n * A stricter version of TypeScript's Omit that only allows omitting keys that actually exist.\n * This prevents typos and ensures type safety at compile time.\n * Unlike regular Omit, this will error if you try to omit a non-existent key.\n */\nexport type StrictOmit\u003cT, K extends keyof T\u003e = Omit\u003cT, K\u003e\n\n/**\n * a shared result type that encapsulates errors instead of throwing them, allows you to optionally specify the ErrorType\n */\nexport type RequestResult\u003cT, ErrorType extends Error = AuthError\u003e =\n  | {\n      data: T\n      error: null\n    }\n  | {\n      data: null\n      error: Error extends AuthError ? AuthError : ErrorType\n    }\n\n/**\n * similar to RequestResult except it allows you to destructure the possible shape of the success response\n *  {@link RequestResult}\n */\nexport type RequestResultSafeDestructure\u003cT\u003e =\n  | { data: T; error: null }\n  | {\n      data: T extends object ? { [K in keyof T]: null } : null\n      error: AuthError\n    }\n\nexport type AuthResponse = RequestResultSafeDestructure\u003c{\n  user: User | null\n  session: Session | null\n}\u003e\n\nexport type AuthResponsePassword = RequestResultSafeDestructure\u003c{\n  user: User | null\n  session: Session | null\n  weak_password?: WeakPassword | null\n}\u003e\n\n/**\n * AuthOtpResponse is returned when OTP is used.\n *\n * {@link AuthResponse}\n */\nexport type AuthOtpResponse = RequestResultSafeDestructure\u003c{\n  user: null\n  session: null\n  messageId?: string | null\n}\u003e\n\nexport type AuthTokenResponse = RequestResultSafeDestructure\u003c{\n  user: User\n  session: Session\n}\u003e\n\nexport type AuthTokenResponsePassword = RequestResultSafeDestructure\u003c{\n  user: User\n  session: Session\n  weakPassword?: WeakPassword\n}\u003e\n\nexport type OAuthResponse =\n  | {\n      data: {\n        provider: Provider\n        url: string\n        /**\n         * Identifier of the PKCE flow started by this call, usable as the\n         * `flowId` option of {@link GoTrueClient#exchangeCodeForSession} to\n         * select this flow's code verifier when several flows are in flight.\n         * `null` on the implicit flow. The id is a selector for a verifier\n         * kept in storage — it is not a secret and never contains the\n         * verifier itself.\n         *\n         * Always set at runtime; optional in the type so existing code that\n         * constructs `OAuthResponse` values (e.g. test mocks) keeps\n         * compiling.\n         */\n        flowId?: string | null\n      }\n      error: null\n    }\n  | {\n      data: {\n        provider: Provider\n        url: null\n        flowId?: string | null\n      }\n      error: AuthError\n    }\n\nexport type SSOResponse = RequestResult\u003c{\n  /**\n   * URL to open in a browser which will complete the sign-in flow by\n   * taking the user to the identity provider's authentication flow.\n   *\n   * On browsers you can set the URL to `window.location.href` to take\n   * the user to the authentication flow.\n   */\n  url: string\n}\u003e\n\nexport type UserResponse = RequestResultSafeDestructure\u003c{\n  user: User\n}\u003e\n\nexport interface Session {\n  /**\n   * The oauth provider token. If present, this can be used to make external API requests to the oauth provider used.\n   */\n  provider_token?: string | null\n  /**\n   * The oauth provider refresh token. If present, this can be used to refresh the provider_token via the oauth provider's API.\n   * Not all oauth providers return a provider refresh token. If the provider_refresh_token is missing, please refer to the oauth provider's documentation for information on how to obtain the provider refresh token.\n   */\n  provider_refresh_token?: string | null\n  /**\n   * The access token jwt. It is recommended to set the JWT_EXPIRY to a shorter expiry value.\n   */\n  access_token: string\n  /**\n   * A one-time used refresh token that never expires.\n   */\n  refresh_token: string\n  /**\n   * The number of seconds until the token expires (since it was issued). Returned when a login is confirmed.\n   */\n  expires_in: number\n  /**\n   * A timestamp of when the token will expire. Returned when a login is confirmed.\n   */\n  expires_at?: number\n  token_type: 'bearer'\n\n  /**\n   * When using a separate user storage, accessing properties of this object will throw an error.\n   */\n  user: User\n}\n\nconst AMRMethods = [\n  'password',\n  'otp',\n  'oauth',\n  'totp',\n  'mfa/totp',\n  'mfa/phone',\n  'mfa/webauthn',\n  'mfa/recovery_code',\n  'anonymous',\n  'sso/saml',\n  'magiclink',\n  'web3',\n  'oauth_provider/authorization_code',\n] as const\n\nexport type AMRMethod = (typeof AMRMethods)[number] | (string \u0026 {})\n\n/**\n * An authentication method reference (AMR) entry.\n *\n * An entry designates what method was used by the user to verify their\n * identity and at what time.\n *\n * Note: Custom access token hooks can return AMR claims as either:\n * - An array of AMREntry objects (detailed format with timestamps)\n * - An array of strings (RFC-8176 compliant format)\n *\n * @see {@link GoTrueMFAApi#getAuthenticatorAssuranceLevel}.\n */\nexport interface AMREntry {\n  /** Authentication method name. */\n  method: AMRMethod\n\n  /**\n   * Timestamp when the method was successfully used. Represents number of\n   * seconds since 1st January 1970 (UNIX epoch) in UTC.\n   */\n  timestamp: number\n}\n\nexport interface UserIdentity {\n  id: string\n  user_id: string\n  identity_data?: {\n    [key: string]: any\n  }\n  identity_id: string\n  provider: string\n  created_at?: string\n  last_sign_in_at?: string\n  updated_at?: string\n}\n\nconst FactorTypes = ['totp', 'phone', 'webauthn', 'recovery_code'] as const\n\n/**\n * Type of factor. `totp`, `phone`, `webauthn` and `recovery_code` are supported.\n *\n * `recovery_code` factors are managed through {@link AuthMFARecoveryCodesApi}\n * (`mfa.recoveryCodes.*`) and cannot be used with `enroll()`, `challenge()`,\n * `verify()` or `unenroll()`.\n */\nexport type FactorType = (typeof FactorTypes)[number]\n\nconst FactorVerificationStatuses = ['verified', 'unverified'] as const\n\n/**\n * The verification status of the factor, default is `unverified` after `.enroll()`, then `verified` after the user verifies it with `.verify()`\n */\ntype FactorVerificationStatus = (typeof FactorVerificationStatuses)[number]\n\n/**\n * A MFA factor.\n *\n * @see {@link GoTrueMFAApi#enroll}\n * @see {@link GoTrueMFAApi#listFactors}\n * @see {@link GoTrueAdminMFAApi#listFactors}\n */\nexport type Factor\u003c\n  Type extends FactorType = FactorType,\n  Status extends FactorVerificationStatus = (typeof FactorVerificationStatuses)[number],\n\u003e = {\n  /** ID of the factor. */\n  id: string\n\n  /** Friendly name of the factor, useful to disambiguate between multiple factors. */\n  friendly_name?: string\n\n  /**\n   * Type of factor. `totp`, `phone`, `webauthn` and `recovery_code` are supported.\n   */\n  factor_type: Type\n\n  /**\n   * The verification status of the factor, default is `unverified` after `.enroll()`, then `verified` after the user verifies it with `.verify()`\n   */\n  status: Status\n\n  created_at: string\n  updated_at: string\n  last_challenged_at?: string\n}\n\nexport interface UserAppMetadata {\n  /**\n   * The first provider that the user used to sign up with.\n   */\n  provider?: string\n  /**\n   * A list of all providers that the user has linked to their account.\n   */\n  providers?: string[]\n  [key: string]: any\n}\n\nexport interface UserMetadata {\n  [key: string]: any\n}\n\nexport interface User {\n  id: string\n  app_metadata: UserAppMetadata\n  user_metadata: UserMetadata\n  aud: string\n  confirmation_sent_at?: string\n  recovery_sent_at?: string\n  email_change_sent_at?: string\n  new_email?: string\n  new_phone?: string\n  invited_at?: string\n  action_link?: string\n  email?: string\n  phone?: string\n  created_at: string\n  confirmed_at?: string\n  email_confirmed_at?: string\n  phone_confirmed_at?: string\n  last_sign_in_at?: string\n  role?: string\n  updated_at?: string\n  identities?: UserIdentity[]\n  is_anonymous?: boolean\n  is_sso_user?: boolean\n  factors?: (Factor\u003cFactorType, 'verified'\u003e | Factor\u003cFactorType, 'unverified'\u003e)[]\n  deleted_at?: string\n  banned_until?: string\n}\n\nexport interface UserAttributes {\n  /**\n   * The user's current password\n   *\n   * This is only ever present when the user is resetting\n   * their password and GOTRUE_SECURITY_UPDATE_PASSWORD_REQUIRE_CURRENT_PASSWORD is true.\n   *\n   */\n  current_password?: string\n\n  /**\n   * The user's email.\n   */\n  email?: string\n\n  /**\n   * The user's phone.\n   */\n  phone?: string\n\n  /**\n   * The user's password.\n   */\n  password?: string\n\n  /**\n   * The nonce sent for reauthentication if the user's password is to be updated.\n   *\n   * Call reauthenticate() to obtain the nonce first.\n   */\n  nonce?: string\n\n  /**\n   * A custom data object to store the user's metadata. This maps to the `auth.users.raw_user_meta_data` column.\n   *\n   * The `data` should be a JSON object that includes user-specific info, such as their first and last name.\n   *\n   */\n  data?: object\n}\n\nexport interface AdminUserAttributes extends Omit\u003cUserAttributes, 'data'\u003e {\n  /**\n   * A custom data object to store the user's metadata. This maps to the `auth.users.raw_user_meta_data` column.\n   *\n   *\n   * The `user_metadata` should be a JSON object that includes user-specific info, such as their first and last name.\n   *\n   * Note: When using the GoTrueAdminApi and wanting to modify a user's metadata,\n   * this attribute is used instead of UserAttributes data.\n   *\n   */\n  user_metadata?: object\n\n  /**\n   * A custom data object to store the user's application specific metadata. This maps to the `auth.users.app_metadata` column.\n   *\n   * Only a service role can modify.\n   *\n   * The `app_metadata` should be a JSON object that includes app-specific info, such as identity providers, roles, and other\n   * access control information.\n   */\n  app_metadata?: object\n\n  /**\n   * Sets the user's email as confirmed when true, or unconfirmed when false.\n   *\n   * Only a service role can modify.\n   */\n  email_confirm?: boolean\n\n  /**\n   * Sets the user's phone as confirmed when true, or unconfirmed when false.\n   *\n   * Only a service role can modify.\n   */\n  phone_confirm?: boolean\n\n  /**\n   * Determines how long a user is banned for.\n   *\n   * The format for the ban duration follows a strict sequence of decimal numbers with a unit suffix.\n   * Valid time units are \"ns\", \"us\" (or \"µs\"), \"ms\", \"s\", \"m\", \"h\".\n   *\n   * For example, some possible durations include: '300ms', '2h45m'.\n   *\n   * Setting the ban duration to 'none' lifts the ban on the user.\n   */\n  ban_duration?: string | 'none'\n\n  /**\n   * The `role` claim set in the user's access token JWT.\n   *\n   * When a user signs up, this role is set to `authenticated` by default. You should only modify the `role` if you need to provision several levels of admin access that have different permissions on individual columns in your database.\n   *\n   * Setting this role to `service_role` is not recommended as it grants the user admin privileges.\n   */\n  role?: string\n\n  /**\n   * The `password_hash` for the user's password.\n   *\n   * Allows you to specify a password hash for the user. This is useful for migrating a user's password hash from another service.\n   *\n   * Supports bcrypt, scrypt (firebase), and argon2 password hashes.\n   */\n  password_hash?: string\n\n  /**\n   * The `id` for the user.\n   *\n   * Allows you to overwrite the default `id` set for the user.\n   */\n  id?: string\n}\n\nexport interface Subscription {\n  /**\n   * A unique identifier for this subscription, set by the client.\n   * This is an internal identifier used for managing callbacks and should not be\n   * relied upon by application code. Use the unsubscribe() method to remove listeners.\n   */\n  id: string | symbol\n  /**\n   * The function to call every time there is an event. eg: (eventName) =\u003e {}\n   */\n  callback: (event: AuthChangeEvent, session: Session | null) =\u003e void\n  /**\n   * Call this to remove the listener.\n   */\n  unsubscribe: () =\u003e void\n}\n\nexport type SignInAnonymouslyCredentials = {\n  options?: {\n    /**\n     * A custom data object to store the user's metadata. This maps to the `auth.users.raw_user_meta_data` column.\n     *\n     * The `data` should be a JSON object that includes user-specific info, such as their first and last name.\n     */\n    data?: object\n    /** Verification token received when the user completes the captcha on the site. */\n    captchaToken?: string\n  }\n}\n\nexport type SignUpWithPasswordCredentials = PasswordCredentialsBase \u0026 {\n  options?: {\n    emailRedirectTo?: string // only for email\n    data?: object\n    captchaToken?: string\n    channel?: 'sms' | 'whatsapp' // only for phone\n  }\n}\n\ntype PasswordCredentialsBase =\n  | { email: string; password: string }\n  | { phone: string; password: string }\n\nexport type SignInWithPasswordCredentials = PasswordCredentialsBase \u0026 {\n  options?: {\n    captchaToken?: string\n  }\n}\n\nexport type SignInWithPasswordlessCredentials =\n  | {\n      /** The user's email address. */\n      email: string\n      options?: {\n        /** The redirect url embedded in the email link */\n        emailRedirectTo?: string\n        /** If set to false, this method will not create a new user. Defaults to true. */\n        shouldCreateUser?: boolean\n        /**\n         * A custom data object to store the user's metadata. This maps to the `auth.users.raw_user_meta_data` column.\n         *\n         * The `data` should be a JSON object that includes user-specific info, such as their first and last name.\n         */\n        data?: object\n        /** Verification token received when the user completes the captcha on the site. */\n        captchaToken?: string\n      }\n    }\n  | {\n      /** The user's phone number. */\n      phone: string\n      options?: {\n        /** If set to false, this method will not create a new user. Defaults to true. */\n        shouldCreateUser?: boolean\n        /**\n         * A custom data object to store the user's metadata. This maps to the `auth.users.raw_user_meta_data` column.\n         *\n         * The `data` should be a JSON object that includes user-specific info, such as their first and last name.\n         */\n        data?: object\n        /** Verification token received when the user completes the captcha on the site. */\n        captchaToken?: string\n        /** Messaging channel to use (e.g. whatsapp or sms) */\n        channel?: 'sms' | 'whatsapp'\n      }\n    }\n\nexport type AuthFlowType = 'implicit' | 'pkce' | (string \u0026 {})\nexport type SignInWithOAuthCredentials = {\n  /** One of the providers supported by GoTrue. */\n  provider: Provider\n  options?: {\n    /** A URL to send the user to after they are confirmed. */\n    redirectTo?: string\n    /** A space-separated list of scopes granted to the OAuth application. */\n    scopes?: string\n    /** An object of query params */\n    queryParams?: { [key: string]: string }\n    /** If set to true does not immediately redirect the current browser context to visit the OAuth authorization page for the provider. */\n    skipBrowserRedirect?: boolean\n  }\n}\n\nexport type SignInWithIdTokenCredentials = {\n  /** Provider name or OIDC `iss` value identifying which provider should be used to verify the provided token. Supported names: `google`, `apple`, `azure`, `facebook`, `kakao`. Use the `custom:` prefix for custom OIDC providers (e.g. `custom:my-oidc-provider`). */\n  provider: 'google' | 'apple' | 'azure' | 'facebook' | 'kakao' | `custom:${string}` | (string \u0026 {})\n  /** OIDC ID token issued by the specified provider. The `iss` claim in the ID token must match the supplied provider. Some ID tokens contain an `at_hash` which require that you provide an `access_token` value to be accepted properly. If the token contains a `nonce` claim you must supply the nonce used to obtain the ID token. */\n  token: string\n  /** If the ID token contains an `at_hash` claim, then the hash of this value is compared to the value in the ID token. */\n  access_token?: string\n  /** If the ID token contains a `nonce` claim, then the hash of this value is compared to the value in the ID token. */\n  nonce?: string\n  options?: {\n    /** Verification token received when the user completes the captcha on the site. */\n    captchaToken?: string\n  }\n}\n\nexport type SolanaWallet = {\n  signIn?: (...inputs: SolanaSignInInput[]) =\u003e Promise\u003cSolanaSignInOutput | SolanaSignInOutput[]\u003e\n  publicKey?: {\n    toBase58: () =\u003e string\n  } | null\n\n  signMessage?: (message: Uint8Array, encoding?: 'utf8' | string) =\u003e Promise\u003cUint8Array\u003e | undefined\n}\n\nexport type SolanaWeb3Credentials =\n  | {\n      chain: 'solana'\n\n      /** Wallet interface to use. If not specified will default to `window.solana`. */\n      wallet?: SolanaWallet\n\n      /** Optional statement to include in the Sign in with Solana message. Must not include new line characters. Most wallets like Phantom **require specifying a statement!** */\n      statement?: string\n\n      options?: {\n        /** URL to use with the wallet interface. Some wallets do not allow signing a message for URLs different from the current page. */\n        url?: string\n\n        /** Verification token received when the user completes the captcha on the site. */\n        captchaToken?: string\n\n        signInWithSolana?: Partial\u003c\n          Omit\u003cSolanaSignInInput, 'version' | 'chain' | 'domain' | 'uri' | 'statement'\u003e\n        \u003e\n      }\n    }\n  | {\n      chain: 'solana'\n\n      /** Sign in with Solana compatible message. Must include `Issued At`, `URI` and `Version`. */\n      message: string\n\n      /** Ed25519 signature of the message. */\n      signature: Uint8Array\n\n      options?: {\n        /** Verification token received when the user completes the captcha on the site. */\n        captchaToken?: string\n      }\n    }\n\nexport type EthereumWallet = EIP1193Provider\n\nexport type EthereumWeb3Credentials =\n  | {\n      chain: 'ethereum'\n\n      /** Wallet interface to use. If not specified will default to `window.ethereum`. */\n      wallet?: EthereumWallet\n\n      /** Optional statement to include in the Sign in with Ethereum message. Must not include new line characters. Most wallets like Phantom **require specifying a statement!** */\n      statement?: string\n\n      options?: {\n        /** URL to use with the wallet interface. Some wallets do not allow signing a message for URLs different from the current page. */\n        url?: string\n\n        /** Verification token received when the user completes the captcha on the site. */\n        captchaToken?: string\n\n        signInWithEthereum?: Partial\u003c\n          Omit\u003cEthereumSignInInput, 'version' | 'domain' | 'uri' | 'statement'\u003e\n        \u003e\n      }\n    }\n  | {\n      chain: 'ethereum'\n\n      /** Sign in with Ethereum compatible message. Must include `Issued At`, `URI` and `Version`. */\n      message: string\n\n      /** Ethereum curve (secp256k1) signature of the message. */\n      signature: Hex\n\n      options?: {\n        /** Verification token received when the user completes the captcha on the site. */\n        captchaToken?: string\n      }\n    }\n\nexport type Web3Credentials = SolanaWeb3Credentials | EthereumWeb3Credentials\n\nexport type VerifyOtpParams = VerifyMobileOtpParams | VerifyEmailOtpParams | VerifyTokenHashParams\nexport interface VerifyMobileOtpParams {\n  /** The user's phone number. */\n  phone: string\n  /** The otp sent to the user's phone number. */\n  token: string\n  /** The user's verification type. */\n  type: MobileOtpType\n  options?: {\n    /** A URL to send the user to after they are confirmed. */\n    redirectTo?: string\n\n    /**\n     * Verification token received when the user completes the captcha on the site.\n     *\n     * @deprecated\n     */\n    captchaToken?: string\n  }\n}\nexport interface VerifyEmailOtpParams {\n  /** The user's email address. */\n  email: string\n  /** The otp sent to the user's email address. */\n  token: string\n  /** The user's verification type. */\n  type: EmailOtpType\n  options?: {\n    /** A URL to send the user to after they are confirmed. */\n    redirectTo?: string\n\n    /** Verification token received when the user completes the captcha on the site.\n     *\n     * @deprecated\n     */\n    captchaToken?: string\n  }\n}\n\nexport interface VerifyTokenHashParams {\n  /** The token hash used in an email link */\n  token_hash: string\n\n  /** The user's verification type. */\n  type: EmailOtpType\n}\n\nexport type MobileOtpType = 'sms' | 'phone_change' | (string \u0026 {})\nexport type EmailOtpType =\n  | 'signup'\n  | 'invite'\n  | 'magiclink'\n  | 'recovery'\n  | 'email_change'\n  | 'email'\n  | (string \u0026 {})\n\nexport type ResendParams =\n  | {\n      type: Extract\u003cEmailOtpType, 'signup' | 'email_change'\u003e\n      email: string\n      options?: {\n        /** A URL to send the user to after they have signed-in. */\n        emailRedirectTo?: string\n        /** Verification token received when the user completes the captcha on the site. */\n        captchaToken?: string\n      }\n    }\n  | {\n      type: Extract\u003cMobileOtpType, 'sms' | 'phone_change'\u003e\n      phone: string\n      options?: {\n        /** Verification token received when the user completes the captcha on the site. */\n        captchaToken?: string\n      }\n    }\n\nexport type SignInWithSSO =\n  | {\n      /** UUID of the SSO provider to invoke single-sign on to. */\n      providerId: string\n\n      options?: {\n        /** A URL to send the user to after they have signed-in. */\n        redirectTo?: string\n        /** Verification token received when the user completes the captcha on the site. */\n        captchaToken?: string\n        /**\n         * If set to true, the redirect will not happen on the client side.\n         * This parameter is used when you wish to handle the redirect yourself.\n         * Defaults to false.\n         */\n        skipBrowserRedirect?: boolean\n      }\n    }\n  | {\n      /** Domain name of the organization for which to invoke single-sign on. */\n      domain: string\n\n      options?: {\n        /** A URL to send the user to after they have signed-in. */\n        redirectTo?: string\n        /** Verification token received when the user completes the captcha on the site. */\n        captchaToken?: string\n        /**\n         * If set to true, the redirect will not happen on the client side.\n         * This parameter is used when you wish to handle the redirect yourself.\n         * Defaults to false.\n         */\n        skipBrowserRedirect?: boolean\n      }\n    }\n\nexport type GenerateSignupLinkParams = {\n  type: 'signup'\n  email: string\n  password: string\n  options?: Pick\u003cGenerateLinkOptions, 'data' | 'redirectTo'\u003e\n}\n\nexport type GenerateInviteOrMagiclinkParams = {\n  type: 'invite' | 'magiclink'\n  /** The user's email */\n  email: string\n  options?: Pick\u003cGenerateLinkOptions, 'data' | 'redirectTo'\u003e\n}\n\nexport type GenerateRecoveryLinkParams = {\n  type: 'recovery'\n  /** The user's email */\n  email: string\n  options?: Pick\u003cGenerateLinkOptions, 'redirectTo'\u003e\n}\n\nexport type GenerateEmailChangeLinkParams = {\n  type: 'email_change_current' | 'email_change_new'\n  /** The user's email */\n  email: string\n  /**\n   * The user's new email. Only required if type is 'email_change_current' or 'email_change_new'.\n   */\n  newEmail: string\n  options?: Pick\u003cGenerateLinkOptions, 'redirectTo'\u003e\n}\n\nexport interface GenerateLinkOptions {\n  /**\n   * A custom data object to store the user's metadata. This maps to the `auth.users.raw_user_meta_data` column.\n   *\n   * The `data` should be a JSON object that includes user-specific info, such as their first and last name.\n   */\n  data?: object\n  /** The URL which will be appended to the email link generated. */\n  redirectTo?: string\n}\n\nexport type GenerateLinkParams =\n  | GenerateSignupLinkParams\n  | GenerateInviteOrMagiclinkParams\n  | GenerateRecoveryLinkParams\n  | GenerateEmailChangeLinkParams\n\nexport type GenerateLinkResponse = RequestResultSafeDestructure\u003c{\n  properties: GenerateLinkProperties\n  user: User\n}\u003e\n\n/** The properties related to the email link generated  */\nexport type GenerateLinkProperties = {\n  /**\n   * The email link to send to the user.\n   * The action_link follows the following format: auth/v1/verify?type={verification_type}\u0026token={hashed_token}\u0026redirect_to={redirect_to}\n   * */\n  action_link: string\n  /**\n   * The raw email OTP.\n   * You should send this in the email if you want your users to verify using an OTP instead of the action link.\n   * */\n  email_otp: string\n  /**\n   * The hashed token appended to the action link.\n   * */\n  hashed_token: string\n  /** The URL appended to the action link. */\n  redirect_to: string\n  /** The verification type that the email link is associated to. */\n  verification_type: GenerateLinkType\n}\n\nexport type GenerateLinkType =\n  | 'signup'\n  | 'invite'\n  | 'magiclink'\n  | 'recovery'\n  | 'email_change_current'\n  | 'email_change_new'\n\nexport type MFAEnrollParams = MFAEnrollTOTPParams | MFAEnrollPhoneParams | MFAEnrollWebauthnParams\n\nexport type MFAUnenrollParams = {\n  /** ID of the factor being unenrolled. */\n  factorId: string\n}\n\ntype MFAVerifyParamsBase = {\n  /** ID of the factor being verified. Returned in enroll(). */\n  factorId: string\n  /** ID of the challenge being verified. Returned in challenge(). */\n  challengeId: string\n}\n\ntype MFAVerifyTOTPParamFields = {\n  /** Verification code provided by the user. */\n  code: string\n}\n\nexport type MFAVerifyTOTPParams = MFAVerifyParamsBase \u0026 MFAVerifyTOTPParamFields\n\ntype MFAVerifyPhoneParamFields = MFAVerifyTOTPParamFields\n\nexport type MFAVerifyPhoneParams = MFAVerifyParamsBase \u0026 MFAVerifyPhoneParamFields\n\ntype MFAVerifyWebauthnParamFieldsBase = {\n  /** Relying party ID */\n  rpId: string\n  /** Relying party origins */\n  rpOrigins?: string[]\n}\n\ntype MFAVerifyWebauthnCredentialParamFields\u003cT extends 'create' | 'request' = 'create' | 'request'\u003e =\n  {\n    /** Operation type */\n    type: T\n    /** Creation response from the authenticator (for enrollment/unverified factors) */\n    credential_response: T extends 'create' ? RegistrationCredential : AuthenticationCredential\n  }\n\n/**\n * WebAuthn-specific fields for MFA verification.\n * Supports both credential creation (registration) and request (authentication) flows.\n * @template T - Type of WebAuthn operation: 'create' for registration, 'request' for authentication\n */\nexport type MFAVerifyWebauthnParamFields\u003cT extends 'create' | 'request' = 'create' | 'request'\u003e = {\n  webauthn: MFAVerifyWebauthnParamFieldsBase \u0026 MFAVerifyWebauthnCredentialParamFields\u003cT\u003e\n}\n\n/**\n * Parameters for WebAuthn MFA verification.\n * Used to verify WebAuthn credentials after challenge.\n * @template T - Type of WebAuthn operation: 'create' for registration, 'request' for authentication\n * @see {@link https://w3c.github.io/webauthn/#sctn-verifying-assertion W3C WebAuthn Spec - Verifying an Authentication Assertion}\n */\nexport type MFAVerifyWebauthnParams\u003cT extends 'create' | 'request' = 'create' | 'request'\u003e =\n  MFAVerifyParamsBase \u0026 MFAVerifyWebauthnParamFields\u003cT\u003e\n\nexport type MFAVerifyParams = MFAVerifyTOTPParams | MFAVerifyPhoneParams | MFAVerifyWebauthnParams\n\ntype MFAChallengeParamsBase = {\n  /** ID of the factor to be challenged. Returned in enroll(). */\n  factorId: string\n}\n\nconst MFATOTPChannels = ['sms', 'whatsapp'] as const\nexport type MFATOTPChannel = (typeof MFATOTPChannels)[number]\n\nexport type MFAChallengeTOTPParams = MFAChallengeParamsBase\n\ntype MFAChallengePhoneParamFields\u003cChannel extends MFATOTPChannel = MFATOTPChannel\u003e = {\n  /** Messaging channel to use (e.g. whatsapp or sms). Only relevant for phone factors */\n  channel: Channel\n}\n\nexport type MFAChallengePhoneParams = MFAChallengeParamsBase \u0026 MFAChallengePhoneParamFields\n\n/** WebAuthn parameters for WebAuthn factor challenge */\ntype MFAChallengeWebauthnParamFields = {\n  webauthn: {\n    /** Relying party ID */\n    rpId: string\n    /** Relying party origins*/\n    rpOrigins?: string[]\n  }\n}\n\n/**\n * Parameters for initiating a WebAuthn MFA challenge.\n * Includes Relying Party information needed for WebAuthn ceremonies.\n * @see {@link https://w3c.github.io/webauthn/#sctn-rp-operations W3C WebAuthn Spec - Relying Party Operations}\n */\nexport type MFAChallengeWebauthnParams = MFAChallengeParamsBase \u0026 MFAChallengeWebauthnParamFields\n\nexport type MFAChallengeParams =\n  | MFAChallengeTOTPParams\n  | MFAChallengePhoneParams\n  | MFAChallengeWebauthnParams\n\ntype MFAChallengeAndVerifyParamsBase = Omit\u003cMFAVerifyParamsBase, 'challengeId'\u003e\n\ntype MFAChallengeAndVerifyTOTPParamFields = MFAVerifyTOTPParamFields\n\ntype MFAChallengeAndVerifyTOTPParams = MFAChallengeAndVerifyParamsBase \u0026\n  MFAChallengeAndVerifyTOTPParamFields\n\nexport type MFAChallengeAndVerifyParams = MFAChallengeAndVerifyTOTPParams\n\n/**\n * Data returned after successful MFA verification.\n * Contains new session tokens and updated user information.\n */\nexport type AuthMFAVerifyResponseData = {\n  /** New access token (JWT) after successful verification. */\n  access_token: string\n\n  /** Type of token, always `bearer`. */\n  token_type: 'bearer'\n\n  /** Number of seconds in which the access token will expire. */\n  expires_in: number\n\n  /** Refresh token you can use to obtain new access tokens when expired. */\n  refresh_token: string\n\n  /** Updated user profile. */\n  user: User\n}\n\n/**\n * Response type for MFA verification operations.\n * Returns session tokens on successful verification.\n */\nexport type AuthMFAVerifyResponse = RequestResult\u003cAuthMFAVerifyResponseData\u003e\n\nexport type AuthMFAEnrollResponse =\n  | AuthMFAEnrollTOTPResponse\n  | AuthMFAEnrollPhoneResponse\n  | AuthMFAEnrollWebauthnResponse\n\nexport type AuthMFAUnenrollResponse = RequestResult\u003c{\n  /** ID of the factor that was successfully unenrolled. */\n  id: string\n}\u003e\n\n/**\n * Parameters for generating a set of MFA recovery codes.\n *\n * @see {@link AuthMFARecoveryCodesApi#generate}\n *\n * @experimental\n */\nexport type MFARecoveryCodesGenerateParams = {\n  /**\n   * Friendly name for the recovery codes factor, as shown in `user.factors`\n   * and `mfa.listFactors()`. Must be unique among the user's factors. The\n   * server defaults it to `Recovery codes` when omitted.\n   */\n  friendlyName?: string\n}\n\n/**\n * Parameters for verifying a single MFA recovery code.\n *\n * @see {@link AuthMFARecoveryCodesApi#verify}\n *\n * @experimental\n */\nexport type MFARecoveryCodesVerifyParams = {\n  /**\n   * One of the user's unused recovery codes, exactly as entered by the user.\n   * Letter case, whitespace and `-` separators are ignored by the server.\n   * Each code can be used only once.\n   */\n  code: string\n}\n\n/**\n * Enrollment status of a user's recovery codes. Never contains code values.\n *\n * @experimental\n */\nexport type AuthMFARecoveryCodesStatusResponseData = {\n  /** ID of the recovery codes factor, as it appears in `user.factors`. */\n  id: string\n\n  /** Type of factor, always `recovery_code`. */\n  type: 'recovery_code'\n\n  /** Number of codes in the current set. */\n  total: number\n\n  /**\n   * Number of codes in the current set that have not been used yet. `0` when\n   * every code has been consumed.\n   */\n  remaining: number\n}\n\n/**\n * Response type for {@link AuthMFARecoveryCodesApi#getStatus}.\n *\n * @experimental\n */\nexport type AuthMFARecoveryCodesStatusResponse =\n  RequestResult\u003cAuthMFARecoveryCodesStatusResponseData\u003e\n\n/**\n * A newly generated set of recovery codes. The `codes` are returned exactly\n * once and cannot be retrieved again; use `regenerate()` to issue a new set.\n *\n * @experimental\n */\nexport type AuthMFARecoveryCodesGenerateResponseData = {\n  /** ID of the recovery codes factor. */\n  id: string\n\n  /** Type of factor, always `recovery_code`. */\n  type: 'recovery_code'\n\n  /** Friendly name of the recovery codes factor. */\n  friendly_name?: string\n\n  /** Number of codes in the set. */\n  total: number\n\n  /**\n   * The plaintext recovery codes in canonical form.\n   * They are returned exactly once and cannot be retrieved again. Show them to\n   * the user in a copy/download-friendly layout and ask them to store the codes\n   * safely.\n   */\n  codes: string[]\n}\n\n/**\n * Response type for {@link AuthMFARecoveryCodesApi#generate} and\n * {@link AuthMFARecoveryCodesApi#regenerate}.\n *\n * @experimental\n */\nexport type AuthMFARecoveryCodesGenerateResponse =\n  RequestResult\u003cAuthMFARecoveryCodesGenerateResponseData\u003e\n\ntype AuthMFAChallengeResponseBase\u003cT extends FactorType\u003e = {\n  /** ID of the newly created challenge. */\n  id: string\n\n  /** Factor Type which generated the challenge */\n  type: T\n\n  /** Timestamp in UNIX seconds when this challenge will no longer be usable. */\n  expires_at: number\n}\n\ntype AuthMFAChallengeTOTPResponseFields = {\n  /** no extra fields for now, kept for consistency and for possible future changes  */\n}\n\nexport type AuthMFAChallengeTOTPResponse = RequestResult\u003c\n  AuthMFAChallengeResponseBase\u003c'totp'\u003e \u0026 AuthMFAChallengeTOTPResponseFields\n\u003e\n\ntype AuthMFAChallengePhoneResponseFields = {\n  /** no extra fields for now, kept for consistency and for possible future changes  */\n}\n\nexport type AuthMFAChallengePhoneResponse = RequestResult\u003c\n  AuthMFAChallengeResponseBase\u003c'phone'\u003e \u0026 AuthMFAChallengePhoneResponseFields\n\u003e\n\ntype AuthMFAChallengeWebauthnResponseFields = {\n  webauthn:\n    | {\n        type: 'create'\n        credential_options: { publicKey: PublicKeyCredentialCreationOptionsFuture }\n      }\n    | {\n        type: 'request'\n        credential_options: { publicKey: PublicKeyCredentialRequestOptionsFuture }\n      }\n}\n\n/**\n * Response type for WebAuthn MFA challenge.\n * Contains credential creation or request options from the server.\n * @see {@link https://w3c.github.io/webauthn/#sctn-credential-creation W3C WebAuthn Spec - Credential Creation}\n */\nexport type AuthMFAChallengeWebauthnResponse = RequestResult\u003c\n  AuthMFAChallengeResponseBase\u003c'webauthn'\u003e \u0026 AuthMFAChallengeWebauthnResponseFields\n\u003e\n\ntype AuthMFAChallengeWebauthnResponseFieldsJSON = {\n  webauthn:\n    | {\n        type: 'create'\n        credential_options: { publicKey: ServerCredentialCreationOptions }\n      }\n    | {\n        type: 'request'\n        credential_options: { publicKey: ServerCredentialRequestOptions }\n      }\n}\n\n/**\n * JSON-serializable version of WebAuthn challenge response.\n * Used for server communication with base64url-encoded binary fields.\n */\nexport type AuthMFAChallengeWebauthnResponseDataJSON = AuthMFAChallengeResponseBase\u003c'webauthn'\u003e \u0026\n  AuthMFAChallengeWebauthnResponseFieldsJSON\n\n/**\n * Server response type for WebAuthn MFA challenge.\n * Contains JSON-formatted WebAuthn options ready for browser API.\n */\nexport type AuthMFAChallengeWebauthnServerResponse =\n  RequestResult\u003cAuthMFAChallengeWebauthnResponseDataJSON\u003e\n\nexport type AuthMFAChallengeResponse =\n  | AuthMFAChallengeTOTPResponse\n  | AuthMFAChallengePhoneResponse\n  | AuthMFAChallengeWebauthnResponse\n\n/** response of ListFactors, which should contain all the types of factors that are available, this ensures we always include all */\nexport type AuthMFAListFactorsResponse\u003cT extends typeof FactorTypes = typeof FactorTypes\u003e =\n  RequestResult\u003c\n    {\n      /** All available factors (verified and unverified). */\n      all: Factor[]\n\n      // Dynamically create a property for each factor type with only verified factors\n    } \u0026 {\n      [K in T[number]]: Factor\u003cK, 'verified'\u003e[]\n    }\n  \u003e\n\nexport type AuthenticatorAssuranceLevels = 'aal1' | 'aal2' | (string \u0026 {})\n\nexport type AuthMFAGetAuthenticatorAssuranceLevelResponse = RequestResult\u003c{\n  /** Current AAL level of the session. */\n  currentLevel: AuthenticatorAssuranceLevels | null\n\n  /**\n   * Next possible AAL level for the session. If the next level is higher\n   * than the current one, the user should go through MFA.\n   *\n   * @see {@link GoTrueMFAApi#challenge}\n   */\n  nextLevel: AuthenticatorAssuranceLevels | null\n\n  /**\n   * A list of all authentication methods attached to this session. Use\n   * the information here to detect the last time a user verified a\n   * factor, for example if implementing a step-up scenario.\n   *\n   * Supports both RFC-8176 compliant format (string[]) and detailed format (AMREntry[]).\n   * - String format: ['password', 'otp'] - RFC-8176 compliant\n   * - Object format: [{ method: 'password', timestamp: 1234567890 }] - includes timestamps\n   */\n  currentAuthenticationMethods: AMREntry[] | string[]\n}\u003e\n\n/**\n * Contains the MFA recovery codes API.\n *\n * Recovery codes are single-use backup codes that let a user reach `aal2`\n * when they cannot use their other MFA factors (for example, a lost\n * authenticator app). A user has a single set of recovery codes; the codes\n * are shown exactly once when generated.\n *\n * Requires `auth.experimental.recoveryCodes: true`; otherwise all methods\n * throw. Recovery codes must also be enabled on the Supabase Auth server.\n *\n * @experimental\n */\nexport interface AuthMFARecoveryCodesApi {\n  /**\n   * Returns the enrollment status of the user's recovery codes: the total\n   * number of codes in the current set and how many are still unused. Never\n   * returns the codes themselves.\n   *\n   * Requires `auth.experimental.recoveryCodes: true`.\n   *\n   * @experimental\n   *\n   * @category Auth\n   * @subcategory Auth MFA Recovery Codes\n   *\n   * @remarks\n   * - Works at any authenticator assurance level (`aal1` or `aal2`).\n   * - Returns an error with code `mfa_factor_not_found` when the user has not generated recovery codes yet.\n   * - `remaining` can be `0` once every code has been used; prompt the user to call `mfa.recoveryCodes.regenerate()`.\n   *\n   * @example Get the recovery codes status\n   * ```js\n   * const { data, error } = await supabase.auth.mfa.recoveryCodes.getStatus()\n   * ```\n   *\n   * @exampleResponse Get the recovery codes status\n   * ```json\n   * {\n   *   data: {\n   *     id: '\u003cFACTOR_ID\u003e',\n   *     type: 'recovery_code',\n   *     total: 10,\n   *     remaining: 7\n   *   },\n   *   error: null\n   * }\n   * ```\n   */\n  getStatus(): Promise\u003cAuthMFARecoveryCodesStatusResponse\u003e\n\n  /**\n   * Generates the user's set of recovery codes. The plaintext codes are\n   * returned exactly once in the response and cannot be retrieved again, so\n   * show them to the user and ask them to store the codes safely.\n   *\n   * Requires `auth.experimental.recoveryCodes: true`.\n   *\n   * @experimental\n   *\n   * @category Auth\n   * @subcategory Auth MFA Recovery Codes\n   *\n   * @remarks\n   * - The session must be at `aal2` (verify another factor first), otherwise an error with code `insufficient_aal` is returned.\n   * - The user must already have another verified factor (for example a TOTP factor): recovery codes can never be the only factor. Otherwise an error with code `mfa_recovery_codes_sole_factor` is returned.\n   * - A user can only have one set of recovery codes. If one already exists, an error with code `mfa_verified_factor_exists` is returned; use `mfa.recoveryCodes.regenerate()` to replace it.\n   * - The codes are returned in canonical form (lowercase, no separators). For display you can group them, for example in blocks of four characters. Avoid logging them to the console.\n   * - Returns an error with code `mfa_recovery_codes_enroll_not_enabled` when recovery codes are disabled on the server.\n   *\n   * @example Generate recovery codes\n   * ```js\n   * const supabase = createClient(supabaseUrl, supabaseKey, {\n   *   auth: { experimental: { recoveryCodes: true } },\n   * })\n   *\n   * const { data, error } = await supabase.auth.mfa.recoveryCodes.generate({\n   *   friendlyName: 'Backup codes',\n   * })\n   *\n   * // Show the codes once, for example grouped in blocks of four characters\n   * const formatted = data.codes.map((code) =\u003e code.match(/.{1,4}/g).join('-'))\n   * ```\n   *\n   * @exampleResponse Generate recovery codes\n   * ```json\n   * {\n   *   data: {\n   *     id: '\u003cFACTOR_ID\u003e',\n   *     type: 'recovery_code',\n   *     friendly_name: 'Backup codes',\n   *     total: 10,\n   *     codes: [\n   *       'k4m9x7qp2ab8ht3z',\n   *       '9wze6r5npd4cmq7v',\n   *       '...'\n   *     ]\n   *   },\n   *   error: null\n   * }\n   * ```\n   */\n  generate(params?: MFARecoveryCodesGenerateParams): Promise\u003cAuthMFARecoveryCodesGenerateResponse\u003e\n\n  /**\n   * Verifies one of the user's recovery codes and upgrades the current\n   * session to `aal2`. Each code can be used only once.\n   *\n   * Requires `auth.experimental.recoveryCodes: true`.\n   *\n   * @experimental\n   *\n   * @category Auth\n   * @subcategory Auth MFA Recovery Codes\n   *\n   * @remarks\n   * - On success the current session is upgraded to `aal2` in place and persisted, and the `MFA_CHALLENGE_VERIFIED` event is emitted. The user's other `aal1` sessions are signed out.\n   * - The new access token includes `mfa/recovery_code` in its `amr` claim.\n   * - The code can be passed exactly as the user typed it: letter case, whitespace and `-` separators are ignored.\n   * - A wrong, already used, or missing code returns an error with code `mfa_verification_failed`.\n   * - After too many failed attempts, verification is locked for a period and an error with code `mfa_recovery_codes_locked` (status `429`) is returned. Ask the user to wait or to use another factor.\n   * - Returns an error with code `mfa_recovery_codes_verify_not_enabled` when recovery code verification is disabled on the server.\n   *\n   * @example Verify a recovery code\n   * ```js\n   * const { data, error } = await supabase.auth.mfa.recoveryCodes.verify({\n   *   code: 'K4M9-X7QP-2AB8-HT3Z',\n   * })\n   * ```\n   *\n   * @exampleResponse Verify a recovery code\n   * ```json\n   * {\n   *   data: {\n   *     access_token: '\u003cACCESS_TOKEN\u003e',\n   *     token_type: 'bearer',\n   *     expires_in: 3600,\n   *     refresh_token: '\u003cREFRESH_TOKEN\u003e',\n   *     user: {\n   *       id: '11111111-1111-1111-1111-111111111111',\n   *       aud: 'authenticated',\n   *       role: 'authenticated',\n   *       email: 'example@email.com',\n   *       factors: [\n   *         {\n   *           id: '\u003cTOTP_FACTOR_ID\u003e',\n   *           friendly_name: 'Authenticator app',\n   *           factor_type: 'totp',\n   *           status: 'verified',\n   *           created_at: '2024-01-01T00:00:00Z',\n   *           updated_at: '2024-01-01T00:00:00Z'\n   *         },\n   *         {\n   *           id: '\u003cRECOVERY_CODES_FACTOR_ID\u003e',\n   *           friendly_name: 'Backup codes',\n   *           factor_type: 'recovery_code',\n   *           status: 'verified',\n   *           created_at: '2024-01-01T00:00:00Z',\n   *           updated_at: '2024-01-01T00:00:00Z'\n   *         }\n   *       ]\n   *     }\n   *   },\n   *   error: null\n   * }\n   * ```\n   */\n  verify(params: MFARecoveryCodesVerifyParams): Promise\u003cAuthMFAVerifyResponse\u003e\n\n  /**\n   * Replaces the user's recovery codes with a brand new set. All remaining\n   * codes from the previous set stop working immediately. The new plaintext\n   * codes are returned exactly once.\n   *\n   * Requires `auth.experimental.recoveryCodes: true`.\n   *\n   * @experimental\n   *\n   * @category Auth\n   * @subcategory Auth MFA Recovery Codes\n   *\n   * @remarks\n   * - The session must be at `aal2`, otherwise an error with code `insufficient_aal` is returned.\n   * - The factor `id` and `friendly_name` are preserved; only the codes change.\n   * - Also clears any verification lockout on the recovery codes.\n   * - Returns an error with code `mfa_factor_not_found` when the user has no recovery codes to regenerate; use `mfa.recoveryCodes.generate()` instead.\n   * - Returns an error with code `mfa_recovery_codes_enroll_not_enabled` when recovery codes are disabled on the server.\n   *\n   * @example Regenerate recovery codes\n   * ```js\n   * const { data, error } = await supabase.auth.mfa.recoveryCodes.regenerate()\n   * ```\n   *\n   * @exampleResponse Regenerate recovery codes\n   * ```json\n   * {\n   *   data: {\n   *     id: '\u003cFACTOR_ID\u003e',\n   *     type: 'recovery_code',\n   *     friendly_name: 'Backup codes',\n   *     total: 10,\n   *     codes: [\n   *       '2h8kqw3m7xt49rpn',\n   *       'nq5v7xk2m9tp4wzs',\n   *       '...'\n   *     ]\n   *   },\n   *   error: null\n   * }\n   * ```\n   */\n  regenerate(): Promise\u003cAuthMFARecoveryCodesGenerateResponse\u003e\n\n  /**\n   * Removes the user's recovery codes factor together with all of its codes.\n   *\n   * Requires `auth.experimental.recoveryCodes: true`.\n   *\n   * @experimental\n   *\n   * @category Auth\n   * @subcategory Auth MFA Recovery Codes\n   *\n   * @remarks\n   * - The session must be at `aal2`, otherwise an error with code `insufficient_aal` is returned.\n   * - Returns an error with code `mfa_factor_not_found` when the user has no recovery codes.\n   *\n   * @example Unenroll recovery codes\n   * ```js\n   * const { data, error } = await supabase.auth.mfa.recoveryCodes.unenroll()\n   * ```\n   *\n   * @exampleResponse Unenroll recovery codes\n   * ```json\n   * {\n   *   data: {\n   *     id: '\u003cFACTOR_ID\u003e'\n   *   },\n   *   error: null\n   * }\n   * ```\n   */\n  unenroll(): Promise\u003cAuthMFAUnenrollResponse\u003e\n}\n\n/**\n * Contains the full multi-factor authentication API.\n *\n */\nexport interface GoTrueMFAApi {\n  /**\n   * Starts the enrollment process for a new Multi-Factor Authentication (MFA)\n   * factor. This method creates a new `unverified` factor.\n   * To verify a factor, present the QR code or secret to the user and ask them to add it to their\n   * authenticator app.\n   * The user has to enter the code from their authenticator app to verify it.\n   *\n   * Upon verifying a factor, all other sessions are logged out and the current session's authenticator level is promoted to `aal2`.\n   *\n   * @category Auth\n   * @subcategory Auth MFA\n   *\n   * @remarks\n   * - Use `totp` or `phone` as the `factorType` and use the returned `id` to create a challenge.\n   * - To create a challenge, see [`mfa.challenge()`](/docs/reference/javascript/auth-mfa-challenge).\n   * - To verify a challenge, see [`mfa.verify()`](/docs/reference/javascript/auth-mfa-verify).\n   * - To create and verify a TOTP challenge in a single step, see [`mfa.challengeAndVerify()`](/docs/reference/javascript/auth-mfa-challengeandverify).\n   * - To generate a QR code for the `totp` secret in Next.js, you can do the following:\n   * ```html\n   * \u003cImage src={data.totp.qr_code} alt={data.totp.uri} layout=\"fill\"\u003e\u003c/Image\u003e\n   * ```\n   * - The `challenge` and `verify` steps are separated when using Phone factors as the user will need time to receive and input the code obtained from the SMS in challenge.\n   *\n   * @example Enroll a time-based, one-time password (TOTP) factor\n   * ```js\n   * const { data, error } = await supabase.auth.mfa.enroll({\n   *   factorType: 'totp',\n   *   friendlyName: 'your_friendly_name'\n   * })\n   *\n   * // Use the id to create a challenge.\n   * // The challenge can be verified by entering the code generated from the authenticator app.\n   * // The code will be generated upon scanning the qr_code or entering the secret into the authenticator app.\n   * const { id, type, totp: { qr_code, secret, uri }, friendly_name } = data\n   * const challenge = await supabase.auth.mfa.challenge({ factorId: id });\n   * ```\n   *\n   * @exampleResponse Enroll a time-based, one-time password (TOTP) factor\n   * ```json\n   * {\n   *   data: {\n   *     id: '\u003cID\u003e',\n   *     type: 'totp'\n   *     totp: {\n   *       qr_code: '\u003cQR_CODE_AS_SVG_DATA\u003e',\n   *       secret: '\u003cSECRET\u003e',\n   *       uri: '\u003cURI\u003e',\n   *     }\n   *     friendly_name?: 'Important app'\n   *   },\n   *   error: null\n   * }\n   * ```\n   *\n   * @example Enroll a Phone Factor\n   * ```js\n   * const { data, error } = await supabase.auth.mfa.enroll({\n   *   factorType: 'phone',\n   *   friendlyName: 'your_friendly_name',\n   *   phone: '+12345678',\n   * })\n   *\n   * // Use the id to create a challenge and send an SMS with a code to the user.\n   * const { id, type, friendly_name, phone } = data\n   *\n   * const challenge = await supabase.auth.mfa.challenge({ factorId: id });\n   * ```\n   *\n   * @exampleResponse Enroll a Phone Factor\n   * ```json\n   * {\n   *   data: {\n   *     id: '\u003cID\u003e',\n   *     type: 'phone',\n   *     friendly_name?: 'Important app',\n   *     phone: '+5787123456'\n   *   },\n   *   error: null\n   * }\n   * ```\n   */\n  enroll(params: MFAEnrollTOTPParams): Promise\u003cAuthMFAEnrollTOTPResponse\u003e\n  enroll(params: MFAEnrollPhoneParams): Promise\u003cAuthMFAEnrollPhoneResponse\u003e\n  enroll(params: MFAEnrollWebauthnParams): Promise\u003cAuthMFAEnrollWebauthnResponse\u003e\n  enroll(params: MFAEnrollParams): Promise\u003cAuthMFAEnrollResponse\u003e\n\n  /**\n   * Prepares a challenge used to verify that a user has access to a MFA\n   * factor.\n   *\n   * @category Auth\n   * @subcategory Auth MFA\n   *\n   * @remarks\n   * - An [enrolled factor](/docs/reference/javascript/auth-mfa-enroll) is required before creating a challenge.\n   * - To verify a challenge, see [`mfa.verify()`](/docs/reference/javascript/auth-mfa-verify).\n   * - A phone factor sends a code to the user upon challenge. The channel defaults to `sms` unless otherwise specified.\n   *\n   * @example Create a challenge for a factor\n   * ```js\n   * const { data, error } = await supabase.auth.mfa.challenge({\n   *   factorId: '34e770dd-9ff9-416c-87fa-43b31d7ef225'\n   * })\n   * ```\n   *\n   * @exampleResponse Create a challenge for a factor\n   * ```json\n   * {\n   *   data: {\n   *     id: '\u003cID\u003e',\n   *     type: 'totp',\n   *     expires_at: 1700000000\n   *   },\n   *   error: null\n   * }\n   * ```\n   *\n   * @example Create a challenge for a phone factor\n   * ```js\n   * const { data, error } = await supabase.auth.mfa.challenge({\n   *   factorId: '34e770dd-9ff9-416c-87fa-43b31d7ef225',\n   * })\n   * ```\n   *\n   * @exampleResponse Create a challenge for a phone factor\n   * ```json\n   * {\n   *   data: {\n   *     id: '\u003cID\u003e',\n   *     type: 'phone',\n   *     expires_at: 1700000000\n   *   },\n   *   error: null\n   * }\n   * ```\n   *\n   * @example Create a challenge for a phone factor (WhatsApp)\n   * ```js\n   * const { data, error } = await supabase.auth.mfa.challenge({\n   *   factorId: '34e770dd-9ff9-416c-87fa-43b31d7ef225',\n   *   channel: 'whatsapp',\n   * })\n   * ```\n   *\n   * @exampleResponse Create a challenge for a phone factor (WhatsApp)\n   * ```json\n   * {\n   *   data: {\n   *     id: '\u003cID\u003e',\n   *     expires_at: 1700000000\n   *   },\n   *   error: null\n   * }\n   * ```\n   */\n  challenge(params: MFAChallengeTOTPParams): Promise\u003cPrettify\u003cAuthMFAChallengeTOTPResponse\u003e\u003e\n  challenge(params: MFAChallengePhoneParams): Promise\u003cPrettify\u003cAuthMFAChallengePhoneResponse\u003e\u003e\n  challenge(params: MFAChallengeWebauthnParams): Promise\u003cPrettify\u003cAuthMFAChallengeWebauthnResponse\u003e\u003e\n  challenge(params: MFAChallengeParams): Promise\u003cAuthMFAChallengeResponse\u003e\n\n  /**\n   * Verifies a code against a challenge. The verification code is\n   * provided by the user by entering a code seen in their authenticator app.\n   *\n   * @category Auth\n   * @subcategory Auth MFA\n   *\n   * @remarks\n   * - To verify a challenge, please [create a challenge](/docs/reference/javascript/auth-mfa-challenge) first.\n   *\n   * @example Verify a challenge for a factor\n   * ```js\n   * const { data, error } = await supabase.auth.mfa.verify({\n   *   factorId: '34e770dd-9ff9-416c-87fa-43b31d7ef225',\n   *   challengeId: '4034ae6f-a8ce-4fb5-8ee5-69a5863a7c15',\n   *   code: '123456'\n   * })\n   * ```\n   *\n   * @exampleResponse Verify a challenge for a factor\n   * ```json\n   * {\n   *   data: {\n   *     access_token: '\u003cACCESS_TOKEN\u003e',\n   *     token_type: 'Bearer',\n   *     expires_in: 3600,\n   *     refresh_token: '\u003cREFRESH_TOKEN\u003e',\n   *     user: {\n   *       id: '11111111-1111-1111-1111-111111111111',\n   *       aud: 'authenticated',\n   *       role: 'authenticated',\n   *       email: 'example@email.com',\n   *       email_confirmed_at: '2024-01-01T00:00:00Z',\n   *       phone: '',\n   *       confirmation_sent_at: '2024-01-01T00:00:00Z',\n   *       confirmed_at: '2024-01-01T00:00:00Z',\n   *       last_sign_in_at: '2024-01-01T00:00:00Z',\n   *       app_metadata: {\n   *         provider: 'email',\n   *         providers: [\n   *           \"email\",\n   *         ]\n   *       },\n   *       user_metadata: {},\n   *       identities: [\n   *         {\n   *           \"identity_id\": \"22222222-2222-2222-2222-222222222222\",\n   *           \"id\": \"11111111-1111-1111-1111-111111111111\",\n   *           \"user_id\": \"11111111-1111-1111-1111-111111111111\",\n   *           \"identity_data\": {\n   *             \"email\": \"example@email.com\",\n   *             \"email_verified\": true,\n   *             \"phone_verified\": false,\n   *             \"sub\": \"11111111-1111-1111-1111-111111111111\"\n   *           },\n   *           \"provider\": \"email\",\n   *           \"last_sign_in_at\": \"2024-01-01T00:00:00Z\",\n   *           \"created_at\": \"2024-01-01T00:00:00Z\",\n   *           \"updated_at\": \"2024-01-01T00:00:00Z\",\n   *           \"email\": \"email@example.com\"\n   *         },\n   *       ],\n   *       created_at: '2024-01-01T00:00:00Z',\n   *       updated_at: '2024-01-01T00:00:00Z',\n   *       is_anonymous: false,\n   *       factors: [\n   *         \"id\": '\u003cID\u003e',\n   *         \"friendly_name\": 'Important Auth App',\n   *         \"factor_type\": 'totp',\n   *         \"status\": 'verified',\n   *         \"created_at\": \"2024-01-01T00:00:00Z\",\n   *         \"updated_at\": \"2024-01-01T00:00:00Z\"\n   *       ]\n   *     }\n   *   }\n   *   error: null\n   * }\n   * ```\n   */\n  verify(params: MFAVerifyTOTPParams): Promise\u003cAuthMFAVerifyResponse\u003e\n  verify(params: MFAVerifyPhoneParams): Promise\u003cAuthMFAVerifyResponse\u003e\n  verify(params: MFAVerifyWebauthnParams): Promise\u003cAuthMFAVerifyResponse\u003e\n  verify(params: MFAVerifyParams): Promise\u003cAuthMFAVerifyResponse\u003e\n\n  /**\n   * Unenroll removes a MFA factor.\n   * A user has to have an `aal2` authenticator level in order to unenroll a `verified` factor.\n   *\n   * @category Auth\n   * @subcategory Auth MFA\n   *\n   * @example Unenroll a factor\n   * ```js\n   * const { data, error } = await supabase.auth.mfa.unenroll({\n   *   factorId: '34e770dd-9ff9-416c-87fa-43b31d7ef225',\n   * })\n   * ```\n   *\n   * @exampleResponse Unenroll a factor\n   * ```json\n   * {\n   *   data: {\n   *     id: '\u003cFACTOR_ID\u003e'\n   *   },\n   *   error: null\n   * }\n   * ```\n   */\n  unenroll(params: MFAUnenrollParams): Promise\u003cAuthMFAUnenrollResponse\u003e\n\n  /**\n   * Helper method which creates a challenge and immediately uses the given code to verify against it thereafter. The verification code is\n   * provided by the user by entering a code seen in their authenticator app.\n   *\n   * @category Auth\n   * @subcategory Auth MFA\n   *\n   * @remarks\n   * - Intended for use with only TOTP factors.\n   * - An [enrolled factor](/docs/reference/javascript/auth-mfa-enroll) is required before invoking `challengeAndVerify()`.\n   * - Executes [`mfa.challenge()`](/docs/reference/javascript/auth-mfa-challenge) and [`mfa.verify()`](/docs/reference/javascript/auth-mfa-verify) in a single step.\n   *\n   * @example Create and verify a challenge for a factor\n   * ```js\n   * const { data, error } = await supabase.auth.mfa.challengeAndVerify({\n   *   factorId: '34e770dd-9ff9-416c-87fa-43b31d7ef225',\n   *   code: '123456'\n   * })\n   * ```\n   *\n   * @exampleResponse Create and verify a challenge for a factor\n   * ```json\n   * {\n   *   data: {\n   *     access_token: '\u003cACCESS_TOKEN\u003e',\n   *     token_type: 'Bearer',\n   *     expires_in: 3600,\n   *     refresh_token: '\u003cREFRESH_TOKEN\u003e',\n   *     user: {\n   *       id: '11111111-1111-1111-1111-111111111111',\n   *       aud: 'authenticated',\n   *       role: 'authenticated',\n   *       email: 'example@email.com',\n   *       email_confirmed_at: '2024-01-01T00:00:00Z',\n   *       phone: '',\n   *       confirmation_sent_at: '2024-01-01T00:00:00Z',\n   *       confirmed_at: '2024-01-01T00:00:00Z',\n   *       last_sign_in_at: '2024-01-01T00:00:00Z',\n   *       app_metadata: {\n   *         provider: 'email',\n   *         providers: [\n   *           \"email\",\n   *         ]\n   *       },\n   *       user_metadata: {},\n   *       identities: [\n   *         {\n   *           \"identity_id\": \"22222222-2222-2222-2222-222222222222\",\n   *           \"id\": \"11111111-1111-1111-1111-111111111111\",\n   *           \"user_id\": \"11111111-1111-1111-1111-111111111111\",\n   *           \"identity_data\": {\n   *             \"email\": \"example@email.com\",\n   *             \"email_verified\": true,\n   *             \"phone_verified\": false,\n   *             \"sub\": \"11111111-1111-1111-1111-111111111111\"\n   *           },\n   *           \"provider\": \"email\",\n   *           \"last_sign_in_at\": \"2024-01-01T00:00:00Z\",\n   *           \"created_at\": \"2024-01-01T00:00:00Z\",\n   *           \"updated_at\": \"2024-01-01T00:00:00Z\",\n   *           \"email\": \"email@example.com\"\n   *         },\n   *       ],\n   *       created_at: '2024-01-01T00:00:00Z',\n   *       updated_at: '2024-01-01T00:00:00Z',\n   *       is_anonymous: false,\n   *       factors: [\n   *         \"id\": '\u003cID\u003e',\n   *         \"friendly_name\": 'Important Auth App',\n   *         \"factor_type\": 'totp',\n   *         \"status\": 'verified',\n   *         \"created_at\": \"2024-01-01T00:00:00Z\",\n   *         \"updated_at\": \"2024-01-01T00:00:00Z\"\n   *       ]\n   *     }\n   *   }\n   *   error: null\n   * }\n   * ```\n   */\n  challengeAndVerify(params: MFAChallengeAndVerifyParams): Promise\u003cAuthMFAVerifyResponse\u003e\n\n  /**\n   * Returns the list of MFA factors enabled for this user.\n   *\n   * @see {@link GoTrueMFAApi#enroll}\n   * @see {@link GoTrueMFAApi#getAuthenticatorAssuranceLevel}\n   * @see {@link GoTrueClient#getUser}\n   *\n   *\n   * @category Auth\n   * @subcategory Auth MFA\n   */\n  listFactors(): Promise\u003cAuthMFAListFactorsResponse\u003e\n\n  /**\n   * Returns the Authenticator Assurance Level (AAL) for the active session.\n   *\n   * - `aal1` (or `null`) means that the user's identity has been verified only\n   * with a conventional login (email+password, OTP, magic link, social sign-in,\n   * etc.).\n   * - `aal2` means that the user's identity has been verified both with a conventional login and at least one MFA factor.\n   *\n   * When called without a JWT parameter, this method is fairly quick (microseconds)\n   * and rarely uses the network. When a JWT is provided (useful in server-side\n   * environments like Edge Functions where no session is stored), this method\n   * will make a network request to validate the user and fetch their MFA factors.\n   *\n   * @param jwt Takes in an optional access token JWT. If no JWT is provided, the JWT from the current session is used.\n   *\n   * @category Auth\n   * @subcategory Auth MFA\n   *\n   * @remarks\n   * - Authenticator Assurance Level (AAL) is the measure of the strength of an authentication mechanism.\n   * - In Supabase, having an AAL of `aal1` refers to having the 1st factor of authentication such as an email and password or OAuth sign-in while `aal2` refers to the 2nd factor of authentication such as a time-based, one-time-password (TOTP) or Phone factor.\n   * - If the user has a verified factor, the `nextLevel` field will return `aal2`, else, it will return `aal1`.\n   * - An optional `jwt` parameter can be passed to check the AAL level of a specific JWT instead of the current session.\n   *\n   * @example Get the AAL details of a session\n   * ```js\n   * const { data, error } = await supabase.auth.mfa.getAuthenticatorAssuranceLevel()\n   * const { currentLevel, nextLevel, currentAuthenticationMethods } = data\n   * ```\n   *\n   * @exampleResponse Get the AAL details of a session\n   * ```json\n   * {\n   *   data: {\n   *     currentLevel: 'aal1',\n   *     nextLevel: 'aal2',\n   *     currentAuthenticationMethods: [\n   *       {\n   *         method: 'password',\n   *         timestamp: 1700000000\n   *       }\n   *     ]\n   *   }\n   *   error: null\n   * }\n   * ```\n   *\n   * @example Get the AAL details for a specific JWT\n   * ```js\n   * const { data, error } = await supabase.auth.mfa.getAuthenticatorAssuranceLevel(jwt)\n   * ```\n   */\n  getAuthenticatorAssuranceLevel(\n    jwt?: string\n  ): Promise\u003cAuthMFAGetAuthenticatorAssuranceLevelResponse\u003e\n\n  // namespace for the webauthn methods\n  webauthn: WebAuthnApi\n\n  /**\n   * Namespace for the MFA recovery codes methods.\n   *\n   * Requires `auth.experimental.recoveryCodes: true`; otherwise all methods throw.\n   *\n   * @see {@link AuthMFARecoveryCodesApi}\n   *\n   * @experimental\n   */\n  recoveryCodes: AuthMFARecoveryCodesApi\n}\n\n/**\n * @experimental\n */\nexport type AuthMFAAdminDeleteFactorResponse = RequestResult\u003c{\n  /** ID of the factor that was successfully deleted. */\n  id: string\n}\u003e\n/**\n * @experimental\n */\nexport type AuthMFAAdminDeleteFactorParams = {\n  /** ID of the MFA factor to delete. */\n  id: string\n\n  /** ID of the user whose factor is being deleted. */\n  userId: string\n}\n\n/**\n * @experimental\n */\nexport type AuthMFAAdminListFactorsResponse = RequestResult\u003c{\n  /** All factors attached to the user. */\n  factors: Factor[]\n}\u003e\n\n/**\n * @experimental\n */\nexport type AuthMFAAdminListFactorsParams = {\n  /** ID of the user. */\n  userId: string\n}\n\n/**\n * Contains the full multi-factor authentication administration API.\n *\n * @experimental\n */\nexport interface GoTrueAdminMFAApi {\n  /**\n   * Lists all factors associated to a user.\n   *\n   *\n   * @category Auth\n   * @subcategory Auth Admin\n   *\n   * @example List all factors for a user\n   * ```js\n   * const { data, error } = await supabase.auth.admin.mfa.listFactors()\n   * ```\n   *\n   * @exampleResponse List all factors for a user\n   * ```json\n   * {\n   *   data: {\n   *     factors: Factor[\n   *       {\n   *         id: '\u003cID\u003e',\n   *         friendly_name: 'Auth App Factor',\n   *         factor_type: 'totp',\n   *         status: 'verified',\n   *         created_at: '2024-01-01T00:00:00Z',\n   *         updated_at: '2024-01-01T00:00:00Z'\n   *       }\n   *     ]\n   *   },\n   *   error: null\n   * }\n   * ```\n   */\n  listFactors(params: AuthMFAAdminListFactorsParams): Promise\u003cAuthMFAAdminListFactorsResponse\u003e\n\n  /**\n   * Deletes a factor on a user. This will log the user out of all active\n   * sessions if the deleted factor was verified.\n   *\n   * @see {@link GoTrueMFAApi#unenroll}\n   *\n   * @experimental\n   *\n   * @category Auth\n   * @subcategory Auth Admin\n   *\n   * @example Delete a factor for a user\n   * ```js\n   * const { data, error } = await supabase.auth.admin.mfa.deleteFactor({\n   *   id: '34e770dd-9ff9-416c-87fa-43b31d7ef225',\n   *   userId: 'a89baba7-b1b7-440f-b4bb-91026967f66b',\n   * })\n   * ```\n   *\n   * @exampleResponse Delete a factor for a user\n   * ```json\n   * {\n   *   data: {\n   *     id: '34e770dd-9ff9-416c-87fa-43b31d7ef225'\n   *   },\n   *   error: null\n   * }\n   * ```\n   */\n  deleteFactor(params: AuthMFAAdminDeleteFactorParams): Promise\u003cAuthMFAAdminDeleteFactorResponse\u003e\n}\n\ntype AnyFunction = (...args: any[]) =\u003e any\ntype MaybePromisify\u003cT\u003e = T | Promise\u003cT\u003e\n\ntype PromisifyMethods\u003cT\u003e = {\n  [K in keyof T]: T[K] extends AnyFunction\n    ? (...args: Parameters\u003cT[K]\u003e) =\u003e MaybePromisify\u003cReturnType\u003cT[K]\u003e\u003e\n    : T[K]\n}\n\nexport type SupportedStorage = PromisifyMethods\u003c\n  Pick\u003cStorage, 'getItem' | 'setItem' | 'removeItem'\u003e\n\u003e \u0026 {\n  /**\n   * If set to `true` signals to the library that the storage medium is used\n   * on a server and the values may not be authentic, such as reading from\n   * request cookies. Implementations should not set this to true if the client\n   * is used on a server that reads storage information from authenticated\n   * sources, such as a secure database or file.\n   */\n  isServer?: boolean\n}\n\nexport type InitializeResult = { error: AuthError | null }\n\nexport type CallRefreshTokenResult = RequestResult\u003cSession\u003e\n\nexport type Pagination = {\n  [key: string]: any\n  nextPage: number | null\n  lastPage: number\n  total: number\n}\n\nexport type PageParams = {\n  /** The page number */\n  page?: number\n  /** Number of items returned per page */\n  perPage?: number\n}\n\nexport type SignOut = {\n  /**\n   * Determines which sessions should be\n   * logged out. Global means all\n   * sessions by this account. Local\n   * means only this session. Others\n   * means all other sessions except the\n   * current one. When using others,\n   * there is no sign-out event fired on\n   * the current session!\n   */\n  scope?: 'global' | 'local' | 'others'\n}\n\ntype MFAEnrollParamsBase\u003cT extends FactorType\u003e = {\n  /** The type of factor being enrolled. */\n  factorType: T\n  /** Human readable name assigned to the factor. */\n  friendlyName?: string\n}\n\ntype MFAEnrollTOTPParamFields = {\n  /** Domain which the user is enrolled with. */\n  issuer?: string\n}\n\nexport type MFAEnrollTOTPParams = MFAEnrollParamsBase\u003c'totp'\u003e \u0026 MFAEnrollTOTPParamFields\n\ntype MFAEnrollPhoneParamFields = {\n  /** Phone number associated with a factor. Number should conform to E.164 format */\n  phone: string\n}\nexport type MFAEnrollPhoneParams = MFAEnrollParamsBase\u003c'phone'\u003e \u0026 MFAEnrollPhoneParamFields\n\ntype MFAEnrollWebauthnFields = {\n  /** no extra fields for now, kept for consistency and for possible future changes  */\n}\n\n/**\n * Parameters for enrolling a WebAuthn factor.\n * Creates an unverified WebAuthn factor that must be verified with a credential.\n * @see {@link https://w3c.github.io/webauthn/#sctn-registering-a-new-credential W3C WebAuthn Spec - Registering a New Credential}\n */\nexport type MFAEnrollWebauthnParams = MFAEnrollParamsBase\u003c'webauthn'\u003e \u0026 MFAEnrollWebauthnFields\n\ntype AuthMFAEnrollResponseBase\u003cT extends FactorType\u003e = {\n  /** ID of the factor that was just enrolled (in an unverified state). */\n  id: string\n\n  /** Type of MFA factor.*/\n  type: T\n\n  /** Friendly name of the factor, useful for distinguishing between factors **/\n  friendly_name?: string\n}\n\ntype AuthMFAEnrollTOTPResponseFields = {\n  /** TOTP enrollment information. */\n  totp: {\n    /** Contains a QR code encoding the authenticator URI. You can\n     * convert it to a URL by prepending `data:image/svg+xml;utf-8,` to\n     * the value. Avoid logging this value to the console. */\n    qr_code: string\n\n    /** The TOTP secret (also encoded in the QR code). Show this secret\n     * in a password-style field to the user, in case they are unable to\n     * scan the QR code. Avoid logging this value to the console. */\n    secret: string\n\n    /** The authenticator URI encoded within the QR code, should you need\n     * to use it. Avoid loggin this value to the console. */\n    uri: string\n  }\n}\n\nexport type AuthMFAEnrollTOTPResponse = RequestResult\u003c\n  AuthMFAEnrollResponseBase\u003c'totp'\u003e \u0026 AuthMFAEnrollTOTPResponseFields\n\u003e\n\ntype AuthMFAEnrollPhoneResponseFields = {\n  /** Phone number of the MFA factor in E.164 format. Used to send messages  */\n  phone: string\n}\n\nexport type AuthMFAEnrollPhoneResponse = RequestResult\u003c\n  AuthMFAEnrollResponseBase\u003c'phone'\u003e \u0026 AuthMFAEnrollPhoneResponseFields\n\u003e\n\ntype AuthMFAEnrollWebauthnFields = {\n  /** no extra fields for now, kept for consistency and for possible future changes  */\n}\n\n/**\n * Response type for WebAuthn factor enrollment.\n * Returns the enrolled factor ID and metadata.\n * @see {@link https://w3c.github.io/webauthn/#sctn-registering-a-new-credential W3C WebAuthn Spec - Registering a New Credential}\n */\nexport type AuthMFAEnrollWebauthnResponse = RequestResult\u003c\n  AuthMFAEnrollResponseBase\u003c'webauthn'\u003e \u0026 AuthMFAEnrollWebauthnFields\n\u003e\n\nexport type JwtHeader = {\n  alg: 'RS256' | 'ES256' | 'HS256' | (string \u0026 {})\n  kid: string\n  typ: string\n}\n\nexport type RequiredClaims = {\n  iss: string\n  sub: string\n  aud: string | string[]\n  exp: number\n  iat: number\n  role: string\n  aal: AuthenticatorAssuranceLevels\n  session_id: string\n}\n\n/**\n * JWT Payload containing claims for Supabase authentication tokens.\n *\n * Required claims (iss, aud, exp, iat, sub, role, aal, session_id) are inherited from RequiredClaims.\n * All other claims are optional as they can be customized via Custom Access Token Hooks.\n *\n * @see https://supabase.com/docs/guides/auth/jwt-fields\n */\nexport interface JwtPayload extends RequiredClaims {\n  // Standard optional claims (can be customized via custom access token hooks)\n  email?: string\n  phone?: string\n  is_anonymous?: boolean\n\n  // Optional claims\n  jti?: string\n  nbf?: number\n  app_metadata?: UserAppMetadata\n  user_metadata?: UserMetadata\n  /**\n   * Authentication Method References.\n   * Supports both RFC-8176 compliant format (string[]) and detailed format (AMREntry[]).\n   * - String format: ['password', 'otp'] - RFC-8176 compliant\n   * - Object format: [{ method: 'password', timestamp: 1234567890 }] - includes timestamps\n   */\n  amr?: AMREntry[] | string[]\n\n  // Special claims (only in anon/service role tokens)\n  ref?: string\n\n  // Allow custom claims via custom access token hooks\n  [key: string]: any\n}\n\nexport interface JWK {\n  kty: 'RSA' | 'EC' | 'oct' | (string \u0026 {})\n  key_ops: string[]\n  alg?: string\n  kid?: string\n  [key: string]: any\n}\n\nexport const SIGN_OUT_SCOPES = ['global', 'local', 'others'] as const\nexport type SignOutScope = (typeof SIGN_OUT_SCOPES)[number]\n\n/**\n * OAuth client grant types supported by the OAuth 2.1 server.\n * Only relevant when the OAuth 2.1 server is enabled in Supabase Auth.\n */\nexport type OAuthClientGrantType = 'authorization_code' | 'refresh_token' | (string \u0026 {})\n\n/**\n * OAuth client response types supported by the OAuth 2.1 server.\n * Only relevant when the OAuth 2.1 server is enabled in Supabase Auth.\n */\nexport type OAuthClientResponseType = 'code'\n\n/**\n * OAuth client type indicating whether the client can keep credentials confidential.\n * Only relevant when the OAuth 2.1 server is enabled in Supabase Auth.\n */\nexport type OAuthClientType = 'public' | 'confidential'\n\n/**\n * OAuth client registration type.\n * Only relevant when the OAuth 2.1 server is enabled in Supabase Auth.\n */\nexport type OAuthClientRegistrationType = 'dynamic' | 'manual'\n\n/**\n * OAuth client token endpoint authentication method.\n * Only relevant when the OAuth 2.1 server is enabled in Supabase Auth.\n */\nexport type OAuthClientTokenEndpointAuthMethod =\n  | 'none'\n  | 'client_secret_basic'\n  | 'client_secret_post'\n\n/**\n * OAuth client object returned from the OAuth 2.1 server.\n * Only relevant when the OAuth 2.1 server is enabled in Supabase Auth.\n */\nexport type OAuthClient = {\n  /** Unique identifier for the OAuth client */\n  client_id: string\n  /** Human-readable name of the OAuth client */\n  client_name: string\n  /** Client secret (only returned on registration and regeneration) */\n  client_secret?: string\n  /** Type of OAuth client */\n  client_type: OAuthClientType\n  /** Token endpoint authentication method */\n  token_endpoint_auth_method: OAuthClientTokenEndpointAuthMethod\n  /** Registration type of the client */\n  registration_type: OAuthClientRegistrationType\n  /** URI of the OAuth client */\n  client_uri?: string\n  /** URI of the OAuth client's logo */\n  logo_uri?: string\n  /** Array of allowed redirect URIs */\n  redirect_uris: string[]\n  /** Array of allowed grant types */\n  grant_types: OAuthClientGrantType[]\n  /** Array of allowed response types */\n  response_types: OAuthClientResponseType[]\n  /** Scope of the OAuth client */\n  scope?: string\n  /** Timestamp when the client was created */\n  created_at: string\n  /** Timestamp when the client was last updated */\n  updated_at: string\n}\n\n/**\n * Parameters for creating a new OAuth client.\n * Only relevant when the OAuth 2.1 server is enabled in Supabase Auth.\n */\nexport type CreateOAuthClientParams = {\n  /** Human-readable name of the OAuth client */\n  client_name: string\n  /** URI of the OAuth client */\n  client_uri?: string\n  /** Array of allowed redirect URIs */\n  redirect_uris: string[]\n  /** Array of allowed grant types (optional, defaults to authorization_code and refresh_token) */\n  grant_types?: OAuthClientGrantType[]\n  /** Array of allowed response types (optional, defaults to code) */\n  response_types?: OAuthClientResponseType[]\n  /** Scope of the OAuth client */\n  scope?: string\n  /** Token endpoint authentication method (defaults to server default if not specified) */\n  token_endpoint_auth_method?: OAuthClientTokenEndpointAuthMethod\n}\n\n/**\n * Parameters for updating an existing OAuth client.\n * All fields are optional. Only provided fields will be updated.\n * Only relevant when the OAuth 2.1 server is enabled in Supabase Auth.\n */\nexport type UpdateOAuthClientParams = {\n  /** Human-readable name of the OAuth client */\n  client_name?: string\n  /** URI of the OAuth client */\n  client_uri?: string\n  /** URI of the OAuth client's logo */\n  logo_uri?: string\n  /** Array of allowed redirect URIs */\n  redirect_uris?: string[]\n  /** Array of allowed grant types */\n  grant_types?: OAuthClientGrantType[]\n  /** Token endpoint authentication method */\n  token_endpoint_auth_method?: OAuthClientTokenEndpointAuthMethod\n}\n\n/**\n * Response type for OAuth client operations.\n * Only relevant when the OAuth 2.1 server is enabled in Supabase Auth.\n */\nexport type OAuthClientResponse = RequestResult\u003cOAuthClient\u003e\n\n/**\n * Response type for listing OAuth clients.\n * Only relevant when the OAuth 2.1 server is enabled in Supabase Auth.\n */\nexport type OAuthClientListResponse =\n  | {\n      data: { clients: OAuthClient[]; aud: string } \u0026 Pagination\n      error: null\n    }\n  | {\n      data: { clients: [] }\n      error: AuthError\n    }\n\n/**\n * Contains all OAuth client administration methods.\n * Only relevant when the OAuth 2.1 server is enabled in Supabase Auth.\n */\nexport interface GoTrueAdminOAuthApi {\n  /**\n   * Lists all OAuth clients with optional pagination.\n   * Only relevant when the OAuth 2.1 server is enabled in Supabase Auth.\n   *\n   * This function should only be called on a server. Never expose your `service_role` key in the browser.\n   *\n   * @category Auth\n   * @subcategory OAuth Admin\n   */\n  listClients(params?: PageParams): Promise\u003cOAuthClientListResponse\u003e\n\n  /**\n   * Creates a new OAuth client.\n   * Only relevant when the OAuth 2.1 server is enabled in Supabase Auth.\n   *\n   * This function should only be called on a server. Never expose your `service_role` key in the browser.\n   *\n   * @category Auth\n   * @subcategory OAuth Admin\n   */\n  createClient(params: CreateOAuthClientParams): Promise\u003cOAuthClientResponse\u003e\n\n  /**\n   * Gets details of a specific OAuth client.\n   * Only relevant when the OAuth 2.1 server is enabled in Supabase Auth.\n   *\n   * This function should only be called on a server. Never expose your `service_role` key in the browser.\n   *\n   * @category Auth\n   * @subcategory OAuth Admin\n   */\n  getClient(clientId: string): Promise\u003cOAuthClientResponse\u003e\n\n  /**\n   * Updates an existing OAuth client.\n   * Only relevant when the OAuth 2.1 server is enabled in Supabase Auth.\n   *\n   * This function should only be called on a server. Never expose your `service_role` key in the browser.\n   *\n   * @category Auth\n   * @subcategory OAuth Admin\n   */\n  updateClient(clientId: string, params: UpdateOAuthClientParams): Promise\u003cOAuthClientResponse\u003e\n\n  /**\n   * Deletes an OAuth client.\n   * Only relevant when the OAuth 2.1 server is enabled in Supabase Auth.\n   *\n   * This function should only be called on a server. Never expose your `service_role` key in the browser.\n   *\n   * @category Auth\n   * @subcategory OAuth Admin\n   */\n  deleteClient(clientId: string): Promise\u003c{ data: null; error: AuthError | null }\u003e\n\n  /**\n   * Regenerates the secret for an OAuth client.\n   * Only relevant when the OAuth 2.1 server is enabled in Supabase Auth.\n   *\n   * This function should only be called on a server. Never expose your `service_role` key in the browser.\n   *\n   * @category Auth\n   * @subcategory OAuth Admin\n   */\n  regenerateClientSecret(clientId: string): Promise\u003cOAuthClientResponse\u003e\n}\n\n/**\n * Type of custom identity provider.\n */\nexport type CustomProviderType = 'oauth2' | 'oidc'\n\n/**\n * OIDC discovery document fields.\n * Populated when the server successfully fetches and validates the\n * provider's OpenID Connect discovery document.\n */\nexport type OIDCDiscoveryDocument = {\n  /** The issuer identifier */\n  issuer: string\n  /** URL of the authorization endpoint */\n  authorization_endpoint: string\n  /** URL of the token endpoint */\n  token_endpoint: string\n  /** URL of the JSON Web Key Set */\n  jwks_uri: string\n  /** URL of the userinfo endpoint */\n  userinfo_endpoint?: string\n  /** URL of the revocation endpoint */\n  revocation_endpoint?: string\n  /** List of supported scopes */\n  supported_scopes?: string[]\n  /** List of supported response types */\n  supported_response_types?: string[]\n  /** List of supported subject types */\n  supported_subject_types?: string[]\n  /** List of supported ID token signing algorithms */\n  supported_id_token_signing_algs?: string[]\n}\n\n/**\n * Custom OAuth/OIDC provider object returned from the admin API.\n */\nexport type CustomOAuthProvider = {\n  /** Unique identifier (UUID) */\n  id: string\n  /** Provider type */\n  provider_type: CustomProviderType\n  /** Provider identifier (e.g. `custom:mycompany`) */\n  identifier: string\n  /** Human-readable name */\n  name: string\n  /** OAuth client ID */\n  client_id: string\n  /** Additional client IDs accepted during token validation */\n  acceptable_client_ids?: string[]\n  /** OAuth scopes requested during authorization */\n  scopes?: string[]\n  /**\n   * Allowlist of raw identity provider claim keys to copy verbatim into the\n   * user's `custom_claims` field (within `identity_data` and\n   * `raw_user_meta_data`), e.g. `[\"groups\", \"org_id\", \"mail\"]`. This is an\n   * opt-in allowlist that defaults to empty (no claims captured) and operates\n   * independently from `attribute_mapping`.\n   */\n  custom_claims_allowlist?: string[]\n  /** Whether PKCE is enabled */\n  pkce_enabled?: boolean\n  /** Mapping of provider attributes to Supabase user attributes */\n  attribute_mapping?: Record\u003cstring, any\u003e\n  /** Additional parameters sent with the authorization request */\n  authorization_params?: Record\u003cstring, string\u003e\n  /** Whether the provider is enabled */\n  enabled?: boolean\n  /** Whether email is optional for this provider */\n  email_optional?: boolean\n  /** OIDC issuer URL */\n  issuer?: string\n  /** OIDC discovery URL */\n  discovery_url?: string\n  /** Whether to skip nonce check (OIDC) */\n  skip_nonce_check?: boolean\n  /** OAuth2 authorization URL */\n  authorization_url?: string\n  /** OAuth2 token URL */\n  token_url?: string\n  /** OAuth2 userinfo URL */\n  userinfo_url?: string\n  /** JWKS URI for token verification */\n  jwks_uri?: string\n  /** OIDC discovery document (OIDC providers only) */\n  discovery_document?: OIDCDiscoveryDocument | null\n  /** Timestamp when the provider was created */\n  created_at: string\n  /** Timestamp when the provider was last updated */\n  updated_at: string\n}\n\n/**\n * Parameters for creating a new custom provider.\n */\nexport type CreateCustomProviderParams = {\n  /** Provider type */\n  provider_type: CustomProviderType\n  /** Provider identifier (e.g. `custom:mycompany`) */\n  identifier: string\n  /** Human-readable name */\n  name: string\n  /** OAuth client ID */\n  client_id: string\n  /** OAuth client secret (write-only, not returned in responses) */\n  client_secret: string\n  /** Additional client IDs accepted during token validation */\n  acceptable_client_ids?: string[]\n  /** OAuth scopes requested during authorization */\n  scopes?: string[]\n  /**\n   * Allowlist of raw identity provider claim keys to copy verbatim into the\n   * user's `custom_claims` field (within `identity_data` and\n   * `raw_user_meta_data`), e.g. `[\"groups\", \"org_id\", \"mail\"]`. This is an\n   * opt-in allowlist that defaults to empty (no claims captured) and operates\n   * independently from `attribute_mapping`.\n   */\n  custom_claims_allowlist?: string[]\n  /** Whether PKCE is enabled */\n  pkce_enabled?: boolean\n  /** Mapping of provider attributes to Supabase user attributes */\n  attribute_mapping?: Record\u003cstring, any\u003e\n  /** Additional parameters sent with the authorization request */\n  authorization_params?: Record\u003cstring, string\u003e\n  /** Whether the provider is enabled */\n  enabled?: boolean\n  /** Whether email is optional for this provider */\n  email_optional?: boolean\n  /** OIDC issuer URL */\n  issuer?: string\n  /** OIDC discovery URL */\n  discovery_url?: string\n  /** Whether to skip nonce check (OIDC) */\n  skip_nonce_check?: boolean\n  /** OAuth2 authorization URL */\n  authorization_url?: string\n  /** OAuth2 token URL */\n  token_url?: string\n  /** OAuth2 userinfo URL */\n  userinfo_url?: string\n  /** JWKS URI for token verification */\n  jwks_uri?: string\n}\n\n/**\n * Parameters for updating an existing custom provider.\n * All fields are optional. Only provided fields will be updated.\n * `provider_type` and `identifier` are immutable and cannot be changed.\n */\nexport type UpdateCustomProviderParams = {\n  /** Human-readable name */\n  name?: string\n  /** OAuth client ID */\n  client_id?: string\n  /** OAuth client secret (write-only, not returned in responses) */\n  client_secret?: string\n  /** Additional client IDs accepted during token validation */\n  acceptable_client_ids?: string[]\n  /** OAuth scopes requested during authorization */\n  scopes?: string[]\n  /**\n   * Allowlist of raw identity provider claim keys to copy verbatim into the\n   * user's `custom_claims` field (within `identity_data` and\n   * `raw_user_meta_data`), e.g. `[\"groups\", \"org_id\", \"mail\"]`. This is an\n   * opt-in allowlist that defaults to empty (no claims captured) and operates\n   * independently from `attribute_mapping`.\n   */\n  custom_claims_allowlist?: string[]\n  /** Whether PKCE is enabled */\n  pkce_enabled?: boolean\n  /** Mapping of provider attributes to Supabase user attributes */\n  attribute_mapping?: Record\u003cstring, any\u003e\n  /** Additional parameters sent with the authorization request */\n  authorization_params?: Record\u003cstring, string\u003e\n  /** Whether the provider is enabled */\n  enabled?: boolean\n  /** Whether email is optional for this provider */\n  email_optional?: boolean\n  /** OIDC issuer URL */\n  issuer?: string\n  /** OIDC discovery URL */\n  discovery_url?: string\n  /** Whether to skip nonce check (OIDC) */\n  skip_nonce_check?: boolean\n  /** OAuth2 authorization URL */\n  authorization_url?: string\n  /** OAuth2 token URL */\n  token_url?: string\n  /** OAuth2 userinfo URL */\n  userinfo_url?: string\n  /** JWKS URI for token verification */\n  jwks_uri?: string\n}\n\n/**\n * Parameters for listing custom providers.\n */\nexport type ListCustomProvidersParams = {\n  /** Filter by provider type */\n  type?: CustomProviderType\n}\n\n/**\n * Response type for custom provider operations.\n */\nexport type CustomProviderResponse = RequestResult\u003cCustomOAuthProvider\u003e\n\n/**\n * Response type for listing custom providers.\n */\nexport type CustomProviderListResponse =\n  | {\n      data: { providers: CustomOAuthProvider[] }\n      error: null\n    }\n  | {\n      data: { providers: [] }\n      error: AuthError\n    }\n\n/**\n * Contains all custom OIDC/OAuth provider administration methods.\n */\nexport interface GoTrueAdminCustomProvidersApi {\n  /**\n   * Lists all custom providers with optional type filter.\n   *\n   * This function should only be called on a server. Never expose your `service_role` key in the browser.\n   *\n   * @category Auth\n   * @subcategory Auth Admin\n   */\n  listProviders(params?: ListCustomProvidersParams): Promise\u003cCustomProviderListResponse\u003e\n\n  /**\n   * Creates a new custom OIDC/OAuth provider.\n   *\n   * For OIDC providers, the server fetches and validates the OpenID Connect discovery document\n   * from the issuer's well-known endpoint (or the provided `discovery_url`) at creation time.\n   * This may return a validation error (`error_code: \"validation_failed\"`) if the discovery\n   * document is unreachable, not valid JSON, missing required fields, or if the issuer\n   * in the document does not match the expected issuer.\n   *\n   * This function should only be called on a server. Never expose your `service_role` key in the browser.\n   *\n   * @category Auth\n   * @subcategory Auth Admin\n   */\n  createProvider(params: CreateCustomProviderParams): Promise\u003cCustomProviderResponse\u003e\n\n  /**\n   * Gets details of a specific custom provider by identifier.\n   *\n   * This function should only be called on a server. Never expose your `service_role` key in the browser.\n   *\n   * @category Auth\n   * @subcategory Auth Admin\n   */\n  getProvider(identifier: string): Promise\u003cCustomProviderResponse\u003e\n\n  /**\n   * Updates an existing custom provider.\n   *\n   * When `issuer` or `discovery_url` is changed on an OIDC provider, the server re-fetches and\n   * validates the discovery document before persisting. This may return a validation error\n   * (`error_code: \"validation_failed\"`) if the discovery document is unreachable, invalid, or\n   * the issuer does not match.\n   *\n   * This function should only be called on a server. Never expose your `service_role` key in the browser.\n   *\n   * @category Auth\n   * @subcategory Auth Admin\n   */\n  updateProvider(\n    identifier: string,\n    params: UpdateCustomProviderParams\n  ): Promise\u003cCustomProviderResponse\u003e\n\n  /**\n   * Deletes a custom provider.\n   *\n   * This function should only be called on a server. Never expose your `service_role` key in the browser.\n   *\n   * @category Auth\n   * @subcategory Auth Admin\n   */\n  deleteProvider(identifier: string): Promise\u003c{ data: null; error: AuthError | null }\u003e\n}\n\n/**\n * OAuth client details in an authorization request.\n * Only relevant when the OAuth 2.1 server is enabled in Supabase Auth.\n */\nexport type OAuthAuthorizationClient = {\n  /** Unique identifier for the OAuth client (UUID) */\n  id: string\n  /** Human-readable name of the OAuth client */\n  name: string\n  /** URI of the OAuth client's website */\n  uri: string\n  /** URI of the OAuth client's logo */\n  logo_uri: string\n}\n\n/**\n * OAuth authorization details when user needs to provide consent.\n * Only relevant when the OAuth 2.1 server is enabled in Supabase Auth.\n *\n * This response includes all information needed to display a consent page:\n * client details, user info, requested scopes, and where the user will be redirected.\n *\n * Note: `redirect_uri` is the base URI (e.g., \"https://app.com/callback\") without\n * query parameters. After consent, you'll receive a complete `redirect_url` with\n * the authorization code and state parameters appended.\n */\nexport type OAuthAuthorizationDetails = {\n  /** The authorization ID used to approve or deny the request */\n  authorization_id: string\n  /** The OAuth client's registered redirect URI (base URI without query parameters) */\n  redirect_uri: string\n  /** OAuth client requesting authorization */\n  client: OAuthAuthorizationClient\n  /** User object associated with the authorization */\n  user: {\n    /** User ID (UUID) */\n    id: string\n    /** User email */\n    email: string\n  }\n  /** Space-separated list of requested scopes (e.g., \"openid profile email\") */\n  scope: string\n}\n\n/**\n * OAuth redirect response when user has already consented or after consent decision.\n * Only relevant when the OAuth 2.1 server is enabled in Supabase Auth.\n *\n * This response is returned in three scenarios:\n * 1. User already consented to these scopes (auto-approved)\n * 2. User just approved the authorization request\n * 3. User just denied the authorization request\n *\n * The `redirect_url` is a complete URL ready for redirecting the user back to the\n * OAuth client, including authorization code (on success) or error (on denial) in\n * query parameters, along with the state parameter if one was provided.\n */\nexport type OAuthRedirect = {\n  /** Complete redirect URL with authorization code and state parameters (e.g., \"https://app.com/callback?code=xxx\u0026state=yyy\") */\n  redirect_url: string\n}\n\n/**\n * Response type for getting OAuth authorization details.\n * Returns either full authorization details (if consent needed) or redirect URL (if already consented).\n * Only relevant when the OAuth 2.1 server is enabled in Supabase Auth.\n *\n * @example\n * ```typescript\n * const { data, error } = await supabase.auth.oauth.getAuthorizationDetails(authorizationId)\n *\n * if (error) {\n *   console.error('Error:', error)\n * } else if ('authorization_id' in data) {\n *   // User needs to provide consent - show consent page\n *   console.log('Client:', data.client.name)\n *   console.log('Scopes:', data.scope)\n *   console.log('Redirect URI:', data.redirect_uri)\n * } else {\n *   // User already consented - redirect immediately\n *   window.location.href = data.redirect_url\n * }\n * ```\n */\nexport type AuthOAuthAuthorizationDetailsResponse = RequestResult\u003c\n  OAuthAuthorizationDetails | OAuthRedirect\n\u003e\n\n/**\n * Response type for OAuth consent decision (approve/deny).\n * Only relevant when the OAuth 2.1 server is enabled in Supabase Auth.\n */\nexport type AuthOAuthConsentResponse = RequestResult\u003cOAuthRedirect\u003e\n\n/**\n * An OAuth grant representing a user's authorization of an OAuth client.\n * Only relevant when the OAuth 2.1 server is enabled in Supabase Auth.\n */\nexport type OAuthGrant = {\n  /** OAuth client information */\n  client: OAuthAuthorizationClient\n  /** Array of scopes granted to this client */\n  scopes: string[]\n  /** Timestamp when the grant was created (ISO 8601 date-time) */\n  granted_at: string\n}\n\n/**\n * Response type for listing user's OAuth grants.\n * Only relevant when the OAuth 2.1 server is enabled in Supabase Auth.\n */\nexport type AuthOAuthGrantsResponse = RequestResult\u003cOAuthGrant[]\u003e\n\n/**\n * Response type for revoking an OAuth grant.\n * Only relevant when the OAuth 2.1 server is enabled in Supabase Auth.\n */\nexport type AuthOAuthRevokeGrantResponse = RequestResult\u003c{}\u003e\n\n/**\n * Contains all OAuth 2.1 authorization server user-facing methods.\n * Only relevant when the OAuth 2.1 server is enabled in Supabase Auth.\n *\n * These methods are used to implement the consent page.\n */\nexport interface AuthOAuthServerApi {\n  /**\n   * Retrieves details about an OAuth authorization request.\n   * Used to display consent information to the user.\n   * Only relevant when the OAuth 2.1 server is enabled in Supabase Auth.\n   *\n   * This method returns one of two response types:\n   * - `OAuthAuthorizationDetails`: User needs to consent - show consent page with client info\n   * - `OAuthRedirect`: User already consented - redirect immediately to the OAuth client\n   *\n   * Use type narrowing to distinguish between the responses:\n   * ```typescript\n   * if ('authorization_id' in data) {\n   *   // Show consent page\n   * } else {\n   *   // Redirect to data.redirect_url\n   * }\n   * ```\n   *\n   * @param authorizationId - The authorization ID from the authorization request\n   * @returns Authorization details or redirect URL depending on consent status\n   *\n   * @category Auth\n   * @subcategory OAuth Server\n   */\n  getAuthorizationDetails(authorizationId: string): Promise\u003cAuthOAuthAuthorizationDetailsResponse\u003e\n\n  /**\n   * Approves an OAuth authorization request.\n   * Only relevant when the OAuth 2.1 server is enabled in Supabase Auth.\n   *\n   * After approval, the user's consent is stored and an authorization code is generated.\n   * The response contains a complete redirect URL with the authorization code and state.\n   *\n   * @param authorizationId - The authorization ID to approve\n   * @param options - Optional parameters\n   * @param options.skipBrowserRedirect - If false (default), automatically redirects the browser to the OAuth client. If true, returns the redirect_url without automatic redirect (useful for custom handling).\n   * @returns Redirect URL to send the user back to the OAuth client with authorization code\n   *\n   * @category Auth\n   * @subcategory OAuth Server\n   */\n  approveAuthorization(\n    authorizationId: string,\n    options?: { skipBrowserRedirect?: boolean }\n  ): Promise\u003cAuthOAuthConsentResponse\u003e\n\n  /**\n   * Denies an OAuth authorization request.\n   * Only relevant when the OAuth 2.1 server is enabled in Supabase Auth.\n   *\n   * After denial, the response contains a redirect URL with an OAuth error\n   * (access_denied) to inform the OAuth client that the user rejected the request.\n   *\n   * @param authorizationId - The authorization ID to deny\n   * @param options - Optional parameters\n   * @param options.skipBrowserRedirect - If false (default), automatically redirects the browser to the OAuth client. If true, returns the redirect_url without automatic redirect (useful for custom handling).\n   * @returns Redirect URL to send the user back to the OAuth client with error information\n   *\n   * @category Auth\n   * @subcategory OAuth Server\n   */\n  denyAuthorization(\n    authorizationId: string,\n    options?: { skipBrowserRedirect?: boolean }\n  ): Promise\u003cAuthOAuthConsentResponse\u003e\n\n  /**\n   * Lists all OAuth grants that the authenticated user has authorized.\n   * Only relevant when the OAuth 2.1 server is enabled in Supabase Auth.\n   *\n   * @returns Response with array of OAuth grants with client information and granted scopes\n   *\n   * @category Auth\n   * @subcategory OAuth Server\n   */\n  listGrants(): Promise\u003cAuthOAuthGrantsResponse\u003e\n\n  /**\n   * Revokes a user's OAuth grant for a specific client.\n   * Only relevant when the OAuth 2.1 server is enabled in Supabase Auth.\n   *\n   * Revocation marks consent as revoked, deletes active sessions for that OAuth client,\n   * and invalidates associated refresh tokens.\n   *\n   * @param options - Revocation options\n   * @param options.clientId - The OAuth client identifier (UUID) to revoke access for\n   * @returns Empty response on successful revocation\n   *\n   * @category Auth\n   * @subcategory OAuth Server\n   */\n  revokeGrant(options: { clientId: string }): Promise\u003cAuthOAuthRevokeGrantResponse\u003e\n}\n\n// --- Passkey Types ---\n\n/** Response from POST /passkeys/registration/options */\nexport type PasskeyRegistrationOptionsResponse = {\n  challenge_id: string\n  options: ServerCredentialCreationOptions\n  expires_at: number\n}\n\n/** Request body for POST /passkeys/registration/verify */\nexport type PasskeyRegistrationVerifyParams = {\n  challenge_id: string\n  credential: RegistrationResponseJSON\n}\n\n/** Response from POST /passkeys/registration/verify */\nexport type PasskeyMetadata = {\n  id: string\n  friendly_name?: string\n  created_at: string\n}\n\n/** Response from POST /passkeys/authentication/options */\nexport type PasskeyAuthenticationOptionsResponse = {\n  challenge_id: string\n  options: ServerCredentialRequestOptions\n  /** Timestamp in UNIX seconds when this challenge will no longer be usable. */\n  expires_at: number\n}\n\n/** Request body for POST /passkeys/authentication/verify */\nexport type PasskeyAuthenticationVerifyParams = {\n  challenge_id: string\n  credential: AuthenticationResponseJSON\n}\n\n/** Item in the passkeys list (GET /passkeys/ and admin list) */\nexport type PasskeyListItem = {\n  id: string\n  friendly_name?: string\n  created_at: string\n  last_used_at?: string\n}\n\n// --- Passkey SDK Method Parameter/Response Types ---\n\nexport type SignInWithPasskeyCredentials = {\n  options?: {\n    captchaToken?: string\n    signal?: AbortSignal\n    /**\n     * Forwarded to `navigator.credentials.get()` as `mediation`.\n     *\n     * Use `'conditional'` to opt into WebAuthn Conditional UI, where the browser\n     * offers passkeys through the autofill prompt instead of a modal picker. The\n     * page also needs an input with `autocomplete=\"username webauthn\"`.\n     *\n     * When omitted the browser's default (modal) behavior is used.\n     *\n     * Note that the server-side challenge expires (5 minutes by default) while\n     * the autofill prompt can stay pending indefinitely; if the user picks a\n     * passkey after that, verification fails with\n     * `error_code: \"webauthn_challenge_expired\"` and the app should call\n     * `signInWithPasskey()` again. See `signInWithPasskey` for details.\n     *\n     * @see {@link https://developer.mozilla.org/en-US/docs/Web/API/CredentialsContainer/get#mediation MDN - mediation}\n     *\n     * @example\n     * ```ts\n     * const credentials: SignInWithPasskeyCredentials = {\n     *   options: {\n     *     mediation: 'conditional'\n     *   }\n     * }\n     * ```\n     */\n    mediation?: CredentialMediationRequirement\n  }\n}\n\nexport type RegisterPasskeyCredentials = {\n  options?: {\n    signal?: AbortSignal\n  }\n}\n\nexport type VerifyPasskeyRegistrationParams = {\n  /** Challenge ID from startRegistration */\n  challengeId: string\n  /** Serialized credential from navigator.credentials.create() */\n  credential: ServerCredentialResponse\n}\n\nexport type StartPasskeyAuthenticationParams = {\n  options?: {\n    captchaToken?: string\n  }\n}\n\nexport type VerifyPasskeyAuthenticationParams = {\n  /** Challenge ID from startAuthentication */\n  challengeId: string\n  /** Serialized credential from navigator.credentials.get() */\n  credential: ServerCredentialResponse\n}\n\nexport type PasskeyUpdateParams = {\n  /** UUID of the passkey to update */\n  passkeyId: string\n  /** New friendly name (max 120 chars) */\n  friendlyName: string\n}\n\nexport type PasskeyDeleteParams = {\n  /** UUID of the passkey to delete */\n  passkeyId: string\n}\n\n// --- Passkey Response Types ---\n\nexport type AuthPasskeyRegistrationOptionsResponse =\n  RequestResult\u003cPasskeyRegistrationOptionsResponse\u003e\nexport type AuthPasskeyRegistrationVerifyResponse = RequestResult\u003c\n  PasskeyMetadata,\n  WebAuthnError | AuthError\n\u003e\nexport type AuthPasskeyAuthenticationOptionsResponse =\n  RequestResult\u003cPasskeyAuthenticationOptionsResponse\u003e\nexport type AuthPasskeyAuthenticationVerifyResponse = RequestResult\u003c\n  { session: Session | null; user: User | null },\n  WebAuthnError | AuthError\n\u003e\nexport type AuthPasskeyListResponse = RequestResult\u003cPasskeyListItem[]\u003e\nexport type AuthPasskeyUpdateResponse = RequestResult\u003cPasskeyListItem\u003e\nexport type AuthPasskeyDeleteResponse = RequestResult\u003cnull\u003e\n\n// --- Passkey Admin Types ---\n\nexport type AuthPasskeyAdminListParams = {\n  userId: string\n}\n\nexport type AuthPasskeyAdminDeleteParams = {\n  userId: string\n  passkeyId: string\n}\n\n// --- Passkey Namespace Interfaces ---\n\n/**\n * Lower-level two-step API and management methods for passkeys.\n * Access via `supabase.auth.passkey`.\n */\nexport interface AuthPasskeyApi {\n  // Two-step registration\n  /**\n   * Starts the passkey registration ceremony. Fetches a registration challenge\n   * and credential creation options from the server. Used as the first step of\n   * a two-step registration flow when the caller wants to handle\n   * `navigator.credentials.create()` themselves.\n   *\n   * @category Auth\n   * @subcategory Auth Passkey\n   */\n  startRegistration(): Promise\u003cAuthPasskeyRegistrationOptionsResponse\u003e\n\n  /**\n   * Verifies a passkey registration credential against a previously issued\n   * challenge. Used as the second step of a two-step registration flow.\n   *\n   * @category Auth\n   * @subcategory Auth Passkey\n   */\n  verifyRegistration(\n    params: VerifyPasskeyRegistrationParams\n  ): Promise\u003cAuthPasskeyRegistrationVerifyResponse\u003e\n\n  // Two-step authentication\n  /**\n   * Starts the passkey authentication ceremony. Fetches an authentication\n   * challenge and credential request options from the server. Used as the\n   * first step of a two-step sign-in flow when the caller wants to handle\n   * `navigator.credentials.get()` themselves.\n   *\n   * @category Auth\n   * @subcategory Auth Passkey\n   */\n  startAuthentication(\n    params?: StartPasskeyAuthenticationParams\n  ): Promise\u003cAuthPasskeyAuthenticationOptionsResponse\u003e\n\n  /**\n   * Verifies a passkey authentication credential against a previously issued\n   * challenge. Used as the second step of a two-step sign-in flow.\n   *\n   * @category Auth\n   * @subcategory Auth Passkey\n   */\n  verifyAuthentication(\n    params: VerifyPasskeyAuthenticationParams\n  ): Promise\u003cAuthPasskeyAuthenticationVerifyResponse\u003e\n\n  // Management\n  /**\n   * Lists all passkeys registered for the currently signed-in user.\n   *\n   * @category Auth\n   * @subcategory Auth Passkey\n   */\n  list(): Promise\u003cAuthPasskeyListResponse\u003e\n\n  /**\n   * Updates a passkey's friendly name.\n   *\n   * @category Auth\n   * @subcategory Auth Passkey\n   */\n  update(params: PasskeyUpdateParams): Promise\u003cAuthPasskeyUpdateResponse\u003e\n\n  /**\n   * Deletes a passkey for the currently signed-in user.\n   *\n   * @category Auth\n   * @subcategory Auth Passkey\n   */\n  delete(params: PasskeyDeleteParams): Promise\u003cAuthPasskeyDeleteResponse\u003e\n}\n\nexport interface GoTrueAdminPasskeyApi {\n  /**\n   * Lists all passkeys registered for a specific user.\n   *\n   * This function should only be called on a server. Never expose your `service_role` key in the browser.\n   *\n   * @category Auth\n   * @subcategory Passkey Admin\n   */\n  listPasskeys(params: AuthPasskeyAdminListParams): Promise\u003cAuthPasskeyListResponse\u003e\n\n  /**\n   * Deletes a specific passkey for a specific user.\n   *\n   * This function should only be called on a server. Never expose your `service_role` key in the browser.\n   *\n   * @category Auth\n   * @subcategory Passkey Admin\n   */\n  deletePasskey(params: AuthPasskeyAdminDeleteParams): Promise\u003cAuthPasskeyDeleteResponse\u003e\n}\n","import {\n  Fetch,\n  _generateLinkResponse,\n  _noResolveJsonResponse,\n  _request,\n  _userResponse,\n} from './lib/fetch'\nimport { resolveFetch, validateUUID } from './lib/helpers'\nimport {\n  AdminUserAttributes,\n  GenerateLinkParams,\n  GenerateLinkResponse,\n  Pagination,\n  User,\n  UserResponse,\n  GoTrueAdminMFAApi,\n  AuthMFAAdminDeleteFactorParams,\n  AuthMFAAdminDeleteFactorResponse,\n  AuthMFAAdminListFactorsParams,\n  AuthMFAAdminListFactorsResponse,\n  PageParams,\n  SIGN_OUT_SCOPES,\n  SignOutScope,\n  GoTrueAdminOAuthApi,\n  CreateOAuthClientParams,\n  UpdateOAuthClientParams,\n  OAuthClientResponse,\n  OAuthClientListResponse,\n  GoTrueAdminCustomProvidersApi,\n  CreateCustomProviderParams,\n  UpdateCustomProviderParams,\n  ListCustomProvidersParams,\n  CustomProviderResponse,\n  CustomProviderListResponse,\n  GoTrueAdminPasskeyApi,\n  AuthPasskeyAdminListParams,\n  AuthPasskeyAdminDeleteParams,\n  AuthPasskeyListResponse,\n  AuthPasskeyDeleteResponse,\n  ExperimentalFeatureFlags,\n} from './lib/types'\nimport { AuthError, isAuthError } from './lib/errors'\n\nexport default class GoTrueAdminApi {\n  /** Contains all MFA administration methods. */\n  mfa: GoTrueAdminMFAApi\n\n  /**\n   * Contains all OAuth client administration methods.\n   * Only relevant when the OAuth 2.1 server is enabled in Supabase Auth.\n   */\n  oauth: GoTrueAdminOAuthApi\n\n  /** Contains all custom OIDC/OAuth provider administration methods. */\n  customProviders: GoTrueAdminCustomProvidersApi\n\n  /**\n   * Contains all passkey administration methods.\n   */\n  passkey: GoTrueAdminPasskeyApi\n\n  protected url: string\n  protected headers: {\n    [key: string]: string\n  }\n  protected fetch: Fetch\n  protected experimental: ExperimentalFeatureFlags\n\n  /**\n   * Creates an admin API client that can be used to manage users and OAuth clients.\n   *\n   * @example Using supabase-js (recommended)\n   * ```ts\n   * import { createClient } from '@supabase/supabase-js'\n   *\n   * const supabase = createClient('https://xyzcompany.supabase.co', 'your-secret-key')\n   * const { data, error } = await supabase.auth.admin.listUsers()\n   * ```\n   *\n   * @example Standalone import for bundle-sensitive environments\n   * ```ts\n   * import { GoTrueAdminApi } from '@supabase/auth-js'\n   *\n   * const admin = new GoTrueAdminApi({\n   *   url: 'https://xyzcompany.supabase.co/auth/v1',\n   *   headers: { Authorization: `Bearer ${process.env.SUPABASE_SECRET_KEY}` },\n   * })\n   * ```\n   */\n  constructor({\n    url = '',\n    headers = {},\n    fetch,\n    experimental,\n  }: {\n    url: string\n    headers?: {\n      [key: string]: string\n    }\n    fetch?: Fetch\n    experimental?: ExperimentalFeatureFlags\n  }) {\n    this.url = url\n    this.headers = headers\n    this.fetch = resolveFetch(fetch)\n    this.experimental = experimental ?? {}\n    this.mfa = {\n      listFactors: this._listFactors.bind(this),\n      deleteFactor: this._deleteFactor.bind(this),\n    }\n    this.oauth = {\n      listClients: this._listOAuthClients.bind(this),\n      createClient: this._createOAuthClient.bind(this),\n      getClient: this._getOAuthClient.bind(this),\n      updateClient: this._updateOAuthClient.bind(this),\n      deleteClient: this._deleteOAuthClient.bind(this),\n      regenerateClientSecret: this._regenerateOAuthClientSecret.bind(this),\n    }\n    this.customProviders = {\n      listProviders: this._listCustomProviders.bind(this),\n      createProvider: this._createCustomProvider.bind(this),\n      getProvider: this._getCustomProvider.bind(this),\n      updateProvider: this._updateCustomProvider.bind(this),\n      deleteProvider: this._deleteCustomProvider.bind(this),\n    }\n    this.passkey = {\n      listPasskeys: this._adminListPasskeys.bind(this),\n      deletePasskey: this._adminDeletePasskey.bind(this),\n    }\n  }\n\n  /**\n   * Removes a logged-in session.\n   * @param jwt A valid, logged-in JWT.\n   * @param scope The logout sope.\n   *\n   * @category Auth\n   * @subcategory Auth Admin\n   */\n  async signOut(\n    jwt: string,\n    scope: SignOutScope = SIGN_OUT_SCOPES[0]\n  ): Promise\u003c{ data: null; error: AuthError | null }\u003e {\n    if (SIGN_OUT_SCOPES.indexOf(scope) \u003c 0) {\n      throw new Error(\n        `@supabase/auth-js: Parameter scope must be one of ${SIGN_OUT_SCOPES.join(', ')}`\n      )\n    }\n\n    try {\n      await _request(this.fetch, 'POST', `${this.url}/logout?scope=${scope}`, {\n        headers: this.headers,\n        jwt,\n        noResolveJson: true,\n      })\n      return { data: null, error: null }\n    } catch (error) {\n      if (isAuthError(error)) {\n        return { data: null, error }\n      }\n\n      throw error\n    }\n  }\n\n  /**\n   * Sends an invite link to an email address.\n   * @param email The email address of the user.\n   * @param options Additional options to be included when inviting.\n   *\n   * @category Auth\n   * @subcategory Auth Admin\n   *\n   * @remarks\n   * - Sends an invite link to the user's email address.\n   * - The `inviteUserByEmail()` method is typically used by administrators to invite users to join the application.\n   * - Note that PKCE is not supported when using `inviteUserByEmail`. This is because the browser initiating the invite is often different from the browser accepting the invite which makes it difficult to provide the security guarantees required of the PKCE flow.\n   *\n   * @example Invite a user\n   * ```js\n   * const { data, error } = await supabase.auth.admin.inviteUserByEmail('email@example.com')\n   * ```\n   *\n   * @exampleResponse Invite a user\n   * ```json\n   * {\n   *   \"data\": {\n   *     \"user\": {\n   *       \"id\": \"11111111-1111-1111-1111-111111111111\",\n   *       \"aud\": \"authenticated\",\n   *       \"role\": \"authenticated\",\n   *       \"email\": \"example@email.com\",\n   *       \"invited_at\": \"2024-01-01T00:00:00Z\",\n   *       \"phone\": \"\",\n   *       \"confirmation_sent_at\": \"2024-01-01T00:00:00Z\",\n   *       \"app_metadata\": {\n   *         \"provider\": \"email\",\n   *         \"providers\": [\n   *           \"email\"\n   *         ]\n   *       },\n   *       \"user_metadata\": {},\n   *       \"identities\": [\n   *         {\n   *           \"identity_id\": \"22222222-2222-2222-2222-222222222222\",\n   *           \"id\": \"11111111-1111-1111-1111-111111111111\",\n   *           \"user_id\": \"11111111-1111-1111-1111-111111111111\",\n   *           \"identity_data\": {\n   *             \"email\": \"example@email.com\",\n   *             \"email_verified\": false,\n   *             \"phone_verified\": false,\n   *             \"sub\": \"11111111-1111-1111-1111-111111111111\"\n   *           },\n   *           \"provider\": \"email\",\n   *           \"last_sign_in_at\": \"2024-01-01T00:00:00Z\",\n   *           \"created_at\": \"2024-01-01T00:00:00Z\",\n   *           \"updated_at\": \"2024-01-01T00:00:00Z\",\n   *           \"email\": \"example@email.com\"\n   *         }\n   *       ],\n   *       \"created_at\": \"2024-01-01T00:00:00Z\",\n   *       \"updated_at\": \"2024-01-01T00:00:00Z\",\n   *       \"is_anonymous\": false\n   *     }\n   *   },\n   *   \"error\": null\n   * }\n   * ```\n   */\n  async inviteUserByEmail(\n    email: string,\n    options: {\n      /** A custom data object to store additional metadata about the user. This maps to the `auth.users.user_metadata` column. */\n      data?: object\n\n      /** The URL which will be appended to the email link sent to the user's email address. Once clicked the user will end up on this URL. */\n      redirectTo?: string\n    } = {}\n  ): Promise\u003cUserResponse\u003e {\n    try {\n      return await _request(this.fetch, 'POST', `${this.url}/invite`, {\n        body: { email, data: options.data },\n        headers: this.headers,\n        redirectTo: options.redirectTo,\n        xform: _userResponse,\n      })\n    } catch (error) {\n      if (isAuthError(error)) {\n        return { data: { user: null }, error }\n      }\n\n      throw error\n    }\n  }\n\n  /**\n   * Generates email links and OTPs to be sent via a custom email provider.\n   * @param params The parameters for generating the link, including the link `type`, the user's `email`, and type-specific options such as `password`, `data`, and `redirectTo`.\n   *\n   * @category Auth\n   * @subcategory Auth Admin\n   *\n   * @remarks\n   * - The following types can be passed into `generateLink()`: `signup`, `magiclink`, `invite`, `recovery`, `email_change_current`, `email_change_new`, `phone_change`.\n   * - `generateLink()` only generates the email link for `email_change_email` if the **Secure email change** is enabled in your project's [email auth provider settings](/dashboard/project/_/auth/providers).\n   * - `generateLink()` handles the creation of the user for `signup`, `invite` and `magiclink`.\n   *\n   * @example Generate a signup link\n   * ```js\n   * const { data, error } = await supabase.auth.admin.generateLink({\n   *   type: 'signup',\n   *   email: 'email@example.com',\n   *   password: 'secret'\n   * })\n   * ```\n   *\n   * @exampleResponse Generate a signup link\n   * ```json\n   * {\n   *   \"data\": {\n   *     \"properties\": {\n   *       \"action_link\": \"\u003cLINK_TO_SEND_TO_USER\u003e\",\n   *       \"email_otp\": \"999999\",\n   *       \"hashed_token\": \"\u003cHASHED_TOKEN\",\n   *       \"redirect_to\": \"\u003cREDIRECT_URL\u003e\",\n   *       \"verification_type\": \"signup\"\n   *     },\n   *     \"user\": {\n   *       \"id\": \"11111111-1111-1111-1111-111111111111\",\n   *       \"aud\": \"authenticated\",\n   *       \"role\": \"authenticated\",\n   *       \"email\": \"email@example.com\",\n   *       \"phone\": \"\",\n   *       \"confirmation_sent_at\": \"2024-01-01T00:00:00Z\",\n   *       \"app_metadata\": {\n   *         \"provider\": \"email\",\n   *         \"providers\": [\n   *           \"email\"\n   *         ]\n   *       },\n   *       \"user_metadata\": {},\n   *       \"identities\": [\n   *         {\n   *           \"identity_id\": \"22222222-2222-2222-2222-222222222222\",\n   *           \"id\": \"11111111-1111-1111-1111-111111111111\",\n   *           \"user_id\": \"11111111-1111-1111-1111-111111111111\",\n   *           \"identity_data\": {\n   *             \"email\": \"email@example.com\",\n   *             \"email_verified\": false,\n   *             \"phone_verified\": false,\n   *             \"sub\": \"11111111-1111-1111-1111-111111111111\"\n   *           },\n   *           \"provider\": \"email\",\n   *           \"last_sign_in_at\": \"2024-01-01T00:00:00Z\",\n   *           \"created_at\": \"2024-01-01T00:00:00Z\",\n   *           \"updated_at\": \"2024-01-01T00:00:00Z\",\n   *           \"email\": \"email@example.com\"\n   *         }\n   *       ],\n   *       \"created_at\": \"2024-01-01T00:00:00Z\",\n   *       \"updated_at\": \"2024-01-01T00:00:00Z\",\n   *       \"is_anonymous\": false\n   *     }\n   *   },\n   *   \"error\": null\n   * }\n   * ```\n   *\n   * @example Generate an invite link\n   * ```js\n   * const { data, error } = await supabase.auth.admin.generateLink({\n   *   type: 'invite',\n   *   email: 'email@example.com'\n   * })\n   * ```\n   *\n   * @example Generate a magic link\n   * ```js\n   * const { data, error } = await supabase.auth.admin.generateLink({\n   *   type: 'magiclink',\n   *   email: 'email@example.com'\n   * })\n   * ```\n   *\n   * @example Generate a recovery link\n   * ```js\n   * const { data, error } = await supabase.auth.admin.generateLink({\n   *   type: 'recovery',\n   *   email: 'email@example.com'\n   * })\n   * ```\n   *\n   * @example Generate links to change current email address\n   * ```js\n   * // generate an email change link to be sent to the current email address\n   * const { data, error } = await supabase.auth.admin.generateLink({\n   *   type: 'email_change_current',\n   *   email: 'current.email@example.com',\n   *   newEmail: 'new.email@example.com'\n   * })\n   *\n   * // generate an email change link to be sent to the new email address\n   * const { data, error } = await supabase.auth.admin.generateLink({\n   *   type: 'email_change_new',\n   *   email: 'current.email@example.com',\n   *   newEmail: 'new.email@example.com'\n   * })\n   * ```\n   */\n  async generateLink(params: GenerateLinkParams): Promise\u003cGenerateLinkResponse\u003e {\n    try {\n      const { options, ...rest } = params\n      const body: any = { ...rest, ...options }\n      if ('newEmail' in rest) {\n        // replace newEmail with new_email in request body\n        body.new_email = rest?.newEmail\n        delete body['newEmail']\n      }\n      return await _request(this.fetch, 'POST', `${this.url}/admin/generate_link`, {\n        body: body,\n        headers: this.headers,\n        xform: _generateLinkResponse,\n        redirectTo: options?.redirectTo,\n      })\n    } catch (error) {\n      if (isAuthError(error)) {\n        return {\n          data: {\n            properties: null,\n            user: null,\n          },\n          error,\n        }\n      }\n      throw error\n    }\n  }\n\n  // User Admin API\n  /**\n   * Creates a new user.\n   * This function should only be called on a server. Never expose your `service_role` key in the browser.\n   *\n   * @category Auth\n   * @subcategory Auth Admin\n   *\n   * @remarks\n   * - To confirm the user's email address or phone number, set `email_confirm` or `phone_confirm` to true. Both arguments default to false.\n   * - `createUser()` will not send a confirmation email to the user. You can use [`inviteUserByEmail()`](/docs/reference/javascript/auth-admin-inviteuserbyemail) if you want to send them an email invite instead.\n   * - If you are sure that the created user's email or phone number is legitimate and verified, you can set the `email_confirm` or `phone_confirm` param to `true`.\n   *\n   * @example With custom user metadata\n   * ```js\n   * const { data, error } = await supabase.auth.admin.createUser({\n   *   email: 'user@email.com',\n   *   password: 'password',\n   *   user_metadata: { name: 'Yoda' }\n   * })\n   * ```\n   *\n   * @exampleResponse With custom user metadata\n   * ```json\n   * {\n   *   data: {\n   *     user: {\n   *       id: '1',\n   *       aud: 'authenticated',\n   *       role: 'authenticated',\n   *       email: 'example@email.com',\n   *       email_confirmed_at: '2024-01-01T00:00:00Z',\n   *       phone: '',\n   *       confirmation_sent_at: '2024-01-01T00:00:00Z',\n   *       confirmed_at: '2024-01-01T00:00:00Z',\n   *       last_sign_in_at: '2024-01-01T00:00:00Z',\n   *       app_metadata: {},\n   *       user_metadata: {},\n   *       identities: [\n   *         {\n   *           \"identity_id\": \"22222222-2222-2222-2222-222222222222\",\n   *           \"id\": \"1\",\n   *           \"user_id\": \"1\",\n   *           \"identity_data\": {\n   *             \"email\": \"example@email.com\",\n   *             \"email_verified\": true,\n   *             \"phone_verified\": false,\n   *             \"sub\": \"1\"\n   *           },\n   *           \"provider\": \"email\",\n   *           \"last_sign_in_at\": \"2024-01-01T00:00:00Z\",\n   *           \"created_at\": \"2024-01-01T00:00:00Z\",\n   *           \"updated_at\": \"2024-01-01T00:00:00Z\",\n   *           \"email\": \"email@example.com\"\n   *         },\n   *       ],\n   *       created_at: '2024-01-01T00:00:00Z',\n   *       updated_at: '2024-01-01T00:00:00Z',\n   *       is_anonymous: false,\n   *     }\n   *   }\n   *   error: null\n   * }\n   * ```\n   *\n   * @example Auto-confirm the user's email\n   * ```js\n   * const { data, error } = await supabase.auth.admin.createUser({\n   *   email: 'user@email.com',\n   *   email_confirm: true\n   * })\n   * ```\n   *\n   * @example Auto-confirm the user's phone number\n   * ```js\n   * const { data, error } = await supabase.auth.admin.createUser({\n   *   phone: '1234567890',\n   *   phone_confirm: true\n   * })\n   * ```\n   */\n  async createUser(attributes: AdminUserAttributes): Promise\u003cUserResponse\u003e {\n    try {\n      return await _request(this.fetch, 'POST', `${this.url}/admin/users`, {\n        body: attributes,\n        headers: this.headers,\n        xform: _userResponse,\n      })\n    } catch (error) {\n      if (isAuthError(error)) {\n        return { data: { user: null }, error }\n      }\n\n      throw error\n    }\n  }\n\n  /**\n   * Get a list of users.\n   *\n   * This function should only be called on a server. Never expose your `service_role` key in the browser.\n   * @param params An object which supports `page` and `perPage` as numbers, to alter the paginated results.\n   *\n   * @category Auth\n   * @subcategory Auth Admin\n   *\n   * @remarks\n   * - Defaults to return 50 users per page.\n   *\n   * @example Get a page of users\n   * ```js\n   * const { data: { users }, error } = await supabase.auth.admin.listUsers()\n   * ```\n   *\n   * @example Paginated list of users\n   * ```js\n   * const { data: { users }, error } = await supabase.auth.admin.listUsers({\n   *   page: 1,\n   *   perPage: 1000\n   * })\n   * ```\n   */\n  async listUsers(\n    params?: PageParams\n  ): Promise\u003c\n    | { data: { users: User[]; aud: string } \u0026 Pagination; error: null }\n    | { data: { users: [] }; error: AuthError }\n  \u003e {\n    try {\n      const pagination: Pagination = { nextPage: null, lastPage: 0, total: 0 }\n      const response = await _request(this.fetch, 'GET', `${this.url}/admin/users`, {\n        headers: this.headers,\n        noResolveJson: true,\n        query: {\n          page: params?.page?.toString() ?? '',\n          per_page: params?.perPage?.toString() ?? '',\n        },\n        xform: _noResolveJsonResponse,\n      })\n      if (response.error) throw response.error\n\n      const users = await response.json()\n      const total = response.headers.get('x-total-count') ?? 0\n      const links = response.headers.get('link')?.split(',') ?? []\n      if (links.length \u003e 0) {\n        links.forEach((link: string) =\u003e {\n          const page = parseInt(link.split(';')[0].split('=')[1].substring(0, 1))\n          const rel = JSON.parse(link.split(';')[1].split('=')[1])\n          pagination[`${rel}Page`] = page\n        })\n\n        pagination.total = parseInt(total)\n      }\n      return { data: { ...users, ...pagination }, error: null }\n    } catch (error) {\n      if (isAuthError(error)) {\n        return { data: { users: [] }, error }\n      }\n      throw error\n    }\n  }\n\n  /**\n   * Get user by id.\n   *\n   * @param uid The user's unique identifier\n   *\n   * This function should only be called on a server. Never expose your `service_role` key in the browser.\n   *\n   * @category Auth\n   * @subcategory Auth Admin\n   *\n   * @remarks\n   * - Fetches the user object from the database based on the user's id.\n   * - The `getUserById()` method requires the user's id which maps to the `auth.users.id` column.\n   *\n   * @example Fetch the user object using the access_token jwt\n   * ```js\n   * const { data, error } = await supabase.auth.admin.getUserById(1)\n   * ```\n   *\n   * @exampleResponse Fetch the user object using the access_token jwt\n   * ```json\n   * {\n   *   data: {\n   *     user: {\n   *       id: '1',\n   *       aud: 'authenticated',\n   *       role: 'authenticated',\n   *       email: 'example@email.com',\n   *       email_confirmed_at: '2024-01-01T00:00:00Z',\n   *       phone: '',\n   *       confirmation_sent_at: '2024-01-01T00:00:00Z',\n   *       confirmed_at: '2024-01-01T00:00:00Z',\n   *       last_sign_in_at: '2024-01-01T00:00:00Z',\n   *       app_metadata: {},\n   *       user_metadata: {},\n   *       identities: [\n   *         {\n   *           \"identity_id\": \"22222222-2222-2222-2222-222222222222\",\n   *           \"id\": \"1\",\n   *           \"user_id\": \"1\",\n   *           \"identity_data\": {\n   *             \"email\": \"example@email.com\",\n   *             \"email_verified\": true,\n   *             \"phone_verified\": false,\n   *             \"sub\": \"1\"\n   *           },\n   *           \"provider\": \"email\",\n   *           \"last_sign_in_at\": \"2024-01-01T00:00:00Z\",\n   *           \"created_at\": \"2024-01-01T00:00:00Z\",\n   *           \"updated_at\": \"2024-01-01T00:00:00Z\",\n   *           \"email\": \"email@example.com\"\n   *         },\n   *       ],\n   *       created_at: '2024-01-01T00:00:00Z',\n   *       updated_at: '2024-01-01T00:00:00Z',\n   *       is_anonymous: false,\n   *     }\n   *   }\n   *   error: null\n   * }\n   * ```\n   */\n  async getUserById(uid: string): Promise\u003cUserResponse\u003e {\n    validateUUID(uid)\n\n    try {\n      return await _request(this.fetch, 'GET', `${this.url}/admin/users/${uid}`, {\n        headers: this.headers,\n        xform: _userResponse,\n      })\n    } catch (error) {\n      if (isAuthError(error)) {\n        return { data: { user: null }, error }\n      }\n\n      throw error\n    }\n  }\n\n  /**\n   * Updates the user data. Changes are applied directly without confirmation flows.\n   *\n   * @param uid The user's unique identifier\n   * @param attributes The data you want to update.\n   *\n   * This function should only be called on a server. Never expose your `service_role` key in the browser.\n   *\n   * @remarks\n   * **Important:** This is a server-side operation and does **not** trigger client-side\n   * `onAuthStateChange` listeners. The admin API has no connection to client state.\n   *\n   * To sync changes to the client after calling this method:\n   * 1. On the client, call `supabase.auth.refreshSession()` to fetch the updated user data\n   * 2. This will trigger the `TOKEN_REFRESHED` event and notify all listeners\n   *\n   * @example\n   * ```typescript\n   * // Server-side (Edge Function)\n   * const { data, error } = await supabase.auth.admin.updateUserById(\n   *   userId,\n   *   { user_metadata: { preferences: { theme: 'dark' } } }\n   * )\n   *\n   * // Client-side (to sync the changes)\n   * const { data, error } = await supabase.auth.refreshSession()\n   * // onAuthStateChange listeners will now be notified with updated user\n   * ```\n   *\n   * @see {@link GoTrueClient.refreshSession} for syncing admin changes to the client\n   * @see {@link GoTrueClient.updateUser} for client-side user updates (triggers listeners automatically)\n   *\n   * @category Auth\n   * @subcategory Auth Admin\n   *\n   * @example Updates a user's email\n   * ```js\n   * const { data: user, error } = await supabase.auth.admin.updateUserById(\n   *   '11111111-1111-1111-1111-111111111111',\n   *   { email: 'new@email.com' }\n   * )\n   * ```\n   *\n   * @exampleResponse Updates a user's email\n   * ```json\n   * {\n   *   \"data\": {\n   *     \"user\": {\n   *       \"id\": \"11111111-1111-1111-1111-111111111111\",\n   *       \"aud\": \"authenticated\",\n   *       \"role\": \"authenticated\",\n   *       \"email\": \"new@email.com\",\n   *       \"email_confirmed_at\": \"2024-01-01T00:00:00Z\",\n   *       \"phone\": \"\",\n   *       \"confirmed_at\": \"2024-01-01T00:00:00Z\",\n   *       \"recovery_sent_at\": \"2024-01-01T00:00:00Z\",\n   *       \"last_sign_in_at\": \"2024-01-01T00:00:00Z\",\n   *       \"app_metadata\": {\n   *         \"provider\": \"email\",\n   *         \"providers\": [\n   *           \"email\"\n   *         ]\n   *       },\n   *       \"user_metadata\": {\n   *         \"email\": \"example@email.com\",\n   *         \"email_verified\": false,\n   *         \"phone_verified\": false,\n   *         \"sub\": \"11111111-1111-1111-1111-111111111111\"\n   *       },\n   *       \"identities\": [\n   *         {\n   *           \"identity_id\": \"22222222-2222-2222-2222-222222222222\",\n   *           \"id\": \"11111111-1111-1111-1111-111111111111\",\n   *           \"user_id\": \"11111111-1111-1111-1111-111111111111\",\n   *           \"identity_data\": {\n   *             \"email\": \"example@email.com\",\n   *             \"email_verified\": false,\n   *             \"phone_verified\": false,\n   *             \"sub\": \"11111111-1111-1111-1111-111111111111\"\n   *           },\n   *           \"provider\": \"email\",\n   *           \"last_sign_in_at\": \"2024-01-01T00:00:00Z\",\n   *           \"created_at\": \"2024-01-01T00:00:00Z\",\n   *           \"updated_at\": \"2024-01-01T00:00:00Z\",\n   *           \"email\": \"example@email.com\"\n   *         }\n   *       ],\n   *       \"created_at\": \"2024-01-01T00:00:00Z\",\n   *       \"updated_at\": \"2024-01-01T00:00:00Z\",\n   *       \"is_anonymous\": false\n   *     }\n   *   },\n   *   \"error\": null\n   * }\n   * ```\n   *\n   * @example Updates a user's password\n   * ```js\n   * const { data: user, error } = await supabase.auth.admin.updateUserById(\n   *   '6aa5d0d4-2a9f-4483-b6c8-0cf4c6c98ac4',\n   *   { password: 'new_password' }\n   * )\n   * ```\n   *\n   * @example Updates a user's metadata\n   * ```js\n   * const { data: user, error } = await supabase.auth.admin.updateUserById(\n   *   '6aa5d0d4-2a9f-4483-b6c8-0cf4c6c98ac4',\n   *   { user_metadata: { hello: 'world' } }\n   * )\n   * ```\n   *\n   * @example Updates a user's app_metadata\n   * ```js\n   * const { data: user, error } = await supabase.auth.admin.updateUserById(\n   *   '6aa5d0d4-2a9f-4483-b6c8-0cf4c6c98ac4',\n   *   { app_metadata: { plan: 'trial' } }\n   * )\n   * ```\n   *\n   * @example Confirms a user's email address\n   * ```js\n   * const { data: user, error } = await supabase.auth.admin.updateUserById(\n   *   '6aa5d0d4-2a9f-4483-b6c8-0cf4c6c98ac4',\n   *   { email_confirm: true }\n   * )\n   * ```\n   *\n   * @example Confirms a user's phone number\n   * ```js\n   * const { data: user, error } = await supabase.auth.admin.updateUserById(\n   *   '6aa5d0d4-2a9f-4483-b6c8-0cf4c6c98ac4',\n   *   { phone_confirm: true }\n   * )\n   * ```\n   *\n   * @example Ban a user for 100 years\n   * ```js\n   * const { data: user, error } = await supabase.auth.admin.updateUserById(\n   *   '6aa5d0d4-2a9f-4483-b6c8-0cf4c6c98ac4',\n   *   { ban_duration: '876000h' }\n   * )\n   * ```\n   */\n  async updateUserById(uid: string, attributes: AdminUserAttributes): Promise\u003cUserResponse\u003e {\n    validateUUID(uid)\n\n    try {\n      return await _request(this.fetch, 'PUT', `${this.url}/admin/users/${uid}`, {\n        body: attributes,\n        headers: this.headers,\n        xform: _userResponse,\n      })\n    } catch (error) {\n      if (isAuthError(error)) {\n        return { data: { user: null }, error }\n      }\n\n      throw error\n    }\n  }\n\n  /**\n   * Delete a user. Requires a `service_role` key.\n   * Returns the user that was deleted. In cases of concurrent updates, the user object returned\n   * might not accurately reflect the user information at the time of deletion.\n   *\n   * @param id The user id you want to remove.\n   * @param shouldSoftDelete If true, then the user will be soft-deleted from the auth schema. Soft deletion allows user identification from the hashed user ID but is not reversible.\n   * Defaults to false for backward compatibility.\n   *\n   * This function should only be called on a server. Never expose your `service_role` key in the browser.\n   *\n   * @category Auth\n   * @subcategory Auth Admin\n   *\n   * @remarks\n   * - The `deleteUser()` method requires the user's ID, which maps to the `auth.users.id` column.\n   *\n   * @example Removes a user\n   * ```js\n   * const { data, error } = await supabase.auth.admin.deleteUser(\n   *   '715ed5db-f090-4b8c-a067-640ecee36aa0'\n   * )\n   * ```\n   *\n   * @exampleResponse Removes a user\n   * ```json\n   * {\n   *   \"data\": {\n   *     \"user\": {\n   *       \"id\": \"715ed5db-f090-4b8c-a067-640ecee36aa0\",\n   *       \"aud\": \"authenticated\",\n   *       \"role\": \"authenticated\",\n   *       \"email\": \"example@email.com\",\n   *       \"created_at\": \"2024-01-01T00:00:00Z\",\n   *       \"updated_at\": \"2024-01-01T00:00:00Z\"\n   *     }\n   *   },\n   *   \"error\": null\n   * }\n   * ```\n   */\n  async deleteUser(id: string, shouldSoftDelete = false): Promise\u003cUserResponse\u003e {\n    validateUUID(id)\n\n    try {\n      // The Auth server answers the DELETE with an empty object. However, this is\n      // a breaking change in the JS API, so until `v3` is released, we polyfill the\n      // result by fetching the user information before it gets deleted.\n      // See https://github.com/supabase/supabase-js/issues/2751\n      const { data, error } = await this.getUserById(id)\n      if (error) {\n        return { data: { user: null }, error }\n      }\n\n      await _request(this.fetch, 'DELETE', `${this.url}/admin/users/${id}`, {\n        headers: this.headers,\n        body: {\n          should_soft_delete: shouldSoftDelete,\n        },\n        noResolveJson: true,\n      })\n\n      return { data, error: null }\n    } catch (error) {\n      if (isAuthError(error)) {\n        return { data: { user: null }, error }\n      }\n\n      throw error\n    }\n  }\n\n  private async _listFactors(\n    params: AuthMFAAdminListFactorsParams\n  ): Promise\u003cAuthMFAAdminListFactorsResponse\u003e {\n    validateUUID(params.userId)\n\n    try {\n      const { data, error } = await _request(\n        this.fetch,\n        'GET',\n        `${this.url}/admin/users/${params.userId}/factors`,\n        {\n          headers: this.headers,\n          xform: (factors: any) =\u003e {\n            return { data: { factors }, error: null }\n          },\n        }\n      )\n      return { data, error }\n    } catch (error) {\n      if (isAuthError(error)) {\n        return { data: null, error }\n      }\n\n      throw error\n    }\n  }\n\n  private async _deleteFactor(\n    params: AuthMFAAdminDeleteFactorParams\n  ): Promise\u003cAuthMFAAdminDeleteFactorResponse\u003e {\n    validateUUID(params.userId)\n    validateUUID(params.id)\n\n    try {\n      const data = await _request(\n        this.fetch,\n        'DELETE',\n        `${this.url}/admin/users/${params.userId}/factors/${params.id}`,\n        {\n          headers: this.headers,\n        }\n      )\n\n      return { data, error: null }\n    } catch (error) {\n      if (isAuthError(error)) {\n        return { data: null, error }\n      }\n\n      throw error\n    }\n  }\n\n  /**\n   * Lists all OAuth clients with optional pagination.\n   * Only relevant when the OAuth 2.1 server is enabled in Supabase Auth.\n   *\n   * This function should only be called on a server. Never expose your `service_role` key in the browser.\n   */\n  private async _listOAuthClients(params?: PageParams): Promise\u003cOAuthClientListResponse\u003e {\n    try {\n      const pagination: Pagination = { nextPage: null, lastPage: 0, total: 0 }\n      const response = await _request(this.fetch, 'GET', `${this.url}/admin/oauth/clients`, {\n        headers: this.headers,\n        noResolveJson: true,\n        query: {\n          page: params?.page?.toString() ?? '',\n          per_page: params?.perPage?.toString() ?? '',\n        },\n        xform: _noResolveJsonResponse,\n      })\n      if (response.error) throw response.error\n\n      const clients = await response.json()\n      const total = response.headers.get('x-total-count') ?? 0\n      const links = response.headers.get('link')?.split(',') ?? []\n      if (links.length \u003e 0) {\n        links.forEach((link: string) =\u003e {\n          const page = parseInt(link.split(';')[0].split('=')[1].substring(0, 1))\n          const rel = JSON.parse(link.split(';')[1].split('=')[1])\n          pagination[`${rel}Page`] = page\n        })\n\n        pagination.total = parseInt(total)\n      }\n      return { data: { ...clients, ...pagination }, error: null }\n    } catch (error) {\n      if (isAuthError(error)) {\n        return { data: { clients: [] }, error }\n      }\n      throw error\n    }\n  }\n\n  /**\n   * Creates a new OAuth client.\n   * Only relevant when the OAuth 2.1 server is enabled in Supabase Auth.\n   *\n   * This function should only be called on a server. Never expose your `service_role` key in the browser.\n   */\n  private async _createOAuthClient(params: CreateOAuthClientParams): Promise\u003cOAuthClientResponse\u003e {\n    try {\n      return await _request(this.fetch, 'POST', `${this.url}/admin/oauth/clients`, {\n        body: params,\n        headers: this.headers,\n        xform: (client: any) =\u003e {\n          return { data: client, error: null }\n        },\n      })\n    } catch (error) {\n      if (isAuthError(error)) {\n        return { data: null, error }\n      }\n\n      throw error\n    }\n  }\n\n  /**\n   * Gets details of a specific OAuth client.\n   * Only relevant when the OAuth 2.1 server is enabled in Supabase Auth.\n   *\n   * This function should only be called on a server. Never expose your `service_role` key in the browser.\n   */\n  private async _getOAuthClient(clientId: string): Promise\u003cOAuthClientResponse\u003e {\n    try {\n      return await _request(this.fetch, 'GET', `${this.url}/admin/oauth/clients/${clientId}`, {\n        headers: this.headers,\n        xform: (client: any) =\u003e {\n          return { data: client, error: null }\n        },\n      })\n    } catch (error) {\n      if (isAuthError(error)) {\n        return { data: null, error }\n      }\n\n      throw error\n    }\n  }\n\n  /**\n   * Updates an existing OAuth client.\n   * Only relevant when the OAuth 2.1 server is enabled in Supabase Auth.\n   *\n   * This function should only be called on a server. Never expose your `service_role` key in the browser.\n   */\n  private async _updateOAuthClient(\n    clientId: string,\n    params: UpdateOAuthClientParams\n  ): Promise\u003cOAuthClientResponse\u003e {\n    try {\n      return await _request(this.fetch, 'PUT', `${this.url}/admin/oauth/clients/${clientId}`, {\n        body: params,\n        headers: this.headers,\n        xform: (client: any) =\u003e {\n          return { data: client, error: null }\n        },\n      })\n    } catch (error) {\n      if (isAuthError(error)) {\n        return { data: null, error }\n      }\n\n      throw error\n    }\n  }\n\n  /**\n   * Deletes an OAuth client.\n   * Only relevant when the OAuth 2.1 server is enabled in Supabase Auth.\n   *\n   * This function should only be called on a server. Never expose your `service_role` key in the browser.\n   */\n  private async _deleteOAuthClient(\n    clientId: string\n  ): Promise\u003c{ data: null; error: AuthError | null }\u003e {\n    try {\n      await _request(this.fetch, 'DELETE', `${this.url}/admin/oauth/clients/${clientId}`, {\n        headers: this.headers,\n        noResolveJson: true,\n      })\n      return { data: null, error: null }\n    } catch (error) {\n      if (isAuthError(error)) {\n        return { data: null, error }\n      }\n\n      throw error\n    }\n  }\n\n  /**\n   * Regenerates the secret for an OAuth client.\n   * Only relevant when the OAuth 2.1 server is enabled in Supabase Auth.\n   *\n   * This function should only be called on a server. Never expose your `service_role` key in the browser.\n   */\n  private async _regenerateOAuthClientSecret(clientId: string): Promise\u003cOAuthClientResponse\u003e {\n    try {\n      return await _request(\n        this.fetch,\n        'POST',\n        `${this.url}/admin/oauth/clients/${clientId}/regenerate_secret`,\n        {\n          headers: this.headers,\n          xform: (client: any) =\u003e {\n            return { data: client, error: null }\n          },\n        }\n      )\n    } catch (error) {\n      if (isAuthError(error)) {\n        return { data: null, error }\n      }\n\n      throw error\n    }\n  }\n\n  /**\n   * Lists all custom providers with optional type filter.\n   *\n   * This function should only be called on a server. Never expose your `service_role` key in the browser.\n   */\n  private async _listCustomProviders(\n    params?: ListCustomProvidersParams\n  ): Promise\u003cCustomProviderListResponse\u003e {\n    try {\n      const query: Record\u003cstring, string\u003e = {}\n      if (params?.type) {\n        query.type = params.type\n      }\n      return await _request(this.fetch, 'GET', `${this.url}/admin/custom-providers`, {\n        headers: this.headers,\n        query,\n        xform: (data: any) =\u003e {\n          return { data: { providers: data?.providers ?? [] }, error: null }\n        },\n      })\n    } catch (error) {\n      if (isAuthError(error)) {\n        return { data: { providers: [] }, error }\n      }\n      throw error\n    }\n  }\n\n  /**\n   * Creates a new custom OIDC/OAuth provider.\n   *\n   * For OIDC providers, the server fetches and validates the OpenID Connect discovery document\n   * from the issuer's well-known endpoint (or the provided `discovery_url`) at creation time.\n   * This may return a validation error (`error_code: \"validation_failed\"`) if the discovery\n   * document is unreachable, not valid JSON, missing required fields, or if the issuer\n   * in the document does not match the expected issuer.\n   *\n   * This function should only be called on a server. Never expose your `service_role` key in the browser.\n   */\n  private async _createCustomProvider(\n    params: CreateCustomProviderParams\n  ): Promise\u003cCustomProviderResponse\u003e {\n    try {\n      return await _request(this.fetch, 'POST', `${this.url}/admin/custom-providers`, {\n        body: params,\n        headers: this.headers,\n        xform: (provider: any) =\u003e {\n          return { data: provider, error: null }\n        },\n      })\n    } catch (error) {\n      if (isAuthError(error)) {\n        return { data: null, error }\n      }\n      throw error\n    }\n  }\n\n  /**\n   * Gets details of a specific custom provider by identifier.\n   *\n   * This function should only be called on a server. Never expose your `service_role` key in the browser.\n   */\n  private async _getCustomProvider(identifier: string): Promise\u003cCustomProviderResponse\u003e {\n    try {\n      return await _request(this.fetch, 'GET', `${this.url}/admin/custom-providers/${identifier}`, {\n        headers: this.headers,\n        xform: (provider: any) =\u003e {\n          return { data: provider, error: null }\n        },\n      })\n    } catch (error) {\n      if (isAuthError(error)) {\n        return { data: null, error }\n      }\n      throw error\n    }\n  }\n\n  /**\n   * Updates an existing custom provider.\n   *\n   * When `issuer` or `discovery_url` is changed on an OIDC provider, the server re-fetches and\n   * validates the discovery document before persisting. This may return a validation error\n   * (`error_code: \"validation_failed\"`) if the discovery document is unreachable, invalid, or\n   * the issuer does not match.\n   *\n   * This function should only be called on a server. Never expose your `service_role` key in the browser.\n   */\n  private async _updateCustomProvider(\n    identifier: string,\n    params: UpdateCustomProviderParams\n  ): Promise\u003cCustomProviderResponse\u003e {\n    try {\n      return await _request(this.fetch, 'PUT', `${this.url}/admin/custom-providers/${identifier}`, {\n        body: params,\n        headers: this.headers,\n        xform: (provider: any) =\u003e {\n          return { data: provider, error: null }\n        },\n      })\n    } catch (error) {\n      if (isAuthError(error)) {\n        return { data: null, error }\n      }\n      throw error\n    }\n  }\n\n  /**\n   * Deletes a custom provider.\n   *\n   * This function should only be called on a server. Never expose your `service_role` key in the browser.\n   */\n  private async _deleteCustomProvider(\n    identifier: string\n  ): Promise\u003c{ data: null; error: AuthError | null }\u003e {\n    try {\n      await _request(this.fetch, 'DELETE', `${this.url}/admin/custom-providers/${identifier}`, {\n        headers: this.headers,\n        noResolveJson: true,\n      })\n      return { data: null, error: null }\n    } catch (error) {\n      if (isAuthError(error)) {\n        return { data: null, error }\n      }\n      throw error\n    }\n  }\n\n  /**\n   * Lists all passkeys for a user.\n   *\n   * This function should only be called on a server. Never expose your secret key in the browser.\n   */\n  private async _adminListPasskeys(\n    params: AuthPasskeyAdminListParams\n  ): Promise\u003cAuthPasskeyListResponse\u003e {\n    validateUUID(params.userId)\n\n    try {\n      return await _request(\n        this.fetch,\n        'GET',\n        `${this.url}/admin/users/${params.userId}/passkeys`,\n        { headers: this.headers, xform: (data: any) =\u003e ({ data, error: null }) }\n      )\n    } catch (error) {\n      if (isAuthError(error)) {\n        return { data: null, error }\n      }\n      throw error\n    }\n  }\n\n  /**\n   * Deletes a user's passkey.\n   *\n   * This function should only be called on a server. Never expose your secret key in the browser.\n   */\n  private async _adminDeletePasskey(\n    params: AuthPasskeyAdminDeleteParams\n  ): Promise\u003cAuthPasskeyDeleteResponse\u003e {\n    validateUUID(params.userId)\n    validateUUID(params.passkeyId)\n\n    try {\n      await _request(\n        this.fetch,\n        'DELETE',\n        `${this.url}/admin/users/${params.userId}/passkeys/${params.passkeyId}`,\n        { headers: this.headers, noResolveJson: true }\n      )\n      return { data: null, error: null }\n    } catch (error) {\n      if (isAuthError(error)) {\n        return { data: null, error }\n      }\n      throw error\n    }\n  }\n}\n","import { SupportedStorage } from './types'\n\n/**\n * Returns a localStorage-like object that stores the key-value pairs in\n * memory.\n */\nexport function memoryLocalStorageAdapter(store: { [key: string]: string } = {}): SupportedStorage {\n  return {\n    getItem: (key) =\u003e {\n      return store[key] || null\n    },\n\n    setItem: (key, value) =\u003e {\n      store[key] = value\n    },\n\n    removeItem: (key) =\u003e {\n      delete store[key]\n    },\n  }\n}\n","/**\n * Lock primitives retained for backwards-compatible imports. The auth client\n * coordinates refreshes itself (deduping in-instance callers onto a shared\n * in-flight promise) and lets the GoTrue server resolve cross-instance races,\n * so it does not invoke any primitive from this module. The functions still\n * work for direct callers that need a navigator.locks-backed or in-process\n * exclusive lock of their own.\n */\n\nimport { supportsLocalStorage } from './helpers'\n\n/**\n * @deprecated Debug flag for `navigatorLock` / `processLock`. The auth\n * client ignores both, so this has no client-side effect.\n * @experimental\n */\nexport const internals = {\n  /**\n   * @experimental\n   */\n  debug: !!(\n    globalThis \u0026\u0026\n    supportsLocalStorage() \u0026\u0026\n    globalThis.localStorage \u0026\u0026\n    globalThis.localStorage.getItem('supabase.gotrue-js.locks.debug') === 'true'\n  ),\n}\n\n/**\n * An error thrown when a lock cannot be acquired after some amount of time.\n *\n * @deprecated The auth client doesn't acquire locks around auth operations,\n * so this error never originates from `supabase.auth.*` calls. Direct callers\n * of `navigatorLock` / `processLock` still receive it on acquire timeout.\n */\nexport abstract class LockAcquireTimeoutError extends Error {\n  public readonly isAcquireTimeout = true\n\n  constructor(message: string) {\n    super(message)\n  }\n}\n\n/**\n * @deprecated The auth client doesn't call `navigator.locks`, so this error\n * never originates from `supabase.auth.*` calls. Direct callers of\n * `navigatorLock` still receive it on acquire timeout.\n */\nexport class NavigatorLockAcquireTimeoutError extends LockAcquireTimeoutError {}\n/**\n * @deprecated The auth client doesn't run `processLock`, so this error\n * never originates from `supabase.auth.*` calls. Direct callers of\n * `processLock` still receive it on acquire timeout.\n */\nexport class ProcessLockAcquireTimeoutError extends LockAcquireTimeoutError {}\n\n/**\n * Implements a global exclusive lock using the Navigator LockManager API. It\n * is available on all browsers released after 2022-03-15 with Safari being the\n * last one to release support. If the API is not available, this function will\n * throw. Make sure you check availablility before configuring {@link\n * GoTrueClient}.\n *\n * You can turn on debugging by setting the `supabase.gotrue-js.locks.debug`\n * local storage item to `true`.\n *\n * Internals:\n *\n * Since the LockManager API does not preserve stack traces for the async\n * function passed in the `request` method, a trick is used where acquiring the\n * lock releases a previously started promise to run the operation in the `fn`\n * function. The lock waits for that promise to finish (with or without error),\n * while the function will finally wait for the result anyway.\n *\n * @param name Name of the lock to be acquired.\n * @param acquireTimeout If negative, no timeout. If 0 an error is thrown if\n *                       the lock can't be acquired without waiting. If positive, the lock acquire\n *                       will time out after so many milliseconds. An error is\n *                       a timeout if it has `isAcquireTimeout` set to true.\n * @param fn The operation to run once the lock is acquired.\n *\n * @deprecated The auth client coordinates refreshes itself and the server\n * resolves concurrent refresh races, so passing `{ lock: navigatorLock }`\n * to it has no effect. You can safely drop the import from your client setup.\n */\nexport async function navigatorLock\u003cR\u003e(\n  name: string,\n  acquireTimeout: number,\n  fn: () =\u003e Promise\u003cR\u003e\n): Promise\u003cR\u003e {\n  if (internals.debug) {\n    console.log('@supabase/gotrue-js: navigatorLock: acquire lock', name, acquireTimeout)\n  }\n\n  const abortController = new globalThis.AbortController()\n\n  let acquireTimeoutTimer: ReturnType\u003ctypeof setTimeout\u003e | undefined\n\n  if (acquireTimeout \u003e 0) {\n    acquireTimeoutTimer = setTimeout(() =\u003e {\n      abortController.abort()\n      if (internals.debug) {\n        console.log('@supabase/gotrue-js: navigatorLock acquire timed out', name)\n      }\n    }, acquireTimeout)\n  }\n\n  // MDN article: https://developer.mozilla.org/en-US/docs/Web/API/LockManager/request\n\n  // Wrapping navigator.locks.request() with a plain Promise is done as some\n  // libraries like zone.js patch the Promise object to track the execution\n  // context. However, it appears that most browsers use an internal promise\n  // implementation when using the navigator.locks.request() API causing them\n  // to lose context and emit confusing log messages or break certain features.\n  // This wrapping is believed to help zone.js track the execution context\n  // better.\n  await Promise.resolve()\n\n  try {\n    return await globalThis.navigator.locks.request(\n      name,\n      acquireTimeout === 0\n        ? {\n            mode: 'exclusive',\n            ifAvailable: true,\n          }\n        : {\n            mode: 'exclusive',\n            signal: abortController.signal,\n          },\n      async (lock) =\u003e {\n        if (lock) {\n          // Lock acquired — cancel the acquire-timeout timer so it cannot fire\n          // while fn() is running. Without this, a delayed timeout abort would\n          // set signal.aborted = true even though we already hold the lock,\n          // causing a subsequent steal to be misclassified as \"our timeout\n          // fired\" and triggering a spurious steal-back cascade.\n          clearTimeout(acquireTimeoutTimer)\n\n          if (internals.debug) {\n            console.log('@supabase/gotrue-js: navigatorLock: acquired', name, lock.name)\n          }\n\n          try {\n            return await fn()\n          } finally {\n            if (internals.debug) {\n              console.log('@supabase/gotrue-js: navigatorLock: released', name, lock.name)\n            }\n          }\n        } else {\n          if (acquireTimeout === 0) {\n            if (internals.debug) {\n              console.log('@supabase/gotrue-js: navigatorLock: not immediately available', name)\n            }\n\n            throw new NavigatorLockAcquireTimeoutError(\n              `Acquiring an exclusive Navigator LockManager lock \"${name}\" immediately failed`\n            )\n          } else {\n            if (internals.debug) {\n              try {\n                const result = await globalThis.navigator.locks.query()\n\n                console.log(\n                  '@supabase/gotrue-js: Navigator LockManager state',\n                  JSON.stringify(result, null, '  ')\n                )\n              } catch (e) {\n                console.warn(\n                  '@supabase/gotrue-js: Error when querying Navigator LockManager state',\n                  e\n                )\n              }\n            }\n\n            // Browser is not following the Navigator LockManager spec, it\n            // returned a null lock when we didn't use ifAvailable. So we can\n            // pretend the lock is acquired in the name of backward compatibility\n            // and user experience and just run the function.\n            console.warn(\n              '@supabase/gotrue-js: Navigator LockManager returned a null lock when using #request without ifAvailable set to true, it appears this browser is not following the LockManager spec https://developer.mozilla.org/en-US/docs/Web/API/LockManager/request'\n            )\n\n            clearTimeout(acquireTimeoutTimer)\n            return await fn()\n          }\n        }\n      }\n    )\n  } catch (e) {\n    // Always clear the acquire timeout once the request settles, so it cannot\n    // fire later and incorrectly abort/log after a rejection.\n    clearTimeout(acquireTimeoutTimer)\n\n    // DOMException does not extend Error in Node.js, so use structural check\n    if (e !== null \u0026\u0026 typeof e === 'object' \u0026\u0026 'name' in e \u0026\u0026 e.name === 'AbortError') {\n      if (abortController.signal.aborted) {\n        // OUR timeout fired — the lock is genuinely orphaned. Steal it.\n        //\n        // The lock acquisition was aborted because the timeout fired while the\n        // request was still pending. This typically means another lock holder is\n        // not releasing the lock, possibly due to React Strict Mode's\n        // double-mount/unmount behavior or a component unmounting mid-operation,\n        // leaving an orphaned lock.\n        //\n        // Recovery: use { steal: true } to forcefully acquire the lock. Per the\n        // Web Locks API spec, this releases any currently held lock with the same\n        // name and grants the request immediately, preempting any queued requests.\n        // The previous holder's callback continues running to completion but no\n        // longer holds the lock for exclusion purposes.\n        //\n        // See: https://github.com/supabase/supabase/issues/42505\n        if (internals.debug) {\n          console.log(\n            '@supabase/gotrue-js: navigatorLock: acquire timeout, recovering by stealing lock',\n            name\n          )\n        }\n\n        console.warn(\n          `@supabase/gotrue-js: Lock \"${name}\" was not released within ${acquireTimeout}ms. ` +\n            'This may indicate an orphaned lock from a component unmount (e.g., React Strict Mode). ' +\n            'Forcefully acquiring the lock to recover.'\n        )\n\n        return await Promise.resolve().then(() =\u003e\n          globalThis.navigator.locks.request(\n            name,\n            {\n              mode: 'exclusive',\n              steal: true,\n            },\n            async (lock) =\u003e {\n              if (lock) {\n                if (internals.debug) {\n                  console.log(\n                    '@supabase/gotrue-js: navigatorLock: recovered (stolen)',\n                    name,\n                    lock.name\n                  )\n                }\n\n                try {\n                  return await fn()\n                } finally {\n                  if (internals.debug) {\n                    console.log(\n                      '@supabase/gotrue-js: navigatorLock: released (stolen)',\n                      name,\n                      lock.name\n                    )\n                  }\n                }\n              } else {\n                // This should not happen with steal: true, but handle gracefully.\n                console.warn(\n                  '@supabase/gotrue-js: Navigator LockManager returned null lock even with steal: true'\n                )\n                return await fn()\n              }\n            }\n          )\n        )\n      } else {\n        // We HELD the lock but another request stole it from us.\n        // Per the Web Locks spec, our fn() callback is still running as an\n        // orphaned background task — do NOT steal back. Stealing back would\n        // cause a cascade (A steals B, B steals A, ...) and run fn() a second\n        // time concurrently, corrupting auth state.\n        // Convert to a typed error so callers (e.g. _autoRefreshTokenTick)\n        // can handle/filter it without it leaking to Sentry as a raw AbortError.\n        if (internals.debug) {\n          console.log(\n            '@supabase/gotrue-js: navigatorLock: lock was stolen by another request',\n            name\n          )\n        }\n\n        throw new NavigatorLockAcquireTimeoutError(\n          `Lock \"${name}\" was released because another request stole it`\n        )\n      }\n    }\n\n    throw e\n  }\n}\n\nconst PROCESS_LOCKS: { [name: string]: Promise\u003cany\u003e } = {}\n\n/**\n * Implements a global exclusive lock that works only in the current process.\n * Useful for environments like React Native or other non-browser\n * single-process (i.e. no concept of \"tabs\") environments.\n *\n * Use {@link navigatorLock} in browser environments.\n *\n * @param name Name of the lock to be acquired.\n * @param acquireTimeout If negative, no timeout. If 0 an error is thrown if\n *                       the lock can't be acquired without waiting. If positive, the lock acquire\n *                       will time out after so many milliseconds. An error is\n *                       a timeout if it has `isAcquireTimeout` set to true.\n * @param fn The operation to run once the lock is acquired.\n *\n * @deprecated The auth client coordinates refreshes itself and the server\n * resolves concurrent refresh races, so passing `{ lock: processLock }`\n * to it has no effect. You can safely drop the import from your client setup.\n *\n * @example\n * ```ts\n * await processLock('migrate', 5000, async () =\u003e {\n *   await runMigration()\n * })\n * ```\n */\nexport async function processLock\u003cR\u003e(\n  name: string,\n  acquireTimeout: number,\n  fn: () =\u003e Promise\u003cR\u003e\n): Promise\u003cR\u003e {\n  const previousOperation = PROCESS_LOCKS[name] ?? Promise.resolve()\n\n  // Wrap previousOperation to handle errors without using .catch()\n  // This avoids Firefox content script security errors\n  const previousOperationHandled = (async () =\u003e {\n    try {\n      await previousOperation\n      return null\n    } catch (e) {\n      // ignore error of previous operation that we're waiting to finish\n      return null\n    }\n  })()\n\n  const currentOperation = (async () =\u003e {\n    let timeoutId: ReturnType\u003ctypeof setTimeout\u003e | null = null\n\n    try {\n      // Wait for either previous operation or timeout\n      const timeoutPromise =\n        acquireTimeout \u003e= 0\n          ? new Promise((_, reject) =\u003e {\n              timeoutId = setTimeout(() =\u003e {\n                console.warn(\n                  `@supabase/gotrue-js: Lock \"${name}\" acquisition timed out after ${acquireTimeout}ms. ` +\n                    'This may be caused by another operation holding the lock. ' +\n                    'Consider increasing lockAcquireTimeout or checking for stuck operations.'\n                )\n\n                reject(\n                  new ProcessLockAcquireTimeoutError(\n                    `Acquiring process lock with name \"${name}\" timed out`\n                  )\n                )\n              }, acquireTimeout)\n            })\n          : null\n\n      await Promise.race([previousOperationHandled, timeoutPromise].filter((x) =\u003e x))\n\n      // If we reach here, previousOperationHandled won the race\n      // Clear the timeout to prevent false warnings\n      if (timeoutId !== null) {\n        clearTimeout(timeoutId)\n      }\n    } catch (e) {\n      // Clear the timeout on error path as well\n      if (timeoutId !== null) {\n        clearTimeout(timeoutId)\n      }\n\n      // Re-throw timeout errors, ignore others\n      if (e instanceof LockAcquireTimeoutError) {\n        throw e\n      }\n      // Fall through to run fn() - previous operation finished with error\n    }\n\n    // Previous operations finished and we didn't get a race on the acquire\n    // timeout, so the current operation can finally start\n    return await fn()\n  })()\n\n  PROCESS_LOCKS[name] = (async () =\u003e {\n    try {\n      return await currentOperation\n    } catch (e) {\n      if (e instanceof LockAcquireTimeoutError) {\n        // if the current operation timed out, it doesn't mean that the previous\n        // operation finished, so we need continue waiting for it to finish\n        try {\n          await previousOperation\n        } catch (prevError) {\n          // Ignore previous operation errors\n        }\n        return null\n      }\n\n      throw e\n    }\n  })()\n\n  // finally wait for the current operation to finish successfully, with an\n  // error or with an acquire timeout error\n  return await currentOperation\n}\n","/**\n * https://mathiasbynens.be/notes/globalthis\n */\nexport function polyfillGlobalThis() {\n  if (typeof globalThis === 'object') return\n  try {\n    Object.defineProperty(Object.prototype, '__magic__', {\n      get: function () {\n        return this\n      },\n      configurable: true,\n    })\n    // @ts-expect-error 'Allow access to magic'\n    __magic__.globalThis = __magic__\n    // @ts-expect-error 'Allow access to magic'\n    delete Object.prototype.__magic__\n  } catch (e) {\n    if (typeof self !== 'undefined') {\n      // @ts-expect-error 'Allow access to globals'\n      self.globalThis = self\n    }\n  }\n}\n","// types and functions copied over from viem so this library doesn't depend on it\n\nexport type Hex = `0x${string}`\n\nexport type Address = Hex\n\nexport type EIP1193EventMap = {\n  accountsChanged(accounts: Address[]): void\n  chainChanged(chainId: string): void\n  connect(connectInfo: { chainId: string }): void\n  disconnect(error: { code: number; message: string }): void\n  message(message: { type: string; data: unknown }): void\n}\n\nexport type EIP1193Events = {\n  on\u003cevent extends keyof EIP1193EventMap\u003e(event: event, listener: EIP1193EventMap[event]): void\n  removeListener\u003cevent extends keyof EIP1193EventMap\u003e(\n    event: event,\n    listener: EIP1193EventMap[event]\n  ): void\n}\n\nexport type EIP1193RequestFn = (args: { method: string; params?: unknown }) =\u003e Promise\u003cunknown\u003e\n\nexport type EIP1193Provider = EIP1193Events \u0026 {\n  address: string\n  request: EIP1193RequestFn\n}\n\nexport type EthereumWallet = EIP1193Provider\n\n/**\n * EIP-4361 message fields\n */\nexport type SiweMessage = {\n  /**\n   * The Ethereum address performing the signing.\n   */\n  address: Address\n  /**\n   * The [EIP-155](https://eips.ethereum.org/EIPS/eip-155) Chain ID to which the session is bound,\n   */\n  chainId: number\n  /**\n   * [RFC 3986](https://www.rfc-editor.org/rfc/rfc3986) authority that is requesting the signing.\n   */\n  domain: string\n  /**\n   * Time when the signed authentication message is no longer valid.\n   */\n  expirationTime?: Date | undefined\n  /**\n   * Time when the message was generated, typically the current time.\n   */\n  issuedAt?: Date | undefined\n  /**\n   * A random string typically chosen by the relying party and used to prevent replay attacks.\n   */\n  nonce?: string\n  /**\n   * Time when the signed authentication message will become valid.\n   */\n  notBefore?: Date | undefined\n  /**\n   * A system-specific identifier that may be used to uniquely refer to the sign-in request.\n   */\n  requestId?: string | undefined\n  /**\n   * A list of information or references to information the user wishes to have resolved as part of authentication by the relying party.\n   */\n  resources?: string[] | undefined\n  /**\n   * [RFC 3986](https://www.rfc-editor.org/rfc/rfc3986#section-3.1) URI scheme of the origin of the request.\n   */\n  scheme?: string | undefined\n  /**\n   * A human-readable ASCII assertion that the user will sign.\n   */\n  statement?: string | undefined\n  /**\n   * [RFC 3986](https://www.rfc-editor.org/rfc/rfc3986) URI referring to the resource that is the subject of the signing (as in the subject of a claim).\n   */\n  uri: string\n  /**\n   * The current version of the SIWE Message.\n   */\n  version: '1'\n}\n\nexport type EthereumSignInInput = SiweMessage\n\nexport function getAddress(address: string): Address {\n  if (!/^0x[a-fA-F0-9]{40}$/.test(address)) {\n    throw new Error(`@supabase/auth-js: Address \"${address}\" is invalid.`)\n  }\n  return address.toLowerCase() as Address\n}\n\nexport function fromHex(hex: Hex): number {\n  return parseInt(hex, 16)\n}\n\nexport function toHex(value: string): Hex {\n  const bytes = new TextEncoder().encode(value)\n  const hex = Array.from(bytes, (byte) =\u003e byte.toString(16).padStart(2, '0')).join('')\n  return ('0x' + hex) as Hex\n}\n\n/**\n * Creates EIP-4361 formatted message.\n */\nexport function createSiweMessage(parameters: SiweMessage): string {\n  const {\n    chainId,\n    domain,\n    expirationTime,\n    issuedAt = new Date(),\n    nonce,\n    notBefore,\n    requestId,\n    resources,\n    scheme,\n    uri,\n    version,\n  } = parameters\n\n  // Validate fields\n  {\n    if (!Number.isInteger(chainId))\n      throw new Error(\n        `@supabase/auth-js: Invalid SIWE message field \"chainId\". Chain ID must be a EIP-155 chain ID. Provided value: ${chainId}`\n      )\n\n    if (!domain)\n      throw new Error(\n        `@supabase/auth-js: Invalid SIWE message field \"domain\". Domain must be provided.`\n      )\n\n    if (nonce \u0026\u0026 nonce.length \u003c 8)\n      throw new Error(\n        `@supabase/auth-js: Invalid SIWE message field \"nonce\". Nonce must be at least 8 characters. Provided value: ${nonce}`\n      )\n\n    if (!uri)\n      throw new Error(`@supabase/auth-js: Invalid SIWE message field \"uri\". URI must be provided.`)\n\n    if (version !== '1')\n      throw new Error(\n        `@supabase/auth-js: Invalid SIWE message field \"version\". Version must be '1'. Provided value: ${version}`\n      )\n\n    if (parameters.statement?.includes('\\n'))\n      throw new Error(\n        `@supabase/auth-js: Invalid SIWE message field \"statement\". Statement must not include '\\\\n'. Provided value: ${parameters.statement}`\n      )\n  }\n\n  // Construct message\n  const address = getAddress(parameters.address)\n  const origin = scheme ? `${scheme}://${domain}` : domain\n  const statement = parameters.statement ? `${parameters.statement}\\n` : ''\n  const prefix = `${origin} wants you to sign in with your Ethereum account:\\n${address}\\n\\n${statement}`\n\n  let suffix = `URI: ${uri}\\nVersion: ${version}\\nChain ID: ${chainId}${\n    nonce ? `\\nNonce: ${nonce}` : ''\n  }\\nIssued At: ${issuedAt.toISOString()}`\n\n  if (expirationTime) suffix += `\\nExpiration Time: ${expirationTime.toISOString()}`\n  if (notBefore) suffix += `\\nNot Before: ${notBefore.toISOString()}`\n  if (requestId) suffix += `\\nRequest ID: ${requestId}`\n  if (resources) {\n    let content = '\\nResources:'\n    for (const resource of resources) {\n      if (!resource || typeof resource !== 'string')\n        throw new Error(\n          `@supabase/auth-js: Invalid SIWE message field \"resources\". Every resource must be a valid string. Provided value: ${resource}`\n        )\n      content += `\\n- ${resource}`\n    }\n    suffix += content\n  }\n\n  return `${prefix}\\n${suffix}`\n}\n","/* eslint-disable @typescript-eslint/ban-ts-comment */\n\nimport { StrictOmit } from './types'\nimport { isValidDomain } from './webauthn'\nimport {\n  PublicKeyCredentialCreationOptionsFuture,\n  PublicKeyCredentialRequestOptionsFuture,\n} from './webauthn.dom'\n\n/**\n * A custom Error used to return a more nuanced error detailing _why_ one of the eight documented\n * errors in the spec was raised after calling `navigator.credentials.create()` or\n * `navigator.credentials.get()`:\n *\n * - `AbortError`\n * - `ConstraintError`\n * - `InvalidStateError`\n * - `NotAllowedError`\n * - `NotSupportedError`\n * - `SecurityError`\n * - `TypeError`\n * - `UnknownError`\n *\n * Error messages were determined through investigation of the spec to determine under which\n * scenarios a given error would be raised.\n */\nexport class WebAuthnError extends Error {\n  code: WebAuthnErrorCode\n\n  protected __isWebAuthnError = true\n\n  constructor({\n    message,\n    code,\n    cause,\n    name,\n  }: {\n    message: string\n    code: WebAuthnErrorCode\n    cause?: Error | unknown\n    name?: string\n  }) {\n    // @ts-ignore: help Rollup understand that `cause` is okay to set\n    super(message, { cause })\n    this.name = name ?? (cause instanceof Error ? cause.name : undefined) ?? 'Unknown Error'\n    this.code = code\n  }\n\n  toJSON(): {\n    name: string\n    message: string\n    code: WebAuthnErrorCode\n  } {\n    return {\n      name: this.name,\n      message: this.message,\n      code: this.code,\n    }\n  }\n}\n\n/**\n * Error class for unknown WebAuthn errors.\n * Wraps unexpected errors that don't match known WebAuthn error conditions.\n */\nexport class WebAuthnUnknownError extends WebAuthnError {\n  originalError: unknown\n\n  constructor(message: string, originalError: unknown) {\n    super({\n      code: 'ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY',\n      cause: originalError,\n      message,\n    })\n    this.name = 'WebAuthnUnknownError'\n    this.originalError = originalError\n  }\n}\n\n/**\n * Type guard to check if an error is a WebAuthnError.\n * @param {unknown} error - The error to check\n * @returns {boolean} True if the error is a WebAuthnError\n */\nexport function isWebAuthnError(error: unknown): error is WebAuthnError {\n  return typeof error === 'object' \u0026\u0026 error !== null \u0026\u0026 '__isWebAuthnError' in error\n}\n\n/**\n * Error codes for WebAuthn operations.\n * These codes provide specific information about why a WebAuthn ceremony failed.\n * @see {@link https://w3c.github.io/webauthn/#sctn-defined-errors W3C WebAuthn Spec - Defined Errors}\n */\nexport type WebAuthnErrorCode =\n  | 'ERROR_CEREMONY_ABORTED'\n  | 'ERROR_INVALID_DOMAIN'\n  | 'ERROR_INVALID_RP_ID'\n  | 'ERROR_INVALID_USER_ID_LENGTH'\n  | 'ERROR_MALFORMED_PUBKEYCREDPARAMS'\n  | 'ERROR_AUTHENTICATOR_GENERAL_ERROR'\n  | 'ERROR_AUTHENTICATOR_MISSING_DISCOVERABLE_CREDENTIAL_SUPPORT'\n  | 'ERROR_AUTHENTICATOR_MISSING_USER_VERIFICATION_SUPPORT'\n  | 'ERROR_AUTHENTICATOR_PREVIOUSLY_REGISTERED'\n  | 'ERROR_AUTHENTICATOR_NO_SUPPORTED_PUBKEYCREDPARAMS_ALG'\n  | 'ERROR_AUTO_REGISTER_USER_VERIFICATION_FAILURE'\n  | 'ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY'\n\n/**\n * Attempt to intuit _why_ an error was raised after calling `navigator.credentials.create()`.\n * Maps browser errors to specific WebAuthn error codes for better debugging.\n * @param {Object} params - Error identification parameters\n * @param {Error} params.error - The error thrown by the browser\n * @param {CredentialCreationOptions} params.options - The options passed to credentials.create()\n * @returns {WebAuthnError} A WebAuthnError with a specific error code\n * @see {@link https://w3c.github.io/webauthn/#sctn-createCredential W3C WebAuthn Spec - Create Credential}\n */\nexport function identifyRegistrationError({\n  error,\n  options,\n}: {\n  error: Error\n  options: StrictOmit\u003cCredentialCreationOptions, 'publicKey'\u003e \u0026 {\n    publicKey: PublicKeyCredentialCreationOptionsFuture\n  }\n}): WebAuthnError {\n  const { publicKey } = options\n\n  if (!publicKey) {\n    throw Error('options was missing required publicKey property')\n  }\n\n  if (error.name === 'AbortError') {\n    if (options.signal instanceof AbortSignal) {\n      // https://www.w3.org/TR/webauthn-2/#sctn-createCredential (Step 16)\n      return new WebAuthnError({\n        message: 'Registration ceremony was sent an abort signal',\n        code: 'ERROR_CEREMONY_ABORTED',\n        cause: error,\n      })\n    }\n  } else if (error.name === 'ConstraintError') {\n    if (publicKey.authenticatorSelection?.requireResidentKey === true) {\n      // https://www.w3.org/TR/webauthn-2/#sctn-op-make-cred (Step 4)\n      return new WebAuthnError({\n        message:\n          'Discoverable credentials were required but no available authenticator supported it',\n        code: 'ERROR_AUTHENTICATOR_MISSING_DISCOVERABLE_CREDENTIAL_SUPPORT',\n        cause: error,\n      })\n    } else if (\n      // @ts-ignore: `mediation` doesn't yet exist on CredentialCreationOptions but it's possible as of Sept 2024\n      options.mediation === 'conditional' \u0026\u0026\n      publicKey.authenticatorSelection?.userVerification === 'required'\n    ) {\n      // https://w3c.github.io/webauthn/#sctn-createCredential (Step 22.4)\n      return new WebAuthnError({\n        message:\n          'User verification was required during automatic registration but it could not be performed',\n        code: 'ERROR_AUTO_REGISTER_USER_VERIFICATION_FAILURE',\n        cause: error,\n      })\n    } else if (publicKey.authenticatorSelection?.userVerification === 'required') {\n      // https://www.w3.org/TR/webauthn-2/#sctn-op-make-cred (Step 5)\n      return new WebAuthnError({\n        message: 'User verification was required but no available authenticator supported it',\n        code: 'ERROR_AUTHENTICATOR_MISSING_USER_VERIFICATION_SUPPORT',\n        cause: error,\n      })\n    }\n  } else if (error.name === 'InvalidStateError') {\n    // https://www.w3.org/TR/webauthn-2/#sctn-createCredential (Step 20)\n    // https://www.w3.org/TR/webauthn-2/#sctn-op-make-cred (Step 3)\n    return new WebAuthnError({\n      message: 'The authenticator was previously registered',\n      code: 'ERROR_AUTHENTICATOR_PREVIOUSLY_REGISTERED',\n      cause: error,\n    })\n  } else if (error.name === 'NotAllowedError') {\n    /**\n     * Pass the error directly through. Platforms are overloading this error beyond what the spec\n     * defines and we don't want to overwrite potentially useful error messages.\n     */\n    return new WebAuthnError({\n      message: error.message,\n      code: 'ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY',\n      cause: error,\n    })\n  } else if (error.name === 'NotSupportedError') {\n    const validPubKeyCredParams = publicKey.pubKeyCredParams.filter(\n      (param) =\u003e param.type === 'public-key'\n    )\n\n    if (validPubKeyCredParams.length === 0) {\n      // https://www.w3.org/TR/webauthn-2/#sctn-createCredential (Step 10)\n      return new WebAuthnError({\n        message: 'No entry in pubKeyCredParams was of type \"public-key\"',\n        code: 'ERROR_MALFORMED_PUBKEYCREDPARAMS',\n        cause: error,\n      })\n    }\n\n    // https://www.w3.org/TR/webauthn-2/#sctn-op-make-cred (Step 2)\n    return new WebAuthnError({\n      message:\n        'No available authenticator supported any of the specified pubKeyCredParams algorithms',\n      code: 'ERROR_AUTHENTICATOR_NO_SUPPORTED_PUBKEYCREDPARAMS_ALG',\n      cause: error,\n    })\n  } else if (error.name === 'SecurityError') {\n    const effectiveDomain = window.location.hostname\n    if (!isValidDomain(effectiveDomain)) {\n      // https://www.w3.org/TR/webauthn-2/#sctn-createCredential (Step 7)\n      return new WebAuthnError({\n        message: `${window.location.hostname} is an invalid domain`,\n        code: 'ERROR_INVALID_DOMAIN',\n        cause: error,\n      })\n    } else if (publicKey.rp.id !== effectiveDomain) {\n      // https://www.w3.org/TR/webauthn-2/#sctn-createCredential (Step 8)\n      return new WebAuthnError({\n        message: `The RP ID \"${publicKey.rp.id}\" is invalid for this domain`,\n        code: 'ERROR_INVALID_RP_ID',\n        cause: error,\n      })\n    }\n  } else if (error.name === 'TypeError') {\n    if (publicKey.user.id.byteLength \u003c 1 || publicKey.user.id.byteLength \u003e 64) {\n      // https://www.w3.org/TR/webauthn-2/#sctn-createCredential (Step 5)\n      return new WebAuthnError({\n        message: 'User ID was not between 1 and 64 characters',\n        code: 'ERROR_INVALID_USER_ID_LENGTH',\n        cause: error,\n      })\n    }\n  } else if (error.name === 'UnknownError') {\n    // https://www.w3.org/TR/webauthn-2/#sctn-op-make-cred (Step 1)\n    // https://www.w3.org/TR/webauthn-2/#sctn-op-make-cred (Step 8)\n    return new WebAuthnError({\n      message:\n        'The authenticator was unable to process the specified options, or could not create a new credential',\n      code: 'ERROR_AUTHENTICATOR_GENERAL_ERROR',\n      cause: error,\n    })\n  }\n\n  return new WebAuthnError({\n    message: 'a Non-Webauthn related error has occurred',\n    code: 'ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY',\n    cause: error,\n  })\n}\n\n/**\n * Attempt to intuit _why_ an error was raised after calling `navigator.credentials.get()`.\n * Maps browser errors to specific WebAuthn error codes for better debugging.\n * @param {Object} params - Error identification parameters\n * @param {Error} params.error - The error thrown by the browser\n * @param {CredentialRequestOptions} params.options - The options passed to credentials.get()\n * @returns {WebAuthnError} A WebAuthnError with a specific error code\n * @see {@link https://w3c.github.io/webauthn/#sctn-getAssertion W3C WebAuthn Spec - Get Assertion}\n */\nexport function identifyAuthenticationError({\n  error,\n  options,\n}: {\n  error: Error\n  options: StrictOmit\u003cCredentialRequestOptions, 'publicKey'\u003e \u0026 {\n    publicKey: PublicKeyCredentialRequestOptionsFuture\n  }\n}): WebAuthnError {\n  const { publicKey } = options\n\n  if (!publicKey) {\n    throw Error('options was missing required publicKey property')\n  }\n\n  if (error.name === 'AbortError') {\n    if (options.signal instanceof AbortSignal) {\n      // https://www.w3.org/TR/webauthn-2/#sctn-createCredential (Step 16)\n      return new WebAuthnError({\n        message: 'Authentication ceremony was sent an abort signal',\n        code: 'ERROR_CEREMONY_ABORTED',\n        cause: error,\n      })\n    }\n  } else if (error.name === 'NotAllowedError') {\n    /**\n     * Pass the error directly through. Platforms are overloading this error beyond what the spec\n     * defines and we don't want to overwrite potentially useful error messages.\n     */\n    return new WebAuthnError({\n      message: error.message,\n      code: 'ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY',\n      cause: error,\n    })\n  } else if (error.name === 'SecurityError') {\n    const effectiveDomain = window.location.hostname\n    if (!isValidDomain(effectiveDomain)) {\n      // https://www.w3.org/TR/webauthn-2/#sctn-discover-from-external-source (Step 5)\n      return new WebAuthnError({\n        message: `${window.location.hostname} is an invalid domain`,\n        code: 'ERROR_INVALID_DOMAIN',\n        cause: error,\n      })\n    } else if (publicKey.rpId !== effectiveDomain) {\n      // https://www.w3.org/TR/webauthn-2/#sctn-discover-from-external-source (Step 6)\n      return new WebAuthnError({\n        message: `The RP ID \"${publicKey.rpId}\" is invalid for this domain`,\n        code: 'ERROR_INVALID_RP_ID',\n        cause: error,\n      })\n    }\n  } else if (error.name === 'UnknownError') {\n    // https://www.w3.org/TR/webauthn-2/#sctn-op-get-assertion (Step 1)\n    // https://www.w3.org/TR/webauthn-2/#sctn-op-get-assertion (Step 12)\n    return new WebAuthnError({\n      message:\n        'The authenticator was unable to process the specified options, or could not create a new assertion signature',\n      code: 'ERROR_AUTHENTICATOR_GENERAL_ERROR',\n      cause: error,\n    })\n  }\n\n  return new WebAuthnError({\n    message: 'a Non-Webauthn related error has occurred',\n    code: 'ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY',\n    cause: error,\n  })\n}\n","import GoTrueClient from '../GoTrueClient'\nimport { base64UrlToUint8Array, bytesToBase64URL } from './base64url'\nimport { AuthError, AuthUnknownError, isAuthError } from './errors'\nimport {\n  AuthMFAEnrollWebauthnResponse,\n  AuthMFAVerifyResponse,\n  AuthMFAVerifyResponseData,\n  MFAChallengeWebauthnParams,\n  MFAEnrollWebauthnParams,\n  MFAVerifyWebauthnParamFields,\n  MFAVerifyWebauthnParams,\n  RequestResult,\n  StrictOmit,\n} from './types'\nimport { isBrowser } from './helpers'\nimport type {\n  AuthenticationCredential,\n  AuthenticationResponseJSON,\n  AuthenticatorAttachment,\n  PublicKeyCredentialCreationOptionsFuture,\n  PublicKeyCredentialCreationOptionsJSON,\n  PublicKeyCredentialFuture,\n  PublicKeyCredentialRequestOptionsFuture,\n  PublicKeyCredentialRequestOptionsJSON,\n  RegistrationCredential,\n  RegistrationResponseJSON,\n} from './webauthn.dom'\n\nimport {\n  identifyAuthenticationError,\n  identifyRegistrationError,\n  isWebAuthnError,\n  WebAuthnError,\n  WebAuthnUnknownError,\n} from './webauthn.errors'\n\nexport { WebAuthnError, isWebAuthnError, identifyRegistrationError, identifyAuthenticationError }\n// Re-export the JSON types for use in other files\nexport type { RegistrationResponseJSON, AuthenticationResponseJSON }\n\n/**\n * WebAuthn abort service to manage ceremony cancellation.\n * Ensures only one WebAuthn ceremony is active at a time to prevent \"operation already in progress\" errors.\n *\n * @experimental This class is experimental and may change in future releases\n * @see {@link https://w3c.github.io/webauthn/#sctn-automation-webdriver-capability W3C WebAuthn Spec - Aborting Ceremonies}\n */\nexport class WebAuthnAbortService {\n  private controller: AbortController | undefined\n\n  /**\n   * Create an abort signal for a new WebAuthn operation.\n   * Automatically cancels any existing operation.\n   *\n   * @returns {AbortSignal} Signal to pass to navigator.credentials.create() or .get()\n   * @see {@link https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal MDN - AbortSignal}\n   */\n  createNewAbortSignal(): AbortSignal {\n    // Abort any existing calls to navigator.credentials.create() or navigator.credentials.get()\n    if (this.controller) {\n      const abortError = new Error('Cancelling existing WebAuthn API call for new one')\n      abortError.name = 'AbortError'\n      this.controller.abort(abortError)\n    }\n\n    const newController = new AbortController()\n    this.controller = newController\n    return newController.signal\n  }\n\n  /**\n   * Manually cancel the current WebAuthn operation.\n   * Useful for cleaning up when user cancels or navigates away.\n   *\n   * @see {@link https://developer.mozilla.org/en-US/docs/Web/API/AbortController/abort MDN - AbortController.abort}\n   */\n  cancelCeremony(): void {\n    if (this.controller) {\n      const abortError = new Error('Manually cancelling existing WebAuthn API call')\n      abortError.name = 'AbortError'\n      this.controller.abort(abortError)\n      this.controller = undefined\n    }\n  }\n}\n\n/**\n * Singleton instance to ensure only one WebAuthn ceremony is active at a time.\n * This prevents \"operation already in progress\" errors when retrying WebAuthn operations.\n *\n * @experimental This instance is experimental and may change in future releases\n */\nexport const webAuthnAbortService = new WebAuthnAbortService()\n\n/**\n * Server response format for WebAuthn credential creation options.\n * Uses W3C standard JSON format with base64url-encoded binary fields.\n */\nexport type ServerCredentialCreationOptions = PublicKeyCredentialCreationOptionsJSON\n\n/**\n * Server response format for WebAuthn credential request options.\n * Uses W3C standard JSON format with base64url-encoded binary fields.\n */\nexport type ServerCredentialRequestOptions = PublicKeyCredentialRequestOptionsJSON\n\n/**\n * Convert base64url encoded strings in WebAuthn credential creation options to ArrayBuffers\n * as required by the WebAuthn browser API.\n * Supports both native WebAuthn Level 3 parseCreationOptionsFromJSON and manual fallback.\n *\n * @param {ServerCredentialCreationOptions} options - JSON options from server with base64url encoded fields\n * @returns {PublicKeyCredentialCreationOptionsFuture} Options ready for navigator.credentials.create()\n * @see {@link https://w3c.github.io/webauthn/#sctn-parseCreationOptionsFromJSON W3C WebAuthn Spec - parseCreationOptionsFromJSON}\n */\nexport function deserializeCredentialCreationOptions(\n  options: ServerCredentialCreationOptions\n): PublicKeyCredentialCreationOptionsFuture {\n  if (!options) {\n    throw new Error('Credential creation options are required')\n  }\n\n  // Check if the native parseCreationOptionsFromJSON method is available\n  if (\n    typeof PublicKeyCredential !== 'undefined' \u0026\u0026\n    'parseCreationOptionsFromJSON' in PublicKeyCredential \u0026\u0026\n    typeof (PublicKeyCredential as unknown as PublicKeyCredentialFuture)\n      .parseCreationOptionsFromJSON === 'function'\n  ) {\n    // Use the native WebAuthn Level 3 method\n    return (\n      PublicKeyCredential as unknown as PublicKeyCredentialFuture\n    ).parseCreationOptionsFromJSON(\n      /** we assert the options here as typescript still doesn't know about future webauthn types */\n      options as any\n    ) as PublicKeyCredentialCreationOptionsFuture\n  }\n\n  // Fallback to manual parsing for browsers that don't support the native method\n  // Destructure to separate fields that need transformation\n  const { challenge: challengeStr, user: userOpts, excludeCredentials, ...restOptions } = options\n\n  // Convert challenge from base64url to ArrayBuffer\n  const challenge = base64UrlToUint8Array(challengeStr).buffer as ArrayBuffer\n\n  // Convert user.id from base64url to ArrayBuffer\n  const user: PublicKeyCredentialUserEntity = {\n    ...userOpts,\n    id: base64UrlToUint8Array(userOpts.id).buffer as ArrayBuffer,\n  }\n\n  // Build the result object\n  const result: PublicKeyCredentialCreationOptionsFuture = {\n    ...restOptions,\n    challenge,\n    user,\n  }\n\n  // Only add excludeCredentials if it exists\n  if (excludeCredentials \u0026\u0026 excludeCredentials.length \u003e 0) {\n    result.excludeCredentials = new Array(excludeCredentials.length)\n\n    for (let i = 0; i \u003c excludeCredentials.length; i++) {\n      const cred = excludeCredentials[i]\n      result.excludeCredentials[i] = {\n        ...cred,\n        id: base64UrlToUint8Array(cred.id).buffer,\n        type: cred.type || 'public-key',\n        // Cast transports to handle future transport types like \"cable\"\n        transports: cred.transports,\n      }\n    }\n  }\n\n  return result\n}\n\n/**\n * Convert base64url encoded strings in WebAuthn credential request options to ArrayBuffers\n * as required by the WebAuthn browser API.\n * Supports both native WebAuthn Level 3 parseRequestOptionsFromJSON and manual fallback.\n *\n * @param {ServerCredentialRequestOptions} options - JSON options from server with base64url encoded fields\n * @returns {PublicKeyCredentialRequestOptionsFuture} Options ready for navigator.credentials.get()\n * @see {@link https://w3c.github.io/webauthn/#sctn-parseRequestOptionsFromJSON W3C WebAuthn Spec - parseRequestOptionsFromJSON}\n */\nexport function deserializeCredentialRequestOptions(\n  options: ServerCredentialRequestOptions\n): PublicKeyCredentialRequestOptionsFuture {\n  if (!options) {\n    throw new Error('Credential request options are required')\n  }\n\n  // Check if the native parseRequestOptionsFromJSON method is available\n  if (\n    typeof PublicKeyCredential !== 'undefined' \u0026\u0026\n    'parseRequestOptionsFromJSON' in PublicKeyCredential \u0026\u0026\n    typeof (PublicKeyCredential as unknown as PublicKeyCredentialFuture)\n      .parseRequestOptionsFromJSON === 'function'\n  ) {\n    // Use the native WebAuthn Level 3 method\n    return (\n      PublicKeyCredential as unknown as PublicKeyCredentialFuture\n    ).parseRequestOptionsFromJSON(options) as PublicKeyCredentialRequestOptionsFuture\n  }\n\n  // Fallback to manual parsing for browsers that don't support the native method\n  // Destructure to separate fields that need transformation\n  const { challenge: challengeStr, allowCredentials, ...restOptions } = options\n\n  // Convert challenge from base64url to ArrayBuffer\n  const challenge = base64UrlToUint8Array(challengeStr).buffer as ArrayBuffer\n\n  // Build the result object\n  const result: PublicKeyCredentialRequestOptionsFuture = {\n    ...restOptions,\n    challenge,\n  }\n\n  // Only add allowCredentials if it exists\n  if (allowCredentials \u0026\u0026 allowCredentials.length \u003e 0) {\n    result.allowCredentials = new Array(allowCredentials.length)\n\n    for (let i = 0; i \u003c allowCredentials.length; i++) {\n      const cred = allowCredentials[i]\n      result.allowCredentials[i] = {\n        ...cred,\n        id: base64UrlToUint8Array(cred.id).buffer,\n        type: cred.type || 'public-key',\n        // Cast transports to handle future transport types like \"cable\"\n        transports: cred.transports,\n      }\n    }\n  }\n\n  return result\n}\n\n/**\n * Server format for credential response with base64url-encoded binary fields\n * Can be either a registration or authentication response\n */\nexport type ServerCredentialResponse = RegistrationResponseJSON | AuthenticationResponseJSON\n\n/**\n * Convert a registration/enrollment credential response to server format.\n * Serializes binary fields to base64url for JSON transmission.\n * Supports both native WebAuthn Level 3 toJSON and manual fallback.\n *\n * @param {RegistrationCredential} credential - Credential from navigator.credentials.create()\n * @returns {RegistrationResponseJSON} JSON-serializable credential for server\n * @see {@link https://w3c.github.io/webauthn/#dom-publickeycredential-tojson W3C WebAuthn Spec - toJSON}\n */\nexport function serializeCredentialCreationResponse(\n  credential: RegistrationCredential\n): RegistrationResponseJSON {\n  // Check if the credential instance has the toJSON method\n  if ('toJSON' in credential \u0026\u0026 typeof credential.toJSON === 'function') {\n    // Use the native WebAuthn Level 3 method\n    return (credential as RegistrationCredential).toJSON()\n  }\n  const credentialWithAttachment = credential as PublicKeyCredential \u0026 {\n    response: AuthenticatorAttestationResponse\n    authenticatorAttachment?: string | null\n  }\n\n  return {\n    id: credential.id,\n    rawId: credential.id,\n    response: {\n      attestationObject: bytesToBase64URL(new Uint8Array(credential.response.attestationObject)),\n      clientDataJSON: bytesToBase64URL(new Uint8Array(credential.response.clientDataJSON)),\n    },\n    type: 'public-key',\n    clientExtensionResults: credential.getClientExtensionResults(),\n    // Convert null to undefined and cast to AuthenticatorAttachment type\n    authenticatorAttachment: (credentialWithAttachment.authenticatorAttachment ?? undefined) as\n      | AuthenticatorAttachment\n      | undefined,\n  }\n}\n\n/**\n * Convert an authentication/verification credential response to server format.\n * Serializes binary fields to base64url for JSON transmission.\n * Supports both native WebAuthn Level 3 toJSON and manual fallback.\n *\n * @param {AuthenticationCredential} credential - Credential from navigator.credentials.get()\n * @returns {AuthenticationResponseJSON} JSON-serializable credential for server\n * @see {@link https://w3c.github.io/webauthn/#dom-publickeycredential-tojson W3C WebAuthn Spec - toJSON}\n */\nexport function serializeCredentialRequestResponse(\n  credential: AuthenticationCredential\n): AuthenticationResponseJSON {\n  // Check if the credential instance has the toJSON method\n  if ('toJSON' in credential \u0026\u0026 typeof credential.toJSON === 'function') {\n    // Use the native WebAuthn Level 3 method\n    return (credential as AuthenticationCredential).toJSON()\n  }\n\n  // Fallback to manual conversion for browsers that don't support toJSON\n  // Access authenticatorAttachment via type assertion to handle TypeScript version differences\n  // @simplewebauthn/types includes this property but base TypeScript 4.7.4 doesn't\n  const credentialWithAttachment = credential as PublicKeyCredential \u0026 {\n    response: AuthenticatorAssertionResponse\n    authenticatorAttachment?: string | null\n  }\n\n  const clientExtensionResults = credential.getClientExtensionResults()\n  const assertionResponse = credential.response\n\n  return {\n    id: credential.id,\n    rawId: credential.id, // W3C spec expects rawId to match id for JSON format\n    response: {\n      authenticatorData: bytesToBase64URL(new Uint8Array(assertionResponse.authenticatorData)),\n      clientDataJSON: bytesToBase64URL(new Uint8Array(assertionResponse.clientDataJSON)),\n      signature: bytesToBase64URL(new Uint8Array(assertionResponse.signature)),\n      userHandle: assertionResponse.userHandle\n        ? bytesToBase64URL(new Uint8Array(assertionResponse.userHandle))\n        : undefined,\n    },\n    type: 'public-key',\n    clientExtensionResults,\n    // Convert null to undefined and cast to AuthenticatorAttachment type\n    authenticatorAttachment: (credentialWithAttachment.authenticatorAttachment ?? undefined) as\n      | AuthenticatorAttachment\n      | undefined,\n  }\n}\n\n/**\n * A simple test to determine if a hostname is a properly-formatted domain name.\n * Considers localhost valid for development environments.\n *\n * A \"valid domain\" is defined here: https://url.spec.whatwg.org/#valid-domain\n *\n * Regex sourced from here:\n * https://www.oreilly.com/library/view/regular-expressions-cookbook/9781449327453/ch08s15.html\n *\n * @param {string} hostname - The hostname to validate\n * @returns {boolean} True if valid domain or localhost\n * @see {@link https://url.spec.whatwg.org/#valid-domain WHATWG URL Spec - Valid Domain}\n */\nexport function isValidDomain(hostname: string): boolean {\n  return (\n    // Consider localhost valid as well since it's okay wrt Secure Contexts\n    hostname === 'localhost' || /^([a-z0-9]+(-[a-z0-9]+)*\\.)+[a-z]{2,}$/i.test(hostname)\n  )\n}\n\n/**\n * Determine if the browser is capable of WebAuthn.\n * Checks for necessary Web APIs: PublicKeyCredential and Credential Management.\n *\n * @returns {boolean} True if browser supports WebAuthn\n * @see {@link https://developer.mozilla.org/en-US/docs/Web/API/PublicKeyCredential#browser_compatibility MDN - PublicKeyCredential Browser Compatibility}\n */\nexport function browserSupportsWebAuthn(): boolean {\n  return !!(\n    isBrowser() \u0026\u0026\n    'PublicKeyCredential' in window \u0026\u0026\n    window.PublicKeyCredential \u0026\u0026\n    'credentials' in navigator \u0026\u0026\n    typeof navigator?.credentials?.create === 'function' \u0026\u0026\n    typeof navigator?.credentials?.get === 'function'\n  )\n}\n\n/**\n * Create a WebAuthn credential using the browser's credentials API.\n * Wraps navigator.credentials.create() with error handling.\n *\n * @param {CredentialCreationOptions} options - Options including publicKey parameters\n * @returns {Promise\u003cRequestResult\u003cRegistrationCredential, WebAuthnError\u003e\u003e} Created credential or error\n * @see {@link https://w3c.github.io/webauthn/#sctn-createCredential W3C WebAuthn Spec - Create Credential}\n * @see {@link https://developer.mozilla.org/en-US/docs/Web/API/CredentialsContainer/create MDN - credentials.create}\n */\nexport async function createCredential(\n  options: StrictOmit\u003cCredentialCreationOptions, 'publicKey'\u003e \u0026 {\n    publicKey: PublicKeyCredentialCreationOptionsFuture\n  }\n): Promise\u003cRequestResult\u003cRegistrationCredential, WebAuthnError\u003e\u003e {\n  try {\n    const response = await navigator.credentials.create(\n      /** we assert the type here until typescript types are updated */\n      options as Parameters\u003ctypeof navigator.credentials.create\u003e[0]\n    )\n    if (!response) {\n      return {\n        data: null,\n        error: new WebAuthnUnknownError('Empty credential response', response),\n      }\n    }\n    if (!(response instanceof PublicKeyCredential)) {\n      return {\n        data: null,\n        error: new WebAuthnUnknownError('Browser returned unexpected credential type', response),\n      }\n    }\n    return { data: response as RegistrationCredential, error: null }\n  } catch (err) {\n    return {\n      data: null,\n      error: identifyRegistrationError({\n        error: err as Error,\n        options,\n      }),\n    }\n  }\n}\n\n/**\n * Get a WebAuthn credential using the browser's credentials API.\n * Wraps navigator.credentials.get() with error handling.\n *\n * @param {CredentialRequestOptions} options - Options including publicKey parameters\n * @returns {Promise\u003cRequestResult\u003cAuthenticationCredential, WebAuthnError\u003e\u003e} Retrieved credential or error\n * @see {@link https://w3c.github.io/webauthn/#sctn-getAssertion W3C WebAuthn Spec - Get Assertion}\n * @see {@link https://developer.mozilla.org/en-US/docs/Web/API/CredentialsContainer/get MDN - credentials.get}\n */\nexport async function getCredential(\n  options: StrictOmit\u003cCredentialRequestOptions, 'publicKey'\u003e \u0026 {\n    publicKey: PublicKeyCredentialRequestOptionsFuture\n  }\n): Promise\u003cRequestResult\u003cAuthenticationCredential, WebAuthnError\u003e\u003e {\n  try {\n    const response = await navigator.credentials.get(\n      /** we assert the type here until typescript types are updated */\n      options as Parameters\u003ctypeof navigator.credentials.get\u003e[0]\n    )\n    if (!response) {\n      return {\n        data: null,\n        error: new WebAuthnUnknownError('Empty credential response', response),\n      }\n    }\n    if (!(response instanceof PublicKeyCredential)) {\n      return {\n        data: null,\n        error: new WebAuthnUnknownError('Browser returned unexpected credential type', response),\n      }\n    }\n    return { data: response as AuthenticationCredential, error: null }\n  } catch (err) {\n    return {\n      data: null,\n      error: identifyAuthenticationError({\n        error: err as Error,\n        options,\n      }),\n    }\n  }\n}\n\nexport const DEFAULT_CREATION_OPTIONS: Partial\u003cPublicKeyCredentialCreationOptionsFuture\u003e = {\n  hints: ['security-key'],\n  authenticatorSelection: {\n    authenticatorAttachment: 'cross-platform',\n    requireResidentKey: false,\n    /** set to preferred because older yubikeys don't have PIN/Biometric */\n    userVerification: 'preferred',\n    residentKey: 'discouraged',\n  },\n  attestation: 'direct',\n}\n\nexport const DEFAULT_REQUEST_OPTIONS: Partial\u003cPublicKeyCredentialRequestOptionsFuture\u003e = {\n  /** set to preferred because older yubikeys don't have PIN/Biometric */\n  userVerification: 'preferred',\n  hints: ['security-key'],\n  attestation: 'direct',\n}\n\nfunction deepMerge\u003cT\u003e(...sources: Partial\u003cT\u003e[]): T {\n  const isObject = (val: unknown): val is Record\u003cstring, unknown\u003e =\u003e\n    val !== null \u0026\u0026 typeof val === 'object' \u0026\u0026 !Array.isArray(val)\n\n  const isArrayBufferLike = (val: unknown): val is ArrayBuffer | ArrayBufferView =\u003e\n    val instanceof ArrayBuffer || ArrayBuffer.isView(val)\n\n  const result: Partial\u003cT\u003e = {}\n\n  for (const source of sources) {\n    if (!source) continue\n\n    for (const key in source) {\n      const value = source[key]\n      if (value === undefined) continue\n\n      if (Array.isArray(value)) {\n        // preserve array reference, including unions like AuthenticatorTransport[]\n        result[key] = value as T[typeof key]\n      } else if (isArrayBufferLike(value)) {\n        result[key] = value as T[typeof key]\n      } else if (isObject(value)) {\n        const existing = result[key]\n        if (isObject(existing)) {\n          result[key] = deepMerge(existing, value) as unknown as T[typeof key]\n        } else {\n          result[key] = deepMerge(value) as unknown as T[typeof key]\n        }\n      } else {\n        result[key] = value as T[typeof key]\n      }\n    }\n  }\n\n  return result as T\n}\n\n/**\n * Merges WebAuthn credential creation options with overrides.\n * Sets sensible defaults for authenticator selection and extensions.\n *\n * @param {PublicKeyCredentialCreationOptionsFuture} baseOptions - The base options from the server\n * @param {PublicKeyCredentialCreationOptionsFuture} overrides - Optional overrides to apply\n * @param {string} friendlyName - Optional friendly name for the credential\n * @returns {PublicKeyCredentialCreationOptionsFuture} Merged credential creation options\n * @see {@link https://w3c.github.io/webauthn/#dictdef-authenticatorselectioncriteria W3C WebAuthn Spec - AuthenticatorSelectionCriteria}\n */\nexport function mergeCredentialCreationOptions(\n  baseOptions: PublicKeyCredentialCreationOptionsFuture,\n  overrides?: Partial\u003cPublicKeyCredentialCreationOptionsFuture\u003e\n): PublicKeyCredentialCreationOptionsFuture {\n  return deepMerge(DEFAULT_CREATION_OPTIONS, baseOptions, overrides || {})\n}\n\n/**\n * Merges WebAuthn credential request options with overrides.\n * Sets sensible defaults for user verification and hints.\n *\n * @param {PublicKeyCredentialRequestOptionsFuture} baseOptions - The base options from the server\n * @param {PublicKeyCredentialRequestOptionsFuture} overrides - Optional overrides to apply\n * @returns {PublicKeyCredentialRequestOptionsFuture} Merged credential request options\n * @see {@link https://w3c.github.io/webauthn/#dictdef-publickeycredentialrequestoptions W3C WebAuthn Spec - PublicKeyCredentialRequestOptions}\n */\nexport function mergeCredentialRequestOptions(\n  baseOptions: PublicKeyCredentialRequestOptionsFuture,\n  overrides?: Partial\u003cPublicKeyCredentialRequestOptionsFuture\u003e\n): PublicKeyCredentialRequestOptionsFuture {\n  return deepMerge(DEFAULT_REQUEST_OPTIONS, baseOptions, overrides || {})\n}\n\n/**\n * WebAuthn API wrapper for Supabase Auth.\n * Provides methods for enrolling, challenging, verifying, authenticating, and registering WebAuthn credentials.\n *\n * @experimental This API is experimental and may change in future releases\n * @see {@link https://w3c.github.io/webauthn/ W3C WebAuthn Specification}\n * @see {@link https://developer.mozilla.org/en-US/docs/Web/API/Web_Authentication_API MDN - Web Authentication API}\n */\nexport class WebAuthnApi {\n  public enroll: typeof WebAuthnApi.prototype._enroll\n  public challenge: typeof WebAuthnApi.prototype._challenge\n  public verify: typeof WebAuthnApi.prototype._verify\n  public authenticate: typeof WebAuthnApi.prototype._authenticate\n  public register: typeof WebAuthnApi.prototype._register\n\n  constructor(private client: GoTrueClient) {\n    // Bind all methods so they can be destructured\n    this.enroll = this._enroll.bind(this)\n    this.challenge = this._challenge.bind(this)\n    this.verify = this._verify.bind(this)\n    this.authenticate = this._authenticate.bind(this)\n    this.register = this._register.bind(this)\n  }\n\n  /**\n   * Enroll a new WebAuthn factor.\n   * Creates an unverified WebAuthn factor that must be verified with a credential.\n   *\n   * @experimental This method is experimental and may change in future releases\n   * @param {Omit\u003cMFAEnrollWebauthnParams, 'factorType'\u003e} params - Enrollment parameters (friendlyName required)\n   * @returns {Promise\u003cAuthMFAEnrollWebauthnResponse\u003e} Enrolled factor details or error\n   * @see {@link https://w3c.github.io/webauthn/#sctn-registering-a-new-credential W3C WebAuthn Spec - Registering a New Credential}\n   */\n  public async _enroll(\n    params: Omit\u003cMFAEnrollWebauthnParams, 'factorType'\u003e\n  ): Promise\u003cAuthMFAEnrollWebauthnResponse\u003e {\n    return this.client.mfa.enroll({ ...params, factorType: 'webauthn' })\n  }\n\n  /**\n   * Challenge for WebAuthn credential creation or authentication.\n   * Combines server challenge with browser credential operations.\n   * Handles both registration (create) and authentication (request) flows.\n   *\n   * @experimental This method is experimental and may change in future releases\n   * @param {MFAChallengeWebauthnParams \u0026 { friendlyName?: string; signal?: AbortSignal }} params - Challenge parameters including factorId\n   * @param {Object} overrides - Allows you to override the parameters passed to navigator.credentials\n   * @param {PublicKeyCredentialCreationOptionsFuture} overrides.create - Override options for credential creation\n   * @param {PublicKeyCredentialRequestOptionsFuture} overrides.request - Override options for credential request\n   * @returns {Promise\u003cRequestResult\u003e} Challenge response with credential or error\n   * @see {@link https://w3c.github.io/webauthn/#sctn-credential-creation W3C WebAuthn Spec - Credential Creation}\n   * @see {@link https://w3c.github.io/webauthn/#sctn-verifying-assertion W3C WebAuthn Spec - Verifying Assertion}\n   */\n  public async _challenge(\n    {\n      factorId,\n      webauthn,\n      friendlyName,\n      signal,\n    }: MFAChallengeWebauthnParams \u0026 { friendlyName?: string; signal?: AbortSignal },\n    overrides?:\n      | {\n          create?: Partial\u003cPublicKeyCredentialCreationOptionsFuture\u003e\n          request?: never\n        }\n      | {\n          create?: never\n          request?: Partial\u003cPublicKeyCredentialRequestOptionsFuture\u003e\n        }\n  ): Promise\u003c\n    RequestResult\u003c\n      { factorId: string; challengeId: string } \u0026 {\n        webauthn: StrictOmit\u003c\n          MFAVerifyWebauthnParamFields\u003c'create' | 'request'\u003e['webauthn'],\n          'rpId' | 'rpOrigins'\n        \u003e\n      },\n      WebAuthnError | AuthError\n    \u003e\n  \u003e {\n    try {\n      // Get challenge from server using the client's MFA methods\n      const { data: challengeResponse, error: challengeError } = await this.client.mfa.challenge({\n        factorId,\n        webauthn,\n      })\n\n      if (!challengeResponse) {\n        return { data: null, error: challengeError }\n      }\n\n      const abortSignal = signal ?? webAuthnAbortService.createNewAbortSignal()\n\n      /** webauthn will fail if either of the name/displayname are blank */\n      if (challengeResponse.webauthn.type === 'create') {\n        const { user } = challengeResponse.webauthn.credential_options.publicKey\n        if (!user.name) {\n          // Preserve original format: use friendlyName if provided, otherwise fetch fallback\n          // This maintains backward compatibility with the ${user.id}:${name} format\n          const nameToUse = friendlyName\n          if (!nameToUse) {\n            // Only fetch user data if friendlyName is not provided (bug fix for null friendlyName)\n            const currentUser = await this.client.getUser()\n            const userData = currentUser.data.user\n            const fallbackName =\n              userData?.user_metadata?.name || userData?.email || userData?.id || 'User'\n            user.name = `${user.id}:${fallbackName}`\n          } else {\n            user.name = `${user.id}:${nameToUse}`\n          }\n        }\n        if (!user.displayName) {\n          user.displayName = user.name\n        }\n      }\n\n      switch (challengeResponse.webauthn.type) {\n        case 'create': {\n          const options = mergeCredentialCreationOptions(\n            challengeResponse.webauthn.credential_options.publicKey,\n            overrides?.create\n          )\n\n          const { data, error } = await createCredential({\n            publicKey: options,\n            signal: abortSignal,\n          })\n\n          if (data) {\n            return {\n              data: {\n                factorId,\n                challengeId: challengeResponse.id,\n                webauthn: {\n                  type: challengeResponse.webauthn.type,\n                  credential_response: data,\n                },\n              },\n              error: null,\n            }\n          }\n          return { data: null, error }\n        }\n\n        case 'request': {\n          const options = mergeCredentialRequestOptions(\n            challengeResponse.webauthn.credential_options.publicKey,\n            overrides?.request\n          )\n\n          const { data, error } = await getCredential({\n            ...challengeResponse.webauthn.credential_options,\n            publicKey: options,\n            signal: abortSignal,\n          })\n\n          if (data) {\n            return {\n              data: {\n                factorId,\n                challengeId: challengeResponse.id,\n                webauthn: {\n                  type: challengeResponse.webauthn.type,\n                  credential_response: data,\n                },\n              },\n              error: null,\n            }\n          }\n          return { data: null, error }\n        }\n      }\n    } catch (error) {\n      if (isAuthError(error)) {\n        return { data: null, error }\n      }\n      return {\n        data: null,\n        error: new AuthUnknownError('Unexpected error in challenge', error),\n      }\n    }\n  }\n\n  /**\n   * Verify a WebAuthn credential with the server.\n   * Completes the WebAuthn ceremony by sending the credential to the server for verification.\n   *\n   * @experimental This method is experimental and may change in future releases\n   * @param {Object} params - Verification parameters\n   * @param {string} params.challengeId - ID of the challenge being verified\n   * @param {string} params.factorId - ID of the WebAuthn factor\n   * @param {MFAVerifyWebauthnParams\u003cT\u003e['webauthn']} params.webauthn - WebAuthn credential response\n   * @returns {Promise\u003cAuthMFAVerifyResponse\u003e} Verification result with session or error\n   * @see {@link https://w3c.github.io/webauthn/#sctn-verifying-assertion W3C WebAuthn Spec - Verifying an Authentication Assertion}\n   * */\n  public async _verify\u003cT extends 'create' | 'request'\u003e({\n    challengeId,\n    factorId,\n    webauthn,\n  }: {\n    challengeId: string\n    factorId: string\n    webauthn: MFAVerifyWebauthnParams\u003cT\u003e['webauthn']\n  }): Promise\u003cAuthMFAVerifyResponse\u003e {\n    return this.client.mfa.verify({\n      factorId,\n      challengeId,\n      webauthn: webauthn,\n    })\n  }\n\n  /**\n   * Complete WebAuthn authentication flow.\n   * Performs challenge and verification in a single operation for existing credentials.\n   *\n   * @experimental This method is experimental and may change in future releases\n   * @param {Object} params - Authentication parameters\n   * @param {string} params.factorId - ID of the WebAuthn factor to authenticate with\n   * @param {Object} params.webauthn - WebAuthn configuration\n   * @param {string} params.webauthn.rpId - Relying Party ID (defaults to current hostname)\n   * @param {string[]} params.webauthn.rpOrigins - Allowed origins (defaults to current origin)\n   * @param {AbortSignal} params.webauthn.signal - Optional abort signal\n   * @param {PublicKeyCredentialRequestOptionsFuture} overrides - Override options for navigator.credentials.get\n   * @returns {Promise\u003cRequestResult\u003cAuthMFAVerifyResponseData, WebAuthnError | AuthError\u003e\u003e} Authentication result\n   * @see {@link https://w3c.github.io/webauthn/#sctn-authentication W3C WebAuthn Spec - Authentication Ceremony}\n   * @see {@link https://developer.mozilla.org/en-US/docs/Web/API/PublicKeyCredentialRequestOptions MDN - PublicKeyCredentialRequestOptions}\n   */\n  public async _authenticate(\n    {\n      factorId,\n      webauthn: {\n        rpId = typeof window !== 'undefined' ? window.location.hostname : undefined,\n        rpOrigins = typeof window !== 'undefined' ? [window.location.origin] : undefined,\n        signal,\n      } = {},\n    }: {\n      factorId: string\n      webauthn?: {\n        rpId?: string\n        rpOrigins?: string[]\n        signal?: AbortSignal\n      }\n    },\n    overrides?: PublicKeyCredentialRequestOptionsFuture\n  ): Promise\u003cRequestResult\u003cAuthMFAVerifyResponseData, WebAuthnError | AuthError\u003e\u003e {\n    if (!rpId) {\n      return {\n        data: null,\n        error: new AuthError('rpId is required for WebAuthn authentication'),\n      }\n    }\n    try {\n      if (!browserSupportsWebAuthn()) {\n        return {\n          data: null,\n          error: new AuthUnknownError('Browser does not support WebAuthn', null),\n        }\n      }\n\n      // Get challenge and credential\n      const { data: challengeResponse, error: challengeError } = await this.challenge(\n        {\n          factorId,\n          webauthn: { rpId, rpOrigins },\n          signal,\n        },\n        { request: overrides }\n      )\n\n      if (!challengeResponse) {\n        return { data: null, error: challengeError }\n      }\n\n      const { webauthn } = challengeResponse\n\n      // Verify credential\n      return this._verify({\n        factorId,\n        challengeId: challengeResponse.challengeId,\n        webauthn: {\n          type: webauthn.type,\n          rpId,\n          rpOrigins,\n          credential_response: webauthn.credential_response,\n        },\n      })\n    } catch (error) {\n      if (isAuthError(error)) {\n        return { data: null, error }\n      }\n      return {\n        data: null,\n        error: new AuthUnknownError('Unexpected error in authenticate', error),\n      }\n    }\n  }\n\n  /**\n   * Complete WebAuthn registration flow.\n   * Performs enrollment, challenge, and verification in a single operation for new credentials.\n   *\n   * @experimental This method is experimental and may change in future releases\n   * @param {Object} params - Registration parameters\n   * @param {string} params.friendlyName - User-friendly name for the credential\n   * @param {string} params.rpId - Relying Party ID (defaults to current hostname)\n   * @param {string[]} params.rpOrigins - Allowed origins (defaults to current origin)\n   * @param {AbortSignal} params.signal - Optional abort signal\n   * @param {PublicKeyCredentialCreationOptionsFuture} overrides - Override options for navigator.credentials.create\n   * @returns {Promise\u003cRequestResult\u003cAuthMFAVerifyResponseData, WebAuthnError | AuthError\u003e\u003e} Registration result\n   * @see {@link https://w3c.github.io/webauthn/#sctn-registering-a-new-credential W3C WebAuthn Spec - Registration Ceremony}\n   * @see {@link https://developer.mozilla.org/en-US/docs/Web/API/PublicKeyCredentialCreationOptions MDN - PublicKeyCredentialCreationOptions}\n   */\n  public async _register(\n    {\n      friendlyName,\n      webauthn: {\n        rpId = typeof window !== 'undefined' ? window.location.hostname : undefined,\n        rpOrigins = typeof window !== 'undefined' ? [window.location.origin] : undefined,\n        signal,\n      } = {},\n    }: {\n      friendlyName: string\n      webauthn?: {\n        rpId?: string\n        rpOrigins?: string[]\n        signal?: AbortSignal\n      }\n    },\n    overrides?: Partial\u003cPublicKeyCredentialCreationOptionsFuture\u003e\n  ): Promise\u003cRequestResult\u003cAuthMFAVerifyResponseData, WebAuthnError | AuthError\u003e\u003e {\n    if (!rpId) {\n      return {\n        data: null,\n        error: new AuthError('rpId is required for WebAuthn registration'),\n      }\n    }\n    try {\n      if (!browserSupportsWebAuthn()) {\n        return {\n          data: null,\n          error: new AuthUnknownError('Browser does not support WebAuthn', null),\n        }\n      }\n\n      // Enroll factor\n      const { data: factor, error: enrollError } = await this._enroll({\n        friendlyName,\n      })\n\n      if (!factor) {\n        await this.client.mfa\n          .listFactors()\n          .then((factors) =\u003e\n            // Only an unverified factor is leftover from the enrollment that just\n            // failed, and removing it is what lets a retry with the same name\n            // succeed. A verified factor of that name is a passkey the user is\n            // already using, so it must never be selected here.\n            factors.data?.all.find(\n              (v) =\u003e\n                v.factor_type === 'webauthn' \u0026\u0026\n                v.friendly_name === friendlyName \u0026\u0026\n                v.status === 'unverified'\n            )\n          )\n          .then((factor) =\u003e (factor ? this.client.mfa.unenroll({ factorId: factor?.id }) : void 0))\n        return { data: null, error: enrollError }\n      }\n\n      // Get challenge and create credential\n      const { data: challengeResponse, error: challengeError } = await this._challenge(\n        {\n          factorId: factor.id,\n          friendlyName: factor.friendly_name,\n          webauthn: { rpId, rpOrigins },\n          signal,\n        },\n        {\n          create: overrides,\n        }\n      )\n\n      if (!challengeResponse) {\n        return { data: null, error: challengeError }\n      }\n\n      return this._verify({\n        factorId: factor.id,\n        challengeId: challengeResponse.challengeId,\n        webauthn: {\n          rpId,\n          rpOrigins,\n          type: challengeResponse.webauthn.type,\n          credential_response: challengeResponse.webauthn.credential_response,\n        },\n      })\n    } catch (error) {\n      if (isAuthError(error)) {\n        return { data: null, error }\n      }\n      return {\n        data: null,\n        error: new AuthUnknownError('Unexpected error in register', error),\n      }\n    }\n  }\n}\n","import GoTrueAdminApi from './GoTrueAdminApi'\nimport {\n  AUTO_REFRESH_TICK_DURATION_MS,\n  AUTO_REFRESH_TICK_THRESHOLD,\n  DEFAULT_HEADERS,\n  EXPIRY_MARGIN_MS,\n  GOTRUE_URL,\n  JWKS_TTL,\n  PKCE_FLOW_ID_PARAM,\n  REFRESH_FAILURE_COOLDOWN_MS,\n  STORAGE_KEY,\n} from './lib/constants'\nimport {\n  AuthError,\n  AuthImplicitGrantRedirectError,\n  AuthInvalidCredentialsError,\n  AuthInvalidJwtError,\n  AuthInvalidTokenResponseError,\n  AuthPKCECodeVerifierMissingError,\n  AuthPKCEGrantCodeExchangeError,\n  AuthRefreshDiscardedError,\n  AuthSessionMissingError,\n  AuthUnknownError,\n  isAuthApiError,\n  isAuthError,\n  isAuthImplicitGrantRedirectError,\n  isAuthRefreshDiscardedError,\n  isAuthRetryableFetchError,\n  isAuthSessionMissingError,\n} from './lib/errors'\nimport {\n  Fetch,\n  _request,\n  _sessionResponse,\n  _sessionResponsePassword,\n  _ssoResponse,\n  _userResponse,\n} from './lib/fetch'\nimport {\n  appendFlowIdToRedirectTo,\n  assertRecoveryCodesExperimentalEnabled,\n  decodeJWT,\n  deepClone,\n  Deferred,\n  expiresAt,\n  generateCallbackId,\n  getAlgorithm,\n  getCodeChallengeAndMethod,\n  getItemAsync,\n  insecureUserWarningProxy,\n  isBrowser,\n  parseParametersFromURL,\n  pkceVerifierSlotKey,\n  removeAllPKCEVerifiers,\n  removeItemAsync,\n  removePKCEVerifier,\n  resolveFetch,\n  retrievePKCEVerifier,\n  retryable,\n  setItemAsync,\n  sleep,\n  supportsLocalStorage,\n  userNotAvailableProxy,\n  validateExp,\n  validatePKCEFlowId,\n} from './lib/helpers'\nimport { memoryLocalStorageAdapter } from './lib/local-storage'\nimport { LockAcquireTimeoutError, navigatorLock } from './lib/locks'\nimport { polyfillGlobalThis } from './lib/polyfills'\nimport { version } from './lib/version'\n\nimport { bytesToBase64URL, stringToUint8Array } from './lib/base64url'\nimport type {\n  AuthChangeEvent,\n  AuthenticatorAssuranceLevels,\n  AuthFlowType,\n  AuthMFAChallengePhoneResponse,\n  AuthMFAChallengeResponse,\n  AuthMFAChallengeTOTPResponse,\n  AuthMFAChallengeWebauthnResponse,\n  AuthMFAChallengeWebauthnServerResponse,\n  AuthMFAEnrollPhoneResponse,\n  AuthMFAEnrollResponse,\n  AuthMFAEnrollTOTPResponse,\n  AuthMFAEnrollWebauthnResponse,\n  AuthMFAGetAuthenticatorAssuranceLevelResponse,\n  AuthMFAListFactorsResponse,\n  AuthMFARecoveryCodesGenerateResponse,\n  AuthMFARecoveryCodesStatusResponse,\n  AuthMFAUnenrollResponse,\n  AuthMFAVerifyResponse,\n  AuthOtpResponse,\n  AuthResponse,\n  AuthResponsePassword,\n  AuthTokenResponse,\n  AuthTokenResponsePassword,\n  CallRefreshTokenResult,\n  EthereumWallet,\n  EthereumWeb3Credentials,\n  Factor,\n  GoTrueClientOptions,\n  GoTrueMFAApi,\n  InitializeResult,\n  JWK,\n  JwtHeader,\n  JwtPayload,\n  LockFunc,\n  MFAChallengeAndVerifyParams,\n  MFAChallengeParams,\n  MFAChallengePhoneParams,\n  MFAChallengeTOTPParams,\n  MFAChallengeWebauthnParams,\n  MFAEnrollParams,\n  MFAEnrollPhoneParams,\n  MFAEnrollTOTPParams,\n  MFAEnrollWebauthnParams,\n  MFARecoveryCodesGenerateParams,\n  MFARecoveryCodesVerifyParams,\n  MFAUnenrollParams,\n  MFAVerifyParams,\n  MFAVerifyPhoneParams,\n  MFAVerifyTOTPParams,\n  MFAVerifyWebauthnParamFields,\n  MFAVerifyWebauthnParams,\n  OAuthResponse,\n  AuthOAuthServerApi,\n  AuthOAuthAuthorizationDetailsResponse,\n  AuthOAuthConsentResponse,\n  AuthOAuthGrantsResponse,\n  AuthOAuthRevokeGrantResponse,\n  Prettify,\n  Provider,\n  ResendParams,\n  Session,\n  SignInAnonymouslyCredentials,\n  SignInWithIdTokenCredentials,\n  SignInWithOAuthCredentials,\n  SignInWithPasswordCredentials,\n  SignInWithPasswordlessCredentials,\n  SignInWithSSO,\n  SignOut,\n  SignUpWithPasswordCredentials,\n  SolanaWallet,\n  SolanaWeb3Credentials,\n  SSOResponse,\n  StrictOmit,\n  Subscription,\n  SupportedStorage,\n  User,\n  UserAttributes,\n  UserIdentity,\n  UserResponse,\n  VerifyOtpParams,\n  Web3Credentials,\n  AuthPasskeyApi,\n  ExperimentalFeatureFlags,\n  SignInWithPasskeyCredentials,\n  RegisterPasskeyCredentials,\n  VerifyPasskeyRegistrationParams,\n  StartPasskeyAuthenticationParams,\n  VerifyPasskeyAuthenticationParams,\n  PasskeyUpdateParams,\n  PasskeyDeleteParams,\n  AuthPasskeyRegistrationOptionsResponse,\n  AuthPasskeyRegistrationVerifyResponse,\n  AuthPasskeyAuthenticationOptionsResponse,\n  AuthPasskeyAuthenticationVerifyResponse,\n  AuthPasskeyListResponse,\n  AuthPasskeyUpdateResponse,\n  AuthPasskeyDeleteResponse,\n} from './lib/types'\nimport {\n  createSiweMessage,\n  fromHex,\n  getAddress,\n  Hex,\n  SiweMessage,\n  toHex,\n} from './lib/web3/ethereum'\nimport {\n  createCredential,\n  deserializeCredentialCreationOptions,\n  deserializeCredentialRequestOptions,\n  getCredential,\n  serializeCredentialCreationResponse,\n  serializeCredentialRequestResponse,\n  browserSupportsWebAuthn,\n  webAuthnAbortService,\n  WebAuthnApi,\n} from './lib/webauthn'\nimport {\n  AuthenticationCredential,\n  PublicKeyCredentialJSON,\n  RegistrationCredential,\n} from './lib/webauthn.dom'\n\npolyfillGlobalThis() // Make \"globalThis\" available\n\nconst DEFAULT_OPTIONS: Omit\u003c\n  Required\u003cGoTrueClientOptions\u003e,\n  'fetch' | 'storage' | 'userStorage' | 'lock'\n\u003e = {\n  url: GOTRUE_URL,\n  storageKey: STORAGE_KEY,\n  autoRefreshToken: true,\n  persistSession: true,\n  detectSessionInUrl: true,\n  headers: DEFAULT_HEADERS,\n  flowType: 'implicit',\n  debug: false,\n  hasCustomAuthorizationHeader: false,\n  throwOnError: false,\n  lockAcquireTimeout: 5000, // 5 seconds. Only used when a custom `lock` is supplied. TODO(v3): remove.\n  skipAutoInitialize: false,\n  experimental: {},\n}\n\n/**\n * No-op lock used internally as a placeholder. Kept so older test setups that\n * inject this exact reference do not break; new code never sees it because\n * `this.lock` stays `null` when no custom lock is supplied (lockless path).\n * TODO(v3): remove with the legacy lock path.\n */\nasync function lockNoOp\u003cR\u003e(name: string, acquireTimeout: number, fn: () =\u003e Promise\u003cR\u003e): Promise\u003cR\u003e {\n  return await fn()\n}\n\n/**\n * Caches JWKS values for all clients created in the same environment. This is\n * especially useful for shared-memory execution environments such as Vercel's\n * Fluid Compute, AWS Lambda or Supabase's Edge Functions. Regardless of how\n * many clients are created, if they share the same storage key they will use\n * the same JWKS cache, significantly speeding up getClaims() with asymmetric\n * JWTs.\n */\nconst GLOBAL_JWKS: { [storageKey: string]: { cachedAt: number; jwks: { keys: JWK[] } } } = {}\n\n// Warn once per JS realm, not per client instance — server-side apps can\n// construct many clients per process and must not be spammed.\nlet deprecatedLockWarned = false\n\nexport default class GoTrueClient {\n  private static nextInstanceID: Record\u003cstring, number\u003e = {}\n\n  private instanceID: number\n\n  /**\n   * Namespace for the GoTrue admin methods.\n   * These methods should only be used in a trusted server-side environment.\n   */\n  admin: GoTrueAdminApi\n  /**\n   * Namespace for the MFA methods.\n   */\n  mfa: GoTrueMFAApi\n  /**\n   * Namespace for the OAuth 2.1 authorization server methods.\n   * Only relevant when the OAuth 2.1 server is enabled in Supabase Auth.\n   * Used to implement the authorization code flow on the consent page.\n   */\n  oauth: AuthOAuthServerApi\n  /**\n   * Namespace for passkey methods.\n   * Includes lower-level two-step registration/authentication and passkey management.\n   */\n  passkey: AuthPasskeyApi\n  /**\n   * The storage key used to identify the values saved in localStorage\n   */\n  protected storageKey: string\n\n  protected flowType: AuthFlowType\n\n  /**\n   * The JWKS used for verifying asymmetric JWTs\n   */\n  protected get jwks() {\n    return GLOBAL_JWKS[this.storageKey]?.jwks ?? { keys: [] }\n  }\n\n  protected set jwks(value: { keys: JWK[] }) {\n    GLOBAL_JWKS[this.storageKey] = { ...GLOBAL_JWKS[this.storageKey], jwks: value }\n  }\n\n  protected get jwks_cached_at() {\n    return GLOBAL_JWKS[this.storageKey]?.cachedAt ?? Number.MIN_SAFE_INTEGER\n  }\n\n  protected set jwks_cached_at(value: number) {\n    GLOBAL_JWKS[this.storageKey] = { ...GLOBAL_JWKS[this.storageKey], cachedAt: value }\n  }\n\n  protected autoRefreshToken: boolean\n  protected persistSession: boolean\n  protected storage: SupportedStorage\n  /**\n   * @experimental\n   */\n  protected userStorage: SupportedStorage | null = null\n  protected memoryStorage: { [key: string]: string } | null = null\n  protected stateChangeEmitters: Map\u003cstring | symbol, Subscription\u003e = new Map()\n  protected autoRefreshTicker: ReturnType\u003ctypeof setInterval\u003e | null = null\n  protected autoRefreshTickTimeout: ReturnType\u003ctypeof setTimeout\u003e | null = null\n  protected visibilityChangedCallback: (() =\u003e Promise\u003cany\u003e) | null = null\n  protected refreshingDeferred: Deferred\u003cCallRefreshTokenResult\u003e | null = null\n  /**\n   * Cache of the most recent refresh failure, keyed by the refresh token\n   * that failed. Serial callers passing the *same* token within\n   * `REFRESH_FAILURE_COOLDOWN_MS` (including subsequent auto-refresh ticks)\n   * receive this cached result instead of firing another `/token` request.\n   * Callers passing a *different* token (token rotation pickup, explicit\n   * `setSession`/`refreshSession({ refresh_token })`, multi-account switch)\n   * bypass the cache and attempt a fresh refresh as they should.\n   * Cleared on any successful refresh (locally or via BroadcastChannel from\n   * another tab) and on `_removeSession`.\n   *\n   * Pairs with `refreshingDeferred`: concurrent callers share the in-flight\n   * promise, serial callers within the cooldown share the failure result.\n   */\n  protected lastRefreshFailure: {\n    refreshToken: string\n    result: CallRefreshTokenResult\n    expiresAt: number\n  } | null = null\n  /**\n   * Monotonic counter incremented at the top of `_removeSession`, before any\n   * `await`. The commit guard inside `_callRefreshToken` captures this value\n   * before `_saveSession` and re-checks it after, so a `signOut` that\n   * interleaves inside `_saveSession`'s storage-write awaits is still caught\n   * (the post-fetch storage snapshot alone misses that window).\n   */\n  protected _sessionRemovalEpoch = 0\n  /**\n   * Keeps track of the async client initialization.\n   * When null or not yet resolved the auth state is `unknown`\n   * Once resolved the auth state is known and it's safe to call any further client methods.\n   * Keep extra care to never reject or throw uncaught errors\n   */\n  protected initializePromise: Promise\u003cInitializeResult\u003e | null = null\n  /**\n   * Non-null only while `initialize()` is running. While open,\n   * `_notifyAllSubscribers` enqueues init-chain notifications (those fired with\n   * `broadcast = true`, i.e. from `_recoverAndRefresh`) into this array instead\n   * of firing directly, so that `initializePromise` is guaranteed to be\n   * resolved before any subscriber callback runs. Callbacks that call\n   * `getSession()` / `getUser()` etc. would otherwise deadlock because those\n   * methods await `initializePromise`. Notifications from the incoming\n   * BroadcastChannel handler (`broadcast = false`) are not enqueued — they fire\n   * immediately. Flushed (in order) by `initialize()` after `initializePromise`\n   * settles.\n   */\n  private _pendingInitNotifications: Array\u003c{\n    event: AuthChangeEvent\n    session: Session | null\n    broadcast: boolean\n  }\u003e | null = null\n  protected detectSessionInUrl:\n    | boolean\n    | ((url: URL, params: { [parameter: string]: string }) =\u003e boolean) = true\n  protected url: string\n  protected headers: {\n    [key: string]: string\n  }\n  protected hasCustomAuthorizationHeader = false\n  protected suppressGetSessionWarning = false\n  protected fetch: Fetch\n  /**\n   * Custom lock function passed via `settings.lock`. When non-null, every auth\n   * operation runs inside `_acquireLock`. When null (the default), the client\n   * uses its lockless coordination (refresh single-flight + commit guard).\n   * TODO(v3): remove along with the legacy lock path.\n   */\n  protected lock: LockFunc | null = null\n  protected lockAcquired = false\n  protected pendingInLock: Promise\u003cany\u003e[] = []\n  protected throwOnError: boolean\n  /**\n   * Only consulted when a custom `lock` is supplied. TODO(v3): remove.\n   */\n  protected lockAcquireTimeout: number\n  /**\n   * Opt-in flags for experimental features. Defaults to an empty object.\n   * See `GoTrueClientOptions.experimental`.\n   */\n  protected experimental: ExperimentalFeatureFlags\n\n  /**\n   * Used to broadcast state change events to other tabs listening.\n   */\n  protected broadcastChannel: BroadcastChannel | null = null\n\n  protected logDebugMessages: boolean\n  protected logger: (message: string, ...args: any[]) =\u003e void = console.log\n\n  /**\n   * Create a new client for use in the browser.\n   *\n   * @example Using supabase-js (recommended)\n   * ```ts\n   * import { createClient } from '@supabase/supabase-js'\n   *\n   * const supabase = createClient('https://xyzcompany.supabase.co', 'your-publishable-key')\n   * const { data, error } = await supabase.auth.getUser()\n   * ```\n   *\n   * @example Standalone import for bundle-sensitive environments\n   * ```ts\n   * import { GoTrueClient } from '@supabase/auth-js'\n   *\n   * const auth = new GoTrueClient({\n   *   url: 'https://xyzcompany.supabase.co/auth/v1',\n   *   headers: { apikey: 'your-publishable-key' },\n   *   storageKey: 'supabase-auth',\n   * })\n   * ```\n   */\n  constructor(options: GoTrueClientOptions) {\n    const settings = { ...DEFAULT_OPTIONS, ...options }\n    this.storageKey = settings.storageKey\n\n    this.instanceID = GoTrueClient.nextInstanceID[this.storageKey] ?? 0\n    GoTrueClient.nextInstanceID[this.storageKey] = this.instanceID + 1\n\n    this.logDebugMessages = !!settings.debug\n    if (typeof settings.debug === 'function') {\n      this.logger = settings.debug\n    }\n\n    if (this.instanceID \u003e 0 \u0026\u0026 isBrowser()) {\n      const message = `${this._logPrefix()} Multiple GoTrueClient instances detected in the same browser context. It is not an error, but this should be avoided as it may produce undefined behavior when used concurrently under the same storage key.`\n      console.warn(message)\n      if (this.logDebugMessages) {\n        console.trace(message)\n      }\n    }\n\n    this.persistSession = settings.persistSession\n    this.autoRefreshToken = settings.autoRefreshToken\n    this.experimental = settings.experimental ?? {}\n    this.admin = new GoTrueAdminApi({\n      url: settings.url,\n      headers: settings.headers,\n      fetch: settings.fetch,\n      experimental: this.experimental,\n    })\n\n    this.url = settings.url\n    this.headers = settings.headers\n    this.fetch = resolveFetch(settings.fetch)\n    this.detectSessionInUrl = settings.detectSessionInUrl\n    this.flowType = settings.flowType\n    this.hasCustomAuthorizationHeader = settings.hasCustomAuthorizationHeader\n    this.throwOnError = settings.throwOnError\n\n    // Always wire `lockAcquireTimeout` even on the lockless path: consumers\n    // (including supabase-js tests) read it off the client to verify option\n    // flow-through.\n    this.lockAcquireTimeout = settings.lockAcquireTimeout\n\n    // TODO(v3): remove. Legacy opt-in path preserved for backwards\n    // compatibility with callers passing a custom `lock` (typically React\n    // Native `processLock` or Node multi-process setups). When `settings.lock`\n    // is null the client uses its lockless coordination — no `navigator.locks`\n    // by default, no implicit `processLock`.\n    if (settings.lock != null) {\n      this.lock = settings.lock\n\n      if (!deprecatedLockWarned) {\n        deprecatedLockWarned = true\n        console.warn(\n          `${this._logPrefix()} The \"lock\" option is deprecated and will be removed in v3. The client now coordinates session refreshes without a lock, so most apps can drop the option. See https://github.com/supabase/supabase-js/blob/master/packages/core/auth-js/migrations/lockless-coordination.md`\n        )\n      }\n    }\n\n    if (!this.jwks) {\n      this.jwks = { keys: [] }\n      this.jwks_cached_at = Number.MIN_SAFE_INTEGER\n    }\n\n    this.mfa = {\n      verify: this._verify.bind(this),\n      enroll: this._enroll.bind(this),\n      unenroll: this._unenroll.bind(this),\n      challenge: this._challenge.bind(this),\n      listFactors: this._listFactors.bind(this),\n      challengeAndVerify: this._challengeAndVerify.bind(this),\n      getAuthenticatorAssuranceLevel: this._getAuthenticatorAssuranceLevel.bind(this),\n      webauthn: new WebAuthnApi(this),\n      recoveryCodes: {\n        getStatus: this._getRecoveryCodesStatus.bind(this),\n        generate: this._generateRecoveryCodes.bind(this),\n        verify: this._verifyRecoveryCode.bind(this),\n        regenerate: this._regenerateRecoveryCodes.bind(this),\n        unenroll: this._unenrollRecoveryCodes.bind(this),\n      },\n    }\n\n    this.oauth = {\n      getAuthorizationDetails: this._getAuthorizationDetails.bind(this),\n      approveAuthorization: this._approveAuthorization.bind(this),\n      denyAuthorization: this._denyAuthorization.bind(this),\n      listGrants: this._listOAuthGrants.bind(this),\n      revokeGrant: this._revokeOAuthGrant.bind(this),\n    }\n\n    this.passkey = {\n      startRegistration: this._startPasskeyRegistration.bind(this),\n      verifyRegistration: this._verifyPasskeyRegistration.bind(this),\n      startAuthentication: this._startPasskeyAuthentication.bind(this),\n      verifyAuthentication: this._verifyPasskeyAuthentication.bind(this),\n      list: this._listPasskeys.bind(this),\n      update: this._updatePasskey.bind(this),\n      delete: this._deletePasskey.bind(this),\n    }\n\n    if (this.persistSession) {\n      if (settings.storage) {\n        this.storage = settings.storage\n      } else {\n        if (supportsLocalStorage()) {\n          this.storage = globalThis.localStorage\n        } else {\n          this.memoryStorage = {}\n          this.storage = memoryLocalStorageAdapter(this.memoryStorage)\n        }\n      }\n\n      if (settings.userStorage) {\n        this.userStorage = settings.userStorage\n      }\n    } else {\n      this.memoryStorage = {}\n      this.storage = memoryLocalStorageAdapter(this.memoryStorage)\n    }\n\n    if (isBrowser() \u0026\u0026 globalThis.BroadcastChannel \u0026\u0026 this.persistSession \u0026\u0026 this.storageKey) {\n      try {\n        this.broadcastChannel = new globalThis.BroadcastChannel(this.storageKey)\n      } catch (e) {\n        console.error(\n          'Failed to create a new BroadcastChannel, multi-tab state changes will not be available',\n          e\n        )\n      }\n\n      this.broadcastChannel?.addEventListener('message', async (event) =\u003e {\n        this._debug('received broadcast notification from other tab or client', event)\n\n        // Another tab successfully refreshed or signed in — any cached\n        // failure in this tab is stale and should not block the next\n        // refresh attempt.\n        if (event.data.event === 'TOKEN_REFRESHED' || event.data.event === 'SIGNED_IN') {\n          this.lastRefreshFailure = null\n        }\n\n        try {\n          await this._notifyAllSubscribers(event.data.event, event.data.session, false) // broadcast = false so we don't get an endless loop of messages\n        } catch (error) {\n          this._debug('#broadcastChannel', 'error', error)\n        }\n      })\n    }\n\n    // Only auto-initialize if not explicitly disabled. Skipped in SSR contexts\n    // where initialization timing must be controlled. All public methods have\n    // lazy initialization, so the client remains fully functional.\n    if (!settings.skipAutoInitialize) {\n      this.initialize().catch((error) =\u003e {\n        this._debug('#initialize()', 'error', error)\n      })\n    }\n  }\n\n  /**\n   * Returns whether error throwing mode is enabled for this client.\n   */\n  public isThrowOnErrorEnabled(): boolean {\n    return this.throwOnError\n  }\n\n  /**\n   * Centralizes return handling with optional error throwing. When `throwOnError` is enabled\n   * and the provided result contains a non-nullish error, the error is thrown instead of\n   * being returned. This ensures consistent behavior across all public API methods.\n   */\n  private _returnResult\u003cT extends { error: any }\u003e(result: T): T {\n    if (this.throwOnError \u0026\u0026 result \u0026\u0026 result.error) {\n      throw result.error\n    }\n    return result\n  }\n\n  private _logPrefix(): string {\n    return (\n      'GoTrueClient@' +\n      `${this.storageKey}:${this.instanceID} (${version}) ${new Date().toISOString()}`\n    )\n  }\n\n  private _debug(...args: any[]): GoTrueClient {\n    if (this.logDebugMessages) {\n      this.logger(this._logPrefix(), ...args)\n    }\n\n    return this\n  }\n\n  /**\n   * Initialize the auth client by loading the session from storage or\n   * detecting it from the URL after an OAuth, magic-link, or password-recovery\n   * redirect.\n   *\n   * **Most callers do not need to invoke this directly.** The client calls it\n   * automatically during construction, and to react to sign-in events (including\n   * post-redirect events) you should subscribe to `onAuthStateChange` rather\n   * than awaiting `initialize()`.\n   *\n   * You only need to call it manually when you have opted out of the automatic\n   * call by passing `skipAutoInitialize: true` — for example, in an SSR context\n   * where you need to control initialization timing. In that case, awaiting\n   * `initialize()` returns the resolved session result (or any error encountered\n   * while detecting it from the URL).\n   *\n   * @category Auth\n   */\n  async initialize(): Promise\u003cInitializeResult\u003e {\n    if (this.initializePromise) {\n      return await this.initializePromise\n    }\n\n    // Open the notification queue before _initialize() runs so that every\n    // _notifyAllSubscribers call inside the init chain enqueues instead of\n    // firing. Without this, a callback receiving SIGNED_IN (or TOKEN_REFRESHED\n    // / SIGNED_OUT) during _recoverAndRefresh would deadlock if it called\n    // getSession() / getUser() — those methods await initializePromise, which\n    // can only resolve after the callback returns, which can only return after\n    // getSession() resolves. The queue is flushed below after initializePromise\n    // has settled, so callbacks run with a fully resolved initializePromise.\n    this._pendingInitNotifications = []\n\n    this.initializePromise = (async () =\u003e {\n      if (this.lock != null) {\n        // TODO(v3): remove legacy lock path\n        return await this._acquireLock(this.lockAcquireTimeout, async () =\u003e {\n          return await this._initialize()\n        })\n      }\n      return await this._initialize()\n    })()\n\n    const result = await this.initializePromise\n\n    // initializePromise is now resolved — flush queued notifications in order.\n    // Callbacks can safely call getSession() / getUser() / signOut() etc.\n    const queue = this._pendingInitNotifications ?? []\n    this._pendingInitNotifications = null\n    for (const n of queue) {\n      await this._notifyAllSubscribers(n.event, n.session, n.broadcast)\n    }\n\n    return result\n  }\n\n  /**\n   * IMPORTANT:\n   * 1. Never throw in this method, as it is called from the constructor\n   * 2. Never return a session from this method as it would be cached over\n   *    the whole lifetime of the client\n   */\n  private async _initialize(): Promise\u003cInitializeResult\u003e {\n    try {\n      let params: { [parameter: string]: string } = {}\n      let callbackUrlType = 'none'\n\n      if (isBrowser()) {\n        params = parseParametersFromURL(window.location.href)\n        if (this._isImplicitGrantCallback(params)) {\n          callbackUrlType = 'implicit'\n        } else if (await this._isPKCECallback(params)) {\n          callbackUrlType = 'pkce'\n        }\n      }\n\n      /**\n       * Attempt to get the session from the URL only if these conditions are fulfilled\n       *\n       * Note: If the URL isn't one of the callback url types (implicit or pkce),\n       * then there could be an existing session so we don't want to prematurely remove it\n       */\n      if (isBrowser() \u0026\u0026 this.detectSessionInUrl \u0026\u0026 callbackUrlType !== 'none') {\n        const { data, error } = await this._getSessionFromURL(params, callbackUrlType)\n        if (error) {\n          this._debug('#_initialize()', 'error detecting session from URL', error)\n\n          if (isAuthImplicitGrantRedirectError(error)) {\n            const errorCode = error.details?.code\n            if (\n              errorCode === 'identity_already_exists' ||\n              errorCode === 'identity_not_found' ||\n              errorCode === 'single_identity_not_deletable'\n            ) {\n              return { error }\n            }\n          }\n\n          // Don't remove existing session on URL login failure.\n          // A failed attempt (e.g. reused magic link) shouldn't invalidate a valid session.\n\n          return { error }\n        }\n\n        const { session, redirectType } = data\n\n        this._debug(\n          '#_initialize()',\n          'detected session in URL',\n          session,\n          'redirect type',\n          redirectType\n        )\n\n        await this._saveSession(session)\n\n        setTimeout(async () =\u003e {\n          if (redirectType === 'recovery') {\n            await this._notifyAllSubscribers('PASSWORD_RECOVERY', session)\n          } else {\n            await this._notifyAllSubscribers('SIGNED_IN', session)\n          }\n        }, 0)\n\n        return { error: null }\n      }\n      // no login attempt via callback url try to recover session from storage\n      await this._recoverAndRefresh()\n      return { error: null }\n    } catch (error) {\n      if (isAuthError(error)) {\n        return this._returnResult({ error })\n      }\n\n      return this._returnResult({\n        error: new AuthUnknownError('Unexpected error during initialization', error),\n      })\n    } finally {\n      await this._handleVisibilityChange()\n      this._debug('#_initialize()', 'end')\n    }\n  }\n\n  /**\n   * Creates a new anonymous user.\n   *\n   * @returns A session where the is_anonymous claim in the access token JWT set to true\n   *\n   * @category Auth\n   *\n   * @remarks\n   * - Returns an anonymous user\n   * - It is recommended to set up captcha for anonymous sign-ins to prevent abuse. You can pass in the captcha token in the `options` param.\n   *\n   * @example Create an anonymous user\n   * ```js\n   * const { data, error } = await supabase.auth.signInAnonymously({\n   *   options: {\n   *     captchaToken\n   *   }\n   * });\n   * ```\n   *\n   * @exampleResponse Create an anonymous user\n   * ```json\n   * {\n   *   \"data\": {\n   *     \"user\": {\n   *       \"id\": \"11111111-1111-1111-1111-111111111111\",\n   *       \"aud\": \"authenticated\",\n   *       \"role\": \"authenticated\",\n   *       \"email\": \"\",\n   *       \"phone\": \"\",\n   *       \"last_sign_in_at\": \"2024-01-01T00:00:00Z\",\n   *       \"app_metadata\": {},\n   *       \"user_metadata\": {},\n   *       \"identities\": [],\n   *       \"created_at\": \"2024-01-01T00:00:00Z\",\n   *       \"updated_at\": \"2024-01-01T00:00:00Z\",\n   *       \"is_anonymous\": true\n   *     },\n   *     \"session\": {\n   *       \"access_token\": \"\u003cACCESS_TOKEN\u003e\",\n   *       \"token_type\": \"bearer\",\n   *       \"expires_in\": 3600,\n   *       \"expires_at\": 1700000000,\n   *       \"refresh_token\": \"\u003cREFRESH_TOKEN\u003e\",\n   *       \"user\": {\n   *         \"id\": \"11111111-1111-1111-1111-111111111111\",\n   *         \"aud\": \"authenticated\",\n   *         \"role\": \"authenticated\",\n   *         \"email\": \"\",\n   *         \"phone\": \"\",\n   *         \"last_sign_in_at\": \"2024-01-01T00:00:00Z\",\n   *         \"app_metadata\": {},\n   *         \"user_metadata\": {},\n   *         \"identities\": [],\n   *         \"created_at\": \"2024-01-01T00:00:00Z\",\n   *         \"updated_at\": \"2024-01-01T00:00:00Z\",\n   *         \"is_anonymous\": true\n   *       }\n   *     }\n   *   },\n   *   \"error\": null\n   * }\n   * ```\n   *\n   * @example Create an anonymous user with custom user metadata\n   * ```js\n   * const { data, error } = await supabase.auth.signInAnonymously({\n   *   options: {\n   *     data\n   *   }\n   * })\n   * ```\n   */\n  async signInAnonymously(credentials?: SignInAnonymouslyCredentials): Promise\u003cAuthResponse\u003e {\n    try {\n      const res = await _request(this.fetch, 'POST', `${this.url}/signup`, {\n        headers: this.headers,\n        body: {\n          data: credentials?.options?.data ?? {},\n          gotrue_meta_security: { captcha_token: credentials?.options?.captchaToken },\n        },\n        xform: _sessionResponse,\n      })\n      const { data, error } = res\n\n      if (error || !data) {\n        return this._returnResult({ data: { user: null, session: null }, error: error })\n      }\n      const session: Session | null = data.session\n      const user: User | null = data.user\n\n      if (data.session) {\n        await this._saveSession(data.session)\n        await this._notifyAllSubscribers('SIGNED_IN', session)\n      }\n\n      return this._returnResult({ data: { user, session }, error: null })\n    } catch (error) {\n      if (isAuthError(error)) {\n        return this._returnResult({ data: { user: null, session: null }, error })\n      }\n\n      throw error\n    }\n  }\n\n  /**\n   * Creates a new user.\n   *\n   * Be aware that if a user account exists in the system you may get back an\n   * error message that attempts to hide this information from the user.\n   * This method has support for PKCE via email signups. The PKCE flow cannot be used when autoconfirm is enabled.\n   *\n   * @returns A logged-in session if the server has \"autoconfirm\" ON\n   * @returns A user if the server has \"autoconfirm\" OFF\n   *\n   * @category Auth\n   *\n   * @remarks\n   * - By default, the user needs to verify their email address before logging in. To turn this off, disable **Confirm email** in [your project](/dashboard/project/_/auth/providers).\n   * - **Confirm email** determines if users need to confirm their email address after signing up.\n   *   - If **Confirm email** is enabled, a `user` is returned but `session` is null.\n   *   - If **Confirm email** is disabled, both a `user` and a `session` are returned.\n   * - When the user confirms their email address, they are redirected to the [`SITE_URL`](/docs/guides/auth/redirect-urls#use-wildcards-in-redirect-urls) by default. You can modify your `SITE_URL` or add additional redirect URLs in [your project](/dashboard/project/_/auth/url-configuration).\n   * - If signUp() is called for an existing confirmed user:\n   *   - When both **Confirm email** and **Confirm phone** (even when phone provider is disabled) are enabled in [your project](/dashboard/project/_/auth/providers), an obfuscated/fake user object is returned.\n   *   - When either **Confirm email** or **Confirm phone** (even when phone provider is disabled) is disabled, the error message, `User already registered` is returned.\n   * - To fetch the currently logged-in user, refer to [`getUser()`](/docs/reference/javascript/auth-getuser).\n   *\n   * @example Sign up with an email and password\n   * ```js\n   * const { data, error } = await supabase.auth.signUp({\n   *   email: 'example@email.com',\n   *   password: 'example-password',\n   * })\n   * ```\n   *\n   * @exampleResponse Sign up with an email and password\n   * ```json\n   * // Some fields may be null if \"confirm email\" is enabled.\n   * {\n   *   \"data\": {\n   *     \"user\": {\n   *       \"id\": \"11111111-1111-1111-1111-111111111111\",\n   *       \"aud\": \"authenticated\",\n   *       \"role\": \"authenticated\",\n   *       \"email\": \"example@email.com\",\n   *       \"email_confirmed_at\": \"2024-01-01T00:00:00Z\",\n   *       \"phone\": \"\",\n   *       \"last_sign_in_at\": \"2024-01-01T00:00:00Z\",\n   *       \"app_metadata\": {\n   *         \"provider\": \"email\",\n   *         \"providers\": [\n   *           \"email\"\n   *         ]\n   *       },\n   *       \"user_metadata\": {},\n   *       \"identities\": [\n   *         {\n   *           \"identity_id\": \"22222222-2222-2222-2222-222222222222\",\n   *           \"id\": \"11111111-1111-1111-1111-111111111111\",\n   *           \"user_id\": \"11111111-1111-1111-1111-111111111111\",\n   *           \"identity_data\": {\n   *             \"email\": \"example@email.com\",\n   *             \"email_verified\": false,\n   *             \"phone_verified\": false,\n   *             \"sub\": \"11111111-1111-1111-1111-111111111111\"\n   *           },\n   *           \"provider\": \"email\",\n   *           \"last_sign_in_at\": \"2024-01-01T00:00:00Z\",\n   *           \"created_at\": \"2024-01-01T00:00:00Z\",\n   *           \"updated_at\": \"2024-01-01T00:00:00Z\",\n   *           \"email\": \"example@email.com\"\n   *         }\n   *       ],\n   *       \"created_at\": \"2024-01-01T00:00:00Z\",\n   *       \"updated_at\": \"2024-01-01T00:00:00Z\"\n   *     },\n   *     \"session\": {\n   *       \"access_token\": \"\u003cACCESS_TOKEN\u003e\",\n   *       \"token_type\": \"bearer\",\n   *       \"expires_in\": 3600,\n   *       \"expires_at\": 1700000000,\n   *       \"refresh_token\": \"\u003cREFRESH_TOKEN\u003e\",\n   *       \"user\": {\n   *         \"id\": \"11111111-1111-1111-1111-111111111111\",\n   *         \"aud\": \"authenticated\",\n   *         \"role\": \"authenticated\",\n   *         \"email\": \"example@email.com\",\n   *         \"email_confirmed_at\": \"2024-01-01T00:00:00Z\",\n   *         \"phone\": \"\",\n   *         \"last_sign_in_at\": \"2024-01-01T00:00:00Z\",\n   *         \"app_metadata\": {\n   *           \"provider\": \"email\",\n   *           \"providers\": [\n   *             \"email\"\n   *           ]\n   *         },\n   *         \"user_metadata\": {},\n   *         \"identities\": [\n   *           {\n   *             \"identity_id\": \"22222222-2222-2222-2222-222222222222\",\n   *             \"id\": \"11111111-1111-1111-1111-111111111111\",\n   *             \"user_id\": \"11111111-1111-1111-1111-111111111111\",\n   *             \"identity_data\": {\n   *               \"email\": \"example@email.com\",\n   *               \"email_verified\": false,\n   *               \"phone_verified\": false,\n   *               \"sub\": \"11111111-1111-1111-1111-111111111111\"\n   *             },\n   *             \"provider\": \"email\",\n   *             \"last_sign_in_at\": \"2024-01-01T00:00:00Z\",\n   *             \"created_at\": \"2024-01-01T00:00:00Z\",\n   *             \"updated_at\": \"2024-01-01T00:00:00Z\",\n   *             \"email\": \"example@email.com\"\n   *           }\n   *         ],\n   *         \"created_at\": \"2024-01-01T00:00:00Z\",\n   *         \"updated_at\": \"2024-01-01T00:00:00Z\"\n   *       }\n   *     }\n   *   },\n   *   \"error\": null\n   * }\n   * ```\n   *\n   * @example Sign up with a phone number and password (SMS)\n   * ```js\n   * const { data, error } = await supabase.auth.signUp({\n   *   phone: '123456789',\n   *   password: 'example-password',\n   *   options: {\n   *     channel: 'sms'\n   *   }\n   * })\n   * ```\n   *\n   * @exampleDescription Sign up with a phone number and password (whatsapp)\n   * The user will be sent a WhatsApp message which contains a OTP. By default, a given user can only request a OTP once every 60 seconds. Note that a user will need to have a valid WhatsApp account that is linked to Twilio in order to use this feature.\n   *\n   * @example Sign up with a phone number and password (whatsapp)\n   * ```js\n   * const { data, error } = await supabase.auth.signUp({\n   *   phone: '123456789',\n   *   password: 'example-password',\n   *   options: {\n   *     channel: 'whatsapp'\n   *   }\n   * })\n   * ```\n   *\n   * @example Sign up with additional user metadata\n   * ```js\n   * const { data, error } = await supabase.auth.signUp(\n   *   {\n   *     email: 'example@email.com',\n   *     password: 'example-password',\n   *     options: {\n   *       data: {\n   *         first_name: 'John',\n   *         age: 27,\n   *       }\n   *     }\n   *   }\n   * )\n   * ```\n   *\n   * @exampleDescription Sign up with a redirect URL\n   * - See [redirect URLs and wildcards](/docs/guides/auth/redirect-urls#use-wildcards-in-redirect-urls) to add additional redirect URLs to your project.\n   *\n   * @example Sign up with a redirect URL\n   * ```js\n   * const { data, error } = await supabase.auth.signUp(\n   *   {\n   *     email: 'example@email.com',\n   *     password: 'example-password',\n   *     options: {\n   *       emailRedirectTo: 'https://example.com/welcome'\n   *     }\n   *   }\n   * )\n   * ```\n   */\n  async signUp(credentials: SignUpWithPasswordCredentials): Promise\u003cAuthResponse\u003e {\n    let flowId: string | null = null\n    try {\n      let res: AuthResponse\n      if ('email' in credentials) {\n        const { email, password, options } = credentials\n        let codeChallenge: string | null = null\n        let codeChallengeMethod: string | null = null\n        if (this.flowType === 'pkce') {\n          ;[codeChallenge, codeChallengeMethod, flowId] = await this._getCodeChallengeAndMethod()\n        }\n        res = await _request(this.fetch, 'POST', `${this.url}/signup`, {\n          headers: this.headers,\n          redirectTo: this._maybeAppendFlowIdToRedirect(options?.emailRedirectTo, flowId),\n          body: {\n            email,\n            password,\n            data: options?.data ?? {},\n            gotrue_meta_security: { captcha_token: options?.captchaToken },\n            code_challenge: codeChallenge,\n            code_challenge_method: codeChallengeMethod,\n          },\n          xform: _sessionResponse,\n        })\n      } else if ('phone' in credentials) {\n        const { phone, password, options } = credentials\n        res = await _request(this.fetch, 'POST', `${this.url}/signup`, {\n          headers: this.headers,\n          body: {\n            phone,\n            password,\n            data: options?.data ?? {},\n            channel: options?.channel ?? 'sms',\n            gotrue_meta_security: { captcha_token: options?.captchaToken },\n          },\n          xform: _sessionResponse,\n        })\n      } else {\n        throw new AuthInvalidCredentialsError(\n          'You must provide either an email or phone number and a password'\n        )\n      }\n\n      const { data, error } = res\n\n      if (error || !data) {\n        await removePKCEVerifier(this.storage, this.storageKey, flowId)\n        return this._returnResult({ data: { user: null, session: null }, error: error })\n      }\n\n      const session: Session | null = data.session\n      const user: User | null = data.user\n\n      if (data.session) {\n        await this._saveSession(data.session)\n        await this._notifyAllSubscribers('SIGNED_IN', session)\n      }\n\n      return this._returnResult({ data: { user, session }, error: null })\n    } catch (error) {\n      await removePKCEVerifier(this.storage, this.storageKey, flowId)\n      if (isAuthError(error)) {\n        return this._returnResult({ data: { user: null, session: null }, error })\n      }\n\n      throw error\n    }\n  }\n\n  /**\n   * Log in an existing user with an email and password or phone and password.\n   *\n   * Be aware that you may get back an error message that will not distinguish\n   * between the cases where the account does not exist or that the\n   * email/phone and password combination is wrong or that the account can only\n   * be accessed via social sign-in.\n   *\n   * @category Auth\n   *\n   * @remarks\n   * - Requires either an email and password or a phone number and password.\n   *\n   * @example Sign in with email and password\n   * ```js\n   * const { data, error } = await supabase.auth.signInWithPassword({\n   *   email: 'example@email.com',\n   *   password: 'example-password',\n   * })\n   * ```\n   *\n   * @exampleResponse Sign in with email and password\n   * ```json\n   * {\n   *   \"data\": {\n   *     \"user\": {\n   *       \"id\": \"11111111-1111-1111-1111-111111111111\",\n   *       \"aud\": \"authenticated\",\n   *       \"role\": \"authenticated\",\n   *       \"email\": \"example@email.com\",\n   *       \"email_confirmed_at\": \"2024-01-01T00:00:00Z\",\n   *       \"phone\": \"\",\n   *       \"last_sign_in_at\": \"2024-01-01T00:00:00Z\",\n   *       \"app_metadata\": {\n   *         \"provider\": \"email\",\n   *         \"providers\": [\n   *           \"email\"\n   *         ]\n   *       },\n   *       \"user_metadata\": {},\n   *       \"identities\": [\n   *         {\n   *           \"identity_id\": \"22222222-2222-2222-2222-222222222222\",\n   *           \"id\": \"11111111-1111-1111-1111-111111111111\",\n   *           \"user_id\": \"11111111-1111-1111-1111-111111111111\",\n   *           \"identity_data\": {\n   *             \"email\": \"example@email.com\",\n   *             \"email_verified\": false,\n   *             \"phone_verified\": false,\n   *             \"sub\": \"11111111-1111-1111-1111-111111111111\"\n   *           },\n   *           \"provider\": \"email\",\n   *           \"last_sign_in_at\": \"2024-01-01T00:00:00Z\",\n   *           \"created_at\": \"2024-01-01T00:00:00Z\",\n   *           \"updated_at\": \"2024-01-01T00:00:00Z\",\n   *           \"email\": \"example@email.com\"\n   *         }\n   *       ],\n   *       \"created_at\": \"2024-01-01T00:00:00Z\",\n   *       \"updated_at\": \"2024-01-01T00:00:00Z\"\n   *     },\n   *     \"session\": {\n   *       \"access_token\": \"\u003cACCESS_TOKEN\u003e\",\n   *       \"token_type\": \"bearer\",\n   *       \"expires_in\": 3600,\n   *       \"expires_at\": 1700000000,\n   *       \"refresh_token\": \"\u003cREFRESH_TOKEN\u003e\",\n   *       \"user\": {\n   *         \"id\": \"11111111-1111-1111-1111-111111111111\",\n   *         \"aud\": \"authenticated\",\n   *         \"role\": \"authenticated\",\n   *         \"email\": \"example@email.com\",\n   *         \"email_confirmed_at\": \"2024-01-01T00:00:00Z\",\n   *         \"phone\": \"\",\n   *         \"last_sign_in_at\": \"2024-01-01T00:00:00Z\",\n   *         \"app_metadata\": {\n   *           \"provider\": \"email\",\n   *           \"providers\": [\n   *             \"email\"\n   *           ]\n   *         },\n   *         \"user_metadata\": {},\n   *         \"identities\": [\n   *           {\n   *             \"identity_id\": \"22222222-2222-2222-2222-222222222222\",\n   *             \"id\": \"11111111-1111-1111-1111-111111111111\",\n   *             \"user_id\": \"11111111-1111-1111-1111-111111111111\",\n   *             \"identity_data\": {\n   *               \"email\": \"example@email.com\",\n   *               \"email_verified\": false,\n   *               \"phone_verified\": false,\n   *               \"sub\": \"11111111-1111-1111-1111-111111111111\"\n   *             },\n   *             \"provider\": \"email\",\n   *             \"last_sign_in_at\": \"2024-01-01T00:00:00Z\",\n   *             \"created_at\": \"2024-01-01T00:00:00Z\",\n   *             \"updated_at\": \"2024-01-01T00:00:00Z\",\n   *             \"email\": \"example@email.com\"\n   *           }\n   *         ],\n   *         \"created_at\": \"2024-01-01T00:00:00Z\",\n   *         \"updated_at\": \"2024-01-01T00:00:00Z\"\n   *       }\n   *     }\n   *   },\n   *   \"error\": null\n   * }\n   * ```\n   *\n   * @example Sign in with phone and password\n   * ```js\n   * const { data, error } = await supabase.auth.signInWithPassword({\n   *   phone: '+13334445555',\n   *   password: 'some-password',\n   * })\n   * ```\n   *\n   * @exampleDescription Handling errors\n   * Log the full `error` object so fields like `code`, `status`, and `name` aren't hidden. The `error.code` (e.g. `'invalid_credentials'`, `'email_not_confirmed'`) is often more useful for branching than `error.message`, and the full object surfaces both.\n   *\n   * @example Handling errors\n   * ```js\n   * const { data, error } = await supabase.auth.signInWithPassword({\n   *   email: 'example@email.com',\n   *   password: 'example-password',\n   * })\n   * if (error) {\n   *   console.error(error)\n   *   return\n   * }\n   * ```\n   */\n  async signInWithPassword(\n    credentials: SignInWithPasswordCredentials\n  ): Promise\u003cAuthTokenResponsePassword\u003e {\n    try {\n      let res: AuthResponsePassword\n      if ('email' in credentials) {\n        const { email, password, options } = credentials\n        res = await _request(this.fetch, 'POST', `${this.url}/token?grant_type=password`, {\n          headers: this.headers,\n          body: {\n            email,\n            password,\n            gotrue_meta_security: { captcha_token: options?.captchaToken },\n          },\n          xform: _sessionResponsePassword,\n        })\n      } else if ('phone' in credentials) {\n        const { phone, password, options } = credentials\n        res = await _request(this.fetch, 'POST', `${this.url}/token?grant_type=password`, {\n          headers: this.headers,\n          body: {\n            phone,\n            password,\n            gotrue_meta_security: { captcha_token: options?.captchaToken },\n          },\n          xform: _sessionResponsePassword,\n        })\n      } else {\n        throw new AuthInvalidCredentialsError(\n          'You must provide either an email or phone number and a password'\n        )\n      }\n      const { data, error } = res\n\n      if (error) {\n        return this._returnResult({ data: { user: null, session: null }, error })\n      } else if (!data || !data.session || !data.user) {\n        const invalidTokenError = new AuthInvalidTokenResponseError()\n        return this._returnResult({ data: { user: null, session: null }, error: invalidTokenError })\n      }\n      if (data.session) {\n        await this._saveSession(data.session)\n        await this._notifyAllSubscribers('SIGNED_IN', data.session)\n      }\n      return this._returnResult({\n        data: {\n          user: data.user,\n          session: data.session,\n          ...(data.weak_password ? { weakPassword: data.weak_password } : null),\n        },\n        error,\n      })\n    } catch (error) {\n      if (isAuthError(error)) {\n        return this._returnResult({ data: { user: null, session: null }, error })\n      }\n      throw error\n    }\n  }\n\n  /**\n   * Log in an existing user via a third-party provider.\n   * This method supports the PKCE flow.\n   *\n   * @category Auth\n   *\n   * @remarks\n   * - This method is used for signing in using [social sign-in (OAuth) providers](/docs/guides/auth/social-sign-in).\n   * - It works by redirecting your application to the provider's authorization screen, before bringing back the user to your app.\n   *\n   * @example Sign in using a third-party provider\n   * ```js\n   * const { data, error } = await supabase.auth.signInWithOAuth({\n   *   provider: 'github'\n   * })\n   * ```\n   *\n   * @exampleResponse Sign in using a third-party provider\n   * ```json\n   * {\n   *   data: {\n   *     provider: 'github',\n   *     url: \u003cPROVIDER_URL_TO_REDIRECT_TO\u003e,\n   *     flowId: \u003cPKCE_FLOW_ID_OR_NULL\u003e\n   *   },\n   *   error: null\n   * }\n   * ```\n   *\n   * @exampleDescription Sign in using a third-party provider with redirect\n   * - When the OAuth provider successfully authenticates the user, they are redirected to the URL specified in the `redirectTo` parameter. This parameter defaults to the [`SITE_URL`](/docs/guides/auth/redirect-urls#use-wildcards-in-redirect-urls). It does not redirect the user immediately after invoking this method.\n   * - See [redirect URLs and wildcards](/docs/guides/auth/redirect-urls#use-wildcards-in-redirect-urls) to add additional redirect URLs to your project.\n   *\n   * @example Sign in using a third-party provider with redirect\n   * ```js\n   * const { data, error } = await supabase.auth.signInWithOAuth({\n   *   provider: 'github',\n   *   options: {\n   *     redirectTo: 'https://example.com/welcome'\n   *   }\n   * })\n   * ```\n   *\n   * @exampleDescription Sign in with scopes and access provider tokens\n   * If you need additional access from an OAuth provider, in order to access provider specific APIs in the name of the user, you can do this by passing in the scopes the user should authorize for your application. Note that the `scopes` option takes in **a space-separated list** of scopes.\n   *\n   * Because OAuth sign-in often includes redirects, you should register an `onAuthStateChange` callback immediately after you create the Supabase client. This callback will listen for the presence of `provider_token` and `provider_refresh_token` properties on the `session` object and store them in local storage. The client library will emit these values **only once** immediately after the user signs in. You can then access them by looking them up in local storage, or send them to your backend servers for further processing.\n   *\n   * Finally, make sure you remove them from local storage on the `SIGNED_OUT` event. If the OAuth provider supports token revocation, make sure you call those APIs either from the frontend or schedule them to be called on the backend.\n   *\n   * @example Sign in with scopes and access provider tokens\n   * ```js\n   * // Register this immediately after calling createClient!\n   * // Because signInWithOAuth causes a redirect, you need to fetch the\n   * // provider tokens from the callback.\n   * supabase.auth.onAuthStateChange((event, session) =\u003e {\n   *   if (session \u0026\u0026 session.provider_token) {\n   *     window.localStorage.setItem('oauth_provider_token', session.provider_token)\n   *   }\n   *\n   *   if (session \u0026\u0026 session.provider_refresh_token) {\n   *     window.localStorage.setItem('oauth_provider_refresh_token', session.provider_refresh_token)\n   *   }\n   *\n   *   if (event === 'SIGNED_OUT') {\n   *     window.localStorage.removeItem('oauth_provider_token')\n   *     window.localStorage.removeItem('oauth_provider_refresh_token')\n   *   }\n   * })\n   *\n   * // Call this on your Sign in with GitHub button to initiate OAuth\n   * // with GitHub with the requested elevated scopes.\n   * await supabase.auth.signInWithOAuth({\n   *   provider: 'github',\n   *   options: {\n   *     scopes: 'repo gist notifications'\n   *   }\n   * })\n   * ```\n   */\n  async signInWithOAuth(credentials: SignInWithOAuthCredentials): Promise\u003cOAuthResponse\u003e {\n    return await this._handleProviderSignIn(credentials.provider, {\n      redirectTo: credentials.options?.redirectTo,\n      scopes: credentials.options?.scopes,\n      queryParams: credentials.options?.queryParams,\n      skipBrowserRedirect: credentials.options?.skipBrowserRedirect,\n    })\n  }\n\n  /**\n   * Log in an existing user by exchanging an Auth Code issued during the PKCE flow.\n   *\n   * @category Auth\n   *\n   * @remarks\n   * - Used when `flowType` is set to `pkce` in client options.\n   * - When several PKCE flows are in flight at once, pass `options.flowId` so\n   *   the code is exchanged with the verifier created by that specific flow.\n   *   The flow id is returned by `signInWithOAuth`, and with\n   *   `experimental.appendPkceFlowIdToRedirects` enabled it also arrives on\n   *   your callback URL as the reserved `sb_flow_id` query parameter (read\n   *   automatically in a browser).\n   * - When a flow id is present but its stored verifier is gone (evicted,\n   *   already used, or from another device), the call fails with a verifier\n   *   missing error instead of trying another flow's verifier — a mismatched\n   *   verifier would consume the single-use code. Without any flow id the\n   *   most recently stored verifier is used, as before.\n   *\n   * @example Exchange Auth Code\n   * ```js\n   * supabase.auth.exchangeCodeForSession('34e770dd-9ff9-416c-87fa-43b31d7ef225')\n   * ```\n   *\n   * @example Exchange Auth Code for a specific flow (e.g. in a server-side callback handler)\n   * ```js\n   * const flowId = requestUrl.searchParams.get('sb_flow_id')\n   * supabase.auth.exchangeCodeForSession(code, flowId ? { flowId } : undefined)\n   * ```\n   *\n   * @exampleResponse Exchange Auth Code\n   * ```json\n   * {\n   *   \"data\": {\n   *     session: {\n   *       access_token: '\u003cACCESS_TOKEN\u003e',\n   *       token_type: 'bearer',\n   *       expires_in: 3600,\n   *       expires_at: 1700000000,\n   *       refresh_token: '\u003cREFRESH_TOKEN\u003e',\n   *       user: {\n   *         id: '11111111-1111-1111-1111-111111111111',\n   *         aud: 'authenticated',\n   *         role: 'authenticated',\n   *         email: 'example@email.com'\n   *         email_confirmed_at: '2024-01-01T00:00:00Z',\n   *         phone: '',\n   *         confirmation_sent_at: '2024-01-01T00:00:00Z',\n   *         confirmed_at: '2024-01-01T00:00:00Z',\n   *         last_sign_in_at: '2024-01-01T00:00:00Z',\n   *         app_metadata: {\n   *           \"provider\": \"email\",\n   *           \"providers\": [\n   *             \"email\",\n   *             \"\u003cOTHER_PROVIDER\u003e\"\n   *           ]\n   *         },\n   *         user_metadata: {\n   *           email: 'email@email.com',\n   *           email_verified: true,\n   *           full_name: 'User Name',\n   *           iss: '\u003cISS\u003e',\n   *           name: 'User Name',\n   *           phone_verified: false,\n   *           provider_id: '\u003cPROVIDER_ID\u003e',\n   *           sub: '\u003cSUB\u003e'\n   *         },\n   *         identities: [\n   *           {\n   *             \"identity_id\": \"22222222-2222-2222-2222-222222222222\",\n   *             \"id\": \"11111111-1111-1111-1111-111111111111\",\n   *             \"user_id\": \"11111111-1111-1111-1111-111111111111\",\n   *             \"identity_data\": {\n   *               \"email\": \"example@email.com\",\n   *               \"email_verified\": false,\n   *               \"phone_verified\": false,\n   *               \"sub\": \"11111111-1111-1111-1111-111111111111\"\n   *             },\n   *             \"provider\": \"email\",\n   *             \"last_sign_in_at\": \"2024-01-01T00:00:00Z\",\n   *             \"created_at\": \"2024-01-01T00:00:00Z\",\n   *             \"updated_at\": \"2024-01-01T00:00:00Z\",\n   *             \"email\": \"email@example.com\"\n   *           },\n   *           {\n   *             \"identity_id\": \"33333333-3333-3333-3333-333333333333\",\n   *             \"id\": \"\u003cID\u003e\",\n   *             \"user_id\": \"\u003cUSER_ID\u003e\",\n   *             \"identity_data\": {\n   *               \"email\": \"example@email.com\",\n   *               \"email_verified\": true,\n   *               \"full_name\": \"User Name\",\n   *               \"iss\": \"\u003cISS\u003e\",\n   *               \"name\": \"User Name\",\n   *               \"phone_verified\": false,\n   *               \"provider_id\": \"\u003cPROVIDER_ID\u003e\",\n   *               \"sub\": \"\u003cSUB\u003e\"\n   *             },\n   *             \"provider\": \"\u003cPROVIDER\u003e\",\n   *             \"last_sign_in_at\": \"2024-01-01T00:00:00Z\",\n   *             \"created_at\": \"2024-01-01T00:00:00Z\",\n   *             \"updated_at\": \"2024-01-01T00:00:00Z\",\n   *             \"email\": \"example@email.com\"\n   *           }\n   *         ],\n   *         created_at: '2024-01-01T00:00:00Z',\n   *         updated_at: '2024-01-01T00:00:00Z',\n   *         is_anonymous: false\n   *       },\n   *       provider_token: '\u003cPROVIDER_TOKEN\u003e',\n   *       provider_refresh_token: '\u003cPROVIDER_REFRESH_TOKEN\u003e'\n   *     },\n   *     user: {\n   *       id: '11111111-1111-1111-1111-111111111111',\n   *       aud: 'authenticated',\n   *       role: 'authenticated',\n   *       email: 'example@email.com',\n   *       email_confirmed_at: '2024-01-01T00:00:00Z',\n   *       phone: '',\n   *       confirmation_sent_at: '2024-01-01T00:00:00Z',\n   *       confirmed_at: '2024-01-01T00:00:00Z',\n   *       last_sign_in_at: '2024-01-01T00:00:00Z',\n   *       app_metadata: {\n   *         provider: 'email',\n   *         providers: [\n   *           \"email\",\n   *           \"\u003cOTHER_PROVIDER\u003e\"\n   *         ]\n   *       },\n   *       user_metadata: {\n   *         email: 'email@email.com',\n   *         email_verified: true,\n   *         full_name: 'User Name',\n   *         iss: '\u003cISS\u003e',\n   *         name: 'User Name',\n   *         phone_verified: false,\n   *         provider_id: '\u003cPROVIDER_ID\u003e',\n   *         sub: '\u003cSUB\u003e'\n   *       },\n   *       identities: [\n   *         {\n   *           \"identity_id\": \"22222222-2222-2222-2222-222222222222\",\n   *           \"id\": \"11111111-1111-1111-1111-111111111111\",\n   *           \"user_id\": \"11111111-1111-1111-1111-111111111111\",\n   *           \"identity_data\": {\n   *             \"email\": \"example@email.com\",\n   *             \"email_verified\": false,\n   *             \"phone_verified\": false,\n   *             \"sub\": \"11111111-1111-1111-1111-111111111111\"\n   *           },\n   *           \"provider\": \"email\",\n   *           \"last_sign_in_at\": \"2024-01-01T00:00:00Z\",\n   *           \"created_at\": \"2024-01-01T00:00:00Z\",\n   *           \"updated_at\": \"2024-01-01T00:00:00Z\",\n   *           \"email\": \"email@example.com\"\n   *         },\n   *         {\n   *           \"identity_id\": \"33333333-3333-3333-3333-333333333333\",\n   *           \"id\": \"\u003cID\u003e\",\n   *           \"user_id\": \"\u003cUSER_ID\u003e\",\n   *           \"identity_data\": {\n   *             \"email\": \"example@email.com\",\n   *             \"email_verified\": true,\n   *             \"full_name\": \"User Name\",\n   *             \"iss\": \"\u003cISS\u003e\",\n   *             \"name\": \"User Name\",\n   *             \"phone_verified\": false,\n   *             \"provider_id\": \"\u003cPROVIDER_ID\u003e\",\n   *             \"sub\": \"\u003cSUB\u003e\"\n   *           },\n   *           \"provider\": \"\u003cPROVIDER\u003e\",\n   *           \"last_sign_in_at\": \"2024-01-01T00:00:00Z\",\n   *           \"created_at\": \"2024-01-01T00:00:00Z\",\n   *           \"updated_at\": \"2024-01-01T00:00:00Z\",\n   *           \"email\": \"example@email.com\"\n   *         }\n   *       ],\n   *       created_at: '2024-01-01T00:00:00Z',\n   *       updated_at: '2024-01-01T00:00:00Z',\n   *       is_anonymous: false\n   *     },\n   *     redirectType: null\n   *   },\n   *   \"error\": null\n   * }\n   * ```\n   */\n  async exchangeCodeForSession(\n    authCode: string,\n    options?: { flowId?: string }\n  ): Promise\u003cAuthTokenResponse\u003e {\n    await this.initializePromise\n\n    if (this.lock != null) {\n      // TODO(v3): remove legacy lock path\n      return this._acquireLock(this.lockAcquireTimeout, async () =\u003e {\n        return this._exchangeCodeForSession(authCode, options)\n      })\n    }\n\n    return this._exchangeCodeForSession(authCode, options)\n  }\n\n  /**\n   * Signs in a user by verifying a message signed by the user's private key.\n   * Supports Ethereum (via Sign-In-With-Ethereum) \u0026 Solana (Sign-In-With-Solana) standards,\n   * both of which derive from the EIP-4361 standard\n   * With slight variation on Solana's side.\n   * @reference https://eips.ethereum.org/EIPS/eip-4361\n   *\n   * @category Auth\n   *\n   * @remarks\n   * - Uses a Web3 (Ethereum, Solana) wallet to sign a user in.\n   * - Read up on the [potential for abuse](/docs/guides/auth/auth-web3#potential-for-abuse) before using it.\n   *\n   * @example Sign in with Solana or Ethereum (Window API)\n   * ```js\n   *   // uses window.ethereum for the wallet\n   *   const { data, error } = await supabase.auth.signInWithWeb3({\n   *     chain: 'ethereum',\n   *     statement: 'I accept the Terms of Service at https://example.com/tos'\n   *   })\n   *\n   *   // uses window.solana for the wallet\n   *   const { data, error } = await supabase.auth.signInWithWeb3({\n   *     chain: 'solana',\n   *     statement: 'I accept the Terms of Service at https://example.com/tos'\n   *   })\n   * ```\n   *\n   * @example Sign in with Ethereum (Message and Signature)\n   * ```js\n   *   const { data, error } = await supabase.auth.signInWithWeb3({\n   *     chain: 'ethereum',\n   *     message: '\u003csign in with ethereum message\u003e',\n   *     signature: '\u003chex of the ethereum signature over the message\u003e',\n   *   })\n   * ```\n   *\n   * @example Sign in with Solana (Brave)\n   * ```js\n   *   const { data, error } = await supabase.auth.signInWithWeb3({\n   *     chain: 'solana',\n   *     statement: 'I accept the Terms of Service at https://example.com/tos',\n   *     wallet: window.braveSolana\n   *   })\n   * ```\n   *\n   * @example Sign in with Solana (Wallet Adapter)\n   * ```jsx\n   *   function SignInButton() {\n   *   const wallet = useWallet()\n   *\n   *   return (\n   *     \u003c\u003e\n   *       {wallet.connected ? (\n   *         \u003cbutton\n   *           onClick={() =\u003e {\n   *             supabase.auth.signInWithWeb3({\n   *               chain: 'solana',\n   *               statement: 'I accept the Terms of Service at https://example.com/tos',\n   *               wallet,\n   *             })\n   *           }}\n   *         \u003e\n   *           Sign in with Solana\n   *         \u003c/button\u003e\n   *       ) : (\n   *         \u003cWalletMultiButton /\u003e\n   *       )}\n   *     \u003c/\u003e\n   *   )\n   * }\n   *\n   * function App() {\n   *   const endpoint = clusterApiUrl('devnet')\n   *   const wallets = useMemo(() =\u003e [], [])\n   *\n   *   return (\n   *     \u003cConnectionProvider endpoint={endpoint}\u003e\n   *       \u003cWalletProvider wallets={wallets}\u003e\n   *         \u003cWalletModalProvider\u003e\n   *           \u003cSignInButton /\u003e\n   *         \u003c/WalletModalProvider\u003e\n   *       \u003c/WalletProvider\u003e\n   *     \u003c/ConnectionProvider\u003e\n   *   )\n   * }\n   * ```\n   */\n  async signInWithWeb3(credentials: Web3Credentials): Promise\u003c\n    | {\n        data: { session: Session; user: User }\n        error: null\n      }\n    | { data: { session: null; user: null }; error: AuthError }\n  \u003e {\n    const { chain } = credentials\n\n    switch (chain) {\n      case 'ethereum':\n        return await this.signInWithEthereum(credentials)\n      case 'solana':\n        return await this.signInWithSolana(credentials)\n      default:\n        throw new Error(`@supabase/auth-js: Unsupported chain \"${chain}\"`)\n    }\n  }\n\n  private async signInWithEthereum(\n    credentials: EthereumWeb3Credentials\n  ): Promise\u003c\n    | { data: { session: Session; user: User }; error: null }\n    | { data: { session: null; user: null }; error: AuthError }\n  \u003e {\n    // TODO: flatten type\n    let message: string\n    let signature: Hex\n\n    if ('message' in credentials) {\n      message = credentials.message\n      signature = credentials.signature\n    } else {\n      const { chain, wallet, statement, options } = credentials\n\n      let resolvedWallet: EthereumWallet\n\n      if (!isBrowser()) {\n        if (typeof wallet !== 'object' || !options?.url) {\n          throw new Error(\n            '@supabase/auth-js: Both wallet and url must be specified in non-browser environments.'\n          )\n        }\n\n        resolvedWallet = wallet\n      } else if (typeof wallet === 'object') {\n        resolvedWallet = wallet\n      } else {\n        const windowAny = window as any\n\n        if (\n          'ethereum' in windowAny \u0026\u0026\n          typeof windowAny.ethereum === 'object' \u0026\u0026\n          'request' in windowAny.ethereum \u0026\u0026\n          typeof windowAny.ethereum.request === 'function'\n        ) {\n          resolvedWallet = windowAny.ethereum\n        } else {\n          throw new Error(\n            `@supabase/auth-js: No compatible Ethereum wallet interface on the window object (window.ethereum) detected. Make sure the user already has a wallet installed and connected for this app. Prefer passing the wallet interface object directly to signInWithWeb3({ chain: 'ethereum', wallet: resolvedUserWallet }) instead.`\n          )\n        }\n      }\n\n      const url = new URL(options?.url ?? window.location.href)\n\n      const accounts = await resolvedWallet\n        .request({\n          method: 'eth_requestAccounts',\n        })\n        .then((accs) =\u003e accs as string[])\n        .catch(() =\u003e {\n          throw new Error(\n            `@supabase/auth-js: Wallet method eth_requestAccounts is missing or invalid`\n          )\n        })\n\n      if (!accounts || accounts.length === 0) {\n        throw new Error(\n          `@supabase/auth-js: No accounts available. Please ensure the wallet is connected.`\n        )\n      }\n\n      const address = getAddress(accounts[0])\n\n      let chainId = options?.signInWithEthereum?.chainId\n      if (!chainId) {\n        const chainIdHex = await resolvedWallet.request({\n          method: 'eth_chainId',\n        })\n        chainId = fromHex(chainIdHex as Hex)\n      }\n\n      const siweMessage: SiweMessage = {\n        domain: url.host,\n        address: address,\n        statement: statement,\n        uri: url.href,\n        version: '1',\n        chainId: chainId,\n        nonce: options?.signInWithEthereum?.nonce,\n        issuedAt: options?.signInWithEthereum?.issuedAt ?? new Date(),\n        expirationTime: options?.signInWithEthereum?.expirationTime,\n        notBefore: options?.signInWithEthereum?.notBefore,\n        requestId: options?.signInWithEthereum?.requestId,\n        resources: options?.signInWithEthereum?.resources,\n      }\n\n      message = createSiweMessage(siweMessage)\n\n      // Sign message\n      signature = (await resolvedWallet.request({\n        method: 'personal_sign',\n        params: [toHex(message), address],\n      })) as Hex\n    }\n\n    try {\n      const { data, error } = await _request(\n        this.fetch,\n        'POST',\n        `${this.url}/token?grant_type=web3`,\n        {\n          headers: this.headers,\n          body: {\n            chain: 'ethereum',\n            message,\n            signature,\n            ...(credentials.options?.captchaToken\n              ? { gotrue_meta_security: { captcha_token: credentials.options?.captchaToken } }\n              : null),\n          },\n          xform: _sessionResponse,\n        }\n      )\n      if (error) {\n        throw error\n      }\n      if (!data || !data.session || !data.user) {\n        const invalidTokenError = new AuthInvalidTokenResponseError()\n        return this._returnResult({ data: { user: null, session: null }, error: invalidTokenError })\n      }\n      if (data.session) {\n        await this._saveSession(data.session)\n        await this._notifyAllSubscribers('SIGNED_IN', data.session)\n      }\n      return this._returnResult({ data: { ...data }, error })\n    } catch (error) {\n      if (isAuthError(error)) {\n        return this._returnResult({ data: { user: null, session: null }, error })\n      }\n\n      throw error\n    }\n  }\n\n  private async signInWithSolana(credentials: SolanaWeb3Credentials) {\n    let message: string\n    let signature: Uint8Array\n\n    if ('message' in credentials) {\n      message = credentials.message\n      signature = credentials.signature\n    } else {\n      const { chain, wallet, statement, options } = credentials\n\n      let resolvedWallet: SolanaWallet\n\n      if (!isBrowser()) {\n        if (typeof wallet !== 'object' || !options?.url) {\n          throw new Error(\n            '@supabase/auth-js: Both wallet and url must be specified in non-browser environments.'\n          )\n        }\n\n        resolvedWallet = wallet\n      } else if (typeof wallet === 'object') {\n        resolvedWallet = wallet\n      } else {\n        const windowAny = window as any\n\n        if (\n          'solana' in windowAny \u0026\u0026\n          typeof windowAny.solana === 'object' \u0026\u0026\n          (('signIn' in windowAny.solana \u0026\u0026 typeof windowAny.solana.signIn === 'function') ||\n            ('signMessage' in windowAny.solana \u0026\u0026\n              typeof windowAny.solana.signMessage === 'function'))\n        ) {\n          resolvedWallet = windowAny.solana\n        } else {\n          throw new Error(\n            `@supabase/auth-js: No compatible Solana wallet interface on the window object (window.solana) detected. Make sure the user already has a wallet installed and connected for this app. Prefer passing the wallet interface object directly to signInWithWeb3({ chain: 'solana', wallet: resolvedUserWallet }) instead.`\n          )\n        }\n      }\n\n      const url = new URL(options?.url ?? window.location.href)\n\n      if ('signIn' in resolvedWallet \u0026\u0026 resolvedWallet.signIn) {\n        const output = await resolvedWallet.signIn({\n          issuedAt: new Date().toISOString(),\n\n          ...options?.signInWithSolana,\n\n          // non-overridable properties\n          version: '1',\n          domain: url.host,\n          uri: url.href,\n\n          ...(statement ? { statement } : null),\n        })\n\n        let outputToProcess: any\n\n        if (Array.isArray(output) \u0026\u0026 output[0] \u0026\u0026 typeof output[0] === 'object') {\n          outputToProcess = output[0]\n        } else if (\n          output \u0026\u0026\n          typeof output === 'object' \u0026\u0026\n          'signedMessage' in output \u0026\u0026\n          'signature' in output\n        ) {\n          outputToProcess = output\n        } else {\n          throw new Error('@supabase/auth-js: Wallet method signIn() returned unrecognized value')\n        }\n\n        if (\n          'signedMessage' in outputToProcess \u0026\u0026\n          'signature' in outputToProcess \u0026\u0026\n          (typeof outputToProcess.signedMessage === 'string' ||\n            outputToProcess.signedMessage instanceof Uint8Array) \u0026\u0026\n          outputToProcess.signature instanceof Uint8Array\n        ) {\n          message =\n            typeof outputToProcess.signedMessage === 'string'\n              ? outputToProcess.signedMessage\n              : new TextDecoder().decode(outputToProcess.signedMessage)\n          signature = outputToProcess.signature\n        } else {\n          throw new Error(\n            '@supabase/auth-js: Wallet method signIn() API returned object without signedMessage and signature fields'\n          )\n        }\n      } else {\n        if (\n          !('signMessage' in resolvedWallet) ||\n          typeof resolvedWallet.signMessage !== 'function' ||\n          !('publicKey' in resolvedWallet) ||\n          typeof resolvedWallet !== 'object' ||\n          !resolvedWallet.publicKey ||\n          !('toBase58' in resolvedWallet.publicKey) ||\n          typeof resolvedWallet.publicKey.toBase58 !== 'function'\n        ) {\n          throw new Error(\n            '@supabase/auth-js: Wallet does not have a compatible signMessage() and publicKey.toBase58() API'\n          )\n        }\n\n        message = [\n          `${url.host} wants you to sign in with your Solana account:`,\n          resolvedWallet.publicKey.toBase58(),\n          ...(statement ? ['', statement, ''] : ['']),\n          'Version: 1',\n          `URI: ${url.href}`,\n          `Issued At: ${options?.signInWithSolana?.issuedAt ?? new Date().toISOString()}`,\n          ...(options?.signInWithSolana?.notBefore\n            ? [`Not Before: ${options.signInWithSolana.notBefore}`]\n            : []),\n          ...(options?.signInWithSolana?.expirationTime\n            ? [`Expiration Time: ${options.signInWithSolana.expirationTime}`]\n            : []),\n          ...(options?.signInWithSolana?.chainId\n            ? [`Chain ID: ${options.signInWithSolana.chainId}`]\n            : []),\n          ...(options?.signInWithSolana?.nonce ? [`Nonce: ${options.signInWithSolana.nonce}`] : []),\n          ...(options?.signInWithSolana?.requestId\n            ? [`Request ID: ${options.signInWithSolana.requestId}`]\n            : []),\n          ...(options?.signInWithSolana?.resources?.length\n            ? [\n                'Resources',\n                ...options.signInWithSolana.resources.map((resource) =\u003e `- ${resource}`),\n              ]\n            : []),\n        ].join('\\n')\n\n        const maybeSignature = await resolvedWallet.signMessage(\n          new TextEncoder().encode(message),\n          'utf8'\n        )\n\n        if (!maybeSignature || !(maybeSignature instanceof Uint8Array)) {\n          throw new Error(\n            '@supabase/auth-js: Wallet signMessage() API returned an recognized value'\n          )\n        }\n\n        signature = maybeSignature\n      }\n    }\n\n    try {\n      const { data, error } = await _request(\n        this.fetch,\n        'POST',\n        `${this.url}/token?grant_type=web3`,\n        {\n          headers: this.headers,\n          body: {\n            chain: 'solana',\n            message,\n            signature: bytesToBase64URL(signature),\n\n            ...(credentials.options?.captchaToken\n              ? { gotrue_meta_security: { captcha_token: credentials.options?.captchaToken } }\n              : null),\n          },\n          xform: _sessionResponse,\n        }\n      )\n      if (error) {\n        throw error\n      }\n      if (!data || !data.session || !data.user) {\n        const invalidTokenError = new AuthInvalidTokenResponseError()\n        return this._returnResult({ data: { user: null, session: null }, error: invalidTokenError })\n      }\n      if (data.session) {\n        await this._saveSession(data.session)\n        await this._notifyAllSubscribers('SIGNED_IN', data.session)\n      }\n      return this._returnResult({ data: { ...data }, error })\n    } catch (error) {\n      if (isAuthError(error)) {\n        return this._returnResult({ data: { user: null, session: null }, error })\n      }\n\n      throw error\n    }\n  }\n\n  private async _exchangeCodeForSession(\n    authCode: string,\n    options?: { flowId?: string }\n  ): Promise\u003c\n    | {\n        data: { session: Session; user: User; redirectType: string | null }\n        error: null\n      }\n    | { data: { session: null; user: null; redirectType: null }; error: AuthError }\n  \u003e {\n    const hasExplicitFlowId = options?.flowId != null\n    const requestedFlowId = hasExplicitFlowId\n      ? validatePKCEFlowId(options?.flowId)\n      : isBrowser()\n        ? validatePKCEFlowId(parseParametersFromURL(window.location.href)[PKCE_FLOW_ID_PARAM])\n        : null\n\n    if (hasExplicitFlowId \u0026\u0026 !requestedFlowId) {\n      this._debug(\n        '#_exchangeCodeForSession()',\n        'provided flowId is not a valid flow id',\n        options?.flowId\n      )\n    }\n\n    // With a flow id (explicit or from the callback URL) the lookup is\n    // slot-only and a miss fails fast — see retrievePKCEVerifier. An invalid\n    // explicit flow id also fails fast rather than borrowing another flow's\n    // verifier.\n    const { verifier: storageItem, flowId } =\n      hasExplicitFlowId \u0026\u0026 !requestedFlowId\n        ? { verifier: null, flowId: null }\n        : await retrievePKCEVerifier(this.storage, this.storageKey, requestedFlowId)\n    const [codeVerifier, redirectType] = (storageItem ?? '').split('/')\n\n    try {\n      if (!codeVerifier \u0026\u0026 this.flowType === 'pkce') {\n        throw new AuthPKCECodeVerifierMissingError()\n      }\n\n      const { data, error } = await _request(\n        this.fetch,\n        'POST',\n        `${this.url}/token?grant_type=pkce`,\n        {\n          headers: this.headers,\n          body: {\n            auth_code: authCode,\n            code_verifier: codeVerifier,\n          },\n          xform: _sessionResponse,\n        }\n      )\n      await removePKCEVerifier(this.storage, this.storageKey, flowId)\n      if (error) {\n        throw error\n      }\n      if (!data || !data.session || !data.user) {\n        const invalidTokenError = new AuthInvalidTokenResponseError()\n        return this._returnResult({\n          data: { user: null, session: null, redirectType: null },\n          error: invalidTokenError,\n        })\n      }\n      if (data.session) {\n        await this._saveSession(data.session)\n        await this._notifyAllSubscribers(\n          redirectType === 'recovery' ? 'PASSWORD_RECOVERY' : 'SIGNED_IN',\n          data.session\n        )\n      }\n      return this._returnResult({ data: { ...data, redirectType: redirectType ?? null }, error })\n    } catch (error) {\n      await removePKCEVerifier(this.storage, this.storageKey, flowId)\n      if (isAuthError(error)) {\n        return this._returnResult({\n          data: { user: null, session: null, redirectType: null },\n          error,\n        })\n      }\n      throw error\n    }\n  }\n\n  /**\n   * Allows signing in with an OIDC ID token. The authentication provider used\n   * should be enabled and configured.\n   *\n   * @category Auth\n   *\n   * @remarks\n   * - Use an ID token to sign in.\n   * - Especially useful when implementing sign in using native platform dialogs in mobile or desktop apps using Sign in with Apple or Sign in with Google on iOS and Android.\n   * - You can also use Google's [One Tap](https://developers.google.com/identity/gsi/web/guides/display-google-one-tap) and [Automatic sign-in](https://developers.google.com/identity/gsi/web/guides/automatic-sign-in-sign-out) via this API.\n   *\n   * @example Sign In using ID Token\n   * ```js\n   * const { data, error } = await supabase.auth.signInWithIdToken({\n   *   provider: 'google',\n   *   token: 'your-id-token'\n   * })\n   * ```\n   *\n   * @exampleResponse Sign In using ID Token\n   * ```json\n   * {\n   *   \"data\": {\n   *     \"user\": {\n   *       \"id\": \"11111111-1111-1111-1111-111111111111\",\n   *       \"aud\": \"authenticated\",\n   *       \"role\": \"authenticated\",\n   *       \"last_sign_in_at\": \"2024-01-01T00:00:00Z\",\n   *       \"app_metadata\": {\n   *         ...\n   *       },\n   *       \"user_metadata\": {\n   *         ...\n   *       },\n   *       \"identities\": [\n   *         {\n   *           \"identity_id\": \"22222222-2222-2222-2222-222222222222\",\n   *           \"provider\": \"google\",\n   *         }\n   *       ],\n   *       \"created_at\": \"2024-01-01T00:00:00Z\",\n   *       \"updated_at\": \"2024-01-01T00:00:00Z\",\n   *     },\n   *     \"session\": {\n   *       \"access_token\": \"\u003cACCESS_TOKEN\u003e\",\n   *       \"token_type\": \"bearer\",\n   *       \"expires_in\": 3600,\n   *       \"expires_at\": 1700000000,\n   *       \"refresh_token\": \"\u003cREFRESH_TOKEN\u003e\",\n   *       \"user\": {\n   *         \"id\": \"11111111-1111-1111-1111-111111111111\",\n   *         \"aud\": \"authenticated\",\n   *         \"role\": \"authenticated\",\n   *         \"last_sign_in_at\": \"2024-01-01T00:00:00Z\",\n   *         \"app_metadata\": {\n   *           ...\n   *         },\n   *         \"user_metadata\": {\n   *           ...\n   *         },\n   *         \"identities\": [\n   *           {\n   *             \"identity_id\": \"22222222-2222-2222-2222-222222222222\",\n   *             \"provider\": \"google\",\n   *           }\n   *         ],\n   *         \"created_at\": \"2024-01-01T00:00:00Z\",\n   *         \"updated_at\": \"2024-01-01T00:00:00Z\",\n   *       }\n   *     }\n   *   },\n   *   \"error\": null\n   * }\n   * ```\n   */\n  async signInWithIdToken(credentials: SignInWithIdTokenCredentials): Promise\u003cAuthTokenResponse\u003e {\n    try {\n      const { options, provider, token, access_token, nonce } = credentials\n\n      const res = await _request(this.fetch, 'POST', `${this.url}/token?grant_type=id_token`, {\n        headers: this.headers,\n        body: {\n          provider,\n          id_token: token,\n          access_token,\n          nonce,\n          gotrue_meta_security: { captcha_token: options?.captchaToken },\n        },\n        xform: _sessionResponse,\n      })\n\n      const { data, error } = res\n      if (error) {\n        return this._returnResult({ data: { user: null, session: null }, error })\n      } else if (!data || !data.session || !data.user) {\n        const invalidTokenError = new AuthInvalidTokenResponseError()\n        return this._returnResult({ data: { user: null, session: null }, error: invalidTokenError })\n      }\n      if (data.session) {\n        await this._saveSession(data.session)\n        await this._notifyAllSubscribers('SIGNED_IN', data.session)\n      }\n      return this._returnResult({ data, error })\n    } catch (error) {\n      if (isAuthError(error)) {\n        return this._returnResult({ data: { user: null, session: null }, error })\n      }\n      throw error\n    }\n  }\n\n  /**\n   * Log in a user using magiclink or a one-time password (OTP).\n   *\n   * If the `{{ .ConfirmationURL }}` variable is specified in the email template, a magiclink will be sent.\n   * If the `{{ .Token }}` variable is specified in the email template, an OTP will be sent.\n   * If you're using phone sign-ins, only an OTP will be sent. You won't be able to send a magiclink for phone sign-ins.\n   *\n   * Be aware that you may get back an error message that will not distinguish\n   * between the cases where the account does not exist or, that the account\n   * can only be accessed via social sign-in.\n   *\n   * Do note that you will need to configure a Whatsapp sender on Twilio\n   * if you are using phone sign in with the 'whatsapp' channel. The whatsapp\n   * channel is not supported on other providers\n   * at this time.\n   * This method supports PKCE when an email is passed.\n   *\n   * @category Auth\n   *\n   * @remarks\n   * - Requires either an email or phone number.\n   * - This method is used for passwordless sign-ins where a OTP is sent to the user's email or phone number.\n   * - If the user doesn't exist, `signInWithOtp()` will signup the user instead. To restrict this behavior, you can set `shouldCreateUser` in `SignInWithPasswordlessCredentials.options` to `false`.\n   * - If you're using an email, you can configure whether you want the user to receive a magiclink or a OTP.\n   * - If you're using phone, you can configure whether you want the user to receive a OTP.\n   * - The magic link's destination URL is determined by the [`SITE_URL`](/docs/guides/auth/redirect-urls#use-wildcards-in-redirect-urls).\n   * - See [redirect URLs and wildcards](/docs/guides/auth/redirect-urls#use-wildcards-in-redirect-urls) to add additional redirect URLs to your project.\n   * - Magic links and OTPs share the same implementation. To send users a one-time code instead of a magic link, [modify the magic link email template](/dashboard/project/_/auth/templates) to include `{{ .Token }}` instead of `{{ .ConfirmationURL }}`.\n   * - See our [Twilio Phone Auth Guide](/docs/guides/auth/phone-login?showSMSProvider=Twilio) for details about configuring WhatsApp sign in.\n   *\n   * @exampleDescription Sign in with email\n   * The user will be sent an email which contains either a magiclink or a OTP or both. By default, a given user can only request a OTP once every 60 seconds.\n   *\n   * @example Sign in with email\n   * ```js\n   * const { data, error } = await supabase.auth.signInWithOtp({\n   *   email: 'example@email.com',\n   *   options: {\n   *     emailRedirectTo: 'https://example.com/welcome'\n   *   }\n   * })\n   * ```\n   *\n   * @exampleResponse Sign in with email\n   * ```json\n   * {\n   *   \"data\": {\n   *     \"user\": null,\n   *     \"session\": null\n   *   },\n   *   \"error\": null\n   * }\n   * ```\n   *\n   * @exampleDescription Sign in with SMS OTP\n   * The user will be sent a SMS which contains a OTP. By default, a given user can only request a OTP once every 60 seconds.\n   *\n   * @example Sign in with SMS OTP\n   * ```js\n   * const { data, error } = await supabase.auth.signInWithOtp({\n   *   phone: '+13334445555',\n   * })\n   * ```\n   *\n   * @exampleDescription Sign in with WhatsApp OTP\n   * The user will be sent a WhatsApp message which contains a OTP. By default, a given user can only request a OTP once every 60 seconds. Note that a user will need to have a valid WhatsApp account that is linked to Twilio in order to use this feature.\n   *\n   * @example Sign in with WhatsApp OTP\n   * ```js\n   * const { data, error } = await supabase.auth.signInWithOtp({\n   *   phone: '+13334445555',\n   *   options: {\n   *     channel:'whatsapp',\n   *   }\n   * })\n   * ```\n   */\n  async signInWithOtp(credentials: SignInWithPasswordlessCredentials): Promise\u003cAuthOtpResponse\u003e {\n    let flowId: string | null = null\n    try {\n      if ('email' in credentials) {\n        const { email, options } = credentials\n        let codeChallenge: string | null = null\n        let codeChallengeMethod: string | null = null\n        if (this.flowType === 'pkce') {\n          ;[codeChallenge, codeChallengeMethod, flowId] = await this._getCodeChallengeAndMethod()\n        }\n        const { error } = await _request(this.fetch, 'POST', `${this.url}/otp`, {\n          headers: this.headers,\n          body: {\n            email,\n            data: options?.data ?? {},\n            create_user: options?.shouldCreateUser ?? true,\n            gotrue_meta_security: { captcha_token: options?.captchaToken },\n            code_challenge: codeChallenge,\n            code_challenge_method: codeChallengeMethod,\n          },\n          redirectTo: this._maybeAppendFlowIdToRedirect(options?.emailRedirectTo, flowId),\n        })\n        return this._returnResult({ data: { user: null, session: null }, error })\n      }\n      if ('phone' in credentials) {\n        const { phone, options } = credentials\n        const { data, error } = await _request(this.fetch, 'POST', `${this.url}/otp`, {\n          headers: this.headers,\n          body: {\n            phone,\n            data: options?.data ?? {},\n            create_user: options?.shouldCreateUser ?? true,\n            gotrue_meta_security: { captcha_token: options?.captchaToken },\n            channel: options?.channel ?? 'sms',\n          },\n        })\n        return this._returnResult({\n          data: { user: null, session: null, messageId: data?.message_id },\n          error,\n        })\n      }\n      throw new AuthInvalidCredentialsError('You must provide either an email or phone number.')\n    } catch (error) {\n      await removePKCEVerifier(this.storage, this.storageKey, flowId)\n      if (isAuthError(error)) {\n        return this._returnResult({ data: { user: null, session: null }, error })\n      }\n\n      throw error\n    }\n  }\n\n  /**\n   * Log in a user given a User supplied OTP or TokenHash received through mobile or email.\n   *\n   * @category Auth\n   *\n   * @remarks\n   * - The `verifyOtp` method takes in different verification types.\n   * - If a phone number is used, the type can either be:\n   *   1. `sms` – Used when verifying a one-time password (OTP) sent via SMS during sign-up or sign-in.\n   *   2. `phone_change` – Used when verifying an OTP sent to a new phone number during a phone number update process.\n   * - If an email address is used, the type can be one of the following (note: `signup` and `magiclink` types are deprecated):\n   *   1. `email` – Used when verifying an OTP sent to the user's email during sign-up or sign-in.\n   *   2. `recovery` – Used when verifying an OTP sent for account recovery, typically after a password reset request.\n   *   3. `invite` – Used when verifying an OTP sent as part of an invitation to join a project or organization.\n   *   4. `email_change` – Used when verifying an OTP sent to a new email address during an email update process.\n   * - The verification type used should be determined based on the corresponding auth method called before `verifyOtp` to sign up / sign-in a user.\n   * - The `TokenHash` is contained in the [email templates](/docs/guides/auth/auth-email-templates) and can be used to sign in.  You may wish to use the hash for the PKCE flow for Server Side Auth. Read [the Password-based Auth guide](/docs/guides/auth/passwords) for more details.\n   *\n   * @example Verify Signup One-Time Password (OTP)\n   * ```js\n   * const { data, error } = await supabase.auth.verifyOtp({ email, token, type: 'email'})\n   * ```\n   *\n   * @exampleResponse Verify Signup One-Time Password (OTP)\n   * ```json\n   * {\n   *   \"data\": {\n   *     \"user\": {\n   *       \"id\": \"11111111-1111-1111-1111-111111111111\",\n   *       \"aud\": \"authenticated\",\n   *       \"role\": \"authenticated\",\n   *       \"email\": \"example@email.com\",\n   *       \"email_confirmed_at\": \"2024-01-01T00:00:00Z\",\n   *       \"phone\": \"\",\n   *       \"confirmed_at\": \"2024-01-01T00:00:00Z\",\n   *       \"recovery_sent_at\": \"2024-01-01T00:00:00Z\",\n   *       \"last_sign_in_at\": \"2024-01-01T00:00:00Z\",\n   *       \"app_metadata\": {\n   *         \"provider\": \"email\",\n   *         \"providers\": [\n   *           \"email\"\n   *         ]\n   *       },\n   *       \"user_metadata\": {\n   *         \"email\": \"example@email.com\",\n   *         \"email_verified\": false,\n   *         \"phone_verified\": false,\n   *         \"sub\": \"11111111-1111-1111-1111-111111111111\"\n   *       },\n   *       \"identities\": [\n   *         {\n   *           \"identity_id\": \"22222222-2222-2222-2222-222222222222\",\n   *           \"id\": \"11111111-1111-1111-1111-111111111111\",\n   *           \"user_id\": \"11111111-1111-1111-1111-111111111111\",\n   *           \"identity_data\": {\n   *             \"email\": \"example@email.com\",\n   *             \"email_verified\": false,\n   *             \"phone_verified\": false,\n   *             \"sub\": \"11111111-1111-1111-1111-111111111111\"\n   *           },\n   *           \"provider\": \"email\",\n   *           \"last_sign_in_at\": \"2024-01-01T00:00:00Z\",\n   *           \"created_at\": \"2024-01-01T00:00:00Z\",\n   *           \"updated_at\": \"2024-01-01T00:00:00Z\",\n   *           \"email\": \"example@email.com\"\n   *         }\n   *       ],\n   *       \"created_at\": \"2024-01-01T00:00:00Z\",\n   *       \"updated_at\": \"2024-01-01T00:00:00Z\",\n   *       \"is_anonymous\": false\n   *     },\n   *     \"session\": {\n   *       \"access_token\": \"\u003cACCESS_TOKEN\u003e\",\n   *       \"token_type\": \"bearer\",\n   *       \"expires_in\": 3600,\n   *       \"expires_at\": 1700000000,\n   *       \"refresh_token\": \"\u003cREFRESH_TOKEN\u003e\",\n   *       \"user\": {\n   *         \"id\": \"11111111-1111-1111-1111-111111111111\",\n   *         \"aud\": \"authenticated\",\n   *         \"role\": \"authenticated\",\n   *         \"email\": \"example@email.com\",\n   *         \"email_confirmed_at\": \"2024-01-01T00:00:00Z\",\n   *         \"phone\": \"\",\n   *         \"confirmed_at\": \"2024-01-01T00:00:00Z\",\n   *         \"recovery_sent_at\": \"2024-01-01T00:00:00Z\",\n   *         \"last_sign_in_at\": \"2024-01-01T00:00:00Z\",\n   *         \"app_metadata\": {\n   *           \"provider\": \"email\",\n   *           \"providers\": [\n   *             \"email\"\n   *           ]\n   *         },\n   *         \"user_metadata\": {\n   *           \"email\": \"example@email.com\",\n   *           \"email_verified\": false,\n   *           \"phone_verified\": false,\n   *           \"sub\": \"11111111-1111-1111-1111-111111111111\"\n   *         },\n   *         \"identities\": [\n   *           {\n   *             \"identity_id\": \"22222222-2222-2222-2222-222222222222\",\n   *             \"id\": \"11111111-1111-1111-1111-111111111111\",\n   *             \"user_id\": \"11111111-1111-1111-1111-111111111111\",\n   *             \"identity_data\": {\n   *               \"email\": \"example@email.com\",\n   *               \"email_verified\": false,\n   *               \"phone_verified\": false,\n   *               \"sub\": \"11111111-1111-1111-1111-111111111111\"\n   *             },\n   *             \"provider\": \"email\",\n   *             \"last_sign_in_at\": \"2024-01-01T00:00:00Z\",\n   *             \"created_at\": \"2024-01-01T00:00:00Z\",\n   *             \"updated_at\": \"2024-01-01T00:00:00Z\",\n   *             \"email\": \"example@email.com\"\n   *           }\n   *         ],\n   *         \"created_at\": \"2024-01-01T00:00:00Z\",\n   *         \"updated_at\": \"2024-01-01T00:00:00Z\",\n   *         \"is_anonymous\": false\n   *       }\n   *     }\n   *   },\n   *   \"error\": null\n   * }\n   * ```\n   *\n   * @example Verify SMS One-Time Password (OTP)\n   * ```js\n   * const { data, error } = await supabase.auth.verifyOtp({ phone, token, type: 'sms'})\n   * ```\n   *\n   * @example Verify Email Auth (Token Hash)\n   * ```js\n   * const { data, error } = await supabase.auth.verifyOtp({ token_hash: tokenHash, type: 'email'})\n   * ```\n   */\n  async verifyOtp(params: VerifyOtpParams): Promise\u003cAuthResponse\u003e {\n    try {\n      let redirectTo: string | undefined = undefined\n      let captchaToken: string | undefined = undefined\n      if ('options' in params) {\n        redirectTo = params.options?.redirectTo\n        captchaToken = params.options?.captchaToken\n      }\n      const { data, error } = await _request(this.fetch, 'POST', `${this.url}/verify`, {\n        headers: this.headers,\n        body: {\n          ...params,\n          gotrue_meta_security: { captcha_token: captchaToken },\n        },\n        redirectTo,\n        xform: _sessionResponse,\n      })\n\n      if (error) {\n        throw error\n      }\n      if (!data) {\n        const tokenVerificationError = new Error('An error occurred on token verification.')\n        throw tokenVerificationError\n      }\n\n      const session: Session | null = data.session\n      const user: User | null = data.user\n\n      if (session?.access_token) {\n        await this._saveSession(session as Session)\n        await this._notifyAllSubscribers(\n          params.type == 'recovery' ? 'PASSWORD_RECOVERY' : 'SIGNED_IN',\n          session\n        )\n      }\n\n      return this._returnResult({ data: { user, session }, error: null })\n    } catch (error) {\n      if (isAuthError(error)) {\n        return this._returnResult({ data: { user: null, session: null }, error })\n      }\n\n      throw error\n    }\n  }\n\n  /**\n   * Attempts a single-sign on using an enterprise Identity Provider. A\n   * successful SSO attempt will redirect the current page to the identity\n   * provider authorization page. The redirect URL is implementation and SSO\n   * protocol specific.\n   *\n   * You can use it by providing a SSO domain. Typically you can extract this\n   * domain by asking users for their email address. If this domain is\n   * registered on the Auth instance the redirect will use that organization's\n   * currently active SSO Identity Provider for the login.\n   *\n   * If you have built an organization-specific login page, you can use the\n   * organization's SSO Identity Provider UUID directly instead.\n   *\n   * @category Auth\n   *\n   * @remarks\n   * - Before you can call this method you need to [establish a connection](/docs/guides/auth/sso/auth-sso-saml#managing-saml-20-connections) to an identity provider. Use the [CLI commands](/docs/reference/cli/supabase-sso) to do this.\n   * - If you've associated an email domain to the identity provider, you can use the `domain` property to start a sign-in flow.\n   * - In case you need to use a different way to start the authentication flow with an identity provider, you can use the `providerId` property. For example:\n   *     - Mapping specific user email addresses with an identity provider.\n   *     - Using different hints to identity the identity provider to be used by the user, like a company-specific page, IP address or other tracking information.\n   *\n   * @example Sign in with email domain\n   * ```js\n   *   // You can extract the user's email domain and use it to trigger the\n   *   // authentication flow with the correct identity provider.\n   *\n   *   const { data, error } = await supabase.auth.signInWithSSO({\n   *     domain: 'company.com'\n   *   })\n   *\n   *   if (data?.url) {\n   *     // redirect the user to the identity provider's authentication flow\n   *     window.location.href = data.url\n   *   }\n   * ```\n   *\n   * @example Sign in with provider UUID\n   * ```js\n   *   // Useful when you need to map a user's sign in request according\n   *   // to different rules that can't use email domains.\n   *\n   *   const { data, error } = await supabase.auth.signInWithSSO({\n   *     providerId: '21648a9d-8d5a-4555-a9d1-d6375dc14e92'\n   *   })\n   *\n   *   if (data?.url) {\n   *     // redirect the user to the identity provider's authentication flow\n   *     window.location.href = data.url\n   *   }\n   * ```\n   */\n  async signInWithSSO(params: SignInWithSSO): Promise\u003cSSOResponse\u003e {\n    let flowId: string | null = null\n    try {\n      let codeChallenge: string | null = null\n      let codeChallengeMethod: string | null = null\n      if (this.flowType === 'pkce') {\n        ;[codeChallenge, codeChallengeMethod, flowId] = await this._getCodeChallengeAndMethod()\n      }\n\n      const result = await _request(this.fetch, 'POST', `${this.url}/sso`, {\n        body: {\n          ...('providerId' in params ? { provider_id: params.providerId } : null),\n          ...('domain' in params ? { domain: params.domain } : null),\n          redirect_to: this._maybeAppendFlowIdToRedirect(params.options?.redirectTo, flowId),\n          ...(params?.options?.captchaToken\n            ? { gotrue_meta_security: { captcha_token: params.options.captchaToken } }\n            : null),\n          skip_http_redirect: true, // fetch does not handle redirects\n          code_challenge: codeChallenge,\n          code_challenge_method: codeChallengeMethod,\n        },\n        headers: this.headers,\n        xform: _ssoResponse,\n      })\n\n      // Automatically redirect in browser unless skipBrowserRedirect is true\n      if (result.data?.url \u0026\u0026 isBrowser() \u0026\u0026 !params.options?.skipBrowserRedirect) {\n        window.location.assign(result.data.url)\n      }\n\n      return this._returnResult(result)\n    } catch (error) {\n      await removePKCEVerifier(this.storage, this.storageKey, flowId)\n      if (isAuthError(error)) {\n        return this._returnResult({ data: null, error })\n      }\n      throw error\n    }\n  }\n\n  /**\n   * Sends a reauthentication OTP to the user's email or phone number.\n   * Requires the user to be signed-in.\n   *\n   * @category Auth\n   *\n   * @remarks\n   * - This method is used together with `updateUser()` when a user's password needs to be updated.\n   * - If you require your user to reauthenticate before updating their password, you need to enable the **Secure password change** option in your [project's email provider settings](/dashboard/project/_/auth/providers).\n   * - A user is only require to reauthenticate before updating their password if **Secure password change** is enabled and the user **hasn't recently signed in**. A user is deemed recently signed in if the session was created in the last 24 hours.\n   * - This method will send a nonce to the user's email. If the user doesn't have a confirmed email address, the method will send the nonce to the user's confirmed phone number instead.\n   * - After receiving the OTP, include it as the `nonce` in your `updateUser()` call to finalize the password change.\n   *\n   * @exampleDescription Send reauthentication nonce\n   * Sends a reauthentication nonce to the user's email or phone number.\n   *\n   * @example Send reauthentication nonce\n   * ```js\n   * const { error } = await supabase.auth.reauthenticate()\n   * ```\n   */\n  async reauthenticate(): Promise\u003cAuthResponse\u003e {\n    await this.initializePromise\n\n    if (this.lock != null) {\n      // TODO(v3): remove legacy lock path\n      return await this._acquireLock(this.lockAcquireTimeout, async () =\u003e {\n        return await this._reauthenticate()\n      })\n    }\n\n    return await this._reauthenticate()\n  }\n\n  private async _reauthenticate(): Promise\u003cAuthResponse\u003e {\n    try {\n      return await this._useSession(async (result) =\u003e {\n        const {\n          data: { session },\n          error: sessionError,\n        } = result\n        if (sessionError) throw sessionError\n        if (!session) throw new AuthSessionMissingError()\n\n        const { error } = await _request(this.fetch, 'GET', `${this.url}/reauthenticate`, {\n          headers: this.headers,\n          jwt: session.access_token,\n        })\n        return this._returnResult({ data: { user: null, session: null }, error })\n      })\n    } catch (error) {\n      if (isAuthError(error)) {\n        return this._returnResult({ data: { user: null, session: null }, error })\n      }\n      throw error\n    }\n  }\n\n  /**\n   * Resends an existing signup confirmation email, email change email, SMS OTP or phone change OTP.\n   *\n   * @category Auth\n   *\n   * @remarks\n   * - Resends a signup confirmation, email change or phone change email to the user.\n   * - Passwordless sign-ins can be resent by calling the `signInWithOtp()` method again.\n   * - Password recovery emails can be resent by calling the `resetPasswordForEmail()` method again.\n   * - This method will only resend an email or phone OTP to the user if there was an initial signup, email change or phone change request being made(note: For existing users signing in with OTP, you should use `signInWithOtp()` again to resend the OTP).\n   * - You can specify a redirect url when you resend an email link using the `emailRedirectTo` option.\n   *\n   * @exampleDescription Resend an email signup confirmation\n   * Resends the email signup confirmation to the user\n   *\n   * @example Resend an email signup confirmation\n   * ```js\n   * const { error } = await supabase.auth.resend({\n   *   type: 'signup',\n   *   email: 'email@example.com',\n   *   options: {\n   *     emailRedirectTo: 'https://example.com/welcome'\n   *   }\n   * })\n   * ```\n   *\n   * @exampleDescription Resend a phone signup confirmation\n   * Resends the phone signup confirmation email to the user\n   *\n   * @example Resend a phone signup confirmation\n   * ```js\n   * const { error } = await supabase.auth.resend({\n   *   type: 'sms',\n   *   phone: '1234567890'\n   * })\n   * ```\n   *\n   * @exampleDescription Resend email change email\n   * Resends the email change email to the user\n   *\n   * @example Resend email change email\n   * ```js\n   * const { error } = await supabase.auth.resend({\n   *   type: 'email_change',\n   *   email: 'email@example.com'\n   * })\n   * ```\n   *\n   * @exampleDescription Resend phone change OTP\n   * Resends the phone change OTP to the user\n   *\n   * @example Resend phone change OTP\n   * ```js\n   * const { error } = await supabase.auth.resend({\n   *   type: 'phone_change',\n   *   phone: '1234567890'\n   * })\n   * ```\n   */\n  async resend(credentials: ResendParams): Promise\u003cAuthOtpResponse\u003e {\n    let flowId: string | null = null\n    try {\n      const endpoint = `${this.url}/resend`\n      if ('email' in credentials) {\n        const { email, type, options } = credentials\n        let codeChallenge: string | null = null\n        let codeChallengeMethod: string | null = null\n        if (this.flowType === 'pkce') {\n          ;[codeChallenge, codeChallengeMethod, flowId] = await this._getCodeChallengeAndMethod()\n        }\n        const { error } = await _request(this.fetch, 'POST', endpoint, {\n          headers: this.headers,\n          body: {\n            email,\n            type,\n            gotrue_meta_security: { captcha_token: options?.captchaToken },\n            code_challenge: codeChallenge,\n            code_challenge_method: codeChallengeMethod,\n          },\n          redirectTo: this._maybeAppendFlowIdToRedirect(options?.emailRedirectTo, flowId),\n        })\n        if (error) {\n          await removePKCEVerifier(this.storage, this.storageKey, flowId)\n        }\n        return this._returnResult({ data: { user: null, session: null }, error })\n      } else if ('phone' in credentials) {\n        const { phone, type, options } = credentials\n        const { data, error } = await _request(this.fetch, 'POST', endpoint, {\n          headers: this.headers,\n          body: {\n            phone,\n            type,\n            gotrue_meta_security: { captcha_token: options?.captchaToken },\n          },\n        })\n        return this._returnResult({\n          data: { user: null, session: null, messageId: data?.message_id },\n          error,\n        })\n      }\n      throw new AuthInvalidCredentialsError(\n        'You must provide either an email or phone number and a type'\n      )\n    } catch (error) {\n      await removePKCEVerifier(this.storage, this.storageKey, flowId)\n      if (isAuthError(error)) {\n        return this._returnResult({ data: { user: null, session: null }, error })\n      }\n      throw error\n    }\n  }\n\n  /**\n   * Returns the session, refreshing it if necessary.\n   *\n   * The session returned can be null if the session is not detected which can happen in the event a user is not signed-in or has logged out.\n   *\n   * **IMPORTANT:** This method loads values directly from the storage attached\n   * to the client. If that storage is based on request cookies for example,\n   * the values in it may not be authentic and therefore it's strongly advised\n   * against using this method and its results in such circumstances. A warning\n   * will be emitted if this is detected. Use {@link GoTrueClient.getUser} instead.\n   *\n   * @category Auth\n   *\n   * @remarks\n   * - Since the introduction of [asymmetric JWT signing keys](/docs/guides/auth/signing-keys), this method is considered low-level and we encourage you to use `getClaims()` or `getUser()` instead.\n   * - Retrieves the current [user session](/docs/guides/auth/sessions) from the storage medium (local storage, cookies).\n   * - The session contains an access token (signed JWT), a refresh token and the user object.\n   * - If the session's access token is expired or is about to expire, this method will use the refresh token to refresh the session.\n   * - When using in a browser, or you've called `startAutoRefresh()` in your environment (React Native, etc.) this function always returns a valid access token without refreshing the session itself, as this is done in the background. This function returns very fast.\n   * - **IMPORTANT SECURITY NOTICE:** If using an insecure storage medium, such as cookies or request headers, the user object returned by this function **must not be trusted**. Always verify the JWT using `getClaims()` or your own JWT verification library to securely establish the user's identity and access. You can also use `getUser()` to fetch the user object directly from the Auth server for this purpose.\n   * - Cross-tab refresh races are handled by the GoTrue server (the rotated token from the first tab is returned to subsequent tabs via the parent-of-active mechanism), so no client-side serialization is needed.\n   *\n   * @example Get the session data\n   * ```js\n   * const { data, error } = await supabase.auth.getSession()\n   * ```\n   *\n   * @exampleResponse Get the session data\n   * ```json\n   * {\n   *   \"data\": {\n   *     \"session\": {\n   *       \"access_token\": \"\u003cACCESS_TOKEN\u003e\",\n   *       \"token_type\": \"bearer\",\n   *       \"expires_in\": 3600,\n   *       \"expires_at\": 1700000000,\n   *       \"refresh_token\": \"\u003cREFRESH_TOKEN\u003e\",\n   *       \"user\": {\n   *         \"id\": \"11111111-1111-1111-1111-111111111111\",\n   *         \"aud\": \"authenticated\",\n   *         \"role\": \"authenticated\",\n   *         \"email\": \"example@email.com\",\n   *         \"email_confirmed_at\": \"2024-01-01T00:00:00Z\",\n   *         \"phone\": \"\",\n   *         \"last_sign_in_at\": \"2024-01-01T00:00:00Z\",\n   *         \"app_metadata\": {\n   *           \"provider\": \"email\",\n   *           \"providers\": [\n   *             \"email\"\n   *           ]\n   *         },\n   *         \"user_metadata\": {\n   *           \"email\": \"example@email.com\",\n   *           \"email_verified\": false,\n   *           \"phone_verified\": false,\n   *           \"sub\": \"11111111-1111-1111-1111-111111111111\"\n   *         },\n   *         \"identities\": [\n   *           {\n   *             \"identity_id\": \"22222222-2222-2222-2222-222222222222\",\n   *             \"id\": \"11111111-1111-1111-1111-111111111111\",\n   *             \"user_id\": \"11111111-1111-1111-1111-111111111111\",\n   *             \"identity_data\": {\n   *               \"email\": \"example@email.com\",\n   *               \"email_verified\": false,\n   *               \"phone_verified\": false,\n   *               \"sub\": \"11111111-1111-1111-1111-111111111111\"\n   *             },\n   *             \"provider\": \"email\",\n   *             \"last_sign_in_at\": \"2024-01-01T00:00:00Z\",\n   *             \"created_at\": \"2024-01-01T00:00:00Z\",\n   *             \"updated_at\": \"2024-01-01T00:00:00Z\",\n   *             \"email\": \"example@email.com\"\n   *           }\n   *         ],\n   *         \"created_at\": \"2024-01-01T00:00:00Z\",\n   *         \"updated_at\": \"2024-01-01T00:00:00Z\",\n   *         \"is_anonymous\": false\n   *       }\n   *     }\n   *   },\n   *   \"error\": null\n   * }\n   * ```\n   */\n  async getSession() {\n    await this.initializePromise\n\n    if (this.lock != null) {\n      // TODO(v3): remove legacy lock path\n      return await this._acquireLock(this.lockAcquireTimeout, async () =\u003e {\n        return this._useSession(async (result) =\u003e {\n          return result\n        })\n      })\n    }\n\n    return await this._useSession(async (result) =\u003e {\n      return result\n    })\n  }\n\n  /**\n   * Acquires a global lock based on the storage key.\n   *\n   * TODO(v3): remove along with the legacy lock path. Only called when\n   * `this.lock` is non-null (custom lock supplied via constructor). The\n   * default lockless path bypasses this entirely.\n   */\n  private async _acquireLock\u003cR\u003e(acquireTimeout: number, fn: () =\u003e Promise\u003cR\u003e): Promise\u003cR\u003e {\n    this._debug('#_acquireLock', 'begin', acquireTimeout)\n\n    try {\n      if (this.lockAcquired) {\n        const last = this.pendingInLock.length\n          ? this.pendingInLock[this.pendingInLock.length - 1]\n          : Promise.resolve()\n\n        const result = (async () =\u003e {\n          await last\n          return await fn()\n        })()\n\n        this.pendingInLock.push(\n          (async () =\u003e {\n            try {\n              await result\n            } catch (_e) {\n              // we just care if it finished\n            }\n          })()\n        )\n\n        return result\n      }\n\n      return await this.lock!(`lock:${this.storageKey}`, acquireTimeout, async () =\u003e {\n        this._debug('#_acquireLock', 'lock acquired for storage key', this.storageKey)\n\n        try {\n          this.lockAcquired = true\n\n          const result = fn()\n\n          this.pendingInLock.push(\n            (async () =\u003e {\n              try {\n                await result\n              } catch (e: any) {\n                // we just care if it finished\n              }\n            })()\n          )\n\n          await result\n\n          // keep draining the queue until there's nothing to wait on\n          while (this.pendingInLock.length) {\n            const waitOn = [...this.pendingInLock]\n\n            await Promise.all(waitOn)\n\n            this.pendingInLock.splice(0, waitOn.length)\n          }\n\n          return await result\n        } finally {\n          this._debug('#_acquireLock', 'lock released for storage key', this.storageKey)\n\n          this.lockAcquired = false\n        }\n      })\n    } finally {\n      this._debug('#_acquireLock', 'end')\n    }\n  }\n\n  /**\n   * Use instead of {@link GoTrueClient.getSession} inside the library. Loads the session\n   * via `__loadSession` (which may trigger a refresh if the access token is\n   * within the expiry margin) and runs `fn` with the result.\n   */\n  private async _useSession\u003cR\u003e(\n    fn: (\n      result:\n        | {\n            data: {\n              session: Session\n            }\n            error: null\n          }\n        | {\n            data: {\n              session: null\n            }\n            error: AuthError\n          }\n        | {\n            data: {\n              session: null\n            }\n            error: null\n          }\n    ) =\u003e Promise\u003cR\u003e\n  ): Promise\u003cR\u003e {\n    this._debug('#_useSession', 'begin')\n\n    try {\n      // Concurrent callers may both reach __loadSession; storage reads are\n      // idempotent, and the only write path inside it (refresh) is\n      // single-flighted downstream by `refreshingDeferred` in\n      // `_callRefreshToken`. No serialization is needed at this layer.\n      const result = await this.__loadSession()\n\n      return await fn(result)\n    } finally {\n      this._debug('#_useSession', 'end')\n    }\n  }\n\n  /**\n   * NEVER USE DIRECTLY!\n   *\n   * Always use `_useSession`.\n   */\n  private async __loadSession(): Promise\u003c\n    | {\n        data: {\n          session: Session\n        }\n        error: null\n      }\n    | {\n        data: {\n          session: null\n        }\n        error: AuthError\n      }\n    | {\n        data: {\n          session: null\n        }\n        error: null\n      }\n  \u003e {\n    this._debug('#__loadSession()', 'begin')\n\n    if (this.lock != null \u0026\u0026 !this.lockAcquired) {\n      // TODO(v3): remove. Only meaningful on the legacy lock path.\n      this._debug('#__loadSession()', 'used outside of an acquired lock!', new Error().stack)\n    }\n\n    try {\n      let currentSession: Session | null = null\n\n      const maybeSession = await getItemAsync(this.storage, this.storageKey)\n\n      this._debug('#getSession()', 'session from storage', maybeSession)\n\n      if (maybeSession !== null) {\n        if (this._isValidSession(maybeSession)) {\n          currentSession = maybeSession\n        } else {\n          this._debug('#getSession()', 'session from storage is not valid')\n          await this._removeSession()\n        }\n      }\n\n      if (!currentSession) {\n        return { data: { session: null }, error: null }\n      }\n\n      // A session is considered expired before the access token _actually_\n      // expires. When the autoRefreshToken option is off (or when the tab is\n      // in the background), very eager users of getSession() -- like\n      // realtime-js -- might send a valid JWT which will expire by the time it\n      // reaches the server.\n      const hasExpired = currentSession.expires_at\n        ? currentSession.expires_at * 1000 - Date.now() \u003c EXPIRY_MARGIN_MS\n        : false\n\n      this._debug(\n        '#__loadSession()',\n        `session has${hasExpired ? '' : ' not'} expired`,\n        'expires_at',\n        currentSession.expires_at\n      )\n\n      if (!hasExpired) {\n        return { data: { session: await this._hydrateSessionUser(currentSession) }, error: null }\n      }\n\n      const { data: session, error } = await this._callRefreshToken(currentSession.refresh_token)\n      if (error) {\n        // A failed refresh does not mean there is no session. Storage is the\n        // source of truth at this point, because either:\n        //  - `_callRefreshToken` kept the original session in storage since\n        //    the access token is still inside its real expiry window (a\n        //    proactive refresh that failed non-retryably), or\n        //  - another caller, in this tab or a different one, committed its\n        //    own rotated session while this refresh was in flight, so this\n        //    one was discarded by the commit guard or rejected by the server\n        //    as already used.\n        // Empty storage (concurrent `signOut`) or an expired stored session\n        // means the session is genuinely gone and the error stands. Callers\n        // that pass an explicit token (`setSession`,\n        // `refreshSession({ refresh_token })`) call `_callRefreshToken`\n        // directly and surface the failure instead.\n        const stored = (await getItemAsync(this.storage, this.storageKey)) as Session | null\n        if (\n          stored \u0026\u0026\n          this._isValidSession(stored) \u0026\u0026\n          stored.expires_at \u0026\u0026\n          stored.expires_at * 1000 \u003e Date.now()\n        ) {\n          return this._returnResult({\n            data: { session: await this._hydrateSessionUser(stored) },\n            error: null,\n          })\n        }\n        return this._returnResult({ data: { session: null }, error })\n      }\n\n      return this._returnResult({ data: { session }, error: null })\n    } finally {\n      this._debug('#__loadSession()', 'end')\n    }\n  }\n\n  /**\n   * Completes a session read back from storage so it matches what callers of\n   * `getSession()` expect: fills in `session.user` from `userStorage` when the\n   * client keeps the user in split storage, and wraps the user in the\n   * insecure-access warning proxy on the server.\n   */\n  private async _hydrateSessionUser(session: Session): Promise\u003cSession\u003e {\n    if (this.userStorage) {\n      const maybeUser: { user?: User | null } | null = (await getItemAsync(\n        this.userStorage,\n        this.storageKey + '-user'\n      )) as any\n\n      session.user = maybeUser?.user ? maybeUser.user : userNotAvailableProxy()\n    }\n\n    // Warns when properties of the user are accessed, not when session.user itself is accessed.\n    if (this.storage.isServer \u0026\u0026 session.user \u0026\u0026 !(session.user as any).__isUserNotAvailableProxy) {\n      const suppressWarningRef = { value: this.suppressGetSessionWarning }\n      session.user = insecureUserWarningProxy(session.user, suppressWarningRef)\n\n      if (suppressWarningRef.value) {\n        this.suppressGetSessionWarning = true\n      }\n    }\n\n    return session\n  }\n\n  /**\n   * Gets the current user details if there is an existing session. This method\n   * performs a network request to the Supabase Auth server, so the returned\n   * value is authentic and can be used to base authorization rules on.\n   *\n   * @param jwt Takes in an optional access token JWT. If no JWT is provided, the JWT from the current session is used.\n   *\n   * @category Auth\n   *\n   * @remarks\n   * - This method fetches the user object from the database instead of local session.\n   * - This method is useful for checking if the user is authorized because it validates the user's access token JWT on the server.\n   * - Should always be used when checking for user authorization on the server. On the client, you can instead use `getSession().session.user` for faster results. `getSession` is insecure on the server.\n   *\n   * @example Get the logged in user with the current existing session\n   * ```js\n   * const { data: { user } } = await supabase.auth.getUser()\n   * ```\n   *\n   * @exampleResponse Get the logged in user with the current existing session\n   * ```json\n   * {\n   *   \"data\": {\n   *     \"user\": {\n   *       \"id\": \"11111111-1111-1111-1111-111111111111\",\n   *       \"aud\": \"authenticated\",\n   *       \"role\": \"authenticated\",\n   *       \"email\": \"example@email.com\",\n   *       \"email_confirmed_at\": \"2024-01-01T00:00:00Z\",\n   *       \"phone\": \"\",\n   *       \"confirmed_at\": \"2024-01-01T00:00:00Z\",\n   *       \"last_sign_in_at\": \"2024-01-01T00:00:00Z\",\n   *       \"app_metadata\": {\n   *         \"provider\": \"email\",\n   *         \"providers\": [\n   *           \"email\"\n   *         ]\n   *       },\n   *       \"user_metadata\": {\n   *         \"email\": \"example@email.com\",\n   *         \"email_verified\": false,\n   *         \"phone_verified\": false,\n   *         \"sub\": \"11111111-1111-1111-1111-111111111111\"\n   *       },\n   *       \"identities\": [\n   *         {\n   *           \"identity_id\": \"22222222-2222-2222-2222-222222222222\",\n   *           \"id\": \"11111111-1111-1111-1111-111111111111\",\n   *           \"user_id\": \"11111111-1111-1111-1111-111111111111\",\n   *           \"identity_data\": {\n   *             \"email\": \"example@email.com\",\n   *             \"email_verified\": false,\n   *             \"phone_verified\": false,\n   *             \"sub\": \"11111111-1111-1111-1111-111111111111\"\n   *           },\n   *           \"provider\": \"email\",\n   *           \"last_sign_in_at\": \"2024-01-01T00:00:00Z\",\n   *           \"created_at\": \"2024-01-01T00:00:00Z\",\n   *           \"updated_at\": \"2024-01-01T00:00:00Z\",\n   *           \"email\": \"example@email.com\"\n   *         }\n   *       ],\n   *       \"created_at\": \"2024-01-01T00:00:00Z\",\n   *       \"updated_at\": \"2024-01-01T00:00:00Z\",\n   *       \"is_anonymous\": false\n   *     }\n   *   },\n   *   \"error\": null\n   * }\n   * ```\n   *\n   * @example Get the logged in user with a custom access token jwt\n   * ```js\n   * const { data: { user } } = await supabase.auth.getUser(jwt)\n   * ```\n   */\n  async getUser(jwt?: string): Promise\u003cUserResponse\u003e {\n    if (jwt) {\n      return await this._getUser(jwt)\n    }\n\n    await this.initializePromise\n\n    let result: UserResponse\n    if (this.lock != null) {\n      // TODO(v3): remove legacy lock path\n      result = await this._acquireLock(this.lockAcquireTimeout, async () =\u003e {\n        return await this._getUser()\n      })\n    } else {\n      result = await this._getUser()\n    }\n\n    if (result.data.user) {\n      this.suppressGetSessionWarning = true\n    }\n\n    return result\n  }\n\n  private async _getUser(jwt?: string): Promise\u003cUserResponse\u003e {\n    try {\n      if (jwt) {\n        return await _request(this.fetch, 'GET', `${this.url}/user`, {\n          headers: this.headers,\n          jwt: jwt,\n          xform: _userResponse,\n        })\n      }\n\n      return await this._useSession(async (result) =\u003e {\n        const { data, error } = result\n        if (error) {\n          throw error\n        }\n\n        // returns an error if there is no access_token or custom authorization header\n        if (!data.session?.access_token \u0026\u0026 !this.hasCustomAuthorizationHeader) {\n          return { data: { user: null }, error: new AuthSessionMissingError() }\n        }\n\n        return await _request(this.fetch, 'GET', `${this.url}/user`, {\n          headers: this.headers,\n          jwt: data.session?.access_token ?? undefined,\n          xform: _userResponse,\n        })\n      })\n    } catch (error) {\n      if (isAuthError(error)) {\n        if (isAuthSessionMissingError(error)) {\n          // JWT contains a `session_id` which does not correspond to an active\n          // session in the database, indicating the user is signed out.\n\n          await this._removeSession()\n        }\n\n        return this._returnResult({ data: { user: null }, error })\n      }\n\n      throw error\n    }\n  }\n\n  /**\n   * Updates user data for a logged in user.\n   *\n   * @category Auth\n   *\n   * @remarks\n   * - In order to use the `updateUser()` method, the user needs to be signed in first.\n   * - By default, email updates sends a confirmation link to both the user's current and new email.\n   * To only send a confirmation link to the user's new email, disable **Secure email change** in your project's [email auth provider settings](/dashboard/project/_/auth/providers).\n   *\n   * @exampleDescription Update the email for an authenticated user\n   * Sends a \"Confirm Email Change\" email to the new address. If **Secure Email Change** is enabled (default), confirmation is also required from the **old email** before the change is applied. To skip dual confirmation and apply the change after only the new email is verified, disable **Secure Email Change** in the [Email Auth Provider settings](/dashboard/project/_/auth/providers?provider=Email).\n   *\n   * @example Update the email for an authenticated user\n   * ```js\n   * const { data, error } = await supabase.auth.updateUser({\n   *   email: 'new@email.com'\n   * })\n   * ```\n   *\n   * @exampleResponse Update the email for an authenticated user\n   * ```json\n   * {\n   *   \"data\": {\n   *     \"user\": {\n   *       \"id\": \"11111111-1111-1111-1111-111111111111\",\n   *       \"aud\": \"authenticated\",\n   *       \"role\": \"authenticated\",\n   *       \"email\": \"example@email.com\",\n   *       \"email_confirmed_at\": \"2024-01-01T00:00:00Z\",\n   *       \"phone\": \"\",\n   *       \"confirmed_at\": \"2024-01-01T00:00:00Z\",\n   *       \"new_email\": \"new@email.com\",\n   *       \"email_change_sent_at\": \"2024-01-01T00:00:00Z\",\n   *       \"last_sign_in_at\": \"2024-01-01T00:00:00Z\",\n   *       \"app_metadata\": {\n   *         \"provider\": \"email\",\n   *         \"providers\": [\n   *           \"email\"\n   *         ]\n   *       },\n   *       \"user_metadata\": {\n   *         \"email\": \"example@email.com\",\n   *         \"email_verified\": false,\n   *         \"phone_verified\": false,\n   *         \"sub\": \"11111111-1111-1111-1111-111111111111\"\n   *       },\n   *       \"identities\": [\n   *         {\n   *           \"identity_id\": \"22222222-2222-2222-2222-222222222222\",\n   *           \"id\": \"11111111-1111-1111-1111-111111111111\",\n   *           \"user_id\": \"11111111-1111-1111-1111-111111111111\",\n   *           \"identity_data\": {\n   *             \"email\": \"example@email.com\",\n   *             \"email_verified\": false,\n   *             \"phone_verified\": false,\n   *             \"sub\": \"11111111-1111-1111-1111-111111111111\"\n   *           },\n   *           \"provider\": \"email\",\n   *           \"last_sign_in_at\": \"2024-01-01T00:00:00Z\",\n   *           \"created_at\": \"2024-01-01T00:00:00Z\",\n   *           \"updated_at\": \"2024-01-01T00:00:00Z\",\n   *           \"email\": \"example@email.com\"\n   *         }\n   *       ],\n   *       \"created_at\": \"2024-01-01T00:00:00Z\",\n   *       \"updated_at\": \"2024-01-01T00:00:00Z\",\n   *       \"is_anonymous\": false\n   *     }\n   *   },\n   *   \"error\": null\n   * }\n   * ```\n   *\n   * @exampleDescription Update the phone number for an authenticated user\n   * Sends a one-time password (OTP) to the new phone number.\n   *\n   * @example Update the phone number for an authenticated user\n   * ```js\n   * const { data, error } = await supabase.auth.updateUser({\n   *   phone: '123456789'\n   * })\n   * ```\n   *\n   * @example Update the password for an authenticated user\n   * ```js\n   * const { data, error } = await supabase.auth.updateUser({\n   *   password: 'new password'\n   * })\n   * ```\n   *\n   * @exampleDescription Update the user's metadata\n   * Updates the user's custom metadata.\n   *\n   * **Note**: The `data` field maps to the `auth.users.raw_user_meta_data` column in your Supabase database. When calling `getUser()`, the data will be available as `user.user_metadata`.\n   *\n   * @example Update the user's metadata\n   * ```js\n   * const { data, error } = await supabase.auth.updateUser({\n   *   data: { hello: 'world' }\n   * })\n   * ```\n   *\n   * @exampleDescription Update the user's password with a nonce\n   * If **Secure password change** is enabled in your [project's email provider settings](/dashboard/project/_/auth/providers), updating the user's password would require a nonce if the user **hasn't recently signed in**. The nonce is sent to the user's email or phone number. A user is deemed recently signed in if the session was created in the last 24 hours.\n   *\n   * @example Update the user's password with a nonce\n   * ```js\n   * const { data, error } = await supabase.auth.updateUser({\n   *   password: 'new password',\n   *   nonce: '123456'\n   * })\n   * ```\n   */\n  async updateUser(\n    attributes: UserAttributes,\n    options: {\n      emailRedirectTo?: string | undefined\n    } = {}\n  ): Promise\u003cUserResponse\u003e {\n    await this.initializePromise\n\n    if (this.lock != null) {\n      // TODO(v3): remove legacy lock path\n      return await this._acquireLock(this.lockAcquireTimeout, async () =\u003e {\n        return await this._updateUser(attributes, options)\n      })\n    }\n\n    return await this._updateUser(attributes, options)\n  }\n\n  protected async _updateUser(\n    attributes: UserAttributes,\n    options: {\n      emailRedirectTo?: string | undefined\n    } = {}\n  ): Promise\u003cUserResponse\u003e {\n    let flowId: string | null = null\n    try {\n      return await this._useSession(async (result) =\u003e {\n        const { data: sessionData, error: sessionError } = result\n        if (sessionError) {\n          throw sessionError\n        }\n        if (!sessionData.session) {\n          throw new AuthSessionMissingError()\n        }\n        const session: Session = sessionData.session\n        let codeChallenge: string | null = null\n        let codeChallengeMethod: string | null = null\n        if (this.flowType === 'pkce' \u0026\u0026 attributes.email != null) {\n          ;[codeChallenge, codeChallengeMethod, flowId] = await this._getCodeChallengeAndMethod()\n        }\n\n        const { data, error: userError } = await _request(this.fetch, 'PUT', `${this.url}/user`, {\n          headers: this.headers,\n          redirectTo: this._maybeAppendFlowIdToRedirect(options?.emailRedirectTo, flowId),\n          body: {\n            ...attributes,\n            code_challenge: codeChallenge,\n            code_challenge_method: codeChallengeMethod,\n          },\n          jwt: session.access_token,\n          xform: _userResponse,\n        })\n        if (userError) {\n          throw userError\n        }\n        session.user = data.user as User\n        await this._saveSession(session)\n        await this._notifyAllSubscribers('USER_UPDATED', session)\n        return this._returnResult({ data: { user: session.user }, error: null })\n      })\n    } catch (error) {\n      await removePKCEVerifier(this.storage, this.storageKey, flowId)\n      if (isAuthError(error)) {\n        return this._returnResult({ data: { user: null }, error })\n      }\n\n      throw error\n    }\n  }\n\n  /**\n   * Sets the session data from the current session. If the current session is expired, setSession will take care of refreshing it to obtain a new session.\n   * If the refresh token or access token in the current session is invalid, an error will be thrown.\n   * @param currentSession The current session that minimally contains an access token and refresh token.\n   *\n   * @category Auth\n   *\n   * @remarks\n   * - This method sets the session using an `access_token` and `refresh_token`.\n   * - If successful, a `SIGNED_IN` event is emitted.\n   *\n   * @exampleDescription Set the session\n   * Sets the session data from an access_token and refresh_token, then returns an auth response or error.\n   *\n   * @example Set the session\n   * ```js\n   *   const { data, error } = await supabase.auth.setSession({\n   *     access_token,\n   *     refresh_token\n   *   })\n   * ```\n   *\n   * @exampleResponse Set the session\n   * ```json\n   * {\n   *   \"data\": {\n   *     \"user\": {\n   *       \"id\": \"11111111-1111-1111-1111-111111111111\",\n   *       \"aud\": \"authenticated\",\n   *       \"role\": \"authenticated\",\n   *       \"email\": \"example@email.com\",\n   *       \"email_confirmed_at\": \"2024-01-01T00:00:00Z\",\n   *       \"phone\": \"\",\n   *       \"confirmed_at\": \"2024-01-01T00:00:00Z\",\n   *       \"last_sign_in_at\": \"2024-01-01T00:00:00Z\",\n   *       \"app_metadata\": {\n   *         \"provider\": \"email\",\n   *         \"providers\": [\n   *           \"email\"\n   *         ]\n   *       },\n   *       \"user_metadata\": {\n   *         \"email\": \"example@email.com\",\n   *         \"email_verified\": false,\n   *         \"phone_verified\": false,\n   *         \"sub\": \"11111111-1111-1111-1111-111111111111\"\n   *       },\n   *       \"identities\": [\n   *         {\n   *           \"identity_id\": \"22222222-2222-2222-2222-222222222222\",\n   *           \"id\": \"11111111-1111-1111-1111-111111111111\",\n   *           \"user_id\": \"11111111-1111-1111-1111-111111111111\",\n   *           \"identity_data\": {\n   *             \"email\": \"example@email.com\",\n   *             \"email_verified\": false,\n   *             \"phone_verified\": false,\n   *             \"sub\": \"11111111-1111-1111-1111-111111111111\"\n   *           },\n   *           \"provider\": \"email\",\n   *           \"last_sign_in_at\": \"2024-01-01T00:00:00Z\",\n   *           \"created_at\": \"2024-01-01T00:00:00Z\",\n   *           \"updated_at\": \"2024-01-01T00:00:00Z\",\n   *           \"email\": \"example@email.com\"\n   *         }\n   *       ],\n   *       \"created_at\": \"2024-01-01T00:00:00Z\",\n   *       \"updated_at\": \"2024-01-01T00:00:00Z\",\n   *       \"is_anonymous\": false\n   *     },\n   *     \"session\": {\n   *       \"access_token\": \"\u003cACCESS_TOKEN\u003e\",\n   *       \"refresh_token\": \"\u003cREFRESH_TOKEN\u003e\",\n   *       \"user\": {\n   *         \"id\": \"11111111-1111-1111-1111-111111111111\",\n   *         \"aud\": \"authenticated\",\n   *         \"role\": \"authenticated\",\n   *         \"email\": \"example@email.com\",\n   *         \"email_confirmed_at\": \"2024-01-01T00:00:00Z\",\n   *         \"phone\": \"\",\n   *         \"confirmed_at\": \"2024-01-01T00:00:00Z\",\n   *         \"last_sign_in_at\": \"11111111-1111-1111-1111-111111111111\",\n   *         \"app_metadata\": {\n   *           \"provider\": \"email\",\n   *           \"providers\": [\n   *             \"email\"\n   *           ]\n   *         },\n   *         \"user_metadata\": {\n   *           \"email\": \"example@email.com\",\n   *           \"email_verified\": false,\n   *           \"phone_verified\": false,\n   *           \"sub\": \"11111111-1111-1111-1111-111111111111\"\n   *         },\n   *         \"identities\": [\n   *           {\n   *             \"identity_id\": \"2024-01-01T00:00:00Z\",\n   *             \"id\": \"11111111-1111-1111-1111-111111111111\",\n   *             \"user_id\": \"11111111-1111-1111-1111-111111111111\",\n   *             \"identity_data\": {\n   *               \"email\": \"example@email.com\",\n   *               \"email_verified\": false,\n   *               \"phone_verified\": false,\n   *               \"sub\": \"11111111-1111-1111-1111-111111111111\"\n   *             },\n   *             \"provider\": \"email\",\n   *             \"last_sign_in_at\": \"2024-01-01T00:00:00Z\",\n   *             \"created_at\": \"2024-01-01T00:00:00Z\",\n   *             \"updated_at\": \"2024-01-01T00:00:00Z\",\n   *             \"email\": \"example@email.com\"\n   *           }\n   *         ],\n   *         \"created_at\": \"2024-01-01T00:00:00Z\",\n   *         \"updated_at\": \"2024-01-01T00:00:00Z\",\n   *         \"is_anonymous\": false\n   *       },\n   *       \"token_type\": \"bearer\",\n   *       \"expires_in\": 3500,\n   *       \"expires_at\": 1700000000\n   *     }\n   *   },\n   *   \"error\": null\n   * }\n   * ```\n   */\n  async setSession(currentSession: {\n    access_token: string\n    refresh_token: string\n  }): Promise\u003cAuthResponse\u003e {\n    await this.initializePromise\n\n    if (this.lock != null) {\n      // TODO(v3): remove legacy lock path\n      return await this._acquireLock(this.lockAcquireTimeout, async () =\u003e {\n        return await this._setSession(currentSession)\n      })\n    }\n\n    return await this._setSession(currentSession)\n  }\n\n  protected async _setSession(currentSession: {\n    access_token: string\n    refresh_token: string\n  }): Promise\u003cAuthResponse\u003e {\n    try {\n      if (!currentSession.access_token || !currentSession.refresh_token) {\n        throw new AuthSessionMissingError()\n      }\n\n      const timeNow = Date.now() / 1000\n      let expiresAt = timeNow\n      let hasExpired = true\n      let session: Session | null = null\n      const { payload } = decodeJWT(currentSession.access_token)\n      if (payload.exp) {\n        expiresAt = payload.exp\n        hasExpired = expiresAt \u003c= timeNow\n      }\n\n      if (hasExpired) {\n        const { data: refreshedSession, error } = await this._callRefreshToken(\n          currentSession.refresh_token\n        )\n        if (error) {\n          return this._returnResult({ data: { user: null, session: null }, error: error })\n        }\n\n        if (!refreshedSession) {\n          return { data: { user: null, session: null }, error: null }\n        }\n        session = refreshedSession\n      } else {\n        const { data, error } = await this._getUser(currentSession.access_token)\n        if (error) {\n          return this._returnResult({ data: { user: null, session: null }, error })\n        }\n        session = {\n          access_token: currentSession.access_token,\n          refresh_token: currentSession.refresh_token,\n          user: data.user,\n          token_type: 'bearer',\n          expires_in: expiresAt - timeNow,\n          expires_at: expiresAt,\n        }\n        await this._saveSession(session)\n        await this._notifyAllSubscribers('SIGNED_IN', session)\n      }\n\n      return this._returnResult({ data: { user: session.user, session }, error: null })\n    } catch (error) {\n      if (isAuthError(error)) {\n        return this._returnResult({ data: { session: null, user: null }, error })\n      }\n\n      throw error\n    }\n  }\n\n  /**\n   * Returns a new session, regardless of expiry status.\n   * Takes in an optional current session. If not passed in, then refreshSession() will attempt to retrieve it from getSession().\n   * If the current session's refresh token is invalid, an error will be thrown.\n   * @param currentSession The current session. If passed in, it must contain a refresh token.\n   *\n   * @category Auth\n   *\n   * @remarks\n   * - This method will refresh and return a new session whether the current one is expired or not.\n   *\n   * @example Refresh session using the current session\n   * ```js\n   * const { data, error } = await supabase.auth.refreshSession()\n   * const { session, user } = data\n   * ```\n   *\n   * @exampleResponse Refresh session using the current session\n   * ```json\n   * {\n   *   \"data\": {\n   *     \"user\": {\n   *       \"id\": \"11111111-1111-1111-1111-111111111111\",\n   *       \"aud\": \"authenticated\",\n   *       \"role\": \"authenticated\",\n   *       \"email\": \"example@email.com\",\n   *       \"email_confirmed_at\": \"2024-01-01T00:00:00Z\",\n   *       \"phone\": \"\",\n   *       \"confirmed_at\": \"2024-01-01T00:00:00Z\",\n   *       \"last_sign_in_at\": \"2024-01-01T00:00:00Z\",\n   *       \"app_metadata\": {\n   *         \"provider\": \"email\",\n   *         \"providers\": [\n   *           \"email\"\n   *         ]\n   *       },\n   *       \"user_metadata\": {\n   *         \"email\": \"example@email.com\",\n   *         \"email_verified\": false,\n   *         \"phone_verified\": false,\n   *         \"sub\": \"11111111-1111-1111-1111-111111111111\"\n   *       },\n   *       \"identities\": [\n   *         {\n   *           \"identity_id\": \"22222222-2222-2222-2222-222222222222\",\n   *           \"id\": \"11111111-1111-1111-1111-111111111111\",\n   *           \"user_id\": \"11111111-1111-1111-1111-111111111111\",\n   *           \"identity_data\": {\n   *             \"email\": \"example@email.com\",\n   *             \"email_verified\": false,\n   *             \"phone_verified\": false,\n   *             \"sub\": \"11111111-1111-1111-1111-111111111111\"\n   *           },\n   *           \"provider\": \"email\",\n   *           \"last_sign_in_at\": \"2024-01-01T00:00:00Z\",\n   *           \"created_at\": \"2024-01-01T00:00:00Z\",\n   *           \"updated_at\": \"2024-01-01T00:00:00Z\",\n   *           \"email\": \"example@email.com\"\n   *         }\n   *       ],\n   *       \"created_at\": \"2024-01-01T00:00:00Z\",\n   *       \"updated_at\": \"2024-01-01T00:00:00Z\",\n   *       \"is_anonymous\": false\n   *     },\n   *     \"session\": {\n   *       \"access_token\": \"\u003cACCESS_TOKEN\u003e\",\n   *       \"token_type\": \"bearer\",\n   *       \"expires_in\": 3600,\n   *       \"expires_at\": 1700000000,\n   *       \"refresh_token\": \"\u003cREFRESH_TOKEN\u003e\",\n   *       \"user\": {\n   *         \"id\": \"11111111-1111-1111-1111-111111111111\",\n   *         \"aud\": \"authenticated\",\n   *         \"role\": \"authenticated\",\n   *         \"email\": \"example@email.com\",\n   *         \"email_confirmed_at\": \"2024-01-01T00:00:00Z\",\n   *         \"phone\": \"\",\n   *         \"confirmed_at\": \"2024-01-01T00:00:00Z\",\n   *         \"last_sign_in_at\": \"2024-01-01T00:00:00Z\",\n   *         \"app_metadata\": {\n   *           \"provider\": \"email\",\n   *           \"providers\": [\n   *             \"email\"\n   *           ]\n   *         },\n   *         \"user_metadata\": {\n   *           \"email\": \"example@email.com\",\n   *           \"email_verified\": false,\n   *           \"phone_verified\": false,\n   *           \"sub\": \"11111111-1111-1111-1111-111111111111\"\n   *         },\n   *         \"identities\": [\n   *           {\n   *             \"identity_id\": \"22222222-2222-2222-2222-222222222222\",\n   *             \"id\": \"11111111-1111-1111-1111-111111111111\",\n   *             \"user_id\": \"11111111-1111-1111-1111-111111111111\",\n   *             \"identity_data\": {\n   *               \"email\": \"example@email.com\",\n   *               \"email_verified\": false,\n   *               \"phone_verified\": false,\n   *               \"sub\": \"11111111-1111-1111-1111-111111111111\"\n   *             },\n   *             \"provider\": \"email\",\n   *             \"last_sign_in_at\": \"2024-01-01T00:00:00Z\",\n   *             \"created_at\": \"2024-01-01T00:00:00Z\",\n   *             \"updated_at\": \"2024-01-01T00:00:00Z\",\n   *             \"email\": \"example@email.com\"\n   *           }\n   *         ],\n   *         \"created_at\": \"2024-01-01T00:00:00Z\",\n   *         \"updated_at\": \"2024-01-01T00:00:00Z\",\n   *         \"is_anonymous\": false\n   *       }\n   *     }\n   *   },\n   *   \"error\": null\n   * }\n   * ```\n   *\n   * @example Refresh session using a refresh token\n   * ```js\n   * const { data, error } = await supabase.auth.refreshSession({ refresh_token })\n   * const { session, user } = data\n   * ```\n   */\n  async refreshSession(currentSession?: { refresh_token: string }): Promise\u003cAuthResponse\u003e {\n    await this.initializePromise\n\n    if (this.lock != null) {\n      // TODO(v3): remove legacy lock path\n      return await this._acquireLock(this.lockAcquireTimeout, async () =\u003e {\n        return await this._refreshSession(currentSession)\n      })\n    }\n\n    return await this._refreshSession(currentSession)\n  }\n\n  protected async _refreshSession(currentSession?: {\n    refresh_token: string\n  }): Promise\u003cAuthResponse\u003e {\n    try {\n      return await this._useSession(async (result) =\u003e {\n        if (!currentSession) {\n          const { data, error } = result\n          if (error) {\n            throw error\n          }\n\n          currentSession = data.session ?? undefined\n        }\n\n        if (!currentSession?.refresh_token) {\n          throw new AuthSessionMissingError()\n        }\n\n        const { data: session, error } = await this._callRefreshToken(currentSession.refresh_token)\n        if (error) {\n          return this._returnResult({ data: { user: null, session: null }, error: error })\n        }\n\n        if (!session) {\n          return this._returnResult({ data: { user: null, session: null }, error: null })\n        }\n\n        return this._returnResult({ data: { user: session.user, session }, error: null })\n      })\n    } catch (error) {\n      if (isAuthError(error)) {\n        return this._returnResult({ data: { user: null, session: null }, error })\n      }\n\n      throw error\n    }\n  }\n\n  /**\n   * Gets the session data from a URL string\n   */\n  private async _getSessionFromURL(\n    params: { [parameter: string]: string },\n    callbackUrlType: string\n  ): Promise\u003c\n    | {\n        data: { session: Session; redirectType: string | null }\n        error: null\n      }\n    | { data: { session: null; redirectType: null }; error: AuthError }\n  \u003e {\n    try {\n      if (!isBrowser()) throw new AuthImplicitGrantRedirectError('No browser detected.')\n\n      // If there's an error in the URL, it doesn't matter what flow it is, we just return the error.\n      if (params.error || params.error_description || params.error_code) {\n        // The error class returned implies that the redirect is from an implicit grant flow\n        // but it could also be from a redirect error from a PKCE flow.\n        throw new AuthImplicitGrantRedirectError(\n          params.error_description || 'Error in URL with unspecified error_description',\n          {\n            error: params.error || 'unspecified_error',\n            code: params.error_code || 'unspecified_code',\n          }\n        )\n      }\n\n      // Checks for mismatches between the flowType initialised in the client and the URL parameters\n      switch (callbackUrlType) {\n        case 'implicit':\n          if (this.flowType === 'pkce') {\n            throw new AuthPKCEGrantCodeExchangeError('Not a valid PKCE flow url.')\n          }\n          break\n        case 'pkce':\n          if (this.flowType === 'implicit') {\n            throw new AuthImplicitGrantRedirectError('Not a valid implicit grant flow url.')\n          }\n          break\n        default:\n        // there's no mismatch so we continue\n      }\n\n      // Since this is a redirect for PKCE, we attempt to retrieve the code from the URL for the code exchange\n      if (callbackUrlType === 'pkce') {\n        this._debug('#_initialize()', 'begin', 'is PKCE flow', true)\n        if (!params.code) throw new AuthPKCEGrantCodeExchangeError('No code detected.')\n        const { data, error } = await this._exchangeCodeForSession(params.code, {\n          flowId: params[PKCE_FLOW_ID_PARAM],\n        })\n        if (error) throw error\n\n        const url = new URL(window.location.href)\n        url.searchParams.delete('code')\n        url.searchParams.delete(PKCE_FLOW_ID_PARAM)\n\n        window.history.replaceState(window.history.state, '', url.toString())\n\n        return {\n          data: { session: data.session, redirectType: data.redirectType ?? null },\n          error: null,\n        }\n      }\n\n      const {\n        provider_token,\n        provider_refresh_token,\n        access_token,\n        refresh_token,\n        expires_in,\n        expires_at,\n        token_type,\n      } = params\n\n      if (!access_token || !expires_in || !refresh_token || !token_type) {\n        throw new AuthImplicitGrantRedirectError('No session defined in URL')\n      }\n\n      const timeNow = Math.round(Date.now() / 1000)\n      const expiresIn = parseInt(expires_in)\n      let expiresAt = timeNow + expiresIn\n\n      if (expires_at) {\n        expiresAt = parseInt(expires_at)\n      }\n\n      const actuallyExpiresIn = expiresAt - timeNow\n      if (actuallyExpiresIn * 1000 \u003c= AUTO_REFRESH_TICK_DURATION_MS) {\n        console.warn(\n          `@supabase/gotrue-js: Session as retrieved from URL expires in ${actuallyExpiresIn}s, should have been closer to ${expiresIn}s`\n        )\n      }\n\n      const issuedAt = expiresAt - expiresIn\n      if (timeNow - issuedAt \u003e= 120) {\n        console.warn(\n          '@supabase/gotrue-js: Session as retrieved from URL was issued over 120s ago, URL could be stale',\n          issuedAt,\n          expiresAt,\n          timeNow\n        )\n      } else if (timeNow - issuedAt \u003c 0) {\n        console.warn(\n          '@supabase/gotrue-js: Session as retrieved from URL was issued in the future? Check the device clock for skew',\n          issuedAt,\n          expiresAt,\n          timeNow\n        )\n      }\n\n      const { data, error } = await this._getUser(access_token)\n      if (error) throw error\n\n      const session: Session = {\n        provider_token,\n        provider_refresh_token,\n        access_token,\n        expires_in: expiresIn,\n        expires_at: expiresAt,\n        refresh_token,\n        token_type: token_type as 'bearer',\n        user: data.user,\n      }\n\n      // Remove tokens from URL\n      window.location.hash = ''\n      this._debug('#_getSessionFromURL()', 'clearing window.location.hash')\n\n      return this._returnResult({ data: { session, redirectType: params.type }, error: null })\n    } catch (error) {\n      if (isAuthError(error)) {\n        return this._returnResult({ data: { session: null, redirectType: null }, error })\n      }\n\n      throw error\n    }\n  }\n\n  /**\n   * Checks if the current URL contains parameters given by an implicit oauth grant flow (https://www.rfc-editor.org/rfc/rfc6749.html#section-4.2)\n   *\n   * If `detectSessionInUrl` is a function, it will be called with the URL and params to determine\n   * if the URL should be processed as a Supabase auth callback. This allows users to exclude\n   * URLs from other OAuth providers (e.g., Facebook Login) that also return access_token in the fragment.\n   */\n  private _isImplicitGrantCallback(params: { [parameter: string]: string }): boolean {\n    if (typeof this.detectSessionInUrl === 'function') {\n      return this.detectSessionInUrl(new URL(window.location.href), params)\n    }\n    return Boolean(\n      params.access_token || params.error || params.error_description || params.error_code\n    )\n  }\n\n  /**\n   * Checks if the current URL and backing storage contain parameters given by a PKCE flow\n   */\n  private async _isPKCECallback(params: { [parameter: string]: string }): Promise\u003cboolean\u003e {\n    if (!params.code) {\n      return false\n    }\n\n    const flowId = validatePKCEFlowId(params[PKCE_FLOW_ID_PARAM])\n    if (\n      flowId \u0026\u0026\n      (await getItemAsync(this.storage, pkceVerifierSlotKey(this.storageKey, flowId)))\n    ) {\n      return true\n    }\n\n    const currentStorageContent = await getItemAsync(\n      this.storage,\n      `${this.storageKey}-code-verifier`\n    )\n\n    return !!currentStorageContent\n  }\n\n  /**\n   * Inside a browser context, `signOut()` will remove the logged in user from the browser session\n   * and log them out - removing all items from localstorage and then trigger a `\"SIGNED_OUT\"`\n   * event.\n   *\n   * For server-side management, you can revoke all refresh tokens for a user by passing a user's\n   * JWT through to `auth.api.signOut(JWT: string)`.\n   *\n   * There is no way to revoke a user's access token jwt until it expires. It is recommended to set\n   * a shorter expiry on the jwt for this reason.\n   *\n   * `signOut` behavior depends on the selected scope:\n   *\n   * - `local`: The local session is removed first and a `SIGNED_OUT` event is fired, then the client\n   *   makes a best-effort request to revoke the refresh token on the server. If the request fails,\n   *   the client is still signed out locally and the error is returned, but the server may retain\n   *   the refresh token until it expires.\n   *\n   * - `global`: All of the user's sessions are first invalidated on the server. Once the server\n   *   acknowledges the request, the local session is cleared. If server logout fails, the local\n   *   session is retained, no `SIGNED_OUT` event is triggered, and the server or network error is\n   *   returned. A 401, 403, or 404 response counts as a successful sign-out.\n   *\n   * - `others`: All other sessions are invalidated when the server accepts the request; the\n   *   current local session remains unchanged. In case of server or network failures, the error is\n   *   returned. A `SIGNED_OUT` event is never triggered, regardless of the outcome.\n   *\n   * **Warning:** the default `scope` is `'global'`. This signs the user out of\n   * **every device they are currently signed in on**, not just the current\n   * tab/session. If you only want to sign the user out of the current session\n   * (the behavior most other auth libraries default to), pass\n   * `{ scope: 'local' }` explicitly.\n   *\n   * @category Auth\n   *\n   * @remarks\n   * - In order to use the `signOut()` method, the user needs to be signed in first.\n   * - By default, `signOut()` uses the **global** scope, which signs out the user\n   *   on every device they are signed in on (not just the current one). Pass\n   *   `{ scope: 'local' }` to only sign out the current session. This is\n   *   usually what apps want on a \"Sign out\" button, especially when users\n   *   sign in from multiple devices and do not expect signing out of one to\n   *   terminate the others.\n   * - With the default `global` scope, `signOut()` while offline returns an error and keeps the user\n   *   signed in. To sign out regardless, fall back to `signOut({ scope: 'local' })` when the call\n   *   returns an error.\n   * - Since Supabase Auth uses JWTs for authentication, the access token JWT will be valid until\n   *   it's expired. When the user signs out, Supabase revokes the refresh token and deletes the\n   *   JWT from the client-side. This does not revoke the JWT and it will still be valid until it\n   *   expires.\n   *\n   * @example Sign out of every device (global – default)\n   * ```js\n   * const { error } = await supabase.auth.signOut()\n   * ```\n   *\n   * @example Sign out only the current session (recommended for most apps)\n   * ```js\n   * const { error } = await supabase.auth.signOut({ scope: 'local' })\n   * ```\n   *\n   * @example Sign out of all other sessions, keep the current one\n   * ```js\n   * const { error } = await supabase.auth.signOut({ scope: 'others' })\n   * ```\n   */\n  async signOut(options: SignOut = { scope: 'global' }): Promise\u003c{ error: AuthError | null }\u003e {\n    await this.initializePromise\n\n    if (this.lock != null) {\n      // TODO(v3): remove legacy lock path\n      return await this._acquireLock(this.lockAcquireTimeout, async () =\u003e {\n        return await this._signOut(options)\n      })\n    }\n\n    return await this._signOut(options)\n  }\n\n  protected async _signOut({ scope = 'global' }: SignOut = {}): Promise\u003c{\n    error: AuthError | null\n  }\u003e {\n    return await this._useSession(async (result) =\u003e {\n      const removeCurrentSession = async () =\u003e {\n        await this._removeSession()\n      }\n      const { data, error: sessionError } = result\n      if (sessionError \u0026\u0026 !isAuthSessionMissingError(sessionError)) {\n        // A retryable refresh failure (offline, 5xx) leaves the session in storage and no access\n        // token to revoke with, so `local` still has to sign out this device. A rejected refresh\n        // has already removed the session and fired `SIGNED_OUT`.\n        if (scope === 'local' \u0026\u0026 isAuthRetryableFetchError(sessionError)) {\n          await removeCurrentSession()\n        }\n        return this._returnResult({ error: sessionError })\n      }\n      const accessToken = data.session?.access_token\n      let removeError: { thrown: unknown } | null = null\n      const finish = \u003cT\u003e(value: T): T =\u003e {\n        if (removeError) {\n          throw removeError.thrown\n        }\n        return value\n      }\n      if (scope === 'local') {\n        // The local session is removed before the request is sent, so signing out of this device\n        // never depends on the network. The request only revokes the refresh token on the server.\n        // A throwing `SIGNED_OUT` subscriber must not skip that request, so its error is rethrown\n        // once the request has been attempted.\n        try {\n          await removeCurrentSession()\n        } catch (thrown) {\n          removeError = { thrown }\n        }\n      }\n      if (accessToken) {\n        const { error } = await this.admin.signOut(accessToken, scope)\n        // The current behavior is wrong for the current version of auth (v2.197.0). However,\n        // changing it could be considered a breaking change and must wait for v3. Before modifying\n        // this code we also need to consider which range of Auth versions we aim to support. Right\n        // now this is not defined and thus undefined.\n        //\n        // Some constraints to be aware of:\n        // - Since supabase/auth v2.145.0 a missing user answers 403 `user_not_found`.\n        // - Since supabase/auth v2.150.0 a missing session answers 403 `session_not_found`.\n        // - Before v2.145.0 an invalid JWT answered 401.\n        // - Before v2.145.0 a missing user answers 404., so those statuses are treated the same way.\n        //\n        // TODO(v3): if we only support auth v2.150.0 or later, change this to:\n        //  - Match on `error.code` instead of `error.status`, and treat only 403 `session_not_found`\n        //    and `user_not_found` as already signed out. Drop the 401 and 404 handling.\n        //  - Return every other error, e.g. 403 `bad_jwt` or `user_banned`, or a 401 or 404 from a\n        //    gateway, instead of treating it as signed out. Today nothing was revoked, yet the\n        //    session is cleared and `error` is null. With `global` the session is then kept.\n        //  - For `others`, return `session_not_found` as well. It describes the current session, not\n        //    the sessions being revoked.\n        if (\n          error \u0026\u0026\n          !(\n            (isAuthApiError(error) \u0026\u0026\n              (error.status === 404 || error.status === 401 || error.status === 403)) ||\n            isAuthSessionMissingError(error)\n          )\n        ) {\n          return finish(this._returnResult({ error }))\n        }\n      }\n      if (scope === 'global') {\n        await removeCurrentSession()\n      }\n      return finish(this._returnResult({ error: null }))\n    })\n  }\n\n  /**\n   * Receive a notification every time an auth event happens.\n   * Safe to use without an async function as callback.\n   *\n   * @param callback A callback function to be invoked when an auth event happens.\n   */\n  onAuthStateChange(callback: (event: AuthChangeEvent, session: Session | null) =\u003e void): {\n    data: { subscription: Subscription }\n  }\n\n  /**\n   * Receive a notification every time an auth event happens. Common reentry\n   * patterns (`getUser`, `setSession`, reading the session from inside a\n   * handler) complete normally. One hazard remains: calling `refreshSession`\n   * (or anything that routes through `_callRefreshToken`) from inside a\n   * `TOKEN_REFRESHED` handler. `refreshingDeferred` resolves only after\n   * `_notifyAllSubscribers` returns, so the inner refresh dedupes onto the\n   * outer's unresolved promise and the two wait on each other.\n   *\n   * @param callback A callback function to be invoked when an auth event happens.\n   *\n   * @deprecated Async callbacks can deadlock when they trigger a nested\n   * refresh from a `TOKEN_REFRESHED` event. Prefer the sync overload, or move\n   * refresh-triggering work outside the callback.\n   */\n  onAuthStateChange(callback: (event: AuthChangeEvent, session: Session | null) =\u003e Promise\u003cvoid\u003e): {\n    data: { subscription: Subscription }\n  }\n\n  /**  *\n   * @category Auth\n   *\n   * @remarks\n   * - Subscribes to important events occurring on the user's session.\n   * - Use on the frontend/client. It is less useful on the server.\n   * - Events are emitted across tabs to keep your application's UI up-to-date. Some events can fire very frequently, based on the number of tabs open. Use a quick and efficient callback function, and defer or debounce as many operations as you can to be performed outside of the callback.\n   * - Callbacks can be `async` and can safely call other Supabase auth methods (`getUser`, `setSession`, etc.) from inside the callback.\n   * - Keep callbacks quick. Events are awaited in order, so a slow callback delays subsequent events to subscribers in this tab.\n   * - Emitted events:\n   *   - `INITIAL_SESSION`\n   *     - Emitted right after the Supabase client is constructed and the initial session from storage is loaded.\n   *   - `SIGNED_IN`\n   *     - Emitted each time a user session is confirmed or re-established, including on user sign in and when refocusing a tab.\n   *     - Avoid making assumptions as to when this event is fired, this may occur even when the user is already signed in. Instead, check the user object attached to the event to see if a new user has signed in and update your application's UI.\n   *     - This event can fire very frequently depending on the number of tabs open in your application.\n   *   - `SIGNED_OUT`\n   *     - Emitted when the user signs out. This can be after:\n   *       - A call to `supabase.auth.signOut()`.\n   *       - After the user's session has expired for any reason:\n   *         - User has signed out on another device.\n   *         - The session has reached its timebox limit or inactivity timeout.\n   *         - User has signed in on another device with single session per user enabled.\n   *         - Check the [User Sessions](/docs/guides/auth/sessions) docs for more information.\n   *     - Use this to clean up any local storage your application has associated with the user.\n   *   - `TOKEN_REFRESHED`\n   *     - Emitted each time a new access and refresh token are fetched for the signed in user.\n   *     - It's best practice and highly recommended to extract the access token (JWT) and store it in memory for further use in your application.\n   *       - Avoid frequent calls to `supabase.auth.getSession()` for the same purpose.\n   *     - There is a background process that keeps track of when the session should be refreshed so you will always receive valid tokens by listening to this event.\n   *     - The frequency of this event is related to the JWT expiry limit configured on your project.\n   *   - `USER_UPDATED`\n   *     - Emitted each time the `supabase.auth.updateUser()` method finishes successfully. Listen to it to update your application's UI based on new profile information.\n   *   - `PASSWORD_RECOVERY`\n   *     - Emitted instead of the `SIGNED_IN` event when the user lands on a page that includes a password recovery link in the URL.\n   *     - Use it to show a UI to the user where they can [reset their password](/docs/guides/auth/passwords#resetting-a-users-password-forgot-password).\n   *\n   * @example Listen to auth changes\n   * ```js\n   * const { data } = supabase.auth.onAuthStateChange((event, session) =\u003e {\n   *   console.log(event, session)\n   *\n   *   if (event === 'INITIAL_SESSION') {\n   *     // handle initial session\n   *   } else if (event === 'SIGNED_IN') {\n   *     // handle sign in event\n   *   } else if (event === 'SIGNED_OUT') {\n   *     // handle sign out event\n   *   } else if (event === 'PASSWORD_RECOVERY') {\n   *     // handle password recovery event\n   *   } else if (event === 'TOKEN_REFRESHED') {\n   *     // handle token refreshed event\n   *   } else if (event === 'USER_UPDATED') {\n   *     // handle user updated event\n   *   }\n   * })\n   *\n   * // call unsubscribe to remove the callback\n   * data.subscription.unsubscribe()\n   * ```\n   *\n   * @exampleDescription Listen to sign out\n   * Make sure you clear out any local data, such as local and session storage, after the client library has detected the user's sign out.\n   *\n   * @example Listen to sign out\n   * ```js\n   * supabase.auth.onAuthStateChange((event, session) =\u003e {\n   *   if (event === 'SIGNED_OUT') {\n   *     console.log('SIGNED_OUT', session)\n   *\n   *     // clear local and session storage\n   *     [\n   *       window.localStorage,\n   *       window.sessionStorage,\n   *     ].forEach((storage) =\u003e {\n   *       Object.entries(storage)\n   *         .forEach(([key]) =\u003e {\n   *           storage.removeItem(key)\n   *         })\n   *     })\n   *   }\n   * })\n   * ```\n   *\n   * @exampleDescription Store OAuth provider tokens on sign in\n   * When using [OAuth (social sign-in)](/docs/guides/auth/social-sign-in) you sometimes wish to get access to the provider's access token and refresh token, in order to call provider APIs in the name of the user.\n   *\n   * For example, if you are using [Sign in with Google](/docs/guides/auth/social-sign-in/auth-google) you may want to use the provider token to call Google APIs on behalf of the user. Supabase Auth does not keep track of the provider access and refresh token, but does return them for you once, immediately after sign in. You can use the `onAuthStateChange` method to listen for the presence of the provider tokens and store them in local storage. You can further send them to your server's APIs for use on the backend.\n   *\n   * Finally, make sure you remove them from local storage on the `SIGNED_OUT` event. If the OAuth provider supports token revocation, make sure you call those APIs either from the frontend or schedule them to be called on the backend.\n   *\n   * @example Store OAuth provider tokens on sign in\n   * ```js\n   * // Register this immediately after calling createClient!\n   * // Because signInWithOAuth causes a redirect, you need to fetch the\n   * // provider tokens from the callback.\n   * supabase.auth.onAuthStateChange((event, session) =\u003e {\n   *   if (session \u0026\u0026 session.provider_token) {\n   *     window.localStorage.setItem('oauth_provider_token', session.provider_token)\n   *   }\n   *\n   *   if (session \u0026\u0026 session.provider_refresh_token) {\n   *     window.localStorage.setItem('oauth_provider_refresh_token', session.provider_refresh_token)\n   *   }\n   *\n   *   if (event === 'SIGNED_OUT') {\n   *     window.localStorage.removeItem('oauth_provider_token')\n   *     window.localStorage.removeItem('oauth_provider_refresh_token')\n   *   }\n   * })\n   * ```\n   *\n   * @exampleDescription Use React Context for the User's session\n   * Instead of relying on `supabase.auth.getSession()` within your React components, you can use a [React Context](https://react.dev/reference/react/createContext) to store the latest session information from the `onAuthStateChange` callback and access it that way.\n   *\n   * @example Use React Context for the User's session\n   * ```js\n   * const SessionContext = React.createContext(null)\n   *\n   * function main() {\n   *   const [session, setSession] = React.useState(null)\n   *\n   *   React.useEffect(() =\u003e {\n   *     const {data: { subscription }} = supabase.auth.onAuthStateChange(\n   *       (event, session) =\u003e {\n   *         if (event === 'SIGNED_OUT') {\n   *           setSession(null)\n   *         } else if (session) {\n   *           setSession(session)\n   *         }\n   *       })\n   *\n   *     return () =\u003e {\n   *       subscription.unsubscribe()\n   *     }\n   *   }, [])\n   *\n   *   return (\n   *     \u003cSessionContext.Provider value={session}\u003e\n   *       \u003cApp /\u003e\n   *     \u003c/SessionContext.Provider\u003e\n   *   )\n   * }\n   * ```\n   *\n   * @example Listen to password recovery events\n   * ```js\n   * supabase.auth.onAuthStateChange((event, session) =\u003e {\n   *   if (event === 'PASSWORD_RECOVERY') {\n   *     console.log('PASSWORD_RECOVERY', session)\n   *     // show screen to update user's password\n   *     showPasswordResetScreen(true)\n   *   }\n   * })\n   * ```\n   *\n   * @example Listen to sign in\n   * ```js\n   * supabase.auth.onAuthStateChange((event, session) =\u003e {\n   *   if (event === 'SIGNED_IN') console.log('SIGNED_IN', session)\n   * })\n   * ```\n   *\n   * @example Listen to token refresh\n   * ```js\n   * supabase.auth.onAuthStateChange((event, session) =\u003e {\n   *   if (event === 'TOKEN_REFRESHED') console.log('TOKEN_REFRESHED', session)\n   * })\n   * ```\n   *\n   * @example Listen to user updates\n   * ```js\n   * supabase.auth.onAuthStateChange((event, session) =\u003e {\n   *   if (event === 'USER_UPDATED') console.log('USER_UPDATED', session)\n   * })\n   * ```\n   */\n  onAuthStateChange(\n    callback: (event: AuthChangeEvent, session: Session | null) =\u003e void | Promise\u003cvoid\u003e\n  ): {\n    data: { subscription: Subscription }\n  } {\n    const id: string | symbol = generateCallbackId()\n    const subscription: Subscription = {\n      id,\n      callback,\n      unsubscribe: () =\u003e {\n        this._debug('#unsubscribe()', 'state change callback with id removed', id)\n\n        this.stateChangeEmitters.delete(id)\n      },\n    }\n\n    this._debug('#onAuthStateChange()', 'registered callback with id', id)\n\n    this.stateChangeEmitters.set(id, subscription)\n    ;(async () =\u003e {\n      await this.initializePromise\n\n      if (this.lock != null) {\n        // TODO(v3): remove legacy lock path\n        await this._acquireLock(this.lockAcquireTimeout, async () =\u003e {\n          this._emitInitialSession(id)\n        })\n      } else {\n        await this._emitInitialSession(id)\n      }\n    })()\n\n    return { data: { subscription } }\n  }\n\n  private async _emitInitialSession(id: string | symbol): Promise\u003cvoid\u003e {\n    return await this._useSession(async (result) =\u003e {\n      try {\n        const {\n          data: { session },\n          error,\n        } = result\n        if (error) throw error\n\n        await this.stateChangeEmitters.get(id)?.callback('INITIAL_SESSION', session)\n        this._debug('INITIAL_SESSION', 'callback id', id, 'session', session)\n      } catch (err) {\n        await this.stateChangeEmitters.get(id)?.callback('INITIAL_SESSION', null)\n        this._debug('INITIAL_SESSION', 'callback id', id, 'error', err)\n        if (isAuthRefreshDiscardedError(err)) {\n          // Same successful no-op _recoverAndRefresh treats as debug-only: the\n          // commit guard discarded a refresh because a concurrent signOut\n          // changed session state mid-flight.\n          return\n        }\n        if (\n          isAuthSessionMissingError(err) ||\n          isAuthRetryableFetchError(err) ||\n          (isAuthApiError(err) \u0026\u0026\n            (err.code === 'refresh_token_not_found' ||\n              err.code === 'refresh_token_already_used' ||\n              err.code === 'session_expired'))\n        ) {\n          // A missing session, a transient/aborted network failure (e.g. a\n          // superseded page navigation cancelling the in-flight request), or\n          // a dead refresh token (e.g. stale SSR cookies) is not an\n          // application error — warn rather than surface it raw.\n          console.warn(err)\n        } else {\n          console.error(err)\n        }\n      }\n    })\n  }\n\n  /**\n   * Sends a password reset request to an email address. This method supports the PKCE flow.\n   *\n   * @param email The email address of the user.\n   * @param options.redirectTo The URL to send the user to after they click the password reset link.\n   * @param options.captchaToken Verification token received when the user completes the captcha on the site.\n   *\n   * @category Auth\n   *\n   * @remarks\n   * - The password reset flow consist of 2 broad steps: (i) Allow the user to login via the password reset link; (ii) Update the user's password.\n   * - The `resetPasswordForEmail()` only sends a password reset link to the user's email.\n   * To update the user's password, see [`updateUser()`](/docs/reference/javascript/auth-updateuser).\n   * - A `PASSWORD_RECOVERY` event will be emitted when the password recovery link is clicked.\n   * You can use [`onAuthStateChange()`](/docs/reference/javascript/auth-onauthstatechange) to listen and invoke a callback function on these events.\n   * - When the user clicks the reset link in the email they are redirected back to your application.\n   * You can configure the URL that the user is redirected to with the `redirectTo` parameter.\n   * See [redirect URLs and wildcards](/docs/guides/auth/redirect-urls#use-wildcards-in-redirect-urls) to add additional redirect URLs to your project.\n   * - After the user has been redirected successfully, prompt them for a new password and call `updateUser()`:\n   * ```js\n   * const { data, error } = await supabase.auth.updateUser({\n   *   password: new_password\n   * })\n   * ```\n   *\n   * @example Reset password\n   * ```js\n   * const { data, error } = await supabase.auth.resetPasswordForEmail(email, {\n   *   redirectTo: 'https://example.com/update-password',\n   * })\n   * ```\n   *\n   * @exampleResponse Reset password\n   * ```json\n   * {\n   *   data: {}\n   *   error: null\n   * }\n   * ```\n   *\n   * @example Reset password (React)\n   * ```js\n   * /**\n   *  * Step 1: Send the user an email to get a password reset token.\n   *  * This email contains a link which sends the user back to your application.\n   *  *\\/\n   * const { data, error } = await supabase.auth\n   *   .resetPasswordForEmail('user@email.com')\n   *\n   * /**\n   *  * Step 2: Once the user is redirected back to your application,\n   *  * ask the user to reset their password.\n   *  *\\/\n   *  useEffect(() =\u003e {\n   *    supabase.auth.onAuthStateChange(async (event, session) =\u003e {\n   *      if (event == \"PASSWORD_RECOVERY\") {\n   *        const newPassword = prompt(\"What would you like your new password to be?\");\n   *        const { data, error } = await supabase.auth\n   *          .updateUser({ password: newPassword })\n   *\n   *        if (data) alert(\"Password updated successfully!\")\n   *        if (error) alert(\"There was an error updating your password.\")\n   *      }\n   *    })\n   *  }, [])\n   * ```\n   */\n  async resetPasswordForEmail(\n    email: string,\n    options: {\n      redirectTo?: string\n      captchaToken?: string\n    } = {}\n  ): Promise\u003c\n    | {\n        data: {}\n        error: null\n      }\n    | { data: null; error: AuthError }\n  \u003e {\n    let codeChallenge: string | null = null\n    let codeChallengeMethod: string | null = null\n    let flowId: string | null = null\n\n    if (this.flowType === 'pkce') {\n      ;[codeChallenge, codeChallengeMethod, flowId] = await this._getCodeChallengeAndMethod(\n        true // isPasswordRecovery\n      )\n    }\n    try {\n      return await _request(this.fetch, 'POST', `${this.url}/recover`, {\n        body: {\n          email,\n          code_challenge: codeChallenge,\n          code_challenge_method: codeChallengeMethod,\n          gotrue_meta_security: { captcha_token: options.captchaToken },\n        },\n        headers: this.headers,\n        redirectTo: this._maybeAppendFlowIdToRedirect(options.redirectTo, flowId),\n      })\n    } catch (error) {\n      await removePKCEVerifier(this.storage, this.storageKey, flowId)\n      if (isAuthError(error)) {\n        return this._returnResult({ data: null, error })\n      }\n\n      throw error\n    }\n  }\n\n  /**\n   * Gets all the identities linked to a user.\n   *\n   * @category Auth\n   *\n   * @remarks\n   * - The user needs to be signed in to call `getUserIdentities()`.\n   *\n   * @example Returns a list of identities linked to the user\n   * ```js\n   * const { data, error } = await supabase.auth.getUserIdentities()\n   * ```\n   *\n   * @exampleResponse Returns a list of identities linked to the user\n   * ```json\n   * {\n   *   \"data\": {\n   *     \"identities\": [\n   *       {\n   *         \"identity_id\": \"22222222-2222-2222-2222-222222222222\",\n   *         \"id\": \"2024-01-01T00:00:00Z\",\n   *         \"user_id\": \"2024-01-01T00:00:00Z\",\n   *         \"identity_data\": {\n   *           \"email\": \"example@email.com\",\n   *           \"email_verified\": false,\n   *           \"phone_verified\": false,\n   *           \"sub\": \"11111111-1111-1111-1111-111111111111\"\n   *         },\n   *         \"provider\": \"email\",\n   *         \"last_sign_in_at\": \"2024-01-01T00:00:00Z\",\n   *         \"created_at\": \"2024-01-01T00:00:00Z\",\n   *         \"updated_at\": \"2024-01-01T00:00:00Z\",\n   *         \"email\": \"example@email.com\"\n   *       }\n   *     ]\n   *   },\n   *   \"error\": null\n   * }\n   * ```\n   */\n  async getUserIdentities(): Promise\u003c\n    | {\n        data: {\n          identities: UserIdentity[]\n        }\n        error: null\n      }\n    | { data: null; error: AuthError }\n  \u003e {\n    try {\n      const { data, error } = await this.getUser()\n      if (error) throw error\n      return this._returnResult({ data: { identities: data.user.identities ?? [] }, error: null })\n    } catch (error) {\n      if (isAuthError(error)) {\n        return this._returnResult({ data: null, error })\n      }\n      throw error\n    }\n  }\n\n  /**\n   * Links an oauth identity to an existing user.\n   * This method supports the PKCE flow.\n   */\n  async linkIdentity(credentials: SignInWithOAuthCredentials): Promise\u003cOAuthResponse\u003e\n\n  /**\n   * Links an OIDC identity to an existing user.\n   */\n  async linkIdentity(credentials: SignInWithIdTokenCredentials): Promise\u003cAuthTokenResponse\u003e\n\n  /**  *\n   * @category Auth\n   *\n   * @remarks\n   * - The **Enable Manual Linking** option must be enabled from your [project's authentication settings](/dashboard/project/_/auth/providers).\n   * - The user needs to be signed in to call `linkIdentity()`.\n   * - If the candidate identity is already linked to the existing user or another user, `linkIdentity()` will fail.\n   * - If `linkIdentity` is run in the browser, the user is automatically redirected to the returned URL. On the server, you should handle the redirect.\n   *\n   * @example Link an identity to a user\n   * ```js\n   * const { data, error } = await supabase.auth.linkIdentity({\n   *   provider: 'github'\n   * })\n   * ```\n   *\n   * @exampleResponse Link an identity to a user\n   * ```json\n   * {\n   *   data: {\n   *     provider: 'github',\n   *     url: \u003cPROVIDER_URL_TO_REDIRECT_TO\u003e,\n   *     flowId: \u003cPKCE_FLOW_ID_OR_NULL\u003e\n   *   },\n   *   error: null\n   * }\n   * ```\n   */\n  async linkIdentity(credentials: any): Promise\u003cany\u003e {\n    if ('token' in credentials) {\n      return this.linkIdentityIdToken(credentials)\n    }\n\n    return this.linkIdentityOAuth(credentials)\n  }\n\n  private async linkIdentityOAuth(credentials: SignInWithOAuthCredentials): Promise\u003cOAuthResponse\u003e {\n    let flowId: string | null = null\n    try {\n      const { data, error } = await this._useSession(async (result) =\u003e {\n        const { data, error } = result\n        if (error) throw error\n        const { url, flowId: urlFlowId } = await this._getUrlForProvider(\n          `${this.url}/user/identities/authorize`,\n          credentials.provider,\n          {\n            redirectTo: credentials.options?.redirectTo,\n            scopes: credentials.options?.scopes,\n            queryParams: credentials.options?.queryParams,\n            skipBrowserRedirect: true,\n          }\n        )\n        flowId = urlFlowId\n        return await _request(this.fetch, 'GET', url, {\n          headers: this.headers,\n          jwt: data.session?.access_token ?? undefined,\n        })\n      })\n      if (error) throw error\n      if (isBrowser() \u0026\u0026 !credentials.options?.skipBrowserRedirect) {\n        window.location.assign(data?.url)\n      }\n      return this._returnResult({\n        data: { provider: credentials.provider, url: data?.url, flowId },\n        error: null,\n      })\n    } catch (error) {\n      if (isAuthError(error)) {\n        return this._returnResult({\n          data: { provider: credentials.provider, url: null, flowId },\n          error,\n        })\n      }\n      throw error\n    }\n  }\n\n  private async linkIdentityIdToken(\n    credentials: SignInWithIdTokenCredentials\n  ): Promise\u003cAuthTokenResponse\u003e {\n    return await this._useSession(async (result) =\u003e {\n      try {\n        const {\n          error: sessionError,\n          data: { session },\n        } = result\n        if (sessionError) throw sessionError\n\n        const { options, provider, token, access_token, nonce } = credentials\n\n        const res = await _request(this.fetch, 'POST', `${this.url}/token?grant_type=id_token`, {\n          headers: this.headers,\n          jwt: session?.access_token ?? undefined,\n          body: {\n            provider,\n            id_token: token,\n            access_token,\n            nonce,\n            link_identity: true,\n            gotrue_meta_security: { captcha_token: options?.captchaToken },\n          },\n          xform: _sessionResponse,\n        })\n\n        const { data, error } = res\n        if (error) {\n          return this._returnResult({ data: { user: null, session: null }, error })\n        } else if (!data || !data.session || !data.user) {\n          return this._returnResult({\n            data: { user: null, session: null },\n            error: new AuthInvalidTokenResponseError(),\n          })\n        }\n        if (data.session) {\n          await this._saveSession(data.session)\n          await this._notifyAllSubscribers('USER_UPDATED', data.session)\n        }\n        return this._returnResult({ data, error })\n      } catch (error) {\n        await removePKCEVerifier(this.storage, this.storageKey, null)\n        if (isAuthError(error)) {\n          return this._returnResult({ data: { user: null, session: null }, error })\n        }\n        throw error\n      }\n    })\n  }\n\n  /**\n   * Unlinks an identity from a user by deleting it. The user will no longer be able to sign in with that identity once it's unlinked.\n   *\n   * @category Auth\n   *\n   * @remarks\n   * - The **Enable Manual Linking** option must be enabled from your [project's authentication settings](/dashboard/project/_/auth/providers).\n   * - The user needs to be signed in to call `unlinkIdentity()`.\n   * - The user must have at least 2 identities in order to unlink an identity.\n   * - The identity to be unlinked must belong to the user.\n   *\n   * @example Unlink an identity\n   * ```js\n   * // retrieve all identities linked to a user\n   * const identities = await supabase.auth.getUserIdentities()\n   *\n   * // find the google identity\n   * const googleIdentity = identities.find(\n   *   identity =\u003e identity.provider === 'google'\n   * )\n   *\n   * // unlink the google identity\n   * const { error } = await supabase.auth.unlinkIdentity(googleIdentity)\n   * ```\n   */\n  async unlinkIdentity(identity: UserIdentity): Promise\u003c\n    | {\n        data: {}\n        error: null\n      }\n    | { data: null; error: AuthError }\n  \u003e {\n    try {\n      return await this._useSession(async (result) =\u003e {\n        const { data, error } = result\n        if (error) {\n          throw error\n        }\n        return await _request(\n          this.fetch,\n          'DELETE',\n          `${this.url}/user/identities/${identity.identity_id}`,\n          {\n            headers: this.headers,\n            jwt: data.session?.access_token ?? undefined,\n          }\n        )\n      })\n    } catch (error) {\n      if (isAuthError(error)) {\n        return this._returnResult({ data: null, error })\n      }\n      throw error\n    }\n  }\n\n  /**\n   * Generates a new JWT.\n   * @param refreshToken A valid refresh token that was returned on login.\n   */\n  private async _refreshAccessToken(refreshToken: string): Promise\u003cAuthResponse\u003e {\n    // Refresh tokens are long-lived bearer credentials; do NOT include any\n    // fragment of the token in the debug tag, even when `debug: true` is\n    // enabled (logs may be forwarded to third-party services).\n    const debugName = `#_refreshAccessToken()`\n    this._debug(debugName, 'begin')\n\n    try {\n      const startedAt = Date.now()\n\n      // will attempt to refresh the token with exponential backoff\n      return await retryable(\n        async (attempt) =\u003e {\n          if (attempt \u003e 0) {\n            await sleep(200 * Math.pow(2, attempt - 1)) // 200, 400, 800, ...\n          }\n\n          this._debug(debugName, 'refreshing attempt', attempt)\n\n          return await _request(this.fetch, 'POST', `${this.url}/token?grant_type=refresh_token`, {\n            body: { refresh_token: refreshToken },\n            headers: this.headers,\n            xform: _sessionResponse,\n          })\n        },\n        (attempt, error) =\u003e {\n          const nextBackOffInterval = 200 * Math.pow(2, attempt)\n          return (\n            error \u0026\u0026\n            isAuthRetryableFetchError(error) \u0026\u0026\n            // retryable only if the request can be sent before the backoff overflows the tick duration\n            Date.now() + nextBackOffInterval - startedAt \u003c AUTO_REFRESH_TICK_DURATION_MS\n          )\n        }\n      )\n    } catch (error) {\n      this._debug(debugName, 'error', error)\n\n      if (isAuthError(error)) {\n        return this._returnResult({ data: { session: null, user: null }, error })\n      }\n      throw error\n    } finally {\n      this._debug(debugName, 'end')\n    }\n  }\n\n  private _isValidSession(maybeSession: unknown): maybeSession is Session {\n    const isValidSession =\n      typeof maybeSession === 'object' \u0026\u0026\n      maybeSession !== null \u0026\u0026\n      'access_token' in maybeSession \u0026\u0026\n      'refresh_token' in maybeSession \u0026\u0026\n      'expires_at' in maybeSession\n\n    return isValidSession\n  }\n\n  private async _handleProviderSignIn(\n    provider: Provider,\n    options: {\n      redirectTo?: string\n      scopes?: string\n      queryParams?: { [key: string]: string }\n      skipBrowserRedirect?: boolean\n    }\n  ) {\n    const { url, flowId } = await this._getUrlForProvider(`${this.url}/authorize`, provider, {\n      redirectTo: options.redirectTo,\n      scopes: options.scopes,\n      queryParams: options.queryParams,\n    })\n\n    this._debug('#_handleProviderSignIn()', 'provider', provider, 'options', options, 'url', url)\n\n    // try to open on the browser\n    if (isBrowser() \u0026\u0026 !options.skipBrowserRedirect) {\n      window.location.assign(url)\n    }\n\n    return { data: { provider, url, flowId }, error: null }\n  }\n\n  /**\n   * Recovers the session from LocalStorage and refreshes the token\n   * Note: this method is async to accommodate for AsyncStorage e.g. in React native.\n   */\n  private async _recoverAndRefresh() {\n    const debugName = '#_recoverAndRefresh()'\n    this._debug(debugName, 'begin')\n\n    try {\n      const currentSession = (await getItemAsync(this.storage, this.storageKey)) as Session | null\n\n      if (currentSession \u0026\u0026 this.userStorage) {\n        let maybeUser: { user: User | null } | null = (await getItemAsync(\n          this.userStorage,\n          this.storageKey + '-user'\n        )) as any\n\n        if (!this.storage.isServer \u0026\u0026 Object.is(this.storage, this.userStorage) \u0026\u0026 !maybeUser) {\n          // storage and userStorage are the same storage medium, for example\n          // window.localStorage if userStorage does not have the user from\n          // storage stored, store it first thereby migrating the user object\n          // from storage -\u003e userStorage\n\n          maybeUser = { user: currentSession.user }\n          await setItemAsync(this.userStorage, this.storageKey + '-user', maybeUser)\n        }\n\n        currentSession.user = maybeUser?.user ?? userNotAvailableProxy()\n      } else if (currentSession \u0026\u0026 !currentSession.user) {\n        // user storage is not set, let's check if it was previously enabled so\n        // we bring back the storage as it should be\n\n        if (!currentSession.user) {\n          // test if userStorage was previously enabled and the storage medium was the same, to move the user back under the same key\n          const separateUser: { user: User | null } | null = (await getItemAsync(\n            this.storage,\n            this.storageKey + '-user'\n          )) as any\n\n          if (separateUser \u0026\u0026 separateUser?.user) {\n            currentSession.user = separateUser.user\n\n            await removeItemAsync(this.storage, this.storageKey + '-user')\n            await setItemAsync(this.storage, this.storageKey, currentSession)\n          } else {\n            currentSession.user = userNotAvailableProxy()\n          }\n        }\n      }\n\n      this._debug(debugName, 'session from storage', currentSession)\n\n      if (!this._isValidSession(currentSession)) {\n        this._debug(debugName, 'session is not valid')\n        if (currentSession !== null) {\n          await this._removeSession()\n        }\n\n        return\n      }\n\n      const expiresWithMargin =\n        (currentSession.expires_at ?? Infinity) * 1000 - Date.now() \u003c EXPIRY_MARGIN_MS\n\n      this._debug(\n        debugName,\n        `session has${expiresWithMargin ? '' : ' not'} expired with margin of ${EXPIRY_MARGIN_MS}s`\n      )\n\n      if (expiresWithMargin) {\n        if (this.autoRefreshToken \u0026\u0026 currentSession.refresh_token) {\n          const { error } = await this._callRefreshToken(currentSession.refresh_token)\n\n          if (error) {\n            // `_callRefreshToken` is the single source of truth for refresh\n            // outcomes: it removes the session itself when the access token\n            // is actually expired, and preserves it when the token is still\n            // valid (proactive-preserve). Don't second-guess that here — a\n            // local `_removeSession` would emit a duplicate `SIGNED_OUT` on\n            // genuine failures and undo the proactive-preserve at init time.\n            if (isAuthRefreshDiscardedError(error)) {\n              this._debug(debugName, 'refresh discarded by commit guard', error)\n            } else {\n              this._debug(debugName, 'refresh failed', error)\n            }\n          }\n        }\n      } else if (\n        currentSession.user \u0026\u0026\n        (currentSession.user as any).__isUserNotAvailableProxy === true\n      ) {\n        // If we have a proxy user, try to get the real user data\n        try {\n          const { data, error: userError } = await this._getUser(currentSession.access_token)\n\n          if (!userError \u0026\u0026 data?.user) {\n            currentSession.user = data.user\n            await this._saveSession(currentSession)\n            await this._notifyAllSubscribers('SIGNED_IN', currentSession)\n          } else {\n            this._debug(debugName, 'could not get user data, skipping SIGNED_IN notification')\n          }\n        } catch (getUserError) {\n          console.error('Error getting user data:', getUserError)\n          this._debug(\n            debugName,\n            'error getting user data, skipping SIGNED_IN notification',\n            getUserError\n          )\n        }\n      } else {\n        // no need to persist currentSession again, as we just loaded it from\n        // local storage; persisting it again may overwrite a value saved by\n        // another client with access to the same local storage\n        await this._notifyAllSubscribers('SIGNED_IN', currentSession)\n      }\n    } catch (err) {\n      this._debug(debugName, 'error', err)\n\n      if (isAuthRetryableFetchError(err)) {\n        // Transient/aborted network failure during session recovery (e.g. a\n        // superseded page navigation cancelling the in-flight request). Warn\n        // rather than surface it raw; the session is untouched and recovery\n        // will run again on the next load.\n        console.warn(err)\n      } else {\n        console.error(err)\n      }\n      return\n    } finally {\n      this._debug(debugName, 'end')\n    }\n  }\n\n  private async _callRefreshToken(refreshToken: string): Promise\u003cCallRefreshTokenResult\u003e {\n    if (!refreshToken) {\n      throw new AuthSessionMissingError()\n    }\n\n    // refreshing is already in progress\n    if (this.refreshingDeferred) {\n      return this.refreshingDeferred.promise\n    }\n\n    // Serial failure cooldown: callers passing the *same* refresh token\n    // after a recent failure receive the cached result instead of firing\n    // another `/token` request. This caps the proactive-refresh storm\n    // where every `getSession()` call inside the 90s EXPIRY_MARGIN_MS\n    // window kept re-firing against the same broken refresh token during\n    // outages. Concurrent callers already share `refreshingDeferred`; this\n    // cache covers serial callers spaced across cooldown windows.\n    //\n    // Token-keyed so callers with a fresh refresh token (rotation pickup\n    // from another tab, explicit `setSession`/`refreshSession({ refresh_token })`,\n    // multi-account switch) bypass the cache and attempt a real refresh.\n    if (\n      this.lastRefreshFailure \u0026\u0026\n      this.lastRefreshFailure.refreshToken === refreshToken \u0026\u0026\n      Date.now() \u003c this.lastRefreshFailure.expiresAt\n    ) {\n      this._debug('#_callRefreshToken()', 'returning cached failure (cooldown active)')\n      return this.lastRefreshFailure.result\n    }\n\n    // Refresh tokens are long-lived bearer credentials; do NOT include any\n    // fragment of the token in the debug tag, even when `debug: true` is\n    // enabled (logs may be forwarded to third-party services).\n    const debugName = `#_callRefreshToken()`\n\n    this._debug(debugName, 'begin')\n\n    try {\n      this.refreshingDeferred = new Deferred\u003cCallRefreshTokenResult\u003e()\n\n      // Only callers that arrive while this refresh is in flight await the\n      // deferred; the original caller is served by the `throw` in the catch\n      // below. Pre-attach a no-op rejection handler so a failing refresh with\n      // no concurrent callers cannot surface as an unhandled rejection —\n      // concurrent callers attach their own handlers via `.promise` and still\n      // observe the rejection.\n      this.refreshingDeferred.promise.then(undefined, () =\u003e {})\n\n      // Snapshot storage before the fetch. The commit guard discards the\n      // rotated tokens only when a non-null pre-fetch snapshot changed under\n      // us — typical case: a concurrent `signOut` ran `_removeSession`, or\n      // another tab's refresh rewrote the slot. Callers passing\n      // externally-sourced tokens (SSR cookie handoff, multi-account\n      // switching, `setSession`/`refreshSession({ refresh_token })`) may\n      // start from a null snapshot OR from a non-null snapshot whose\n      // refresh_token differs from the one they're hydrating; in both\n      // cases the guard fires only when storage was *modified between\n      // snapshots*, not when the input token disagrees with what's stored.\n      const storedAtStart = (await getItemAsync(this.storage, this.storageKey)) as Session | null\n\n      const { data, error } = await this._refreshAccessToken(refreshToken)\n      if (error) throw error\n      if (!data.session) throw new AuthSessionMissingError()\n\n      const storedAfter = (await getItemAsync(this.storage, this.storageKey)) as Session | null\n      const storageChangedUnderUs =\n        storedAtStart !== null \u0026\u0026\n        (storedAfter === null || storedAfter.refresh_token !== storedAtStart.refresh_token)\n\n      if (storageChangedUnderUs) {\n        this._debug(\n          debugName,\n          'commit guard: storage changed since refresh started, discarding rotated tokens',\n          {\n            // Presence indicators only — never log refresh token fragments,\n            // even partial. Logs may be forwarded to third-party services.\n            startedWith: 'present',\n            nowHolds: storedAfter ? 'replaced' : 'cleared',\n          }\n        )\n        const discarded: CallRefreshTokenResult = {\n          data: null,\n          error: new AuthRefreshDiscardedError(),\n        }\n        this.refreshingDeferred.resolve(discarded)\n        return discarded\n      }\n\n      // Second leg of the commit guard: close the TOCTOU window between the\n      // synchronous `storageChangedUnderUs` check and the actual storage\n      // writes inside `_saveSession`. A concurrent `signOut → _removeSession`\n      // can land inside `_saveSession`'s `await setItemAsync(...)` yields and\n      // clear storage just before we overwrite it. Capture the epoch BEFORE\n      // the save and re-check after; if it advanced, undo the write directly\n      // (do NOT call `_removeSession` — that would emit a duplicate\n      // SIGNED_OUT for the concurrent signOut that already fired one).\n      const epochBeforeSave = this._sessionRemovalEpoch\n\n      await this._saveSession(data.session)\n\n      if (this._sessionRemovalEpoch !== epochBeforeSave) {\n        this._debug(\n          debugName,\n          'commit guard (post-save): _removeSession ran during _saveSession, undoing write'\n        )\n        await removeItemAsync(this.storage, this.storageKey)\n        if (this.userStorage) {\n          await removeItemAsync(this.userStorage, this.storageKey + '-user')\n        }\n        const discarded: CallRefreshTokenResult = {\n          data: null,\n          error: new AuthRefreshDiscardedError(),\n        }\n        this.refreshingDeferred.resolve(discarded)\n        return discarded\n      }\n\n      await this._notifyAllSubscribers('TOKEN_REFRESHED', data.session)\n\n      const result = { data: data.session, error: null }\n\n      // Refresh succeeded — clear any cached failure so the next caller\n      // (including the auto-refresh ticker) attempts a real refresh again.\n      this.lastRefreshFailure = null\n\n      this.refreshingDeferred.resolve(result)\n\n      return result\n    } catch (error) {\n      this._debug(debugName, 'error', error)\n\n      if (isAuthError(error)) {\n        const result = { data: null, error }\n\n        if (!isAuthRetryableFetchError(error)) {\n          // Proactive vs reactive distinction: a refresh fires whenever\n          // the access token is within EXPIRY_MARGIN_MS of expiry. If the\n          // access token is *still valid* at this moment, the refresh was\n          // proactive and the existing session is still usable until its\n          // real expiry — destroying it now would log out a user whose\n          // access token works. If the access token has actually expired,\n          // the refresh token is the only credential left and it just got\n          // rejected — the session is genuinely dead. `__loadSession`\n          // mirrors this distinction on the read path so callers see the\n          // preserved session instead of `session: null`.\n          const storedNow = (await getItemAsync(this.storage, this.storageKey)) as Session | null\n          const accessTokenStillValid = !!(\n            storedNow?.expires_at \u0026\u0026 storedNow.expires_at * 1000 \u003e Date.now()\n          )\n\n          if (accessTokenStillValid) {\n            this._debug(\n              debugName,\n              'proactive refresh failed, access token still valid — preserving session'\n            )\n          } else {\n            await this._removeSession()\n          }\n        }\n\n        // Cache the failure so serial callers (and the next auto-refresh\n        // tick) passing the same refresh token within the cooldown window\n        // receive it synchronously instead of firing another `/token`\n        // call. Set after the optional `_removeSession` above (which\n        // clears the cache as part of teardown) so the cache survives.\n        this.lastRefreshFailure = {\n          refreshToken,\n          result,\n          expiresAt: Date.now() + REFRESH_FAILURE_COOLDOWN_MS,\n        }\n\n        this.refreshingDeferred?.resolve(result)\n\n        return result\n      }\n\n      this.refreshingDeferred?.reject(error)\n      throw error\n    } finally {\n      this.refreshingDeferred = null\n      this._debug(debugName, 'end')\n    }\n  }\n\n  private async _notifyAllSubscribers(\n    event: AuthChangeEvent,\n    session: Session | null,\n    broadcast = true\n  ) {\n    if (this._pendingInitNotifications !== null \u0026\u0026 broadcast) {\n      // We're inside initialize() before initializePromise has resolved, and\n      // this notification originates from the init chain (_recoverAndRefresh),\n      // which always fires with broadcast = true. Enqueue instead of firing so\n      // that callbacks can safely call getSession() / getUser() without\n      // deadlocking on initializePromise.\n      //\n      // Notifications with broadcast = false come from the incoming\n      // BroadcastChannel handler (a cross-tab event), not the init chain, so\n      // they are fired immediately to preserve multi-tab ordering.\n      this._pendingInitNotifications.push({ event, session, broadcast })\n      return\n    }\n\n    const debugName = `#_notifyAllSubscribers(${event})`\n    this._debug(debugName, 'begin', session, `broadcast = ${broadcast}`)\n\n    try {\n      if (this.broadcastChannel \u0026\u0026 broadcast) {\n        this.broadcastChannel.postMessage({ event, session })\n      }\n\n      const errors: unknown[] = []\n      const promises = Array.from(this.stateChangeEmitters.values()).map(async (x) =\u003e {\n        try {\n          await x.callback(event, session)\n        } catch (e) {\n          errors.push(e)\n        }\n      })\n\n      await Promise.all(promises)\n\n      if (errors.length \u003e 0) {\n        for (let i = 0; i \u003c errors.length; i += 1) {\n          console.error(errors[i])\n        }\n\n        throw errors[0]\n      }\n    } finally {\n      this._debug(debugName, 'end')\n    }\n  }\n\n  /**\n   * set currentSession and currentUser\n   * process to _startAutoRefreshToken if possible\n   */\n  private async _saveSession(session: Session) {\n    this._debug('#_saveSession()', session)\n    // _saveSession is always called whenever a new session has been acquired\n    // so we can safely suppress the warning returned by future getSession calls\n    this.suppressGetSessionWarning = true\n    // Create a shallow copy to work with, to avoid mutating the original session object if it's used elsewhere\n    const sessionToProcess = { ...session }\n\n    const userIsProxy =\n      sessionToProcess.user \u0026\u0026 (sessionToProcess.user as any).__isUserNotAvailableProxy === true\n    if (this.userStorage) {\n      if (!userIsProxy \u0026\u0026 sessionToProcess.user) {\n        // If it's a real user object, save it to userStorage.\n        await setItemAsync(this.userStorage, this.storageKey + '-user', {\n          user: sessionToProcess.user,\n        })\n      } else if (userIsProxy) {\n        // If it's the proxy, it means user was not found in userStorage.\n        // We should ensure no stale user data for this key exists in userStorage if we were to save null,\n        // or simply not save the proxy. For now, we don't save the proxy here.\n        // If there's a need to clear userStorage if user becomes proxy, that logic would go here.\n      }\n\n      // Prepare the main session data for primary storage: remove the user property before cloning\n      // This is important because the original session.user might be the proxy\n      const mainSessionData: Omit\u003cSession, 'user'\u003e \u0026 { user?: User } = { ...sessionToProcess }\n      delete mainSessionData.user // Remove user (real or proxy) before cloning for main storage\n\n      const clonedMainSessionData = deepClone(mainSessionData)\n      await setItemAsync(this.storage, this.storageKey, clonedMainSessionData)\n    } else {\n      // No userStorage is configured.\n      // In this case, session.user should ideally not be a proxy.\n      // If it were, structuredClone would fail. This implies an issue elsewhere if user is a proxy here\n      const clonedSession = deepClone(sessionToProcess) // sessionToProcess still has its original user property\n      await setItemAsync(this.storage, this.storageKey, clonedSession)\n    }\n  }\n\n  private async _removeSession() {\n    // Bump synchronously, BEFORE any `await`, so that `_callRefreshToken`'s\n    // post-save check sees the increment whenever this method has started —\n    // even if it hasn't finished. Pairs with the epoch check in\n    // `_callRefreshToken`. See `_sessionRemovalEpoch` field doc.\n    this._sessionRemovalEpoch += 1\n    this._debug('#_removeSession()')\n\n    // The session is gone — no point holding on to a cached refresh failure\n    // for a token that no longer exists. Synchronous, before any `await`.\n    this.lastRefreshFailure = null\n\n    this.suppressGetSessionWarning = false\n\n    await removeItemAsync(this.storage, this.storageKey)\n    await removeAllPKCEVerifiers(this.storage, this.storageKey)\n    await removeItemAsync(this.storage, this.storageKey + '-user')\n\n    if (this.userStorage) {\n      await removeItemAsync(this.userStorage, this.storageKey + '-user')\n    }\n\n    await this._notifyAllSubscribers('SIGNED_OUT', null)\n  }\n\n  /**\n   * Removes any registered visibilitychange callback.\n   *\n   * {@link GoTrueClient.startAutoRefresh}\n   * {@link GoTrueClient.stopAutoRefresh}\n   */\n  private _removeVisibilityChangedCallback() {\n    this._debug('#_removeVisibilityChangedCallback()')\n\n    const callback = this.visibilityChangedCallback\n    this.visibilityChangedCallback = null\n\n    try {\n      if (callback \u0026\u0026 isBrowser() \u0026\u0026 window?.removeEventListener) {\n        window.removeEventListener('visibilitychange', callback)\n      }\n    } catch (e) {\n      console.error('removing visibilitychange callback failed', e)\n    }\n  }\n\n  /**\n   * This is the private implementation of {@link GoTrueClient.startAutoRefresh}. Use this\n   * within the library.\n   */\n  private async _startAutoRefresh() {\n    await this._stopAutoRefresh()\n\n    this._debug('#_startAutoRefresh()')\n\n    const ticker = setInterval(() =\u003e this._autoRefreshTokenTick(), AUTO_REFRESH_TICK_DURATION_MS)\n    this.autoRefreshTicker = ticker\n\n    if (ticker \u0026\u0026 typeof ticker === 'object' \u0026\u0026 typeof ticker.unref === 'function') {\n      // ticker is a NodeJS Timeout object that has an `unref` method\n      // https://nodejs.org/api/timers.html#timeoutunref\n      // When auto refresh is used in NodeJS (like for testing) the\n      // `setInterval` is preventing the process from being marked as\n      // finished and tests run endlessly. This can be prevented by calling\n      // `unref()` on the returned object.\n      ticker.unref()\n      // @ts-expect-error TS has no context of Deno\n    } else if (typeof Deno !== 'undefined' \u0026\u0026 typeof Deno.unrefTimer === 'function') {\n      // similar like for NodeJS, but with the Deno API\n      // https://deno.land/api@latest?unstable\u0026s=Deno.unrefTimer\n      // @ts-expect-error TS has no context of Deno\n      Deno.unrefTimer(ticker)\n    }\n\n    // run the tick immediately, but in the next pass of the event loop so that\n    // #_initialize can be allowed to complete without recursively waiting on\n    // itself\n    const timeout = setTimeout(async () =\u003e {\n      await this.initializePromise\n      await this._autoRefreshTokenTick()\n    }, 0)\n    this.autoRefreshTickTimeout = timeout\n\n    if (timeout \u0026\u0026 typeof timeout === 'object' \u0026\u0026 typeof timeout.unref === 'function') {\n      timeout.unref()\n      // @ts-expect-error TS has no context of Deno\n    } else if (typeof Deno !== 'undefined' \u0026\u0026 typeof Deno.unrefTimer === 'function') {\n      // @ts-expect-error TS has no context of Deno\n      Deno.unrefTimer(timeout)\n    }\n  }\n\n  /**\n   * This is the private implementation of {@link GoTrueClient.stopAutoRefresh}. Use this\n   * within the library.\n   */\n  private async _stopAutoRefresh() {\n    this._debug('#_stopAutoRefresh()')\n\n    const ticker = this.autoRefreshTicker\n    this.autoRefreshTicker = null\n\n    if (ticker) {\n      clearInterval(ticker)\n    }\n\n    const timeout = this.autoRefreshTickTimeout\n    this.autoRefreshTickTimeout = null\n\n    if (timeout) {\n      clearTimeout(timeout)\n    }\n  }\n\n  /**\n   * Starts an auto-refresh process in the background. The session is checked\n   * every few seconds. Close to the time of expiration a process is started to\n   * refresh the session. If refreshing fails it will be retried for as long as\n   * necessary.\n   *\n   * If you set the {@link GoTrueClientOptions#autoRefreshToken} you don't need\n   * to call this function, it will be called for you.\n   *\n   * On browsers the refresh process works only when the tab/window is in the\n   * foreground to conserve resources as well as prevent race conditions and\n   * flooding auth with requests. If you call this method any managed\n   * visibility change callback will be removed and you must manage visibility\n   * changes on your own.\n   *\n   * On non-browser platforms the refresh process works *continuously* in the\n   * background, which may not be desirable. You should hook into your\n   * platform's foreground indication mechanism and call these methods\n   * appropriately to conserve resources.\n   *\n   * {@link GoTrueClient.stopAutoRefresh}\n   *\n   * @category Auth\n   *\n   * @remarks\n   * - Only useful in non-browser environments such as React Native or Electron.\n   * - The Supabase Auth library automatically starts and stops proactively refreshing the session when a tab is focused or not.\n   * - On non-browser platforms, such as mobile or desktop apps built with web technologies, the library is not able to effectively determine whether the application is _focused_ or not.\n   * - To give this hint to the application, you should be calling this method when the app is in focus and calling `supabase.auth.stopAutoRefresh()` when it's out of focus.\n   *\n   * @example Start and stop auto refresh in React Native\n   * ```js\n   * import { AppState } from 'react-native'\n   *\n   * // make sure you register this only once!\n   * AppState.addEventListener('change', (state) =\u003e {\n   *   if (state === 'active') {\n   *     supabase.auth.startAutoRefresh()\n   *   } else {\n   *     supabase.auth.stopAutoRefresh()\n   *   }\n   * })\n   * ```\n   */\n  async startAutoRefresh() {\n    this._removeVisibilityChangedCallback()\n    await this._startAutoRefresh()\n  }\n\n  /**\n   * Stops an active auto refresh process running in the background (if any).\n   *\n   * If you call this method any managed visibility change callback will be\n   * removed and you must manage visibility changes on your own.\n   *\n   * See {@link GoTrueClient.startAutoRefresh} for more details.\n   *\n   * @category Auth\n   *\n   * @remarks\n   * - Only useful in non-browser environments such as React Native or Electron.\n   * - The Supabase Auth library automatically starts and stops proactively refreshing the session when a tab is focused or not.\n   * - On non-browser platforms, such as mobile or desktop apps built with web technologies, the library is not able to effectively determine whether the application is _focused_ or not.\n   * - When your application goes in the background or out of focus, call this method to stop the proactive refreshing of the session.\n   *\n   * @example Start and stop auto refresh in React Native\n   * ```js\n   * import { AppState } from 'react-native'\n   *\n   * // make sure you register this only once!\n   * AppState.addEventListener('change', (state) =\u003e {\n   *   if (state === 'active') {\n   *     supabase.auth.startAutoRefresh()\n   *   } else {\n   *     supabase.auth.stopAutoRefresh()\n   *   }\n   * })\n   * ```\n   */\n  async stopAutoRefresh() {\n    this._removeVisibilityChangedCallback()\n    await this._stopAutoRefresh()\n  }\n\n  /**\n   * Tears down the client's background work: stops the auto-refresh interval,\n   * removes the `visibilitychange` listener, closes the cross-tab\n   * `BroadcastChannel`, and clears registered `onAuthStateChange` subscribers.\n   *\n   * Call this from cleanup hooks when the client is being replaced before\n   * its JS realm is destroyed. React Strict Mode and HMR are the common\n   * cases. Any in-flight `fetch` calls continue to completion and may still\n   * write to storage; dispose doesn't abort them or erase storage.\n   *\n   * Lifecycle caveat: because in-flight refreshes are not aborted, a\n   * disposed instance can still persist a rotated session to storage after\n   * `dispose()` returns. A subsequent `createClient` against the same\n   * `storageKey` will pick up that session on its next read. If you need\n   * strict isolation between client lifecycles, await any pending auth\n   * operation before calling `dispose()` (or change the `storageKey` for\n   * the replacement client).\n   *\n   * Safe to call repeatedly.\n   *\n   * @category Auth\n   *\n   * @example Cleanup on React unmount\n   * ```ts\n   * useEffect(() =\u003e {\n   *   const client = createClient(...)\n   *   return () =\u003e { client.auth.dispose() }\n   * }, [])\n   * ```\n   */\n  async dispose(): Promise\u003cvoid\u003e {\n    this._removeVisibilityChangedCallback()\n    await this._stopAutoRefresh()\n    this.broadcastChannel?.close()\n    this.broadcastChannel = null\n    this.stateChangeEmitters.clear()\n  }\n\n  /**\n   * Runs the auto refresh token tick.\n   */\n  private async _autoRefreshTokenTick() {\n    this._debug('#_autoRefreshTokenTick()', 'begin')\n\n    if (this.lock != null) {\n      // TODO(v3): remove legacy lock path. Uses `_acquireLock(0, ...)` which\n      // throws `LockAcquireTimeoutError` immediately if the lock is held —\n      // that's the fail-fast skip path that lets the tick bail out instead\n      // of queuing behind a long-running operation.\n      try {\n        await this._acquireLock(0, async () =\u003e {\n          try {\n            const now = Date.now()\n            try {\n              return await this._useSession(async (result) =\u003e {\n                const {\n                  data: { session },\n                } = result\n\n                if (!session || !session.refresh_token || !session.expires_at) {\n                  this._debug('#_autoRefreshTokenTick()', 'no session')\n                  return\n                }\n\n                const expiresInTicks = Math.floor(\n                  (session.expires_at * 1000 - now) / AUTO_REFRESH_TICK_DURATION_MS\n                )\n\n                this._debug(\n                  '#_autoRefreshTokenTick()',\n                  `access token expires in ${expiresInTicks} ticks, a tick lasts ${AUTO_REFRESH_TICK_DURATION_MS}ms, refresh threshold is ${AUTO_REFRESH_TICK_THRESHOLD} ticks`\n                )\n\n                if (expiresInTicks \u003c= AUTO_REFRESH_TICK_THRESHOLD) {\n                  await this._callRefreshToken(session.refresh_token)\n                }\n              })\n            } catch (e) {\n              console.error(\n                'Auto refresh tick failed with error. This is likely a transient error.',\n                e\n              )\n            }\n          } finally {\n            this._debug('#_autoRefreshTokenTick()', 'end')\n          }\n        })\n      } catch (e) {\n        if (e instanceof LockAcquireTimeoutError) {\n          this._debug('auto refresh token tick lock not available')\n        } else {\n          throw e\n        }\n      }\n      return\n    }\n\n    // Lockless default: skip if a refresh is already in flight.\n    // `_callRefreshToken` also dedupes via the same field; this is just a\n    // fast-path skip to avoid an unnecessary storage read.\n    if (this.refreshingDeferred !== null) {\n      this._debug('#_autoRefreshTokenTick()', 'refresh already in flight, skipping')\n      return\n    }\n\n    try {\n      const now = Date.now()\n\n      try {\n        await this._useSession(async (result) =\u003e {\n          const {\n            data: { session },\n          } = result\n\n          if (!session || !session.refresh_token || !session.expires_at) {\n            this._debug('#_autoRefreshTokenTick()', 'no session')\n            return\n          }\n\n          // session will expire in this many ticks (or has already expired if \u003c= 0)\n          const expiresInTicks = Math.floor(\n            (session.expires_at * 1000 - now) / AUTO_REFRESH_TICK_DURATION_MS\n          )\n\n          this._debug(\n            '#_autoRefreshTokenTick()',\n            `access token expires in ${expiresInTicks} ticks, a tick lasts ${AUTO_REFRESH_TICK_DURATION_MS}ms, refresh threshold is ${AUTO_REFRESH_TICK_THRESHOLD} ticks`\n          )\n\n          if (expiresInTicks \u003c= AUTO_REFRESH_TICK_THRESHOLD) {\n            await this._callRefreshToken(session.refresh_token)\n          }\n        })\n      } catch (e) {\n        console.error('Auto refresh tick failed with error. This is likely a transient error.', e)\n      }\n    } finally {\n      this._debug('#_autoRefreshTokenTick()', 'end')\n    }\n  }\n\n  /**\n   * Registers callbacks on the browser / platform, which in-turn run\n   * algorithms when the browser window/tab are in foreground. On non-browser\n   * platforms it assumes always foreground.\n   */\n  private async _handleVisibilityChange() {\n    this._debug('#_handleVisibilityChange()')\n\n    if (!isBrowser() || !window?.addEventListener) {\n      if (this.autoRefreshToken) {\n        // in non-browser environments the refresh token ticker runs always\n        this.startAutoRefresh()\n      }\n\n      return false\n    }\n\n    try {\n      this.visibilityChangedCallback = async () =\u003e {\n        try {\n          await this._onVisibilityChanged(false)\n        } catch (error) {\n          this._debug('#visibilityChangedCallback', 'error', error)\n        }\n      }\n\n      window?.addEventListener('visibilitychange', this.visibilityChangedCallback)\n\n      // now immediately call the visbility changed callback to setup with the\n      // current visbility state\n      await this._onVisibilityChanged(true) // initial call\n    } catch (error) {\n      console.error('_handleVisibilityChange', error)\n    }\n  }\n\n  /**\n   * Callback registered with `window.addEventListener('visibilitychange')`.\n   */\n  private async _onVisibilityChanged(calledFromInitialize: boolean) {\n    const methodName = `#_onVisibilityChanged(${calledFromInitialize})`\n    this._debug(methodName, 'visibilityState', document.visibilityState)\n\n    if (document.visibilityState === 'visible') {\n      if (this.autoRefreshToken) {\n        // in browser environments the refresh token ticker runs only on focused tabs\n        // which prevents race conditions\n        this._startAutoRefresh()\n      }\n\n      if (!calledFromInitialize) {\n        // called when the visibility has changed, i.e. the browser\n        // transitioned from hidden -\u003e visible so we need to see if the session\n        // should be recovered\n        await this.initializePromise\n\n        if (this.lock != null) {\n          // TODO(v3): remove legacy lock path\n          await this._acquireLock(this.lockAcquireTimeout, async () =\u003e {\n            if (document.visibilityState !== 'visible') {\n              this._debug(\n                methodName,\n                'acquired the lock to recover the session, but the browser visibilityState is no longer visible, aborting'\n              )\n              return\n            }\n            await this._recoverAndRefresh()\n          })\n        } else {\n          if (document.visibilityState !== 'visible') {\n            this._debug(methodName, 'visibilityState is no longer visible, skipping recovery')\n            return\n          }\n          // recover the session\n          await this._recoverAndRefresh()\n        }\n      }\n    } else if (document.visibilityState === 'hidden') {\n      if (this.autoRefreshToken) {\n        this._stopAutoRefresh()\n      }\n    }\n  }\n\n  /**\n   * Generates the relevant login URL for a third-party provider.\n   * @param options.redirectTo A URL or mobile address to send the user to after they are confirmed.\n   * @param options.scopes A space-separated list of scopes granted to the OAuth application.\n   * @param options.queryParams An object of key-value pairs containing query parameters granted to the OAuth application.\n   */\n  private async _getUrlForProvider(\n    url: string,\n    provider: Provider,\n    options: {\n      redirectTo?: string\n      scopes?: string\n      queryParams?: { [key: string]: string }\n      skipBrowserRedirect?: boolean\n    }\n  ) {\n    let redirectTo = options?.redirectTo\n    let codeChallenge: string | null = null\n    let codeChallengeMethod: string | null = null\n    let flowId: string | null = null\n    if (this.flowType === 'pkce') {\n      ;[codeChallenge, codeChallengeMethod, flowId] = await this._getCodeChallengeAndMethod()\n      redirectTo = this._maybeAppendFlowIdToRedirect(redirectTo, flowId)\n    }\n\n    const urlParams: string[] = [`provider=${encodeURIComponent(provider)}`]\n    if (redirectTo) {\n      urlParams.push(`redirect_to=${encodeURIComponent(redirectTo)}`)\n    }\n    if (options?.scopes) {\n      urlParams.push(`scopes=${encodeURIComponent(options.scopes)}`)\n    }\n    if (codeChallenge != null \u0026\u0026 codeChallengeMethod != null) {\n      const flowParams = new URLSearchParams({\n        code_challenge: `${encodeURIComponent(codeChallenge)}`,\n        code_challenge_method: `${encodeURIComponent(codeChallengeMethod)}`,\n      })\n      urlParams.push(flowParams.toString())\n    }\n    if (options?.queryParams) {\n      const query = new URLSearchParams(options.queryParams)\n      urlParams.push(query.toString())\n    }\n    if (options?.skipBrowserRedirect) {\n      urlParams.push(`skip_http_redirect=${options.skipBrowserRedirect}`)\n    }\n\n    return { url: `${url}?${urlParams.join('\u0026')}`, flowId }\n  }\n\n  /**\n   * Appends the reserved flow id parameter to a redirect URL so the callback\n   * can be matched to the verifier stored for its flow. Opt-in via\n   * `experimental.appendPkceFlowIdToRedirects`: redirect URLs are validated\n   * against the project's allow list including the query string, so an extra\n   * parameter can stop exact (non-wildcard) entries from matching.\n   */\n  private _maybeAppendFlowIdToRedirect(\n    redirectTo: string | undefined,\n    flowId: string | null\n  ): string | undefined {\n    if (!redirectTo || !flowId || !this.experimental.appendPkceFlowIdToRedirects) {\n      return redirectTo ?? undefined\n    }\n    return appendFlowIdToRedirectTo(redirectTo, flowId)\n  }\n\n  /**\n   * Generates and stores a PKCE challenge/verifier pair for a new flow,\n   * logging any pending verifier the bounded slot ring evicts.\n   */\n  private async _getCodeChallengeAndMethod(\n    isPasswordRecovery = false\n  ): Promise\u003c[string, string, string]\u003e {\n    return getCodeChallengeAndMethod(\n      this.storage,\n      this.storageKey,\n      isPasswordRecovery,\n      (evictedFlowId) =\u003e\n        this._debug(\n          '#_getCodeChallengeAndMethod()',\n          'evicted oldest pending PKCE verifier slot',\n          evictedFlowId\n        )\n    )\n  }\n\n  private async _unenroll(params: MFAUnenrollParams): Promise\u003cAuthMFAUnenrollResponse\u003e {\n    try {\n      return await this._useSession(async (result) =\u003e {\n        const { data: sessionData, error: sessionError } = result\n        if (sessionError) {\n          return this._returnResult({ data: null, error: sessionError })\n        }\n\n        return await _request(this.fetch, 'DELETE', `${this.url}/factors/${params.factorId}`, {\n          headers: this.headers,\n          jwt: sessionData?.session?.access_token,\n        })\n      })\n    } catch (error) {\n      if (isAuthError(error)) {\n        return this._returnResult({ data: null, error })\n      }\n      throw error\n    }\n  }\n\n  /**\n   * {@link GoTrueMFAApi#enroll}\n   */\n  private async _enroll(params: MFAEnrollTOTPParams): Promise\u003cAuthMFAEnrollTOTPResponse\u003e\n  private async _enroll(params: MFAEnrollPhoneParams): Promise\u003cAuthMFAEnrollPhoneResponse\u003e\n  private async _enroll(params: MFAEnrollWebauthnParams): Promise\u003cAuthMFAEnrollWebauthnResponse\u003e\n  private async _enroll(params: MFAEnrollParams): Promise\u003cAuthMFAEnrollResponse\u003e {\n    try {\n      return await this._useSession(async (result) =\u003e {\n        const { data: sessionData, error: sessionError } = result\n        if (sessionError) {\n          return this._returnResult({ data: null, error: sessionError })\n        }\n\n        const body = {\n          friendly_name: params.friendlyName,\n          factor_type: params.factorType,\n          ...(params.factorType === 'phone'\n            ? { phone: params.phone }\n            : params.factorType === 'totp'\n              ? { issuer: params.issuer }\n              : {}),\n        }\n\n        const { data, error } = (await _request(this.fetch, 'POST', `${this.url}/factors`, {\n          body,\n          headers: this.headers,\n          jwt: sessionData?.session?.access_token,\n        })) as AuthMFAEnrollResponse\n        if (error) {\n          return this._returnResult({ data: null, error })\n        }\n\n        if (params.factorType === 'totp' \u0026\u0026 data.type === 'totp' \u0026\u0026 data?.totp?.qr_code) {\n          data.totp.qr_code = `data:image/svg+xml;utf-8,${data.totp.qr_code}`\n        }\n\n        return this._returnResult({ data, error: null })\n      })\n    } catch (error) {\n      if (isAuthError(error)) {\n        return this._returnResult({ data: null, error })\n      }\n      throw error\n    }\n  }\n\n  /**\n   * {@link GoTrueMFAApi#verify}\n   */\n  private async _verify(params: MFAVerifyTOTPParams): Promise\u003cAuthMFAVerifyResponse\u003e\n  private async _verify(params: MFAVerifyPhoneParams): Promise\u003cAuthMFAVerifyResponse\u003e\n  private async _verify\u003cT extends 'create' | 'request'\u003e(\n    params: MFAVerifyWebauthnParams\u003cT\u003e\n  ): Promise\u003cAuthMFAVerifyResponse\u003e\n  private async _verify(params: MFAVerifyParams): Promise\u003cAuthMFAVerifyResponse\u003e {\n    const run = async (): Promise\u003cAuthMFAVerifyResponse\u003e =\u003e {\n      try {\n        return await this._useSession(async (result) =\u003e {\n          const { data: sessionData, error: sessionError } = result\n          if (sessionError) {\n            return this._returnResult({ data: null, error: sessionError })\n          }\n\n          const body: StrictOmit\u003c\n            | Exclude\u003cMFAVerifyParams, MFAVerifyWebauthnParams\u003e\n            /** Exclude out the webauthn params from here because we're going to need to serialize them in the response */\n            | Prettify\u003c\n                StrictOmit\u003cMFAVerifyWebauthnParams, 'webauthn'\u003e \u0026 {\n                  webauthn: Prettify\u003c\n                    StrictOmit\u003cMFAVerifyWebauthnParamFields['webauthn'], 'credential_response'\u003e \u0026 {\n                      credential_response: PublicKeyCredentialJSON\n                    }\n                  \u003e\n                }\n              \u003e,\n            /*  Exclude challengeId because the backend expects snake_case, and exclude factorId since it's passed in the path params */\n            'challengeId' | 'factorId'\n          \u003e \u0026 {\n            challenge_id: string\n          } = {\n            challenge_id: params.challengeId,\n            ...('webauthn' in params\n              ? {\n                  webauthn: {\n                    ...params.webauthn,\n                    credential_response:\n                      params.webauthn.type === 'create'\n                        ? serializeCredentialCreationResponse(\n                            params.webauthn.credential_response as RegistrationCredential\n                          )\n                        : serializeCredentialRequestResponse(\n                            params.webauthn.credential_response as AuthenticationCredential\n                          ),\n                  },\n                }\n              : { code: params.code }),\n          }\n\n          const { data, error } = await _request(\n            this.fetch,\n            'POST',\n            `${this.url}/factors/${params.factorId}/verify`,\n            {\n              body,\n              headers: this.headers,\n              jwt: sessionData?.session?.access_token,\n            }\n          )\n          if (error) {\n            return this._returnResult({ data: null, error })\n          }\n\n          await this._saveSession({\n            expires_at: Math.round(Date.now() / 1000) + data.expires_in,\n            ...data,\n          })\n          await this._notifyAllSubscribers('MFA_CHALLENGE_VERIFIED', data)\n\n          return this._returnResult({ data, error })\n        })\n      } catch (error) {\n        if (isAuthError(error)) {\n          return this._returnResult({ data: null, error })\n        }\n        throw error\n      }\n    }\n\n    if (this.lock != null) {\n      // TODO(v3): remove legacy lock path\n      return this._acquireLock(this.lockAcquireTimeout, run)\n    }\n    return run()\n  }\n\n  /**\n   * {@link GoTrueMFAApi#challenge}\n   */\n  private async _challenge(\n    params: MFAChallengeTOTPParams\n  ): Promise\u003cPrettify\u003cAuthMFAChallengeTOTPResponse\u003e\u003e\n  private async _challenge(\n    params: MFAChallengePhoneParams\n  ): Promise\u003cPrettify\u003cAuthMFAChallengePhoneResponse\u003e\u003e\n  private async _challenge(\n    params: MFAChallengeWebauthnParams\n  ): Promise\u003cPrettify\u003cAuthMFAChallengeWebauthnResponse\u003e\u003e\n  private async _challenge(params: MFAChallengeParams): Promise\u003cAuthMFAChallengeResponse\u003e {\n    const run = async (): Promise\u003cAuthMFAChallengeResponse\u003e =\u003e {\n      try {\n        return await this._useSession(async (result) =\u003e {\n          const { data: sessionData, error: sessionError } = result\n          if (sessionError) {\n            return this._returnResult({ data: null, error: sessionError })\n          }\n\n          const response = (await _request(\n            this.fetch,\n            'POST',\n            `${this.url}/factors/${params.factorId}/challenge`,\n            {\n              body: params,\n              headers: this.headers,\n              jwt: sessionData?.session?.access_token,\n            }\n          )) as\n            | Exclude\u003cAuthMFAChallengeResponse, AuthMFAChallengeWebauthnResponse\u003e\n            /** The server will send `serialized` data, so we assert the serialized response */\n            | AuthMFAChallengeWebauthnServerResponse\n\n          if (response.error) {\n            return response\n          }\n\n          const { data } = response\n\n          if (data.type !== 'webauthn') {\n            return { data, error: null }\n          }\n\n          switch (data.webauthn.type) {\n            case 'create':\n              return {\n                data: {\n                  ...data,\n                  webauthn: {\n                    ...data.webauthn,\n                    credential_options: {\n                      ...data.webauthn.credential_options,\n                      publicKey: deserializeCredentialCreationOptions(\n                        data.webauthn.credential_options.publicKey\n                      ),\n                    },\n                  },\n                },\n                error: null,\n              }\n            case 'request':\n              return {\n                data: {\n                  ...data,\n                  webauthn: {\n                    ...data.webauthn,\n                    credential_options: {\n                      ...data.webauthn.credential_options,\n                      publicKey: deserializeCredentialRequestOptions(\n                        data.webauthn.credential_options.publicKey\n                      ),\n                    },\n                  },\n                },\n                error: null,\n              }\n          }\n        })\n      } catch (error) {\n        if (isAuthError(error)) {\n          return this._returnResult({ data: null, error })\n        }\n        throw error\n      }\n    }\n\n    if (this.lock != null) {\n      // TODO(v3): remove legacy lock path\n      return this._acquireLock(this.lockAcquireTimeout, run)\n    }\n    return run()\n  }\n\n  /**\n   * {@link GoTrueMFAApi#challengeAndVerify}\n   */\n  private async _challengeAndVerify(\n    params: MFAChallengeAndVerifyParams\n  ): Promise\u003cAuthMFAVerifyResponse\u003e {\n    const { data: challengeData, error: challengeError } = await this._challenge({\n      factorId: params.factorId,\n    })\n    if (challengeError) {\n      return this._returnResult({ data: null, error: challengeError })\n    }\n\n    return await this._verify({\n      factorId: params.factorId,\n      challengeId: challengeData.id,\n      code: params.code,\n    })\n  }\n\n  /**\n   * {@link GoTrueMFAApi#listFactors}\n   */\n  private async _listFactors(): Promise\u003cAuthMFAListFactorsResponse\u003e {\n    const {\n      data: { user },\n      error: userError,\n    } = await this.getUser()\n    if (userError) {\n      return { data: null, error: userError }\n    }\n\n    const data: AuthMFAListFactorsResponse['data'] = {\n      all: [],\n      phone: [],\n      totp: [],\n      webauthn: [],\n      recovery_code: [],\n    }\n\n    // loop over the factors ONCE\n    for (const factor of user?.factors ?? []) {\n      data.all.push(factor)\n      // Types that are not recognized are pushed to `all` bucket.\n      if (\n        factor.status === 'verified' \u0026\u0026\n        factor.factor_type in data \u0026\u0026\n        Array.isArray(data[factor.factor_type])\n      ) {\n        ;(data[factor.factor_type] as (typeof factor)[]).push(factor)\n      }\n    }\n\n    return {\n      data,\n      error: null,\n    }\n  }\n\n  /**\n   * {@link GoTrueMFAApi#getAuthenticatorAssuranceLevel}\n   */\n  private async _getAuthenticatorAssuranceLevel(\n    jwt?: string\n  ): Promise\u003cAuthMFAGetAuthenticatorAssuranceLevelResponse\u003e {\n    if (jwt) {\n      try {\n        const { payload } = decodeJWT(jwt)\n\n        let currentLevel: AuthenticatorAssuranceLevels | null = null\n        if (payload.aal) {\n          currentLevel = payload.aal\n        }\n\n        let nextLevel: AuthenticatorAssuranceLevels | null = currentLevel\n\n        const {\n          data: { user },\n          error: userError,\n        } = await this.getUser(jwt)\n\n        if (userError) {\n          return this._returnResult({ data: null, error: userError })\n        }\n\n        const verifiedFactors =\n          user?.factors?.filter((factor: Factor) =\u003e factor.status === 'verified') ?? []\n\n        if (verifiedFactors.length \u003e 0) {\n          nextLevel = 'aal2'\n        }\n\n        const currentAuthenticationMethods = payload.amr || []\n\n        return { data: { currentLevel, nextLevel, currentAuthenticationMethods }, error: null }\n      } catch (error) {\n        if (isAuthError(error)) {\n          return this._returnResult({ data: null, error })\n        }\n        throw error\n      }\n    }\n\n    const {\n      data: { session },\n      error: sessionError,\n    } = await this.getSession()\n\n    if (sessionError) {\n      return this._returnResult({ data: null, error: sessionError })\n    }\n    if (!session) {\n      return {\n        data: { currentLevel: null, nextLevel: null, currentAuthenticationMethods: [] },\n        error: null,\n      }\n    }\n\n    const { payload } = decodeJWT(session.access_token)\n\n    let currentLevel: AuthenticatorAssuranceLevels | null = null\n\n    if (payload.aal) {\n      currentLevel = payload.aal\n    }\n\n    let nextLevel: AuthenticatorAssuranceLevels | null = currentLevel\n\n    const verifiedFactors =\n      session.user.factors?.filter((factor: Factor) =\u003e factor.status === 'verified') ?? []\n\n    if (verifiedFactors.length \u003e 0) {\n      nextLevel = 'aal2'\n    }\n\n    const currentAuthenticationMethods = payload.amr || []\n\n    return { data: { currentLevel, nextLevel, currentAuthenticationMethods }, error: null }\n  }\n\n  /**\n   * {@link AuthMFARecoveryCodesApi#getStatus}\n   */\n  private async _getRecoveryCodesStatus(): Promise\u003cAuthMFARecoveryCodesStatusResponse\u003e {\n    assertRecoveryCodesExperimentalEnabled(this.experimental)\n    try {\n      return await this._useSession(async (result) =\u003e {\n        const { data: sessionData, error: sessionError } = result\n        if (sessionError) {\n          return this._returnResult({ data: null, error: sessionError })\n        }\n\n        const { data, error } = await _request(\n          this.fetch,\n          'GET',\n          `${this.url}/factors/recovery-codes`,\n          {\n            headers: this.headers,\n            jwt: sessionData?.session?.access_token,\n          }\n        )\n        if (error) {\n          return this._returnResult({ data: null, error })\n        }\n\n        return this._returnResult({ data, error: null })\n      })\n    } catch (error) {\n      if (isAuthError(error)) {\n        return this._returnResult({ data: null, error })\n      }\n      throw error\n    }\n  }\n\n  /**\n   * {@link AuthMFARecoveryCodesApi#generate}\n   */\n  private async _generateRecoveryCodes(\n    params?: MFARecoveryCodesGenerateParams\n  ): Promise\u003cAuthMFARecoveryCodesGenerateResponse\u003e {\n    assertRecoveryCodesExperimentalEnabled(this.experimental)\n    try {\n      return await this._useSession(async (result) =\u003e {\n        const { data: sessionData, error: sessionError } = result\n        if (sessionError) {\n          return this._returnResult({ data: null, error: sessionError })\n        }\n\n        const { data, error } = await _request(\n          this.fetch,\n          'POST',\n          `${this.url}/factors/recovery-codes`,\n          {\n            // The body is optional server-side; only send one when a name was given.\n            body: params?.friendlyName ? { friendly_name: params.friendlyName } : undefined,\n            headers: this.headers,\n            jwt: sessionData?.session?.access_token,\n          }\n        )\n        if (error) {\n          return this._returnResult({ data: null, error })\n        }\n\n        return this._returnResult({ data, error: null })\n      })\n    } catch (error) {\n      if (isAuthError(error)) {\n        return this._returnResult({ data: null, error })\n      }\n      throw error\n    }\n  }\n\n  /**\n   * {@link AuthMFARecoveryCodesApi#verify}\n   */\n  private async _verifyRecoveryCode(\n    params: MFARecoveryCodesVerifyParams\n  ): Promise\u003cAuthMFAVerifyResponse\u003e {\n    assertRecoveryCodesExperimentalEnabled(this.experimental)\n    const run = async (): Promise\u003cAuthMFAVerifyResponse\u003e =\u003e {\n      try {\n        return await this._useSession(async (result) =\u003e {\n          const { data: sessionData, error: sessionError } = result\n          if (sessionError) {\n            return this._returnResult({ data: null, error: sessionError })\n          }\n\n          const { data, error } = await _request(\n            this.fetch,\n            'POST',\n            `${this.url}/factors/recovery-codes/verify`,\n            {\n              body: { code: params.code },\n              headers: this.headers,\n              jwt: sessionData?.session?.access_token,\n            }\n          )\n          if (error) {\n            return this._returnResult({ data: null, error })\n          }\n\n          // A server-provided expires_at takes precedence over the computed one.\n          const session: Session = { expires_at: expiresAt(data.expires_in), ...data }\n          await this._saveSession(session)\n          await this._notifyAllSubscribers('MFA_CHALLENGE_VERIFIED', session)\n\n          return this._returnResult({ data, error: null })\n        })\n      } catch (error) {\n        if (isAuthError(error)) {\n          return this._returnResult({ data: null, error })\n        }\n        throw error\n      }\n    }\n\n    if (this.lock != null) {\n      return this._acquireLock(this.lockAcquireTimeout, run)\n    }\n    return run()\n  }\n\n  /**\n   * {@link AuthMFARecoveryCodesApi#regenerate}\n   */\n  private async _regenerateRecoveryCodes(): Promise\u003cAuthMFARecoveryCodesGenerateResponse\u003e {\n    assertRecoveryCodesExperimentalEnabled(this.experimental)\n    try {\n      return await this._useSession(async (result) =\u003e {\n        const { data: sessionData, error: sessionError } = result\n        if (sessionError) {\n          return this._returnResult({ data: null, error: sessionError })\n        }\n\n        const { data, error } = await _request(\n          this.fetch,\n          'POST',\n          `${this.url}/factors/recovery-codes/regenerate`,\n          {\n            headers: this.headers,\n            jwt: sessionData?.session?.access_token,\n          }\n        )\n        if (error) {\n          return this._returnResult({ data: null, error })\n        }\n\n        return this._returnResult({ data, error: null })\n      })\n    } catch (error) {\n      if (isAuthError(error)) {\n        return this._returnResult({ data: null, error })\n      }\n      throw error\n    }\n  }\n\n  /**\n   * {@link AuthMFARecoveryCodesApi#unenroll}\n   */\n  private async _unenrollRecoveryCodes(): Promise\u003cAuthMFAUnenrollResponse\u003e {\n    assertRecoveryCodesExperimentalEnabled(this.experimental)\n    try {\n      return await this._useSession(async (result) =\u003e {\n        const { data: sessionData, error: sessionError } = result\n        if (sessionError) {\n          return this._returnResult({ data: null, error: sessionError })\n        }\n\n        const { data, error } = await _request(\n          this.fetch,\n          'DELETE',\n          `${this.url}/factors/recovery-codes`,\n          {\n            headers: this.headers,\n            jwt: sessionData?.session?.access_token,\n          }\n        )\n        if (error) {\n          return this._returnResult({ data: null, error })\n        }\n\n        return this._returnResult({ data, error: null })\n      })\n    } catch (error) {\n      if (isAuthError(error)) {\n        return this._returnResult({ data: null, error })\n      }\n      throw error\n    }\n  }\n\n  /**\n   * Retrieves details about an OAuth authorization request.\n   * Only relevant when the OAuth 2.1 server is enabled in Supabase Auth.\n   *\n   * Returns authorization details including client info, scopes, and user information.\n   * If the response includes only a redirect_url field, it means consent was already given - the caller\n   * should handle the redirect manually if needed.\n   */\n  private async _getAuthorizationDetails(\n    authorizationId: string\n  ): Promise\u003cAuthOAuthAuthorizationDetailsResponse\u003e {\n    try {\n      return await this._useSession(async (result) =\u003e {\n        const {\n          data: { session },\n          error: sessionError,\n        } = result\n\n        if (sessionError) {\n          return this._returnResult({ data: null, error: sessionError })\n        }\n\n        if (!session) {\n          return this._returnResult({ data: null, error: new AuthSessionMissingError() })\n        }\n\n        return await _request(\n          this.fetch,\n          'GET',\n          `${this.url}/oauth/authorizations/${authorizationId}`,\n          {\n            headers: this.headers,\n            jwt: session.access_token,\n            xform: (data: any) =\u003e ({ data, error: null }),\n          }\n        )\n      })\n    } catch (error) {\n      if (isAuthError(error)) {\n        return this._returnResult({ data: null, error })\n      }\n\n      throw error\n    }\n  }\n\n  /**\n   * Approves an OAuth authorization request.\n   * Only relevant when the OAuth 2.1 server is enabled in Supabase Auth.\n   */\n  private async _approveAuthorization(\n    authorizationId: string,\n    options?: { skipBrowserRedirect?: boolean }\n  ): Promise\u003cAuthOAuthConsentResponse\u003e {\n    try {\n      return await this._useSession(async (result) =\u003e {\n        const {\n          data: { session },\n          error: sessionError,\n        } = result\n\n        if (sessionError) {\n          return this._returnResult({ data: null, error: sessionError })\n        }\n\n        if (!session) {\n          return this._returnResult({ data: null, error: new AuthSessionMissingError() })\n        }\n\n        const response = await _request(\n          this.fetch,\n          'POST',\n          `${this.url}/oauth/authorizations/${authorizationId}/consent`,\n          {\n            headers: this.headers,\n            jwt: session.access_token,\n            body: { action: 'approve' },\n            xform: (data: any) =\u003e ({ data, error: null }),\n          }\n        )\n\n        if (response.data \u0026\u0026 response.data.redirect_url) {\n          // Automatically redirect in browser unless skipBrowserRedirect is true\n          if (isBrowser() \u0026\u0026 !options?.skipBrowserRedirect) {\n            window.location.assign(response.data.redirect_url)\n          }\n        }\n\n        return response\n      })\n    } catch (error) {\n      if (isAuthError(error)) {\n        return this._returnResult({ data: null, error })\n      }\n\n      throw error\n    }\n  }\n\n  /**\n   * Denies an OAuth authorization request.\n   * Only relevant when the OAuth 2.1 server is enabled in Supabase Auth.\n   */\n  private async _denyAuthorization(\n    authorizationId: string,\n    options?: { skipBrowserRedirect?: boolean }\n  ): Promise\u003cAuthOAuthConsentResponse\u003e {\n    try {\n      return await this._useSession(async (result) =\u003e {\n        const {\n          data: { session },\n          error: sessionError,\n        } = result\n\n        if (sessionError) {\n          return this._returnResult({ data: null, error: sessionError })\n        }\n\n        if (!session) {\n          return this._returnResult({ data: null, error: new AuthSessionMissingError() })\n        }\n\n        const response = await _request(\n          this.fetch,\n          'POST',\n          `${this.url}/oauth/authorizations/${authorizationId}/consent`,\n          {\n            headers: this.headers,\n            jwt: session.access_token,\n            body: { action: 'deny' },\n            xform: (data: any) =\u003e ({ data, error: null }),\n          }\n        )\n\n        if (response.data \u0026\u0026 response.data.redirect_url) {\n          // Automatically redirect in browser unless skipBrowserRedirect is true\n          if (isBrowser() \u0026\u0026 !options?.skipBrowserRedirect) {\n            window.location.assign(response.data.redirect_url)\n          }\n        }\n\n        return response\n      })\n    } catch (error) {\n      if (isAuthError(error)) {\n        return this._returnResult({ data: null, error })\n      }\n\n      throw error\n    }\n  }\n\n  /**\n   * Lists all OAuth grants that the authenticated user has authorized.\n   * Only relevant when the OAuth 2.1 server is enabled in Supabase Auth.\n   */\n  private async _listOAuthGrants(): Promise\u003cAuthOAuthGrantsResponse\u003e {\n    try {\n      return await this._useSession(async (result) =\u003e {\n        const {\n          data: { session },\n          error: sessionError,\n        } = result\n\n        if (sessionError) {\n          return this._returnResult({ data: null, error: sessionError })\n        }\n\n        if (!session) {\n          return this._returnResult({ data: null, error: new AuthSessionMissingError() })\n        }\n\n        return await _request(this.fetch, 'GET', `${this.url}/user/oauth/grants`, {\n          headers: this.headers,\n          jwt: session.access_token,\n          xform: (data: any) =\u003e ({ data, error: null }),\n        })\n      })\n    } catch (error) {\n      if (isAuthError(error)) {\n        return this._returnResult({ data: null, error })\n      }\n\n      throw error\n    }\n  }\n\n  /**\n   * Revokes a user's OAuth grant for a specific client.\n   * Only relevant when the OAuth 2.1 server is enabled in Supabase Auth.\n   */\n  private async _revokeOAuthGrant(options: {\n    clientId: string\n  }): Promise\u003cAuthOAuthRevokeGrantResponse\u003e {\n    try {\n      return await this._useSession(async (result) =\u003e {\n        const {\n          data: { session },\n          error: sessionError,\n        } = result\n\n        if (sessionError) {\n          return this._returnResult({ data: null, error: sessionError })\n        }\n\n        if (!session) {\n          return this._returnResult({ data: null, error: new AuthSessionMissingError() })\n        }\n\n        await _request(this.fetch, 'DELETE', `${this.url}/user/oauth/grants`, {\n          headers: this.headers,\n          jwt: session.access_token,\n          query: { client_id: options.clientId },\n          noResolveJson: true,\n        })\n        return { data: {}, error: null }\n      })\n    } catch (error) {\n      if (isAuthError(error)) {\n        return this._returnResult({ data: null, error })\n      }\n\n      throw error\n    }\n  }\n\n  private async fetchJwk(kid: string, jwks: { keys: JWK[] } = { keys: [] }): Promise\u003cJWK | null\u003e {\n    // try fetching from the supplied jwks\n    let jwk = jwks.keys.find((key) =\u003e key.kid === kid)\n    if (jwk) {\n      return jwk\n    }\n\n    const now = Date.now()\n\n    // try fetching from cache\n    jwk = this.jwks.keys.find((key) =\u003e key.kid === kid)\n\n    // jwk exists and jwks isn't stale\n    if (jwk \u0026\u0026 this.jwks_cached_at + JWKS_TTL \u003e now) {\n      return jwk\n    }\n    // jwk isn't cached in memory so we need to fetch it from the well-known endpoint\n    const { data, error } = await _request(this.fetch, 'GET', `${this.url}/.well-known/jwks.json`, {\n      headers: this.headers,\n    })\n    if (error) {\n      throw error\n    }\n    if (!data.keys || data.keys.length === 0) {\n      return null\n    }\n\n    this.jwks = data\n    this.jwks_cached_at = now\n\n    // Find the signing key\n    jwk = data.keys.find((key: any) =\u003e key.kid === kid)\n    if (!jwk) {\n      return null\n    }\n    return jwk\n  }\n\n  /**\n   * Extracts the JWT claims present in the access token by first verifying the\n   * JWT against the server's JSON Web Key Set endpoint\n   * `/.well-known/jwks.json` which is often cached, resulting in significantly\n   * faster responses. Prefer this method over {@link GoTrueClient.getUser} which always\n   * sends a request to the Auth server for each JWT.\n   *\n   * If the project is not using an asymmetric JWT signing key (like ECC or\n   * RSA) it always sends a request to the Auth server (similar to\n   * {@link GoTrueClient.getUser}) to verify the JWT.\n   *\n   * @param jwt An optional specific JWT you wish to verify, not the one you\n   *            can obtain from {@link GoTrueClient.getSession}.\n   * @param options Various additional options that allow you to customize the\n   *                behavior of this method.\n   *\n   * @category Auth\n   *\n   * @remarks\n   * - Parses the user's [access token](/docs/guides/auth/sessions#access-token-jwt-claims) as a [JSON Web Token (JWT)](/docs/guides/auth/jwts) and returns its components if valid and not expired.\n   * - If your project is using asymmetric JWT signing keys, then the verification is done locally usually without a network request using the [WebCrypto API](https://developer.mozilla.org/en-US/docs/Web/API/Web_Crypto_API).\n   * - A network request is sent to your project's JWT signing key discovery endpoint `https://project-id.supabase.co/auth/v1/.well-known/jwks.json`, which is cached locally. If your environment is ephemeral, such as a Lambda function that is destroyed after every request, a network request will be sent for each new invocation. Supabase provides a network-edge cache providing fast responses for these situations.\n   * - If the user's access token is about to expire when calling this function, the user's session will first be refreshed before validating the JWT.\n   * - If your project is using a symmetric secret to sign the JWT, it always sends a request similar to `getUser()` to validate the JWT at the server before returning the decoded token. This is also used if the WebCrypto API is not available in the environment. Make sure you polyfill it in such situations.\n   * - The returned claims can be customized per project using the [Custom Access Token Hook](/docs/guides/auth/auth-hooks/custom-access-token-hook).\n   *\n   * @example Get JWT claims, header and signature\n   * ```js\n   * const { data, error } = await supabase.auth.getClaims()\n   * ```\n   *\n   * @exampleResponse Get JWT claims, header and signature\n   * ```json\n   * {\n   *   \"data\": {\n   *     \"claims\": {\n   *       \"aal\": \"aal1\",\n   *       \"amr\": [{\n   *         \"method\": \"email\",\n   *         \"timestamp\": 1715766000\n   *       }],\n   *       \"app_metadata\": {},\n   *       \"aud\": \"authenticated\",\n   *       \"email\": \"example@email.com\",\n   *       \"exp\": 1715769600,\n   *       \"iat\": 1715766000,\n   *       \"is_anonymous\": false,\n   *       \"iss\": \"https://project-id.supabase.co/auth/v1\",\n   *       \"phone\": \"+13334445555\",\n   *       \"role\": \"authenticated\",\n   *       \"session_id\": \"11111111-1111-1111-1111-111111111111\",\n   *       \"sub\": \"11111111-1111-1111-1111-111111111111\",\n   *       \"user_metadata\": {}\n   *     },\n   *     \"header\": {\n   *       \"alg\": \"RS256\",\n   *       \"typ\": \"JWT\",\n   *       \"kid\": \"11111111-1111-1111-1111-111111111111\"\n   *     },\n   *     \"signature\": [/** Uint8Array *\\/],\n   *   },\n   *   \"error\": null\n   * }\n   * ```\n   */\n  async getClaims(\n    jwt?: string,\n    options: {\n      /**\n       * @deprecated Please use options.jwks instead.\n       */\n      keys?: JWK[]\n\n      /** If set to `true` the `exp` claim will not be validated against the current time. */\n      allowExpired?: boolean\n\n      /** If set, this JSON Web Key Set is going to have precedence over the cached value available on the server. */\n      jwks?: { keys: JWK[] }\n    } = {}\n  ): Promise\u003c\n    | {\n        data: { claims: JwtPayload; header: JwtHeader; signature: Uint8Array }\n        error: null\n      }\n    | { data: null; error: AuthError }\n    | { data: null; error: null }\n  \u003e {\n    try {\n      let token = jwt\n      if (!token) {\n        const { data, error } = await this.getSession()\n        if (error || !data.session) {\n          return this._returnResult({ data: null, error })\n        }\n        token = data.session.access_token\n      }\n\n      const {\n        header,\n        payload,\n        signature,\n        raw: { header: rawHeader, payload: rawPayload },\n      } = decodeJWT(token)\n\n      if (!options?.allowExpired) {\n        // Reject expired JWTs should only happen if jwt argument was passed.\n        // Rethrow as AuthInvalidJwtError so the outer catch converts it to { data, error }.\n        try {\n          validateExp(payload.exp)\n        } catch (e) {\n          throw new AuthInvalidJwtError(e instanceof Error ? e.message : 'JWT validation failed')\n        }\n      }\n\n      const signingKey =\n        !header.alg ||\n        header.alg.startsWith('HS') ||\n        !header.kid ||\n        !('crypto' in globalThis \u0026\u0026 'subtle' in globalThis.crypto)\n          ? null\n          : await this.fetchJwk(header.kid, options?.keys ? { keys: options.keys } : options?.jwks)\n\n      // If symmetric algorithm or WebCrypto API is unavailable, fallback to getUser()\n      if (!signingKey) {\n        const { error } = await this.getUser(token)\n        if (error) {\n          throw error\n        }\n        // getUser succeeds so the claims in the JWT can be trusted\n        return {\n          data: {\n            claims: payload,\n            header,\n            signature,\n          },\n          error: null,\n        }\n      }\n\n      const algorithm = getAlgorithm(header.alg)\n\n      // Convert JWK to CryptoKey\n      const publicKey = await crypto.subtle.importKey('jwk', signingKey, algorithm, true, [\n        'verify',\n      ])\n\n      // Verify the signature\n      const isValid = await crypto.subtle.verify(\n        algorithm,\n        publicKey,\n        signature,\n        stringToUint8Array(`${rawHeader}.${rawPayload}`)\n      )\n\n      if (!isValid) {\n        throw new AuthInvalidJwtError('Invalid JWT signature')\n      }\n\n      // If verification succeeds, decode and return claims\n      return {\n        data: {\n          claims: payload,\n          header,\n          signature,\n        },\n        error: null,\n      }\n    } catch (error) {\n      if (isAuthError(error)) {\n        return this._returnResult({ data: null, error })\n      }\n      throw error\n    }\n  }\n\n  // --- Passkey Methods ---\n\n  /**\n   * Sign in with a passkey. Handles the full WebAuthn ceremony:\n   * 1. Fetches authentication challenge from server\n   * 2. Prompts user via navigator.credentials.get()\n   * 3. Verifies credential with server and creates session\n   *\n   * Pass `options.mediation: 'conditional'` to use WebAuthn Conditional UI\n   * (passkey autofill) instead of the modal picker; the value is forwarded to\n   * `navigator.credentials.get()` unchanged.\n   *\n   * The challenge fetched in step 1 expires after the server's\n   * GOTRUE_WEBAUTHN_CHALLENGE_EXPIRY_DURATION (5 minutes by default). With\n   * `mediation: 'conditional'` the autofill prompt can stay pending for longer\n   * than that: the browser ceremony then still succeeds, but verification fails\n   * with `error_code: \"webauthn_challenge_expired\"`. Recover by calling\n   * `signInWithPasskey()` again. It fetches a fresh challenge and, unless you\n   * passed your own `options.signal`, cancels the pending ceremony first, so\n   * the browser never sees two concurrent WebAuthn requests; the earlier call\n   * resolves with a `WebAuthnError` whose code is `ERROR_CEREMONY_ABORTED`. If\n   * you pass your own `signal`, abort it before retrying.\n   *\n   * @category Auth\n   *\n   * @example Sign in with Conditional UI (passkey autofill)\n   * ```js\n   * // \u003cinput autocomplete=\"username webauthn\" /\u003e somewhere on the page\n   * const { data, error } = await supabase.auth.signInWithPasskey({\n   *   options: {\n   *     mediation: 'conditional'\n   *   }\n   * });\n   * ```\n   */\n  async signInWithPasskey(\n    credentials?: SignInWithPasskeyCredentials\n  ): Promise\u003cAuthPasskeyAuthenticationVerifyResponse\u003e {\n    try {\n      if (!browserSupportsWebAuthn()) {\n        return this._returnResult({\n          data: null,\n          error: new AuthUnknownError('Browser does not support WebAuthn', null),\n        })\n      }\n\n      // 1. Get challenge options from server\n      const { data: options, error: optionsError } = await this._startPasskeyAuthentication({\n        options: { captchaToken: credentials?.options?.captchaToken },\n      })\n      if (optionsError || !options) {\n        return this._returnResult({ data: null, error: optionsError })\n      }\n\n      // 2. Deserialize and prompt user via browser WebAuthn API\n      const publicKeyOptions = deserializeCredentialRequestOptions(options.options)\n      const signal = credentials?.options?.signal ?? webAuthnAbortService.createNewAbortSignal()\n      const { data: credential, error: credentialError } = await getCredential({\n        publicKey: publicKeyOptions,\n        signal,\n        mediation: credentials?.options?.mediation,\n      })\n      if (credentialError || !credential) {\n        return this._returnResult({\n          data: null,\n          error: credentialError ?? new AuthUnknownError('WebAuthn ceremony failed', null),\n        })\n      }\n\n      // 3. Serialize and verify with server\n      const serialized = serializeCredentialRequestResponse(credential)\n      return this._verifyPasskeyAuthentication({\n        challengeId: options.challenge_id,\n        credential: serialized,\n      })\n    } catch (error) {\n      if (isAuthError(error)) {\n        return this._returnResult({ data: null, error })\n      }\n      throw error\n    }\n  }\n\n  /**\n   * Register a passkey for the current authenticated user. Handles the full WebAuthn ceremony:\n   * 1. Fetches registration challenge from server\n   * 2. Prompts user via navigator.credentials.create()\n   * 3. Verifies credential with server\n   *\n   * Requires an active session.\n   *\n   * @category Auth\n   */\n  async registerPasskey(\n    credentials?: RegisterPasskeyCredentials\n  ): Promise\u003cAuthPasskeyRegistrationVerifyResponse\u003e {\n    try {\n      if (!browserSupportsWebAuthn()) {\n        return this._returnResult({\n          data: null,\n          error: new AuthUnknownError('Browser does not support WebAuthn', null),\n        })\n      }\n\n      // 1. Get challenge options from server\n      const { data: options, error: optionsError } = await this._startPasskeyRegistration()\n      if (optionsError || !options) {\n        return this._returnResult({ data: null, error: optionsError })\n      }\n\n      // 2. Deserialize and prompt user via browser WebAuthn API\n      const publicKeyOptions = deserializeCredentialCreationOptions(options.options)\n      const signal = credentials?.options?.signal ?? webAuthnAbortService.createNewAbortSignal()\n      const { data: credential, error: credentialError } = await createCredential({\n        publicKey: publicKeyOptions,\n        signal,\n      })\n      if (credentialError || !credential) {\n        return this._returnResult({\n          data: null,\n          error: credentialError ?? new AuthUnknownError('WebAuthn ceremony failed', null),\n        })\n      }\n\n      // 3. Serialize and verify with server\n      const serialized = serializeCredentialCreationResponse(credential)\n      return this._verifyPasskeyRegistration({\n        challengeId: options.challenge_id,\n        credential: serialized,\n      })\n    } catch (error) {\n      if (isAuthError(error)) {\n        return this._returnResult({ data: null, error })\n      }\n      throw error\n    }\n  }\n\n  /**\n   * Start passkey registration for the current authenticated user.\n   * Returns WebAuthn credential creation options to pass to navigator.credentials.create().\n   */\n  private async _startPasskeyRegistration(): Promise\u003cAuthPasskeyRegistrationOptionsResponse\u003e {\n    try {\n      return await this._useSession(async (result) =\u003e {\n        const {\n          data: { session },\n          error: sessionError,\n        } = result\n        if (sessionError) {\n          return this._returnResult({ data: null, error: sessionError })\n        }\n        if (!session) {\n          return this._returnResult({ data: null, error: new AuthSessionMissingError() })\n        }\n        const { data, error } = await _request(\n          this.fetch,\n          'POST',\n          `${this.url}/passkeys/registration/options`,\n          {\n            headers: this.headers,\n            jwt: session.access_token,\n            body: {},\n          }\n        )\n        if (error) {\n          return this._returnResult({ data: null, error })\n        }\n        return this._returnResult({ data, error: null })\n      })\n    } catch (error) {\n      if (isAuthError(error)) {\n        return this._returnResult({ data: null, error })\n      }\n      throw error\n    }\n  }\n\n  /**\n   * Verify passkey registration with the credential response.\n   * The credentialResponse should be the serialized output of navigator.credentials.create().\n   */\n  private async _verifyPasskeyRegistration(\n    params: VerifyPasskeyRegistrationParams\n  ): Promise\u003cAuthPasskeyRegistrationVerifyResponse\u003e {\n    try {\n      return await this._useSession(async (result) =\u003e {\n        const {\n          data: { session },\n          error: sessionError,\n        } = result\n        if (sessionError) {\n          return this._returnResult({ data: null, error: sessionError })\n        }\n        if (!session) {\n          return this._returnResult({ data: null, error: new AuthSessionMissingError() })\n        }\n        const { data, error } = await _request(\n          this.fetch,\n          'POST',\n          `${this.url}/passkeys/registration/verify`,\n          {\n            headers: this.headers,\n            jwt: session.access_token,\n            body: {\n              challenge_id: params.challengeId,\n              credential: params.credential,\n            },\n          }\n        )\n        if (error) {\n          return this._returnResult({ data: null, error })\n        }\n        return this._returnResult({ data, error: null })\n      })\n    } catch (error) {\n      if (isAuthError(error)) {\n        return this._returnResult({ data: null, error })\n      }\n      throw error\n    }\n  }\n\n  /**\n   * Start passkey authentication.\n   * Returns WebAuthn credential request options to pass to navigator.credentials.get().\n   */\n  private async _startPasskeyAuthentication(\n    params?: StartPasskeyAuthenticationParams\n  ): Promise\u003cAuthPasskeyAuthenticationOptionsResponse\u003e {\n    try {\n      const { data, error } = await _request(\n        this.fetch,\n        'POST',\n        `${this.url}/passkeys/authentication/options`,\n        {\n          headers: this.headers,\n          body: {\n            gotrue_meta_security: { captcha_token: params?.options?.captchaToken },\n          },\n        }\n      )\n      if (error) {\n        return this._returnResult({ data: null, error })\n      }\n      return this._returnResult({ data, error: null })\n    } catch (error) {\n      if (isAuthError(error)) {\n        return this._returnResult({ data: null, error })\n      }\n      throw error\n    }\n  }\n\n  /**\n   * Verify passkey authentication and create a session.\n   * The credential should be the serialized output of navigator.credentials.get().\n   */\n  private async _verifyPasskeyAuthentication(\n    params: VerifyPasskeyAuthenticationParams\n  ): Promise\u003cAuthPasskeyAuthenticationVerifyResponse\u003e {\n    try {\n      const { data, error } = await _request(\n        this.fetch,\n        'POST',\n        `${this.url}/passkeys/authentication/verify`,\n        {\n          headers: this.headers,\n          body: {\n            challenge_id: params.challengeId,\n            credential: params.credential,\n          },\n          xform: _sessionResponse,\n        }\n      )\n      if (error) {\n        return this._returnResult({ data: null, error })\n      }\n      if (data.session) {\n        await this._saveSession(data.session)\n        await this._notifyAllSubscribers('SIGNED_IN', data.session)\n      }\n      return this._returnResult({ data, error: null })\n    } catch (error) {\n      if (isAuthError(error)) {\n        return this._returnResult({ data: null, error })\n      }\n      throw error\n    }\n  }\n\n  /**\n   * List all passkeys for the current user.\n   */\n  private async _listPasskeys(): Promise\u003cAuthPasskeyListResponse\u003e {\n    try {\n      return await this._useSession(async (result) =\u003e {\n        const {\n          data: { session },\n          error: sessionError,\n        } = result\n        if (sessionError) {\n          return this._returnResult({ data: null, error: sessionError })\n        }\n        if (!session) {\n          return this._returnResult({ data: null, error: new AuthSessionMissingError() })\n        }\n        const { data, error } = await _request(this.fetch, 'GET', `${this.url}/passkeys`, {\n          headers: this.headers,\n          jwt: session.access_token,\n          xform: (data: any) =\u003e ({ data, error: null }),\n        })\n        if (error) {\n          return this._returnResult({ data: null, error })\n        }\n        return this._returnResult({ data, error: null })\n      })\n    } catch (error) {\n      if (isAuthError(error)) {\n        return this._returnResult({ data: null, error })\n      }\n      throw error\n    }\n  }\n\n  /**\n   * Update a passkey.\n   */\n  private async _updatePasskey(params: PasskeyUpdateParams): Promise\u003cAuthPasskeyUpdateResponse\u003e {\n    try {\n      return await this._useSession(async (result) =\u003e {\n        const {\n          data: { session },\n          error: sessionError,\n        } = result\n        if (sessionError) {\n          return this._returnResult({ data: null, error: sessionError })\n        }\n        if (!session) {\n          return this._returnResult({ data: null, error: new AuthSessionMissingError() })\n        }\n        const { data, error } = await _request(\n          this.fetch,\n          'PATCH',\n          `${this.url}/passkeys/${params.passkeyId}`,\n          {\n            headers: this.headers,\n            jwt: session.access_token,\n            body: { friendly_name: params.friendlyName },\n          }\n        )\n        if (error) {\n          return this._returnResult({ data: null, error })\n        }\n        return this._returnResult({ data, error: null })\n      })\n    } catch (error) {\n      if (isAuthError(error)) {\n        return this._returnResult({ data: null, error })\n      }\n      throw error\n    }\n  }\n\n  /**\n   * Delete a passkey.\n   */\n  private async _deletePasskey(params: PasskeyDeleteParams): Promise\u003cAuthPasskeyDeleteResponse\u003e {\n    try {\n      return await this._useSession(async (result) =\u003e {\n        const {\n          data: { session },\n          error: sessionError,\n        } = result\n        if (sessionError) {\n          return this._returnResult({ data: null, error: sessionError })\n        }\n        if (!session) {\n          return this._returnResult({ data: null, error: new AuthSessionMissingError() })\n        }\n        const { error } = await _request(\n          this.fetch,\n          'DELETE',\n          `${this.url}/passkeys/${params.passkeyId}`,\n          {\n            headers: this.headers,\n            jwt: session.access_token,\n            noResolveJson: true,\n          }\n        )\n        if (error) {\n          return this._returnResult({ data: null, error })\n        }\n        return this._returnResult({ data: null, error: null })\n      })\n    } catch (error) {\n      if (isAuthError(error)) {\n        return this._returnResult({ data: null, error })\n      }\n      throw error\n    }\n  }\n}\n","import GoTrueAdminApi from './GoTrueAdminApi'\n\nconst AuthAdminApi = GoTrueAdminApi\n\nexport default AuthAdminApi\n","import GoTrueClient from './GoTrueClient'\n\nconst AuthClient = GoTrueClient\n\nexport default AuthClient\n"],"version":3}
