{
  "version": 3,
  "sources": ["../node_modules/@capacitor/core/build/util.js", "../node_modules/@capacitor/core/build/runtime.js", "../node_modules/@capacitor/core/build/global.js", "../node_modules/@capacitor/core/build/web-plugin.js", "../node_modules/@capacitor/core/build/core-plugins.js", "../node_modules/@capacitor/filesystem/src/definitions.ts", "../node_modules/@capacitor/filesystem/src/web.ts", "../node_modules/@capacitor/share/src/web.ts", "../public/model.mjs", "../public/import.mjs", "../node_modules/@supabase/supabase-js/src/lib/tracingRegistry.ts", "../node_modules/tslib/tslib.es6.mjs", "../node_modules/@supabase/functions-js/src/helper.ts", "../node_modules/@supabase/functions-js/src/types.ts", "../node_modules/@supabase/functions-js/src/FunctionsClient.ts", "../node_modules/@supabase/postgrest-js/src/PostgrestError.ts", "../node_modules/@supabase/postgrest-js/src/types/common/common.ts", "../node_modules/@supabase/postgrest-js/src/fetchWithRetry.ts", "../node_modules/@supabase/postgrest-js/src/PostgrestBuilder.ts", "../node_modules/@supabase/postgrest-js/src/PostgrestTransformBuilder.ts", "../node_modules/@supabase/postgrest-js/src/PostgrestFilterBuilder.ts", "../node_modules/@supabase/postgrest-js/src/PostgrestQueryBuilder.ts", "../node_modules/@supabase/postgrest-js/src/PostgrestClient.ts", "../node_modules/@supabase/postgrest-js/src/index.ts", "../node_modules/@supabase/realtime-js/src/lib/websocket-factory.ts", "../node_modules/@supabase/realtime-js/src/lib/version.ts", "../node_modules/@supabase/realtime-js/src/lib/constants.ts", "../node_modules/@supabase/realtime-js/src/lib/serializer.ts", "../node_modules/@supabase/realtime-js/src/lib/transformers.ts", "../node_modules/@supabase/phoenix/assets/js/phoenix/utils.js", "../node_modules/@supabase/phoenix/assets/js/phoenix/constants.js", "../node_modules/@supabase/phoenix/assets/js/phoenix/push.js", "../node_modules/@supabase/phoenix/assets/js/phoenix/timer.js", "../node_modules/@supabase/phoenix/assets/js/phoenix/channel.js", "../node_modules/@supabase/phoenix/assets/js/phoenix/ajax.js", "../node_modules/@supabase/phoenix/assets/js/phoenix/longpoll.js", "../node_modules/@supabase/phoenix/assets/js/phoenix/presence.js", "../node_modules/@supabase/phoenix/assets/js/phoenix/serializer.js", "../node_modules/@supabase/phoenix/assets/js/phoenix/socket.js", "../node_modules/@supabase/realtime-js/src/phoenix/presenceAdapter.ts", "../node_modules/@supabase/realtime-js/src/RealtimePresence.ts", "../node_modules/@supabase/realtime-js/src/lib/normalizeChannelError.ts", "../node_modules/@supabase/realtime-js/src/phoenix/channelAdapter.ts", "../node_modules/@supabase/realtime-js/src/RealtimePostgresFilterBuilder.ts", "../node_modules/@supabase/realtime-js/src/RealtimeChannel.ts", "../node_modules/@supabase/realtime-js/src/phoenix/socketAdapter.ts", "../node_modules/@supabase/realtime-js/src/RealtimeClient.ts", "../node_modules/iceberg-js/src/errors/IcebergError.ts", "../node_modules/iceberg-js/src/utils/url.ts", "../node_modules/iceberg-js/src/http/createFetchClient.ts", "../node_modules/iceberg-js/src/catalog/namespaces.ts", "../node_modules/iceberg-js/src/catalog/tables.ts", "../node_modules/iceberg-js/src/catalog/IcebergRestCatalog.ts", "../node_modules/iceberg-js/src/catalog/types.ts", "../node_modules/@supabase/storage-js/src/lib/common/errors.ts", "../node_modules/@supabase/storage-js/src/lib/common/headers.ts", "../node_modules/@supabase/storage-js/src/lib/common/helpers.ts", "../node_modules/@supabase/storage-js/src/lib/common/fetch.ts", "../node_modules/@supabase/storage-js/src/lib/common/BaseApiClient.ts", "../node_modules/@supabase/storage-js/src/packages/StreamDownloadBuilder.ts", "../node_modules/@supabase/storage-js/src/packages/BlobDownloadBuilder.ts", "../node_modules/@supabase/storage-js/src/packages/StorageFileApi.ts", "../node_modules/@supabase/storage-js/src/lib/version.ts", "../node_modules/@supabase/storage-js/src/lib/constants.ts", "../node_modules/@supabase/storage-js/src/packages/StorageBucketApi.ts", "../node_modules/@supabase/storage-js/src/packages/StorageAnalyticsClient.ts", "../node_modules/@supabase/storage-js/src/packages/VectorIndexApi.ts", "../node_modules/@supabase/storage-js/src/packages/VectorDataApi.ts", "../node_modules/@supabase/storage-js/src/packages/VectorBucketApi.ts", "../node_modules/@supabase/storage-js/src/packages/StorageVectorsClient.ts", "../node_modules/@supabase/storage-js/src/StorageClient.ts", "../node_modules/@supabase/auth-js/src/lib/version.ts", "../node_modules/@supabase/auth-js/src/lib/constants.ts", "../node_modules/@supabase/auth-js/src/lib/errors.ts", "../node_modules/@supabase/auth-js/src/lib/base64url.ts", "../node_modules/@supabase/auth-js/src/lib/helpers.ts", "../node_modules/@supabase/auth-js/src/lib/fetch.ts", "../node_modules/@supabase/auth-js/src/lib/types.ts", "../node_modules/@supabase/auth-js/src/GoTrueAdminApi.ts", "../node_modules/@supabase/auth-js/src/lib/local-storage.ts", "../node_modules/@supabase/auth-js/src/lib/locks.ts", "../node_modules/@supabase/auth-js/src/lib/polyfills.ts", "../node_modules/@supabase/auth-js/src/lib/web3/ethereum.ts", "../node_modules/@supabase/auth-js/src/lib/webauthn.errors.ts", "../node_modules/@supabase/auth-js/src/lib/webauthn.ts", "../node_modules/@supabase/auth-js/src/GoTrueClient.ts", "../node_modules/@supabase/auth-js/src/AuthClient.ts", "../node_modules/@supabase/supabase-js/src/lib/version.ts", "../node_modules/@supabase/supabase-js/src/lib/constants.ts", "../node_modules/shared/tracing/dist/module/parse.js", "../node_modules/shared/tracing/dist/module/validate.js", "../node_modules/shared/tracing/dist/module/defaults.js", "../node_modules/@supabase/supabase-js/src/lib/fetch.ts", "../node_modules/@supabase/supabase-js/src/lib/helpers.ts", "../node_modules/@supabase/supabase-js/src/lib/SupabaseAuthClient.ts", "../node_modules/@supabase/supabase-js/src/SupabaseClient.ts", "../node_modules/@supabase/supabase-js/src/index.ts", "../public/storage.mjs", "../node_modules/@capacitor/filesystem/src/index.ts", "../node_modules/@capacitor/synapse/dist/synapse.mjs", "../node_modules/@capacitor/share/src/index.ts", "../public/merge.mjs", "../public/repository.mjs", "../public/account.mjs", "../public/rules.mjs", "../public/library.mjs", "../public/app.mjs"],
  "sourcesContent": ["export var ExceptionCode;\n(function (ExceptionCode) {\n    /**\n     * API is not implemented.\n     *\n     * This usually means the API can't be used because it is not implemented for\n     * the current platform.\n     */\n    ExceptionCode[\"Unimplemented\"] = \"UNIMPLEMENTED\";\n    /**\n     * API is not available.\n     *\n     * This means the API can't be used right now because:\n     *   - it is currently missing a prerequisite, such as network connectivity\n     *   - it requires a particular platform or browser version\n     */\n    ExceptionCode[\"Unavailable\"] = \"UNAVAILABLE\";\n})(ExceptionCode || (ExceptionCode = {}));\nexport class CapacitorException extends Error {\n    constructor(message, code, data) {\n        super(message);\n        this.message = message;\n        this.code = code;\n        this.data = data;\n    }\n}\nexport const getPlatformId = (win) => {\n    var _a, _b;\n    if (win === null || win === void 0 ? void 0 : win.androidBridge) {\n        return 'android';\n    }\n    else if ((_b = (_a = win === null || win === void 0 ? void 0 : win.webkit) === null || _a === void 0 ? void 0 : _a.messageHandlers) === null || _b === void 0 ? void 0 : _b.bridge) {\n        return 'ios';\n    }\n    else {\n        return 'web';\n    }\n};\n//# sourceMappingURL=util.js.map", "import { CapacitorException, getPlatformId, ExceptionCode } from './util';\nexport const createCapacitor = (win) => {\n    const capCustomPlatform = win.CapacitorCustomPlatform || null;\n    const cap = win.Capacitor || {};\n    const Plugins = (cap.Plugins = cap.Plugins || {});\n    const getPlatform = () => {\n        return capCustomPlatform !== null ? capCustomPlatform.name : getPlatformId(win);\n    };\n    const isNativePlatform = () => getPlatform() !== 'web';\n    const isPluginAvailable = (pluginName) => {\n        const plugin = registeredPlugins.get(pluginName);\n        if (plugin === null || plugin === void 0 ? void 0 : plugin.platforms.has(getPlatform())) {\n            // JS implementation available for the current platform.\n            return true;\n        }\n        if (getPluginHeader(pluginName)) {\n            // Native implementation available.\n            return true;\n        }\n        return false;\n    };\n    const getPluginHeader = (pluginName) => { var _a; return (_a = cap.PluginHeaders) === null || _a === void 0 ? void 0 : _a.find((h) => h.name === pluginName); };\n    const handleError = (err) => win.console.error(err);\n    const registeredPlugins = new Map();\n    const registerPlugin = (pluginName, jsImplementations = {}) => {\n        const registeredPlugin = registeredPlugins.get(pluginName);\n        if (registeredPlugin) {\n            console.warn(`Capacitor plugin \"${pluginName}\" already registered. Cannot register plugins twice.`);\n            return registeredPlugin.proxy;\n        }\n        const platform = getPlatform();\n        const pluginHeader = getPluginHeader(pluginName);\n        let jsImplementation;\n        const loadPluginImplementation = async () => {\n            if (!jsImplementation && platform in jsImplementations) {\n                jsImplementation =\n                    typeof jsImplementations[platform] === 'function'\n                        ? (jsImplementation = await jsImplementations[platform]())\n                        : (jsImplementation = jsImplementations[platform]);\n            }\n            else if (capCustomPlatform !== null && !jsImplementation && 'web' in jsImplementations) {\n                jsImplementation =\n                    typeof jsImplementations['web'] === 'function'\n                        ? (jsImplementation = await jsImplementations['web']())\n                        : (jsImplementation = jsImplementations['web']);\n            }\n            return jsImplementation;\n        };\n        const createPluginMethod = (impl, prop) => {\n            var _a, _b;\n            if (pluginHeader) {\n                const methodHeader = pluginHeader === null || pluginHeader === void 0 ? void 0 : pluginHeader.methods.find((m) => prop === m.name);\n                if (methodHeader) {\n                    if (methodHeader.rtype === 'promise') {\n                        return (options) => cap.nativePromise(pluginName, prop.toString(), options);\n                    }\n                    else {\n                        return (options, callback) => cap.nativeCallback(pluginName, prop.toString(), options, callback);\n                    }\n                }\n                else if (impl) {\n                    return (_a = impl[prop]) === null || _a === void 0 ? void 0 : _a.bind(impl);\n                }\n            }\n            else if (impl) {\n                return (_b = impl[prop]) === null || _b === void 0 ? void 0 : _b.bind(impl);\n            }\n            else {\n                throw new CapacitorException(`\"${pluginName}\" plugin is not implemented on ${platform}`, ExceptionCode.Unimplemented);\n            }\n        };\n        const createPluginMethodWrapper = (prop) => {\n            let remove;\n            const wrapper = (...args) => {\n                const p = loadPluginImplementation().then((impl) => {\n                    const fn = createPluginMethod(impl, prop);\n                    if (fn) {\n                        const p = fn(...args);\n                        remove = p === null || p === void 0 ? void 0 : p.remove;\n                        return p;\n                    }\n                    else {\n                        throw new CapacitorException(`\"${pluginName}.${prop}()\" is not implemented on ${platform}`, ExceptionCode.Unimplemented);\n                    }\n                });\n                if (prop === 'addListener') {\n                    p.remove = async () => remove();\n                }\n                return p;\n            };\n            // Some flair ✨\n            wrapper.toString = () => `${prop.toString()}() { [capacitor code] }`;\n            Object.defineProperty(wrapper, 'name', {\n                value: prop,\n                writable: false,\n                configurable: false,\n            });\n            return wrapper;\n        };\n        const addListener = createPluginMethodWrapper('addListener');\n        const removeListener = createPluginMethodWrapper('removeListener');\n        const addListenerNative = (eventName, callback) => {\n            const call = addListener({ eventName }, callback);\n            const remove = async () => {\n                const callbackId = await call;\n                removeListener({\n                    eventName,\n                    callbackId,\n                }, callback);\n            };\n            const p = new Promise((resolve) => call.then(() => resolve({ remove })));\n            p.remove = async () => {\n                console.warn(`Using addListener() without 'await' is deprecated.`);\n                await remove();\n            };\n            return p;\n        };\n        const proxy = new Proxy({}, {\n            get(_, prop) {\n                switch (prop) {\n                    // https://github.com/facebook/react/issues/20030\n                    case '$$typeof':\n                        return undefined;\n                    case 'toJSON':\n                        return () => ({});\n                    case 'addListener':\n                        return pluginHeader ? addListenerNative : addListener;\n                    case 'removeListener':\n                        return removeListener;\n                    default:\n                        return createPluginMethodWrapper(prop);\n                }\n            },\n        });\n        Plugins[pluginName] = proxy;\n        registeredPlugins.set(pluginName, {\n            name: pluginName,\n            proxy,\n            platforms: new Set([...Object.keys(jsImplementations), ...(pluginHeader ? [platform] : [])]),\n        });\n        return proxy;\n    };\n    // Add in convertFileSrc for web, it will already be available in native context\n    if (!cap.convertFileSrc) {\n        cap.convertFileSrc = (filePath) => filePath;\n    }\n    cap.getPlatform = getPlatform;\n    cap.handleError = handleError;\n    cap.isNativePlatform = isNativePlatform;\n    cap.isPluginAvailable = isPluginAvailable;\n    cap.registerPlugin = registerPlugin;\n    cap.Exception = CapacitorException;\n    cap.DEBUG = !!cap.DEBUG;\n    cap.isLoggingEnabled = !!cap.isLoggingEnabled;\n    return cap;\n};\nexport const initCapacitorGlobal = (win) => (win.Capacitor = createCapacitor(win));\n//# sourceMappingURL=runtime.js.map", "import { initCapacitorGlobal } from './runtime';\nexport const Capacitor = /*#__PURE__*/ initCapacitorGlobal(typeof globalThis !== 'undefined'\n    ? globalThis\n    : typeof self !== 'undefined'\n        ? self\n        : typeof window !== 'undefined'\n            ? window\n            : typeof global !== 'undefined'\n                ? global\n                : {});\nexport const registerPlugin = Capacitor.registerPlugin;\n//# sourceMappingURL=global.js.map", "import { Capacitor } from './global';\nimport { ExceptionCode } from './util';\n/**\n * Base class web plugins should extend.\n */\nexport class WebPlugin {\n    constructor() {\n        this.listeners = {};\n        this.retainedEventArguments = {};\n        this.windowListeners = {};\n    }\n    addListener(eventName, listenerFunc) {\n        let firstListener = false;\n        const listeners = this.listeners[eventName];\n        if (!listeners) {\n            this.listeners[eventName] = [];\n            firstListener = true;\n        }\n        this.listeners[eventName].push(listenerFunc);\n        // If we haven't added a window listener for this event and it requires one,\n        // go ahead and add it\n        const windowListener = this.windowListeners[eventName];\n        if (windowListener && !windowListener.registered) {\n            this.addWindowListener(windowListener);\n        }\n        if (firstListener) {\n            this.sendRetainedArgumentsForEvent(eventName);\n        }\n        const remove = async () => this.removeListener(eventName, listenerFunc);\n        const p = Promise.resolve({ remove });\n        return p;\n    }\n    async removeAllListeners() {\n        this.listeners = {};\n        for (const listener in this.windowListeners) {\n            this.removeWindowListener(this.windowListeners[listener]);\n        }\n        this.windowListeners = {};\n    }\n    notifyListeners(eventName, data, retainUntilConsumed) {\n        const listeners = this.listeners[eventName];\n        if (!listeners) {\n            if (retainUntilConsumed) {\n                let args = this.retainedEventArguments[eventName];\n                if (!args) {\n                    args = [];\n                }\n                args.push(data);\n                this.retainedEventArguments[eventName] = args;\n            }\n            return;\n        }\n        listeners.forEach((listener) => listener(data));\n    }\n    hasListeners(eventName) {\n        var _a;\n        return !!((_a = this.listeners[eventName]) === null || _a === void 0 ? void 0 : _a.length);\n    }\n    registerWindowListener(windowEventName, pluginEventName) {\n        this.windowListeners[pluginEventName] = {\n            registered: false,\n            windowEventName,\n            pluginEventName,\n            handler: (event) => {\n                this.notifyListeners(pluginEventName, event);\n            },\n        };\n    }\n    unimplemented(msg = 'not implemented') {\n        return new Capacitor.Exception(msg, ExceptionCode.Unimplemented);\n    }\n    unavailable(msg = 'not available') {\n        return new Capacitor.Exception(msg, ExceptionCode.Unavailable);\n    }\n    async removeListener(eventName, listenerFunc) {\n        const listeners = this.listeners[eventName];\n        if (!listeners) {\n            return;\n        }\n        const index = listeners.indexOf(listenerFunc);\n        if (index !== -1) {\n            this.listeners[eventName].splice(index, 1);\n        }\n        // If there are no more listeners for this type of event,\n        // remove the window listener\n        if (!this.listeners[eventName].length) {\n            this.removeWindowListener(this.windowListeners[eventName]);\n        }\n    }\n    addWindowListener(handle) {\n        window.addEventListener(handle.windowEventName, handle.handler);\n        handle.registered = true;\n    }\n    removeWindowListener(handle) {\n        if (!handle) {\n            return;\n        }\n        window.removeEventListener(handle.windowEventName, handle.handler);\n        handle.registered = false;\n    }\n    sendRetainedArgumentsForEvent(eventName) {\n        const args = this.retainedEventArguments[eventName];\n        if (!args) {\n            return;\n        }\n        delete this.retainedEventArguments[eventName];\n        args.forEach((arg) => {\n            this.notifyListeners(eventName, arg);\n        });\n    }\n}\n//# sourceMappingURL=web-plugin.js.map", "import { registerPlugin } from './global';\nimport { WebPlugin } from './web-plugin';\nexport const WebView = /*#__PURE__*/ registerPlugin('WebView');\n/******** END WEB VIEW PLUGIN ********/\n/******** COOKIES PLUGIN ********/\n/**\n * Safely web encode a string value (inspired by js-cookie)\n * @param str The string value to encode\n */\nconst encode = (str) => encodeURIComponent(str)\n    .replace(/%(2[346B]|5E|60|7C)/g, decodeURIComponent)\n    .replace(/[()]/g, escape);\n/**\n * Safely web decode a string value (inspired by js-cookie)\n * @param str The string value to decode\n */\nconst decode = (str) => str.replace(/(%[\\dA-F]{2})+/gi, decodeURIComponent);\nexport class CapacitorCookiesPluginWeb extends WebPlugin {\n    async getCookies() {\n        const cookies = document.cookie;\n        const cookieMap = {};\n        cookies.split(';').forEach((cookie) => {\n            if (cookie.length <= 0)\n                return;\n            // Replace first \"=\" with CAP_COOKIE to prevent splitting on additional \"=\"\n            let [key, value] = cookie.replace(/=/, 'CAP_COOKIE').split('CAP_COOKIE');\n            key = decode(key).trim();\n            value = decode(value).trim();\n            cookieMap[key] = value;\n        });\n        return cookieMap;\n    }\n    async setCookie(options) {\n        try {\n            // Safely Encoded Key/Value\n            const encodedKey = encode(options.key);\n            const encodedValue = encode(options.value);\n            // Clean & sanitize options\n            const expires = options.expires ? `; expires=${options.expires.replace('expires=', '')}` : '';\n            const path = (options.path || '/').replace('path=', ''); // Default is \"path=/\"\n            const domain = options.url != null && options.url.length > 0 ? `domain=${options.url}` : '';\n            document.cookie = `${encodedKey}=${encodedValue || ''}${expires}; path=${path}; ${domain};`;\n        }\n        catch (error) {\n            return Promise.reject(error);\n        }\n    }\n    async deleteCookie(options) {\n        try {\n            document.cookie = `${options.key}=; Max-Age=0`;\n        }\n        catch (error) {\n            return Promise.reject(error);\n        }\n    }\n    async clearCookies() {\n        try {\n            const cookies = document.cookie.split(';') || [];\n            for (const cookie of cookies) {\n                document.cookie = cookie.replace(/^ +/, '').replace(/=.*/, `=;expires=${new Date().toUTCString()};path=/`);\n            }\n        }\n        catch (error) {\n            return Promise.reject(error);\n        }\n    }\n    async clearAllCookies() {\n        try {\n            await this.clearCookies();\n        }\n        catch (error) {\n            return Promise.reject(error);\n        }\n    }\n}\nexport const CapacitorCookies = registerPlugin('CapacitorCookies', {\n    web: () => new CapacitorCookiesPluginWeb(),\n});\n// UTILITY FUNCTIONS\n/**\n * Read in a Blob value and return it as a base64 string\n * @param blob The blob value to convert to a base64 string\n */\nexport const readBlobAsBase64 = async (blob) => new Promise((resolve, reject) => {\n    const reader = new FileReader();\n    reader.onload = () => {\n        const base64String = reader.result;\n        // remove prefix \"data:application/pdf;base64,\"\n        resolve(base64String.indexOf(',') >= 0 ? base64String.split(',')[1] : base64String);\n    };\n    reader.onerror = (error) => reject(error);\n    reader.readAsDataURL(blob);\n});\n/**\n * Normalize an HttpHeaders map by lowercasing all of the values\n * @param headers The HttpHeaders object to normalize\n */\nconst normalizeHttpHeaders = (headers = {}) => {\n    const originalKeys = Object.keys(headers);\n    const loweredKeys = Object.keys(headers).map((k) => k.toLocaleLowerCase());\n    const normalized = loweredKeys.reduce((acc, key, index) => {\n        acc[key] = headers[originalKeys[index]];\n        return acc;\n    }, {});\n    return normalized;\n};\n/**\n * Builds a string of url parameters that\n * @param params A map of url parameters\n * @param shouldEncode true if you should encodeURIComponent() the values (true by default)\n */\nconst buildUrlParams = (params, shouldEncode = true) => {\n    if (!params)\n        return null;\n    const output = Object.entries(params).reduce((accumulator, entry) => {\n        const [key, value] = entry;\n        let encodedValue;\n        let item;\n        if (Array.isArray(value)) {\n            item = '';\n            value.forEach((str) => {\n                encodedValue = shouldEncode ? encodeURIComponent(str) : str;\n                item += `${key}=${encodedValue}&`;\n            });\n            // last character will always be \"&\" so slice it off\n            item.slice(0, -1);\n        }\n        else {\n            encodedValue = shouldEncode ? encodeURIComponent(value) : value;\n            item = `${key}=${encodedValue}`;\n        }\n        return `${accumulator}&${item}`;\n    }, '');\n    // Remove initial \"&\" from the reduce\n    return output.substr(1);\n};\n/**\n * Build the RequestInit object based on the options passed into the initial request\n * @param options The Http plugin options\n * @param extra Any extra RequestInit values\n */\nexport const buildRequestInit = (options, extra = {}) => {\n    const output = Object.assign({ method: options.method || 'GET', headers: options.headers }, extra);\n    // Get the content-type\n    const headers = normalizeHttpHeaders(options.headers);\n    const type = headers['content-type'] || '';\n    // If body is already a string, then pass it through as-is.\n    if (typeof options.data === 'string') {\n        output.body = options.data;\n    }\n    // Build request initializers based off of content-type\n    else if (type.includes('application/x-www-form-urlencoded')) {\n        const params = new URLSearchParams();\n        for (const [key, value] of Object.entries(options.data || {})) {\n            params.set(key, value);\n        }\n        output.body = params.toString();\n    }\n    else if (type.includes('multipart/form-data') || options.data instanceof FormData) {\n        const form = new FormData();\n        if (options.data instanceof FormData) {\n            options.data.forEach((value, key) => {\n                form.append(key, value);\n            });\n        }\n        else {\n            for (const key of Object.keys(options.data)) {\n                form.append(key, options.data[key]);\n            }\n        }\n        output.body = form;\n        const headers = new Headers(output.headers);\n        headers.delete('content-type'); // content-type will be set by `window.fetch` to includy boundary\n        output.headers = headers;\n    }\n    else if (type.includes('application/json') || typeof options.data === 'object') {\n        output.body = JSON.stringify(options.data);\n    }\n    return output;\n};\n// WEB IMPLEMENTATION\nexport class CapacitorHttpPluginWeb extends WebPlugin {\n    /**\n     * Perform an Http request given a set of options\n     * @param options Options to build the HTTP request\n     */\n    async request(options) {\n        const requestInit = buildRequestInit(options, options.webFetchExtra);\n        const urlParams = buildUrlParams(options.params, options.shouldEncodeUrlParams);\n        const url = urlParams ? `${options.url}?${urlParams}` : options.url;\n        const response = await fetch(url, requestInit);\n        const contentType = response.headers.get('content-type') || '';\n        // Default to 'text' responseType so no parsing happens\n        let { responseType = 'text' } = response.ok ? options : {};\n        // If the response content-type is json, force the response to be json\n        if (contentType.includes('application/json')) {\n            responseType = 'json';\n        }\n        let data;\n        let blob;\n        switch (responseType) {\n            case 'arraybuffer':\n            case 'blob':\n                blob = await response.blob();\n                data = await readBlobAsBase64(blob);\n                break;\n            case 'json':\n                data = await response.json();\n                break;\n            case 'document':\n            case 'text':\n            default:\n                data = await response.text();\n        }\n        // Convert fetch headers to Capacitor HttpHeaders\n        const headers = {};\n        response.headers.forEach((value, key) => {\n            headers[key] = value;\n        });\n        return {\n            data,\n            headers,\n            status: response.status,\n            url: response.url,\n        };\n    }\n    /**\n     * Perform an Http GET request given a set of options\n     * @param options Options to build the HTTP request\n     */\n    async get(options) {\n        return this.request(Object.assign(Object.assign({}, options), { method: 'GET' }));\n    }\n    /**\n     * Perform an Http POST request given a set of options\n     * @param options Options to build the HTTP request\n     */\n    async post(options) {\n        return this.request(Object.assign(Object.assign({}, options), { method: 'POST' }));\n    }\n    /**\n     * Perform an Http PUT request given a set of options\n     * @param options Options to build the HTTP request\n     */\n    async put(options) {\n        return this.request(Object.assign(Object.assign({}, options), { method: 'PUT' }));\n    }\n    /**\n     * Perform an Http PATCH request given a set of options\n     * @param options Options to build the HTTP request\n     */\n    async patch(options) {\n        return this.request(Object.assign(Object.assign({}, options), { method: 'PATCH' }));\n    }\n    /**\n     * Perform an Http DELETE request given a set of options\n     * @param options Options to build the HTTP request\n     */\n    async delete(options) {\n        return this.request(Object.assign(Object.assign({}, options), { method: 'DELETE' }));\n    }\n}\nexport const CapacitorHttp = registerPlugin('CapacitorHttp', {\n    web: () => new CapacitorHttpPluginWeb(),\n});\n/******** END HTTP PLUGIN ********/\n/******** SYSTEM BARS PLUGIN ********/\n/**\n * Available status bar styles.\n */\nexport var SystemBarsStyle;\n(function (SystemBarsStyle) {\n    /**\n     * Light system bar content on a dark background.\n     *\n     * @since 8.0.0\n     */\n    SystemBarsStyle[\"Dark\"] = \"DARK\";\n    /**\n     * For dark system bar content on a light background.\n     *\n     * @since 8.0.0\n     */\n    SystemBarsStyle[\"Light\"] = \"LIGHT\";\n    /**\n     * The style is based on the device appearance or the underlying content.\n     * If the device is using Dark mode, the system bars content will be light.\n     * If the device is using Light mode, the system bars content will be dark.\n     *\n     * @since 8.0.0\n     */\n    SystemBarsStyle[\"Default\"] = \"DEFAULT\";\n})(SystemBarsStyle || (SystemBarsStyle = {}));\n/**\n * Available system bar types.\n */\nexport var SystemBarType;\n(function (SystemBarType) {\n    /**\n     * The top status bar on both Android and iOS.\n     *\n     * @since 8.0.0\n     */\n    SystemBarType[\"StatusBar\"] = \"StatusBar\";\n    /**\n     * The navigation bar (or gesture bar on iOS) on both Android and iOS.\n     *\n     * @since 8.0.0\n     */\n    SystemBarType[\"NavigationBar\"] = \"NavigationBar\";\n})(SystemBarType || (SystemBarType = {}));\nexport class SystemBarsPluginWeb extends WebPlugin {\n    async setStyle() {\n        this.unavailable('not available for web');\n    }\n    async setAnimation() {\n        this.unavailable('not available for web');\n    }\n    async show() {\n        this.unavailable('not available for web');\n    }\n    async hide() {\n        this.unavailable('not available for web');\n    }\n}\nexport const SystemBars = registerPlugin('SystemBars', {\n    web: () => new SystemBarsPluginWeb(),\n});\n/******** END SYSTEM BARS PLUGIN ********/\n//# sourceMappingURL=core-plugins.js.map", "import type { HttpOptions, PermissionState, PluginListenerHandle } from '@capacitor/core';\n\nexport type CallbackID = string;\n\nexport interface PermissionStatus {\n  publicStorage: PermissionState;\n}\n\nexport enum Directory {\n  /**\n   * The Documents directory.\n   * On iOS it's the app's documents directory.\n   * Use this directory to store user-generated content.\n   * On Android it's the Public Documents folder, so it's accessible from other apps.\n   * It's not accessible on Android 10 unless the app enables legacy External Storage\n   * by adding `android:requestLegacyExternalStorage=\"true\"` in the `application` tag\n   * in the `AndroidManifest.xml`.\n   * On Android 11 or newer the app can only access the files/folders the app created.\n   *\n   * @since 1.0.0\n   */\n  Documents = 'DOCUMENTS',\n\n  /**\n   * The Data directory.\n   * On iOS it will use the Documents directory.\n   * On Android it's the directory holding application files.\n   * Files will be deleted when the application is uninstalled.\n   *\n   * @since 1.0.0\n   */\n  Data = 'DATA',\n\n  /**\n   * The Library directory.\n   * On iOS it will use the Library directory.\n   * On Android it's the directory holding application files.\n   * Files will be deleted when the application is uninstalled.\n   *\n   * @since 1.1.0\n   */\n  Library = 'LIBRARY',\n\n  /**\n   * The Cache directory.\n   * Can be deleted in cases of low memory, so use this directory to write app-specific files.\n   * that your app can re-create easily.\n   *\n   * @since 1.0.0\n   */\n  Cache = 'CACHE',\n\n  /**\n   * The external directory.\n   * On iOS it will use the Documents directory.\n   * On Android it's the directory on the primary shared/external\n   * storage device where the application can place persistent files it owns.\n   * These files are internal to the applications, and not typically visible\n   * to the user as media.\n   * Files will be deleted when the application is uninstalled.\n   *\n   * @since 1.0.0\n   */\n  External = 'EXTERNAL',\n\n  /**\n   * The external storage directory.\n   * On iOS it will use the Documents directory.\n   * On Android it's the primary shared/external storage directory.\n   * It's not accessible on Android 10 unless the app enables legacy External Storage\n   * by adding `android:requestLegacyExternalStorage=\"true\"` in the `application` tag\n   * in the `AndroidManifest.xml`.\n   * It's not accessible on Android 11 or newer.\n   *\n   * @since 1.0.0\n   */\n\n  ExternalStorage = 'EXTERNAL_STORAGE',\n  /**\n   * The external cache directory.\n   * On iOS it will use the Documents directory.\n   * On Android it's the primary shared/external cache.\n   *\n   * @since 7.1.0\n   */\n  ExternalCache = 'EXTERNAL_CACHE',\n\n  /**\n   * The Library directory without cloud backup. Used in iOS.\n   * On Android it's the directory holding application files.\n   *\n   * @since 7.1.0\n   */\n  LibraryNoCloud = 'LIBRARY_NO_CLOUD',\n\n  /**\n   * A temporary directory for iOS.\n   * On Android it's the directory holding the application cache.\n   *\n   * @since 7.1.0\n   */\n  Temporary = 'TEMPORARY',\n}\n\nexport enum Encoding {\n  /**\n   * Eight-bit UCS Transformation Format\n   *\n   * @since 1.0.0\n   */\n  UTF8 = 'utf8',\n\n  /**\n   * Seven-bit ASCII, a.k.a. ISO646-US, a.k.a. the Basic Latin block of the\n   * Unicode character set\n   * This encoding is only supported on Android.\n   *\n   * @since 1.0.0\n   */\n  ASCII = 'ascii',\n\n  /**\n   * Sixteen-bit UCS Transformation Format, byte order identified by an\n   * optional byte-order mark\n   * This encoding is only supported on Android.\n   *\n   * @since 1.0.0\n   */\n  UTF16 = 'utf16',\n}\n\nexport interface WriteFileOptions {\n  /**\n   * The path of the file to write\n   *\n   * @since 1.0.0\n   */\n  path: string;\n\n  /**\n   * The data to write\n   *\n   * Note: Blob data is only supported on Web.\n   *\n   * @since 1.0.0\n   */\n  data: string | Blob;\n\n  /**\n   * The `Directory` to store the file in\n   *\n   * @since 1.0.0\n   */\n  directory?: Directory;\n\n  /**\n   * The encoding to write the file in.\n   * If not provided, binary data will be written. For this, you must provide data as base64 encoded,\n   * so that the plugin can decode it before writing to disk.\n   * If you do not provide encoding and use non-base64 data, an error will be thrown.\n   *\n   * Pass Encoding.UTF8 to write data as string\n   *\n   * @since 1.0.0\n   */\n  encoding?: Encoding;\n\n  /**\n   * Whether to create any missing parent directories.\n   *\n   * @default false\n   * @since 1.0.0\n   */\n  recursive?: boolean;\n}\n\nexport interface AppendFileOptions {\n  /**\n   * The path of the file to append\n   *\n   * @since 1.0.0\n   */\n  path: string;\n\n  /**\n   * The data to append\n   *\n   * @since 1.0.0\n   */\n  data: string;\n\n  /**\n   * The `Directory` to store the file in\n   *\n   * @since 1.0.0\n   */\n  directory?: Directory;\n\n  /**\n   * The encoding to append to the file.\n   * If not provided, binary data will be appended. For this, you must provide data as base64 encoded,\n   * so that the plugin can decode it before writing to disk.\n   * If you do not provide encoding and use non-base64 data, an error will be thrown.\n   *\n   * Pass Encoding.UTF8 to write data as string\n   *\n   * @since 1.0.0\n   */\n  encoding?: Encoding;\n}\n\nexport interface ReadFileOptions {\n  /**\n   * The path of the file to read\n   *\n   * @since 1.0.0\n   */\n  path: string;\n\n  /**\n   * The `Directory` to read the file from\n   *\n   * @since 1.0.0\n   */\n  directory?: Directory;\n\n  /**\n   * The encoding to read the file in, if not provided, data\n   * is read as binary and returned as base64 encoded.\n   *\n   * Pass Encoding.UTF8 to read data as string\n   *\n   * @since 1.0.0\n   */\n  encoding?: Encoding;\n\n  /**\n   * The offset to start reading the file from, in bytes.\n   * Native only (not available in web).\n   * Can be used in conjunction with length to partially read files.\n   *\n   * @since 8.1.0\n   * @default 0\n   */\n  offset?: number;\n\n  /**\n   * The length of data to read, in bytes.\n   * Any non-positive value means to read to the end of the file.\n   * Native only (not available in web).\n   * Can be used in conjunction with offset to partially read files.\n   *\n   * @since 8.1.0\n   * @default -1\n   */\n  length?: number;\n}\n\nexport interface ReadFileInChunksOptions extends ReadFileOptions {\n  /**\n   * Size of the chunks in bytes.\n   *\n   * @since 7.1.0\n   */\n  chunkSize: number;\n}\n\nexport interface DeleteFileOptions {\n  /**\n   * The path of the file to delete\n   *\n   * @since 1.0.0\n   */\n  path: string;\n\n  /**\n   * The `Directory` to delete the file from\n   *\n   * @since 1.0.0\n   */\n  directory?: Directory;\n}\n\nexport interface MkdirOptions {\n  /**\n   * The path of the new directory\n   *\n   * @since 1.0.0\n   */\n  path: string;\n\n  /**\n   * The `Directory` to make the new directory in\n   *\n   * @since 1.0.0\n   */\n  directory?: Directory;\n\n  /**\n   * Whether to create any missing parent directories as well.\n   *\n   * @default false\n   * @since 1.0.0\n   */\n  recursive?: boolean;\n}\n\nexport interface RmdirOptions {\n  /**\n   * The path of the directory to remove\n   *\n   * @since 1.0.0\n   */\n  path: string;\n\n  /**\n   * The `Directory` to remove the directory from\n   *\n   * @since 1.0.0\n   */\n  directory?: Directory;\n\n  /**\n   * Whether to recursively remove the contents of the directory\n   *\n   * @default false\n   * @since 1.0.0\n   */\n  recursive?: boolean;\n}\n\nexport interface ReaddirOptions {\n  /**\n   * The path of the directory to read\n   *\n   * @since 1.0.0\n   */\n  path: string;\n\n  /**\n   * The `Directory` to list files from\n   *\n   * @since 1.0.0\n   */\n  directory?: Directory;\n}\n\nexport interface GetUriOptions {\n  /**\n   * The path of the file to get the URI for\n   *\n   * @since 1.0.0\n   */\n  path: string;\n\n  /**\n   * The `Directory` to get the file under\n   *\n   * @since 1.0.0\n   */\n  directory: Directory;\n}\n\nexport interface StatOptions {\n  /**\n   * The path of the file to get data about\n   *\n   * @since 1.0.0\n   */\n  path: string;\n\n  /**\n   * The `Directory` to get the file under\n   *\n   * @since 1.0.0\n   */\n  directory?: Directory;\n}\n\nexport interface CopyOptions {\n  /**\n   * The existing file or directory\n   *\n   * @since 1.0.0\n   */\n  from: string;\n\n  /**\n   * The destination file or directory\n   *\n   * @since 1.0.0\n   */\n  to: string;\n\n  /**\n   * The `Directory` containing the existing file or directory\n   *\n   * @since 1.0.0\n   */\n  directory?: Directory;\n\n  /**\n   * The `Directory` containing the destination file or directory. If not supplied will use the 'directory'\n   * parameter as the destination\n   *\n   * @since 1.0.0\n   */\n  toDirectory?: Directory;\n}\n\nexport type RenameOptions = CopyOptions;\n\nexport interface ReadFileResult {\n  /**\n   * The representation of the data contained in the file\n   *\n   * Note: Blob is only available on Web. On native, the data is returned as a string.\n   *\n   * @since 1.0.0\n   */\n  data: string | Blob;\n}\n\nexport interface WriteFileResult {\n  /**\n   * The uri where the file was written into\n   *\n   * @since 1.0.0\n   */\n  uri: string;\n}\n\nexport interface ReaddirResult {\n  /**\n   * List of files and directories inside the directory\n   *\n   * @since 1.0.0\n   */\n  files: FileInfo[];\n}\n\nexport interface FileInfo {\n  /**\n   * Name of the file or directory.\n   *\n   * @since 7.1.0\n   */\n  name: string;\n\n  /**\n   * Type of the file.\n   *\n   * @since 4.0.0\n   */\n  type: 'directory' | 'file';\n\n  /**\n   * Size of the file in bytes.\n   *\n   * @since 4.0.0\n   */\n  size: number;\n\n  /**\n   * Time of creation in milliseconds.\n   *\n   * It's not available on Android 7 and older devices.\n   *\n   * @since 7.1.0\n   */\n  ctime?: number;\n\n  /**\n   * Time of last modification in milliseconds.\n   *\n   * @since 7.1.0\n   */\n  mtime: number;\n\n  /**\n   * The uri of the file.\n   *\n   * @since 4.0.0\n   */\n  uri: string;\n}\n\nexport interface GetUriResult {\n  /**\n   * The uri of the file\n   *\n   * @since 1.0.0\n   */\n  uri: string;\n}\n\nexport type StatResult = FileInfo;\nexport interface CopyResult {\n  /**\n   * The uri where the file was copied into\n   *\n   * @since 4.0.0\n   */\n  uri: string;\n}\n\nexport interface DownloadFileOptions extends HttpOptions {\n  /**\n   * The path the downloaded file should be moved to.\n   *\n   * @since 5.1.0\n   */\n  path: string;\n  /**\n   * The directory to write the file to.\n   * If this option is used, filePath can be a relative path rather than absolute.\n   * The default is the `DATA` directory.\n   *\n   * @since 5.1.0\n   */\n  directory?: Directory;\n  /**\n   * An optional listener function to receive downloaded progress events.\n   * If this option is used, progress event should be dispatched on every chunk received.\n   * Chunks are throttled to every 100ms on Android/iOS to avoid slowdowns.\n   *\n   * @since 5.1.0\n   */\n  progress?: boolean;\n  /**\n   * Whether to create any missing parent directories.\n   *\n   * @default false\n   * @since 5.1.2\n   */\n  recursive?: boolean;\n}\n\nexport interface DownloadFileResult {\n  /**\n   * The path the file was downloaded to.\n   *\n   * @since 5.1.0\n   */\n  path?: string;\n  /**\n   * The blob data of the downloaded file.\n   * This is only available on web.\n   *\n   * @since 5.1.0\n   */\n  blob?: Blob;\n}\n\nexport interface ProgressStatus {\n  /**\n   * The url of the file being downloaded.\n   *\n   * @since 5.1.0\n   */\n  url: string;\n  /**\n   * The number of bytes downloaded so far.\n   *\n   * @since 5.1.0\n   */\n  bytes: number;\n  /**\n   * The total number of bytes to download for this file.\n   *\n   * @since 5.1.0\n   */\n  contentLength: number;\n}\n\n/**\n * Callback for receiving chunks read from a file, or error if something went wrong.\n *\n * @since 7.1.0\n */\nexport type ReadFileInChunksCallback = (chunkRead: ReadFileResult | null, err?: any) => void;\n\n/**\n * A listener function that receives progress events.\n *\n * @since 5.1.0\n */\nexport type ProgressListener = (progress: ProgressStatus) => void;\n\nexport interface FilesystemPlugin {\n  /**\n   * Check read/write permissions.\n   * Required on Android, only when using `Directory.Documents` or\n   * `Directory.ExternalStorage`.\n   *\n   * @since 1.0.0\n   */\n  checkPermissions(): Promise<PermissionStatus>;\n\n  /**\n   * Request read/write permissions.\n   * Required on Android, only when using `Directory.Documents` or\n   * `Directory.ExternalStorage`.\n   *\n   * @since 1.0.0\n   */\n  requestPermissions(): Promise<PermissionStatus>;\n\n  /**\n   * Read a file from disk\n   *\n   * @since 1.0.0\n   */\n  readFile(options: ReadFileOptions): Promise<ReadFileResult>;\n\n  /**\n   * Read a file from disk, in chunks.\n   * Native only (not available in web).\n   * Use the callback to receive each read chunk.\n   * If empty chunk is returned, it means file has been completely read.\n   *\n   * @since 7.1.0\n   */\n  readFileInChunks(options: ReadFileInChunksOptions, callback: ReadFileInChunksCallback): Promise<CallbackID>;\n\n  /**\n   * Write a file to disk in the specified location on device\n   *\n   * @since 1.0.0\n   */\n  writeFile(options: WriteFileOptions): Promise<WriteFileResult>;\n\n  /**\n   * Append to a file on disk in the specified location on device\n   *\n   * @since 1.0.0\n   */\n  appendFile(options: AppendFileOptions): Promise<void>;\n\n  /**\n   * Delete a file from disk\n   *\n   * @since 1.0.0\n   */\n  deleteFile(options: DeleteFileOptions): Promise<void>;\n\n  /**\n   * Create a directory.\n   *\n   * @since 1.0.0\n   */\n  mkdir(options: MkdirOptions): Promise<void>;\n\n  /**\n   * Remove a directory\n   *\n   * @since 1.0.0\n   */\n  rmdir(options: RmdirOptions): Promise<void>;\n\n  /**\n   * Return a list of files from the directory (not recursive)\n   *\n   * @since 1.0.0\n   */\n  readdir(options: ReaddirOptions): Promise<ReaddirResult>;\n\n  /**\n   * Return full File URI for a path and directory\n   *\n   * @since 1.0.0\n   */\n  getUri(options: GetUriOptions): Promise<GetUriResult>;\n\n  /**\n   * Return data about a file\n   *\n   * @since 1.0.0\n   */\n  stat(options: StatOptions): Promise<StatResult>;\n\n  /**\n   * Rename a file or directory\n   *\n   * @since 1.0.0\n   */\n  rename(options: RenameOptions): Promise<void>;\n\n  /**\n   * Copy a file or directory\n   *\n   * @since 1.0.0\n   */\n  copy(options: CopyOptions): Promise<CopyResult>;\n\n  /**\n   * Perform a http request to a server and download the file to the specified destination.\n   *\n   * This method has been deprecated since version 7.1.0.\n   * We recommend using the @capacitor/file-transfer plugin instead, in conjunction with this plugin.\n   *\n   * @since 5.1.0\n   * @deprecated Use the @capacitor/file-transfer plugin instead.\n   */\n  downloadFile(options: DownloadFileOptions): Promise<DownloadFileResult>;\n\n  /**\n   * Add a listener to file download progress events.\n   *\n   * This method has been deprecated since version 7.1.0.\n   * We recommend using the @capacitor/file-transfer plugin instead, in conjunction with this plugin.\n   *\n   * @since 5.1.0\n   * @deprecated Use the @capacitor/file-transfer plugin instead.\n   */\n  addListener(eventName: 'progress', listenerFunc: ProgressListener): Promise<PluginListenerHandle>;\n\n  /**\n   * Remove all listeners for this plugin.\n   *\n   * This method has been deprecated since version 7.1.0.\n   * We recommend using the @capacitor/file-transfer plugin instead, in conjunction with this plugin.\n   *\n   * @since 5.2.0\n   * @deprecated Use the @capacitor/file-transfer plugin instead.\n   */\n  removeAllListeners(): Promise<void>;\n}\n\n/**\n * Structure for errors returned by the plugin.\n *\n * `code` follows \"OS-PLUG-FILE-XXXX\" format\n *\n * @since 1.0.0\n */\nexport type PluginError = {\n  code: string;\n  message: string;\n};\n\n/**\n * @deprecated Use `ReadFileOptions`.\n * @since 1.0.0\n */\nexport type FileReadOptions = ReadFileOptions;\n\n/**\n * @deprecated Use `ReadFileResult`.\n * @since 1.0.0\n */\nexport type FileReadResult = ReadFileResult;\n\n/**\n * @deprecated Use `WriteFileOptions`.\n * @since 1.0.0\n */\nexport type FileWriteOptions = WriteFileOptions;\n\n/**\n * @deprecated Use `WriteFileResult`.\n * @since 1.0.0\n */\nexport type FileWriteResult = WriteFileResult;\n\n/**\n * @deprecated Use `AppendFileOptions`.\n * @since 1.0.0\n */\nexport type FileAppendOptions = AppendFileOptions;\n\n/**\n * @deprecated Use `DeleteFileOptions`.\n * @since 1.0.0\n */\nexport type FileDeleteOptions = DeleteFileOptions;\n\n/**\n * @deprecated Use `Directory`.\n * @since 1.0.0\n */\nexport const FilesystemDirectory = Directory;\n\n/**\n * @deprecated Use `Encoding`.\n * @since 1.0.0\n */\nexport const FilesystemEncoding = Encoding;\n", "import { WebPlugin, buildRequestInit } from '@capacitor/core';\n\nimport type {\n  AppendFileOptions,\n  CopyOptions,\n  CopyResult,\n  DeleteFileOptions,\n  FilesystemPlugin,\n  GetUriOptions,\n  GetUriResult,\n  MkdirOptions,\n  PermissionStatus,\n  ReadFileOptions,\n  ReadFileResult,\n  ReaddirOptions,\n  ReaddirResult,\n  RenameOptions,\n  RmdirOptions,\n  StatOptions,\n  StatResult,\n  WriteFileOptions,\n  WriteFileResult,\n  Directory,\n  ReadFileInChunksOptions,\n  CallbackID,\n  DownloadFileOptions,\n  DownloadFileResult,\n  ProgressStatus,\n  ReadFileInChunksCallback,\n} from './definitions';\nimport { Encoding } from './definitions';\n\nfunction resolve(path: string): string {\n  const posix = path.split('/').filter((item) => item !== '.');\n  const newPosix: string[] = [];\n\n  posix.forEach((item) => {\n    if (item === '..' && newPosix.length > 0 && newPosix[newPosix.length - 1] !== '..') {\n      newPosix.pop();\n    } else {\n      newPosix.push(item);\n    }\n  });\n\n  return newPosix.join('/');\n}\nfunction isPathParent(parent: string, children: string): boolean {\n  parent = resolve(parent);\n  children = resolve(children);\n  const pathsA = parent.split('/');\n  const pathsB = children.split('/');\n\n  return parent !== children && pathsA.every((value, index) => value === pathsB[index]);\n}\n\nexport class FilesystemWeb extends WebPlugin implements FilesystemPlugin {\n  readFileInChunks(_options: ReadFileInChunksOptions, _callback: ReadFileInChunksCallback): Promise<CallbackID> {\n    throw this.unavailable('Method not implemented.');\n  }\n  DB_VERSION = 1;\n  DB_NAME = 'Disc';\n\n  private _writeCmds: string[] = ['add', 'put', 'delete'];\n  private _db?: IDBDatabase;\n  static _debug = true;\n  async initDb(): Promise<IDBDatabase> {\n    if (this._db !== undefined) {\n      return this._db;\n    }\n    if (!('indexedDB' in window)) {\n      throw this.unavailable(\"This browser doesn't support IndexedDB\");\n    }\n\n    return new Promise<IDBDatabase>((resolve, reject) => {\n      const request = indexedDB.open(this.DB_NAME, this.DB_VERSION);\n      request.onupgradeneeded = FilesystemWeb.doUpgrade;\n      request.onsuccess = () => {\n        this._db = request.result;\n        resolve(request.result);\n      };\n      request.onerror = () => reject(request.error);\n      request.onblocked = () => {\n        console.warn('db blocked');\n      };\n    });\n  }\n\n  static doUpgrade(event: IDBVersionChangeEvent): void {\n    const eventTarget = event.target as IDBOpenDBRequest;\n    const db = eventTarget.result;\n    switch (event.oldVersion) {\n      case 0:\n      case 1:\n      default: {\n        if (db.objectStoreNames.contains('FileStorage')) {\n          db.deleteObjectStore('FileStorage');\n        }\n        const store = db.createObjectStore('FileStorage', { keyPath: 'path' });\n        store.createIndex('by_folder', 'folder');\n      }\n    }\n  }\n\n  async dbRequest(cmd: string, args: any[]): Promise<any> {\n    const readFlag = this._writeCmds.indexOf(cmd) !== -1 ? 'readwrite' : 'readonly';\n    return this.initDb().then((conn: IDBDatabase) => {\n      return new Promise<IDBObjectStore>((resolve, reject) => {\n        const tx: IDBTransaction = conn.transaction(['FileStorage'], readFlag);\n        const store: any = tx.objectStore('FileStorage');\n        const req = store[cmd](...args);\n        req.onsuccess = () => resolve(req.result);\n        req.onerror = () => reject(req.error);\n      });\n    });\n  }\n\n  async dbIndexRequest(indexName: string, cmd: string, args: [any]): Promise<any> {\n    const readFlag = this._writeCmds.indexOf(cmd) !== -1 ? 'readwrite' : 'readonly';\n    return this.initDb().then((conn: IDBDatabase) => {\n      return new Promise<IDBObjectStore>((resolve, reject) => {\n        const tx: IDBTransaction = conn.transaction(['FileStorage'], readFlag);\n        const store: IDBObjectStore = tx.objectStore('FileStorage');\n        const index: any = store.index(indexName);\n        const req = index[cmd](...args) as any;\n        req.onsuccess = () => resolve(req.result);\n        req.onerror = () => reject(req.error);\n      });\n    });\n  }\n\n  private getPath(directory: Directory | undefined, uriPath: string | undefined): string {\n    const cleanedUriPath = uriPath !== undefined ? uriPath.replace(/^[/]+|[/]+$/g, '') : '';\n    let fsPath = '';\n    if (directory !== undefined) fsPath += '/' + directory;\n    if (uriPath !== '') fsPath += '/' + cleanedUriPath;\n    return fsPath;\n  }\n\n  async clear(): Promise<void> {\n    const conn: IDBDatabase = await this.initDb();\n    const tx: IDBTransaction = conn.transaction(['FileStorage'], 'readwrite');\n    const store: IDBObjectStore = tx.objectStore('FileStorage');\n    store.clear();\n  }\n\n  /**\n   * Read a file from disk\n   * @param options options for the file read\n   * @return a promise that resolves with the read file data result\n   */\n  async readFile(options: ReadFileOptions): Promise<ReadFileResult> {\n    const path: string = this.getPath(options.directory, options.path);\n    // const encoding = options.encoding;\n\n    const entry = (await this.dbRequest('get', [path])) as EntryObj;\n    if (entry === undefined) throw Error('File does not exist.');\n    return { data: entry.content ? entry.content : '' };\n  }\n\n  /**\n   * Write a file to disk in the specified location on device\n   * @param options options for the file write\n   * @return a promise that resolves with the file write result\n   */\n  async writeFile(options: WriteFileOptions): Promise<WriteFileResult> {\n    const path: string = this.getPath(options.directory, options.path);\n    let data = options.data;\n    const encoding = options.encoding;\n    const doRecursive = options.recursive;\n\n    const occupiedEntry = (await this.dbRequest('get', [path])) as EntryObj;\n    if (occupiedEntry && occupiedEntry.type === 'directory') throw Error('The supplied path is a directory.');\n\n    const parentPath = path.substr(0, path.lastIndexOf('/'));\n\n    const parentEntry = (await this.dbRequest('get', [parentPath])) as EntryObj;\n    if (parentEntry === undefined) {\n      const subDirIndex = parentPath.indexOf('/', 1);\n      if (subDirIndex !== -1) {\n        const parentArgPath = parentPath.substr(subDirIndex);\n        await this.mkdir({\n          path: parentArgPath,\n          directory: options.directory,\n          recursive: doRecursive,\n        });\n      }\n    }\n\n    if (!encoding && !(data instanceof Blob)) {\n      data = data.indexOf(',') >= 0 ? data.split(',')[1] : data;\n      if (!this.isBase64String(data)) throw Error('The supplied data is not valid base64 content.');\n    }\n\n    const now = Date.now();\n    const pathObj: EntryObj = {\n      path: path,\n      folder: parentPath,\n      type: 'file',\n      size: data instanceof Blob ? data.size : data.length,\n      ctime: now,\n      mtime: now,\n      content: data,\n    };\n    await this.dbRequest('put', [pathObj]);\n    return {\n      uri: pathObj.path,\n    };\n  }\n\n  /**\n   * Append to a file on disk in the specified location on device\n   * @param options options for the file append\n   * @return a promise that resolves with the file write result\n   */\n  async appendFile(options: AppendFileOptions): Promise<void> {\n    const path: string = this.getPath(options.directory, options.path);\n    let data = options.data;\n    const encoding = options.encoding;\n    const parentPath = path.substr(0, path.lastIndexOf('/'));\n\n    const now = Date.now();\n    let ctime = now;\n\n    const occupiedEntry = (await this.dbRequest('get', [path])) as EntryObj;\n    if (occupiedEntry && occupiedEntry.type === 'directory') throw Error('The supplied path is a directory.');\n\n    const parentEntry = (await this.dbRequest('get', [parentPath])) as EntryObj;\n    if (parentEntry === undefined) {\n      const subDirIndex = parentPath.indexOf('/', 1);\n      if (subDirIndex !== -1) {\n        const parentArgPath = parentPath.substr(subDirIndex);\n        await this.mkdir({\n          path: parentArgPath,\n          directory: options.directory,\n          recursive: true,\n        });\n      }\n    }\n\n    if (!encoding && !this.isBase64String(data)) throw Error('The supplied data is not valid base64 content.');\n\n    if (occupiedEntry !== undefined) {\n      if (occupiedEntry.content instanceof Blob) {\n        throw Error('The occupied entry contains a Blob object which cannot be appended to.');\n      }\n\n      if (occupiedEntry.content !== undefined && !encoding) {\n        data = btoa(atob(occupiedEntry.content) + atob(data));\n      } else {\n        data = occupiedEntry.content + data;\n      }\n      ctime = occupiedEntry.ctime;\n    }\n    const pathObj: EntryObj = {\n      path: path,\n      folder: parentPath,\n      type: 'file',\n      size: data.length,\n      ctime: ctime,\n      mtime: now,\n      content: data,\n    };\n    await this.dbRequest('put', [pathObj]);\n  }\n\n  /**\n   * Delete a file from disk\n   * @param options options for the file delete\n   * @return a promise that resolves with the deleted file data result\n   */\n  async deleteFile(options: DeleteFileOptions): Promise<void> {\n    const path: string = this.getPath(options.directory, options.path);\n\n    const entry = (await this.dbRequest('get', [path])) as EntryObj;\n    if (entry === undefined) throw Error('File does not exist.');\n    const entries = await this.dbIndexRequest('by_folder', 'getAllKeys', [IDBKeyRange.only(path)]);\n    if (entries.length !== 0) throw Error('Folder is not empty.');\n\n    await this.dbRequest('delete', [path]);\n  }\n\n  /**\n   * Create a directory.\n   * @param options options for the mkdir\n   * @return a promise that resolves with the mkdir result\n   */\n  async mkdir(options: MkdirOptions): Promise<void> {\n    const path: string = this.getPath(options.directory, options.path);\n    const doRecursive = options.recursive;\n    const parentPath = path.substr(0, path.lastIndexOf('/'));\n\n    const depth = (path.match(/\\//g) || []).length;\n    const parentEntry = (await this.dbRequest('get', [parentPath])) as EntryObj;\n    const occupiedEntry = (await this.dbRequest('get', [path])) as EntryObj;\n    if (depth === 1) throw Error('Cannot create Root directory');\n    if (occupiedEntry !== undefined) throw Error('Current directory does already exist.');\n    if (!doRecursive && depth !== 2 && parentEntry === undefined) throw Error('Parent directory must exist');\n\n    if (doRecursive && depth !== 2 && parentEntry === undefined) {\n      const parentArgPath = parentPath.substr(parentPath.indexOf('/', 1));\n      await this.mkdir({\n        path: parentArgPath,\n        directory: options.directory,\n        recursive: doRecursive,\n      });\n    }\n    const now = Date.now();\n    const pathObj: EntryObj = {\n      path: path,\n      folder: parentPath,\n      type: 'directory',\n      size: 0,\n      ctime: now,\n      mtime: now,\n    };\n    await this.dbRequest('put', [pathObj]);\n  }\n\n  /**\n   * Remove a directory\n   * @param options the options for the directory remove\n   */\n  async rmdir(options: RmdirOptions): Promise<void> {\n    const { path, directory, recursive } = options;\n    const fullPath: string = this.getPath(directory, path);\n\n    const entry = (await this.dbRequest('get', [fullPath])) as EntryObj;\n\n    if (entry === undefined) throw Error('Folder does not exist.');\n\n    if (entry.type !== 'directory') throw Error('Requested path is not a directory');\n\n    const readDirResult = await this.readdir({ path, directory });\n\n    if (readDirResult.files.length !== 0 && !recursive) throw Error('Folder is not empty');\n\n    for (const entry of readDirResult.files) {\n      const entryPath = `${path}/${entry.name}`;\n      const entryObj = await this.stat({ path: entryPath, directory });\n      if (entryObj.type === 'file') {\n        await this.deleteFile({ path: entryPath, directory });\n      } else {\n        await this.rmdir({ path: entryPath, directory, recursive });\n      }\n    }\n\n    await this.dbRequest('delete', [fullPath]);\n  }\n\n  /**\n   * Return a list of files from the directory (not recursive)\n   * @param options the options for the readdir operation\n   * @return a promise that resolves with the readdir directory listing result\n   */\n  async readdir(options: ReaddirOptions): Promise<ReaddirResult> {\n    const path: string = this.getPath(options.directory, options.path);\n\n    const entry = (await this.dbRequest('get', [path])) as EntryObj;\n    if (options.path !== '' && entry === undefined) throw Error('Folder does not exist.');\n\n    const entries: string[] = await this.dbIndexRequest('by_folder', 'getAllKeys', [IDBKeyRange.only(path)]);\n    const files = await Promise.all(\n      entries.map(async (e) => {\n        let subEntry = (await this.dbRequest('get', [e])) as EntryObj;\n        if (subEntry === undefined) {\n          subEntry = (await this.dbRequest('get', [e + '/'])) as EntryObj;\n        }\n        return {\n          name: e.substring(path.length + 1),\n          type: subEntry.type,\n          size: subEntry.size,\n          ctime: subEntry.ctime,\n          mtime: subEntry.mtime,\n          uri: subEntry.path,\n        };\n      }),\n    );\n    return { files: files };\n  }\n\n  /**\n   * Return full File URI for a path and directory\n   * @param options the options for the stat operation\n   * @return a promise that resolves with the file stat result\n   */\n  async getUri(options: GetUriOptions): Promise<GetUriResult> {\n    const path: string = this.getPath(options.directory, options.path);\n\n    let entry = (await this.dbRequest('get', [path])) as EntryObj;\n    if (entry === undefined) {\n      entry = (await this.dbRequest('get', [path + '/'])) as EntryObj;\n    }\n    return {\n      uri: entry?.path || path,\n    };\n  }\n\n  /**\n   * Return data about a file\n   * @param options the options for the stat operation\n   * @return a promise that resolves with the file stat result\n   */\n  async stat(options: StatOptions): Promise<StatResult> {\n    const path: string = this.getPath(options.directory, options.path);\n\n    let entry = (await this.dbRequest('get', [path])) as EntryObj;\n    if (entry === undefined) {\n      entry = (await this.dbRequest('get', [path + '/'])) as EntryObj;\n    }\n    if (entry === undefined) throw Error('Entry does not exist.');\n\n    return {\n      name: entry.path.substring(path.length + 1),\n      type: entry.type,\n      size: entry.size,\n      ctime: entry.ctime,\n      mtime: entry.mtime,\n      uri: entry.path,\n    };\n  }\n\n  /**\n   * Rename a file or directory\n   * @param options the options for the rename operation\n   * @return a promise that resolves with the rename result\n   */\n  async rename(options: RenameOptions): Promise<void> {\n    await this._copy(options, true);\n    return;\n  }\n\n  /**\n   * Copy a file or directory\n   * @param options the options for the copy operation\n   * @return a promise that resolves with the copy result\n   */\n  async copy(options: CopyOptions): Promise<CopyResult> {\n    return this._copy(options, false);\n  }\n\n  async requestPermissions(): Promise<PermissionStatus> {\n    return { publicStorage: 'granted' };\n  }\n\n  async checkPermissions(): Promise<PermissionStatus> {\n    return { publicStorage: 'granted' };\n  }\n\n  /**\n   * Function that can perform a copy or a rename\n   * @param options the options for the rename operation\n   * @param doRename whether to perform a rename or copy operation\n   * @return a promise that resolves with the result\n   */\n  private async _copy(options: CopyOptions, doRename = false): Promise<CopyResult> {\n    let { toDirectory } = options;\n    const { to, from, directory: fromDirectory } = options;\n\n    if (!to || !from) {\n      throw Error('Both to and from must be provided');\n    }\n\n    // If no \"to\" directory is provided, use the \"from\" directory\n    if (!toDirectory) {\n      toDirectory = fromDirectory;\n    }\n\n    const fromPath = this.getPath(fromDirectory, from);\n    const toPath = this.getPath(toDirectory, to);\n\n    // Test that the \"to\" and \"from\" locations are different\n    if (fromPath === toPath) {\n      return {\n        uri: toPath,\n      };\n    }\n\n    if (isPathParent(fromPath, toPath)) {\n      throw Error('To path cannot contain the from path');\n    }\n\n    // Check the state of the \"to\" location\n    let toObj;\n    try {\n      toObj = await this.stat({\n        path: to,\n        directory: toDirectory,\n      });\n    } catch (e) {\n      // To location does not exist, ensure the directory containing \"to\" location exists and is a directory\n      const toPathComponents = to.split('/');\n      toPathComponents.pop();\n      const toPath = toPathComponents.join('/');\n\n      // Check the containing directory of the \"to\" location exists\n      if (toPathComponents.length > 0) {\n        const toParentDirectory = await this.stat({\n          path: toPath,\n          directory: toDirectory,\n        });\n\n        if (toParentDirectory.type !== 'directory') {\n          throw new Error('Parent directory of the to path is a file');\n        }\n      }\n    }\n\n    // Cannot overwrite a directory\n    if (toObj && toObj.type === 'directory') {\n      throw new Error('Cannot overwrite a directory with a file');\n    }\n\n    // Ensure the \"from\" object exists\n    const fromObj = await this.stat({\n      path: from,\n      directory: fromDirectory,\n    });\n\n    // Set the mtime/ctime of the supplied path\n    const updateTime = async (path: string, ctime: number, mtime: number) => {\n      const fullPath: string = this.getPath(toDirectory, path);\n      const entry = (await this.dbRequest('get', [fullPath])) as EntryObj;\n      entry.ctime = ctime;\n      entry.mtime = mtime;\n      await this.dbRequest('put', [entry]);\n    };\n\n    const ctime = fromObj.ctime ? fromObj.ctime : Date.now();\n\n    switch (fromObj.type) {\n      // The \"from\" object is a file\n      case 'file': {\n        // Read the file\n        const file = await this.readFile({\n          path: from,\n          directory: fromDirectory,\n        });\n\n        // Optionally remove the file\n        if (doRename) {\n          await this.deleteFile({\n            path: from,\n            directory: fromDirectory,\n          });\n        }\n\n        let encoding;\n        if (!(file.data instanceof Blob) && !this.isBase64String(file.data)) {\n          encoding = Encoding.UTF8;\n        }\n\n        // Write the file to the new location\n        const writeResult = await this.writeFile({\n          path: to,\n          directory: toDirectory,\n          data: file.data,\n          encoding: encoding,\n        });\n\n        // Copy the mtime/ctime of a renamed file\n        if (doRename) {\n          await updateTime(to, ctime, fromObj.mtime);\n        }\n\n        // Resolve promise\n        return writeResult;\n      }\n      case 'directory': {\n        if (toObj) {\n          throw Error('Cannot move a directory over an existing object');\n        }\n\n        try {\n          // Create the to directory\n          await this.mkdir({\n            path: to,\n            directory: toDirectory,\n            recursive: false,\n          });\n\n          // Copy the mtime/ctime of a renamed directory\n          if (doRename) {\n            await updateTime(to, ctime, fromObj.mtime);\n          }\n        } catch (e) {\n          // ignore\n        }\n\n        // Iterate over the contents of the from location\n        const contents = (\n          await this.readdir({\n            path: from,\n            directory: fromDirectory,\n          })\n        ).files;\n\n        for (const filename of contents) {\n          // Move item from the from directory to the to directory\n          await this._copy(\n            {\n              from: `${from}/${filename.name}`,\n              to: `${to}/${filename.name}`,\n              directory: fromDirectory,\n              toDirectory,\n            },\n            doRename,\n          );\n        }\n\n        // Optionally remove the original from directory\n        if (doRename) {\n          await this.rmdir({\n            path: from,\n            directory: fromDirectory,\n          });\n        }\n      }\n    }\n    return {\n      uri: toPath,\n    };\n  }\n\n  /**\n   * Function that performs a http request to a server and downloads the file to the specified destination\n   *\n   * @deprecated Use the @capacitor/file-transfer plugin instead.\n   * @param options the options for the download operation\n   * @returns a promise that resolves with the download file result\n   */\n  public downloadFile = async (options: DownloadFileOptions): Promise<DownloadFileResult> => {\n    const requestInit = buildRequestInit(options, options.webFetchExtra);\n    const response = await fetch(options.url, requestInit);\n    let blob: Blob;\n\n    if (!options.progress) blob = await response.blob();\n    else if (!response?.body) blob = new Blob();\n    else {\n      const reader = response.body.getReader();\n\n      let bytes = 0;\n      const chunks: (Uint8Array | undefined)[] = [];\n\n      const contentType: string | null = response.headers.get('content-type');\n      const contentLength: number = parseInt(response.headers.get('content-length') || '0', 10);\n\n      while (true) {\n        const { done, value } = await reader.read();\n\n        if (done) break;\n\n        chunks.push(value);\n        bytes += value?.length || 0;\n\n        const status: ProgressStatus = {\n          url: options.url,\n          bytes,\n          contentLength,\n        };\n\n        this.notifyListeners('progress', status);\n      }\n\n      const allChunks = new Uint8Array(bytes);\n      let position = 0;\n      for (const chunk of chunks) {\n        if (typeof chunk === 'undefined') continue;\n\n        allChunks.set(chunk, position);\n        position += chunk.length;\n      }\n\n      blob = new Blob([allChunks.buffer], { type: contentType || undefined });\n    }\n\n    const result = await this.writeFile({\n      path: options.path,\n      directory: options.directory ?? undefined,\n      recursive: options.recursive ?? false,\n      data: blob,\n    });\n\n    return { path: result.uri, blob };\n  };\n\n  private isBase64String(str: string): boolean {\n    try {\n      return btoa(atob(str)) == str;\n    } catch (err) {\n      return false;\n    }\n  }\n}\n\ninterface EntryObj {\n  path: string;\n  folder: string;\n  type: 'directory' | 'file';\n  size: number;\n  ctime: number;\n  mtime: number;\n  uri?: string;\n  content?: string | Blob;\n}\n", "import { WebPlugin } from '@capacitor/core';\n\nimport type { CanShareResult, ShareOptions, SharePlugin, ShareResult } from './definitions';\n\nexport class ShareWeb extends WebPlugin implements SharePlugin {\n  async canShare(): Promise<CanShareResult> {\n    if (typeof navigator === 'undefined' || !navigator.share) {\n      return { value: false };\n    } else {\n      return { value: true };\n    }\n  }\n  async share(options: ShareOptions): Promise<ShareResult> {\n    if (typeof navigator === 'undefined' || !navigator.share) {\n      throw this.unavailable('Share API not available in this browser');\n    }\n\n    await navigator.share({\n      title: options.title,\n      text: options.text,\n      url: options.url,\n    });\n    return {};\n  }\n}\n", "export const abilities=['str','dex','con','int','wis','cha'];\r\nexport const labels={ancestry:'Ancestry / creature type',classLevel:'Class & level',background:'Background',alignment:'Alignment',cr:'Challenge rating',ac:'Armour class',hp:'Current hit points',maxHp:'Maximum hit points',tempHp:'Temporary hit points',speed:'Speed',initiative:'Initiative',proficiency:'Proficiency bonus',str:'Strength',dex:'Dexterity',con:'Constitution',int:'Intelligence',wis:'Wisdom',cha:'Charisma',saves:'Saving throws',skills:'Skills & proficiencies',attacks:'Attacks & actions',spells:'Spellcasting',spellSlots:'Spell slots',equipment:'Equipment & treasure',traits:'Features & traits',notes:'Notes',sourceText:'Extracted source information'};\r\nconst aliases={name:['name','charactername','character','npcname'],ancestry:['ancestry','race','species','creaturetype'],classLevel:['classlevel','classandlevel','class','classes'],background:['background'],alignment:['alignment'],cr:['cr','challengerating'],ac:['ac','armorclass','armourclass'],hp:['hp','currenthp','hpcurrent','currenthitpoints','hitpoints'],maxHp:['maxhp','hpmax','maximumhitpoints','hitpointmaximum','hitpointsmax'],tempHp:['temphp','hptemp','temporaryhitpoints'],speed:['speed','walk','walkspeed'],initiative:['initiative','init'],proficiency:['proficiency','proficiencybonus','profbonus'],str:['str','strength'],dex:['dex','dexterity'],con:['con','constitution'],int:['int','intelligence'],wis:['wis','wisdom'],cha:['cha','charisma'],saves:['saves','savingthrows'],skills:['skills','proficiencies'],attacks:['attacks','actions','weapons'],spells:['spells','spellcasting'],spellSlots:['spellslots'],equipment:['equipment','inventory','treasure'],traits:['traits','features','featuresandtraits'],notes:['notes','backstory','description']};\r\nconst norm=s=>String(s).toLowerCase().replace(/[^a-z0-9]/g,'');\r\nconst clean=s=>String(s??'').replace(/<br\\s*\\/?\\s*>/gi,'\\n').replace(/<\\/p>/gi,'\\n').replace(/<[^>]*>/g,'').replace(/&nbsp;/g,' ').replace(/&amp;/g,'&').trim();\r\nexport function textValue(v){if(v==null)return '';if(typeof v==='object')return JSON.stringify(v,null,2);return clean(v);}\r\nexport function blank(name='',kind='PC'){return {id:globalThis.crypto?.randomUUID?.()||`c-${Date.now()}-${Math.random().toString(36).slice(2)}`,name,kind,fields:Object.fromEntries(Object.keys(labels).map(k=>[k,'']))};}\r\nexport function fromPairs(pairs,c){\r\n for(const [key,value] of pairs){const k=norm(key);const target=Object.keys(aliases).find(a=>aliases[a].includes(k));const v=textValue(value);if(!target||!v)continue;if(target==='name'){if(!c.name)c.name=v;}else if(!c.fields[target])c.fields[target]=v;}\r\n return c;\r\n}\r\nconst abilityNames={str:'Strength',dex:'Dexterity',con:'Constitution',int:'Intelligence',wis:'Wisdom',cha:'Charisma'};\r\nconst creatureLine=/^(Tiny|Small|Medium|Large|Huge|Gargantuan)\\s+(?:humanoid|undead|monstrosity|beast|dragon|fey|fiend|celestial|construct|aberration|elemental|giant|ooze|plant)\\b/i;\r\nfunction chatNoise(line){return /^(?:OP|example\\s+(?:one|two|\\d+)\\s*:|page\\s+\\d+(?:\\s+of\\s+\\d+)?)$/i.test(line)||/^[-\u2014\u2013]\\s*\\d{1,2}\\/\\d{1,2}\\/\\d{2,4}\\b/.test(line)||/^[^:]{1,60}\\s+\\[[^\\]]{1,20}\\],?$/.test(line);}\r\nexport function splitCharacterText(text){\r\n const lines=text.replace(/\\r/g,'').split('\\n');const starts=[0];\r\n for(let i=1;i<lines.length;i++){\r\n  const line=lines[i].trim();\r\n  const named=/^(?:character name|name)\\s*:/i.test(line);\r\n  const example=/^example\\s+(?:one|two|\\d+)\\s*:/i.test(line);\r\n  const next=lines.slice(i+1).map(x=>x.trim()).filter(x=>x&&!chatNoise(x)&&!/^Level\\s+\\d+\\s+/i.test(x)).slice(0,3);\r\n  const statStart=line.length>0&&line.length<100&&!/[:.|]/.test(line)&&creatureLine.test(next[0]||'')&&/^Armou?r Class\\s*:/i.test(next[1]||'');\r\n  if((named||statStart||example)&&lines.slice(starts.at(-1),i).some(x=>/^(?:Name:|Armou?r Class|AC\\s*:)/i.test(x.trim())))starts.push(i);\r\n }\r\n return starts.map((start,i)=>lines.slice(start,starts[i+1]??lines.length).join('\\n')).filter(x=>x.trim());\r\n}\r\nexport function fromText(text,c){\r\n const block=splitCharacterText(text)[0];\r\n const lines=block.replace(/\\*\\*/g,'').replace(/\\r/g,'').split('\\n').map(s=>s.trim()).filter(l=>!chatNoise(l));\r\n const set=(k,v)=>{if(v&&!c.fields[k])c.fields[k]=String(v).trim();};\r\n const sections={};const add=(k,line)=>{if(line)(sections[k]??=[]).push(line);};\r\n let active=null,level='',className='';\r\n const numeric={ac:'(?:armou?r class|AC)',hp:'(?:hit points|HP|current hit points)',maxHp:'(?:maximum hit points|max(?:imum)? HP|HP max)',tempHp:'(?:temporary hit points|temp HP)',proficiency:'proficiency bonus',initiative:'initiative',cr:'(?:challenge(?: rating)?|CR)'};\r\n const inlineLabels='Character Name|Name|Class & Level|Class and Level|Class|Level|Armour Class|Armor Class|AC|Hit Points|HP|Background|Speed|Size|Race|Species|Ancestry|Alignment';\r\n const first=lines.find(l=>l&&!/^[-_]{3,}$/.test(l));if(!c.name&&first&&first.length<=100&&!/[:\\t]|^(armor|armour|hit points|strength|str\\b|name\\b|character sheet)/i.test(first))c.name=first.replace(/^#+\\s*/,'');\r\n for(let i=0;i<lines.length;i++){\r\n  const line=lines[i];if(!line){if(active)add(active,'');continue;}\r\n  if(/^[-_]{3,}$/.test(line)){active=null;continue;}\r\n  const heading=line.replace(/^#+\\s*/,'').replace(/[:.]$/,'').trim();\r\n  const lower=heading.toLowerCase();\r\n  const featureClass=heading.match(/^Class Features\\s*\\(([^)]+)\\)$/i);if(featureClass){className=featureClass[1];active='traits';add(active,line);continue;}\r\n  const species=heading.match(/^(?:Species|Race|Ancestry) Features\\s*\\(([^)]+)\\)$/i);if(species){set('ancestry',species[1]);active='traits';add(active,line);continue;}\r\n  const headingMap={'actions':'attacks','action':'attacks','attacks':'attacks','attacks & spellcasting':'attacks','bonus actions':'attacks','reactions':'attacks','reaction':'attacks','legendary actions':'attacks','lair actions':'attacks','spells':'spells','spellcasting':'spells','innate spellcasting':'spells','equipment':'equipment','equipped gear':'equipment','equipment & treasure':'equipment','inventory':'equipment','features':'traits','traits':'traits','features and traits':'traits','features & traits':'traits','notes':'notes','backstory':'notes','skills':'skills','proficiencies':'skills','saving throws':'saves','tools':'skills','spirit companions':'traits','encounter balance':'notes'};\r\n  if(headingMap[lower]){active=headingMap[lower];add(active,line);continue;}\r\n  if(/^Soul Weaving\\s*:/i.test(line)){active='traits';add(active,line);continue;}\r\n  if(/combination abilities$/i.test(heading)){active='traits';add(active,line);continue;}\r\n  if(/^Spell List\\s*:/i.test(line)){active='spells';add(active,line);continue;}\r\n  const skill=line.match(/^(Acrobatics|Animal Handling|Arcana|Athletics|Deception|History|Insight|Intimidation|Investigation|Medicine|Nature|Perception|Performance|Persuasion|Religion|Sleight of Hand|Stealth|Survival)(?:\\s*\\([^)]*\\))?\\s*[: ]\\s*[+\u2212-]\\d+/i);\r\n  if(skill){active='skills';add(active,line);continue;}\r\n  const save=line.match(/^(Strength|Dexterity|Constitution|Intelligence|Wisdom|Charisma|STR|DEX|CON|INT|WIS|CHA)\\s*:\\s*[+\u2212-]\\d+/i);\r\n  if(save){add('saves',line);continue;}\r\n  const inlineSection=line.match(/^(Saving Throws|Skills|Spellcasting(?: Ability)?|Innate Spellcasting|Equipment|Features and Traits)\\s*[:.]?\\s+(.+)$/i);\r\n  if(inlineSection){const key=inlineSection[1].toLowerCase();const target=key==='saving throws'?'saves':key==='skills'?'skills':key.startsWith('spellcasting')||key==='innate spellcasting'?'spells':key==='equipment'?'equipment':'traits';add(target,inlineSection[2]);active=['spells','equipment','traits'].includes(target)?target:null;continue;}\r\n  if(/^(?:Senses|Languages|Damage (?:Resistances|Immunities|Vulnerabilities)|Condition Immunities)\\b/i.test(line)){add('traits',line);active=null;continue;}\r\n  // Once inside prose, do not read nested creatures or spell text as the parent statistics.\r\n  if(active){add(active,line);if(active==='equipment'&&/(?:[+\u2212-]\\d+\\s+to hit|\\b\\d+d\\d+\\b.*(?:damage|slashing|piercing|bludgeoning))/i.test(line))add('attacks',line);if(active==='spells'){const slots=line.match(/^(\\d+)(?:st|nd|rd|th)\\s+Level\\s+(\\d+)\\s+Slots\\s*:/i);if(slots)add('spellSlots',`Level ${slots[1]}: ${slots[2]}`);}continue;}\r\n  let recognised=false;\r\n  const simple=line.match(/^(Speed|Background|Alignment|Race|Species|Ancestry|Class(?:\\s*(?:&|and)\\s*Level)?|Spell Slots)\\s*:?\\s+(.+)$/i);\r\n  if(simple&&!/\\s+(?:Size|Level|AC|HP|Background)\\s*:/i.test(simple[2])){const key=simple[1].toLowerCase();const target=key==='spell slots'?'spellSlots':key.startsWith('class')?'classLevel':['race','species','ancestry'].includes(key)?'ancestry':key;set(target,simple[2]);recognised=true;}\r\n\r\n  const segments=[...line.matchAll(new RegExp('(?:^|\\\\s+)('+inlineLabels+')\\\\s*:\\\\s*','gi'))];\r\n  for(let j=0;j<segments.length;j++){\r\n   const m=segments[j],key=m[1].toLowerCase(),value=line.slice(m.index+m[0].length,segments[j+1]?.index??line.length).trim();recognised=true;\r\n   if(key==='name'||key==='character name'){if(!c.name)c.name=value;}\r\n   else if(key==='level')level=value.match(/^\\d+/)?.[0]||'';\r\n   else if(['class','class & level','class and level'].includes(key))set('classLevel',value);\r\n   else if(['race','species','ancestry'].includes(key))set('ancestry',value);\r\n   else if(['background','speed','alignment'].includes(key))set(key,value);\r\n   else if(key==='size')add('traits','Size: '+value);\r\n   else if(['hp','hit points'].includes(key)){const hp=value.match(/^(\\d+)(?:\\s*\\/\\s*(\\d+))?/);if(hp){set('hp',hp[1]);set('maxHp',hp[2]);}}\r\n   else if(['ac','armour class','armor class'].includes(key))set('ac',value.match(/^\\d+/)?.[0]);\r\n  }\r\n  for(const [k,label]of Object.entries(numeric)){const m=line.match(new RegExp('^'+label+'\\\\s*:?\\\\s*([+\u2212-]?\\\\d+(?:/\\\\d+)?)','i'));if(m){set(k,k==='hp'?m[1].split('/')[0]:m[1]);if(k==='hp'&&m[1].includes('/'))set('maxHp',m[1].split('/')[1]);recognised=true;}}\r\n  for(const k of abilities){const m=line.match(new RegExp('(?:^|[\\\\s|,;])(?:'+k+'|'+abilityNames[k]+')\\\\s*:?\\\\s*(\\\\d{1,2})(?=\\\\s|[([,;|]|$)','i'));if(m){set(k,m[1]);recognised=true;}}\r\n  if(/^STR\\s+DEX\\s+CON\\s+INT\\s+WIS\\s+CHA$/i.test(line.replace(/\\|/g,' ').replace(/\\s+/g,' '))){const next=lines.slice(i+1,i+7).join(' ');const nums=[...next.matchAll(/(\\d{1,2})\\s*[([][+\\-\u2212]?\\d+[)\\]]/g)].map(m=>m[1]);if(nums.length>=6)abilities.forEach((k,j)=>set(k,nums[j]));else{const raw=lines[i+1]?.split(/\\s+/);if(raw?.length===6&&raw.every(v=>/^\\d{1,2}$/.test(v)))abilities.forEach((k,j)=>set(k,raw[j]));}recognised=true;}\r\n  const title=line.match(/^Level\\s+(\\d+)\\s+([^|]+)(?:\\|.*)?$/i);if(title){set('classLevel',title[2].trim()+' '+title[1]);if(/\\bNPC\\b/i.test(line))c.kind='NPC';recognised=true;}\r\n  if(creatureLine.test(line)){const parts=line.split(',');set('ancestry',parts[0]);set('alignment',parts[1]);c.kind='NPC';recognised=true;}\r\n  if(!recognised&&line!==first&&!/^Stats:?$/i.test(line))add(/^[A-Z][^.]{2,60}\\.\\s+/.test(line)?'traits':'notes',line);\r\n }\r\n if(!c.fields.classLevel&&(className||level))set('classLevel',[className||'Level',level].filter(Boolean).join(' '));\r\n for(const [k,rows]of Object.entries(sections))set(k,rows.join('\\n').trim());\r\n if(c.kind==='NPC'&&c.fields.hp&&!c.fields.maxHp)set('maxHp',c.fields.hp);\r\n c.fields.sourceText=block.slice(0,500000);return c;\r\n}\r\nexport function fromJSON(input,c){\r\n let obj=input;if(Array.isArray(obj)){if(obj.length!==1)throw new Error('This JSON contains multiple records. Import one character at a time.');obj=obj[0];}\r\n if(!obj||typeof obj!=='object')throw new Error('The JSON must contain a character object.');\r\n if(obj.format==='character-ledger')throw new Error('This is a collection backup. Use Restore backup instead.');\r\n if(obj.character&&typeof obj.character==='object')obj=obj.character;\r\n fromPairs(Object.entries(obj),c);\r\n if(obj.fields&&typeof obj.fields==='object')fromPairs(Object.entries(obj.fields),c);\r\n if(obj.kind==='NPC'||obj.type==='npc')c.kind='NPC';\r\n const sys=obj.system;\r\n if(sys){\r\n  const a=sys.attributes||{},d=sys.details||{};\r\n  const set=(k,v)=>{if(v!=null&&v!=='')c.fields[k]=textValue(v);};\r\n  set('ac',a.ac?.value??a.ac?.flat);set('hp',a.hp?.value);set('maxHp',a.hp?.max);set('tempHp',a.hp?.temp);set('speed',a.movement?.walk);set('proficiency',a.prof);set('initiative',a.init?.total);set('cr',d.cr);set('alignment',d.alignment);set('ancestry',typeof d.type==='object'?d.type?.value:d.type);set('background',d.background);set('notes',d.biography?.value);\r\n  for(const k of abilities)set(k,sys.abilities?.[k]?.value);\r\n  if(sys.skills)set('skills',Object.entries(sys.skills).map(([k,v])=>`${k}: ${v.total!=null?(Number(v.total)>=0?'+':'')+v.total:v.value!=null?'proficiency '+v.value:'not specified'}`).join('\\n'));\r\n }\r\n if(obj.abilities)for(const k of abilities){const v=obj.abilities[k];if(v!=null)c.fields[k]=textValue(typeof v==='object'?v.value??v.score:v);}\r\n if(Array.isArray(obj.items)){\r\n  const groups={attacks:[],spells:[],equipment:[],traits:[],classLevel:[]};\r\n  for(const item of obj.items){const group=item.type==='spell'?'spells':item.type==='weapon'?'attacks':item.type==='feat'?'traits':item.type==='class'?'classLevel':'equipment';groups[group].push([item.name,item.system?.levels,item.system?.description?.value].filter(v=>v!=null&&v!=='').map(clean).join('\\n'));}\r\n  for(const [k,arr]of Object.entries(groups))if(arr.length)c.fields[k]=arr.join('\\n\\n').slice(0,500000);\r\n }\r\n c.fields.sourceText=JSON.stringify(input,null,2).slice(0,500000);return c;\r\n}\r\nexport function fromRows(sheets,c){\r\n const pairs=[],text=[];\r\n for(const {name,rows}of sheets){text.push(`[${name}]`);for(let i=0;i<rows.length;i++){const row=rows[i];text.push(row.map(textValue).join('\\t'));for(let j=0;j<row.length-1;j++)if(row[j]!==''&&row[j+1]!=='')pairs.push([row[j],row[j+1]]);}\r\n  if(rows.length>=2)for(let j=0;j<rows[0].length;j++)pairs.push([rows[0][j],rows[1][j]]);\r\n }\r\n // Header tables take precedence over adjacent cells that are themselves labels.\r\n const filtered=pairs.filter(([,v])=>!Object.values(aliases).flat().includes(norm(v)));\r\n fromPairs(filtered,c);c.fields.sourceText=text.join('\\n').slice(0,500000);return c;\r\n}\r\nexport function modifier(value){if(value===''||!Number.isFinite(Number(value)))return '';const n=Math.floor((Number(value)-10)/2);return (n>=0?'+':'')+n;}\r\n", "import {blank,fromJSON,fromRows,fromPairs,fromText} from './model.mjs';\nexport async function importFile(file,kind){\n if(file.size>30*1024*1024)throw new Error('Please use a file smaller than 30 MB.');\n const ext=file.name.split('.').pop().toLowerCase();const bytes=new Uint8Array(await file.arrayBuffer());let c=blank('',kind),notice='Review the imported details. Missing values are left blank; check the original for anything not recognised.';\n if(ext==='json')c=fromJSON(JSON.parse(new TextDecoder().decode(bytes)),c);\n else if(['xlsx','xls','csv','ods','tsv'].includes(ext)){\n  const wb=globalThis.XLSX.read(bytes,{type:'array'});\n  c=fromRows(wb.SheetNames.map(name=>({name,rows:globalThis.XLSX.utils.sheet_to_json(wb.Sheets[name],{header:1,defval:'',raw:false})})),c);\n }else if(ext==='pdf'){\n  if(!Promise.withResolvers)Promise.withResolvers=function(){let resolve,reject;const promise=new Promise((a,b)=>{resolve=a;reject=b;});return {promise,resolve,reject};};\n  const pdfjs=await import('./vendor/pdf.min.mjs');pdfjs.GlobalWorkerOptions.workerSrc='./vendor/pdf-worker-wrapper.mjs';\n  const doc=await pdfjs.getDocument({data:bytes.slice(),isEvalSupported:false,useSystemFonts:true}).promise;\n  try{\n   if(doc.numPages>100)throw new Error('Please use a character sheet of 100 pages or fewer.');\n   const text=[],pairs=[];\n   for(let n=1;n<=doc.numPages;n++){const page=await doc.getPage(n);const content=await page.getTextContent();let lastY=null,line='';text.push(`Page ${n}`);for(const t of content.items){if(!('str'in t))continue;const y=t.transform?.[5];if(lastY!==null&&Math.abs(y-lastY)>3){text.push(line);line='';}line+=(line?' ':'')+t.str;lastY=y;if(t.hasEOL){text.push(line);line='';lastY=null;}}if(line)text.push(line);for(const a of await page.getAnnotations())if(a.fieldName&&a.fieldValue!=null)pairs.push([a.fieldName,a.fieldValue]);}\n   fromPairs(pairs,c);fromText(text.join('\\n'),c);\n   if(text.join('').replace(/Page \\d+/g,'').trim().length<20)notice='This PDF appears to be scanned or image-only. The original is attached, but automatic text recognition is not included. Enter the character details below.';\n  }finally{await doc.destroy();}\n }else throw new Error('Supported files: PDF, XLSX, XLS, CSV, TSV, ODS and JSON.');\n if(!c.name)c.name=file.name.replace(/\\.[^.]+$/,'');\n let binary='';for(let i=0;i<bytes.length;i+=32768)binary+=String.fromCharCode(...bytes.subarray(i,i+32768));\n c.source={name:file.name,type:file.type||'application/octet-stream',data:btoa(binary)};return {character:c,notice};\n}\n", "import type { TraceContextExtractor } from '@supabase/tracing'\n\nexport type { TraceContextExtractor }\n\n// The extractor lives in a `Symbol.for()`-keyed slot on `globalThis` rather\n// than a module-level variable. Bundlers and the ESM/CJS dual build can load\n// this module more than once in a single application (e.g. the tracing\n// subpath resolved to `dist/tracing.mjs` while the main entry resolves to\n// `dist/index.cjs`) — separate module instances would each get their own\n// variable, but they all share the global symbol registry.\n//\n// The symbol string is a de-facto stable contract: module-resolution tests\n// read the slot directly, and changing it orphans registrations from other\n// copies of this package in the same process.\nconst EXTRACTOR_KEY = Symbol.for('@supabase/supabase-js.traceContextExtractor')\n\ntype ExtractorSlot = { [EXTRACTOR_KEY]?: TraceContextExtractor }\n\n/**\n * Register the trace context extractor used by all Supabase clients in this\n * process. Called by the `@supabase/supabase-js/tracing` subpath as an import\n * side effect; the last registration wins.\n */\nexport function registerTraceContextExtractor(extractor: TraceContextExtractor): void {\n  ;(globalThis as ExtractorSlot)[EXTRACTOR_KEY] = extractor\n}\n\n/**\n * The currently registered trace context extractor, if any.\n */\nexport function getTraceContextExtractor(): TraceContextExtractor | undefined {\n  return (globalThis as ExtractorSlot)[EXTRACTOR_KEY]\n}\n\n/**\n * For tests only. Removes the registered extractor.\n *\n * @internal\n */\nexport function _unregisterTraceContextExtractor(): void {\n  delete (globalThis as ExtractorSlot)[EXTRACTOR_KEY]\n}\n", "/******************************************************************************\nCopyright (c) Microsoft Corporation.\n\nPermission to use, copy, modify, and/or distribute this software for any\npurpose with or without fee is hereby granted.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH\nREGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY\nAND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,\nINDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM\nLOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR\nOTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR\nPERFORMANCE OF THIS SOFTWARE.\n***************************************************************************** */\n/* global Reflect, Promise, SuppressedError, Symbol, Iterator */\n\nvar extendStatics = function(d, b) {\n  extendStatics = Object.setPrototypeOf ||\n      ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n      function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };\n  return extendStatics(d, b);\n};\n\nexport function __extends(d, b) {\n  if (typeof b !== \"function\" && b !== null)\n      throw new TypeError(\"Class extends value \" + String(b) + \" is not a constructor or null\");\n  extendStatics(d, b);\n  function __() { this.constructor = d; }\n  d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n}\n\nexport var __assign = function() {\n  __assign = Object.assign || function __assign(t) {\n      for (var s, i = 1, n = arguments.length; i < n; i++) {\n          s = arguments[i];\n          for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];\n      }\n      return t;\n  }\n  return __assign.apply(this, arguments);\n}\n\nexport function __rest(s, e) {\n  var t = {};\n  for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)\n      t[p] = s[p];\n  if (s != null && typeof Object.getOwnPropertySymbols === \"function\")\n      for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {\n          if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))\n              t[p[i]] = s[p[i]];\n      }\n  return t;\n}\n\nexport function __decorate(decorators, target, key, desc) {\n  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;\n  if (typeof Reflect === \"object\" && typeof Reflect.decorate === \"function\") r = Reflect.decorate(decorators, target, key, desc);\n  else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;\n  return c > 3 && r && Object.defineProperty(target, key, r), r;\n}\n\nexport function __param(paramIndex, decorator) {\n  return function (target, key) { decorator(target, key, paramIndex); }\n}\n\nexport function __esDecorate(ctor, descriptorIn, decorators, contextIn, initializers, extraInitializers) {\n  function accept(f) { if (f !== void 0 && typeof f !== \"function\") throw new TypeError(\"Function expected\"); return f; }\n  var kind = contextIn.kind, key = kind === \"getter\" ? \"get\" : kind === \"setter\" ? \"set\" : \"value\";\n  var target = !descriptorIn && ctor ? contextIn[\"static\"] ? ctor : ctor.prototype : null;\n  var descriptor = descriptorIn || (target ? Object.getOwnPropertyDescriptor(target, contextIn.name) : {});\n  var _, done = false;\n  for (var i = decorators.length - 1; i >= 0; i--) {\n      var context = {};\n      for (var p in contextIn) context[p] = p === \"access\" ? {} : contextIn[p];\n      for (var p in contextIn.access) context.access[p] = contextIn.access[p];\n      context.addInitializer = function (f) { if (done) throw new TypeError(\"Cannot add initializers after decoration has completed\"); extraInitializers.push(accept(f || null)); };\n      var result = (0, decorators[i])(kind === \"accessor\" ? { get: descriptor.get, set: descriptor.set } : descriptor[key], context);\n      if (kind === \"accessor\") {\n          if (result === void 0) continue;\n          if (result === null || typeof result !== \"object\") throw new TypeError(\"Object expected\");\n          if (_ = accept(result.get)) descriptor.get = _;\n          if (_ = accept(result.set)) descriptor.set = _;\n          if (_ = accept(result.init)) initializers.unshift(_);\n      }\n      else if (_ = accept(result)) {\n          if (kind === \"field\") initializers.unshift(_);\n          else descriptor[key] = _;\n      }\n  }\n  if (target) Object.defineProperty(target, contextIn.name, descriptor);\n  done = true;\n};\n\nexport function __runInitializers(thisArg, initializers, value) {\n  var useValue = arguments.length > 2;\n  for (var i = 0; i < initializers.length; i++) {\n      value = useValue ? initializers[i].call(thisArg, value) : initializers[i].call(thisArg);\n  }\n  return useValue ? value : void 0;\n};\n\nexport function __propKey(x) {\n  return typeof x === \"symbol\" ? x : \"\".concat(x);\n};\n\nexport function __setFunctionName(f, name, prefix) {\n  if (typeof name === \"symbol\") name = name.description ? \"[\".concat(name.description, \"]\") : \"\";\n  return Object.defineProperty(f, \"name\", { configurable: true, value: prefix ? \"\".concat(prefix, \" \", name) : name });\n};\n\nexport function __metadata(metadataKey, metadataValue) {\n  if (typeof Reflect === \"object\" && typeof Reflect.metadata === \"function\") return Reflect.metadata(metadataKey, metadataValue);\n}\n\nexport function __awaiter(thisArg, _arguments, P, generator) {\n  function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\n  return new (P || (P = Promise))(function (resolve, reject) {\n      function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\n      function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\n      function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\n      step((generator = generator.apply(thisArg, _arguments || [])).next());\n  });\n}\n\nexport function __generator(thisArg, body) {\n  var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g = Object.create((typeof Iterator === \"function\" ? Iterator : Object).prototype);\n  return g.next = verb(0), g[\"throw\"] = verb(1), g[\"return\"] = verb(2), typeof Symbol === \"function\" && (g[Symbol.iterator] = function() { return this; }), g;\n  function verb(n) { return function (v) { return step([n, v]); }; }\n  function step(op) {\n      if (f) throw new TypeError(\"Generator is already executing.\");\n      while (g && (g = 0, op[0] && (_ = 0)), _) try {\n          if (f = 1, y && (t = op[0] & 2 ? y[\"return\"] : op[0] ? y[\"throw\"] || ((t = y[\"return\"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;\n          if (y = 0, t) op = [op[0] & 2, t.value];\n          switch (op[0]) {\n              case 0: case 1: t = op; break;\n              case 4: _.label++; return { value: op[1], done: false };\n              case 5: _.label++; y = op[1]; op = [0]; continue;\n              case 7: op = _.ops.pop(); _.trys.pop(); continue;\n              default:\n                  if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }\n                  if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }\n                  if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }\n                  if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }\n                  if (t[2]) _.ops.pop();\n                  _.trys.pop(); continue;\n          }\n          op = body.call(thisArg, _);\n      } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }\n      if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };\n  }\n}\n\nexport var __createBinding = Object.create ? (function(o, m, k, k2) {\n  if (k2 === undefined) k2 = k;\n  var desc = Object.getOwnPropertyDescriptor(m, k);\n  if (!desc || (\"get\" in desc ? !m.__esModule : desc.writable || desc.configurable)) {\n      desc = { enumerable: true, get: function() { return m[k]; } };\n  }\n  Object.defineProperty(o, k2, desc);\n}) : (function(o, m, k, k2) {\n  if (k2 === undefined) k2 = k;\n  o[k2] = m[k];\n});\n\nexport function __exportStar(m, o) {\n  for (var p in m) if (p !== \"default\" && !Object.prototype.hasOwnProperty.call(o, p)) __createBinding(o, m, p);\n}\n\nexport function __values(o) {\n  var s = typeof Symbol === \"function\" && Symbol.iterator, m = s && o[s], i = 0;\n  if (m) return m.call(o);\n  if (o && typeof o.length === \"number\") return {\n      next: function () {\n          if (o && i >= o.length) o = void 0;\n          return { value: o && o[i++], done: !o };\n      }\n  };\n  throw new TypeError(s ? \"Object is not iterable.\" : \"Symbol.iterator is not defined.\");\n}\n\nexport function __read(o, n) {\n  var m = typeof Symbol === \"function\" && o[Symbol.iterator];\n  if (!m) return o;\n  var i = m.call(o), r, ar = [], e;\n  try {\n      while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);\n  }\n  catch (error) { e = { error: error }; }\n  finally {\n      try {\n          if (r && !r.done && (m = i[\"return\"])) m.call(i);\n      }\n      finally { if (e) throw e.error; }\n  }\n  return ar;\n}\n\n/** @deprecated */\nexport function __spread() {\n  for (var ar = [], i = 0; i < arguments.length; i++)\n      ar = ar.concat(__read(arguments[i]));\n  return ar;\n}\n\n/** @deprecated */\nexport function __spreadArrays() {\n  for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length;\n  for (var r = Array(s), k = 0, i = 0; i < il; i++)\n      for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)\n          r[k] = a[j];\n  return r;\n}\n\nexport function __spreadArray(to, from, pack) {\n  if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {\n      if (ar || !(i in from)) {\n          if (!ar) ar = Array.prototype.slice.call(from, 0, i);\n          ar[i] = from[i];\n      }\n  }\n  return to.concat(ar || Array.prototype.slice.call(from));\n}\n\nexport function __await(v) {\n  return this instanceof __await ? (this.v = v, this) : new __await(v);\n}\n\nexport function __asyncGenerator(thisArg, _arguments, generator) {\n  if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\n  var g = generator.apply(thisArg, _arguments || []), i, q = [];\n  return i = Object.create((typeof AsyncIterator === \"function\" ? AsyncIterator : Object).prototype), verb(\"next\"), verb(\"throw\"), verb(\"return\", awaitReturn), i[Symbol.asyncIterator] = function () { return this; }, i;\n  function awaitReturn(f) { return function (v) { return Promise.resolve(v).then(f, reject); }; }\n  function verb(n, f) { if (g[n]) { i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; if (f) i[n] = f(i[n]); } }\n  function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }\n  function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }\n  function fulfill(value) { resume(\"next\", value); }\n  function reject(value) { resume(\"throw\", value); }\n  function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }\n}\n\nexport function __asyncDelegator(o) {\n  var i, p;\n  return i = {}, verb(\"next\"), verb(\"throw\", function (e) { throw e; }), verb(\"return\"), i[Symbol.iterator] = function () { return this; }, i;\n  function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: false } : f ? f(v) : v; } : f; }\n}\n\nexport function __asyncValues(o) {\n  if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\n  var m = o[Symbol.asyncIterator], i;\n  return m ? m.call(o) : (o = typeof __values === \"function\" ? __values(o) : o[Symbol.iterator](), i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i);\n  function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }\n  function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }\n}\n\nexport function __makeTemplateObject(cooked, raw) {\n  if (Object.defineProperty) { Object.defineProperty(cooked, \"raw\", { value: raw }); } else { cooked.raw = raw; }\n  return cooked;\n};\n\nvar __setModuleDefault = Object.create ? (function(o, v) {\n  Object.defineProperty(o, \"default\", { enumerable: true, value: v });\n}) : function(o, v) {\n  o[\"default\"] = v;\n};\n\nvar ownKeys = function(o) {\n  ownKeys = Object.getOwnPropertyNames || function (o) {\n    var ar = [];\n    for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;\n    return ar;\n  };\n  return ownKeys(o);\n};\n\nexport function __importStar(mod) {\n  if (mod && mod.__esModule) return mod;\n  var result = {};\n  if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== \"default\") __createBinding(result, mod, k[i]);\n  __setModuleDefault(result, mod);\n  return result;\n}\n\nexport function __importDefault(mod) {\n  return (mod && mod.__esModule) ? mod : { default: mod };\n}\n\nexport function __classPrivateFieldGet(receiver, state, kind, f) {\n  if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a getter\");\n  if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot read private member from an object whose class did not declare it\");\n  return kind === \"m\" ? f : kind === \"a\" ? f.call(receiver) : f ? f.value : state.get(receiver);\n}\n\nexport function __classPrivateFieldSet(receiver, state, value, kind, f) {\n  if (kind === \"m\") throw new TypeError(\"Private method is not writable\");\n  if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a setter\");\n  if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot write private member to an object whose class did not declare it\");\n  return (kind === \"a\" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;\n}\n\nexport function __classPrivateFieldIn(state, receiver) {\n  if (receiver === null || (typeof receiver !== \"object\" && typeof receiver !== \"function\")) throw new TypeError(\"Cannot use 'in' operator on non-object\");\n  return typeof state === \"function\" ? receiver === state : state.has(receiver);\n}\n\nexport function __addDisposableResource(env, value, async) {\n  if (value !== null && value !== void 0) {\n    if (typeof value !== \"object\" && typeof value !== \"function\") throw new TypeError(\"Object expected.\");\n    var dispose, inner;\n    if (async) {\n      if (!Symbol.asyncDispose) throw new TypeError(\"Symbol.asyncDispose is not defined.\");\n      dispose = value[Symbol.asyncDispose];\n    }\n    if (dispose === void 0) {\n      if (!Symbol.dispose) throw new TypeError(\"Symbol.dispose is not defined.\");\n      dispose = value[Symbol.dispose];\n      if (async) inner = dispose;\n    }\n    if (typeof dispose !== \"function\") throw new TypeError(\"Object not disposable.\");\n    if (inner) dispose = function() { try { inner.call(this); } catch (e) { return Promise.reject(e); } };\n    env.stack.push({ value: value, dispose: dispose, async: async });\n  }\n  else if (async) {\n    env.stack.push({ async: true });\n  }\n  return value;\n}\n\nvar _SuppressedError = typeof SuppressedError === \"function\" ? SuppressedError : function (error, suppressed, message) {\n  var e = new Error(message);\n  return e.name = \"SuppressedError\", e.error = error, e.suppressed = suppressed, e;\n};\n\nexport function __disposeResources(env) {\n  function fail(e) {\n    env.error = env.hasError ? new _SuppressedError(e, env.error, \"An error was suppressed during disposal.\") : e;\n    env.hasError = true;\n  }\n  var r, s = 0;\n  function next() {\n    while (r = env.stack.pop()) {\n      try {\n        if (!r.async && s === 1) return s = 0, env.stack.push(r), Promise.resolve().then(next);\n        if (r.dispose) {\n          var result = r.dispose.call(r.value);\n          if (r.async) return s |= 2, Promise.resolve(result).then(next, function(e) { fail(e); return next(); });\n        }\n        else s |= 1;\n      }\n      catch (e) {\n        fail(e);\n      }\n    }\n    if (s === 1) return env.hasError ? Promise.reject(env.error) : Promise.resolve();\n    if (env.hasError) throw env.error;\n  }\n  return next();\n}\n\nexport function __rewriteRelativeImportExtension(path, preserveJsx) {\n  if (typeof path === \"string\" && /^\\.\\.?\\//.test(path)) {\n      return path.replace(/\\.(tsx)$|((?:\\.d)?)((?:\\.[^./]+?)?)\\.([cm]?)ts$/i, function (m, tsx, d, ext, cm) {\n          return tsx ? preserveJsx ? \".jsx\" : \".js\" : d && (!ext || !cm) ? m : (d + ext + \".\" + cm.toLowerCase() + \"js\");\n      });\n  }\n  return path;\n}\n\nexport default {\n  __extends,\n  __assign,\n  __rest,\n  __decorate,\n  __param,\n  __esDecorate,\n  __runInitializers,\n  __propKey,\n  __setFunctionName,\n  __metadata,\n  __awaiter,\n  __generator,\n  __createBinding,\n  __exportStar,\n  __values,\n  __read,\n  __spread,\n  __spreadArrays,\n  __spreadArray,\n  __await,\n  __asyncGenerator,\n  __asyncDelegator,\n  __asyncValues,\n  __makeTemplateObject,\n  __importStar,\n  __importDefault,\n  __classPrivateFieldGet,\n  __classPrivateFieldSet,\n  __classPrivateFieldIn,\n  __addDisposableResource,\n  __disposeResources,\n  __rewriteRelativeImportExtension,\n};\n", "import { Fetch } from './types'\n\nexport const resolveFetch = (customFetch?: Fetch): Fetch => {\n  if (customFetch) {\n    return (...args) => customFetch(...args)\n  }\n  return (...args) => fetch(...args)\n}\n", "export type Fetch = typeof fetch\n\n/**\n * Response format\n */\nexport interface FunctionsResponseSuccess<T> {\n  data: T\n  error: null\n  response?: Response\n}\nexport interface FunctionsResponseFailure {\n  data: null\n  error: any\n  response?: Response\n}\nexport type FunctionsResponse<T> = FunctionsResponseSuccess<T> | FunctionsResponseFailure\n\n/**\n * Base error for Supabase Edge Function invocations.\n *\n * @example\n * ```ts\n * import { FunctionsError } from '@supabase/functions-js'\n *\n * throw new FunctionsError('Unexpected error invoking function', 'FunctionsError', {\n *   requestId: 'abc123',\n * })\n * ```\n */\nexport class FunctionsError extends Error {\n  context: any\n  constructor(message: string, name = 'FunctionsError', context?: any) {\n    super(message)\n    this.name = name\n    this.context = context\n  }\n\n  toJSON(): { name: string; message: string; context: any } {\n    return {\n      name: this.name,\n      message: this.message,\n      context: this.context,\n    }\n  }\n}\n\n/**\n * Error thrown when the network request to an Edge Function fails.\n *\n * @example\n * ```ts\n * import { FunctionsFetchError } from '@supabase/functions-js'\n *\n * throw new FunctionsFetchError({ requestId: 'abc123' })\n * ```\n */\nexport class FunctionsFetchError extends FunctionsError {\n  constructor(context: any) {\n    super('Failed to send a request to the Edge Function', 'FunctionsFetchError', context)\n  }\n}\n\n/**\n * Error thrown when the Supabase relay cannot reach the Edge Function.\n *\n * @example\n * ```ts\n * import { FunctionsRelayError } from '@supabase/functions-js'\n *\n * throw new FunctionsRelayError({ region: 'us-east-1' })\n * ```\n */\nexport class FunctionsRelayError extends FunctionsError {\n  constructor(context: any) {\n    super('Relay Error invoking the Edge Function', 'FunctionsRelayError', context)\n  }\n}\n\n/**\n * Error thrown when the Edge Function returns a non-2xx status code.\n *\n * @example\n * ```ts\n * import { FunctionsHttpError } from '@supabase/functions-js'\n *\n * throw new FunctionsHttpError({ status: 500 })\n * ```\n */\nexport class FunctionsHttpError extends FunctionsError {\n  constructor(context: any) {\n    super('Edge Function returned a non-2xx status code', 'FunctionsHttpError', context)\n  }\n}\n// Define the enum for the 'region' property\nexport enum FunctionRegion {\n  Any = 'any',\n  ApNortheast1 = 'ap-northeast-1',\n  ApNortheast2 = 'ap-northeast-2',\n  ApSouth1 = 'ap-south-1',\n  ApSoutheast1 = 'ap-southeast-1',\n  ApSoutheast2 = 'ap-southeast-2',\n  CaCentral1 = 'ca-central-1',\n  EuCentral1 = 'eu-central-1',\n  EuWest1 = 'eu-west-1',\n  EuWest2 = 'eu-west-2',\n  EuWest3 = 'eu-west-3',\n  SaEast1 = 'sa-east-1',\n  UsEast1 = 'us-east-1',\n  UsWest1 = 'us-west-1',\n  UsWest2 = 'us-west-2',\n}\n\nexport type FunctionInvokeOptions = {\n  /**\n   * Object representing the headers to send with the request.\n   */\n  headers?: { [key: string]: string }\n  /**\n   * The HTTP verb of the request\n   */\n  method?: 'POST' | 'GET' | 'PUT' | 'PATCH' | 'DELETE'\n  /**\n   * The Region to invoke the function in.\n   */\n  region?: FunctionRegion\n  /**\n   * The body of the request.\n   */\n  body?:\n    | File\n    | Blob\n    | ArrayBuffer\n    | FormData\n    | ReadableStream<Uint8Array>\n    | Record<string, any>\n    | string\n  /**\n   * The AbortSignal to use for the request.\n   * */\n  signal?: AbortSignal\n  /**\n   * The timeout for the request in milliseconds.\n   * If the function takes longer than this, the request will be aborted.\n   * */\n  timeout?: number\n}\n", "import { resolveFetch } from './helper'\nimport {\n  Fetch,\n  FunctionInvokeOptions,\n  FunctionRegion,\n  FunctionsFetchError,\n  FunctionsHttpError,\n  FunctionsRelayError,\n  FunctionsResponse,\n} from './types'\n\n/**\n * Client for invoking Supabase Edge Functions.\n */\nexport class FunctionsClient {\n  protected url: string\n  protected headers: Record<string, string>\n  protected region: FunctionRegion\n  protected fetch: Fetch\n\n  /**\n   * Creates a new Functions client bound to an Edge Functions URL.\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.functions.invoke('hello-world')\n   * ```\n   *\n   * @category Edge Functions\n   *\n   * @example Standalone import for bundle-sensitive environments\n   * ```ts\n   * import { FunctionsClient, FunctionRegion } from '@supabase/functions-js'\n   *\n   * const functions = new FunctionsClient('https://xyzcompany.supabase.co/functions/v1', {\n   *   headers: { apikey: 'your-publishable-key' },\n   *   region: FunctionRegion.UsEast1,\n   * })\n   * ```\n   */\n  constructor(\n    url: string,\n    {\n      headers = {},\n      customFetch,\n      region = FunctionRegion.Any,\n    }: {\n      headers?: Record<string, string>\n      customFetch?: Fetch\n      region?: FunctionRegion\n    } = {}\n  ) {\n    this.url = url\n    this.headers = headers\n    this.region = region\n    this.fetch = resolveFetch(customFetch)\n  }\n\n  /**\n   * Updates the authorization header\n   * @param token - the new jwt token sent in the authorisation header\n   *\n   * @category Edge Functions\n   *\n   * @example Setting the authorization header\n   * ```ts\n   * functions.setAuth(session.access_token)\n   * ```\n   */\n  setAuth(token: string) {\n    this.headers.Authorization = `Bearer ${token}`\n  }\n\n  /**\n   * Invokes a function\n   * @param functionName - The name of the Function to invoke.\n   * @param options - Options for invoking the Function.\n   * @example\n   * ```ts\n   * const { data, error } = await functions.invoke('hello-world', {\n   *   body: { name: 'Ada' },\n   * })\n   * ```\n   *\n   * @category Edge Functions\n   *\n   * @remarks\n   * - The API key is sent in the `apikey` header. The `Authorization` header is reserved\n   *   for the signed-in user's JWT (or a custom auth token) \u2014 when there is no session, a\n   *   new-format API key (`sb_publishable_\u2026` / `sb_secret_\u2026`) is not sent as a Bearer token.\n   * - Invoke params generally match the [Fetch API](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API) spec.\n   * - When you pass in a body to your function, we automatically attach the Content-Type header for `Blob`, `ArrayBuffer`, `File`, `FormData` and `String`. If it doesn't match any of these types we assume the payload is `json`, serialize it and attach the `Content-Type` header as `application/json`. You can override this behavior by passing in a `Content-Type` header of your own.\n   * - Responses are automatically parsed as `json`, `blob` and `form-data` depending on the `Content-Type` header sent by your function. Responses are parsed as `text` by default.\n   *\n   * @example Basic invocation\n   * ```js\n   * const { data, error } = await supabase.functions.invoke('hello', {\n   *   body: { foo: 'bar' }\n   * })\n   * ```\n   *\n   * @exampleDescription Error handling\n   * A `FunctionsHttpError` error is returned if your function throws an error, `FunctionsRelayError` if the Supabase Relay has an error processing your function and `FunctionsFetchError` if there is a network error in calling your function. Log the full error object so fields like `name`, `context`, and any structured body aren't hidden.\n   *\n   * @example Error handling\n   * ```js\n   * import { FunctionsHttpError, FunctionsRelayError, FunctionsFetchError } from \"@supabase/supabase-js\";\n   *\n   * const { data, error } = await supabase.functions.invoke('hello', {\n   *   headers: {\n   *     \"my-custom-header\": 'my-custom-header-value'\n   *   },\n   *   body: { foo: 'bar' }\n   * })\n   *\n   * if (error instanceof FunctionsHttpError) {\n   *   const errorMessage = await error.context.json()\n   *   console.error('Function returned an error', errorMessage)\n   * } else if (error instanceof FunctionsRelayError) {\n   *   console.error('Relay error:', error)\n   * } else if (error instanceof FunctionsFetchError) {\n   *   console.error('Fetch error:', error)\n   * }\n   * ```\n   *\n   * @exampleDescription Passing custom headers\n   * You can pass custom headers to your function. Note: supabase-js automatically passes the `Authorization` header with the signed in user's JWT.\n   *\n   * @example Passing custom headers\n   * ```js\n   * const { data, error } = await supabase.functions.invoke('hello', {\n   *   headers: {\n   *     \"my-custom-header\": 'my-custom-header-value'\n   *   },\n   *   body: { foo: 'bar' }\n   * })\n   * ```\n   *\n   * @exampleDescription Calling with DELETE HTTP verb\n   * You can also set the HTTP verb to `DELETE` when calling your Edge Function.\n   *\n   * @example Calling with DELETE HTTP verb\n   * ```js\n   * const { data, error } = await supabase.functions.invoke('hello', {\n   *   headers: {\n   *     \"my-custom-header\": 'my-custom-header-value'\n   *   },\n   *   body: { foo: 'bar' },\n   *   method: 'DELETE'\n   * })\n   * ```\n   *\n   * @exampleDescription Invoking a Function in the UsEast1 region\n   * Here are the available regions:\n   * - `FunctionRegion.Any`\n   * - `FunctionRegion.ApNortheast1`\n   * - `FunctionRegion.ApNortheast2`\n   * - `FunctionRegion.ApSouth1`\n   * - `FunctionRegion.ApSoutheast1`\n   * - `FunctionRegion.ApSoutheast2`\n   * - `FunctionRegion.CaCentral1`\n   * - `FunctionRegion.EuCentral1`\n   * - `FunctionRegion.EuWest1`\n   * - `FunctionRegion.EuWest2`\n   * - `FunctionRegion.EuWest3`\n   * - `FunctionRegion.SaEast1`\n   * - `FunctionRegion.UsEast1`\n   * - `FunctionRegion.UsWest1`\n   * - `FunctionRegion.UsWest2`\n   *\n   * @example Invoking a Function in the UsEast1 region\n   * ```js\n   * import { createClient, FunctionRegion } from '@supabase/supabase-js'\n   *\n   * const { data, error } = await supabase.functions.invoke('hello', {\n   *   body: { foo: 'bar' },\n   *   region: FunctionRegion.UsEast1\n   * })\n   * ```\n   *\n   * @exampleDescription Calling with GET HTTP verb\n   * You can also set the HTTP verb to `GET` when calling your Edge Function.\n   *\n   * @example Calling with GET HTTP verb\n   * ```js\n   * const { data, error } = await supabase.functions.invoke('hello', {\n   *   headers: {\n   *     \"my-custom-header\": 'my-custom-header-value'\n   *   },\n   *   method: 'GET'\n   * })\n   * ```\n   *\n   * @example Standalone client invoke\n   * ```ts\n   * const { data, error } = await functions.invoke('hello-world', {\n   *   body: { name: 'Ada' },\n   * })\n   * ```\n   */\n  async invoke<T = any>(\n    functionName: string,\n    options: FunctionInvokeOptions = {}\n  ): Promise<FunctionsResponse<T>> {\n    let timeoutId: ReturnType<typeof setTimeout> | undefined\n    let timeoutController: AbortController | undefined\n    let onAbort: (() => void) | undefined\n\n    try {\n      const { headers, method, body: functionArgs, signal, timeout } = options\n      let _headers: Record<string, string> = {}\n      let { region } = options\n      if (!region) {\n        region = this.region\n      }\n      // Add region as query parameter using URL API\n      const url = new URL(`${this.url}/${functionName}`)\n      if (region && region !== 'any') {\n        _headers['x-region'] = region\n        url.searchParams.set('forceFunctionRegion', region)\n      }\n      let body: any\n      // HTTP header names are case-insensitive, so detect a caller-supplied Content-Type\n      // regardless of casing \u2014 otherwise the SDK injects a second, conflicting Content-Type.\n      const hasContentTypeHeader =\n        !!headers && Object.keys(headers).some((key) => key.toLowerCase() === 'content-type')\n      if (functionArgs && !hasContentTypeHeader) {\n        if (\n          (typeof Blob !== 'undefined' && functionArgs instanceof Blob) ||\n          functionArgs instanceof ArrayBuffer\n        ) {\n          // will work for File as File inherits Blob\n          // also works for ArrayBuffer as it is the same underlying structure as a Blob\n          _headers['Content-Type'] = (functionArgs as Blob).type || 'application/octet-stream'\n          body = functionArgs\n        } else if (typeof functionArgs === 'string') {\n          // plain string\n          _headers['Content-Type'] = 'text/plain'\n          body = functionArgs\n        } else if (typeof FormData !== 'undefined' && functionArgs instanceof FormData) {\n          // don't set content-type headers\n          // Request will automatically add the right boundary value\n          body = functionArgs\n        } else {\n          // default, assume this is JSON\n          _headers['Content-Type'] = 'application/json'\n          body = JSON.stringify(functionArgs)\n        }\n      } else {\n        if (\n          functionArgs &&\n          typeof functionArgs !== 'string' &&\n          !(typeof Blob !== 'undefined' && functionArgs instanceof Blob) &&\n          !(functionArgs instanceof ArrayBuffer) &&\n          !(typeof FormData !== 'undefined' && functionArgs instanceof FormData)\n        ) {\n          body = JSON.stringify(functionArgs)\n        } else {\n          body = functionArgs\n        }\n      }\n\n      // Handle timeout by creating an AbortController\n      let effectiveSignal = signal\n      if (timeout) {\n        timeoutController = new AbortController()\n        timeoutId = setTimeout(() => timeoutController!.abort(), timeout)\n\n        // If user provided their own signal, we need to respect both\n        if (signal) {\n          effectiveSignal = timeoutController.signal\n          // If the user's signal is aborted, abort our timeout controller too.\n          // Store the listener so we can clean it up in finally.\n          onAbort = () => timeoutController!.abort()\n          signal.addEventListener('abort', onAbort)\n        } else {\n          effectiveSignal = timeoutController.signal\n        }\n      }\n\n      const response = await this.fetch(url.toString(), {\n        method: method || 'POST',\n        // headers priority is (high to low):\n        // 1. invoke-level headers\n        // 2. client-level headers\n        // 3. default Content-Type header\n        headers: { ..._headers, ...this.headers, ...headers },\n        body,\n        signal: effectiveSignal,\n      }).catch((fetchError) => {\n        throw new FunctionsFetchError(fetchError)\n      })\n\n      const isRelayError = response.headers.get('x-relay-error')\n      if (isRelayError && isRelayError === 'true') {\n        throw new FunctionsRelayError(response)\n      }\n\n      if (!response.ok) {\n        throw new FunctionsHttpError(response)\n      }\n\n      // HTTP media types are case-insensitive (RFC 9110), so normalize before\n      // matching \u2014 otherwise an \"Application/JSON\" response falls through to text.\n      let responseType = (response.headers.get('Content-Type') ?? 'text/plain')\n        .split(';')[0]\n        .trim()\n        .toLowerCase()\n      let data: any\n      if (responseType === 'application/json') {\n        data = await response.json()\n      } else if (\n        responseType === 'application/octet-stream' ||\n        responseType === 'application/pdf'\n      ) {\n        data = await response.blob()\n      } else if (responseType === 'text/event-stream') {\n        data = response\n      } else if (responseType === 'multipart/form-data') {\n        data = await response.formData()\n      } else {\n        // default to text\n        data = await response.text()\n      }\n\n      return { data, error: null, response }\n    } catch (error) {\n      return {\n        data: null,\n        error,\n        response:\n          error instanceof FunctionsHttpError || error instanceof FunctionsRelayError\n            ? error.context\n            : undefined,\n      }\n    } finally {\n      // Clear the timeout if it was set\n      if (timeoutId) {\n        clearTimeout(timeoutId)\n      }\n      // Remove the cross-signal listener to prevent memory leaks when the caller\n      // reuses the same AbortSignal across multiple invocations.\n      if (onAbort) {\n        options.signal?.removeEventListener('abort', onAbort)\n      }\n    }\n  }\n}\n", "/**\n * Error format\n *\n * Returned by every PostgREST request that fails. When something fails, the\n * single most useful field is usually `hint` — Postgres often returns the\n * actionable fix there, not in `message`. Always log the full object (e.g.\n * `console.error(error)`); logging only `error.message` hides the hint.\n *\n * Read the fields in roughly this order of usefulness:\n *\n * - `hint` — actionable guidance from the database when available. For\n *   permission-denied errors (`42501`), this is the literal SQL to fix the\n *   problem, e.g.\n *   `\"Grant the required privileges to the current role with: GRANT SELECT ON public.users TO anon;\"`.\n *   Missing column? `hint` suggests the column you probably meant. Whenever\n *   Postgres knows the fix, it puts it in `hint`.\n * - `code` — stable error code from PostgREST (e.g. `PGRST301`) or Postgres\n *   (e.g. `42501`). Branch on this rather than on `message` text.\n * - `details` — extra context, often the offending value, key, or row.\n * - `message` — human-readable summary. Useful in UI strings; less useful\n *   for debugging.\n *\n * {@link https://postgrest.org/en/stable/api.html?highlight=options#errors-and-http-status-codes}\n */\nexport default class PostgrestError extends Error {\n  details: string\n  hint: string\n  code: string\n\n  /**\n   * @example\n   * ```ts\n   * import PostgrestError from '@supabase/postgrest-js'\n   *\n   * throw new PostgrestError({\n   *   message: 'Row level security prevented the request',\n   *   details: 'RLS denied the insert',\n   *   hint: 'Check your policies',\n   *   code: 'PGRST301',\n   * })\n   * ```\n   */\n  constructor(context: { message: string; details: string; hint: string; code: string }) {\n    super(context.message)\n    this.name = 'PostgrestError'\n    this.details = context.details\n    this.hint = context.hint\n    this.code = context.code\n  }\n\n  toJSON(): { name: string; message: string; details: string; hint: string; code: string } {\n    return {\n      name: this.name,\n      message: this.message,\n      details: this.details,\n      hint: this.hint,\n      code: this.code,\n    }\n  }\n}\n", "// Types that are shared between supabase-js and postgrest-js\n\nexport type Fetch = typeof fetch\n\n/**\n * Default number of retry attempts.\n */\nexport const DEFAULT_MAX_RETRIES = 3\n\n/**\n * Default exponential backoff delay function.\n * Delays: 1s, 2s, 4s, 8s, ... (max 30s)\n *\n * @param attemptIndex - Zero-based index of the retry attempt\n * @returns Delay in milliseconds before the next retry\n */\nexport const getRetryDelay = (attemptIndex: number): number =>\n  Math.min(1000 * 2 ** attemptIndex, 30000)\n\n/**\n * Status codes that are safe to retry.\n * 520 = Cloudflare timeout/connection errors (transient)\n * 503 = PostgREST schema cache not yet loaded (transient, signals retry via Retry-After header)\n */\nexport const RETRYABLE_STATUS_CODES = [520, 503] as const\n\n/**\n * HTTP methods that are safe to retry (idempotent operations).\n */\nexport const RETRYABLE_METHODS = ['GET', 'HEAD', 'OPTIONS'] as const\n\nexport type GenericRelationship = {\n  foreignKeyName: string\n  columns: string[]\n  isOneToOne?: boolean\n  referencedRelation: string\n  referencedColumns: string[]\n}\n\nexport type GenericTable = {\n  Row: Record<string, unknown>\n  Insert: Record<string, unknown>\n  Update: Record<string, unknown>\n  Relationships: GenericRelationship[]\n  /**\n   * Names of the `Row` keys that are computed fields (functions taking the row), which\n   * PostgREST leaves out of `select('*')`. Generated types declare it; when absent, the\n   * computed fields are inferred from `Functions`.\n   */\n  ComputedFields?: string\n}\n\nexport type GenericUpdatableView = {\n  Row: Record<string, unknown>\n  Insert: Record<string, unknown>\n  Update: Record<string, unknown>\n  Relationships: GenericRelationship[]\n  ComputedFields?: string\n}\n\nexport type GenericNonUpdatableView = {\n  Row: Record<string, unknown>\n  Relationships: GenericRelationship[]\n  ComputedFields?: string\n}\n\nexport type GenericView = GenericUpdatableView | GenericNonUpdatableView\n\nexport type GenericSetofOption = {\n  isSetofReturn?: boolean | undefined\n  isOneToOne?: boolean | undefined\n  isNotNullable?: boolean | undefined\n  to: string\n  from: string\n}\n\nexport type GenericFunction = {\n  Args: Record<string, unknown> | never\n  Returns: unknown\n  SetofOptions?: GenericSetofOption\n}\n\nexport type GenericSchema = {\n  Tables: Record<string, GenericTable>\n  Views: Record<string, GenericView>\n  Functions: Record<string, GenericFunction>\n}\n\nexport type ClientServerOptions = {\n  PostgrestVersion?: string\n}\n", "import {\n  DEFAULT_MAX_RETRIES,\n  Fetch,\n  getRetryDelay,\n  RETRYABLE_METHODS,\n  RETRYABLE_STATUS_CODES,\n} from './types/common/common'\n\n/**\n * Sleep for a given number of milliseconds.\n * If an AbortSignal is provided, the sleep resolves early when the signal is aborted.\n */\nfunction sleep(ms: number, signal?: AbortSignal): Promise<void> {\n  return new Promise((resolve) => {\n    if (signal?.aborted) {\n      resolve()\n      return\n    }\n    const id = setTimeout(() => {\n      signal?.removeEventListener('abort', onAbort)\n      resolve()\n    }, ms)\n    function onAbort() {\n      clearTimeout(id)\n      resolve()\n    }\n    signal?.addEventListener('abort', onAbort)\n  })\n}\n\n/**\n * Check if a request should be retried based on method and status code.\n */\nfunction shouldRetry(\n  method: string,\n  status: number,\n  attemptCount: number,\n  retryEnabled: boolean\n): boolean {\n  // Don't retry if retries are disabled or we've exhausted attempts\n  if (!retryEnabled || attemptCount >= DEFAULT_MAX_RETRIES) {\n    return false\n  }\n\n  // Only retry idempotent methods (GET, HEAD, OPTIONS)\n  if (!RETRYABLE_METHODS.includes(method as (typeof RETRYABLE_METHODS)[number])) {\n    return false\n  }\n\n  // Only retry on specific status codes (520 - Cloudflare errors)\n  if (!RETRYABLE_STATUS_CODES.includes(status as (typeof RETRYABLE_STATUS_CODES)[number])) {\n    return false\n  }\n\n  return true\n}\n\nexport interface RetryableRequest {\n  method: string\n  /** Plain object, never a Headers instance: React Native's XHR-based fetch drops the latter. */\n  headers: Record<string, string>\n  body?: string\n  signal?: AbortSignal\n}\n\n/**\n * Perform a request with the retry policy shared by every PostgREST call.\n *\n * Idempotent methods (GET, HEAD, OPTIONS) are retried up to\n * `DEFAULT_MAX_RETRIES` times when the fetch rejects or the server answers\n * with a retryable status (503, 520). The wait honours the `Retry-After`\n * header when present and backs off exponentially otherwise. Retried\n * attempts carry an `X-Retry-Count` header. Aborted requests (including\n * `AbortSignal.timeout()`, which rejects with `TimeoutError`) and\n * non-idempotent methods are never retried: their rejection propagates\n * unchanged. A response body is drained before its request is retried.\n */\nexport async function fetchWithRetry(\n  fetchImpl: Fetch,\n  url: string,\n  request: RetryableRequest,\n  retryEnabled: boolean\n): Promise<Response> {\n  let attemptCount = 0\n\n  while (true) {\n    const headers: Record<string, string> = { ...request.headers }\n    if (attemptCount > 0) {\n      headers['X-Retry-Count'] = String(attemptCount)\n    }\n\n    let res: Response\n    try {\n      res = await fetchImpl(url, {\n        method: request.method,\n        headers,\n        body: request.body,\n        signal: request.signal,\n      })\n      // JS allows throwing any value, and serverless or realm-crossing fetch\n      // implementations can reject with non-Error objects. `instanceof Error`\n      // is too narrow here; narrow at the use site with optional chaining.\n      // eslint-disable-next-line @typescript-eslint/no-explicit-any\n    } catch (fetchError: any) {\n      // Never retry aborted requests. `AbortSignal.timeout()` rejects with\n      // `TimeoutError` rather than `AbortError`, so it needs its own check.\n      // Gated on `request.signal?.aborted` because `TimeoutError`, unlike\n      // `AbortError`, isn't exclusive to aborts: a custom fetch implementation\n      // may throw it for an unrelated, retryable timeout of its own.\n      if (\n        fetchError?.name === 'AbortError' ||\n        fetchError?.code === 'ABORT_ERR' ||\n        (fetchError?.name === 'TimeoutError' && request.signal?.aborted)\n      ) {\n        throw fetchError\n      }\n\n      // Don't retry network errors for non-idempotent methods\n      if (!RETRYABLE_METHODS.includes(request.method as (typeof RETRYABLE_METHODS)[number])) {\n        throw fetchError\n      }\n\n      // Check if we should retry network errors\n      if (retryEnabled && attemptCount < DEFAULT_MAX_RETRIES) {\n        const delay = getRetryDelay(attemptCount)\n        attemptCount++\n        await sleep(delay, request.signal)\n        continue\n      }\n\n      // Exhausted retries or retries disabled, throw the last error\n      throw fetchError\n    }\n\n    // Check if we should retry this HTTP response\n    if (shouldRetry(request.method, res.status, attemptCount, retryEnabled)) {\n      const retryAfterHeader = res.headers?.get('Retry-After') ?? null\n      const delay =\n        retryAfterHeader !== null\n          ? Math.max(0, parseInt(retryAfterHeader, 10) || 0) * 1000\n          : getRetryDelay(attemptCount)\n      await res.text()\n      attemptCount++\n      await sleep(delay, request.signal)\n      continue\n    }\n\n    return res\n  }\n}\n", "import type {\n  PostgrestSingleResponse,\n  PostgrestResponseSuccess,\n  CheckMatchingArrayTypes,\n  MergePartialResult,\n  IsValidResultOverride,\n} from './types/types'\nimport { ClientServerOptions, Fetch } from './types/common/common'\nimport PostgrestError from './PostgrestError'\nimport { fetchWithRetry } from './fetchWithRetry'\nimport { ContainsNull } from './select-query-parser/types'\n\nexport default abstract class PostgrestBuilder<\n  ClientOptions extends ClientServerOptions,\n  Result,\n  ThrowOnError extends boolean = false,\n> implements PromiseLike<\n  ThrowOnError extends true ? PostgrestResponseSuccess<Result> : PostgrestSingleResponse<Result>\n> {\n  protected method: 'GET' | 'HEAD' | 'POST' | 'PATCH' | 'DELETE'\n  protected url: URL\n  protected headers: Headers\n  protected schema?: string\n  protected body?: unknown\n  protected shouldThrowOnError = false\n  protected signal?: AbortSignal\n  protected fetch: Fetch\n  protected isMaybeSingle: boolean\n  protected shouldStripNulls: boolean\n  protected urlLengthLimit: number\n\n  // Retry configuration - enabled by default\n  protected retryEnabled: boolean = true\n\n  /**\n   * Creates a builder configured for a specific PostgREST request.\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.from('users').select('*')\n   * ```\n   *\n   * @category Database\n   *\n   * @example Standalone import for bundle-sensitive environments\n   * ```ts\n   * import { PostgrestQueryBuilder } from '@supabase/postgrest-js'\n   *\n   * const builder = new PostgrestQueryBuilder(\n   *   new URL('https://xyzcompany.supabase.co/rest/v1/users'),\n   *   { headers: new Headers({ apikey: 'your-publishable-key' }) }\n   * )\n   * ```\n   */\n  constructor(builder: {\n    method: 'GET' | 'HEAD' | 'POST' | 'PATCH' | 'DELETE'\n    url: URL\n    headers: HeadersInit\n    schema?: string\n    body?: unknown\n    shouldThrowOnError?: boolean\n    signal?: AbortSignal\n    fetch?: Fetch\n    isMaybeSingle?: boolean\n    shouldStripNulls?: boolean\n    urlLengthLimit?: number\n    // Retry option\n    retry?: boolean\n  }) {\n    this.method = builder.method\n    this.url = builder.url\n    this.headers = new Headers(builder.headers)\n    this.schema = builder.schema\n    this.body = builder.body\n    this.shouldThrowOnError = builder.shouldThrowOnError ?? false\n    this.signal = builder.signal\n    this.isMaybeSingle = builder.isMaybeSingle ?? false\n    this.shouldStripNulls = builder.shouldStripNulls ?? false\n    this.urlLengthLimit = builder.urlLengthLimit ?? 8000\n    this.retryEnabled = builder.retry ?? true\n\n    if (builder.fetch) {\n      this.fetch = builder.fetch\n    } else {\n      this.fetch = fetch\n    }\n  }\n\n  /**\n   * If there's 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   * {@link https://github.com/supabase/supabase-js/issues/92}\n   *\n   * @category Database\n   * @subcategory Using modifiers\n   */\n  throwOnError(): PostgrestBuilder<ClientOptions, Result, true> {\n    this.shouldThrowOnError = true\n    return this as PostgrestBuilder<ClientOptions, Result, true>\n  }\n\n  /**\n   * Strip null values from the response data. Properties with `null` values\n   * will be omitted from the returned JSON objects.\n   *\n   * Requires PostgREST 11.2.0+.\n   *\n   * {@link https://docs.postgrest.org/en/stable/references/api/resource_representation.html#stripped-nulls}\n   *\n   * @category Database\n   * @subcategory Using modifiers\n   *\n   * @example With `select()`\n   * ```ts\n   * const { data, error } = await supabase\n   *   .from('characters')\n   *   .select()\n   *   .stripNulls()\n   * ```\n   *\n   * @exampleSql With `select()`\n   * ```sql\n   * create table\n   *   characters (id int8 primary key, name text, bio text);\n   *\n   * insert into\n   *   characters (id, name, bio)\n   * values\n   *   (1, 'Luke', null),\n   *   (2, 'Leia', 'Princess of Alderaan');\n   * ```\n   *\n   * @exampleResponse With `select()`\n   * ```json\n   * {\n   *   \"data\": [\n   *     {\n   *       \"id\": 1,\n   *       \"name\": \"Luke\"\n   *     },\n   *     {\n   *       \"id\": 2,\n   *       \"name\": \"Leia\",\n   *       \"bio\": \"Princess of Alderaan\"\n   *     }\n   *   ],\n   *   \"status\": 200,\n   *   \"statusText\": \"OK\"\n   * }\n   * ```\n   */\n  stripNulls(): this {\n    if (this.headers.get('Accept') === 'text/csv') {\n      throw new Error('stripNulls() cannot be used with csv()')\n    }\n    this.shouldStripNulls = true\n    return this\n  }\n\n  /**\n   * Set an HTTP header on this single PostgREST request, overriding any header\n   * with the same name set on the client.\n   *\n   * This is an advanced escape hatch for one-off needs (passing a custom\n   * `Authorization` for a single query, attaching a tracing header, etc.).\n   * Most callers do not need it: configure client-wide headers via the\n   * `headers` option when constructing the client, and authentication via\n   * Supabase Auth.\n   *\n   * @param name - HTTP header name\n   * @param value - HTTP header value\n   *\n   * @category Database\n   * @subcategory Using modifiers\n   */\n  setHeader(name: string, value: string): this {\n    this.headers = new Headers(this.headers)\n    this.headers.set(name, value)\n    return this\n  }\n\n  /**\n   * @category Database\n   * @subcategory Using modifiers\n   *\n   * Configure retry behavior for this request.\n   *\n   * By default, retries are enabled for idempotent requests (GET, HEAD, OPTIONS)\n   * that fail with network errors or specific HTTP status codes (503, 520).\n   * Retries use exponential backoff (1s, 2s, 4s) with a maximum of 3 attempts.\n   *\n   * @param enabled - Whether to enable retries for this request\n   *\n   * @example\n   * ```ts\n   * // Disable retries for a specific query\n   * const { data, error } = await supabase\n   *   .from('users')\n   *   .select()\n   *   .retry(false)\n   * ```\n   */\n  retry(enabled: boolean): this {\n    this.retryEnabled = enabled\n    return this\n  }\n\n  then<\n    TResult1 = ThrowOnError extends true\n      ? PostgrestResponseSuccess<Result>\n      : PostgrestSingleResponse<Result>,\n    TResult2 = never,\n  >(\n    onfulfilled?:\n      | ((\n          value: ThrowOnError extends true\n            ? PostgrestResponseSuccess<Result>\n            : PostgrestSingleResponse<Result>\n        ) => TResult1 | PromiseLike<TResult1>)\n      | undefined\n      | null,\n    onrejected?: ((reason: any) => TResult2 | PromiseLike<TResult2>) | undefined | null\n  ): PromiseLike<TResult1 | TResult2> {\n    // https://postgrest.org/en/stable/api.html#switching-schemas\n    if (this.schema === undefined) {\n      // skip\n    } else if (['GET', 'HEAD'].includes(this.method)) {\n      this.headers.set('Accept-Profile', this.schema)\n    } else {\n      this.headers.set('Content-Profile', this.schema)\n    }\n    if (this.method !== 'GET' && this.method !== 'HEAD') {\n      this.headers.set('Content-Type', 'application/json')\n    }\n\n    // https://docs.postgrest.org/en/stable/references/api/resource_representation.html#stripped-nulls\n    if (this.shouldStripNulls) {\n      const currentAccept = this.headers.get('Accept')\n      if (currentAccept === 'application/vnd.pgrst.object+json') {\n        this.headers.set('Accept', 'application/vnd.pgrst.object+json;nulls=stripped')\n      } else if (!currentAccept || currentAccept === 'application/json') {\n        this.headers.set('Accept', 'application/vnd.pgrst.array+json;nulls=stripped')\n      }\n    }\n\n    // NOTE: Invoke w/o `this` to avoid illegal invocation error.\n    // https://github.com/supabase/postgrest-js/pull/247\n    const _fetch = this.fetch\n\n    // Execute fetch with retry logic\n    const executeWithRetry = async (): Promise<{\n      error: any\n      data: any\n      count: number | null\n      status: number\n      statusText: string\n    }> => {\n      // Serialize headers as a plain object rather than a Headers instance.\n      // React Native's XHR-based fetch silently drops headers (notably Content-Type)\n      // when given a Headers instance, causing PGRST202 on parameter-less RPC calls.\n      // See supabase/supabase-js#1562 and facebook/react-native#33933.\n      // All sibling packages (auth-js, storage-js, functions-js) already pass plain objects.\n      const headers: Record<string, string> = {}\n      this.headers.forEach((value, key) => {\n        headers[key] = value\n      })\n\n      // Only the fetch itself is retried — processResponse errors must never trigger retries\n      const res = await fetchWithRetry(\n        _fetch,\n        this.url.toString(),\n        {\n          method: this.method,\n          headers,\n          body: JSON.stringify(this.body, (_, value) =>\n            typeof value === 'bigint' ? value.toString() : value\n          ),\n          signal: this.signal,\n        },\n        this.retryEnabled\n      )\n\n      return await this.processResponse(res)\n    }\n\n    let res = executeWithRetry()\n\n    if (!this.shouldThrowOnError) {\n      res = res.catch((fetchError) => {\n        // Build detailed error information including cause if available\n        // Note: We don't populate code/hint for client-side network errors since those\n        // fields are meant for upstream service errors (PostgREST/PostgreSQL)\n        let errorDetails = ''\n        let hint = ''\n        let code = ''\n\n        // Add cause information if available (e.g., DNS errors, network failures)\n        const cause = fetchError?.cause\n        if (cause) {\n          const causeMessage = cause?.message ?? ''\n          const causeCode = cause?.code ?? ''\n\n          errorDetails = `${fetchError?.name ?? 'FetchError'}: ${fetchError?.message}`\n          errorDetails += `\\n\\nCaused by: ${cause?.name ?? 'Error'}: ${causeMessage}`\n          if (causeCode) {\n            errorDetails += ` (${causeCode})`\n          }\n          if (cause?.stack) {\n            errorDetails += `\\n${cause.stack}`\n          }\n        } else {\n          // No cause available, just include the error stack\n          errorDetails = fetchError?.stack ?? ''\n        }\n\n        // Get URL length for potential hints\n        const urlLength = this.url.toString().length\n\n        // Handle AbortError specially with helpful hints\n        if (fetchError?.name === 'AbortError' || fetchError?.code === 'ABORT_ERR') {\n          code = ''\n          hint = 'Request was aborted (timeout or manual cancellation)'\n\n          if (urlLength > this.urlLengthLimit) {\n            hint += `. Note: Your request URL is ${urlLength} characters, which may exceed server limits. If selecting many fields, consider using views. If filtering with large arrays (e.g., .in('id', [many IDs])), consider using an RPC function to pass values server-side.`\n          }\n        }\n        // Handle HeadersOverflowError from undici (Node.js fetch implementation)\n        else if (\n          cause?.name === 'HeadersOverflowError' ||\n          cause?.code === 'UND_ERR_HEADERS_OVERFLOW'\n        ) {\n          code = ''\n          hint = 'HTTP headers exceeded server limits (typically 16KB)'\n\n          if (urlLength > this.urlLengthLimit) {\n            hint += `. Your request URL is ${urlLength} characters. If selecting many fields, consider using views. If filtering with large arrays (e.g., .in('id', [200+ IDs])), consider using an RPC function instead.`\n          }\n        }\n\n        return {\n          success: false as const,\n          error: {\n            message: `${fetchError?.name ?? 'FetchError'}: ${fetchError?.message}`,\n            details: errorDetails,\n            hint: hint,\n            code: code,\n          },\n          data: null,\n          count: null,\n          status: 0,\n          statusText: '',\n        }\n      })\n    }\n\n    return (\n      res as Promise<\n        ThrowOnError extends true\n          ? PostgrestResponseSuccess<Result>\n          : PostgrestSingleResponse<Result>\n      >\n    ).then(onfulfilled, onrejected)\n  }\n\n  /**\n   * Process a fetch response and return the standardized postgrest response.\n   */\n  private async processResponse(res: Response): Promise<{\n    success: boolean\n    error: any\n    data: any\n    count: number | null\n    status: number\n    statusText: string\n  }> {\n    let error = null\n    let data = null\n    let count: number | null = null\n    let status = res.status\n    let statusText = res.statusText\n\n    if (res.ok) {\n      if (this.method !== 'HEAD') {\n        const body = await res.text()\n        if (body === '') {\n          // Prefer: return=minimal\n        } else if (this.headers.get('Accept') === 'text/csv') {\n          data = body\n        } else if (\n          this.headers.get('Accept') &&\n          this.headers.get('Accept')?.includes('application/vnd.pgrst.plan+text')\n        ) {\n          data = body\n        } else {\n          try {\n            data = JSON.parse(body)\n          } catch {\n            // A 2xx status doesn't guarantee a JSON body; mirror the non-2xx fallback below.\n            error = { message: body }\n            data = null\n\n            if (this.shouldThrowOnError) {\n              throw new PostgrestError({ message: body, details: '', hint: '', code: '' })\n            }\n          }\n        }\n      }\n\n      const countHeader = this.headers.get('Prefer')?.match(/count=(exact|planned|estimated)/)\n      const contentRange = res.headers.get('content-range')?.split('/')\n      if (countHeader && contentRange && contentRange.length > 1) {\n        count = parseInt(contentRange[1])\n      }\n\n      // Fix for https://github.com/supabase/postgrest-js/issues/361 — applies to all methods.\n      if (this.isMaybeSingle && Array.isArray(data)) {\n        if (data.length > 1) {\n          error = {\n            // https://github.com/PostgREST/postgrest/blob/a867d79c42419af16c18c3fb019eba8df992626f/src/PostgREST/Error.hs#L553\n            code: 'PGRST116',\n            details: `Results contain ${data.length} rows, application/vnd.pgrst.object+json requires 1 row`,\n            hint: null,\n            message: 'JSON object requested, multiple (or no) rows returned',\n          }\n          data = null\n          count = null\n          status = 406\n          statusText = 'Not Acceptable'\n\n          if (this.shouldThrowOnError) {\n            // `hint` is null in the returned error to match PostgREST, but\n            // PostgrestError types it as a string, like the other throws here.\n            throw new PostgrestError({ ...error, hint: error.hint ?? '' })\n          }\n        } else if (data.length === 1) {\n          data = data[0]\n        } else {\n          data = null\n        }\n      }\n    } else {\n      const body = await res.text()\n\n      try {\n        error = JSON.parse(body)\n\n        // Workaround for https://github.com/supabase/postgrest-js/issues/295\n        if (Array.isArray(error) && res.status === 404) {\n          data = []\n          error = null\n          status = 200\n          statusText = 'OK'\n        }\n      } catch {\n        // Workaround for https://github.com/supabase/postgrest-js/issues/295\n        if (res.status === 404 && body === '') {\n          status = 204\n          statusText = 'No Content'\n        } else {\n          error = {\n            message: body,\n          }\n        }\n      }\n\n      if (error && this.shouldThrowOnError) {\n        throw new PostgrestError(error)\n      }\n    }\n\n    return {\n      success: error === null,\n      error,\n      data,\n      count,\n      status,\n      statusText,\n    }\n  }\n\n  /**\n   * Override the type of the returned `data`.\n   *\n   * @typeParam NewResult - The new result type to override with\n   * @deprecated Use overrideTypes<yourType, { merge: false }>() method at the end of your call chain instead\n   *\n   * @category Database\n   * @subcategory Using modifiers\n   */\n  returns<NewResult>(): PostgrestBuilder<\n    ClientOptions,\n    CheckMatchingArrayTypes<Result, NewResult>,\n    ThrowOnError\n  > {\n    /* istanbul ignore next */\n    return this as unknown as PostgrestBuilder<\n      ClientOptions,\n      CheckMatchingArrayTypes<Result, NewResult>,\n      ThrowOnError\n    >\n  }\n\n  /**\n   * Override the type of the returned `data` field in the response.\n   *\n   * @typeParam NewResult - The new type to cast the response data to\n   * @typeParam Options - Optional type configuration (defaults to { merge: true })\n   * @typeParam Options.merge - When true, merges the new type with existing return type. When false, replaces the existing types entirely (defaults to true)\n   * @example\n   * ```typescript\n   * // Merge with existing types (default behavior)\n   * const query = supabase\n   *   .from('users')\n   *   .select()\n   *   .overrideTypes<{ custom_field: string }>()\n   *\n   * // Replace existing types completely\n   * const replaceQuery = supabase\n   *   .from('users')\n   *   .select()\n   *   .overrideTypes<{ id: number; name: string }, { merge: false }>()\n   * ```\n   * @returns A PostgrestBuilder instance with the new type\n   *\n   * @category Database\n   * @subcategory Using modifiers\n   *\n   * @example Complete Override type of successful response\n   * ```ts\n   * const { data } = await supabase\n   *   .from('countries')\n   *   .select()\n   *   .overrideTypes<Array<MyType>, { merge: false }>()\n   * ```\n   *\n   * @exampleResponse Complete Override type of successful response\n   * ```ts\n   * let x: typeof data // MyType[]\n   * ```\n   *\n   * @example Complete Override type of object response\n   * ```ts\n   * const { data } = await supabase\n   *   .from('countries')\n   *   .select()\n   *   .maybeSingle()\n   *   .overrideTypes<MyType, { merge: false }>()\n   * ```\n   *\n   * @exampleResponse Complete Override type of object response\n   * ```ts\n   * let x: typeof data // MyType | null\n   * ```\n   *\n   * @example Partial Override type of successful response\n   * ```ts\n   * const { data } = await supabase\n   *   .from('countries')\n   *   .select()\n   *   .overrideTypes<Array<{ status: \"A\" | \"B\" }>>()\n   * ```\n   *\n   * @exampleResponse Partial Override type of successful response\n   * ```ts\n   * let x: typeof data // Array<CountryRowProperties & { status: \"A\" | \"B\" }>\n   * ```\n   *\n   * @example Partial Override type of object response\n   * ```ts\n   * const { data } = await supabase\n   *   .from('countries')\n   *   .select()\n   *   .maybeSingle()\n   *   .overrideTypes<{ status: \"A\" | \"B\" }>()\n   * ```\n   *\n   * @exampleResponse Partial Override type of object response\n   * ```ts\n   * let x: typeof data // CountryRowProperties & { status: \"A\" | \"B\" } | null\n   * ```\n   *\n   * @example Merge vs replace existing types\n   * ```typescript\n   * // Merge with existing types (default behavior)\n   * const query = supabase\n   *   .from('users')\n   *   .select()\n   *   .overrideTypes<{ custom_field: string }>()\n   *\n   * // Replace existing types completely\n   * const replaceQuery = supabase\n   *   .from('users')\n   *   .select()\n   *   .overrideTypes<{ id: number; name: string }, { merge: false }>()\n   * ```\n   */\n  overrideTypes<\n    NewResult,\n    Options extends { merge?: boolean } = { merge: true },\n  >(): PostgrestBuilder<\n    ClientOptions,\n    IsValidResultOverride<Result, NewResult, false, false> extends true\n      ? // Preserve the optionality of the result if the overriden type is an object (case of chaining with `maybeSingle`)\n        ContainsNull<Result> extends true\n        ? MergePartialResult<NewResult, NonNullable<Result>, Options> | null\n        : MergePartialResult<NewResult, Result, Options>\n      : CheckMatchingArrayTypes<Result, NewResult>,\n    ThrowOnError\n  > {\n    return this as unknown as PostgrestBuilder<\n      ClientOptions,\n      IsValidResultOverride<Result, NewResult, false, false> extends true\n        ? // Preserve the optionality of the result if the overriden type is an object (case of chaining with `maybeSingle`)\n          ContainsNull<Result> extends true\n          ? MergePartialResult<NewResult, NonNullable<Result>, Options> | null\n          : MergePartialResult<NewResult, Result, Options>\n        : CheckMatchingArrayTypes<Result, NewResult>,\n      ThrowOnError\n    >\n  }\n}\n", "import PostgrestBuilder from './PostgrestBuilder'\nimport PostgrestFilterBuilder, { InvalidMethodError } from './PostgrestFilterBuilder'\nimport { GetResult } from './select-query-parser/result'\nimport { CheckMatchingArrayTypes } from './types/types'\nimport { ClientServerOptions, GenericSchema } from './types/common/common'\nimport type { MaxAffectedEnabled } from './types/feature-flags'\n\nexport default class PostgrestTransformBuilder<\n  ClientOptions extends ClientServerOptions,\n  Schema extends GenericSchema,\n  Row extends Record<string, unknown>,\n  Result,\n  RelationName = unknown,\n  Relationships = unknown,\n  Method = unknown,\n  ThrowOnError extends boolean = false,\n> extends PostgrestBuilder<ClientOptions, Result, ThrowOnError> {\n  throwOnError(): PostgrestTransformBuilder<\n    ClientOptions,\n    Schema,\n    Row,\n    Result,\n    RelationName,\n    Relationships,\n    Method,\n    true\n  > {\n    return super.throwOnError() as PostgrestTransformBuilder<\n      ClientOptions,\n      Schema,\n      Row,\n      Result,\n      RelationName,\n      Relationships,\n      Method,\n      true\n    >\n  }\n\n  /**\n   * Perform a SELECT on the query result.\n   *\n   * By default, `.insert()`, `.update()`, `.upsert()`, and `.delete()` do not\n   * return modified rows. By calling this method, modified rows are returned in\n   * `data`.\n   *\n   * @param columns - The columns to retrieve, separated by commas\n   *\n   * @category Database\n   * @subcategory Using modifiers\n   *\n   * @example With `upsert()`\n   * ```ts\n   * const { data, error } = await supabase\n   *   .from('characters')\n   *   .upsert({ id: 1, name: 'Han Solo' })\n   *   .select()\n   * ```\n   *\n   * @exampleSql With `upsert()`\n   * ```sql\n   * create table\n   *   characters (id int8 primary key, name text);\n   *\n   * insert into\n   *   characters (id, name)\n   * values\n   *   (1, 'Han');\n   * ```\n   *\n   * @exampleResponse With `upsert()`\n   * ```json\n   * {\n   *   \"data\": [\n   *     {\n   *       \"id\": 1,\n   *       \"name\": \"Han Solo\"\n   *     }\n   *   ],\n   *   \"status\": 201,\n   *   \"statusText\": \"\"\n   * }\n   * ```\n   */\n  select<\n    Query extends string = '*',\n    NewResultOne = GetResult<Schema, Row, RelationName, Relationships, Query, ClientOptions>,\n  >(\n    columns?: Query\n  ): PostgrestFilterBuilder<\n    ClientOptions,\n    Schema,\n    Row,\n    Method extends 'RPC'\n      ? Result extends unknown[]\n        ? NewResultOne[]\n        : NewResultOne\n      : NewResultOne[],\n    RelationName,\n    Relationships,\n    Method,\n    ThrowOnError\n  > {\n    // Remove whitespaces except when quoted\n    let quoted = false\n    const cleanedColumns = (columns ?? '*')\n      .split('')\n      .map((c) => {\n        if (/\\s/.test(c) && !quoted) {\n          return ''\n        }\n        if (c === '\"') {\n          quoted = !quoted\n        }\n        return c\n      })\n      .join('')\n    this.url.searchParams.set('select', cleanedColumns)\n    this.headers.append('Prefer', 'return=representation')\n    return this as unknown as PostgrestFilterBuilder<\n      ClientOptions,\n      Schema,\n      Row,\n      Method extends 'RPC'\n        ? Result extends unknown[]\n          ? NewResultOne[]\n          : NewResultOne\n        : NewResultOne[],\n      RelationName,\n      Relationships,\n      Method,\n      ThrowOnError\n    >\n  }\n\n  /**\n   * Order the query result by `column`.\n   *\n   * You can call this method multiple times to order by multiple columns.\n   *\n   * You can order referenced tables, but it only affects the ordering of the\n   * parent table if you use `!inner` in the query.\n   *\n   * @param column - The column to order by\n   * @param options - Named parameters\n   * @param options.ascending - If `true`, the result will be in ascending order\n   * @param options.nullsFirst - If `true`, `null`s appear first. If `false`,\n   * `null`s appear last.\n   * @param options.referencedTable - Set this to order a referenced table by\n   * its columns\n   *\n   * @category Database\n   * @subcategory Using modifiers\n   */\n  order<ColumnName extends string & keyof Row>(\n    column: ColumnName,\n    options?: { ascending?: boolean; nullsFirst?: boolean; referencedTable?: undefined }\n  ): this\n  order(\n    column: string,\n    options?: { ascending?: boolean; nullsFirst?: boolean; referencedTable?: string }\n  ): this\n  /**\n   * @deprecated Use `options.referencedTable` instead of `options.foreignTable`\n   */\n  order<ColumnName extends string & keyof Row>(\n    column: ColumnName,\n    options?: { ascending?: boolean; nullsFirst?: boolean; foreignTable?: undefined }\n  ): this\n  /**\n   * @deprecated Use `options.referencedTable` instead of `options.foreignTable`\n   */\n  order(\n    column: string,\n    options?: { ascending?: boolean; nullsFirst?: boolean; foreignTable?: string }\n  ): this\n  /**\n   * Order the query result by `column`.\n   *\n   * You can call this method multiple times to order by multiple columns.\n   *\n   * You can order referenced tables, but it only affects the ordering of the\n   * parent table if you use `!inner` in the query.\n   *\n   * @param column - The column to order by\n   * @param options - Named parameters\n   * @param options.ascending - If `true`, the result will be in ascending order\n   * @param options.nullsFirst - If `true`, `null`s appear first. If `false`,\n   * `null`s appear last.\n   * @param options.referencedTable - Set this to order a referenced table by\n   * its columns\n   * @param options.foreignTable - Deprecated, use `options.referencedTable`\n   * instead\n   *\n   * @category Database\n   * @subcategory Using modifiers\n   *\n   * @example With `select()`\n   * ```ts\n   * const { data, error } = await supabase\n   *   .from('characters')\n   *   .select('id, name')\n   *   .order('id', { ascending: false })\n   * ```\n   *\n   * @exampleSql With `select()`\n   * ```sql\n   * create table\n   *   characters (id int8 primary key, name text);\n   *\n   * insert into\n   *   characters (id, name)\n   * values\n   *   (1, 'Luke'),\n   *   (2, 'Leia'),\n   *   (3, 'Han');\n   * ```\n   *\n   * @exampleResponse With `select()`\n   * ```json\n   * {\n   *   \"data\": [\n   *     {\n   *       \"id\": 3,\n   *       \"name\": \"Han\"\n   *     },\n   *     {\n   *       \"id\": 2,\n   *       \"name\": \"Leia\"\n   *     },\n   *     {\n   *       \"id\": 1,\n   *       \"name\": \"Luke\"\n   *     }\n   *   ],\n   *   \"status\": 200,\n   *   \"statusText\": \"OK\"\n   * }\n   * ```\n   *\n   * @exampleDescription On a referenced table\n   * Ordering with `referencedTable` doesn't affect the ordering of the\n   * parent table.\n   *\n   * @example On a referenced table\n   * ```ts\n   *   const { data, error } = await supabase\n   *     .from('orchestral_sections')\n   *     .select(`\n   *       name,\n   *       instruments (\n   *         name\n   *       )\n   *     `)\n   *     .order('name', { referencedTable: 'instruments', ascending: false })\n   *\n   * ```\n   *\n   * @exampleSql On a referenced table\n   * ```sql\n   * create table\n   *   orchestral_sections (id int8 primary key, name text);\n   * create table\n   *   instruments (\n   *     id int8 primary key,\n   *     section_id int8 not null references orchestral_sections,\n   *     name text\n   *   );\n   *\n   * insert into\n   *   orchestral_sections (id, name)\n   * values\n   *   (1, 'strings'),\n   *   (2, 'woodwinds');\n   * insert into\n   *   instruments (id, section_id, name)\n   * values\n   *   (1, 1, 'harp'),\n   *   (2, 1, 'violin');\n   * ```\n   *\n   * @exampleResponse On a referenced table\n   * ```json\n   * {\n   *   \"data\": [\n   *     {\n   *       \"name\": \"strings\",\n   *       \"instruments\": [\n   *         {\n   *           \"name\": \"violin\"\n   *         },\n   *         {\n   *           \"name\": \"harp\"\n   *         }\n   *       ]\n   *     },\n   *     {\n   *       \"name\": \"woodwinds\",\n   *       \"instruments\": []\n   *     }\n   *   ],\n   *   \"status\": 200,\n   *   \"statusText\": \"OK\"\n   * }\n   * ```\n   *\n   * @exampleDescription Order parent table by a referenced table\n   * Ordering with `referenced_table(col)` affects the ordering of the\n   * parent table.\n   *\n   * @example Order parent table by a referenced table\n   * ```ts\n   *   const { data, error } = await supabase\n   *     .from('instruments')\n   *     .select(`\n   *       name,\n   *       section:orchestral_sections (\n   *         name\n   *       )\n   *     `)\n   *     .order('section(name)', { ascending: true })\n   *\n   * ```\n   *\n   * @exampleSql Order parent table by a referenced table\n   * ```sql\n   * create table\n   *   orchestral_sections (id int8 primary key, name text);\n   * create table\n   *   instruments (\n   *     id int8 primary key,\n   *     section_id int8 not null references orchestral_sections,\n   *     name text\n   *   );\n   *\n   * insert into\n   *   orchestral_sections (id, name)\n   * values\n   *   (1, 'strings'),\n   *   (2, 'woodwinds');\n   * insert into\n   *   instruments (id, section_id, name)\n   * values\n   *   (1, 2, 'flute'),\n   *   (2, 1, 'violin');\n   * ```\n   *\n   * @exampleResponse Order parent table by a referenced table\n   * ```json\n   * {\n   *   \"data\": [\n   *     {\n   *       \"name\": \"violin\",\n   *       \"orchestral_sections\": {\"name\": \"strings\"}\n   *     },\n   *     {\n   *       \"name\": \"flute\",\n   *       \"orchestral_sections\": {\"name\": \"woodwinds\"}\n   *     }\n   *   ],\n   *   \"status\": 200,\n   *   \"statusText\": \"OK\"\n   * }\n   * ```\n   */\n  order(\n    column: string,\n    {\n      ascending = true,\n      nullsFirst,\n      foreignTable,\n      referencedTable = foreignTable,\n    }: {\n      ascending?: boolean\n      nullsFirst?: boolean\n      foreignTable?: string\n      referencedTable?: string\n    } = {}\n  ): this {\n    const key = referencedTable ? `${referencedTable}.order` : 'order'\n    const existingOrder = this.url.searchParams.get(key)\n\n    this.url.searchParams.set(\n      key,\n      `${existingOrder ? `${existingOrder},` : ''}${column}.${ascending ? 'asc' : 'desc'}${\n        nullsFirst === undefined ? '' : nullsFirst ? '.nullsfirst' : '.nullslast'\n      }`\n    )\n    return this\n  }\n\n  /**\n   * Limit the query result by `rows`.\n   *\n   * @param rows - The maximum number of rows to return\n   * @param options - Named parameters\n   * @param options.referencedTable - Set this to limit rows of referenced\n   * tables instead of the parent table\n   * @param options.foreignTable - Deprecated, use `options.referencedTable`\n   * instead\n   *\n   * @category Database\n   * @subcategory Using modifiers\n   *\n   * @example With `select()`\n   * ```ts\n   * const { data, error } = await supabase\n   *   .from('characters')\n   *   .select('name')\n   *   .limit(1)\n   * ```\n   *\n   * @exampleSql With `select()`\n   * ```sql\n   * create table\n   *   characters (id int8 primary key, name text);\n   *\n   * insert into\n   *   characters (id, name)\n   * values\n   *   (1, 'Luke'),\n   *   (2, 'Leia'),\n   *   (3, 'Han');\n   * ```\n   *\n   * @exampleResponse With `select()`\n   * ```json\n   * {\n   *   \"data\": [\n   *     {\n   *       \"name\": \"Luke\"\n   *     }\n   *   ],\n   *   \"status\": 200,\n   *   \"statusText\": \"OK\"\n   * }\n   * ```\n   *\n   * @example On a referenced table\n   * ```ts\n   * const { data, error } = await supabase\n   *   .from('orchestral_sections')\n   *   .select(`\n   *     name,\n   *     instruments (\n   *       name\n   *     )\n   *   `)\n   *   .limit(1, { referencedTable: 'instruments' })\n   * ```\n   *\n   * @exampleSql On a referenced table\n   * ```sql\n   * create table\n   *   orchestral_sections (id int8 primary key, name text);\n   * create table\n   *   instruments (\n   *     id int8 primary key,\n   *     section_id int8 not null references orchestral_sections,\n   *     name text\n   *   );\n   *\n   * insert into\n   *   orchestral_sections (id, name)\n   * values\n   *   (1, 'strings');\n   * insert into\n   *   instruments (id, section_id, name)\n   * values\n   *   (1, 1, 'harp'),\n   *   (2, 1, 'violin');\n   * ```\n   *\n   * @exampleResponse On a referenced table\n   * ```json\n   * {\n   *   \"data\": [\n   *     {\n   *       \"name\": \"strings\",\n   *       \"instruments\": [\n   *         {\n   *           \"name\": \"violin\"\n   *         }\n   *       ]\n   *     }\n   *   ],\n   *   \"status\": 200,\n   *   \"statusText\": \"OK\"\n   * }\n   * ```\n   */\n  limit(\n    rows: number,\n    {\n      foreignTable,\n      referencedTable = foreignTable,\n    }: { foreignTable?: string; referencedTable?: string } = {}\n  ): this {\n    const key = typeof referencedTable === 'undefined' ? 'limit' : `${referencedTable}.limit`\n    this.url.searchParams.set(key, `${rows}`)\n    return this\n  }\n\n  /**\n   * Limit the query result by starting at an offset `from` and ending at the offset `to`.\n   * Only records within this range are returned.\n   * This respects the query order and if there is no order clause the range could behave unexpectedly.\n   * The `from` and `to` values are 0-based and inclusive: `range(1, 3)` will include the second, third\n   * and fourth rows of the query.\n   *\n   * @param from - The starting index from which to limit the result\n   * @param to - The last index to which to limit the result\n   * @param options - Named parameters\n   * @param options.referencedTable - Set this to limit rows of referenced\n   * tables instead of the parent table\n   * @param options.foreignTable - Deprecated, use `options.referencedTable`\n   * instead\n   *\n   * @category Database\n   * @subcategory Using modifiers\n   *\n   * @example With `select()`\n   * ```ts\n   * const { data, error } = await supabase\n   *   .from('characters')\n   *   .select('name')\n   *   .range(0, 1)\n   * ```\n   *\n   * @exampleSql With `select()`\n   * ```sql\n   * create table\n   *   characters (id int8 primary key, name text);\n   *\n   * insert into\n   *   characters (id, name)\n   * values\n   *   (1, 'Luke'),\n   *   (2, 'Leia'),\n   *   (3, 'Han');\n   * ```\n   *\n   * @exampleResponse With `select()`\n   * ```json\n   * {\n   *   \"data\": [\n   *     {\n   *       \"name\": \"Luke\"\n   *     },\n   *     {\n   *       \"name\": \"Leia\"\n   *     }\n   *   ],\n   *   \"status\": 200,\n   *   \"statusText\": \"OK\"\n   * }\n   * ```\n   */\n  range(\n    from: number,\n    to: number,\n    {\n      foreignTable,\n      referencedTable = foreignTable,\n    }: { foreignTable?: string; referencedTable?: string } = {}\n  ): this {\n    const keyOffset =\n      typeof referencedTable === 'undefined' ? 'offset' : `${referencedTable}.offset`\n    const keyLimit = typeof referencedTable === 'undefined' ? 'limit' : `${referencedTable}.limit`\n    this.url.searchParams.set(keyOffset, `${from}`)\n    // Range is inclusive, so add 1\n    this.url.searchParams.set(keyLimit, `${to - from + 1}`)\n    return this\n  }\n\n  /**\n   * Set the AbortSignal for the fetch request.\n   *\n   * @param signal - The AbortSignal to use for the fetch request\n   *\n   * @category Database\n   * @subcategory Using modifiers\n   *\n   * @remarks\n   * You can use this to set a timeout for the request.\n   *\n   * @exampleDescription Aborting requests in-flight\n   * You can use an [`AbortController`](https://developer.mozilla.org/en-US/docs/Web/API/AbortController) to abort requests.\n   * Note that `status` and `statusText` don't mean anything for aborted requests as the request wasn't fulfilled.\n   *\n   * @example Aborting requests in-flight\n   * ```ts\n   * const ac = new AbortController()\n   *\n   * const { data, error } = await supabase\n   *   .from('very_big_table')\n   *   .select()\n   *   .abortSignal(ac.signal)\n   *\n   * // Abort the request after 100 ms\n   * setTimeout(() => ac.abort(), 100)\n   * ```\n   *\n   * @exampleResponse Aborting requests in-flight\n   * ```json\n   *   {\n   *     \"error\": {\n   *       \"message\": \"AbortError: The user aborted a request.\",\n   *       \"details\": \"\",\n   *       \"hint\": \"The request was aborted locally via the provided AbortSignal.\",\n   *       \"code\": \"\"\n   *     },\n   *     \"status\": 0,\n   *     \"statusText\": \"\"\n   *   }\n   *\n   * ```\n   *\n   * @example Set a timeout\n   * ```ts\n   * const { data, error } = await supabase\n   *   .from('very_big_table')\n   *   .select()\n   *   .abortSignal(AbortSignal.timeout(1000 /* ms *\\/))\n   * ```\n   *\n   * @exampleResponse Set a timeout\n   * ```json\n   *   {\n   *     \"error\": {\n   *       \"message\": \"FetchError: The user aborted a request.\",\n   *       \"details\": \"\",\n   *       \"hint\": \"\",\n   *       \"code\": \"\"\n   *     },\n   *     \"status\": 0,\n   *     \"statusText\": \"\"\n   *   }\n   *\n   * ```\n   */\n  abortSignal(signal: AbortSignal): this {\n    this.signal = signal\n    return this\n  }\n\n  /**\n   * Return `data` as a single object instead of an array of objects.\n   *\n   * Query result must be one row (e.g. using `.limit(1)`), otherwise this\n   * returns an error.\n   *\n   * @category Database\n   * @subcategory Using modifiers\n   *\n   * @example With `select()`\n   * ```ts\n   * const { data, error } = await supabase\n   *   .from('characters')\n   *   .select('name')\n   *   .limit(1)\n   *   .single()\n   * ```\n   *\n   * @exampleSql With `select()`\n   * ```sql\n   * create table\n   *   characters (id int8 primary key, name text);\n   *\n   * insert into\n   *   characters (id, name)\n   * values\n   *   (1, 'Luke'),\n   *   (2, 'Leia'),\n   *   (3, 'Han');\n   * ```\n   *\n   * @exampleResponse With `select()`\n   * ```json\n   * {\n   *   \"data\": {\n   *     \"name\": \"Luke\"\n   *   },\n   *   \"status\": 200,\n   *   \"statusText\": \"OK\"\n   * }\n   * ```\n   */\n  single<ResultOne = Result extends (infer ResultOne)[] ? ResultOne : never>(): PostgrestBuilder<\n    ClientOptions,\n    ResultOne,\n    ThrowOnError\n  > {\n    this.headers.set('Accept', 'application/vnd.pgrst.object+json')\n    return this as unknown as PostgrestBuilder<ClientOptions, ResultOne, ThrowOnError>\n  }\n\n  /**\n   * Return `data` as a single object instead of an array of objects.\n   *\n   * Query result must be zero or one row (e.g. using `.limit(1)`), otherwise\n   * this returns an error.\n   *\n   * @category Database\n   * @subcategory Using modifiers\n   *\n   * @example With `select()`\n   * ```ts\n   * const { data, error } = await supabase\n   *   .from('characters')\n   *   .select()\n   *   .eq('name', 'Katniss')\n   *   .maybeSingle()\n   * ```\n   *\n   * @exampleSql With `select()`\n   * ```sql\n   * create table\n   *   characters (id int8 primary key, name text);\n   *\n   * insert into\n   *   characters (id, name)\n   * values\n   *   (1, 'Luke'),\n   *   (2, 'Leia'),\n   *   (3, 'Han');\n   * ```\n   *\n   * @exampleResponse With `select()`\n   * ```json\n   * {\n   *   \"status\": 200,\n   *   \"statusText\": \"OK\"\n   * }\n   * ```\n   */\n  maybeSingle<\n    ResultOne = Result extends (infer ResultOne)[] ? ResultOne : never,\n  >(): PostgrestBuilder<ClientOptions, ResultOne | null, ThrowOnError> {\n    // No Accept header override — we fetch as a list and enforce cardinality client-side.\n    // Fixes https://github.com/supabase/postgrest-js/issues/361 for all request methods.\n    this.isMaybeSingle = true\n    return this as unknown as PostgrestBuilder<ClientOptions, ResultOne | null, ThrowOnError>\n  }\n\n  /**\n   * Return `data` as a string in CSV format.\n   *\n   * @category Database\n   * @subcategory Using modifiers\n   *\n   * @exampleDescription Return data as CSV\n   * By default, the data is returned in JSON format, but can also be returned as Comma Separated Values.\n   *\n   * @example Return data as CSV\n   * ```ts\n   * const { data, error } = await supabase\n   *   .from('characters')\n   *   .select()\n   *   .csv()\n   * ```\n   *\n   * @exampleSql Return data as CSV\n   * ```sql\n   * create table\n   *   characters (id int8 primary key, name text);\n   *\n   * insert into\n   *   characters (id, name)\n   * values\n   *   (1, 'Luke'),\n   *   (2, 'Leia'),\n   *   (3, 'Han');\n   * ```\n   *\n   * @exampleResponse Return data as CSV\n   * ```json\n   * {\n   *   \"data\": \"id,name\\n1,Luke\\n2,Leia\\n3,Han\",\n   *   \"status\": 200,\n   *   \"statusText\": \"OK\"\n   * }\n   * ```\n   */\n  csv(): PostgrestBuilder<ClientOptions, string, ThrowOnError> {\n    this.headers.set('Accept', 'text/csv')\n    return this as unknown as PostgrestBuilder<ClientOptions, string, ThrowOnError>\n  }\n\n  /**\n   * Return `data` as an object in [GeoJSON](https://geojson.org) format.\n   *\n   * @category Database\n   * @subcategory Using modifiers\n   */\n  geojson(): PostgrestBuilder<ClientOptions, Record<string, unknown>, ThrowOnError> {\n    this.headers.set('Accept', 'application/geo+json')\n    return this as unknown as PostgrestBuilder<ClientOptions, Record<string, unknown>, ThrowOnError>\n  }\n\n  /**\n   * Return `data` as the EXPLAIN plan for the query.\n   *\n   * You need to enable the\n   * [db_plan_enabled](https://supabase.com/docs/guides/database/debugging-performance#enabling-explain)\n   * setting before using this method.\n   *\n   * @param options - Named parameters\n   *\n   * @param options.analyze - If `true`, the query will be executed and the\n   * actual run time will be returned\n   *\n   * @param options.verbose - If `true`, the query identifier will be returned\n   * and `data` will include the output columns of the query\n   *\n   * @param options.settings - If `true`, include information on configuration\n   * parameters that affect query planning\n   *\n   * @param options.buffers - If `true`, include information on buffer usage\n   *\n   * @param options.wal - If `true`, include information on WAL record generation\n   *\n   * @param options.format - The format of the output, can be `\"text\"` (default)\n   * or `\"json\"`\n   *\n   * @category Database\n   * @subcategory Using modifiers\n   *\n   * @exampleDescription Get the execution plan\n   * By default, the data is returned in TEXT format, but can also be returned as JSON by using the `format` parameter.\n   *\n   * @example Get the execution plan\n   * ```ts\n   * const { data, error } = await supabase\n   *   .from('characters')\n   *   .select()\n   *   .explain()\n   * ```\n   *\n   * @exampleSql Get the execution plan\n   * ```sql\n   * create table\n   *   characters (id int8 primary key, name text);\n   *\n   * insert into\n   *   characters (id, name)\n   * values\n   *   (1, 'Luke'),\n   *   (2, 'Leia'),\n   *   (3, 'Han');\n   * ```\n   *\n   * @exampleResponse Get the execution plan\n   * ```js\n   * Aggregate  (cost=33.34..33.36 rows=1 width=112)\n   *   ->  Limit  (cost=0.00..18.33 rows=1000 width=40)\n   *         ->  Seq Scan on characters  (cost=0.00..22.00 rows=1200 width=40)\n   * ```\n   *\n   * @exampleDescription Get the execution plan with analyze and verbose\n   * By default, the data is returned in TEXT format, but can also be returned as JSON by using the `format` parameter.\n   *\n   * @example Get the execution plan with analyze and verbose\n   * ```ts\n   * const { data, error } = await supabase\n   *   .from('characters')\n   *   .select()\n   *   .explain({analyze:true,verbose:true})\n   * ```\n   *\n   * @exampleSql Get the execution plan with analyze and verbose\n   * ```sql\n   * create table\n   *   characters (id int8 primary key, name text);\n   *\n   * insert into\n   *   characters (id, name)\n   * values\n   *   (1, 'Luke'),\n   *   (2, 'Leia'),\n   *   (3, 'Han');\n   * ```\n   *\n   * @exampleResponse Get the execution plan with analyze and verbose\n   * ```js\n   * Aggregate  (cost=33.34..33.36 rows=1 width=112) (actual time=0.041..0.041 rows=1 loops=1)\n   *   Output: NULL::bigint, count(ROW(characters.id, characters.name)), COALESCE(json_agg(ROW(characters.id, characters.name)), '[]'::json), NULLIF(current_setting('response.headers'::text, true), ''::text), NULLIF(current_setting('response.status'::text, true), ''::text)\n   *   ->  Limit  (cost=0.00..18.33 rows=1000 width=40) (actual time=0.005..0.006 rows=3 loops=1)\n   *         Output: characters.id, characters.name\n   *         ->  Seq Scan on public.characters  (cost=0.00..22.00 rows=1200 width=40) (actual time=0.004..0.005 rows=3 loops=1)\n   *               Output: characters.id, characters.name\n   * Query Identifier: -4730654291623321173\n   * Planning Time: 0.407 ms\n   * Execution Time: 0.119 ms\n   * ```\n   */\n  explain({\n    analyze = false,\n    verbose = false,\n    settings = false,\n    buffers = false,\n    wal = false,\n    format = 'text',\n  }: {\n    analyze?: boolean\n    verbose?: boolean\n    settings?: boolean\n    buffers?: boolean\n    wal?: boolean\n    format?: 'json' | 'text'\n  } = {}) {\n    const options = [\n      analyze ? 'analyze' : null,\n      verbose ? 'verbose' : null,\n      settings ? 'settings' : null,\n      buffers ? 'buffers' : null,\n      wal ? 'wal' : null,\n    ]\n      .filter(Boolean)\n      .join('|')\n    // An Accept header can carry multiple media types but postgrest-js always sends one\n    const forMediatype = this.headers.get('Accept') ?? 'application/json'\n    this.headers.set(\n      'Accept',\n      `application/vnd.pgrst.plan+${format}; for=\"${forMediatype}\"; options=${options};`\n    )\n    if (format === 'json') {\n      return this as unknown as PostgrestBuilder<\n        ClientOptions,\n        Record<string, unknown>[],\n        ThrowOnError\n      >\n    } else {\n      return this as unknown as PostgrestBuilder<ClientOptions, string, ThrowOnError>\n    }\n  }\n\n  /**\n   * Dry-run this request: execute the query but discard the changes.\n   *\n   * Server-side, PostgREST runs the query inside a transaction and rolls it back\n   * instead of committing. The response still contains the data that *would* have\n   * been returned — `RETURNING` clauses execute and RLS, triggers, and constraints\n   * are all evaluated — but no row is actually inserted, updated, or deleted.\n   *\n   * This affects only the single request it is chained to. The JS caller has no\n   * handle on the transaction: supabase-js does not group multiple queries into\n   * one transaction. For multi-statement transactional logic, use a database\n   * function (`supabase.rpc(...)`).\n   *\n   * Sets the `Prefer: tx=rollback` header. See PostgREST's docs on transaction\n   * preferences for the underlying mechanism.\n   *\n   * @category Database\n   * @subcategory Using modifiers\n   *\n   * @example Validate an insert without persisting\n   * ```ts\n   * const { data, error } = await supabase\n   *   .from('countries')\n   *   .insert({ name: 'France' })\n   *   .select()\n   *   .rollback()\n   * // `data` shows what would have been inserted; nothing is saved.\n   * ```\n   */\n  rollback(): this {\n    this.headers.append('Prefer', 'tx=rollback')\n    return this\n  }\n\n  /**\n   * Override the type of the returned `data`.\n   *\n   * @typeParam NewResult - The new result type to override with\n   * @deprecated Use overrideTypes<yourType, { merge: false }>() method at the end of your call chain instead\n   *\n   * @category Database\n   * @subcategory Using modifiers\n   *\n   * @remarks\n   * - Deprecated: use overrideTypes method instead\n   *\n   * @example Override type of successful response\n   * ```ts\n   * const { data } = await supabase\n   *   .from('countries')\n   *   .select()\n   *   .returns<Array<MyType>>()\n   * ```\n   *\n   * @exampleResponse Override type of successful response\n   * ```js\n   * let x: typeof data // MyType[]\n   * ```\n   *\n   * @example Override type of object response\n   * ```ts\n   * const { data } = await supabase\n   *   .from('countries')\n   *   .select()\n   *   .maybeSingle()\n   *   .returns<MyType>()\n   * ```\n   *\n   * @exampleResponse Override type of object response\n   * ```js\n   * let x: typeof data // MyType | null\n   * ```\n   */\n  returns<NewResult>(): PostgrestTransformBuilder<\n    ClientOptions,\n    Schema,\n    Row,\n    CheckMatchingArrayTypes<Result, NewResult>,\n    RelationName,\n    Relationships,\n    Method,\n    ThrowOnError\n  > {\n    return this as unknown as PostgrestTransformBuilder<\n      ClientOptions,\n      Schema,\n      Row,\n      CheckMatchingArrayTypes<Result, NewResult>,\n      RelationName,\n      Relationships,\n      Method,\n      ThrowOnError\n    >\n  }\n\n  /**\n   * Set the maximum number of rows that can be affected by the query.\n   * Only available in PostgREST v13+ and only works with PATCH and DELETE methods.\n   *\n   * @param rows - The maximum number of rows that can be affected\n   *\n   * @category Database\n   * @subcategory Using modifiers\n   */\n  maxAffected(rows: number): MaxAffectedEnabled<ClientOptions['PostgrestVersion']> extends true\n    ? // TODO: update the RPC case to only work on RPC that returns SETOF rows\n      Method extends 'PATCH' | 'DELETE' | 'RPC'\n      ? this\n      : InvalidMethodError<'maxAffected method only available on update or delete'>\n    : InvalidMethodError<'maxAffected method only available on postgrest 13+'> {\n    this.headers.append('Prefer', 'handling=strict')\n    this.headers.append('Prefer', `max-affected=${rows}`)\n    return this as unknown as MaxAffectedEnabled<ClientOptions['PostgrestVersion']> extends true\n      ? Method extends 'PATCH' | 'DELETE' | 'RPC'\n        ? this\n        : InvalidMethodError<'maxAffected method only available on update or delete'>\n      : InvalidMethodError<'maxAffected method only available on postgrest 13+'>\n  }\n}\n", "import PostgrestTransformBuilder from './PostgrestTransformBuilder'\nimport { JsonPathToAccessor, JsonPathToType } from './select-query-parser/utils'\nimport { ClientServerOptions, GenericSchema } from './types/common/common'\n\ntype FilterOperator =\n  | 'eq'\n  | 'neq'\n  | 'gt'\n  | 'gte'\n  | 'lt'\n  | 'lte'\n  | 'like'\n  | 'ilike'\n  | 'is'\n  | 'isdistinct'\n  | 'in'\n  | 'cs'\n  | 'cd'\n  | 'sl'\n  | 'sr'\n  | 'nxl'\n  | 'nxr'\n  | 'adj'\n  | 'ov'\n  | 'fts'\n  | 'plfts'\n  | 'phfts'\n  | 'wfts'\n  | 'match'\n  | 'imatch'\n\nexport type IsStringOperator<Path extends string> = Path extends `${string}->>${string}`\n  ? true\n  : false\n\nconst PostgrestReservedCharsRegexp = new RegExp('[,()]')\n\n// Match relationship filters with `table.column` syntax and resolve underlying\n// column value. If not matched, fallback to generic type.\n// TODO: Validate the relationship itself ala select-query-parser. Currently we\n// assume that all tables have valid relationships to each other, despite\n// nonexistent foreign keys.\ntype ResolveFilterValue<\n  Schema extends GenericSchema,\n  Row extends Record<string, unknown>,\n  ColumnName extends string,\n> = ColumnName extends `${infer RelationshipTable}.${infer Remainder}`\n  ? Remainder extends `${infer _}.${infer _}`\n    ? ResolveFilterValue<Schema, Row, Remainder>\n    : ResolveFilterRelationshipValue<Schema, RelationshipTable, Remainder>\n  : ColumnName extends keyof Row\n    ? Row[ColumnName]\n    : // If the column selection is a jsonpath like `data->value` or `data->>value` we attempt to match\n      // the expected type with the parsed custom json type\n      IsStringOperator<ColumnName> extends true\n      ? string\n      : JsonPathToType<Row, JsonPathToAccessor<ColumnName>> extends infer JsonPathValue\n        ? JsonPathValue extends never\n          ? never\n          : JsonPathValue\n        : never\n\ntype ResolveFilterRelationshipValue<\n  Schema extends GenericSchema,\n  RelationshipTable extends string,\n  RelationshipColumn extends string,\n> = Schema['Tables'] & Schema['Views'] extends infer TablesAndViews\n  ? RelationshipTable extends keyof TablesAndViews\n    ? 'Row' extends keyof TablesAndViews[RelationshipTable]\n      ? RelationshipColumn extends keyof TablesAndViews[RelationshipTable]['Row']\n        ? TablesAndViews[RelationshipTable]['Row'][RelationshipColumn]\n        : unknown\n      : unknown\n    : unknown\n  : never\n\nexport type InvalidMethodError<S extends string> = { Error: S }\n\ntype NonNullableColumn<T extends Record<string, unknown>, Col extends string> = Col extends keyof T\n  ? { [K in keyof T]: K extends Col ? NonNullable<T[K]> : T[K] }\n  : T\n\ntype NarrowResultColumn<T, Col extends string> = T extends (infer Item)[]\n  ? Item extends Record<string, unknown>\n    ? Col extends keyof Item\n      ? { [K in keyof Item]: K extends Col ? NonNullable<Item[K]> : Item[K] }[]\n      : T\n    : T\n  : T extends Record<string, unknown>\n    ? Col extends keyof T\n      ? { [K in keyof T]: K extends Col ? NonNullable<T[K]> : T[K] }\n      : T\n    : T\n\nexport default class PostgrestFilterBuilder<\n  ClientOptions extends ClientServerOptions,\n  Schema extends GenericSchema,\n  Row extends Record<string, unknown>,\n  Result,\n  RelationName = unknown,\n  Relationships = unknown,\n  Method = unknown,\n  ThrowOnError extends boolean = false,\n> extends PostgrestTransformBuilder<\n  ClientOptions,\n  Schema,\n  Row,\n  Result,\n  RelationName,\n  Relationships,\n  Method,\n  ThrowOnError\n> {\n  throwOnError(): PostgrestFilterBuilder<\n    ClientOptions,\n    Schema,\n    Row,\n    Result,\n    RelationName,\n    Relationships,\n    Method,\n    true\n  > {\n    return super.throwOnError() as PostgrestFilterBuilder<\n      ClientOptions,\n      Schema,\n      Row,\n      Result,\n      RelationName,\n      Relationships,\n      Method,\n      true\n    >\n  }\n\n  /**\n   * Match only rows where `column` is equal to `value`.\n   *\n   * To check if the value of `column` is NULL, you should use `.is()` instead.\n   *\n   * @param column - The column to filter on\n   * @param value - The value to filter with\n   *\n   * @category Database\n   * @subcategory Using filters\n   *\n   * @example With `select()`\n   * ```ts\n   * const { data, error } = await supabase\n   *   .from('characters')\n   *   .select()\n   *   .eq('name', 'Leia')\n   * ```\n   *\n   * @exampleSql With `select()`\n   * ```sql\n   * create table\n   *   characters (id int8 primary key, name text);\n   *\n   * insert into\n   *   characters (id, name)\n   * values\n   *   (1, 'Luke'),\n   *   (2, 'Leia'),\n   *   (3, 'Han');\n   * ```\n   *\n   * @exampleResponse With `select()`\n   * ```json\n   * {\n   *   \"data\": [\n   *     {\n   *       \"id\": 2,\n   *       \"name\": \"Leia\"\n   *     }\n   *   ],\n   *   \"status\": 200,\n   *   \"statusText\": \"OK\"\n   * }\n   * ```\n   */\n  eq<ColumnName extends string>(\n    column: ColumnName extends keyof Row\n      ? ColumnName\n      : ColumnName extends `${string}.${string}` | `${string}->${string}`\n        ? ColumnName\n        : string extends ColumnName\n          ? string\n          : keyof Row,\n    value: ResolveFilterValue<Schema, Row, ColumnName> extends never\n      ? NonNullable<unknown>\n      : ResolveFilterValue<Schema, Row, ColumnName> extends infer ResolvedFilterValue\n        ? NonNullable<ResolvedFilterValue>\n        : never\n  ): this {\n    this.url.searchParams.append(column as string, `eq.${value}`)\n    return this\n  }\n\n  /**\n   * Match only rows where `column` is not equal to `value`.\n   *\n   * This filter does not include rows where `column` is `NULL`. To match null\n   * values, use `.is(column, null)` instead.\n   *\n   * @param column - The column to filter on\n   * @param value - The value to filter with\n   *\n   * @category Database\n   * @subcategory Using filters\n   *\n   * @example With `select()`\n   * ```ts\n   * const { data, error } = await supabase\n   *   .from('characters')\n   *   .select()\n   *   .neq('name', 'Leia')\n   * ```\n   *\n   * @exampleSql With `select()`\n   * ```sql\n   * create table\n   *   characters (id int8 primary key, name text);\n   *\n   * insert into\n   *   characters (id, name)\n   * values\n   *   (1, 'Luke'),\n   *   (2, 'Leia'),\n   *   (3, 'Han');\n   * ```\n   *\n   * @exampleResponse With `select()`\n   * ```json\n   * {\n   *   \"data\": [\n   *     {\n   *       \"id\": 1,\n   *       \"name\": \"Luke\"\n   *     },\n   *     {\n   *       \"id\": 3,\n   *       \"name\": \"Han\"\n   *     }\n   *   ],\n   *   \"status\": 200,\n   *   \"statusText\": \"OK\"\n   * }\n   * ```\n   */\n  neq<ColumnName extends string>(\n    column: ColumnName extends keyof Row\n      ? ColumnName\n      : ColumnName extends `${string}.${string}` | `${string}->${string}`\n        ? ColumnName\n        : string extends ColumnName\n          ? string\n          : keyof Row,\n    value: ResolveFilterValue<Schema, Row, ColumnName> extends never\n      ? unknown\n      : ResolveFilterValue<Schema, Row, ColumnName> extends infer Resolved\n        ? Resolved\n        : never\n  ): this {\n    this.url.searchParams.append(column as string, `neq.${value}`)\n    return this\n  }\n\n  /**\n   * Match only rows where `column` is greater than `value`.\n   *\n   * @param column - The column to filter on\n   * @param value - The value to filter with\n   *\n   * @category Database\n   * @subcategory Using filters\n   *\n   * @exampleDescription With `select()`\n   * When using [reserved words](https://www.postgresql.org/docs/current/sql-keywords-appendix.html) for column names you need\n   * to add double quotes e.g. `.gt('\"order\"', 2)`\n   *\n   * @example With `select()`\n   * ```ts\n   * const { data, error } = await supabase\n   *   .from('characters')\n   *   .select()\n   *   .gt('id', 2)\n   * ```\n   *\n   * @exampleSql With `select()`\n   * ```sql\n   * create table\n   *   characters (id int8 primary key, name text);\n   *\n   * insert into\n   *   characters (id, name)\n   * values\n   *   (1, 'Luke'),\n   *   (2, 'Leia'),\n   *   (3, 'Han');\n   * ```\n   *\n   * @exampleResponse With `select()`\n   * ```json\n   * {\n   *   \"data\": [\n   *     {\n   *       \"id\": 3,\n   *       \"name\": \"Han\"\n   *     }\n   *   ],\n   *   \"status\": 200,\n   *   \"statusText\": \"OK\"\n   * }\n   * ```\n   */\n  gt<ColumnName extends string & keyof Row>(column: ColumnName, value: Row[ColumnName]): this\n  gt(column: string, value: unknown): this\n  gt(column: string, value: unknown): this {\n    this.url.searchParams.append(column, `gt.${value}`)\n    return this\n  }\n\n  /**\n   * Match only rows where `column` is greater than or equal to `value`.\n   *\n   * @param column - The column to filter on\n   * @param value - The value to filter with\n   *\n   * @category Database\n   * @subcategory Using filters\n   *\n   * @example With `select()`\n   * ```ts\n   * const { data, error } = await supabase\n   *   .from('characters')\n   *   .select()\n   *   .gte('id', 2)\n   * ```\n   *\n   * @exampleSql With `select()`\n   * ```sql\n   * create table\n   *   characters (id int8 primary key, name text);\n   *\n   * insert into\n   *   characters (id, name)\n   * values\n   *   (1, 'Luke'),\n   *   (2, 'Leia'),\n   *   (3, 'Han');\n   * ```\n   *\n   * @exampleResponse With `select()`\n   * ```json\n   * {\n   *   \"data\": [\n   *     {\n   *       \"id\": 2,\n   *       \"name\": \"Leia\"\n   *     },\n   *     {\n   *       \"id\": 3,\n   *       \"name\": \"Han\"\n   *     }\n   *   ],\n   *   \"status\": 200,\n   *   \"statusText\": \"OK\"\n   * }\n   * ```\n   */\n  gte<ColumnName extends string & keyof Row>(column: ColumnName, value: Row[ColumnName]): this\n  gte(column: string, value: unknown): this\n  gte(column: string, value: unknown): this {\n    this.url.searchParams.append(column, `gte.${value}`)\n    return this\n  }\n\n  /**\n   * Match only rows where `column` is less than `value`.\n   *\n   * @param column - The column to filter on\n   * @param value - The value to filter with\n   *\n   * @category Database\n   * @subcategory Using filters\n   *\n   * @example With `select()`\n   * ```ts\n   * const { data, error } = await supabase\n   *   .from('characters')\n   *   .select()\n   *   .lt('id', 2)\n   * ```\n   *\n   * @exampleSql With `select()`\n   * ```sql\n   * create table\n   *   characters (id int8 primary key, name text);\n   *\n   * insert into\n   *   characters (id, name)\n   * values\n   *   (1, 'Luke'),\n   *   (2, 'Leia'),\n   *   (3, 'Han');\n   * ```\n   *\n   * @exampleResponse With `select()`\n   * ```json\n   * {\n   *   \"data\": [\n   *     {\n   *       \"id\": 1,\n   *       \"name\": \"Luke\"\n   *     }\n   *   ],\n   *   \"status\": 200,\n   *   \"statusText\": \"OK\"\n   * }\n   * ```\n   */\n  lt<ColumnName extends string & keyof Row>(column: ColumnName, value: Row[ColumnName]): this\n  lt(column: string, value: unknown): this\n  lt(column: string, value: unknown): this {\n    this.url.searchParams.append(column, `lt.${value}`)\n    return this\n  }\n\n  /**\n   * Match only rows where `column` is less than or equal to `value`.\n   *\n   * @param column - The column to filter on\n   * @param value - The value to filter with\n   *\n   * @category Database\n   * @subcategory Using filters\n   *\n   * @example With `select()`\n   * ```ts\n   * const { data, error } = await supabase\n   *   .from('characters')\n   *   .select()\n   *   .lte('id', 2)\n   * ```\n   *\n   * @exampleSql With `select()`\n   * ```sql\n   * create table\n   *   characters (id int8 primary key, name text);\n   *\n   * insert into\n   *   characters (id, name)\n   * values\n   *   (1, 'Luke'),\n   *   (2, 'Leia'),\n   *   (3, 'Han');\n   * ```\n   *\n   * @exampleResponse With `select()`\n   * ```json\n   * {\n   *   \"data\": [\n   *     {\n   *       \"id\": 1,\n   *       \"name\": \"Luke\"\n   *     },\n   *     {\n   *       \"id\": 2,\n   *       \"name\": \"Leia\"\n   *     }\n   *   ],\n   *   \"status\": 200,\n   *   \"statusText\": \"OK\"\n   * }\n   * ```\n   */\n  lte<ColumnName extends string & keyof Row>(column: ColumnName, value: Row[ColumnName]): this\n  lte(column: string, value: unknown): this\n  lte(column: string, value: unknown): this {\n    this.url.searchParams.append(column, `lte.${value}`)\n    return this\n  }\n\n  /**\n   * Match only rows where `column` matches `pattern` case-sensitively.\n   *\n   * @param column - The column to filter on\n   * @param pattern - The pattern to match with\n   *\n   * @category Database\n   * @subcategory Using filters\n   *\n   * @example With `select()`\n   * ```ts\n   * const { data, error } = await supabase\n   *   .from('characters')\n   *   .select()\n   *   .like('name', '%Lu%')\n   * ```\n   *\n   * @exampleSql With `select()`\n   * ```sql\n   * create table\n   *   characters (id int8 primary key, name text);\n   *\n   * insert into\n   *   characters (id, name)\n   * values\n   *   (1, 'Luke'),\n   *   (2, 'Leia'),\n   *   (3, 'Han');\n   * ```\n   *\n   * @exampleResponse With `select()`\n   * ```json\n   * {\n   *   \"data\": [\n   *     {\n   *       \"id\": 1,\n   *       \"name\": \"Luke\"\n   *     }\n   *   ],\n   *   \"status\": 200,\n   *   \"statusText\": \"OK\"\n   * }\n   * ```\n   */\n  like<ColumnName extends string & keyof Row>(column: ColumnName, pattern: string): this\n  like(column: string, pattern: string): this\n  like(column: string, pattern: string): this {\n    this.url.searchParams.append(column, `like.${pattern}`)\n    return this\n  }\n\n  /**\n   * Match only rows where `column` matches all of `patterns` case-sensitively.\n   *\n   * @param column - The column to filter on\n   * @param patterns - The patterns to match with\n   *\n   * @category Database\n   * @subcategory Using filters\n   */\n  likeAllOf<ColumnName extends string & keyof Row>(\n    column: ColumnName,\n    patterns: readonly string[]\n  ): this\n  likeAllOf(column: string, patterns: readonly string[]): this\n  likeAllOf(column: string, patterns: readonly string[]): this {\n    this.url.searchParams.append(column, `like(all).{${patterns.join(',')}}`)\n    return this\n  }\n\n  /**\n   * Match only rows where `column` matches any of `patterns` case-sensitively.\n   *\n   * @param column - The column to filter on\n   * @param patterns - The patterns to match with\n   *\n   * @category Database\n   * @subcategory Using filters\n   */\n  likeAnyOf<ColumnName extends string & keyof Row>(\n    column: ColumnName,\n    patterns: readonly string[]\n  ): this\n  likeAnyOf(column: string, patterns: readonly string[]): this\n  likeAnyOf(column: string, patterns: readonly string[]): this {\n    this.url.searchParams.append(column, `like(any).{${patterns.join(',')}}`)\n    return this\n  }\n\n  /**\n   * Match only rows where `column` matches `pattern` case-insensitively.\n   *\n   * @param column - The column to filter on\n   * @param pattern - The pattern to match with\n   *\n   * @category Database\n   * @subcategory Using filters\n   *\n   * @example With `select()`\n   * ```ts\n   * const { data, error } = await supabase\n   *   .from('characters')\n   *   .select()\n   *   .ilike('name', '%lu%')\n   * ```\n   *\n   * @exampleSql With `select()`\n   * ```sql\n   * create table\n   *   characters (id int8 primary key, name text);\n   *\n   * insert into\n   *   characters (id, name)\n   * values\n   *   (1, 'Luke'),\n   *   (2, 'Leia'),\n   *   (3, 'Han');\n   * ```\n   *\n   * @exampleResponse With `select()`\n   * ```json\n   * {\n   *   \"data\": [\n   *     {\n   *       \"id\": 1,\n   *       \"name\": \"Luke\"\n   *     }\n   *   ],\n   *   \"status\": 200,\n   *   \"statusText\": \"OK\"\n   * }\n   * ```\n   */\n  ilike<ColumnName extends string & keyof Row>(column: ColumnName, pattern: string): this\n  ilike(column: string, pattern: string): this\n  ilike(column: string, pattern: string): this {\n    this.url.searchParams.append(column, `ilike.${pattern}`)\n    return this\n  }\n\n  /**\n   * Match only rows where `column` matches all of `patterns` case-insensitively.\n   *\n   * @param column - The column to filter on\n   * @param patterns - The patterns to match with\n   *\n   * @category Database\n   * @subcategory Using filters\n   */\n  ilikeAllOf<ColumnName extends string & keyof Row>(\n    column: ColumnName,\n    patterns: readonly string[]\n  ): this\n  ilikeAllOf(column: string, patterns: readonly string[]): this\n  ilikeAllOf(column: string, patterns: readonly string[]): this {\n    this.url.searchParams.append(column, `ilike(all).{${patterns.join(',')}}`)\n    return this\n  }\n\n  /**\n   * Match only rows where `column` matches any of `patterns` case-insensitively.\n   *\n   * @param column - The column to filter on\n   * @param patterns - The patterns to match with\n   *\n   * @category Database\n   * @subcategory Using filters\n   */\n  ilikeAnyOf<ColumnName extends string & keyof Row>(\n    column: ColumnName,\n    patterns: readonly string[]\n  ): this\n  ilikeAnyOf(column: string, patterns: readonly string[]): this\n  ilikeAnyOf(column: string, patterns: readonly string[]): this {\n    this.url.searchParams.append(column, `ilike(any).{${patterns.join(',')}}`)\n    return this\n  }\n\n  /**\n   * Match only rows where `column` matches the PostgreSQL regex `pattern`\n   * case-sensitively (using the `~` operator).\n   *\n   * @param column - The column to filter on\n   * @param pattern - The PostgreSQL regular expression pattern to match with\n   */\n  regexMatch<ColumnName extends string & keyof Row>(column: ColumnName, pattern: string): this\n  regexMatch(column: string, pattern: string): this\n  regexMatch(column: string, pattern: string): this {\n    this.url.searchParams.append(column, `match.${pattern}`)\n    return this\n  }\n\n  /**\n   * Match only rows where `column` matches the PostgreSQL regex `pattern`\n   * case-insensitively (using the `~*` operator).\n   *\n   * @param column - The column to filter on\n   * @param pattern - The PostgreSQL regular expression pattern to match with\n   */\n  regexIMatch<ColumnName extends string & keyof Row>(column: ColumnName, pattern: string): this\n  regexIMatch(column: string, pattern: string): this\n  regexIMatch(column: string, pattern: string): this {\n    this.url.searchParams.append(column, `imatch.${pattern}`)\n    return this\n  }\n\n  /**\n   * Match only rows where `column` IS `value`.\n   *\n   * For non-boolean columns, this is only relevant for checking if the value of\n   * `column` is NULL by setting `value` to `null`.\n   *\n   * For boolean columns, you can also set `value` to `true` or `false` and it\n   * will behave the same way as `.eq()`.\n   *\n   * @param column - The column to filter on\n   * @param value - The value to filter with\n   *\n   * @category Database\n   * @subcategory Using filters\n   *\n   * @exampleDescription Checking for nullness, true or false\n   * Using the `eq()` filter doesn't work when filtering for `null`.\n   *\n   * Instead, you need to use `is()`.\n   *\n   * @example Checking for nullness, true or false\n   * ```ts\n   * const { data, error } = await supabase\n   *   .from('countries')\n   *   .select()\n   *   .is('name', null)\n   * ```\n   *\n   * @exampleSql Checking for nullness, true or false\n   * ```sql\n   * create table\n   *   countries (id int8 primary key, name text);\n   *\n   * insert into\n   *   countries (id, name)\n   * values\n   *   (1, 'null'),\n   *   (2, null);\n   * ```\n   *\n   * @exampleResponse Checking for nullness, true or false\n   * ```json\n   * {\n   *   \"data\": [\n   *     {\n   *       \"id\": 2,\n   *       \"name\": \"null\"\n   *     }\n   *   ],\n   *   \"status\": 200,\n   *   \"statusText\": \"OK\"\n   * }\n   * ```\n   */\n  is<ColumnName extends string & keyof Row>(\n    column: ColumnName,\n    value: Row[ColumnName] & (boolean | null)\n  ): this\n  is(column: string, value: boolean | null): this\n  is(column: string, value: boolean | null): this {\n    this.url.searchParams.append(column, `is.${value}`)\n    return this\n  }\n\n  /**\n   * Match only rows where `column` IS DISTINCT FROM `value`.\n   *\n   * Unlike `.neq()`, this treats `NULL` as a comparable value. Two `NULL` values\n   * are considered equal (not distinct), and comparing `NULL` with any non-NULL\n   * value returns true (distinct).\n   *\n   * @param column - The column to filter on\n   * @param value - The value to filter with\n   */\n  isDistinct<ColumnName extends string>(\n    column: ColumnName,\n    value: ResolveFilterValue<Schema, Row, ColumnName> extends never\n      ? unknown\n      : ResolveFilterValue<Schema, Row, ColumnName> extends infer ResolvedFilterValue\n        ? ResolvedFilterValue\n        : never\n  ): this {\n    this.url.searchParams.append(column, `isdistinct.${value}`)\n    return this\n  }\n\n  /**\n   * Match only rows where `column` is included in the `values` array.\n   *\n   * @param column - The column to filter on\n   * @param values - The values array to filter with\n   *\n   * @category Database\n   * @subcategory Using filters\n   *\n   * @example With `select()`\n   * ```ts\n   * const { data, error } = await supabase\n   *   .from('characters')\n   *   .select()\n   *   .in('name', ['Leia', 'Han'])\n   * ```\n   *\n   * @exampleSql With `select()`\n   * ```sql\n   * create table\n   *   characters (id int8 primary key, name text);\n   *\n   * insert into\n   *   characters (id, name)\n   * values\n   *   (1, 'Luke'),\n   *   (2, 'Leia'),\n   *   (3, 'Han');\n   * ```\n   *\n   * @exampleResponse With `select()`\n   * ```json\n   * {\n   *   \"data\": [\n   *     {\n   *       \"id\": 2,\n   *       \"name\": \"Leia\"\n   *     },\n   *     {\n   *       \"id\": 3,\n   *       \"name\": \"Han\"\n   *     }\n   *   ],\n   *   \"status\": 200,\n   *   \"statusText\": \"OK\"\n   * }\n   * ```\n   */\n  in<ColumnName extends string>(\n    column: ColumnName,\n    values: ReadonlyArray<\n      ResolveFilterValue<Schema, Row, ColumnName> extends never\n        ? unknown\n        : // We want to infer the type before wrapping it into a `NonNullable` to avoid too deep\n          // type resolution error\n          ResolveFilterValue<Schema, Row, ColumnName> extends infer ResolvedFilterValue\n          ? ResolvedFilterValue\n          : // We should never enter this case as all the branches are covered above\n            never\n    >\n  ): this {\n    const cleanedValues = Array.from(new Set(values))\n      .map((s) => {\n        // handle postgrest reserved characters\n        // https://postgrest.org/en/v7.0.0/api.html#reserved-characters\n        if (typeof s === 'string' && PostgrestReservedCharsRegexp.test(s)) return `\"${s}\"`\n        else return `${s}`\n      })\n      .join(',')\n    this.url.searchParams.append(column, `in.(${cleanedValues})`)\n    return this\n  }\n\n  /**\n   * Match only rows where `column` is NOT included in the `values` array.\n   *\n   * @param column - The column to filter on\n   * @param values - The values array to filter with\n   */\n  notIn<ColumnName extends string>(\n    column: ColumnName,\n    values: ReadonlyArray<\n      ResolveFilterValue<Schema, Row, ColumnName> extends never\n        ? unknown\n        : ResolveFilterValue<Schema, Row, ColumnName> extends infer ResolvedFilterValue\n          ? ResolvedFilterValue\n          : never\n    >\n  ): this {\n    const cleanedValues = Array.from(new Set(values))\n      .map((s) => {\n        // handle postgrest reserved characters\n        // https://postgrest.org/en/v7.0.0/api.html#reserved-characters\n        if (typeof s === 'string' && PostgrestReservedCharsRegexp.test(s)) return `\"${s}\"`\n        else return `${s}`\n      })\n      .join(',')\n    this.url.searchParams.append(column, `not.in.(${cleanedValues})`)\n    return this\n  }\n\n  /**\n   * Only relevant for jsonb, array, and range columns. Match only rows where\n   * `column` contains every element appearing in `value`.\n   *\n   * @param column - The jsonb, array, or range column to filter on\n   * @param value - The jsonb, array, or range value to filter with\n   *\n   * @category Database\n   * @subcategory Using filters\n   *\n   * @example On array columns\n   * ```ts\n   * const { data, error } = await supabase\n   *   .from('issues')\n   *   .select()\n   *   .contains('tags', ['is:open', 'priority:low'])\n   * ```\n   *\n   * @exampleSql On array columns\n   * ```sql\n   * create table\n   *   issues (\n   *     id int8 primary key,\n   *     title text,\n   *     tags text[]\n   *   );\n   *\n   * insert into\n   *   issues (id, title, tags)\n   * values\n   *   (1, 'Cache invalidation is not working', array['is:open', 'severity:high', 'priority:low']),\n   *   (2, 'Use better names', array['is:open', 'severity:low', 'priority:medium']);\n   * ```\n   *\n   * @exampleResponse On array columns\n   * ```json\n   * {\n   *   \"data\": [\n   *     {\n   *       \"title\": \"Cache invalidation is not working\"\n   *     }\n   *   ],\n   *   \"status\": 200,\n   *   \"statusText\": \"OK\"\n   * }\n   * ```\n   *\n   * @exampleDescription On range columns\n   * Postgres supports a number of [range\n   * types](https://www.postgresql.org/docs/current/rangetypes.html). You\n   * can filter on range columns using the string representation of range\n   * values.\n   *\n   * @example On range columns\n   * ```ts\n   * const { data, error } = await supabase\n   *   .from('reservations')\n   *   .select()\n   *   .contains('during', '[2000-01-01 13:00, 2000-01-01 13:30)')\n   * ```\n   *\n   * @exampleSql On range columns\n   * ```sql\n   * create table\n   *   reservations (\n   *     id int8 primary key,\n   *     room_name text,\n   *     during tsrange\n   *   );\n   *\n   * insert into\n   *   reservations (id, room_name, during)\n   * values\n   *   (1, 'Emerald', '[2000-01-01 13:00, 2000-01-01 15:00)'),\n   *   (2, 'Topaz', '[2000-01-02 09:00, 2000-01-02 10:00)');\n   * ```\n   *\n   * @exampleResponse On range columns\n   * ```json\n   * {\n   *   \"data\": [\n   *     {\n   *       \"id\": 1,\n   *       \"room_name\": \"Emerald\",\n   *       \"during\": \"[\\\"2000-01-01 13:00:00\\\",\\\"2000-01-01 15:00:00\\\")\"\n   *     }\n   *   ],\n   *   \"status\": 200,\n   *   \"statusText\": \"OK\"\n   * }\n   * ```\n   *\n   * @example On `jsonb` columns\n   * ```ts\n   * const { data, error } = await supabase\n   *   .from('users')\n   *   .select('name')\n   *   .contains('address', { postcode: 90210 })\n   * ```\n   *\n   * @exampleSql On `jsonb` columns\n   * ```sql\n   * create table\n   *   users (\n   *     id int8 primary key,\n   *     name text,\n   *     address jsonb\n   *   );\n   *\n   * insert into\n   *   users (id, name, address)\n   * values\n   *   (1, 'Michael', '{ \"postcode\": 90210, \"street\": \"Melrose Place\" }'),\n   *   (2, 'Jane', '{}');\n   * ```\n   *\n   * @exampleResponse On `jsonb` columns\n   * ```json\n   * {\n   *   \"data\": [\n   *     {\n   *       \"name\": \"Michael\"\n   *     }\n   *   ],\n   *   \"status\": 200,\n   *   \"statusText\": \"OK\"\n   * }\n   * ```\n   */\n  contains<ColumnName extends string & keyof Row>(\n    column: ColumnName,\n    value: string | ReadonlyArray<Row[ColumnName]> | Record<string, unknown>\n  ): this\n  contains(column: string, value: string | readonly unknown[] | Record<string, unknown>): this\n  contains(column: string, value: string | readonly unknown[] | Record<string, unknown>): this {\n    if (typeof value === 'string') {\n      // range types can be inclusive '[', ']' or exclusive '(', ')' so just\n      // keep it simple and accept a string\n      this.url.searchParams.append(column, `cs.${value}`)\n    } else if (Array.isArray(value)) {\n      // array\n      this.url.searchParams.append(column, `cs.{${value.join(',')}}`)\n    } else {\n      // json\n      this.url.searchParams.append(column, `cs.${JSON.stringify(value)}`)\n    }\n    return this\n  }\n\n  /**\n   * Only relevant for jsonb, array, and range columns. Match only rows where\n   * every element appearing in `column` is contained by `value`.\n   *\n   * @param column - The jsonb, array, or range column to filter on\n   * @param value - The jsonb, array, or range value to filter with\n   *\n   * @category Database\n   * @subcategory Using filters\n   *\n   * @example On array columns\n   * ```ts\n   * const { data, error } = await supabase\n   *   .from('classes')\n   *   .select('name')\n   *   .containedBy('days', ['monday', 'tuesday', 'wednesday', 'friday'])\n   * ```\n   *\n   * @exampleSql On array columns\n   * ```sql\n   * create table\n   *   classes (\n   *     id int8 primary key,\n   *     name text,\n   *     days text[]\n   *   );\n   *\n   * insert into\n   *   classes (id, name, days)\n   * values\n   *   (1, 'Chemistry', array['monday', 'friday']),\n   *   (2, 'History', array['monday', 'wednesday', 'thursday']);\n   * ```\n   *\n   * @exampleResponse On array columns\n   * ```json\n   * {\n   *   \"data\": [\n   *     {\n   *       \"name\": \"Chemistry\"\n   *     }\n   *   ],\n   *   \"status\": 200,\n   *   \"statusText\": \"OK\"\n   * }\n   * ```\n   *\n   * @exampleDescription On range columns\n   * Postgres supports a number of [range\n   * types](https://www.postgresql.org/docs/current/rangetypes.html). You\n   * can filter on range columns using the string representation of range\n   * values.\n   *\n   * @example On range columns\n   * ```ts\n   * const { data, error } = await supabase\n   *   .from('reservations')\n   *   .select()\n   *   .containedBy('during', '[2000-01-01 00:00, 2000-01-01 23:59)')\n   * ```\n   *\n   * @exampleSql On range columns\n   * ```sql\n   * create table\n   *   reservations (\n   *     id int8 primary key,\n   *     room_name text,\n   *     during tsrange\n   *   );\n   *\n   * insert into\n   *   reservations (id, room_name, during)\n   * values\n   *   (1, 'Emerald', '[2000-01-01 13:00, 2000-01-01 15:00)'),\n   *   (2, 'Topaz', '[2000-01-02 09:00, 2000-01-02 10:00)');\n   * ```\n   *\n   * @exampleResponse On range columns\n   * ```json\n   * {\n   *   \"data\": [\n   *     {\n   *       \"id\": 1,\n   *       \"room_name\": \"Emerald\",\n   *       \"during\": \"[\\\"2000-01-01 13:00:00\\\",\\\"2000-01-01 15:00:00\\\")\"\n   *     }\n   *   ],\n   *   \"status\": 200,\n   *   \"statusText\": \"OK\"\n   * }\n   * ```\n   *\n   * @example On `jsonb` columns\n   * ```ts\n   * const { data, error } = await supabase\n   *   .from('users')\n   *   .select('name')\n   *   .containedBy('address', {})\n   * ```\n   *\n   * @exampleSql On `jsonb` columns\n   * ```sql\n   * create table\n   *   users (\n   *     id int8 primary key,\n   *     name text,\n   *     address jsonb\n   *   );\n   *\n   * insert into\n   *   users (id, name, address)\n   * values\n   *   (1, 'Michael', '{ \"postcode\": 90210, \"street\": \"Melrose Place\" }'),\n   *   (2, 'Jane', '{}');\n   * ```\n   *\n   * @exampleResponse On `jsonb` columns\n   * ```json\n   *   {\n   *     \"data\": [\n   *       {\n   *         \"name\": \"Jane\"\n   *       }\n   *     ],\n   *     \"status\": 200,\n   *     \"statusText\": \"OK\"\n   *   }\n   *\n   * ```\n   */\n  containedBy<ColumnName extends string & keyof Row>(\n    column: ColumnName,\n    value: string | ReadonlyArray<Row[ColumnName]> | Record<string, unknown>\n  ): this\n  containedBy(column: string, value: string | readonly unknown[] | Record<string, unknown>): this\n  containedBy(column: string, value: string | readonly unknown[] | Record<string, unknown>): this {\n    if (typeof value === 'string') {\n      // range\n      this.url.searchParams.append(column, `cd.${value}`)\n    } else if (Array.isArray(value)) {\n      // array\n      this.url.searchParams.append(column, `cd.{${value.join(',')}}`)\n    } else {\n      // json\n      this.url.searchParams.append(column, `cd.${JSON.stringify(value)}`)\n    }\n    return this\n  }\n\n  /**\n   * Only relevant for range columns. Match only rows where every element in\n   * `column` is greater than any element in `range`.\n   *\n   * @param column - The range column to filter on\n   * @param range - The range to filter with\n   *\n   * @category Database\n   * @subcategory Using filters\n   *\n   * @exampleDescription With `select()`\n   * Postgres supports a number of [range\n   * types](https://www.postgresql.org/docs/current/rangetypes.html). You\n   * can filter on range columns using the string representation of range\n   * values.\n   *\n   * @example With `select()`\n   * ```ts\n   * const { data, error } = await supabase\n   *   .from('reservations')\n   *   .select()\n   *   .rangeGt('during', '[2000-01-02 08:00, 2000-01-02 09:00)')\n   * ```\n   *\n   * @exampleSql With `select()`\n   * ```sql\n   * create table\n   *   reservations (\n   *     id int8 primary key,\n   *     room_name text,\n   *     during tsrange\n   *   );\n   *\n   * insert into\n   *   reservations (id, room_name, during)\n   * values\n   *   (1, 'Emerald', '[2000-01-01 13:00, 2000-01-01 15:00)'),\n   *   (2, 'Topaz', '[2000-01-02 09:00, 2000-01-02 10:00)');\n   * ```\n   *\n   * @exampleResponse With `select()`\n   * ```json\n   *   {\n   *     \"data\": [\n   *       {\n   *         \"id\": 2,\n   *         \"room_name\": \"Topaz\",\n   *         \"during\": \"[\\\"2000-01-02 09:00:00\\\",\\\"2000-01-02 10:00:00\\\")\"\n   *       }\n   *     ],\n   *     \"status\": 200,\n   *     \"statusText\": \"OK\"\n   *   }\n   *\n   * ```\n   */\n  rangeGt<ColumnName extends string & keyof Row>(column: ColumnName, range: string): this\n  rangeGt(column: string, range: string): this\n  rangeGt(column: string, range: string): this {\n    this.url.searchParams.append(column, `sr.${range}`)\n    return this\n  }\n\n  /**\n   * Only relevant for range columns. Match only rows where every element in\n   * `column` is either contained in `range` or greater than any element in\n   * `range`.\n   *\n   * @param column - The range column to filter on\n   * @param range - The range to filter with\n   *\n   * @category Database\n   * @subcategory Using filters\n   *\n   * @exampleDescription With `select()`\n   * Postgres supports a number of [range\n   * types](https://www.postgresql.org/docs/current/rangetypes.html). You\n   * can filter on range columns using the string representation of range\n   * values.\n   *\n   * @example With `select()`\n   * ```ts\n   * const { data, error } = await supabase\n   *   .from('reservations')\n   *   .select()\n   *   .rangeGte('during', '[2000-01-02 08:30, 2000-01-02 09:30)')\n   * ```\n   *\n   * @exampleSql With `select()`\n   * ```sql\n   * create table\n   *   reservations (\n   *     id int8 primary key,\n   *     room_name text,\n   *     during tsrange\n   *   );\n   *\n   * insert into\n   *   reservations (id, room_name, during)\n   * values\n   *   (1, 'Emerald', '[2000-01-01 13:00, 2000-01-01 15:00)'),\n   *   (2, 'Topaz', '[2000-01-02 09:00, 2000-01-02 10:00)');\n   * ```\n   *\n   * @exampleResponse With `select()`\n   * ```json\n   *   {\n   *     \"data\": [\n   *       {\n   *         \"id\": 2,\n   *         \"room_name\": \"Topaz\",\n   *         \"during\": \"[\\\"2000-01-02 09:00:00\\\",\\\"2000-01-02 10:00:00\\\")\"\n   *       }\n   *     ],\n   *     \"status\": 200,\n   *     \"statusText\": \"OK\"\n   *   }\n   *\n   * ```\n   */\n  rangeGte<ColumnName extends string & keyof Row>(column: ColumnName, range: string): this\n  rangeGte(column: string, range: string): this\n  rangeGte(column: string, range: string): this {\n    this.url.searchParams.append(column, `nxl.${range}`)\n    return this\n  }\n\n  /**\n   * Only relevant for range columns. Match only rows where every element in\n   * `column` is less than any element in `range`.\n   *\n   * @param column - The range column to filter on\n   * @param range - The range to filter with\n   *\n   * @category Database\n   * @subcategory Using filters\n   *\n   * @exampleDescription With `select()`\n   * Postgres supports a number of [range\n   * types](https://www.postgresql.org/docs/current/rangetypes.html). You\n   * can filter on range columns using the string representation of range\n   * values.\n   *\n   * @example With `select()`\n   * ```ts\n   * const { data, error } = await supabase\n   *   .from('reservations')\n   *   .select()\n   *   .rangeLt('during', '[2000-01-01 15:00, 2000-01-01 16:00)')\n   * ```\n   *\n   * @exampleSql With `select()`\n   * ```sql\n   * create table\n   *   reservations (\n   *     id int8 primary key,\n   *     room_name text,\n   *     during tsrange\n   *   );\n   *\n   * insert into\n   *   reservations (id, room_name, during)\n   * values\n   *   (1, 'Emerald', '[2000-01-01 13:00, 2000-01-01 15:00)'),\n   *   (2, 'Topaz', '[2000-01-02 09:00, 2000-01-02 10:00)');\n   * ```\n   *\n   * @exampleResponse With `select()`\n   * ```json\n   * {\n   *   \"data\": [\n   *     {\n   *       \"id\": 1,\n   *       \"room_name\": \"Emerald\",\n   *       \"during\": \"[\\\"2000-01-01 13:00:00\\\",\\\"2000-01-01 15:00:00\\\")\"\n   *     }\n   *   ],\n   *   \"status\": 200,\n   *   \"statusText\": \"OK\"\n   * }\n   * ```\n   */\n  rangeLt<ColumnName extends string & keyof Row>(column: ColumnName, range: string): this\n  rangeLt(column: string, range: string): this\n  rangeLt(column: string, range: string): this {\n    this.url.searchParams.append(column, `sl.${range}`)\n    return this\n  }\n\n  /**\n   * Only relevant for range columns. Match only rows where every element in\n   * `column` is either contained in `range` or less than any element in\n   * `range`.\n   *\n   * @param column - The range column to filter on\n   * @param range - The range to filter with\n   *\n   * @category Database\n   * @subcategory Using filters\n   *\n   * @exampleDescription With `select()`\n   * Postgres supports a number of [range\n   * types](https://www.postgresql.org/docs/current/rangetypes.html). You\n   * can filter on range columns using the string representation of range\n   * values.\n   *\n   * @example With `select()`\n   * ```ts\n   * const { data, error } = await supabase\n   *   .from('reservations')\n   *   .select()\n   *   .rangeLte('during', '[2000-01-01 14:00, 2000-01-01 16:00)')\n   * ```\n   *\n   * @exampleSql With `select()`\n   * ```sql\n   * create table\n   *   reservations (\n   *     id int8 primary key,\n   *     room_name text,\n   *     during tsrange\n   *   );\n   *\n   * insert into\n   *   reservations (id, room_name, during)\n   * values\n   *   (1, 'Emerald', '[2000-01-01 13:00, 2000-01-01 15:00)'),\n   *   (2, 'Topaz', '[2000-01-02 09:00, 2000-01-02 10:00)');\n   * ```\n   *\n   * @exampleResponse With `select()`\n   * ```json\n   *   {\n   *     \"data\": [\n   *       {\n   *         \"id\": 1,\n   *         \"room_name\": \"Emerald\",\n   *         \"during\": \"[\\\"2000-01-01 13:00:00\\\",\\\"2000-01-01 15:00:00\\\")\"\n   *       }\n   *     ],\n   *     \"status\": 200,\n   *     \"statusText\": \"OK\"\n   *   }\n   *\n   * ```\n   */\n  rangeLte<ColumnName extends string & keyof Row>(column: ColumnName, range: string): this\n  rangeLte(column: string, range: string): this\n  rangeLte(column: string, range: string): this {\n    this.url.searchParams.append(column, `nxr.${range}`)\n    return this\n  }\n\n  /**\n   * Only relevant for range columns. Match only rows where `column` is\n   * mutually exclusive to `range` and there can be no element between the two\n   * ranges.\n   *\n   * @param column - The range column to filter on\n   * @param range - The range to filter with\n   *\n   * @category Database\n   * @subcategory Using filters\n   *\n   * @exampleDescription With `select()`\n   * Postgres supports a number of [range\n   * types](https://www.postgresql.org/docs/current/rangetypes.html). You\n   * can filter on range columns using the string representation of range\n   * values.\n   *\n   * @example With `select()`\n   * ```ts\n   * const { data, error } = await supabase\n   *   .from('reservations')\n   *   .select()\n   *   .rangeAdjacent('during', '[2000-01-01 12:00, 2000-01-01 13:00)')\n   * ```\n   *\n   * @exampleSql With `select()`\n   * ```sql\n   * create table\n   *   reservations (\n   *     id int8 primary key,\n   *     room_name text,\n   *     during tsrange\n   *   );\n   *\n   * insert into\n   *   reservations (id, room_name, during)\n   * values\n   *   (1, 'Emerald', '[2000-01-01 13:00, 2000-01-01 15:00)'),\n   *   (2, 'Topaz', '[2000-01-02 09:00, 2000-01-02 10:00)');\n   * ```\n   *\n   * @exampleResponse With `select()`\n   * ```json\n   * {\n   *   \"data\": [\n   *     {\n   *       \"id\": 1,\n   *       \"room_name\": \"Emerald\",\n   *       \"during\": \"[\\\"2000-01-01 13:00:00\\\",\\\"2000-01-01 15:00:00\\\")\"\n   *     }\n   *   ],\n   *   \"status\": 200,\n   *   \"statusText\": \"OK\"\n   * }\n   * ```\n   */\n  rangeAdjacent<ColumnName extends string & keyof Row>(column: ColumnName, range: string): this\n  rangeAdjacent(column: string, range: string): this\n  rangeAdjacent(column: string, range: string): this {\n    this.url.searchParams.append(column, `adj.${range}`)\n    return this\n  }\n\n  /**\n   * Only relevant for array and range columns. Match only rows where\n   * `column` and `value` have an element in common.\n   *\n   * @param column - The array or range column to filter on\n   * @param value - The array or range value to filter with\n   *\n   * @category Database\n   * @subcategory Using filters\n   *\n   * @example On array columns\n   * ```ts\n   * const { data, error } = await supabase\n   *   .from('issues')\n   *   .select('title')\n   *   .overlaps('tags', ['is:closed', 'severity:high'])\n   * ```\n   *\n   * @exampleSql On array columns\n   * ```sql\n   * create table\n   *   issues (\n   *     id int8 primary key,\n   *     title text,\n   *     tags text[]\n   *   );\n   *\n   * insert into\n   *   issues (id, title, tags)\n   * values\n   *   (1, 'Cache invalidation is not working', array['is:open', 'severity:high', 'priority:low']),\n   *   (2, 'Use better names', array['is:open', 'severity:low', 'priority:medium']);\n   * ```\n   *\n   * @exampleResponse On array columns\n   * ```json\n   * {\n   *   \"data\": [\n   *     {\n   *       \"title\": \"Cache invalidation is not working\"\n   *     }\n   *   ],\n   *   \"status\": 200,\n   *   \"statusText\": \"OK\"\n   * }\n   * ```\n   *\n   * @exampleDescription On range columns\n   * Postgres supports a number of [range\n   * types](https://www.postgresql.org/docs/current/rangetypes.html). You\n   * can filter on range columns using the string representation of range\n   * values.\n   *\n   * @example On range columns\n   * ```ts\n   * const { data, error } = await supabase\n   *   .from('reservations')\n   *   .select()\n   *   .overlaps('during', '[2000-01-01 12:45, 2000-01-01 13:15)')\n   * ```\n   *\n   * @exampleSql On range columns\n   * ```sql\n   * create table\n   *   reservations (\n   *     id int8 primary key,\n   *     room_name text,\n   *     during tsrange\n   *   );\n   *\n   * insert into\n   *   reservations (id, room_name, during)\n   * values\n   *   (1, 'Emerald', '[2000-01-01 13:00, 2000-01-01 15:00)'),\n   *   (2, 'Topaz', '[2000-01-02 09:00, 2000-01-02 10:00)');\n   * ```\n   *\n   * @exampleResponse On range columns\n   * ```json\n   * {\n   *   \"data\": [\n   *     {\n   *       \"id\": 1,\n   *       \"room_name\": \"Emerald\",\n   *       \"during\": \"[\\\"2000-01-01 13:00:00\\\",\\\"2000-01-01 15:00:00\\\")\"\n   *     }\n   *   ],\n   *   \"status\": 200,\n   *   \"statusText\": \"OK\"\n   * }\n   * ```\n   */\n  overlaps<ColumnName extends string & keyof Row>(\n    column: ColumnName,\n    value: string | ReadonlyArray<Row[ColumnName]>\n  ): this\n  overlaps(column: string, value: string | readonly unknown[]): this\n  overlaps(column: string, value: string | readonly unknown[]): this {\n    if (typeof value === 'string') {\n      // range\n      this.url.searchParams.append(column, `ov.${value}`)\n    } else {\n      // array\n      this.url.searchParams.append(column, `ov.{${value.join(',')}}`)\n    }\n    return this\n  }\n\n  /**\n   * Only relevant for text and tsvector columns. Match only rows where\n   * `column` matches the query string in `query`.\n   *\n   * @param column - The text or tsvector column to filter on\n   * @param query - The query text to match with\n   * @param options - Named parameters\n   * @param options.config - The text search configuration to use\n   * @param options.type - Change how the `query` text is interpreted\n   *\n   * @category Database\n   * @subcategory Using filters\n   *\n   * @remarks\n   * - For more information, see [Postgres full text search](/docs/guides/database/full-text-search).\n   *\n   * @example Text search\n   * ```ts\n   * const result = await supabase\n   *   .from(\"texts\")\n   *   .select(\"content\")\n   *   .textSearch(\"content\", `'eggs' & 'ham'`, {\n   *     config: \"english\",\n   *   });\n   * ```\n   *\n   * @exampleSql Text search\n   * ```sql\n   * create table texts (\n   *   id      bigint\n   *           primary key\n   *           generated always as identity,\n   *   content text\n   * );\n   *\n   * insert into texts (content) values\n   *     ('Four score and seven years ago'),\n   *     ('The road goes ever on and on'),\n   *     ('Green eggs and ham')\n   * ;\n   * ```\n   *\n   * @exampleResponse Text search\n   * ```json\n   * {\n   *   \"data\": [\n   *     {\n   *       \"content\": \"Green eggs and ham\"\n   *     }\n   *   ],\n   *   \"status\": 200,\n   *   \"statusText\": \"OK\"\n   * }\n   * ```\n   *\n   * @exampleDescription Basic normalization\n   * Uses PostgreSQL's `plainto_tsquery` function.\n   *\n   * @example Basic normalization\n   * ```ts\n   * const { data, error } = await supabase\n   *   .from('quotes')\n   *   .select('catchphrase')\n   *   .textSearch('catchphrase', `'fat' & 'cat'`, {\n   *     type: 'plain',\n   *     config: 'english'\n   *   })\n   * ```\n   *\n   * @exampleDescription Full normalization\n   * Uses PostgreSQL's `phraseto_tsquery` function.\n   *\n   * @example Full normalization\n   * ```ts\n   * const { data, error } = await supabase\n   *   .from('quotes')\n   *   .select('catchphrase')\n   *   .textSearch('catchphrase', `'fat' & 'cat'`, {\n   *     type: 'phrase',\n   *     config: 'english'\n   *   })\n   * ```\n   *\n   * @exampleDescription Websearch\n   * Uses PostgreSQL's `websearch_to_tsquery` function.\n   * This function will never raise syntax errors, which makes it possible to use raw user-supplied input for search, and can be used\n   * with advanced operators.\n   *\n   * - `unquoted text`: text not inside quote marks will be converted to terms separated by & operators, as if processed by plainto_tsquery.\n   * - `\"quoted text\"`: text inside quote marks will be converted to terms separated by `<->` operators, as if processed by phraseto_tsquery.\n   * - `OR`: the word “or” will be converted to the | operator.\n   * - `-`: a dash will be converted to the ! operator.\n   *\n   * @example Websearch\n   * ```ts\n   * const { data, error } = await supabase\n   *   .from('quotes')\n   *   .select('catchphrase')\n   *   .textSearch('catchphrase', `'fat or cat'`, {\n   *     type: 'websearch',\n   *     config: 'english'\n   *   })\n   * ```\n   */\n  textSearch<ColumnName extends string & keyof Row>(\n    column: ColumnName,\n    query: string,\n    options?: { config?: string; type?: 'plain' | 'phrase' | 'websearch' }\n  ): this\n  textSearch(\n    column: string,\n    query: string,\n    options?: { config?: string; type?: 'plain' | 'phrase' | 'websearch' }\n  ): this\n  textSearch(\n    column: string,\n    query: string,\n    { config, type }: { config?: string; type?: 'plain' | 'phrase' | 'websearch' } = {}\n  ): this {\n    let typePart = ''\n    if (type === 'plain') {\n      typePart = 'pl'\n    } else if (type === 'phrase') {\n      typePart = 'ph'\n    } else if (type === 'websearch') {\n      typePart = 'w'\n    }\n    const configPart = config === undefined ? '' : `(${config})`\n    this.url.searchParams.append(column, `${typePart}fts${configPart}.${query}`)\n    return this\n  }\n\n  /**\n   * Match only rows where each column in `query` keys is equal to its\n   * associated value. Shorthand for multiple `.eq()`s.\n   *\n   * @param query - The object to filter with, with column names as keys mapped\n   * to their filter values\n   *\n   * @category Database\n   * @subcategory Using filters\n   *\n   * @example With `select()`\n   * ```ts\n   * const { data, error } = await supabase\n   *   .from('characters')\n   *   .select('name')\n   *   .match({ id: 2, name: 'Leia' })\n   * ```\n   *\n   * @exampleSql With `select()`\n   * ```sql\n   * create table\n   *   characters (id int8 primary key, name text);\n   *\n   * insert into\n   *   characters (id, name)\n   * values\n   *   (1, 'Luke'),\n   *   (2, 'Leia'),\n   *   (3, 'Han');\n   * ```\n   *\n   * @exampleResponse With `select()`\n   * ```json\n   * {\n   *   \"data\": [\n   *     {\n   *       \"name\": \"Leia\"\n   *     }\n   *   ],\n   *   \"status\": 200,\n   *   \"statusText\": \"OK\"\n   * }\n   * ```\n   */\n  match<ColumnName extends string & keyof Row>(query: Record<ColumnName, Row[ColumnName]>): this\n  match(query: Record<string, unknown>): this\n  match(query: Record<string, unknown>): this {\n    Object.entries(query)\n      // columns with `undefined` value needs to be filtered out, otherwise it'll\n      // show up as `?column=eq.undefined`\n      .filter(([_, value]) => value !== undefined)\n      .forEach(([column, value]) => {\n        this.url.searchParams.append(column, `eq.${value}`)\n      })\n    return this\n  }\n\n  /**\n   * Match only rows which doesn't satisfy the filter.\n   *\n   * Unlike most filters, `opearator` and `value` are used as-is and need to\n   * follow [PostgREST\n   * syntax](https://postgrest.org/en/stable/api.html#operators). You also need\n   * to make sure they are properly sanitized.\n   *\n   * @param column - The column to filter on\n   * @param operator - The operator to be negated to filter with, following\n   * PostgREST syntax\n   * @param value - The value to filter with, following PostgREST syntax\n   *\n   * @category Database\n   * @subcategory Using filters\n   */\n  not<ColumnName extends string & keyof Row>(\n    column: ColumnName,\n    operator: 'is',\n    value: null\n  ): PostgrestFilterBuilder<\n    ClientOptions,\n    Schema,\n    NonNullableColumn<Row, ColumnName>,\n    NarrowResultColumn<Result, ColumnName>,\n    RelationName,\n    Relationships,\n    Method,\n    ThrowOnError\n  > &\n    this\n  not<ColumnName extends string & keyof Row>(\n    column: ColumnName,\n    operator: FilterOperator,\n    value: Row[ColumnName]\n  ): this\n  not(column: string, operator: string, value: unknown): this\n  /**\n   * Match only rows which doesn't satisfy the filter.\n   *\n   * Unlike most filters, `opearator` and `value` are used as-is and need to\n   * follow [PostgREST\n   * syntax](https://postgrest.org/en/stable/api.html#operators). You also need\n   * to make sure they are properly sanitized.\n   *\n   * @param column - The column to filter on\n   * @param operator - The operator to be negated to filter with, following\n   * PostgREST syntax\n   * @param value - The value to filter with, following PostgREST syntax\n   *\n   * @category Database\n   * @subcategory Using filters\n   *\n   * @remarks\n   * not() expects you to use the raw PostgREST syntax for the filter values.\n   *\n   * ```ts\n   * .not('id', 'in', '(5,6,7)')  // Use `()` for `in` filter\n   * .not('arraycol', 'cs', '{\"a\",\"b\"}')  // Use `cs` for `contains()`, `{}` for array values\n   * ```\n   *\n   * @example With `select()`\n   * ```ts\n   * const { data, error } = await supabase\n   *   .from('countries')\n   *   .select()\n   *   .not('name', 'is', null)\n   * ```\n   *\n   * @exampleSql With `select()`\n   * ```sql\n   * create table\n   *   countries (id int8 primary key, name text);\n   *\n   * insert into\n   *   countries (id, name)\n   * values\n   *   (1, 'null'),\n   *   (2, null);\n   * ```\n   *\n   * @exampleResponse With `select()`\n   * ```json\n   *   {\n   *     \"data\": [\n   *       {\n   *         \"id\": 1,\n   *         \"name\": \"null\"\n   *       }\n   *     ],\n   *     \"status\": 200,\n   *     \"statusText\": \"OK\"\n   *   }\n   *\n   * ```\n   */\n  not(\n    column: string,\n    operator: string,\n    value: unknown\n  ): PostgrestFilterBuilder<\n    ClientOptions,\n    Schema,\n    any,\n    any,\n    RelationName,\n    Relationships,\n    Method,\n    ThrowOnError\n  > &\n    this {\n    this.url.searchParams.append(column, `not.${operator}.${value}`)\n    return this as any\n  }\n\n  /**\n   * Match only rows which satisfy at least one of the filters.\n   *\n   * Unlike most filters, `filters` is used as-is and needs to follow [PostgREST\n   * syntax](https://postgrest.org/en/stable/api.html#operators). You also need\n   * to make sure it's properly sanitized.\n   *\n   * It's currently not possible to do an `.or()` filter across multiple tables.\n   *\n   * @param filters - The filters to use, following PostgREST syntax\n   * @param options - Named parameters\n   * @param options.referencedTable - Set this to filter on referenced tables\n   * instead of the parent table\n   * @param options.foreignTable - Deprecated, use `referencedTable` instead\n   *\n   * @category Database\n   * @subcategory Using filters\n   *\n   * @remarks\n   * or() expects you to use the raw PostgREST syntax for the filter names and values.\n   *\n   * ```ts\n   * .or('id.in.(5,6,7), arraycol.cs.{\"a\",\"b\"}')  // Use `()` for `in` filter, `{}` for array values and `cs` for `contains()`.\n   * .or('id.in.(5,6,7), arraycol.cd.{\"a\",\"b\"}')  // Use `cd` for `containedBy()`\n   * ```\n   *\n   * @example With `select()`\n   * ```ts\n   * const { data, error } = await supabase\n   *   .from('characters')\n   *   .select('name')\n   *   .or('id.eq.2,name.eq.Han')\n   * ```\n   *\n   * @exampleSql With `select()`\n   * ```sql\n   * create table\n   *   characters (id int8 primary key, name text);\n   *\n   * insert into\n   *   characters (id, name)\n   * values\n   *   (1, 'Luke'),\n   *   (2, 'Leia'),\n   *   (3, 'Han');\n   * ```\n   *\n   * @exampleResponse With `select()`\n   * ```json\n   * {\n   *   \"data\": [\n   *     {\n   *       \"name\": \"Leia\"\n   *     },\n   *     {\n   *       \"name\": \"Han\"\n   *     }\n   *   ],\n   *   \"status\": 200,\n   *   \"statusText\": \"OK\"\n   * }\n   * ```\n   *\n   * @example Use `or` with `and`\n   * ```ts\n   * const { data, error } = await supabase\n   *   .from('characters')\n   *   .select('name')\n   *   .or('id.gt.3,and(id.eq.1,name.eq.Luke)')\n   * ```\n   *\n   * @exampleSql Use `or` with `and`\n   * ```sql\n   * create table\n   *   characters (id int8 primary key, name text);\n   *\n   * insert into\n   *   characters (id, name)\n   * values\n   *   (1, 'Luke'),\n   *   (2, 'Leia'),\n   *   (3, 'Han');\n   * ```\n   *\n   * @exampleResponse Use `or` with `and`\n   * ```json\n   * {\n   *   \"data\": [\n   *     {\n   *       \"name\": \"Luke\"\n   *     }\n   *   ],\n   *   \"status\": 200,\n   *   \"statusText\": \"OK\"\n   * }\n   * ```\n   *\n   * @example Use `or` on referenced tables\n   * ```ts\n   * const { data, error } = await supabase\n   *   .from('orchestral_sections')\n   *   .select(`\n   *     name,\n   *     instruments!inner (\n   *       name\n   *     )\n   *   `)\n   *   .or('section_id.eq.1,name.eq.guzheng', { referencedTable: 'instruments' })\n   * ```\n   *\n   * @exampleSql Use `or` on referenced tables\n   * ```sql\n   * create table\n   *   orchestral_sections (id int8 primary key, name text);\n   * create table\n   *   instruments (\n   *     id int8 primary key,\n   *     section_id int8 not null references orchestral_sections,\n   *     name text\n   *   );\n   *\n   * insert into\n   *   orchestral_sections (id, name)\n   * values\n   *   (1, 'strings'),\n   *   (2, 'woodwinds');\n   * insert into\n   *   instruments (id, section_id, name)\n   * values\n   *   (1, 2, 'flute'),\n   *   (2, 1, 'violin');\n   * ```\n   *\n   * @exampleResponse Use `or` on referenced tables\n   * ```json\n   * {\n   *   \"data\": [\n   *     {\n   *       \"name\": \"strings\",\n   *       \"instruments\": [\n   *         {\n   *           \"name\": \"violin\"\n   *         }\n   *       ]\n   *     }\n   *   ],\n   *   \"status\": 200,\n   *   \"statusText\": \"OK\"\n   * }\n   * ```\n   */\n  or(\n    filters: string,\n    {\n      foreignTable,\n      referencedTable = foreignTable,\n    }: { foreignTable?: string; referencedTable?: string } = {}\n  ): this {\n    const key = referencedTable ? `${referencedTable}.or` : 'or'\n    this.url.searchParams.append(key, `(${filters})`)\n    return this\n  }\n\n  /**\n   * Match only rows which satisfy the filter. This is an escape hatch - you\n   * should use the specific filter methods wherever possible.\n   *\n   * Unlike most filters, `opearator` and `value` are used as-is and need to\n   * follow [PostgREST\n   * syntax](https://postgrest.org/en/stable/api.html#operators). You also need\n   * to make sure they are properly sanitized.\n   *\n   * @param column - The column to filter on\n   * @param operator - The operator to filter with, following PostgREST syntax\n   * @param value - The value to filter with, following PostgREST syntax\n   *\n   * @category Database\n   * @subcategory Using filters\n   *\n   * @remarks\n   * filter() expects you to use the raw PostgREST syntax for the filter values.\n   *\n   * ```ts\n   * .filter('id', 'in', '(5,6,7)')  // Use `()` for `in` filter\n   * .filter('arraycol', 'cs', '{\"a\",\"b\"}')  // Use `cs` for `contains()`, `{}` for array values\n   * ```\n   *\n   * @example With `select()`\n   * ```ts\n   * const { data, error } = await supabase\n   *   .from('characters')\n   *   .select()\n   *   .filter('name', 'in', '(\"Han\",\"Yoda\")')\n   * ```\n   *\n   * @exampleSql With `select()`\n   * ```sql\n   * create table\n   *   characters (id int8 primary key, name text);\n   *\n   * insert into\n   *   characters (id, name)\n   * values\n   *   (1, 'Luke'),\n   *   (2, 'Leia'),\n   *   (3, 'Han');\n   * ```\n   *\n   * @exampleResponse With `select()`\n   * ```json\n   * {\n   *   \"data\": [\n   *     {\n   *       \"id\": 3,\n   *       \"name\": \"Han\"\n   *     }\n   *   ],\n   *   \"status\": 200,\n   *   \"statusText\": \"OK\"\n   * }\n   * ```\n   *\n   * @example On a referenced table\n   * ```ts\n   * const { data, error } = await supabase\n   *   .from('orchestral_sections')\n   *   .select(`\n   *     name,\n   *     instruments!inner (\n   *       name\n   *     )\n   *   `)\n   *   .filter('instruments.name', 'eq', 'flute')\n   * ```\n   *\n   * @exampleSql On a referenced table\n   * ```sql\n   * create table\n   *   orchestral_sections (id int8 primary key, name text);\n   * create table\n   *    instruments (\n   *     id int8 primary key,\n   *     section_id int8 not null references orchestral_sections,\n   *     name text\n   *   );\n   *\n   * insert into\n   *   orchestral_sections (id, name)\n   * values\n   *   (1, 'strings'),\n   *   (2, 'woodwinds');\n   * insert into\n   *   instruments (id, section_id, name)\n   * values\n   *   (1, 2, 'flute'),\n   *   (2, 1, 'violin');\n   * ```\n   *\n   * @exampleResponse On a referenced table\n   * ```json\n   * {\n   *   \"data\": [\n   *     {\n   *       \"name\": \"woodwinds\",\n   *       \"instruments\": [\n   *         {\n   *           \"name\": \"flute\"\n   *         }\n   *       ]\n   *     }\n   *   ],\n   *   \"status\": 200,\n   *   \"statusText\": \"OK\"\n   * }\n   * ```\n   */\n  filter<ColumnName extends string & keyof Row>(\n    column: ColumnName,\n    operator: `${'' | 'not.'}${FilterOperator}`,\n    value: unknown\n  ): this\n  filter(column: string, operator: string, value: unknown): this\n  filter(column: string, operator: string, value: unknown): this {\n    this.url.searchParams.append(column, `${operator}.${value}`)\n    return this\n  }\n}\n", "import PostgrestFilterBuilder from './PostgrestFilterBuilder'\nimport { GetResult } from './select-query-parser/result'\nimport {\n  ClientServerOptions,\n  Fetch,\n  GenericSchema,\n  GenericTable,\n  GenericView,\n} from './types/common/common'\nimport { RejectExcessProperties } from './types/types'\n\nexport default class PostgrestQueryBuilder<\n  ClientOptions extends ClientServerOptions,\n  Schema extends GenericSchema,\n  Relation extends GenericTable | GenericView,\n  RelationName = unknown,\n  Relationships = Relation extends { Relationships: infer R } ? R : unknown,\n> {\n  url: URL\n  headers: Headers\n  schema?: string\n  signal?: AbortSignal\n  fetch?: Fetch\n  urlLengthLimit: number\n\n  /**\n   * Enable or disable automatic retries for transient errors.\n   * When enabled, idempotent requests (GET/HEAD/OPTIONS) that fail with network\n   * errors or HTTP 503/520 responses are automatically retried with exponential\n   * backoff (1s, 2s, 4s, up to 3 attempts). Defaults to `true` when not specified.\n   */\n  retry?: boolean\n\n  /**\n   * Creates a query builder scoped to a Postgres table or view.\n   *\n   * @category Database\n   *\n   * @param url - The URL for the query\n   * @param options - Named parameters\n   * @param options.headers - Custom headers\n   * @param options.schema - Postgres schema to use\n   * @param options.fetch - Custom fetch implementation\n   * @param options.urlLengthLimit - Maximum URL length before warning\n   * @param options.retry - Enable automatic retries for transient errors (default: true)\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.from('users').select('*')\n   * ```\n   *\n   * @example Standalone import for bundle-sensitive environments\n   * ```ts\n   * import { PostgrestQueryBuilder } from '@supabase/postgrest-js'\n   *\n   * const query = new PostgrestQueryBuilder(\n   *   new URL('https://xyzcompany.supabase.co/rest/v1/users'),\n   *   { headers: { apikey: 'your-publishable-key' }, retry: true }\n   * )\n   * ```\n   */\n  constructor(\n    url: URL,\n    {\n      headers = {},\n      schema,\n      fetch,\n      urlLengthLimit = 8000,\n      retry,\n    }: {\n      headers?: HeadersInit\n      schema?: string\n      fetch?: Fetch\n      urlLengthLimit?: number\n      retry?: boolean\n    }\n  ) {\n    this.url = url\n    this.headers = new Headers(headers)\n    this.schema = schema\n    this.fetch = fetch\n    this.urlLengthLimit = urlLengthLimit\n    this.retry = retry\n  }\n\n  /**\n   * Clone URL and headers to prevent shared state between operations.\n   */\n  private cloneRequestState(): { url: URL; headers: Headers } {\n    return {\n      url: new URL(this.url.toString()),\n      headers: new Headers(this.headers),\n    }\n  }\n\n  /**\n       * Perform a SELECT query on the table or view.\n       *\n       * @param columns - The columns to retrieve, separated by commas. Columns can be renamed when returned with `customName:columnName`\n       *\n       * @param options - Named parameters\n       *\n       * @param options.head - When set to `true`, `data` will not be returned.\n       * Useful if you only need the count.\n       *\n       * @param options.count - Count algorithm to use to count rows in the table or view.\n       *\n       * `\"exact\"`: Exact but slow count algorithm. Performs a `COUNT(*)` under the\n       * hood.\n       *\n       * `\"planned\"`: Approximated but fast count algorithm. Uses the Postgres\n       * statistics under the hood.\n       *\n       * `\"estimated\"`: Uses exact count for low numbers and planned count for high\n       * numbers.\n       *\n       * @remarks\n       * When using `count` with `.range()` or `.limit()`, the returned `count` is the total number of rows\n       * that match your filters, not the number of rows in the current page. Use this to build pagination UI.\n       \n     * - By default, Supabase projects return a maximum of 1,000 rows. This setting can be changed in your project's [API settings](/dashboard/project/_/settings/api). It's recommended that you keep it low to limit the payload size of accidental or malicious requests. You can use `range()` queries to paginate through your data.\n     * - `select()` can be combined with [Filters](/docs/reference/javascript/using-filters)\n     * - `select()` can be combined with [Modifiers](/docs/reference/javascript/using-modifiers)\n     * - `apikey` is a reserved keyword if you're using the [Supabase Platform](/docs/guides/platform) and [should be avoided as a column name](https://github.com/supabase/supabase/issues/5465). *\n     * @category Database\n     *\n     * @example Getting your data\n     * ```js\n     * const { data, error } = await supabase\n     *   .from('characters')\n     *   .select()\n     * ```\n     *\n     * @exampleSql Getting your data\n     * ```sql\n     * create table\n     *   characters (id int8 primary key, name text);\n     *\n     * insert into\n     *   characters (id, name)\n     * values\n     *   (1, 'Harry'),\n     *   (2, 'Frodo'),\n     *   (3, 'Katniss');\n     * ```\n     *\n     * @exampleResponse Getting your data\n     * ```json\n     * {\n     *   \"data\": [\n     *     {\n     *       \"id\": 1,\n     *       \"name\": \"Harry\"\n     *     },\n     *     {\n     *       \"id\": 2,\n     *       \"name\": \"Frodo\"\n     *     },\n     *     {\n     *       \"id\": 3,\n     *       \"name\": \"Katniss\"\n     *     }\n     *   ],\n     *   \"status\": 200,\n     *   \"statusText\": \"OK\"\n     * }\n     * ```\n     *\n     * @exampleDescription Handling errors\n     * The most useful field on a Postgres error is usually `hint` — when the database knows the fix, it puts the literal SQL there. For example, a permission-denied error (`code: '42501'`) arrives with a `hint` like `\"Grant the required privileges to the current role with: GRANT SELECT ON public.characters TO anon;\"`. Log the full `error` object so the hint isn't hidden behind `error.message`.\n     *\n     * @example Handling errors\n     * ```js\n     * const { data, error } = await supabase.from('characters').select()\n     * if (error) {\n     *   // Logs the full error: message, code, details, and hint.\n     *   console.error(error)\n     *   return\n     * }\n     * ```\n     *\n     * @exampleResponse Handling errors\n     * ```json\n     * {\n     *   \"error\": {\n     *     \"code\": \"42501\",\n     *     \"details\": null,\n     *     \"hint\": \"Grant the required privileges to the current role with: GRANT SELECT ON public.characters TO anon;\",\n     *     \"message\": \"permission denied for table characters\"\n     *   },\n     *   \"status\": 401,\n     *   \"statusText\": \"\"\n     * }\n     * ```\n     *\n     * @example Selecting specific columns\n     * ```js\n     * const { data, error } = await supabase\n     *   .from('characters')\n     *   .select('name')\n     * ```\n     *\n     * @exampleSql Selecting specific columns\n     * ```sql\n     * create table\n     *   characters (id int8 primary key, name text);\n     *\n     * insert into\n     *   characters (id, name)\n     * values\n     *   (1, 'Frodo'),\n     *   (2, 'Harry'),\n     *   (3, 'Katniss');\n     * ```\n     *\n     * @exampleResponse Selecting specific columns\n     * ```json\n     * {\n     *   \"data\": [\n     *     {\n     *       \"name\": \"Frodo\"\n     *     },\n     *     {\n     *       \"name\": \"Harry\"\n     *     },\n     *     {\n     *       \"name\": \"Katniss\"\n     *     }\n     *   ],\n     *   \"status\": 200,\n     *   \"statusText\": \"OK\"\n     * }\n     * ```\n     *\n     * @exampleDescription Query referenced tables\n     * If your database has foreign key relationships, you can query related tables too.\n     *\n     * @example Query referenced tables\n     * ```js\n     * const { data, error } = await supabase\n     *   .from('orchestral_sections')\n     *   .select(`\n     *     name,\n     *     instruments (\n     *       name\n     *     )\n     *   `)\n     * ```\n     *\n     * @exampleSql Query referenced tables\n     * ```sql\n     * create table\n     *   orchestral_sections (id int8 primary key, name text);\n     * create table\n     *   instruments (\n     *     id int8 primary key,\n     *     section_id int8 not null references orchestral_sections,\n     *     name text\n     *   );\n     *\n     * insert into\n     *   orchestral_sections (id, name)\n     * values\n     *   (1, 'strings'),\n     *   (2, 'woodwinds');\n     * insert into\n     *   instruments (id, section_id, name)\n     * values\n     *   (1, 2, 'flute'),\n     *   (2, 1, 'violin');\n     * ```\n     *\n     * @exampleResponse Query referenced tables\n     * ```json\n     * {\n     *   \"data\": [\n     *     {\n     *       \"name\": \"strings\",\n     *       \"instruments\": [\n     *         {\n     *           \"name\": \"violin\"\n     *         }\n     *       ]\n     *     },\n     *     {\n     *       \"name\": \"woodwinds\",\n     *       \"instruments\": [\n     *         {\n     *           \"name\": \"flute\"\n     *         }\n     *       ]\n     *     }\n     *   ],\n     *   \"status\": 200,\n     *   \"statusText\": \"OK\"\n     * }\n     * ```\n     *\n     * @exampleDescription Query referenced tables with spaces in their names\n     * If your table name contains spaces, you must use double quotes in the `select` statement to reference the table.\n     *\n     * @example Query referenced tables with spaces in their names\n     * ```js\n     * const { data, error } = await supabase\n     *   .from('orchestral sections')\n     *   .select(`\n     *     name,\n     *     \"musical instruments\" (\n     *       name\n     *     )\n     *   `)\n     * ```\n     *\n     * @exampleSql Query referenced tables with spaces in their names\n     * ```sql\n     * create table\n     *   \"orchestral sections\" (id int8 primary key, name text);\n     * create table\n     *   \"musical instruments\" (\n     *     id int8 primary key,\n     *     section_id int8 not null references \"orchestral sections\",\n     *     name text\n     *   );\n     *\n     * insert into\n     *   \"orchestral sections\" (id, name)\n     * values\n     *   (1, 'strings'),\n     *   (2, 'woodwinds');\n     * insert into\n     *   \"musical instruments\" (id, section_id, name)\n     * values\n     *   (1, 2, 'flute'),\n     *   (2, 1, 'violin');\n     * ```\n     *\n     * @exampleResponse Query referenced tables with spaces in their names\n     * ```json\n     * {\n     *   \"data\": [\n     *     {\n     *       \"name\": \"strings\",\n     *       \"musical instruments\": [\n     *         {\n     *           \"name\": \"violin\"\n     *         }\n     *       ]\n     *     },\n     *     {\n     *       \"name\": \"woodwinds\",\n     *       \"musical instruments\": [\n     *         {\n     *           \"name\": \"flute\"\n     *         }\n     *       ]\n     *     }\n     *   ],\n     *   \"status\": 200,\n     *   \"statusText\": \"OK\"\n     * }\n     * ```\n     *\n     * @exampleDescription Query referenced tables through a join table\n     * If you're in a situation where your tables are **NOT** directly\n     * related, but instead are joined by a _join table_, you can still use\n     * the `select()` method to query the related data. The join table needs\n     * to have the foreign keys as part of its composite primary key.\n     *\n     * @example Query referenced tables through a join table\n     * ```ts\n     * const { data, error } = await supabase\n     *   .from('users')\n     *   .select(`\n     *     name,\n     *     teams (\n     *       name\n     *     )\n     *   `)\n     *   \n     * ```\n     *\n     * @exampleSql Query referenced tables through a join table\n     * ```sql\n     * create table\n     *   users (\n     *     id int8 primary key,\n     *     name text\n     *   );\n     * create table\n     *   teams (\n     *     id int8 primary key,\n     *     name text\n     *   );\n     * -- join table\n     * create table\n     *   users_teams (\n     *     user_id int8 not null references users,\n     *     team_id int8 not null references teams,\n     *     -- both foreign keys must be part of a composite primary key\n     *     primary key (user_id, team_id)\n     *   );\n     *\n     * insert into\n     *   users (id, name)\n     * values\n     *   (1, 'Kiran'),\n     *   (2, 'Evan');\n     * insert into\n     *   teams (id, name)\n     * values\n     *   (1, 'Green'),\n     *   (2, 'Blue');\n     * insert into\n     *   users_teams (user_id, team_id)\n     * values\n     *   (1, 1),\n     *   (1, 2),\n     *   (2, 2);\n     * ```\n     *\n     * @exampleResponse Query referenced tables through a join table\n     * ```json\n     *   {\n     *     \"data\": [\n     *       {\n     *         \"name\": \"Kiran\",\n     *         \"teams\": [\n     *           {\n     *             \"name\": \"Green\"\n     *           },\n     *           {\n     *             \"name\": \"Blue\"\n     *           }\n     *         ]\n     *       },\n     *       {\n     *         \"name\": \"Evan\",\n     *         \"teams\": [\n     *           {\n     *             \"name\": \"Blue\"\n     *           }\n     *         ]\n     *       }\n     *     ],\n     *     \"status\": 200,\n     *     \"statusText\": \"OK\"\n     *   }\n     *   \n     * ```\n     *\n     * @exampleDescription Query the same referenced table multiple times\n     * If you need to query the same referenced table twice, use the name of the\n     * joined column to identify which join to use. You can also give each\n     * column an alias.\n     *\n     * @example Query the same referenced table multiple times\n     * ```ts\n     * const { data, error } = await supabase\n     *   .from('messages')\n     *   .select(`\n     *     content,\n     *     from:sender_id(name),\n     *     to:receiver_id(name)\n     *   `)\n     *\n     * // To infer types, use the name of the table (in this case `users`) and\n     * // the name of the foreign key constraint.\n     * const { data, error } = await supabase\n     *   .from('messages')\n     *   .select(`\n     *     content,\n     *     from:users!messages_sender_id_fkey(name),\n     *     to:users!messages_receiver_id_fkey(name)\n     *   `)\n     * ```\n     *\n     * @exampleSql Query the same referenced table multiple times\n     * ```sql\n     *  create table\n     *  users (id int8 primary key, name text);\n     *\n     *  create table\n     *    messages (\n     *      sender_id int8 not null references users,\n     *      receiver_id int8 not null references users,\n     *      content text\n     *    );\n     *\n     *  insert into\n     *    users (id, name)\n     *  values\n     *    (1, 'Kiran'),\n     *    (2, 'Evan');\n     *\n     *  insert into\n     *    messages (sender_id, receiver_id, content)\n     *  values\n     *    (1, 2, '👋');\n     *  ```\n     * ```\n     *\n     * @exampleResponse Query the same referenced table multiple times\n     * ```json\n     * {\n     *   \"data\": [\n     *     {\n     *       \"content\": \"👋\",\n     *       \"from\": {\n     *         \"name\": \"Kiran\"\n     *       },\n     *       \"to\": {\n     *         \"name\": \"Evan\"\n     *       }\n     *     }\n     *   ],\n     *   \"status\": 200,\n     *   \"statusText\": \"OK\"\n     * }\n     * ```\n     *\n     * @exampleDescription Query nested foreign tables through a join table\n     * You can use the result of a joined table to gather data in\n     * another foreign table. With multiple references to the same foreign\n     * table you must specify the column on which to conduct the join.\n     *\n     * @example Query nested foreign tables through a join table\n     * ```ts\n     *   const { data, error } = await supabase\n     *     .from('games')\n     *     .select(`\n     *       game_id:id,\n     *       away_team:teams!games_away_team_fkey (\n     *         users (\n     *           id,\n     *           name\n     *         )\n     *       )\n     *     `)\n     *   \n     * ```\n     *\n     * @exampleSql Query nested foreign tables through a join table\n     * ```sql\n     * ```sql\n     * create table\n     *   users (\n     *     id int8 primary key,\n     *     name text\n     *   );\n     * create table\n     *   teams (\n     *     id int8 primary key,\n     *     name text\n     *   );\n     * -- join table\n     * create table\n     *   users_teams (\n     *     user_id int8 not null references users,\n     *     team_id int8 not null references teams,\n     *\n     *     primary key (user_id, team_id)\n     *   );\n     * create table\n     *   games (\n     *     id int8 primary key,\n     *     home_team int8 not null references teams,\n     *     away_team int8 not null references teams,\n     *     name text\n     *   );\n     *\n     * insert into users (id, name)\n     * values\n     *   (1, 'Kiran'),\n     *   (2, 'Evan');\n     * insert into\n     *   teams (id, name)\n     * values\n     *   (1, 'Green'),\n     *   (2, 'Blue');\n     * insert into\n     *   users_teams (user_id, team_id)\n     * values\n     *   (1, 1),\n     *   (1, 2),\n     *   (2, 2);\n     * insert into\n     *   games (id, home_team, away_team, name)\n     * values\n     *   (1, 1, 2, 'Green vs Blue'),\n     *   (2, 2, 1, 'Blue vs Green');\n     * ```\n     *\n     * @exampleResponse Query nested foreign tables through a join table\n     * ```json\n     *   {\n     *     \"data\": [\n     *       {\n     *         \"game_id\": 1,\n     *         \"away_team\": {\n     *           \"users\": [\n     *             {\n     *               \"id\": 1,\n     *               \"name\": \"Kiran\"\n     *             },\n     *             {\n     *               \"id\": 2,\n     *               \"name\": \"Evan\"\n     *             }\n     *           ]\n     *         }\n     *       },\n     *       {\n     *         \"game_id\": 2,\n     *         \"away_team\": {\n     *           \"users\": [\n     *             {\n     *               \"id\": 1,\n     *               \"name\": \"Kiran\"\n     *             }\n     *           ]\n     *         }\n     *       }\n     *     ],\n     *     \"status\": 200,\n     *     \"statusText\": \"OK\"\n     *   }\n     *   \n     * ```\n     *\n     * @exampleDescription Filtering through referenced tables\n     * If the filter on a referenced table's column is not satisfied, the referenced\n     * table returns `[]` or `null` but the parent table is not filtered out.\n     * If you want to filter out the parent table rows, use the `!inner` hint\n     *\n     * @example Filtering through referenced tables\n     * ```ts\n     * const { data, error } = await supabase\n     *   .from('instruments')\n     *   .select('name, orchestral_sections(*)')\n     *   .eq('orchestral_sections.name', 'percussion')\n     * ```\n     *\n     * @exampleSql Filtering through referenced tables\n     * ```sql\n     * create table\n     *   orchestral_sections (id int8 primary key, name text);\n     * create table\n     *   instruments (\n     *     id int8 primary key,\n     *     section_id int8 not null references orchestral_sections,\n     *     name text\n     *   );\n     *\n     * insert into\n     *   orchestral_sections (id, name)\n     * values\n     *   (1, 'strings'),\n     *   (2, 'woodwinds');\n     * insert into\n     *   instruments (id, section_id, name)\n     * values\n     *   (1, 2, 'flute'),\n     *   (2, 1, 'violin');\n     * ```\n     *\n     * @exampleResponse Filtering through referenced tables\n     * ```json\n     * {\n     *   \"data\": [\n     *     {\n     *       \"name\": \"flute\",\n     *       \"orchestral_sections\": null\n     *     },\n     *     {\n     *       \"name\": \"violin\",\n     *       \"orchestral_sections\": null\n     *     }\n     *   ],\n     *   \"status\": 200,\n     *   \"statusText\": \"OK\"\n     * }\n     * ```\n     *\n     * @exampleDescription Querying referenced table with count\n     * You can get the number of rows in a related table by using the\n     * **count** property.\n     *\n     * @example Querying referenced table with count\n     * ```ts\n     * const { data, error } = await supabase\n     *   .from('orchestral_sections')\n     *   .select(`*, instruments(count)`)\n     * ```\n     *\n     * @exampleSql Querying referenced table with count\n     * ```sql\n     * create table orchestral_sections (\n     *   \"id\" \"uuid\" primary key default \"extensions\".\"uuid_generate_v4\"() not null,\n     *   \"name\" text\n     * );\n     *\n     * create table characters (\n     *   \"id\" \"uuid\" primary key default \"extensions\".\"uuid_generate_v4\"() not null,\n     *   \"name\" text,\n     *   \"section_id\" \"uuid\" references public.orchestral_sections on delete cascade\n     * );\n     *\n     * with section as (\n     *   insert into orchestral_sections (name)\n     *   values ('strings') returning id\n     * )\n     * insert into instruments (name, section_id) values\n     * ('violin', (select id from section)),\n     * ('viola', (select id from section)),\n     * ('cello', (select id from section)),\n     * ('double bass', (select id from section));\n     * ```\n     *\n     * @exampleResponse Querying referenced table with count\n     * ```json\n     * [\n     *   {\n     *     \"id\": \"693694e7-d993-4360-a6d7-6294e325d9b6\",\n     *     \"name\": \"strings\",\n     *     \"instruments\": [\n     *       {\n     *         \"count\": 4\n     *       }\n     *     ]\n     *   }\n     * ]\n     * ```\n     *\n     * @exampleDescription Querying with count option\n     * You can get the number of rows by using the\n     * [count](/docs/reference/javascript/select#parameters) option.\n     *\n     * @example Querying with count option\n     * ```ts\n     * const { count, error } = await supabase\n     *   .from('characters')\n     *   .select('*', { count: 'exact', head: true })\n     * ```\n     *\n     * @exampleSql Querying with count option\n     * ```sql\n     * create table\n     *   characters (id int8 primary key, name text);\n     *\n     * insert into\n     *   characters (id, name)\n     * values\n     *   (1, 'Luke'),\n     *   (2, 'Leia'),\n     *   (3, 'Han');\n     * ```\n     *\n     * @exampleResponse Querying with count option\n     * ```json\n     * {\n     *   \"count\": 3,\n     *   \"status\": 200,\n     *   \"statusText\": \"OK\"\n     * }\n     * ```\n     *\n     * @exampleDescription Querying JSON data\n     * You can select and filter data inside of\n     * [JSON](/docs/guides/database/json) columns. Postgres offers some\n     * [operators](/docs/guides/database/json#query-the-jsonb-data) for\n     * querying JSON data.\n     *\n     * @example Querying JSON data\n     * ```ts\n     * const { data, error } = await supabase\n     *   .from('users')\n     *   .select(`\n     *     id, name,\n     *     address->city\n     *   `)\n     * ```\n     *\n     * @exampleSql Querying JSON data\n     * ```sql\n     * create table\n     *   users (\n     *     id int8 primary key,\n     *     name text,\n     *     address jsonb\n     *   );\n     *\n     * insert into\n     *   users (id, name, address)\n     * values\n     *   (1, 'Frodo', '{\"city\":\"Hobbiton\"}');\n     * ```\n     *\n     * @exampleResponse Querying JSON data\n     * ```json\n     * {\n     *   \"data\": [\n     *     {\n     *       \"id\": 1,\n     *       \"name\": \"Frodo\",\n     *       \"city\": \"Hobbiton\"\n     *     }\n     *   ],\n     *   \"status\": 200,\n     *   \"statusText\": \"OK\"\n     * }\n     * ```\n     *\n     * @exampleDescription Querying referenced table with inner join\n     * If you don't want to return the referenced table contents, you can leave the parenthesis empty.\n     * Like `.select('name, orchestral_sections!inner()')`.\n     *\n     * @example Querying referenced table with inner join\n     * ```ts\n     * const { data, error } = await supabase\n     *   .from('instruments')\n     *   .select('name, orchestral_sections!inner(name)')\n     *   .eq('orchestral_sections.name', 'woodwinds')\n     *   .limit(1)\n     * ```\n     *\n     * @exampleSql Querying referenced table with inner join\n     * ```sql\n     * create table orchestral_sections (\n     *   \"id\" \"uuid\" primary key default \"extensions\".\"uuid_generate_v4\"() not null,\n     *   \"name\" text\n     * );\n     *\n     * create table instruments (\n     *   \"id\" \"uuid\" primary key default \"extensions\".\"uuid_generate_v4\"() not null,\n     *   \"name\" text,\n     *   \"section_id\" \"uuid\" references public.orchestral_sections on delete cascade\n     * );\n     *\n     * with section as (\n     *   insert into orchestral_sections (name)\n     *   values ('woodwinds') returning id\n     * )\n     * insert into instruments (name, section_id) values\n     * ('flute', (select id from section)),\n     * ('clarinet', (select id from section)),\n     * ('bassoon', (select id from section)),\n     * ('piccolo', (select id from section));\n     * ```\n     *\n     * @exampleResponse Querying referenced table with inner join\n     * ```json\n     * {\n     *   \"data\": [\n     *     {\n     *       \"name\": \"flute\",\n     *       \"orchestral_sections\": {\"name\": \"woodwinds\"}\n     *     }\n     *   ],\n     *   \"status\": 200,\n     *   \"statusText\": \"OK\"\n     * }\n     * ```\n     *\n     * @exampleDescription Switching schemas per query\n     * In addition to setting the schema during initialization, you can also switch schemas on a per-query basis.\n     * Make sure you've set up your [database privileges and API settings](/docs/guides/api/using-custom-schemas).\n     *\n     * @example Switching schemas per query\n     * ```ts\n     * const { data, error } = await supabase\n     *   .schema('myschema')\n     *   .from('mytable')\n     *   .select()\n     * ```\n     *\n     * @exampleSql Switching schemas per query\n     * ```sql\n     * create schema myschema;\n     *\n     * create table myschema.mytable (\n     *   id uuid primary key default gen_random_uuid(),\n     *   data text\n     * );\n     *\n     * insert into myschema.mytable (data) values ('mydata');\n     * ```\n     *\n     * @exampleResponse Switching schemas per query\n     * ```json\n     * {\n     *   \"data\": [\n     *     {\n     *       \"id\": \"4162e008-27b0-4c0f-82dc-ccaeee9a624d\",\n     *       \"data\": \"mydata\"\n     *     }\n     *   ],\n     *   \"status\": 200,\n     *   \"statusText\": \"OK\"\n     * }\n     * ```\n       */\n  select<\n    Query extends string = '*',\n    ResultOne = GetResult<\n      Schema,\n      Relation['Row'],\n      RelationName,\n      Relationships,\n      Query,\n      ClientOptions\n    >,\n  >(\n    columns?: Query,\n    options?: {\n      head?: boolean\n      count?: 'exact' | 'planned' | 'estimated' | (string & {})\n    }\n  ): PostgrestFilterBuilder<\n    ClientOptions,\n    Schema,\n    Relation['Row'],\n    ResultOne[],\n    RelationName,\n    Relationships,\n    'GET'\n  > {\n    const { head = false, count } = options ?? {}\n\n    const method = head ? 'HEAD' : 'GET'\n    // Remove whitespaces except when quoted\n    let quoted = false\n    const cleanedColumns = (columns ?? '*')\n      .split('')\n      .map((c) => {\n        if (/\\s/.test(c) && !quoted) {\n          return ''\n        }\n        if (c === '\"') {\n          quoted = !quoted\n        }\n        return c\n      })\n      .join('')\n\n    const { url, headers } = this.cloneRequestState()\n    url.searchParams.set('select', cleanedColumns)\n\n    if (count) {\n      headers.append('Prefer', `count=${count}`)\n    }\n\n    return new PostgrestFilterBuilder({\n      method,\n      url,\n      headers,\n      schema: this.schema,\n      fetch: this.fetch,\n      urlLengthLimit: this.urlLengthLimit,\n      retry: this.retry,\n    })\n  }\n\n  /**\n   * Perform an INSERT into the table or view.\n   *\n   * By default, inserted rows are not returned. To return it, chain the call\n   * with `.select()`.\n   *\n   * @param values - The values to insert. Pass an object to insert a single row\n   * or an array to insert multiple rows.\n   *\n   * @param options - Named parameters\n   *\n   * @param options.count - Count algorithm to use to count inserted rows.\n   *\n   * `\"exact\"`: Exact but slow count algorithm. Performs a `COUNT(*)` under the\n   * hood.\n   *\n   * `\"planned\"`: Approximated but fast count algorithm. Uses the Postgres\n   * statistics under the hood.\n   *\n   * `\"estimated\"`: Uses exact count for low numbers and planned count for high\n   * numbers.\n   *\n   * @param options.defaultToNull - Make missing fields default to `null`.\n   * Otherwise, use the default value for the column. Only applies for bulk\n   * inserts.\n   *\n   * @category Database\n   *\n   * @example Create a record\n   * ```ts\n   * const { error } = await supabase\n   *   .from('countries')\n   *   .insert({ id: 1, name: 'Mordor' })\n   * ```\n   *\n   * @exampleSql Create a record\n   * ```sql\n   * create table\n   *   countries (id int8 primary key, name text);\n   * ```\n   *\n   * @exampleResponse Create a record\n   * ```json\n   * {\n   *   \"status\": 201,\n   *   \"statusText\": \"\"\n   * }\n   * ```\n   *\n   * @exampleDescription Handling errors\n   * `error.hint` from Postgres often contains the actionable fix (e.g. `\"Grant the required privileges to the current role with: GRANT INSERT ON public.countries TO anon;\"` for a `42501` permission-denied error). Log the full `error` object so it isn't hidden behind `error.message`.\n   *\n   * @example Handling errors\n   * ```js\n   * const { error } = await supabase.from('countries').insert({ id: 1, name: 'Mordor' })\n   * if (error) console.error(error)\n   * ```\n   *\n   * @example Create a record and return it\n   * ```ts\n   * const { data, error } = await supabase\n   *   .from('countries')\n   *   .insert({ id: 1, name: 'Mordor' })\n   *   .select()\n   * ```\n   *\n   * @exampleSql Create a record and return it\n   * ```sql\n   * create table\n   *   countries (id int8 primary key, name text);\n   * ```\n   *\n   * @exampleResponse Create a record and return it\n   * ```json\n   * {\n   *   \"data\": [\n   *     {\n   *       \"id\": 1,\n   *       \"name\": \"Mordor\"\n   *     }\n   *   ],\n   *   \"status\": 201,\n   *   \"statusText\": \"\"\n   * }\n   * ```\n   *\n   * @exampleDescription Bulk create\n   * A bulk create operation is handled in a single transaction.\n   * If any of the inserts fail, none of the rows are inserted.\n   *\n   * @example Bulk create\n   * ```ts\n   * const { error } = await supabase\n   *   .from('countries')\n   *   .insert([\n   *     { id: 1, name: 'Mordor' },\n   *     { id: 1, name: 'The Shire' },\n   *   ])\n   * ```\n   *\n   * @exampleSql Bulk create\n   * ```sql\n   * create table\n   *   countries (id int8 primary key, name text);\n   * ```\n   *\n   * @exampleResponse Bulk create\n   * ```json\n   * {\n   *   \"error\": {\n   *     \"code\": \"23505\",\n   *     \"details\": \"Key (id)=(1) already exists.\",\n   *     \"hint\": null,\n   *     \"message\": \"duplicate key value violates unique constraint \\\"countries_pkey\\\"\"\n   *   },\n   *   \"status\": 409,\n   *   \"statusText\": \"\"\n   * }\n   * ```\n   */\n  insert<Row extends Relation extends { Insert: unknown } ? Relation['Insert'] : never>(\n    values:\n      | RejectExcessProperties<\n          Relation extends { Insert: unknown } ? Relation['Insert'] : never,\n          Row\n        >\n      | RejectExcessProperties<\n          Relation extends { Insert: unknown } ? Relation['Insert'] : never,\n          Row\n        >[],\n    {\n      count,\n      defaultToNull = true,\n    }: {\n      count?: 'exact' | 'planned' | 'estimated' | (string & {})\n      defaultToNull?: boolean\n    } = {}\n  ): PostgrestFilterBuilder<\n    ClientOptions,\n    Schema,\n    Relation['Row'],\n    null,\n    RelationName,\n    Relationships,\n    'POST'\n  > {\n    const method = 'POST'\n    const { url, headers } = this.cloneRequestState()\n\n    if (count) {\n      headers.append('Prefer', `count=${count}`)\n    }\n    if (!defaultToNull) {\n      headers.append('Prefer', `missing=default`)\n    }\n\n    if (Array.isArray(values)) {\n      const columns = values.reduce((acc, x) => acc.concat(Object.keys(x)), [] as string[])\n      if (columns.length > 0) {\n        const uniqueColumns = [...new Set(columns)].map((column) => `\"${column}\"`)\n        url.searchParams.set('columns', uniqueColumns.join(','))\n      }\n    }\n\n    return new PostgrestFilterBuilder({\n      method,\n      url,\n      headers,\n      schema: this.schema,\n      body: values,\n      fetch: this.fetch ?? fetch,\n      urlLengthLimit: this.urlLengthLimit,\n      retry: this.retry,\n    })\n  }\n\n  /**\n   * Perform an UPSERT on the table or view. Depending on the column(s) passed\n   * to `onConflict`, `.upsert()` allows you to perform the equivalent of\n   * `.insert()` if a row with the corresponding `onConflict` columns doesn't\n   * exist, or if it does exist, perform an alternative action depending on\n   * `ignoreDuplicates`.\n   *\n   * By default, upserted rows are not returned. To return it, chain the call\n   * with `.select()`.\n   *\n   * @param values - The values to upsert with. Pass an object to upsert a\n   * single row or an array to upsert multiple rows.\n   *\n   * @param options - Named parameters\n   *\n   * @param options.onConflict - Comma-separated UNIQUE column(s) to specify how\n   * duplicate rows are determined. Two rows are duplicates if all the\n   * `onConflict` columns are equal.\n   *\n   * @param options.ignoreDuplicates - If `true`, duplicate rows are ignored. If\n   * `false`, duplicate rows are merged with existing rows.\n   *\n   * @param options.count - Count algorithm to use to count upserted rows.\n   *\n   * `\"exact\"`: Exact but slow count algorithm. Performs a `COUNT(*)` under the\n   * hood.\n   *\n   * `\"planned\"`: Approximated but fast count algorithm. Uses the Postgres\n   * statistics under the hood.\n   *\n   * `\"estimated\"`: Uses exact count for low numbers and planned count for high\n   * numbers.\n   *\n   * @param options.defaultToNull - Make missing fields default to `null`.\n   * Otherwise, use the default value for the column. This only applies when\n   * inserting new rows, not when merging with existing rows under\n   * `ignoreDuplicates: false`. This also only applies when doing bulk upserts.\n   *\n   * @example Upsert a single row using a unique key\n   * ```ts\n   * // Upserting a single row, overwriting based on the 'username' unique column\n   * const { data, error } = await supabase\n   *   .from('users')\n   *   .upsert({ username: 'supabot' }, { onConflict: 'username' })\n   *\n   * // Example response:\n   * // {\n   * //   data: [\n   * //     { id: 4, message: 'bar', username: 'supabot' }\n   * //   ],\n   * //   error: null\n   * // }\n   * ```\n   *\n   * @example Upsert with conflict resolution and exact row counting\n   * ```ts\n   * // Upserting and returning exact count\n   * const { data, error, count } = await supabase\n   *   .from('users')\n   *   .upsert(\n   *     {\n   *       id: 3,\n   *       message: 'foo',\n   *       username: 'supabot'\n   *     },\n   *     {\n   *       onConflict: 'username',\n   *       count: 'exact'\n   *     }\n   *   )\n   *\n   * // Example response:\n   * // {\n   * //   data: [\n   * //     {\n   * //       id: 42,\n   * //       handle: \"saoirse\",\n   * //       display_name: \"Saoirse\"\n   * //     }\n   * //   ],\n   * //   count: 1,\n   * //   error: null\n   * // }\n   * ```\n   *\n   * @category Database\n   *\n   * @remarks\n   * - Primary keys must be included in `values` to use upsert.\n   *\n   * @example Upsert your data\n   * ```ts\n   * const { data, error } = await supabase\n   *   .from('instruments')\n   *   .upsert({ id: 1, name: 'piano' })\n   *   .select()\n   * ```\n   *\n   * @exampleSql Upsert your data\n   * ```sql\n   * create table\n   *   instruments (id int8 primary key, name text);\n   *\n   * insert into\n   *   instruments (id, name)\n   * values\n   *   (1, 'harpsichord');\n   * ```\n   *\n   * @exampleResponse Upsert your data\n   * ```json\n   * {\n   *   \"data\": [\n   *     {\n   *       \"id\": 1,\n   *       \"name\": \"piano\"\n   *     }\n   *   ],\n   *   \"status\": 201,\n   *   \"statusText\": \"\"\n   * }\n   * ```\n   *\n   * @exampleDescription Handling errors\n   * `error.hint` from Postgres often contains the actionable fix (e.g. `\"Grant the required privileges to the current role with: GRANT INSERT, UPDATE ON public.instruments TO anon;\"` for a `42501` permission-denied error). Log the full `error` object so it isn't hidden behind `error.message`.\n   *\n   * @example Handling errors\n   * ```js\n   * const { data, error } = await supabase.from('instruments').upsert({ id: 1, name: 'piano' }).select()\n   * if (error) console.error(error)\n   * ```\n   *\n   * @example Bulk Upsert your data\n   * ```ts\n   * const { data, error } = await supabase\n   *   .from('instruments')\n   *   .upsert([\n   *     { id: 1, name: 'piano' },\n   *     { id: 2, name: 'harp' },\n   *   ])\n   *   .select()\n   * ```\n   *\n   * @exampleSql Bulk Upsert your data\n   * ```sql\n   * create table\n   *   instruments (id int8 primary key, name text);\n   *\n   * insert into\n   *   instruments (id, name)\n   * values\n   *   (1, 'harpsichord');\n   * ```\n   *\n   * @exampleResponse Bulk Upsert your data\n   * ```json\n   * {\n   *   \"data\": [\n   *     {\n   *       \"id\": 1,\n   *       \"name\": \"piano\"\n   *     },\n   *     {\n   *       \"id\": 2,\n   *       \"name\": \"harp\"\n   *     }\n   *   ],\n   *   \"status\": 201,\n   *   \"statusText\": \"\"\n   * }\n   * ```\n   *\n   * @exampleDescription Upserting into tables with constraints\n   * In the following query, `upsert()` implicitly uses the `id`\n   * (primary key) column to determine conflicts. If there is no existing\n   * row with the same `id`, `upsert()` inserts a new row, which\n   * will fail in this case as there is already a row with `handle` `\"saoirse\"`.\n   * Using the `onConflict` option, you can instruct `upsert()` to use\n   * another column with a unique constraint to determine conflicts.\n   *\n   * @example Upserting into tables with constraints\n   * ```ts\n   * const { data, error } = await supabase\n   *   .from('users')\n   *   .upsert({ id: 42, handle: 'saoirse', display_name: 'Saoirse' })\n   *   .select()\n   * ```\n   *\n   * @exampleSql Upserting into tables with constraints\n   * ```sql\n   * create table\n   *   users (\n   *     id int8 generated by default as identity primary key,\n   *     handle text not null unique,\n   *     display_name text\n   *   );\n   *\n   * insert into\n   *   users (id, handle, display_name)\n   * values\n   *   (1, 'saoirse', null);\n   * ```\n   *\n   * @exampleResponse Upserting into tables with constraints\n   * ```json\n   * {\n   *   \"error\": {\n   *     \"code\": \"23505\",\n   *     \"details\": \"Key (handle)=(saoirse) already exists.\",\n   *     \"hint\": null,\n   *     \"message\": \"duplicate key value violates unique constraint \\\"users_handle_key\\\"\"\n   *   },\n   *   \"status\": 409,\n   *   \"statusText\": \"\"\n   * }\n   * ```\n   */\n\n  upsert<Row extends Relation extends { Insert: unknown } ? Relation['Insert'] : never>(\n    values:\n      | RejectExcessProperties<\n          Relation extends { Insert: unknown } ? Relation['Insert'] : never,\n          Row\n        >\n      | RejectExcessProperties<\n          Relation extends { Insert: unknown } ? Relation['Insert'] : never,\n          Row\n        >[],\n    {\n      onConflict,\n      ignoreDuplicates = false,\n      count,\n      defaultToNull = true,\n    }: {\n      onConflict?: string\n      ignoreDuplicates?: boolean\n      count?: 'exact' | 'planned' | 'estimated' | (string & {})\n      defaultToNull?: boolean\n    } = {}\n  ): PostgrestFilterBuilder<\n    ClientOptions,\n    Schema,\n    Relation['Row'],\n    null,\n    RelationName,\n    Relationships,\n    'POST'\n  > {\n    const method = 'POST'\n    const { url, headers } = this.cloneRequestState()\n\n    headers.append('Prefer', `resolution=${ignoreDuplicates ? 'ignore' : 'merge'}-duplicates`)\n\n    if (onConflict !== undefined) url.searchParams.set('on_conflict', onConflict)\n    if (count) {\n      headers.append('Prefer', `count=${count}`)\n    }\n    if (!defaultToNull) {\n      headers.append('Prefer', 'missing=default')\n    }\n\n    if (Array.isArray(values)) {\n      const columns = values.reduce((acc, x) => acc.concat(Object.keys(x)), [] as string[])\n      if (columns.length > 0) {\n        const uniqueColumns = [...new Set(columns)].map((column) => `\"${column}\"`)\n        url.searchParams.set('columns', uniqueColumns.join(','))\n      }\n    }\n\n    return new PostgrestFilterBuilder({\n      method,\n      url,\n      headers,\n      schema: this.schema,\n      body: values,\n      fetch: this.fetch ?? fetch,\n      urlLengthLimit: this.urlLengthLimit,\n      retry: this.retry,\n    })\n  }\n\n  /**\n   * Perform an UPDATE on the table or view.\n   *\n   * By default, updated rows are not returned. To return it, chain the call\n   * with `.select()` after filters.\n   *\n   * @param values - The values to update with\n   *\n   * @param options - Named parameters\n   *\n   * @param options.count - Count algorithm to use to count updated rows.\n   *\n   * `\"exact\"`: Exact but slow count algorithm. Performs a `COUNT(*)` under the\n   * hood.\n   *\n   * `\"planned\"`: Approximated but fast count algorithm. Uses the Postgres\n   * statistics under the hood.\n   *\n   * `\"estimated\"`: Uses exact count for low numbers and planned count for high\n   * numbers.\n   *\n   * @category Database\n   *\n   * @remarks\n   * - `update()` should always be combined with [Filters](/docs/reference/javascript/using-filters) to target the item(s) you wish to update.\n   *\n   * @example Updating your data\n   * ```ts\n   * const { error } = await supabase\n   *   .from('instruments')\n   *   .update({ name: 'piano' })\n   *   .eq('id', 1)\n   * ```\n   *\n   * @exampleSql Updating your data\n   * ```sql\n   * create table\n   *   instruments (id int8 primary key, name text);\n   *\n   * insert into\n   *   instruments (id, name)\n   * values\n   *   (1, 'harpsichord');\n   * ```\n   *\n   * @exampleResponse Updating your data\n   * ```json\n   * {\n   *   \"status\": 204,\n   *   \"statusText\": \"\"\n   * }\n   * ```\n   *\n   * @exampleDescription Handling errors\n   * `error.hint` from Postgres often contains the actionable fix (e.g. `\"Grant the required privileges to the current role with: GRANT UPDATE ON public.instruments TO anon;\"` for a `42501` permission-denied error). Log the full `error` object so it isn't hidden behind `error.message`.\n   *\n   * @example Handling errors\n   * ```js\n   * const { error } = await supabase.from('instruments').update({ name: 'piano' }).eq('id', 1)\n   * if (error) console.error(error)\n   * ```\n   *\n   * @example Update a record and return it\n   * ```ts\n   * const { data, error } = await supabase\n   *   .from('instruments')\n   *   .update({ name: 'piano' })\n   *   .eq('id', 1)\n   *   .select()\n   * ```\n   *\n   * @exampleSql Update a record and return it\n   * ```sql\n   * create table\n   *   instruments (id int8 primary key, name text);\n   *\n   * insert into\n   *   instruments (id, name)\n   * values\n   *   (1, 'harpsichord');\n   * ```\n   *\n   * @exampleResponse Update a record and return it\n   * ```json\n   * {\n   *   \"data\": [\n   *     {\n   *       \"id\": 1,\n   *       \"name\": \"piano\"\n   *     }\n   *   ],\n   *   \"status\": 200,\n   *   \"statusText\": \"OK\"\n   * }\n   * ```\n   *\n   * @exampleDescription Updating JSON data\n   * Postgres offers some\n   * [operators](/docs/guides/database/json#query-the-jsonb-data) for\n   * working with JSON data. Currently, it is only possible to update the entire JSON document.\n   *\n   * @example Updating JSON data\n   * ```ts\n   * const { data, error } = await supabase\n   *   .from('users')\n   *   .update({\n   *     address: {\n   *       street: 'Melrose Place',\n   *       postcode: 90210\n   *     }\n   *   })\n   *   .eq('address->postcode', 90210)\n   *   .select()\n   * ```\n   *\n   * @exampleSql Updating JSON data\n   * ```sql\n   * create table\n   *   users (\n   *     id int8 primary key,\n   *     name text,\n   *     address jsonb\n   *   );\n   *\n   * insert into\n   *   users (id, name, address)\n   * values\n   *   (1, 'Michael', '{ \"postcode\": 90210 }');\n   * ```\n   *\n   * @exampleResponse Updating JSON data\n   * ```json\n   * {\n   *   \"data\": [\n   *     {\n   *       \"id\": 1,\n   *       \"name\": \"Michael\",\n   *       \"address\": {\n   *         \"street\": \"Melrose Place\",\n   *         \"postcode\": 90210\n   *       }\n   *     }\n   *   ],\n   *   \"status\": 200,\n   *   \"statusText\": \"OK\"\n   * }\n   * ```\n   */\n  update<Row extends Relation extends { Update: unknown } ? Relation['Update'] : never>(\n    values: RejectExcessProperties<\n      Relation extends { Update: unknown } ? Relation['Update'] : never,\n      Row\n    >,\n    {\n      count,\n    }: {\n      count?: 'exact' | 'planned' | 'estimated' | (string & {})\n    } = {}\n  ): PostgrestFilterBuilder<\n    ClientOptions,\n    Schema,\n    Relation['Row'],\n    null,\n    RelationName,\n    Relationships,\n    'PATCH'\n  > {\n    const method = 'PATCH'\n    const { url, headers } = this.cloneRequestState()\n\n    if (count) {\n      headers.append('Prefer', `count=${count}`)\n    }\n\n    return new PostgrestFilterBuilder({\n      method,\n      url,\n      headers,\n      schema: this.schema,\n      body: values,\n      fetch: this.fetch ?? fetch,\n      urlLengthLimit: this.urlLengthLimit,\n      retry: this.retry,\n    })\n  }\n\n  /**\n   * Perform a DELETE on the table or view.\n   *\n   * By default, deleted rows are not returned. To return it, chain the call\n   * with `.select()` after filters.\n   *\n   * @param options - Named parameters\n   *\n   * @param options.count - Count algorithm to use to count deleted rows.\n   *\n   * `\"exact\"`: Exact but slow count algorithm. Performs a `COUNT(*)` under the\n   * hood.\n   *\n   * `\"planned\"`: Approximated but fast count algorithm. Uses the Postgres\n   * statistics under the hood.\n   *\n   * `\"estimated\"`: Uses exact count for low numbers and planned count for high\n   * numbers.\n   *\n   * @category Database\n   *\n   * @remarks\n   * - `delete()` should always be combined with [filters](/docs/reference/javascript/using-filters) to target the item(s) you wish to delete.\n   * - If you use `delete()` with filters and you have\n   *   [RLS](/docs/learn/auth-deep-dive/auth-row-level-security) enabled, only\n   *   rows visible through `SELECT` policies are deleted. Note that by default\n   *   no rows are visible, so you need at least one `SELECT`/`ALL` policy that\n   *   makes the rows visible.\n   * - When using `delete().in()`, specify an array of values to target multiple rows with a single query. This is particularly useful for batch deleting entries that share common criteria, such as deleting users by their IDs. Ensure that the array you provide accurately represents all records you intend to delete to avoid unintended data removal.\n   *\n   * @example Delete a single record\n   * ```ts\n   * const response = await supabase\n   *   .from('countries')\n   *   .delete()\n   *   .eq('id', 1)\n   * ```\n   *\n   * @exampleSql Delete a single record\n   * ```sql\n   * create table\n   *   countries (id int8 primary key, name text);\n   *\n   * insert into\n   *   countries (id, name)\n   * values\n   *   (1, 'Mordor');\n   * ```\n   *\n   * @exampleResponse Delete a single record\n   * ```json\n   * {\n   *   \"status\": 204,\n   *   \"statusText\": \"\"\n   * }\n   * ```\n   *\n   * @exampleDescription Handling errors\n   * `error.hint` from Postgres often contains the actionable fix (e.g. `\"Grant the required privileges to the current role with: GRANT DELETE ON public.countries TO anon;\"` for a `42501` permission-denied error). Log the full `error` object so it isn't hidden behind `error.message`.\n   *\n   * @example Handling errors\n   * ```js\n   * const { error } = await supabase.from('countries').delete().eq('id', 1)\n   * if (error) console.error(error)\n   * ```\n   *\n   * @example Delete a record and return it\n   * ```ts\n   * const { data, error } = await supabase\n   *   .from('countries')\n   *   .delete()\n   *   .eq('id', 1)\n   *   .select()\n   * ```\n   *\n   * @exampleSql Delete a record and return it\n   * ```sql\n   * create table\n   *   countries (id int8 primary key, name text);\n   *\n   * insert into\n   *   countries (id, name)\n   * values\n   *   (1, 'Mordor');\n   * ```\n   *\n   * @exampleResponse Delete a record and return it\n   * ```json\n   * {\n   *   \"data\": [\n   *     {\n   *       \"id\": 1,\n   *       \"name\": \"Mordor\"\n   *     }\n   *   ],\n   *   \"status\": 200,\n   *   \"statusText\": \"OK\"\n   * }\n   * ```\n   *\n   * @example Delete multiple records\n   * ```ts\n   * const response = await supabase\n   *   .from('countries')\n   *   .delete()\n   *   .in('id', [1, 2, 3])\n   * ```\n   *\n   * @exampleSql Delete multiple records\n   * ```sql\n   * create table\n   *   countries (id int8 primary key, name text);\n   *\n   * insert into\n   *   countries (id, name)\n   * values\n   *   (1, 'Rohan'), (2, 'The Shire'), (3, 'Mordor');\n   * ```\n   *\n   * @exampleResponse Delete multiple records\n   * ```json\n   * {\n   *   \"status\": 204,\n   *   \"statusText\": \"\"\n   * }\n   * ```\n   */\n  delete({\n    count,\n  }: {\n    count?: 'exact' | 'planned' | 'estimated' | (string & {})\n  } = {}): PostgrestFilterBuilder<\n    ClientOptions,\n    Schema,\n    Relation['Row'],\n    null,\n    RelationName,\n    Relationships,\n    'DELETE'\n  > {\n    const method = 'DELETE'\n    const { url, headers } = this.cloneRequestState()\n\n    if (count) {\n      headers.append('Prefer', `count=${count}`)\n    }\n\n    return new PostgrestFilterBuilder({\n      method,\n      url,\n      headers,\n      schema: this.schema,\n      fetch: this.fetch ?? fetch,\n      urlLengthLimit: this.urlLengthLimit,\n      retry: this.retry,\n    })\n  }\n}\n", "import PostgrestQueryBuilder from './PostgrestQueryBuilder'\nimport PostgrestFilterBuilder from './PostgrestFilterBuilder'\nimport { Fetch, GenericSchema, ClientServerOptions } from './types/common/common'\nimport { GetRpcFunctionFilterBuilderByArgs } from './types/common/rpc'\nimport PostgrestError from './PostgrestError'\nimport { fetchWithRetry } from './fetchWithRetry'\nimport {\n  PostgrestOpenApiSpec,\n  PostgrestResponseFailure,\n  PostgrestSingleResponse,\n} from './types/types'\n\n/**\n * Build the error for a failed OpenAPI request. PostgREST answers with a JSON\n * error object when it produced the failure itself; proxies and disabled\n * OpenAPI output answer with plain text or an empty body, in which case the\n * body (or, failing that, the status text) becomes the message.\n */\nfunction toOpenApiError(body: string, statusText: string): PostgrestError {\n  try {\n    const parsed = JSON.parse(body)\n    if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) {\n      return new PostgrestError({\n        message: String(parsed.message ?? body),\n        details: parsed.details ?? '',\n        hint: parsed.hint ?? '',\n        code: parsed.code ?? '',\n      })\n    }\n  } catch {\n    // Not JSON; fall through to the plain-text message.\n  }\n  return new PostgrestError({ message: body || statusText, details: '', hint: '', code: '' })\n}\n\n/**\n * Build the response for a request that yielded no readable body: the fetch\n * itself rejected (no status is known, so it is 0), or the body stream failed\n * while being read (the response status is preserved).\n */\nfunction toTransportFailure(\n  cause: unknown,\n  status: number,\n  statusText: string\n): PostgrestResponseFailure {\n  const err = cause as { name?: string; message?: string } | null | undefined\n  return {\n    success: false,\n    error: new PostgrestError({\n      message: `${err?.name ?? 'FetchError'}: ${err?.message}`,\n      details: '',\n      hint: '',\n      code: '',\n    }),\n    data: null,\n    count: null,\n    status,\n    statusText,\n  }\n}\n\n/**\n * PostgREST client.\n *\n * @typeParam Database - Types for the schema from the [type\n * generator](https://supabase.com/docs/reference/javascript/next/typescript-support)\n *\n * @typeParam SchemaName - Postgres schema to switch to. Must be a string\n * literal, the same one passed to the constructor. If the schema is not\n * `\"public\"`, this must be supplied manually.\n */\nexport default class PostgrestClient<\n  Database = any,\n  ClientOptions extends ClientServerOptions = Database extends {\n    __InternalSupabase: infer I extends ClientServerOptions\n  }\n    ? I\n    : {},\n  SchemaName extends string & keyof Omit<Database, '__InternalSupabase'> =\n    'public' extends keyof Omit<Database, '__InternalSupabase'>\n      ? 'public'\n      : string & keyof Omit<Database, '__InternalSupabase'>,\n  Schema extends GenericSchema = Omit<\n    Database,\n    '__InternalSupabase'\n  >[SchemaName] extends GenericSchema\n    ? Omit<Database, '__InternalSupabase'>[SchemaName]\n    : any,\n> {\n  url: string\n  headers: Headers\n  schemaName?: SchemaName\n  fetch?: Fetch\n  urlLengthLimit: number\n\n  // Retry configuration - enabled by default\n  retry?: boolean\n\n  // TODO: Add back shouldThrowOnError once we figure out the typings\n  /**\n   * Creates a PostgREST client.\n   *\n   * @param url - URL of the PostgREST endpoint\n   * @param options - Named parameters\n   * @param options.headers - Custom headers\n   * @param options.schema - Postgres schema to switch to\n   * @param options.fetch - Custom fetch\n   * @param options.timeout - Optional timeout in milliseconds for all requests. When set, requests will automatically abort after this duration to prevent indefinite hangs.\n   * @param options.urlLengthLimit - Maximum URL length in characters before warnings/errors are triggered. Defaults to 8000.\n   * @param options.retry - Enable or disable automatic retries for transient errors.\n   *   When enabled, idempotent requests (GET, HEAD, OPTIONS) that fail with network\n   *   errors or HTTP 503/520 responses will be automatically retried up to 3 times\n   *   with exponential backoff (1s, 2s, 4s). Defaults to `true`.\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.from('profiles').select('*')\n   * ```\n   *\n   * @category Database\n   *\n   * @remarks\n   * - A `timeout` option (in milliseconds) can be set to automatically abort requests that take too long.\n   * - A `urlLengthLimit` option (default: 8000) can be set to control when URL length warnings are included in error messages for aborted requests.\n   *\n   * @example Standalone import for bundle-sensitive environments\n   * ```ts\n   * import { PostgrestClient } from '@supabase/postgrest-js'\n   *\n   * const postgrest = new PostgrestClient('https://xyzcompany.supabase.co/rest/v1', {\n   *   headers: { apikey: 'your-publishable-key' },\n   *   schema: 'public',\n   *   timeout: 30000, // 30 second timeout\n   * })\n   * ```\n   */\n  constructor(\n    url: string,\n    {\n      headers = {},\n      schema,\n      fetch,\n      timeout,\n      urlLengthLimit = 8000,\n      retry,\n    }: {\n      headers?: HeadersInit\n      schema?: SchemaName\n      fetch?: Fetch\n      timeout?: number\n      urlLengthLimit?: number\n      retry?: boolean\n    } = {}\n  ) {\n    this.url = url\n    this.headers = new Headers(headers)\n    this.schemaName = schema\n    this.urlLengthLimit = urlLengthLimit\n\n    const originalFetch = fetch ?? globalThis.fetch\n\n    // Wrap fetch with timeout if specified\n    if (timeout !== undefined && timeout > 0) {\n      this.fetch = (input, init) => {\n        const controller = new AbortController()\n        const timeoutId = setTimeout(() => controller.abort(), timeout)\n\n        // Merge abort signals if one already exists\n        const existingSignal = init?.signal\n        if (existingSignal) {\n          // If the existing signal is already aborted, use it directly\n          if (existingSignal.aborted) {\n            clearTimeout(timeoutId)\n            return originalFetch(input, init)\n          }\n\n          // Listen to existing signal and abort our controller too\n          const abortHandler = () => {\n            clearTimeout(timeoutId)\n            controller.abort()\n          }\n          existingSignal.addEventListener('abort', abortHandler, { once: true })\n\n          return originalFetch(input, {\n            ...init,\n            signal: controller.signal,\n          }).finally(() => {\n            clearTimeout(timeoutId)\n            existingSignal.removeEventListener('abort', abortHandler)\n          })\n        }\n\n        return originalFetch(input, {\n          ...init,\n          signal: controller.signal,\n        }).finally(() => clearTimeout(timeoutId))\n      }\n    } else {\n      this.fetch = originalFetch\n    }\n    this.retry = retry\n  }\n  /**\n   * Perform a query on a table or a view.\n   *\n   * @param relation - The table or view name to query\n   *\n   * @category Database\n   */\n  from<\n    TableName extends string & keyof Schema['Tables'],\n    Table extends Schema['Tables'][TableName],\n  >(relation: TableName): PostgrestQueryBuilder<ClientOptions, Schema, Table, TableName>\n  from<ViewName extends string & keyof Schema['Views'], View extends Schema['Views'][ViewName]>(\n    relation: ViewName\n  ): PostgrestQueryBuilder<ClientOptions, Schema, View, ViewName>\n  from(\n    relation: (string & keyof Schema['Tables']) | (string & keyof Schema['Views'])\n  ): PostgrestQueryBuilder<ClientOptions, Schema, any, any> {\n    if (!relation || typeof relation !== 'string' || relation.trim() === '') {\n      throw new Error('Invalid relation name: relation must be a non-empty string.')\n    }\n\n    const url = new URL(`${this.url}/${relation}`)\n    return new PostgrestQueryBuilder(url, {\n      headers: new Headers(this.headers),\n      schema: this.schemaName,\n      fetch: this.fetch,\n      urlLengthLimit: this.urlLengthLimit,\n      retry: this.retry,\n    })\n  }\n\n  /**\n   * Select a schema to query or perform an function (rpc) call.\n   *\n   * The schema needs to be on the list of exposed schemas inside Supabase.\n   *\n   * @param schema - The schema to query\n   *\n   * @category Database\n   */\n  schema<DynamicSchema extends string & keyof Omit<Database, '__InternalSupabase'>>(\n    schema: DynamicSchema\n  ): PostgrestClient<\n    Database,\n    ClientOptions,\n    DynamicSchema,\n    Database[DynamicSchema] extends GenericSchema ? Database[DynamicSchema] : any\n  > {\n    return new PostgrestClient(this.url, {\n      headers: this.headers,\n      schema,\n      fetch: this.fetch,\n      urlLengthLimit: this.urlLengthLimit,\n      retry: this.retry,\n    })\n  }\n\n  /**\n   * Fetch the OpenAPI description PostgREST publishes for this client's schema.\n   *\n   * The document lists only the tables, views and functions the caller's role\n   * holds privileges on; PostgREST applies that filtering server-side. The\n   * schema is the one this client was created with, so call `.schema()` first\n   * to describe a different one. Transient failures are retried according to\n   * the client's `retry` option, like any other idempotent request.\n   *\n   * @example\n   * ```ts\n   * const { data, error } = await supabase.getOpenApiSpec()\n   * ```\n   *\n   * @example Describe a schema other than the client default\n   * ```ts\n   * const { data, error } = await supabase.schema('billing').getOpenApiSpec()\n   * ```\n   *\n   * @category Database\n   */\n  async getOpenApiSpec(): Promise<PostgrestSingleResponse<PostgrestOpenApiSpec>> {\n    const headers = new Headers(this.headers)\n    headers.set('Accept', 'application/openapi+json')\n    if (this.schemaName) {\n      headers.set('Accept-Profile', this.schemaName)\n    }\n\n    // Headers reach the fetch implementation as a plain object, as in\n    // PostgrestBuilder: React Native's XHR-based fetch drops headers that are\n    // supplied as a Headers instance.\n    const requestHeaders: Record<string, string> = {}\n    headers.forEach((value, key) => {\n      requestHeaders[key] = value\n    })\n\n    const fetchImpl = this.fetch ?? globalThis.fetch\n    let res: Response\n    try {\n      res = await fetchWithRetry(\n        fetchImpl,\n        `${this.url}/`,\n        { method: 'GET', headers: requestHeaders },\n        this.retry ?? true\n      )\n    } catch (fetchError) {\n      return toTransportFailure(fetchError, 0, '')\n    }\n\n    let body: string\n    try {\n      body = await res.text()\n    } catch (readError) {\n      return toTransportFailure(readError, res.status, res.statusText)\n    }\n\n    if (res.ok) {\n      try {\n        return {\n          success: true,\n          error: null,\n          data: JSON.parse(body) as PostgrestOpenApiSpec,\n          count: null,\n          status: res.status,\n          statusText: res.statusText,\n        }\n      } catch {\n        // A 2xx status does not guarantee a JSON body; report it like a failure.\n      }\n    }\n\n    return {\n      success: false,\n      error: toOpenApiError(body, res.statusText),\n      data: null,\n      count: null,\n      status: res.status,\n      statusText: res.statusText,\n    }\n  }\n\n  /**\n   * Perform a function call.\n   *\n   * @param fn - The function name to call\n   * @param args - The arguments to pass to the function call\n   * @param options - Named parameters\n   * @param options.head - When set to `true`, `data` will not be returned.\n   * Useful if you only need the count.\n   * @param options.get - When set to `true`, the function will be called with\n   * read-only access mode.\n   * @param options.count - Count algorithm to use to count rows returned by the\n   * function. Only applicable for [set-returning\n   * functions](https://www.postgresql.org/docs/current/functions-srf.html).\n   *\n   * `\"exact\"`: Exact but slow count algorithm. Performs a `COUNT(*)` under the\n   * hood.\n   *\n   * `\"planned\"`: Approximated but fast count algorithm. Uses the Postgres\n   * statistics under the hood.\n   *\n   * `\"estimated\"`: Uses exact count for low numbers and planned count for high\n   * numbers.\n   *\n   * @example\n   * ```ts\n   * // For cross-schema functions where type inference fails, use overrideTypes:\n   * const { data } = await supabase\n   *   .schema('schema_b')\n   *   .rpc('function_a', {})\n   *   .overrideTypes<{ id: string; user_id: string }[]>()\n   * ```\n   *\n   * @category Database\n   *\n   * @example Call a Postgres function without arguments\n   * ```ts\n   * const { data, error } = await supabase.rpc('hello_world')\n   * ```\n   *\n   * @exampleSql Call a Postgres function without arguments\n   * ```sql\n   * create function hello_world() returns text as $$\n   *   select 'Hello world';\n   * $$ language sql;\n   * ```\n   *\n   * @exampleResponse Call a Postgres function without arguments\n   * ```json\n   * {\n   *   \"data\": \"Hello world\",\n   *   \"status\": 200,\n   *   \"statusText\": \"OK\"\n   * }\n   * ```\n   *\n   * @example Call a Postgres function with arguments\n   * ```ts\n   * const { data, error } = await supabase.rpc('echo', { say: '👋' })\n   * ```\n   *\n   * @exampleSql Call a Postgres function with arguments\n   * ```sql\n   * create function echo(say text) returns text as $$\n   *   select say;\n   * $$ language sql;\n   * ```\n   *\n   * @exampleResponse Call a Postgres function with arguments\n   * ```json\n   *   {\n   *     \"data\": \"👋\",\n   *     \"status\": 200,\n   *     \"statusText\": \"OK\"\n   *   }\n   *\n   * ```\n   *\n   * @exampleDescription Bulk processing\n   * You can process large payloads by passing in an array as an argument.\n   *\n   * @example Bulk processing\n   * ```ts\n   * const { data, error } = await supabase.rpc('add_one_each', { arr: [1, 2, 3] })\n   * ```\n   *\n   * @exampleSql Bulk processing\n   * ```sql\n   * create function add_one_each(arr int[]) returns int[] as $$\n   *   select array_agg(n + 1) from unnest(arr) as n;\n   * $$ language sql;\n   * ```\n   *\n   * @exampleResponse Bulk processing\n   * ```json\n   * {\n   *   \"data\": [\n   *     2,\n   *     3,\n   *     4\n   *   ],\n   *   \"status\": 200,\n   *   \"statusText\": \"OK\"\n   * }\n   * ```\n   *\n   * @exampleDescription Call a Postgres function with filters\n   * Postgres functions that return tables can also be combined with [Filters](/docs/reference/javascript/using-filters) and [Modifiers](/docs/reference/javascript/using-modifiers).\n   *\n   * @example Call a Postgres function with filters\n   * ```ts\n   * const { data, error } = await supabase\n   *   .rpc('list_stored_countries')\n   *   .eq('id', 1)\n   *   .single()\n   * ```\n   *\n   * @exampleSql Call a Postgres function with filters\n   * ```sql\n   * create table\n   *   countries (id int8 primary key, name text);\n   *\n   * insert into\n   *   countries (id, name)\n   * values\n   *   (1, 'Rohan'),\n   *   (2, 'The Shire');\n   *\n   * create function list_stored_countries() returns setof countries as $$\n   *   select * from countries;\n   * $$ language sql;\n   * ```\n   *\n   * @exampleResponse Call a Postgres function with filters\n   * ```json\n   * {\n   *   \"data\": {\n   *     \"id\": 1,\n   *     \"name\": \"Rohan\"\n   *   },\n   *   \"status\": 200,\n   *   \"statusText\": \"OK\"\n   * }\n   * ```\n   *\n   * @example Call a read-only Postgres function\n   * ```ts\n   * const { data, error } = await supabase.rpc('hello_world', undefined, { get: true })\n   * ```\n   *\n   * @exampleSql Call a read-only Postgres function\n   * ```sql\n   * create function hello_world() returns text as $$\n   *   select 'Hello world';\n   * $$ language sql;\n   * ```\n   *\n   * @exampleResponse Call a read-only Postgres function\n   * ```json\n   * {\n   *   \"data\": \"Hello world\",\n   *   \"status\": 200,\n   *   \"statusText\": \"OK\"\n   * }\n   * ```\n   */\n  rpc<\n    FnName extends string & keyof Schema['Functions'],\n    Args extends Schema['Functions'][FnName]['Args'] = never,\n    FilterBuilder extends GetRpcFunctionFilterBuilderByArgs<Schema, FnName, Args> =\n      GetRpcFunctionFilterBuilderByArgs<Schema, FnName, Args>,\n  >(\n    fn: FnName,\n    args: Args = {} as Args,\n    {\n      head = false,\n      get = false,\n      count,\n    }: {\n      head?: boolean\n      get?: boolean\n      count?: 'exact' | 'planned' | 'estimated' | (string & {})\n    } = {}\n  ): PostgrestFilterBuilder<\n    ClientOptions,\n    Schema,\n    FilterBuilder['Row'],\n    FilterBuilder['Result'],\n    FilterBuilder['RelationName'],\n    FilterBuilder['Relationships'],\n    'RPC'\n  > {\n    let method: 'HEAD' | 'GET' | 'POST'\n    const url = new URL(`${this.url}/rpc/${fn}`)\n    let body: unknown | undefined\n    // objects/arrays-of-objects can't be serialized to URL params, use POST + return=minimal instead\n    const _isObject = (v: unknown): boolean =>\n      v !== null && typeof v === 'object' && (!Array.isArray(v) || v.some(_isObject))\n    const _hasObjectArg = head && Object.values(args as object).some(_isObject)\n    if (_hasObjectArg) {\n      method = 'POST'\n      body = args\n    } else if (head || get) {\n      method = head ? 'HEAD' : 'GET'\n      Object.entries(args)\n        // params with undefined value needs to be filtered out, otherwise it'll\n        // show up as `?param=undefined`\n        .filter(([_, value]) => value !== undefined)\n        // array values need special syntax\n        .map(([name, value]) => [name, Array.isArray(value) ? `{${value.join(',')}}` : `${value}`])\n        .forEach(([name, value]) => {\n          url.searchParams.append(name, value)\n        })\n    } else {\n      method = 'POST'\n      body = args\n    }\n\n    const headers = new Headers(this.headers)\n    if (_hasObjectArg) {\n      headers.set('Prefer', count ? `count=${count},return=minimal` : 'return=minimal')\n    } else if (count) {\n      headers.set('Prefer', `count=${count}`)\n    }\n\n    return new PostgrestFilterBuilder({\n      method,\n      url,\n      headers,\n      schema: this.schemaName,\n      body,\n      fetch: this.fetch ?? fetch,\n      urlLengthLimit: this.urlLengthLimit,\n      retry: this.retry,\n    })\n  }\n}\n", "import PostgrestClient from './PostgrestClient'\nimport PostgrestQueryBuilder from './PostgrestQueryBuilder'\nimport PostgrestFilterBuilder from './PostgrestFilterBuilder'\nimport PostgrestTransformBuilder from './PostgrestTransformBuilder'\nimport PostgrestBuilder from './PostgrestBuilder'\nimport PostgrestError from './PostgrestError'\n\nexport {\n  PostgrestClient,\n  PostgrestQueryBuilder,\n  PostgrestFilterBuilder,\n  PostgrestTransformBuilder,\n  PostgrestBuilder,\n  PostgrestError,\n}\nexport default {\n  PostgrestClient,\n  PostgrestQueryBuilder,\n  PostgrestFilterBuilder,\n  PostgrestTransformBuilder,\n  PostgrestBuilder,\n  PostgrestError,\n}\nexport type {\n  PostgrestResponse,\n  PostgrestResponseFailure,\n  PostgrestResponseSuccess,\n  PostgrestSingleResponse,\n  PostgrestMaybeSingleResponse,\n  PostgrestOpenApiSpec,\n} from './types/types'\nexport type { ClientServerOptions as PostgrestClientOptions } from './types/common/common'\n// https://github.com/supabase/postgrest-js/issues/551\n// To be replaced with a helper type that only uses public types\nexport type { GetResult as UnstableGetResult } from './select-query-parser/result'\n", "export interface WebSocketLike {\n  readonly CONNECTING: number\n  readonly OPEN: number\n  readonly CLOSING: number\n  readonly CLOSED: number\n  readonly readyState: number\n  readonly url: string\n  readonly protocol: string\n\n  /**\n   * Closes the socket, optionally providing a close code and reason.\n   */\n  close(code?: number, reason?: string): void\n  /**\n   * Sends data through the socket using the underlying implementation.\n   */\n  send(data: string | ArrayBufferLike | Blob | ArrayBufferView): void\n\n  onopen: ((this: any, ev: Event) => any) | null\n  onmessage: ((this: any, ev: MessageEvent) => any) | null\n  onclose: ((this: any, ev: CloseEvent) => any) | null\n  onerror: ((this: any, ev: Event) => any) | null\n\n  /**\n   * Registers an event listener on the socket (compatible with browser WebSocket API).\n   */\n  addEventListener(type: string, listener: EventListener): void\n  /**\n   * Removes a previously registered event listener.\n   */\n  removeEventListener(type: string, listener: EventListener): void\n\n  // Add additional properties that may exist on WebSocket implementations\n  binaryType?: string\n  bufferedAmount?: number\n  extensions?: string\n  dispatchEvent?: (event: Event) => boolean\n}\n\nexport interface WebSocketEnvironment {\n  type: 'native' | 'cloudflare' | 'unsupported'\n  /** WebSocket constructor for this environment, if available. */\n  wsConstructor?: typeof WebSocket\n  error?: string\n  workaround?: string\n}\n\n/**\n * Extended globalThis with optional runtime-specific properties\n * that may or may not exist depending on the environment.\n */\ninterface RuntimeGlobals {\n  WebSocket?: { new (url: string, protocols?: string | string[]): WebSocketLike }\n  WebSocketPair?: unknown\n  EdgeRuntime?: unknown\n}\n\n/**\n * Utilities for creating WebSocket instances across runtimes.\n */\nexport class WebSocketFactory {\n  /**\n   * Static-only utility \u2013 prevent instantiation.\n   */\n  private constructor() {}\n  private static detectEnvironment(): WebSocketEnvironment {\n    if (typeof WebSocket !== 'undefined') {\n      return { type: 'native', wsConstructor: WebSocket }\n    }\n\n    const gt = globalThis as typeof globalThis & RuntimeGlobals\n    if (typeof globalThis !== 'undefined' && typeof gt.WebSocket !== 'undefined') {\n      return { type: 'native', wsConstructor: gt.WebSocket as typeof WebSocket }\n    }\n\n    const gl =\n      typeof global !== 'undefined' ? (global as typeof global & RuntimeGlobals) : undefined\n    if (gl && typeof gl.WebSocket !== 'undefined') {\n      return { type: 'native', wsConstructor: gl.WebSocket as typeof WebSocket }\n    }\n\n    if (\n      typeof globalThis !== 'undefined' &&\n      typeof gt.WebSocketPair !== 'undefined' &&\n      typeof globalThis.WebSocket === 'undefined'\n    ) {\n      return {\n        type: 'cloudflare',\n        error:\n          'Cloudflare Workers detected. WebSocket clients are not supported in Cloudflare Workers.',\n        workaround:\n          'Use Cloudflare Workers WebSocket API for server-side WebSocket handling, or deploy to a different runtime.',\n      }\n    }\n\n    if (\n      (typeof globalThis !== 'undefined' && gt.EdgeRuntime) ||\n      (typeof navigator !== 'undefined' && navigator.userAgent?.includes('Vercel-Edge'))\n    ) {\n      return {\n        type: 'unsupported',\n        error:\n          'Edge runtime detected (Vercel Edge/Netlify Edge). WebSockets are not supported in edge functions.',\n        workaround:\n          'Use serverless functions or a different deployment target for WebSocket functionality.',\n      }\n    }\n\n    // Use dynamic property access to avoid Next.js Edge Runtime static analysis warnings\n    const _process = (globalThis as Record<string, unknown>)['process'] as\n      | { versions?: { node?: string } }\n      | undefined\n    if (_process) {\n      const processVersions = _process['versions']\n      if (processVersions && processVersions['node']) {\n        // Reaching here means an earlier check did not find a native WebSocket,\n        // so this Node.js process is missing the global WebSocket (Node.js 22+).\n        return {\n          type: 'unsupported',\n          error: 'Node.js detected but native WebSocket not found.',\n          workaround:\n            'Ensure you are running Node.js 22+ or provide a WebSocket implementation via the transport option.',\n        }\n      }\n    }\n\n    return {\n      type: 'unsupported',\n      error: 'Unknown JavaScript runtime without WebSocket support.',\n      workaround:\n        \"Ensure you're running in a supported environment (browser, Node.js, Deno) or provide a custom WebSocket implementation.\",\n    }\n  }\n\n  /**\n   * Returns the best available WebSocket constructor for the current runtime.\n   *\n   * @category Realtime\n   *\n   * @example Example with error handling\n   * ```ts\n   * try {\n   *   const WS = WebSocketFactory.getWebSocketConstructor()\n   *   const socket = new WS('wss://example.com/socket')\n   * } catch (error) {\n   *   console.error('WebSocket not available in this environment.', error)\n   * }\n   * ```\n   */\n  public static getWebSocketConstructor(): typeof WebSocket {\n    const env = this.detectEnvironment()\n    if (env.wsConstructor) {\n      return env.wsConstructor\n    }\n    let errorMessage = env.error || 'WebSocket not supported in this environment.'\n    if (env.workaround) {\n      errorMessage += `\\n\\nSuggested solution: ${env.workaround}`\n    }\n    throw new Error(errorMessage)\n  }\n\n  /**\n   * Detects whether the runtime can establish WebSocket connections.\n   *\n   * @category Realtime\n   *\n   * @example Example in a Node.js script\n   * ```ts\n   * if (!WebSocketFactory.isWebSocketSupported()) {\n   *   console.error('WebSockets are required for this script.')\n   *   process.exitCode = 1\n   * }\n   * ```\n   */\n  public static isWebSocketSupported(): boolean {\n    try {\n      const env = this.detectEnvironment()\n      return env.type === 'native'\n    } catch {\n      return false\n    }\n  }\n}\n\nexport default WebSocketFactory\n", "// 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.118.0'\n", "import { version } from './version'\nimport type {\n  SocketState,\n  ChannelState,\n  ChannelEvent as PhoenixChannelEvent,\n  Transport,\n  Vsn,\n} from '../phoenix/types'\n\nexport type { SocketState, ChannelState, Transport }\n\nexport const DEFAULT_VERSION = `realtime-js/${version}`\n\nexport const VSN_1_0_0: Vsn = '1.0.0'\nexport const VSN_2_0_0: Vsn = '2.0.0'\nexport const DEFAULT_VSN: Vsn = VSN_2_0_0\n\nexport const VERSION = version\n\nexport const DEFAULT_TIMEOUT = 10000\n\n/** Mirrors the Realtime server's own default for `postgres_changes_options.timeout`. */\nexport const DEFAULT_POSTGRES_CHANGES_WAIT_TIMEOUT = 15000\n\n/**\n * Headroom added to the join timeout when waiting on postgres_changes, covering the\n * CHANNEL_ERROR_BACKOFF_MS sleep (5s by default) the server takes before rejecting a join.\n */\nexport const POSTGRES_CHANGES_WAIT_ERROR_GRACE = 10000\n\nexport const WS_CLOSE_NORMAL = 1000\nexport const MAX_PUSH_BUFFER_SIZE = 100\n\nexport const SOCKET_STATES = {\n  connecting: 0,\n  open: 1,\n  closing: 2,\n  closed: 3,\n} as const\n\nexport const CHANNEL_STATES = {\n  closed: 'closed',\n  errored: 'errored',\n  joined: 'joined',\n  joining: 'joining',\n  leaving: 'leaving',\n} as const\n\nexport type ChannelEvent = PhoenixChannelEvent | 'access_token'\n\nexport const CHANNEL_EVENTS = {\n  close: 'phx_close',\n  error: 'phx_error',\n  join: 'phx_join',\n  reply: 'phx_reply',\n  leave: 'phx_leave',\n  access_token: 'access_token',\n} as const\n\nexport const TRANSPORTS = {\n  websocket: 'websocket',\n} as const\n\nexport type ConnectionState = 'connecting' | 'open' | 'closing' | 'closed' | (string & {})\n\nexport const CONNECTION_STATE = {\n  connecting: 'connecting',\n  open: 'open',\n  closing: 'closing',\n  closed: 'closed',\n} as const\n", "// This file draws heavily from https://github.com/phoenixframework/phoenix/commit/cf098e9cf7a44ee6479d31d911a97d3c7430c6fe\n// License: https://github.com/phoenixframework/phoenix/blob/master/LICENSE.md\nexport type Msg<T> = {\n  join_ref?: string | null\n  ref?: string | null\n  topic: string\n  event: string\n  payload: T\n}\n\nexport default class Serializer {\n  HEADER_LENGTH = 1\n  USER_BROADCAST_PUSH_META_LENGTH = 6\n  KINDS = { userBroadcastPush: 3, userBroadcast: 4 }\n  BINARY_ENCODING = 0\n  JSON_ENCODING = 1\n  BROADCAST_EVENT = 'broadcast'\n\n  allowedMetadataKeys: string[] = []\n\n  constructor(allowedMetadataKeys?: string[] | null) {\n    this.allowedMetadataKeys = allowedMetadataKeys ?? []\n  }\n\n  encode(msg: Msg<{ [key: string]: any }>, callback: (result: ArrayBuffer | string) => any) {\n    if (\n      msg.event === this.BROADCAST_EVENT &&\n      !(msg.payload instanceof ArrayBuffer) &&\n      typeof msg.payload.event === 'string'\n    ) {\n      return callback(\n        this._binaryEncodeUserBroadcastPush(msg as Msg<{ event: string } & { [key: string]: any }>)\n      )\n    }\n\n    let payload = [msg.join_ref, msg.ref, msg.topic, msg.event, msg.payload]\n    return callback(JSON.stringify(payload))\n  }\n\n  private _binaryEncodeUserBroadcastPush(message: Msg<{ event: string } & { [key: string]: any }>) {\n    if (this._isArrayBuffer(message.payload?.payload)) {\n      return this._encodeBinaryUserBroadcastPush(message)\n    } else {\n      return this._encodeJsonUserBroadcastPush(message)\n    }\n  }\n\n  private _encodeBinaryUserBroadcastPush(message: Msg<{ event: string } & { [key: string]: any }>) {\n    const userPayload = message.payload?.payload ?? new ArrayBuffer(0)\n    return this._encodeUserBroadcastPush(message, this.BINARY_ENCODING, userPayload)\n  }\n\n  private _encodeJsonUserBroadcastPush(message: Msg<{ event: string } & { [key: string]: any }>) {\n    const userPayload = message.payload?.payload ?? {}\n    const encoder = new TextEncoder()\n    const encodedUserPayload = encoder.encode(JSON.stringify(userPayload)).buffer\n    return this._encodeUserBroadcastPush(message, this.JSON_ENCODING, encodedUserPayload)\n  }\n\n  private _encodeUserBroadcastPush(\n    message: Msg<{ event: string } & { [key: string]: any }>,\n    encodingType: number,\n    encodedPayload: ArrayBuffer\n  ) {\n    // Encode each header field as UTF-8. The length prefixes are byte counts and\n    // the decode side uses TextDecoder (UTF-8), so measuring with String.length\n    // and writing with charCodeAt would corrupt any multi-byte character (e.g.\n    // accents or emoji) and desynchronize the buffer.\n    const encoder = new TextEncoder()\n    const topic = encoder.encode(message.topic)\n    const ref = encoder.encode(message.ref ?? '')\n    const joinRef = encoder.encode(message.join_ref ?? '')\n    const userEvent = encoder.encode(message.payload.event)\n\n    // Filter metadata based on allowed keys\n    const rest = this.allowedMetadataKeys\n      ? this._pick(message.payload, this.allowedMetadataKeys)\n      : {}\n\n    const metadata = encoder.encode(Object.keys(rest).length === 0 ? '' : JSON.stringify(rest))\n\n    // Validate byte lengths don't exceed uint8 max value (255)\n    if (joinRef.length > 255) {\n      throw new Error(`joinRef length ${joinRef.length} exceeds maximum of 255`)\n    }\n    if (ref.length > 255) {\n      throw new Error(`ref length ${ref.length} exceeds maximum of 255`)\n    }\n    if (topic.length > 255) {\n      throw new Error(`topic length ${topic.length} exceeds maximum of 255`)\n    }\n    if (userEvent.length > 255) {\n      throw new Error(`userEvent length ${userEvent.length} exceeds maximum of 255`)\n    }\n    if (metadata.length > 255) {\n      throw new Error(`metadata length ${metadata.length} exceeds maximum of 255`)\n    }\n\n    const metaLength =\n      this.USER_BROADCAST_PUSH_META_LENGTH +\n      joinRef.length +\n      ref.length +\n      topic.length +\n      userEvent.length +\n      metadata.length\n\n    const header = new ArrayBuffer(this.HEADER_LENGTH + metaLength)\n    const view = new DataView(header)\n    const bytes = new Uint8Array(header)\n    let offset = 0\n\n    view.setUint8(offset++, this.KINDS.userBroadcastPush) // kind\n    view.setUint8(offset++, joinRef.length)\n    view.setUint8(offset++, ref.length)\n    view.setUint8(offset++, topic.length)\n    view.setUint8(offset++, userEvent.length)\n    view.setUint8(offset++, metadata.length)\n    view.setUint8(offset++, encodingType)\n    bytes.set(joinRef, offset)\n    offset += joinRef.length\n    bytes.set(ref, offset)\n    offset += ref.length\n    bytes.set(topic, offset)\n    offset += topic.length\n    bytes.set(userEvent, offset)\n    offset += userEvent.length\n    bytes.set(metadata, offset)\n    offset += metadata.length\n\n    var combined = new Uint8Array(header.byteLength + encodedPayload.byteLength)\n    combined.set(new Uint8Array(header), 0)\n    combined.set(new Uint8Array(encodedPayload), header.byteLength)\n\n    return combined.buffer\n  }\n\n  decode(rawPayload: ArrayBuffer | string, callback: Function) {\n    if (this._isArrayBuffer(rawPayload)) {\n      let result = this._binaryDecode(rawPayload as ArrayBuffer)\n      return callback(result)\n    }\n\n    if (typeof rawPayload === 'string') {\n      const jsonPayload = JSON.parse(rawPayload)\n      const [join_ref, ref, topic, event, payload] = jsonPayload\n      return callback({ join_ref, ref, topic, event, payload })\n    }\n\n    return callback({})\n  }\n\n  private _binaryDecode(buffer: ArrayBuffer) {\n    const view = new DataView(buffer)\n    const kind = view.getUint8(0)\n    const decoder = new TextDecoder()\n    switch (kind) {\n      case this.KINDS.userBroadcast:\n        return this._decodeUserBroadcast(buffer, view, decoder)\n    }\n  }\n\n  private _decodeUserBroadcast(\n    buffer: ArrayBuffer,\n    view: DataView,\n    decoder: TextDecoder\n  ): {\n    join_ref: null\n    ref: null\n    topic: string\n    event: string\n    payload: { [key: string]: any }\n  } {\n    const topicSize = view.getUint8(1)\n    const userEventSize = view.getUint8(2)\n    const metadataSize = view.getUint8(3)\n    const payloadEncoding = view.getUint8(4)\n\n    let offset = this.HEADER_LENGTH + 4\n    const topic = decoder.decode(buffer.slice(offset, offset + topicSize))\n    offset = offset + topicSize\n    const userEvent = decoder.decode(buffer.slice(offset, offset + userEventSize))\n    offset = offset + userEventSize\n    const metadata = decoder.decode(buffer.slice(offset, offset + metadataSize))\n    offset = offset + metadataSize\n\n    const payload = buffer.slice(offset, buffer.byteLength)\n    const parsedPayload =\n      payloadEncoding === this.JSON_ENCODING ? JSON.parse(decoder.decode(payload)) : payload\n\n    const data: { [key: string]: any } = {\n      type: this.BROADCAST_EVENT,\n      event: userEvent,\n      payload: parsedPayload,\n    }\n\n    // Metadata is optional and always JSON encoded\n    if (metadataSize > 0) {\n      data['meta'] = JSON.parse(metadata)\n    }\n\n    return { join_ref: null, ref: null, topic: topic, event: this.BROADCAST_EVENT, payload: data }\n  }\n\n  private _isArrayBuffer(buffer: any): boolean {\n    return buffer instanceof ArrayBuffer || buffer?.constructor?.name === 'ArrayBuffer'\n  }\n\n  private _pick(obj: Record<string, any> | null | undefined, keys: string[]): Record<string, any> {\n    if (!obj || typeof obj !== 'object') {\n      return {}\n    }\n    return Object.fromEntries(Object.entries(obj).filter(([key]) => keys.includes(key)))\n  }\n}\n", "/**\n * Helpers to convert the change Payload into native JS types.\n */\n\n// Adapted from epgsql (src/epgsql_binary.erl), this module licensed under\n// 3-clause BSD found here: https://raw.githubusercontent.com/epgsql/epgsql/devel/LICENSE\n\nexport enum PostgresTypes {\n  abstime = 'abstime',\n  bool = 'bool',\n  date = 'date',\n  daterange = 'daterange',\n  float4 = 'float4',\n  float8 = 'float8',\n  int2 = 'int2',\n  int4 = 'int4',\n  int4range = 'int4range',\n  int8 = 'int8',\n  int8range = 'int8range',\n  json = 'json',\n  jsonb = 'jsonb',\n  money = 'money',\n  numeric = 'numeric',\n  oid = 'oid',\n  reltime = 'reltime',\n  text = 'text',\n  time = 'time',\n  timestamp = 'timestamp',\n  timestamptz = 'timestamptz',\n  timetz = 'timetz',\n  tsrange = 'tsrange',\n  tstzrange = 'tstzrange',\n}\n\ntype Columns = {\n  name: string // the column name. eg: \"user_id\"\n  type: string // the column type. eg: \"uuid\"\n  flags?: string[] // any special flags for the column. eg: [\"key\"]\n  type_modifier?: number // the type modifier. eg: 4294967295\n}[]\n\ntype BaseValue = null | string | number | boolean\ntype RecordValue = BaseValue | BaseValue[]\n\ntype Record = {\n  [key: string]: RecordValue\n}\n\n/**\n * Takes an array of columns and an object of string values then converts each string value\n * to its mapped type.\n *\n * @param {{name: String, type: String}[]} columns\n * @param {Object} record\n * @param {Object} options The map of various options that can be applied to the mapper\n * @param {Array} options.skipTypes The array of types that should not be converted\n *\n * @example convertChangeData([{name: 'first_name', type: 'text'}, {name: 'age', type: 'int4'}], {first_name: 'Paul', age:'33'}, {})\n * //=>{ first_name: 'Paul', age: 33 }\n */\nexport const convertChangeData = (\n  columns: Columns,\n  record: Record | null,\n  options: { skipTypes?: string[] } = {}\n): Record => {\n  const skipTypes = options.skipTypes ?? []\n\n  if (!record) {\n    return {}\n  }\n\n  return Object.keys(record).reduce((acc, rec_key) => {\n    acc[rec_key] = convertColumn(rec_key, columns, record, skipTypes)\n    return acc\n  }, {} as Record)\n}\n\n/**\n * Converts the value of an individual column.\n *\n * @param {String} columnName The column that you want to convert\n * @param {{name: String, type: String}[]} columns All of the columns\n * @param {Object} record The map of string values\n * @param {Array} skipTypes An array of types that should not be converted\n * @return {object} Useless information\n *\n * @example convertColumn('age', [{name: 'first_name', type: 'text'}, {name: 'age', type: 'int4'}], {first_name: 'Paul', age: '33'}, [])\n * //=> 33\n * @example convertColumn('age', [{name: 'first_name', type: 'text'}, {name: 'age', type: 'int4'}], {first_name: 'Paul', age: '33'}, ['int4'])\n * //=> \"33\"\n */\nexport const convertColumn = (\n  columnName: string,\n  columns: Columns,\n  record: Record,\n  skipTypes: string[]\n): RecordValue => {\n  const column = columns.find((x) => x.name === columnName)\n  const colType = column?.type\n  const value = record[columnName]\n\n  if (colType && !skipTypes.includes(colType)) {\n    return convertCell(colType, value)\n  }\n\n  return noop(value)\n}\n\n/**\n * If the value of the cell is `null`, returns null.\n * Otherwise converts the string value to the correct type.\n * @param {String} type A postgres column type\n * @param {String} value The cell value\n *\n * @example convertCell('bool', 't')\n * //=> true\n * @example convertCell('int8', '10')\n * //=> 10\n * @example convertCell('_int4', '{1,2,3,4}')\n * //=> [1,2,3,4]\n */\nexport const convertCell = (type: string, value: RecordValue): RecordValue => {\n  // if data type is an array\n  if (type.charAt(0) === '_') {\n    const dataType = type.slice(1, type.length)\n    return toArray(value, dataType)\n  }\n\n  // If not null, convert to correct type.\n  switch (type) {\n    case PostgresTypes.bool:\n      return toBoolean(value)\n    case PostgresTypes.float4:\n    case PostgresTypes.float8:\n    case PostgresTypes.int2:\n    case PostgresTypes.int4:\n    case PostgresTypes.int8:\n    case PostgresTypes.numeric:\n    case PostgresTypes.oid:\n      return toNumber(value)\n    case PostgresTypes.json:\n    case PostgresTypes.jsonb:\n      return toJson(value)\n    case PostgresTypes.timestamp:\n      return toTimestampString(value) // Format to be consistent with PostgREST\n    case PostgresTypes.abstime: // To allow users to cast it based on Timezone\n    case PostgresTypes.date: // To allow users to cast it based on Timezone\n    case PostgresTypes.daterange:\n    case PostgresTypes.int4range:\n    case PostgresTypes.int8range:\n    case PostgresTypes.money:\n    case PostgresTypes.reltime: // To allow users to cast it based on Timezone\n    case PostgresTypes.text:\n    case PostgresTypes.time: // To allow users to cast it based on Timezone\n    case PostgresTypes.timestamptz: // To allow users to cast it based on Timezone\n    case PostgresTypes.timetz: // To allow users to cast it based on Timezone\n    case PostgresTypes.tsrange:\n    case PostgresTypes.tstzrange:\n      return noop(value)\n    default:\n      // Return the value for remaining types\n      return noop(value)\n  }\n}\n\nconst noop = (value: RecordValue): RecordValue => {\n  return value\n}\nexport const toBoolean = (value: RecordValue): RecordValue => {\n  switch (value) {\n    case 't':\n      return true\n    case 'f':\n      return false\n    default:\n      return value\n  }\n}\nexport const toNumber = (value: RecordValue): RecordValue => {\n  if (typeof value === 'string') {\n    const parsedValue = parseFloat(value)\n    if (!Number.isNaN(parsedValue)) {\n      return parsedValue\n    }\n  }\n  return value\n}\nexport const toJson = (value: RecordValue): RecordValue => {\n  if (typeof value === 'string') {\n    try {\n      return JSON.parse(value)\n    } catch {\n      return value\n    }\n  }\n  return value\n}\n\n/**\n * Converts a Postgres Array into a native JS array\n *\n * @example toArray('{}', 'int4')\n * //=> []\n * @example toArray('{\"[2021-01-01,2021-12-31)\",\"(2021-01-01,2021-12-32]\"}', 'daterange')\n * //=> ['[2021-01-01,2021-12-31)', '(2021-01-01,2021-12-32]']\n * @example toArray([1,2,3,4], 'int4')\n * //=> [1,2,3,4]\n */\nexport const toArray = (value: RecordValue, type: string): RecordValue => {\n  if (typeof value !== 'string') {\n    return value\n  }\n\n  const lastIdx = value.length - 1\n  const closeBrace = value[lastIdx]\n  const openBrace = value[0]\n\n  // Confirm value is a Postgres array by checking curly brackets\n  if (openBrace === '{' && closeBrace === '}') {\n    let arr\n    const valTrim = value.slice(1, lastIdx)\n\n    // TODO: find a better solution to separate Postgres array data\n    try {\n      arr = JSON.parse('[' + valTrim + ']')\n    } catch (_) {\n      // WARNING: splitting on comma does not cover all edge cases\n      arr = valTrim ? valTrim.split(',') : []\n    }\n\n    return arr.map((val: BaseValue) => convertCell(type, val))\n  }\n\n  return value\n}\n\n/**\n * Fixes timestamp to be ISO-8601. Swaps the space between the date and time for a 'T'\n * See https://github.com/supabase/supabase/issues/18\n *\n * @example toTimestampString('2019-09-10 00:00:00')\n * //=> '2019-09-10T00:00:00'\n */\nexport const toTimestampString = (value: RecordValue): RecordValue => {\n  if (typeof value === 'string') {\n    return value.replace(' ', 'T')\n  }\n\n  return value\n}\n\nexport const httpEndpointURL = (socketUrl: string): string => {\n  const wsUrl = new URL(socketUrl)\n\n  wsUrl.protocol = wsUrl.protocol.replace(/^ws/i, 'http')\n\n  wsUrl.pathname = wsUrl.pathname\n    .replace(/\\/+$/, '') // remove all trailing slashes\n    .replace(/\\/socket\\/websocket$/i, '') // remove the socket/websocket path\n    .replace(/\\/socket$/i, '') // remove the socket path\n    .replace(/\\/websocket$/i, '') // remove the websocket path\n\n  if (wsUrl.pathname === '' || wsUrl.pathname === '/') {\n    wsUrl.pathname = '/api/broadcast'\n  } else {\n    wsUrl.pathname = wsUrl.pathname + '/api/broadcast'\n  }\n\n  return wsUrl.href\n}\n", "/**\n*\n* Wraps value in closure or returns closure\n*\n* @template T\n* @param {T | (() => T)} value\n* @returns {() => T}\n*/\nexport let closure = (value) => {\n  if(typeof value === \"function\"){\n    return /** @type {() => T} */ (value)\n  } else {\n    let closure = function (){ return value }\n    return closure\n  }\n}\n", "export const globalSelf = typeof self !== \"undefined\" ? self : null\nexport const phxWindow = typeof window !== \"undefined\" ? window : null\nexport const global = globalSelf || phxWindow || globalThis\nexport const DEFAULT_VSN = \"2.0.0\"\nexport const DEFAULT_TIMEOUT = 10000\nexport const WS_CLOSE_NORMAL = 1000\nexport const MAX_LONGPOLL_BATCH_SIZE = 100\n\nexport const SOCKET_STATES = /** @type {const} */ ({connecting: 0, open: 1, closing: 2, closed: 3})\n\nexport const CHANNEL_STATES = /** @type {const} */ ({\n  closed: \"closed\",\n  errored: \"errored\",\n  joined: \"joined\",\n  joining: \"joining\",\n  leaving: \"leaving\",\n})\n\nexport const CHANNEL_EVENTS = /** @type {const} */ ({\n  close: \"phx_close\",\n  error: \"phx_error\",\n  join: \"phx_join\",\n  reply: \"phx_reply\",\n  leave: \"phx_leave\"\n})\n\nexport const TRANSPORTS = /** @type {const} */ ({\n  longpoll: \"longpoll\",\n  websocket: \"websocket\"\n})\n\nexport const XHR_STATES = /** @type {const} */ ({\n  complete: 4\n})\n\nexport const AUTH_TOKEN_PREFIX = \"base64url.bearer.phx.\"\n", "/**\n * @import Channel from \"./channel\"\n * @import { ChannelEvent } from \"./types\"\n */\nexport default class Push {\n  /**\n   * Initializes the Push\n   * @param {Channel} channel - The Channel\n   * @param {ChannelEvent} event - The event, for example `\"phx_join\"`\n   * @param {() => Record<string, unknown>} payload - The payload, for example `{user_id: 123}`\n   * @param {number} timeout - The push timeout in milliseconds\n   */\n  constructor(channel, event, payload, timeout){\n    /** @type{Channel} */\n    this.channel = channel\n    /** @type{ChannelEvent} */\n    this.event = event\n    /** @type{() => Record<string, unknown>} */\n    this.payload = payload || function (){ return {} }\n    this.receivedResp = null\n    /** @type{number} */\n    this.timeout = timeout\n    /** @type{(ReturnType<typeof setTimeout>) | null} */\n    this.timeoutTimer = null\n    /** @type{{status: string; callback: (response: any) => void}[]} */\n    this.recHooks = []\n    /** @type{boolean} */\n    this.sent = false\n    /** @type{string | null | undefined} */\n    this.ref = undefined\n  }\n\n  /**\n   *\n   * @param {number} timeout\n   */\n  resend(timeout){\n    this.timeout = timeout\n    this.reset()\n    this.send()\n  }\n\n  /**\n   *\n   */\n  send(){\n    if(this.hasReceived(\"timeout\")){ return }\n    this.startTimeout()\n    this.sent = true\n    this.channel.socket.push({\n      topic: this.channel.topic,\n      event: this.event,\n      payload: this.payload(),\n      ref: this.ref,\n      join_ref: this.channel.joinRef()\n    })\n  }\n\n  /**\n   *\n   * @param {string} status\n   * @param {(response: any) => void} callback\n   */\n  receive(status, callback){\n    if(this.hasReceived(status)){\n      callback(this.receivedResp.response)\n    }\n\n    this.recHooks.push({status, callback})\n    return this\n  }\n\n  reset(){\n    this.cancelRefEvent()\n    this.ref = null\n    this.refEvent = null\n    this.receivedResp = null\n    this.sent = false\n  }\n\n  destroy(){\n    this.cancelRefEvent()\n    this.cancelTimeout()\n  }\n\n  /**\n   * @private\n   */\n  matchReceive({status, response, _ref}){\n    this.recHooks.filter(h => h.status === status)\n      .forEach(h => h.callback(response))\n  }\n\n  /**\n   * @private\n   */\n  cancelRefEvent(){\n    if(!this.refEvent){ return }\n    this.channel.off(this.refEvent)\n  }\n\n  cancelTimeout(){\n    clearTimeout(this.timeoutTimer)\n    this.timeoutTimer = null\n  }\n\n  startTimeout(){\n    if(this.timeoutTimer){ this.cancelTimeout() }\n    this.ref = this.channel.socket.makeRef()\n    this.refEvent = this.channel.replyEventName(this.ref)\n\n    this.channel.on(this.refEvent, payload => {\n      this.cancelRefEvent()\n      this.cancelTimeout()\n      this.receivedResp = payload\n      this.matchReceive(payload)\n    })\n\n    this.timeoutTimer = setTimeout(() => {\n      this.trigger(\"timeout\", {})\n    }, this.timeout)\n  }\n\n  /**\n   * @private\n   */\n  hasReceived(status){\n    return this.receivedResp && this.receivedResp.status === status\n  }\n\n  trigger(status, response){\n    this.channel.trigger(this.refEvent, {status, response})\n  }\n}\n", "/**\n *\n * Creates a timer that accepts a `timerCalc` function to perform\n * calculated timeout retries, such as exponential backoff.\n *\n * @example\n * let reconnectTimer = new Timer(() => this.connect(), function(tries){\n *   return [1000, 5000, 10000][tries - 1] || 10000\n * })\n * reconnectTimer.scheduleTimeout() // fires after 1000\n * reconnectTimer.scheduleTimeout() // fires after 5000\n * reconnectTimer.reset()\n * reconnectTimer.scheduleTimeout() // fires after 1000\n *\n */\nexport default class Timer {\n  /**\n  * @param {() => void} callback\n  * @param {(tries: number) => number} timerCalc\n  */\n  constructor(callback, timerCalc){\n    /** @type {() => void} */\n    this.callback = callback\n    /** @type {(tries: number) => number} */\n    this.timerCalc = timerCalc\n    /** @type {ReturnType<typeof setTimeout> | undefined} */\n    this.timer = undefined\n    /** @type {number} */\n    this.tries = 0\n  }\n\n  reset(){\n    this.tries = 0\n    clearTimeout(this.timer)\n  }\n\n  /**\n   * Cancels any previous scheduleTimeout and schedules callback\n   */\n  scheduleTimeout(){\n    clearTimeout(this.timer)\n\n    this.timer = setTimeout(() => {\n      this.tries = this.tries + 1\n      this.callback()\n    }, this.timerCalc(this.tries + 1))\n  }\n}\n", "import {closure} from \"./utils\"\nimport {\n  CHANNEL_EVENTS,\n  CHANNEL_STATES,\n} from \"./constants\"\n\nimport Push from \"./push\"\nimport Timer from \"./timer\"\n\n/**\n* @import Socket from \"./socket\"\n* @import { ChannelState, Params, ChannelBindingCallback, ChannelOnMessage, ChannelFilterBindings, ChannelOnErrorCallback, ChannelBinding } from \"./types\"\n*/\n\nexport default class Channel {\n/**\n * @param {string} topic\n * @param {Params | (() => Params)} params\n * @param {Socket} socket\n */\n  constructor(topic, params, socket){\n    /** @type{ChannelState} */\n    this.state = CHANNEL_STATES.closed\n    /** @type{string} */\n    this.topic = topic\n    /** @type{() => Params} */\n    this.params = closure(params || {})\n    /** @type {Socket} */\n    this.socket = socket\n    /** @type{ChannelBinding[]} */\n    this.bindings = []\n    /** @type{number} */\n    this.bindingRef = 0\n    /** @type{number} */\n    this.timeout = this.socket.timeout\n    /** @type{boolean} */\n    this.joinedOnce = false\n    /** @type{Push} */\n    this.joinPush = new Push(this, CHANNEL_EVENTS.join, this.params, this.timeout)\n    /** @type{Push[]} */\n    this.pushBuffer = []\n    /** @type{string[]} */\n    this.stateChangeRefs = []\n\n    /** @type{Timer} */\n    this.rejoinTimer = new Timer(() => {\n      if(this.socket.isConnected()){ this.rejoin() }\n    }, this.socket.rejoinAfterMs)\n    this.stateChangeRefs.push(this.socket.onError(() => this.rejoinTimer.reset()))\n    this.stateChangeRefs.push(this.socket.onOpen(() => {\n      this.rejoinTimer.reset()\n      if(this.isErrored()){ this.rejoin() }\n    })\n    )\n    this.joinPush.receive(\"ok\", () => {\n      this.state = CHANNEL_STATES.joined\n      this.rejoinTimer.reset()\n      this.pushBuffer.forEach(pushEvent => pushEvent.send())\n      this.pushBuffer = []\n    })\n    this.joinPush.receive(\"error\", (reason) => {\n      this.state = CHANNEL_STATES.errored\n      if(this.socket.hasLogger()) this.socket.log(\"channel\", `error ${this.topic}`, reason)\n      if(this.socket.isConnected()){ this.rejoinTimer.scheduleTimeout() }\n    })\n    this.onClose(() => {\n      this.rejoinTimer.reset()\n      if(this.socket.hasLogger()) this.socket.log(\"channel\", `close ${this.topic}`)\n      this.state = CHANNEL_STATES.closed\n      this.socket.remove(this)\n    })\n    this.onError(reason => {\n      if(this.socket.hasLogger()) this.socket.log(\"channel\", `error ${this.topic}`, reason)\n      if(this.isJoining()){ this.joinPush.reset() }\n      this.state = CHANNEL_STATES.errored\n      if(this.socket.isConnected()){ this.rejoinTimer.scheduleTimeout() }\n    })\n    this.joinPush.receive(\"timeout\", () => {\n      if(this.socket.hasLogger()) this.socket.log(\"channel\", `timeout ${this.topic}`, this.joinPush.timeout)\n      let leavePush = new Push(this, CHANNEL_EVENTS.leave, closure({}), this.timeout)\n      leavePush.send()\n      this.state = CHANNEL_STATES.errored\n      this.joinPush.reset()\n      if(this.socket.isConnected()){ this.rejoinTimer.scheduleTimeout() }\n    })\n    this.on(CHANNEL_EVENTS.reply, (payload, ref) => {\n      this.trigger(this.replyEventName(ref), payload)\n    })\n  }\n\n  /**\n   * Join the channel\n   * @param {number} timeout\n   * @returns {Push}\n   */\n  join(timeout = this.timeout){\n    if(this.joinedOnce){\n      throw new Error(\"tried to join multiple times. 'join' can only be called a single time per channel instance\")\n    } else {\n      this.timeout = timeout\n      this.joinedOnce = true\n      this.rejoin()\n      return this.joinPush\n    }\n  }\n\n  /**\n   * Teardown the channel.\n   *\n   * Destroys and stops related timers.\n   */\n  teardown(){\n    this.pushBuffer.forEach((push) => push.destroy())\n    this.pushBuffer = []\n    this.rejoinTimer.reset()\n    this.joinPush.destroy()\n    this.state = CHANNEL_STATES.closed\n    this.bindings = []\n  }\n\n  /**\n   * Hook into channel close\n   * @param {ChannelBindingCallback} callback\n   */\n  onClose(callback){\n    this.on(CHANNEL_EVENTS.close, callback)\n  }\n\n  /**\n   * Hook into channel errors\n   * @param {ChannelOnErrorCallback} callback\n   * @return {number}\n   */\n  onError(callback){\n    return this.on(CHANNEL_EVENTS.error, reason => callback(reason))\n  }\n\n  /**\n   * Subscribes on channel events\n   *\n   * Subscription returns a ref counter, which can be used later to\n   * unsubscribe the exact event listener\n   *\n   * @example\n   * const ref1 = channel.on(\"event\", do_stuff)\n   * const ref2 = channel.on(\"event\", do_other_stuff)\n   * channel.off(\"event\", ref1)\n   * // Since unsubscription, do_stuff won't fire,\n   * // while do_other_stuff will keep firing on the \"event\"\n   *\n   * @param {string} event\n   * @param {ChannelBindingCallback} callback\n   * @returns {number} ref\n   */\n  on(event, callback){\n    let ref = this.bindingRef++\n    this.bindings.push({event, ref, callback})\n    return ref\n  }\n\n  /**\n   * Unsubscribes off of channel events\n   *\n   * Use the ref returned from a channel.on() to unsubscribe one\n   * handler, or pass nothing for the ref to unsubscribe all\n   * handlers for the given event.\n   *\n   * @example\n   * // Unsubscribe the do_stuff handler\n   * const ref1 = channel.on(\"event\", do_stuff)\n   * channel.off(\"event\", ref1)\n   *\n   * // Unsubscribe all handlers from event\n   * channel.off(\"event\")\n   *\n   * @param {string} event\n   * @param {number} [ref]\n   */\n  off(event, ref){\n    this.bindings = this.bindings.filter((bind) => {\n      return !(bind.event === event && (typeof ref === \"undefined\" || ref === bind.ref))\n    })\n  }\n\n  /**\n   * @private\n   */\n  canPush(){ return this.socket.isConnected() && this.isJoined() }\n\n  /**\n   * Sends a message `event` to phoenix with the payload `payload`.\n   * Phoenix receives this in the `handle_in(event, payload, socket)`\n   * function. if phoenix replies or it times out (default 10000ms),\n   * then optionally the reply can be received.\n   *\n   * @example\n   * channel.push(\"event\")\n   *   .receive(\"ok\", payload => console.log(\"phoenix replied:\", payload))\n   *   .receive(\"error\", err => console.log(\"phoenix errored\", err))\n   *   .receive(\"timeout\", () => console.log(\"timed out pushing\"))\n   * @param {string} event\n   * @param {Object} payload\n   * @param {number} [timeout]\n   * @returns {Push}\n   */\n  push(event, payload, timeout = this.timeout){\n    payload = payload || {}\n    if(!this.joinedOnce){\n      throw new Error(`tried to push '${event}' to '${this.topic}' before joining. Use channel.join() before pushing events`)\n    }\n    let pushEvent = new Push(this, event, function (){ return payload }, timeout)\n    if(this.canPush()){\n      pushEvent.send()\n    } else {\n      pushEvent.startTimeout()\n      this.pushBuffer.push(pushEvent)\n    }\n\n    return pushEvent\n  }\n\n  /** Leaves the channel\n   *\n   * Unsubscribes from server events, and\n   * instructs channel to terminate on server\n   *\n   * Triggers onClose() hooks\n   *\n   * To receive leave acknowledgements, use the `receive`\n   * hook to bind to the server ack, ie:\n   *\n   * @example\n   * channel.leave().receive(\"ok\", () => alert(\"left!\") )\n   *\n   * @param {number} timeout\n   * @returns {Push}\n   */\n  leave(timeout = this.timeout){\n    this.rejoinTimer.reset()\n    this.joinPush.cancelTimeout()\n\n    this.state = CHANNEL_STATES.leaving\n    let onClose = () => {\n      if(this.socket.hasLogger()) this.socket.log(\"channel\", `leave ${this.topic}`)\n      this.trigger(CHANNEL_EVENTS.close, \"leave\")\n    }\n    let leavePush = new Push(this, CHANNEL_EVENTS.leave, closure({}), timeout)\n    leavePush.receive(\"ok\", () => onClose())\n      .receive(\"timeout\", () => onClose())\n    leavePush.send()\n    if(!this.canPush()){ leavePush.trigger(\"ok\", {}) }\n\n    return leavePush\n  }\n\n  /**\n   * Overridable message hook\n   *\n   * Receives all events for specialized message handling\n   * before dispatching to the channel callbacks.\n   *\n   * Must return the payload, modified or unmodified\n   * @type{ChannelOnMessage}\n   */\n  onMessage(_event, payload, _ref){ return payload }\n\n  /**\n   * Overridable filter hook\n   *\n   * If this function returns `true`, `binding`'s callback will be called.\n   *\n   * @type{ChannelFilterBindings}\n   */\n  filterBindings(_binding, _payload, _ref){ return true }\n\n  isMember(topic, event, payload, joinRef){\n    if(this.topic !== topic){ return false }\n\n    if(joinRef && joinRef !== this.joinRef()){\n      if(this.socket.hasLogger()) this.socket.log(\"channel\", \"dropping outdated message\", {topic, event, payload, joinRef})\n      return false\n    } else {\n      return true\n    }\n  }\n\n  joinRef(){ return this.joinPush.ref }\n\n  /**\n   * @private\n   */\n  rejoin(timeout = this.timeout){\n    if(this.isLeaving()){ return }\n    this.socket.leaveOpenTopic(this.topic)\n    this.state = CHANNEL_STATES.joining\n    this.joinPush.resend(timeout)\n  }\n\n  /**\n   * @param {string} event\n   * @param {unknown} [payload]\n   * @param {?string} [ref]\n   * @param {?string} [joinRef]\n   */\n  trigger(event, payload, ref, joinRef){\n    let handledPayload = this.onMessage(event, payload, ref, joinRef)\n    if(payload && !handledPayload){ throw new Error(\"channel onMessage callbacks must return the payload, modified or unmodified\") }\n\n    let eventBindings = this.bindings.filter(bind => bind.event === event && this.filterBindings(bind, payload, ref))\n\n    for(let i = 0; i < eventBindings.length; i++){\n      let bind = eventBindings[i]\n      bind.callback(handledPayload, ref, joinRef || this.joinRef())\n    }\n  }\n\n  /**\n  * @param {string} ref\n  */\n  replyEventName(ref){ return `chan_reply_${ref}` }\n\n  isClosed(){ return this.state === CHANNEL_STATES.closed }\n\n  isErrored(){ return this.state === CHANNEL_STATES.errored }\n\n  isJoined(){ return this.state === CHANNEL_STATES.joined }\n\n  isJoining(){ return this.state === CHANNEL_STATES.joining }\n\n  isLeaving(){ return this.state === CHANNEL_STATES.leaving }\n}\n", "import {\n  global,\n  XHR_STATES\n} from \"./constants\"\n\nexport default class Ajax {\n\n  static request(method, endPoint, headers, body, timeout, ontimeout, callback){\n    if(global.XDomainRequest){\n      let req = new global.XDomainRequest() // IE8, IE9\n      return this.xdomainRequest(req, method, endPoint, body, timeout, ontimeout, callback)\n    } else if(global.XMLHttpRequest){\n      let req = new global.XMLHttpRequest() // IE7+, Firefox, Chrome, Opera, Safari\n      return this.xhrRequest(req, method, endPoint, headers, body, timeout, ontimeout, callback)\n    } else if(global.fetch && global.AbortController){\n      // Fetch with AbortController for modern browsers\n      return this.fetchRequest(method, endPoint, headers, body, timeout, ontimeout, callback)\n    } else {\n      throw new Error(\"No suitable XMLHttpRequest implementation found\")\n    }\n  }\n\n  static fetchRequest(method, endPoint, headers, body, timeout, ontimeout, callback){\n    let options = {\n      method,\n      headers,\n      body,\n    }\n    let controller = null\n    if(timeout){\n      controller = new AbortController()\n      const _timeoutId = setTimeout(() => controller.abort(), timeout)\n      options.signal = controller.signal\n    }\n    global.fetch(endPoint, options)\n      .then(response => response.text())\n      .then(data => this.parseJSON(data))\n      .then(data => callback && callback(data))\n      .catch(err => {\n        if(err.name === \"AbortError\" && ontimeout){\n          ontimeout()\n        } else {\n          callback && callback(null)\n        }\n      })\n    return controller\n  }\n\n  static xdomainRequest(req, method, endPoint, body, timeout, ontimeout, callback){\n    req.timeout = timeout\n    req.open(method, endPoint)\n    req.onload = () => {\n      let response = this.parseJSON(req.responseText)\n      callback && callback(response)\n    }\n    if(ontimeout){ req.ontimeout = ontimeout }\n\n    // Work around bug in IE9 that requires an attached onprogress handler\n    req.onprogress = () => { }\n\n    req.send(body)\n    return req\n  }\n\n  static xhrRequest(req, method, endPoint, headers, body, timeout, ontimeout, callback){\n    req.open(method, endPoint, true)\n    req.timeout = timeout\n    for(let [key, value] of Object.entries(headers)){\n      req.setRequestHeader(key, value)\n    }\n    req.onerror = () => callback && callback(null)\n    req.onreadystatechange = () => {\n      if(req.readyState === XHR_STATES.complete && callback){\n        let response = this.parseJSON(req.responseText)\n        callback(response)\n      }\n    }\n    if(ontimeout){ req.ontimeout = ontimeout }\n\n    req.send(body)\n    return req\n  }\n\n  static parseJSON(resp){\n    if(!resp || resp === \"\"){ return null }\n\n    try {\n      return JSON.parse(resp)\n    } catch {\n      console && console.log(\"failed to parse JSON response\", resp)\n      return null\n    }\n  }\n\n  static serialize(obj, parentKey){\n    let queryStr = []\n    for(var key in obj){\n      if(!Object.prototype.hasOwnProperty.call(obj, key)){ continue }\n      let paramKey = parentKey ? `${parentKey}[${key}]` : key\n      let paramVal = obj[key]\n      if(typeof paramVal === \"object\"){\n        queryStr.push(this.serialize(paramVal, paramKey))\n      } else {\n        queryStr.push(encodeURIComponent(paramKey) + \"=\" + encodeURIComponent(paramVal))\n      }\n    }\n    return queryStr.join(\"&\")\n  }\n\n  static appendParams(url, params){\n    if(Object.keys(params).length === 0){ return url }\n\n    let prefix = url.match(/\\?/) ? \"&\" : \"?\"\n    return `${url}${prefix}${this.serialize(params)}`\n  }\n}\n", "import {\n  SOCKET_STATES,\n  TRANSPORTS,\n  AUTH_TOKEN_PREFIX,\n  MAX_LONGPOLL_BATCH_SIZE\n} from \"./constants\"\n\nimport Ajax from \"./ajax\"\n\nlet arrayBufferToBase64 = (buffer) => {\n  let binary = \"\"\n  let bytes = new Uint8Array(buffer)\n  let len = bytes.byteLength\n  for(let i = 0; i < len; i++){ binary += String.fromCharCode(bytes[i]) }\n  return btoa(binary)\n}\n\nexport default class LongPoll {\n\n  constructor(endPoint, protocols){\n    // we only support subprotocols for authToken\n    // [\"phoenix\", \"base64url.bearer.phx.BASE64_ENCODED_TOKEN\"]\n    if(protocols && protocols.length === 2 && protocols[1].startsWith(AUTH_TOKEN_PREFIX)){\n      this.authToken = atob(protocols[1].slice(AUTH_TOKEN_PREFIX.length))\n    }\n    this.endPoint = null\n    this.token = null\n    this.skipHeartbeat = true\n    this.reqs = new Set()\n    this.awaitingBatchAck = false\n    this.currentBatch = null\n    this.currentBatchTimer = null\n    this.batchBuffer = []\n    this.onopen = function (){ } // noop\n    this.onerror = function (){ } // noop\n    this.onmessage = function (){ } // noop\n    this.onclose = function (){ } // noop\n    this.pollEndpoint = this.normalizeEndpoint(endPoint)\n    this.readyState = SOCKET_STATES.connecting\n    // we must wait for the caller to finish setting up our callbacks and timeout properties\n    setTimeout(() => this.poll(), 0)\n  }\n\n  normalizeEndpoint(endPoint){\n    return (endPoint\n      .replace(\"ws://\", \"http://\")\n      .replace(\"wss://\", \"https://\")\n      .replace(new RegExp(\"(.*)\\/\" + TRANSPORTS.websocket), \"$1/\" + TRANSPORTS.longpoll))\n  }\n\n  endpointURL(){\n    return Ajax.appendParams(this.pollEndpoint, {token: this.token})\n  }\n\n  closeAndRetry(code, reason, wasClean){\n    this.close(code, reason, wasClean)\n    this.readyState = SOCKET_STATES.connecting\n  }\n\n  ontimeout(){\n    this.onerror(\"timeout\")\n    this.closeAndRetry(1005, \"timeout\", false)\n  }\n\n  isActive(){ return this.readyState === SOCKET_STATES.open || this.readyState === SOCKET_STATES.connecting }\n\n  poll(){\n    const headers = {\"Accept\": \"application/json\"}\n    if(this.authToken){\n      headers[\"X-Phoenix-AuthToken\"] = this.authToken\n    }\n    this.ajax(\"GET\", headers, null, () => this.ontimeout(), resp => {\n      if(resp){\n        var {status, token, messages} = resp\n        if(status === 410 && this.token !== null){\n          // In case we already have a token, this means that our existing session\n          // is gone. We fail so that the client rejoins its channels.\n          this.onerror(410)\n          this.closeAndRetry(3410, \"session_gone\", false)\n          return\n        }\n        this.token = token\n      } else {\n        status = 0\n      }\n\n      switch(status){\n        case 200:\n          messages.forEach(msg => {\n            // Tasks are what things like event handlers, setTimeout callbacks,\n            // promise resolves and more are run within.\n            // In modern browsers, there are two different kinds of tasks,\n            // microtasks and macrotasks.\n            // Microtasks are mainly used for Promises, while macrotasks are\n            // used for everything else.\n            // Microtasks always have priority over macrotasks. If the JS engine\n            // is looking for a task to run, it will always try to empty the\n            // microtask queue before attempting to run anything from the\n            // macrotask queue.\n            //\n            // For the WebSocket transport, messages always arrive in their own\n            // event. This means that if any promises are resolved from within,\n            // their callbacks will always finish execution by the time the\n            // next message event handler is run.\n            //\n            // In order to emulate this behaviour, we need to make sure each\n            // onmessage handler is run within its own macrotask.\n            setTimeout(() => this.onmessage({data: msg}), 0)\n          })\n          this.poll()\n          break\n        case 204:\n          this.poll()\n          break\n        case 410:\n          this.readyState = SOCKET_STATES.open\n          this.onopen({})\n          this.poll()\n          break\n        case 403:\n          this.onerror(403)\n          this.close(1008, \"forbidden\", false)\n          break\n        case 0:\n        case 500:\n          this.onerror(500)\n          this.closeAndRetry(1011, \"internal server error\", 500)\n          break\n        default: throw new Error(`unhandled poll status ${status}`)\n      }\n    })\n  }\n\n  // we collect all pushes within the current event loop by\n  // setTimeout 0, which optimizes back-to-back procedural\n  // pushes against an empty buffer\n\n  send(body){\n    if(typeof(body) !== \"string\"){ body = arrayBufferToBase64(body) }\n    if(this.currentBatch){\n      this.currentBatch.push(body)\n    } else if(this.awaitingBatchAck){\n      this.batchBuffer.push(body)\n    } else {\n      this.currentBatch = [body]\n      this.currentBatchTimer = setTimeout(() => {\n        this.batchSend(this.currentBatch)\n        this.currentBatch = null\n      }, 0)\n    }\n  }\n\n  batchSend(messages, offset = 0){\n    this.awaitingBatchAck = true\n    const next = offset + MAX_LONGPOLL_BATCH_SIZE\n    const batch = messages.slice(offset, next)\n    this.ajax(\"POST\", {\"Content-Type\": \"application/x-ndjson\"}, batch.join(\"\\n\"), () => this.onerror(\"timeout\"), resp => {\n      if(!resp || resp.status !== 200){\n        this.awaitingBatchAck = false\n        this.onerror(resp && resp.status)\n        this.closeAndRetry(1011, \"internal server error\", false)\n      } else if(next < messages.length){\n        this.batchSend(messages, next)\n      } else if(this.batchBuffer.length > 0){\n        this.batchSend(this.batchBuffer)\n        this.batchBuffer = []\n      } else {\n        this.awaitingBatchAck = false\n      }\n    })\n  }\n\n  close(code, reason, wasClean){\n    for(let req of this.reqs){ req.abort() }\n    this.readyState = SOCKET_STATES.closed\n    let opts = Object.assign({code: 1000, reason: undefined, wasClean: true}, {code, reason, wasClean})\n    this.batchBuffer = []\n    clearTimeout(this.currentBatchTimer)\n    this.currentBatchTimer = null\n    if(typeof(CloseEvent) !== \"undefined\"){\n      this.onclose(new CloseEvent(\"close\", opts))\n    } else {\n      this.onclose(opts)\n    }\n  }\n\n  ajax(method, headers, body, onCallerTimeout, callback){\n    let req\n    let ontimeout = () => {\n      this.reqs.delete(req)\n      onCallerTimeout()\n    }\n    req = Ajax.request(method, this.endpointURL(), headers, body, this.timeout, ontimeout, resp => {\n      this.reqs.delete(req)\n      if(this.isActive()){ callback(resp) }\n    })\n    this.reqs.add(req)\n  }\n}\n", "/**\n * @import Channel from \"./channel\"\n * @import { PresenceEvents, PresenceOnJoin, PresenceOnLeave, PresenceOnSync, PresenceState, PresenceDiff, PresenceOptions } from \"./types\"\n */\nexport default class Presence {\n\n  /**\n   * Initializes the Presence\n   * @param {Channel} channel - The Channel\n   * @param {PresenceOptions} [opts] - The options, for example `{events: {state: \"state\", diff: \"diff\"}}`\n   */\n  constructor(channel, opts = {}){\n    let events = opts.events || /** @type {PresenceEvents} */ ({state: \"presence_state\", diff: \"presence_diff\"})\n    /** @type{Record<string, PresenceState>} */\n    this.state = Object.create(null)\n    /** @type{PresenceDiff[]} */\n    this.pendingDiffs = []\n    /** @type{Channel} */\n    this.channel = channel\n    /** @type{?number} */\n    this.joinRef = null\n    /** @type{({ onJoin: PresenceOnJoin; onLeave: PresenceOnLeave; onSync: PresenceOnSync })} */\n    this.caller = {\n      onJoin: function (){ },\n      onLeave: function (){ },\n      onSync: function (){ }\n    }\n\n    this.channel.on(events.state, newState => {\n      let {onJoin, onLeave, onSync} = this.caller\n\n      this.joinRef = this.channel.joinRef()\n      this.state = Presence.syncState(this.state, newState, onJoin, onLeave)\n\n      this.pendingDiffs.forEach(diff => {\n        this.state = Presence.syncDiff(this.state, diff, onJoin, onLeave)\n      })\n      this.pendingDiffs = []\n      onSync()\n    })\n\n    this.channel.on(events.diff, diff => {\n      let {onJoin, onLeave, onSync} = this.caller\n\n      if(this.inPendingSyncState()){\n        this.pendingDiffs.push(diff)\n      } else {\n        this.state = Presence.syncDiff(this.state, diff, onJoin, onLeave)\n        onSync()\n      }\n    })\n  }\n\n  /**\n   * @param {PresenceOnJoin} callback\n   */\n  onJoin(callback){ this.caller.onJoin = callback }\n\n  /**\n   * @param {PresenceOnLeave} callback\n   */\n  onLeave(callback){ this.caller.onLeave = callback }\n\n  /**\n   * @param {PresenceOnSync} callback\n   */\n  onSync(callback){ this.caller.onSync = callback }\n\n  /**\n   * Returns the array of presences, with selected metadata.\n   *\n   * @template [T=PresenceState]\n   * @param {((key: string, obj: PresenceState) => T)} [by]\n   *\n   * @returns {T[]}\n   */\n  list(by){ return Presence.list(this.state, by) }\n\n  inPendingSyncState(){\n    return !this.joinRef || (this.joinRef !== this.channel.joinRef())\n  }\n\n  // lower-level public static API\n\n  /**\n   * Used to sync the list of presences on the server\n   * with the client's state. An optional `onJoin` and `onLeave` callback can\n   * be provided to react to changes in the client's local presences across\n   * disconnects and reconnects with the server.\n   *\n   * @param {Record<string, PresenceState>} currentState\n   * @param {Record<string, PresenceState>} newState\n   * @param {PresenceOnJoin} onJoin\n   * @param {PresenceOnLeave} onLeave\n   *\n   * @returns {Record<string, PresenceState>}\n   */\n  static syncState(currentState, newState, onJoin, onLeave){\n    let state = this.toNullProtoObj(this.clone(currentState))\n    newState = this.toNullProtoObj(newState)\n    let joins = Object.create(null)\n    let leaves = Object.create(null)\n\n    this.map(state, (key, presence) => {\n      if(!newState[key]){\n        leaves[key] = presence\n      }\n    })\n    this.map(newState, (key, newPresence) => {\n      let currentPresence = state[key]\n      if(currentPresence){\n        let newRefs = newPresence.metas.map(m => m.phx_ref)\n        let curRefs = currentPresence.metas.map(m => m.phx_ref)\n        let joinedMetas = newPresence.metas.filter(m => curRefs.indexOf(m.phx_ref) < 0)\n        let leftMetas = currentPresence.metas.filter(m => newRefs.indexOf(m.phx_ref) < 0)\n        if(joinedMetas.length > 0){\n          joins[key] = newPresence\n          joins[key].metas = joinedMetas\n        }\n        if(leftMetas.length > 0){\n          leaves[key] = this.clone(currentPresence)\n          leaves[key].metas = leftMetas\n        }\n      } else {\n        joins[key] = newPresence\n      }\n    })\n    return this.syncDiff(state, {joins: joins, leaves: leaves}, onJoin, onLeave)\n  }\n\n  /**\n   *\n   * Used to sync a diff of presence join and leave\n   * events from the server, as they happen. Like `syncState`, `syncDiff`\n   * accepts optional `onJoin` and `onLeave` callbacks to react to a user\n   * joining or leaving from a device.\n   *\n   * @param {Record<string, PresenceState>} state\n   * @param {PresenceDiff} diff\n   * @param {PresenceOnJoin} onJoin\n   * @param {PresenceOnLeave} onLeave\n   *\n   * @returns {Record<string, PresenceState>}\n   */\n  static syncDiff(state, diff, onJoin, onLeave){\n    state = this.toNullProtoObj(state)\n    let {joins, leaves} = this.clone(diff)\n    if(!onJoin){ onJoin = function (){ } }\n    if(!onLeave){ onLeave = function (){ } }\n\n    this.map(joins, (key, newPresence) => {\n      let currentPresence = state[key]\n      state[key] = this.clone(newPresence)\n      if(currentPresence){\n        let joinedRefs = state[key].metas.map(m => m.phx_ref)\n        let curMetas = currentPresence.metas.filter(m => joinedRefs.indexOf(m.phx_ref) < 0)\n        state[key].metas.unshift(...curMetas)\n      }\n      onJoin(key, currentPresence, newPresence)\n    })\n    this.map(leaves, (key, leftPresence) => {\n      let currentPresence = state[key]\n      if(!currentPresence){ return }\n      let refsToRemove = leftPresence.metas.map(m => m.phx_ref)\n      currentPresence.metas = currentPresence.metas.filter(p => {\n        return refsToRemove.indexOf(p.phx_ref) < 0\n      })\n      onLeave(key, currentPresence, leftPresence)\n      if(currentPresence.metas.length === 0){\n        delete state[key]\n      }\n    })\n    return state\n  }\n\n  /**\n   * Returns the array of presences, with selected metadata.\n   *\n   * @template [T=PresenceState]\n   * @param {Record<string, PresenceState>} presences\n   * @param {((key: string, obj: PresenceState) => T)} [chooser]\n   *\n   * @returns {T[]}\n   */\n  static list(presences, chooser){\n    if(!chooser){ chooser = function (key, pres){ return pres } }\n\n    return this.map(presences, (key, presence) => {\n      return chooser(key, presence)\n    })\n  }\n\n  // private\n\n  /**\n  * @template T\n  * @param {Record<string, PresenceState>} obj\n  * @param {(key: string, obj: PresenceState) => T} func\n  */\n  static map(obj, func){\n    return Object.getOwnPropertyNames(obj).map(key => func(key, obj[key]))\n  }\n\n  // Presence keys are chosen on the server and may collide with\n  // Object.prototype properties (\"__proto__\", \"constructor\", ...), so any\n  // object indexed by presence key must not have a prototype chain\n  //\n  // TODO: replace the null-prototype objects with Maps in Phoenix 2.0\n  // (breaking change for the lower-level static API)\n  static toNullProtoObj(obj){\n    if(Object.getPrototypeOf(obj) === null){ return obj }\n    let cleaned = Object.create(null)\n    Object.getOwnPropertyNames(obj).forEach(key => {\n      cleaned[key] = obj[key]\n    })\n    return cleaned\n  }\n\n  /**\n  * @template T\n  * @param {T} obj\n  * @returns {T}\n  */\n  static clone(obj){ return JSON.parse(JSON.stringify(obj)) }\n}\n", "/* The default serializer for encoding and decoding messages */\nimport {\n  CHANNEL_EVENTS\n} from \"./constants\"\n\n/**\n * @import { Message } from \"./types\"\n */\n\nexport default {\n  HEADER_LENGTH: 1,\n  META_LENGTH: 4,\n  KINDS: {push: 0, reply: 1, broadcast: 2},\n\n  /**\n  * @template T\n  * @param {Message<Record<string, any>>} msg\n  * @param {(msg: ArrayBuffer | string) => T} callback\n  * @returns {T}\n  */\n  encode(msg, callback){\n    if(msg.payload.constructor === ArrayBuffer){\n      return callback(this.binaryEncode(msg))\n    } else {\n      let payload = [msg.join_ref, msg.ref, msg.topic, msg.event, msg.payload]\n      return callback(JSON.stringify(payload))\n    }\n  },\n\n  /**\n  * @template T\n  * @param {ArrayBuffer | string} rawPayload\n  * @param {(msg: Message<unknown>) => T} callback\n  * @returns {T}\n  */\n  decode(rawPayload, callback){\n    if(rawPayload.constructor === ArrayBuffer){\n      return callback(this.binaryDecode(rawPayload))\n    } else {\n      let [join_ref, ref, topic, event, payload] = JSON.parse(rawPayload)\n      return callback({join_ref, ref, topic, event, payload})\n    }\n  },\n\n  /** @private */\n  binaryEncode(message){\n    let {join_ref, ref, event, topic, payload} = message\n    let encoder = new TextEncoder()\n    let joinRefBytes = encoder.encode(join_ref)\n    let refBytes = encoder.encode(ref)\n    let topicBytes = encoder.encode(topic)\n    let eventBytes = encoder.encode(event)\n\n    this.assertFieldSize(joinRefBytes.byteLength, \"join_ref\")\n    this.assertFieldSize(refBytes.byteLength, \"ref\")\n    this.assertFieldSize(topicBytes.byteLength, \"topic\")\n    this.assertFieldSize(eventBytes.byteLength, \"event\")\n\n    let metaLength = this.META_LENGTH + joinRefBytes.byteLength + refBytes.byteLength + topicBytes.byteLength + eventBytes.byteLength\n    let header = new ArrayBuffer(this.HEADER_LENGTH + metaLength)\n    let headerBytes = new Uint8Array(header)\n    let view = new DataView(header)\n    let offset = 0\n\n    view.setUint8(offset++, this.KINDS.push) // kind\n    view.setUint8(offset++, joinRefBytes.byteLength)\n    view.setUint8(offset++, refBytes.byteLength)\n    view.setUint8(offset++, topicBytes.byteLength)\n    view.setUint8(offset++, eventBytes.byteLength)\n    headerBytes.set(joinRefBytes, offset); offset += joinRefBytes.byteLength\n    headerBytes.set(refBytes, offset); offset += refBytes.byteLength\n    headerBytes.set(topicBytes, offset); offset += topicBytes.byteLength\n    headerBytes.set(eventBytes, offset); offset += eventBytes.byteLength\n\n    var combined = new Uint8Array(header.byteLength + payload.byteLength)\n    combined.set(headerBytes, 0)\n    combined.set(new Uint8Array(payload), header.byteLength)\n\n    return combined.buffer\n  },\n\n  assertFieldSize(size, name){\n    if(size > 255){\n      throw new Error(`unable to convert ${name} to binary: must be less than or equal to 255 bytes, but is ${size} bytes`)\n    }\n  },\n\n  /**\n  * @private\n  */\n  binaryDecode(buffer){\n    let view = new DataView(buffer)\n    let kind = view.getUint8(0)\n    let decoder = new TextDecoder()\n    switch(kind){\n      case this.KINDS.push: return this.decodePush(buffer, view, decoder)\n      case this.KINDS.reply: return this.decodeReply(buffer, view, decoder)\n      case this.KINDS.broadcast: return this.decodeBroadcast(buffer, view, decoder)\n    }\n  },\n\n  /** @private */\n  decodePush(buffer, view, decoder){\n    let joinRefSize = view.getUint8(1)\n    let topicSize = view.getUint8(2)\n    let eventSize = view.getUint8(3)\n    let offset = this.HEADER_LENGTH + this.META_LENGTH - 1 // pushes have no ref\n    let joinRef = decoder.decode(buffer.slice(offset, offset + joinRefSize))\n    offset = offset + joinRefSize\n    let topic = decoder.decode(buffer.slice(offset, offset + topicSize))\n    offset = offset + topicSize\n    let event = decoder.decode(buffer.slice(offset, offset + eventSize))\n    offset = offset + eventSize\n    let data = buffer.slice(offset, buffer.byteLength)\n    return {join_ref: joinRef, ref: null, topic: topic, event: event, payload: data}\n  },\n\n  /** @private */\n  decodeReply(buffer, view, decoder){\n    let joinRefSize = view.getUint8(1)\n    let refSize = view.getUint8(2)\n    let topicSize = view.getUint8(3)\n    let eventSize = view.getUint8(4)\n    let offset = this.HEADER_LENGTH + this.META_LENGTH\n    let joinRef = decoder.decode(buffer.slice(offset, offset + joinRefSize))\n    offset = offset + joinRefSize\n    let ref = decoder.decode(buffer.slice(offset, offset + refSize))\n    offset = offset + refSize\n    let topic = decoder.decode(buffer.slice(offset, offset + topicSize))\n    offset = offset + topicSize\n    let event = decoder.decode(buffer.slice(offset, offset + eventSize))\n    offset = offset + eventSize\n    let data = buffer.slice(offset, buffer.byteLength)\n    let payload = {status: event, response: data}\n    return {join_ref: joinRef, ref: ref, topic: topic, event: CHANNEL_EVENTS.reply, payload: payload}\n  },\n\n  /** @private */\n  decodeBroadcast(buffer, view, decoder){\n    let topicSize = view.getUint8(1)\n    let eventSize = view.getUint8(2)\n    let offset = this.HEADER_LENGTH + 2\n    let topic = decoder.decode(buffer.slice(offset, offset + topicSize))\n    offset = offset + topicSize\n    let event = decoder.decode(buffer.slice(offset, offset + eventSize))\n    offset = offset + eventSize\n    let data = buffer.slice(offset, buffer.byteLength)\n\n    return {join_ref: null, ref: null, topic: topic, event: event, payload: data}\n  }\n}\n", "import {\n  global,\n  phxWindow,\n  CHANNEL_EVENTS,\n  DEFAULT_TIMEOUT,\n  DEFAULT_VSN,\n  SOCKET_STATES,\n  TRANSPORTS,\n  WS_CLOSE_NORMAL,\n  AUTH_TOKEN_PREFIX\n} from \"./constants\"\n\nimport {\n  closure\n} from \"./utils\"\n\nimport Ajax from \"./ajax\"\nimport Channel from \"./channel\"\nimport LongPoll from \"./longpoll\"\nimport Serializer from \"./serializer\"\nimport Timer from \"./timer\"\n\n/**\n* @import { Encode, Decode, Message, Vsn, SocketTransport, Params, SocketOnOpen, SocketOnClose, SocketOnError, SocketOnMessage, SocketOptions, SocketStateChangeCallbacks, HeartbeatCallback } from \"./types\"\n*/\n\nexport default class Socket {\n  /** Initializes the Socket *\n   *\n   * For IE8 support use an ES5-shim (https://github.com/es-shims/es5-shim)\n   *\n   * @constructor\n   * @param {string} endPoint - The string WebSocket endpoint, ie, `\"ws://example.com/socket\"`,\n   *                                               `\"wss://example.com\"`\n   *                                               `\"/socket\"` (inherited host & protocol)\n   * @param {SocketOptions} [opts] - Optional configuration\n   */\n  constructor(endPoint, opts = {}){\n    /** @type{SocketStateChangeCallbacks} */\n    this.stateChangeCallbacks = {open: [], close: [], error: [], message: []}\n    /** @type{Channel[]} */\n    this.channels = []\n    /** @type{(() => void)[]} */\n    this.sendBuffer = []\n    /** @type{number} */\n    this.ref = 0\n    /** @type{?string} */\n    this.fallbackRef = null\n    /** @type{number} */\n    this.timeout = opts.timeout || DEFAULT_TIMEOUT\n    /** @type{SocketTransport} */\n    this.transport = opts.transport || global.WebSocket || LongPoll\n    /** @type{InstanceType<SocketTransport> | undefined | null} */\n    this.conn = undefined\n    /** @type{boolean} */\n    this.primaryPassedHealthCheck = false\n    /** @type{number | undefined} */\n    this.longPollFallbackMs = opts.longPollFallbackMs\n    /** @type{ReturnType<typeof setTimeout>} */\n    this.fallbackTimer = null\n    // In some environments (sandboxed iframes without `allow-same-origin`,\n    // in-app webviews, \"block third-party storage\" privacy modes), reading\n    // `global.sessionStorage` throws SecurityError at the property-access level.\n    // Wrap the read so the Socket constructor cannot throw synchronously.\n    let envSessionStorage = null\n    try { envSessionStorage = global && global.sessionStorage } catch {}\n    /** @type{Storage} */\n    this.sessionStore = opts.sessionStorage || envSessionStorage\n    /** @type{number} */\n    this.establishedConnections = 0\n    /** @type{Encode<void>} */\n    this.defaultEncoder = Serializer.encode.bind(Serializer)\n    /** @type{Decode<void>} */\n    this.defaultDecoder = Serializer.decode.bind(Serializer)\n    // We start with closeWasClean true to avoid the visibility change\n    // logic from connecting if the socket was never connected in the first place.\n    // transportConnect sets it to false on open.\n    /** @type{boolean} */\n    this.closeWasClean = true\n    /** @type{boolean} */\n    this.disconnecting = false\n    /** @type{BinaryType} */\n    this.binaryType = opts.binaryType || \"arraybuffer\"\n    /** @type{number} */\n    this.connectClock = 1\n    /** @type{boolean} */\n    this.pageHidden = false\n    /** @type{Encode<void>} */\n    this.encode = undefined\n    /** @type{Decode<void>} */\n    this.decode = undefined\n    if(this.transport !== LongPoll){\n      this.encode = opts.encode || this.defaultEncoder\n      this.decode = opts.decode || this.defaultDecoder\n    } else {\n      this.encode = this.defaultEncoder\n      this.decode = this.defaultDecoder\n    }\n    /** @type{number | null} */\n    let awaitingConnectionOnPageShow = null\n    if(phxWindow && phxWindow.addEventListener){\n      phxWindow.addEventListener(\"pagehide\", _e => {\n        if(this.conn){\n          this.disconnect()\n          awaitingConnectionOnPageShow = this.connectClock\n        }\n      })\n      phxWindow.addEventListener(\"pageshow\", _e => {\n        if(awaitingConnectionOnPageShow === this.connectClock){\n          awaitingConnectionOnPageShow = null\n          this.connect()\n        }\n      })\n      phxWindow.addEventListener(\"visibilitychange\", () => {\n        if(document.visibilityState === \"hidden\"){\n          this.pageHidden = true\n        } else {\n          this.pageHidden = false\n          // reconnect immediately\n          if(!this.isConnected() && !this.closeWasClean){\n            this.teardown(() => this.connect())\n          }\n        }\n      })\n    }\n    /** @type{number} */\n    this.heartbeatIntervalMs = opts.heartbeatIntervalMs || 30000\n    /** @type{boolean} */\n    this.autoSendHeartbeat = opts.autoSendHeartbeat ?? true\n    /** @type{HeartbeatCallback} */\n    this.heartbeatCallback = opts.heartbeatCallback ?? (() => {})\n    /** @type{(tries: number) => number} */\n    this.rejoinAfterMs = (tries) => {\n      if(opts.rejoinAfterMs){\n        return opts.rejoinAfterMs(tries)\n      } else {\n        return [1000, 2000, 5000][tries - 1] || 10000\n      }\n    }\n    /** @type{(tries: number) => number} */\n    this.reconnectAfterMs = (tries) => {\n      if(opts.reconnectAfterMs){\n        return opts.reconnectAfterMs(tries)\n      } else {\n        return [10, 50, 100, 150, 200, 250, 500, 1000, 2000][tries - 1] || 5000\n      }\n    }\n    /** @type{((kind: string, msg: string, data: any) => void) | null} */\n    this.logger = opts.logger || null\n    if(!this.logger && opts.debug){\n      this.logger = (kind, msg, data) => { console.log(`${kind}: ${msg}`, data) }\n    }\n    /** @type{number} */\n    this.longpollerTimeout = opts.longpollerTimeout || 20000\n    /** @type{() => Params} */\n    this.params = closure(opts.params || {})\n    /** @type{string} */\n    this.endPoint = `${endPoint}/${TRANSPORTS.websocket}`\n    /** @type{Vsn} */\n    this.vsn = opts.vsn || DEFAULT_VSN\n    /** @type{ReturnType<typeof setTimeout>} */\n    this.heartbeatTimeoutTimer = null\n    /** @type{ReturnType<typeof setTimeout>} */\n    this.heartbeatTimer = null\n    /** @type{number | null} */\n    this.heartbeatSentAt = null\n    /** @type{?string} */\n    this.pendingHeartbeatRef = null\n    /** @type{Timer} */\n    this.reconnectTimer = new Timer( () => {\n      if(this.pageHidden){\n        this.log(\"Not reconnecting as page is hidden!\")\n        this.teardown()\n        return\n      }\n\n      this.teardown(async () => {\n        if(opts.beforeReconnect) await opts.beforeReconnect()\n        this.connect()\n      })\n    }, this.reconnectAfterMs)\n    /** @type{(() => string) | undefined} */\n    this.authToken = opts.authToken && closure(opts.authToken)\n  }\n\n  /**\n   * Returns the LongPoll transport reference\n   */\n  getLongPollTransport(){ return LongPoll }\n\n  /**\n   * Disconnects and replaces the active transport\n   *\n   * @param {SocketTransport} newTransport - The new transport class to instantiate\n   *\n   */\n  replaceTransport(newTransport){\n    this.connectClock++\n    this.closeWasClean = true\n    clearTimeout(this.fallbackTimer)\n    this.reconnectTimer.reset()\n    if(this.conn){\n      this.conn.close()\n      this.conn = null\n    }\n    this.transport = newTransport\n  }\n\n  /**\n   * Returns the socket protocol\n   *\n   * @returns {\"wss\" | \"ws\"}\n   */\n  protocol(){ return location.protocol.match(/^https/) ? \"wss\" : \"ws\" }\n\n  /**\n   * The fully qualified socket url\n   *\n   * @returns {string}\n   */\n  endPointURL(){\n    let uri = Ajax.appendParams(\n      Ajax.appendParams(this.endPoint, this.params()), {vsn: this.vsn})\n    if(uri.charAt(0) !== \"/\"){ return uri }\n    if(uri.charAt(1) === \"/\"){ return `${this.protocol()}:${uri}` }\n\n    return `${this.protocol()}://${location.host}${uri}`\n  }\n\n  /**\n   * Disconnects the socket\n   *\n   * See https://developer.mozilla.org/en-US/docs/Web/API/CloseEvent#Status_codes for valid status codes.\n   *\n   * @param {() => void} [callback] - Optional callback which is called after socket is disconnected.\n   * @param {number} [code] - A status code for disconnection (Optional).\n   * @param {string} [reason] - A textual description of the reason to disconnect. (Optional)\n   */\n  disconnect(callback, code, reason){\n    this.connectClock++\n    this.disconnecting = true\n    this.closeWasClean = true\n    clearTimeout(this.fallbackTimer)\n    this.reconnectTimer.reset()\n    this.teardown(() => {\n      this.disconnecting = false\n      callback && callback()\n    }, code, reason)\n  }\n\n  /**\n   * @param {Params} [params] - [DEPRECATED] The params to send when connecting, for example `{user_id: userToken}`\n   *\n   * Passing params to connect is deprecated; pass them in the Socket constructor instead:\n   * `new Socket(\"/socket\", {params: {user_id: userToken}})`.\n   */\n  connect(params){\n    if(params){\n      console && console.log(\"passing params to connect is deprecated. Instead pass :params to the Socket constructor\")\n      this.params = closure(params)\n    }\n    if(this.conn && !this.disconnecting){ return }\n    if(this.longPollFallbackMs && this.transport !== LongPoll){\n      this.connectWithFallback(LongPoll, this.longPollFallbackMs)\n    } else {\n      this.transportConnect()\n    }\n  }\n\n  /**\n   * Logs the message. Override `this.logger` for specialized logging. noops by default\n   * @param {string} kind\n   * @param {string} msg\n   * @param {Object} data\n   */\n  log(kind, msg, data){ this.logger && this.logger(kind, msg, data) }\n\n  /**\n   * Returns true if a logger has been set on this socket.\n   */\n  hasLogger(){ return this.logger !== null }\n\n  /**\n   * Registers callbacks for connection open events\n   *\n   * @example socket.onOpen(function(){ console.info(\"the socket was opened\") })\n   *\n   * @param {SocketOnOpen} callback\n   */\n  onOpen(callback){\n    let ref = this.makeRef()\n    this.stateChangeCallbacks.open.push([ref, callback])\n    return ref\n  }\n\n  /**\n   * Registers callbacks for connection close events\n   * @param {SocketOnClose} callback\n   * @returns {string}\n   */\n  onClose(callback){\n    let ref = this.makeRef()\n    this.stateChangeCallbacks.close.push([ref, callback])\n    return ref\n  }\n\n  /**\n   * Registers callbacks for connection error events\n   *\n   * @example socket.onError(function(error){ alert(\"An error occurred\") })\n   *\n   * @param {SocketOnError} callback\n   * @returns {string}\n   */\n  onError(callback){\n    let ref = this.makeRef()\n    this.stateChangeCallbacks.error.push([ref, callback])\n    return ref\n  }\n\n  /**\n   * Registers callbacks for connection message events\n   * @param {SocketOnMessage} callback\n   * @returns {string}\n   */\n  onMessage(callback){\n    let ref = this.makeRef()\n    this.stateChangeCallbacks.message.push([ref, callback])\n    return ref\n  }\n\n  /**\n   * Sets a callback that receives lifecycle events for internal heartbeat messages.\n   * Useful for instrumenting connection health (e.g. sent/ok/timeout/disconnected).\n   * @param {HeartbeatCallback} callback\n   */\n  onHeartbeat(callback){\n    this.heartbeatCallback = callback\n  }\n\n  /**\n   * Pings the server and invokes the callback with the RTT in milliseconds\n   * @param {(timeDelta: number) => void} callback\n   *\n   * Returns true if the ping was pushed or false if unable to be pushed.\n   */\n  ping(callback){\n    if(!this.isConnected()){ return false }\n    let ref = this.makeRef()\n    let startTime = Date.now()\n    this.push({topic: \"phoenix\", event: \"heartbeat\", payload: {}, ref: ref})\n    let onMsgRef = this.onMessage(msg => {\n      if(msg.ref === ref){\n        this.off([onMsgRef])\n        callback(Date.now() - startTime)\n      }\n    })\n    return true\n  }\n\n  /**\n   * @private\n   *\n   * @param {Function}\n   */\n  transportName(transport){\n    // JavaScript minification, enabled by default in production in Phoenix\n    // projects, renames symbols to reduce code size.\n    // See https://esbuild.github.io/api/#keep-names.\n    // This helper ensures we return the correct name for the LongPoll transport\n    // even after minification. The other common transport is WebSocket, which\n    // is native to browsers and does not need special handling.\n    switch(transport){\n      case LongPoll: return \"LongPoll\"\n      default: return transport.name\n    }\n  }\n\n  /**\n   * @private\n   */\n  transportConnect(){\n    this.connectClock++\n    this.closeWasClean = false\n    let protocols = undefined\n    // Sec-WebSocket-Protocol based token\n    // (longpoll uses Authorization header instead)\n    if(this.authToken){\n      protocols = [\"phoenix\", `${AUTH_TOKEN_PREFIX}${btoa(this.authToken()).replace(/=/g, \"\")}`]\n    }\n    this.conn = new this.transport(this.endPointURL(), protocols)\n    this.conn.binaryType = this.binaryType\n    this.conn.timeout = this.longpollerTimeout\n    this.conn.onopen = () => this.onConnOpen()\n    this.conn.onerror = error => this.onConnError(error)\n    this.conn.onmessage = event => this.onConnMessage(event)\n    this.conn.onclose = event => this.onConnClose(event)\n  }\n\n  getSession(key){ return this.sessionStore && this.sessionStore.getItem(key) }\n\n  storeSession(key, val){ this.sessionStore && this.sessionStore.setItem(key, val) }\n\n  connectWithFallback(fallbackTransport, fallbackThreshold = 2500){\n    clearTimeout(this.fallbackTimer)\n    let established = false\n    let primaryTransport = true\n    let openRef, errorRef\n    let fallbackTransportName = this.transportName(fallbackTransport)\n    let fallback = (reason) => {\n      this.log(\"transport\", `falling back to ${fallbackTransportName}...`, reason)\n      this.off([openRef, errorRef])\n      primaryTransport = false\n      this.replaceTransport(fallbackTransport)\n      this.transportConnect()\n    }\n    if(this.getSession(`phx:fallback:${fallbackTransportName}`)){ return fallback(\"memorized\") }\n\n    this.fallbackTimer = setTimeout(fallback, fallbackThreshold)\n\n    errorRef = this.onError(reason => {\n      this.log(\"transport\", \"error\", reason)\n      if(primaryTransport && !established){\n        clearTimeout(this.fallbackTimer)\n        fallback(reason)\n      }\n    })\n    if(this.fallbackRef){\n      this.off([this.fallbackRef])\n    }\n    this.fallbackRef = this.onOpen(() => {\n      established = true\n      if(!primaryTransport){\n        let fallbackTransportName = this.transportName(fallbackTransport)\n        // only memorize LP if we never connected to primary\n        if(!this.primaryPassedHealthCheck){ this.storeSession(`phx:fallback:${fallbackTransportName}`, \"true\") }\n        return this.log(\"transport\", `established ${fallbackTransportName} fallback`)\n      }\n      // if we've established primary, give the fallback a new period to attempt ping\n      clearTimeout(this.fallbackTimer)\n      this.fallbackTimer = setTimeout(fallback, fallbackThreshold)\n      this.ping(rtt => {\n        this.log(\"transport\", \"connected to primary after\", rtt)\n        this.primaryPassedHealthCheck = true\n        clearTimeout(this.fallbackTimer)\n      })\n    })\n    this.transportConnect()\n  }\n\n  clearHeartbeats(){\n    clearTimeout(this.heartbeatTimer)\n    clearTimeout(this.heartbeatTimeoutTimer)\n  }\n\n  onConnOpen(){\n    if(this.hasLogger()) this.log(\"transport\", `connected to ${this.endPointURL()}`)\n    this.closeWasClean = false\n    this.disconnecting = false\n    this.establishedConnections++\n    this.flushSendBuffer()\n    this.reconnectTimer.reset()\n    if(this.autoSendHeartbeat){\n      this.resetHeartbeat()\n    }\n    this.triggerStateCallbacks(\"open\")\n  }\n\n  /**\n   * @private\n   */\n\n  heartbeatTimeout(){\n    if(this.pendingHeartbeatRef){\n      this.pendingHeartbeatRef = null\n      this.heartbeatSentAt = null\n      if(this.hasLogger()){ this.log(\"transport\", \"heartbeat timeout. Attempting to re-establish connection\") }\n      try {\n        this.heartbeatCallback(\"timeout\")\n      } catch (e){\n        this.log(\"error\", \"error in heartbeat callback\", e)\n      }\n      this.triggerChanError(new Error(\"heartbeat timeout\"))\n      this.closeWasClean = false\n      this.teardown(() => this.reconnectTimer.scheduleTimeout(), WS_CLOSE_NORMAL, \"heartbeat timeout\")\n    }\n  }\n\n  resetHeartbeat(){\n    if(this.conn && this.conn.skipHeartbeat){ return }\n    this.pendingHeartbeatRef = null\n    this.clearHeartbeats()\n    this.heartbeatTimer = setTimeout(() => this.sendHeartbeat(), this.heartbeatIntervalMs)\n  }\n\n  teardown(callback, code, reason){\n    if(!this.conn){\n      return callback && callback()\n    }\n\n    // If someone calls connect before we finish tearing down,\n    // we create a new connection, but we still want to finish tearing down the old one.\n    const connToClose = this.conn\n\n    this.waitForBufferDone(connToClose, () => {\n      if(code){ connToClose.close(code, reason || \"\") } else { connToClose.close() }\n\n      this.waitForSocketClosed(connToClose, () => {\n        if(this.conn === connToClose){\n          this.conn.onopen = function (){ } // noop\n          this.conn.onerror = function (){ } // noop\n          this.conn.onmessage = function (){ } // noop\n          this.conn.onclose = function (){ } // noop\n          this.conn = null\n        }\n\n        callback && callback()\n      })\n    })\n  }\n\n  waitForBufferDone(conn, callback, tries = 1){\n    if(tries === 5 || !conn.bufferedAmount){\n      callback()\n      return\n    }\n\n    setTimeout(() => {\n      this.waitForBufferDone(conn, callback, tries + 1)\n    }, 150 * tries)\n  }\n\n  waitForSocketClosed(conn, callback, tries = 1){\n    if(tries === 5 || conn.readyState === SOCKET_STATES.closed){\n      callback()\n      return\n    }\n\n    setTimeout(() => {\n      this.waitForSocketClosed(conn, callback, tries + 1)\n    }, 150 * tries)\n  }\n\n  /**\n  * @param {CloseEvent} event\n  */\n  onConnClose(event){\n    if(this.conn) this.conn.onclose = () => {} // noop to prevent recursive calls in teardown\n    if(this.hasLogger()) this.log(\"transport\", \"close\", event)\n    this.triggerChanError(event)\n    this.clearHeartbeats()\n    if(!this.closeWasClean){\n      this.reconnectTimer.scheduleTimeout()\n    }\n    this.triggerStateCallbacks(\"close\", event)\n  }\n\n  /**\n   * @private\n   * @param {Event} error\n   */\n  onConnError(error){\n    if(this.hasLogger()) this.log(\"transport\", \"error\", error)\n    let transportBefore = this.transport\n    let establishedBefore = this.establishedConnections\n    this.triggerStateCallbacks(\"error\", error, transportBefore, establishedBefore)\n    if(transportBefore === this.transport || establishedBefore > 0){\n      this.triggerChanError(error)\n    }\n  }\n\n  /**\n   * @private\n   * @param {unknown} [reason] underlying close/error event forwarded to channel error listeners\n   */\n  triggerChanError(reason){\n    this.channels.forEach(channel => {\n      if(!(channel.isErrored() || channel.isLeaving() || channel.isClosed())){\n        channel.trigger(CHANNEL_EVENTS.error, reason)\n      }\n    })\n  }\n\n  /**\n   * @returns {string}\n   */\n  connectionState(){\n    switch(this.conn && this.conn.readyState){\n      case SOCKET_STATES.connecting: return \"connecting\"\n      case SOCKET_STATES.open: return \"open\"\n      case SOCKET_STATES.closing: return \"closing\"\n      default: return \"closed\"\n    }\n  }\n\n  /**\n   * @returns {boolean}\n   */\n  isConnected(){ return this.connectionState() === \"open\" }\n\n  /**\n   *\n   * @param {Channel} channel\n   */\n  remove(channel){\n    this.off(channel.stateChangeRefs)\n    this.channels = this.channels.filter(c => c !== channel)\n  }\n\n  /**\n   * Removes `onOpen`, `onClose`, `onError,` and `onMessage` registrations.\n   *\n   * @param {string[]} refs - list of refs returned by calls to\n   *                 `onOpen`, `onClose`, `onError,` and `onMessage`\n   */\n  off(refs){\n    for(let key in this.stateChangeCallbacks){\n      this.stateChangeCallbacks[key] = this.stateChangeCallbacks[key].filter(([ref]) => {\n        return refs.indexOf(ref) === -1\n      })\n    }\n  }\n\n  /**\n   * Initiates a new channel for the given topic\n   *\n   * @param {string} topic\n   * @param {Params | (() => Params)} [chanParams]- Parameters for the channel\n   * @returns {Channel}\n   */\n  channel(topic, chanParams = {}){\n    let chan = new Channel(topic, chanParams, this)\n    this.channels.push(chan)\n    return chan\n  }\n\n  /**\n   * @param {Message<Record<string, any>>} data\n   */\n  push(data){\n    if(this.hasLogger()){\n      let {topic, event, payload, ref, join_ref} = data\n      this.log(\"push\", `${topic} ${event} (${join_ref}, ${ref})`, payload)\n    }\n\n    if(this.isConnected()){\n      this.encode(data, result => this.conn.send(result))\n    } else {\n      this.sendBuffer.push(() => this.encode(data, result => this.conn.send(result)))\n    }\n  }\n\n  /**\n   * Return the next message ref, accounting for overflows\n   * @returns {string}\n   */\n  makeRef(){\n    let newRef = this.ref + 1\n    if(newRef === this.ref){ this.ref = 0 } else { this.ref = newRef }\n\n    return this.ref.toString()\n  }\n\n  sendHeartbeat(){\n    if(!this.isConnected()){\n      try {\n        this.heartbeatCallback(\"disconnected\")\n      } catch (e){\n        this.log(\"error\", \"error in heartbeat callback\", e)\n      }\n      return\n    }\n    if(this.pendingHeartbeatRef){\n      this.heartbeatTimeout()\n      return\n    }\n    this.pendingHeartbeatRef = this.makeRef()\n    this.heartbeatSentAt = Date.now()\n    this.push({topic: \"phoenix\", event: \"heartbeat\", payload: {}, ref: this.pendingHeartbeatRef})\n    try {\n      this.heartbeatCallback(\"sent\")\n    } catch (e){\n      this.log(\"error\", \"error in heartbeat callback\", e)\n    }\n    this.heartbeatTimeoutTimer = setTimeout(() => this.heartbeatTimeout(), this.heartbeatIntervalMs)\n  }\n\n  flushSendBuffer(){\n    if(this.isConnected() && this.sendBuffer.length > 0){\n      this.sendBuffer.forEach(callback => callback())\n      this.sendBuffer = []\n    }\n  }\n\n  /**\n  * @param {MessageEvent<any>} rawMessage\n  */\n  onConnMessage(rawMessage){\n    this.decode(rawMessage.data, msg => {\n      let {topic, event, payload, ref, join_ref} = msg\n      if(ref && ref === this.pendingHeartbeatRef){\n        const latency = this.heartbeatSentAt ? Date.now() - this.heartbeatSentAt : undefined\n        this.clearHeartbeats()\n        try {\n          this.heartbeatCallback(payload.status === \"ok\" ? \"ok\" : \"error\", latency)\n        } catch (e){\n          this.log(\"error\", \"error in heartbeat callback\", e)\n        }\n        this.pendingHeartbeatRef = null\n        this.heartbeatSentAt = null\n        if(this.autoSendHeartbeat){\n          this.heartbeatTimer = setTimeout(() => this.sendHeartbeat(), this.heartbeatIntervalMs)\n        }\n      }\n\n      if(this.hasLogger()) this.log(\"receive\", `${payload.status || \"\"} ${topic} ${event} ${ref && \"(\" + ref + \")\" || \"\"}`.trim(), payload)\n\n      for(let i = 0; i < this.channels.length; i++){\n        const channel = this.channels[i]\n        if(!channel.isMember(topic, event, payload, join_ref)){ continue }\n        channel.trigger(event, payload, ref, join_ref)\n      }\n\n      this.triggerStateCallbacks(\"message\", msg)\n    })\n  }\n\n  /**\n   * @private\n   * @template {keyof SocketStateChangeCallbacks} K\n   * @param {K} event\n   * @param {...Parameters<SocketStateChangeCallbacks[K][number][1]>} args\n   * @returns {void}\n   */\n  triggerStateCallbacks(event, ...args){\n    try {\n      this.stateChangeCallbacks[event].forEach(([_, callback]) => {\n        try {\n          callback(...args)\n        } catch (e){\n          this.log(\"error\", `error in ${event} callback`, e)\n        }\n      })\n    } catch (e){\n      this.log(\"error\", `error triggering ${event} callbacks`, e)\n    }\n  }\n\n  leaveOpenTopic(topic){\n    let dupChannel = this.channels.find(c => c.topic === topic && (c.isJoined() || c.isJoining()))\n    if(dupChannel){\n      if(this.hasLogger()) this.log(\"transport\", `leaving duplicate topic \"${topic}\"`)\n      dupChannel.leave()\n    }\n  }\n}\n", "import { Presence } from '@supabase/phoenix'\nimport type { PresenceState, PresenceStates } from './types'\nimport type {\n  RealtimePresenceOptions,\n  RealtimePresenceState,\n  Presence as RealtimePresenceType,\n} from '../RealtimePresence'\nimport ChannelAdapter from './channelAdapter'\n\nexport default class PresenceAdapter {\n  private presence: Presence\n\n  constructor(channel: ChannelAdapter, opts?: RealtimePresenceOptions) {\n    const phoenixOptions = phoenixPresenceOptions(opts)\n    this.presence = new Presence(channel.getChannel(), phoenixOptions)\n\n    this.presence.onJoin((key, currentPresence, newPresence) => {\n      const onJoinPayload = PresenceAdapter.onJoinPayload(key, currentPresence, newPresence)\n      channel.getChannel().trigger('presence', onJoinPayload)\n    })\n\n    this.presence.onLeave((key, currentPresence, leftPresence) => {\n      const onLeavePayload = PresenceAdapter.onLeavePayload(key, currentPresence, leftPresence)\n      channel.getChannel().trigger('presence', onLeavePayload)\n    })\n\n    this.presence.onSync(() => {\n      channel.getChannel().trigger('presence', { event: 'sync' })\n    })\n  }\n\n  get state() {\n    return PresenceAdapter.transformState(this.presence.state)\n  }\n\n  /**\n   * @private\n   * Remove 'metas' key\n   * Change 'phx_ref' to 'presence_ref'\n   * Remove 'phx_ref' and 'phx_ref_prev'\n   *\n   * @example Transform state\n   * // returns {\n   *  abc123: [\n   *    { presence_ref: '2', user_id: 1 },\n   *    { presence_ref: '3', user_id: 2 }\n   *  ]\n   * }\n   * RealtimePresence.transformState({\n   *  abc123: {\n   *    metas: [\n   *      { phx_ref: '2', phx_ref_prev: '1' user_id: 1 },\n   *      { phx_ref: '3', user_id: 2 }\n   *    ]\n   *  }\n   * })\n   *\n   */\n  static transformState(state: PresenceStates): RealtimePresenceState {\n    state = cloneState(state)\n\n    return Object.getOwnPropertyNames(state).reduce((newState, key) => {\n      const presences = state[key]\n      newState[key] = transformState(presences)\n\n      return newState\n    }, {} as RealtimePresenceState)\n  }\n\n  static onJoinPayload(key: string, currentPresence: PresenceState, newPresence: PresenceState) {\n    const currentPresences = parseCurrentPresences(currentPresence)\n    const newPresences = transformState(newPresence)\n\n    return {\n      event: 'join',\n      key,\n      currentPresences,\n      newPresences,\n    }\n  }\n\n  static onLeavePayload(key: string, currentPresence: PresenceState, leftPresence: PresenceState) {\n    const currentPresences = parseCurrentPresences(currentPresence)\n    const leftPresences = transformState(leftPresence)\n\n    return {\n      event: 'leave',\n      key,\n      currentPresences,\n      leftPresences,\n    }\n  }\n}\n\nfunction transformState(presences: PresenceState) {\n  return presences.metas.map((presence) => {\n    // Object spread compiles to Object.assign for ES2017, which treats __proto__ as a setter.\n    const descriptors = Object.getOwnPropertyDescriptors(presence)\n    const transformedPresence = Object.defineProperties({}, descriptors) as typeof presence\n    transformedPresence['presence_ref'] = transformedPresence['phx_ref']\n\n    delete transformedPresence['phx_ref']\n    delete transformedPresence['phx_ref_prev']\n\n    return transformedPresence\n  }) as RealtimePresenceType[]\n}\n\nfunction cloneState(state: PresenceStates): PresenceStates {\n  return JSON.parse(JSON.stringify(state))\n}\n\nfunction phoenixPresenceOptions(opts?: RealtimePresenceOptions) {\n  return opts?.events && { events: opts.events }\n}\n\nfunction parseCurrentPresences(currentPresences?: PresenceState) {\n  return currentPresences?.metas ? transformState(currentPresences) : []\n}\n", "/*\n  This file draws heavily from https://github.com/phoenixframework/phoenix/blob/d344ec0a732ab4ee204215b31de69cf4be72e3bf/assets/js/phoenix/presence.js\n  License: https://github.com/phoenixframework/phoenix/blob/d344ec0a732ab4ee204215b31de69cf4be72e3bf/LICENSE.md\n*/\n\nimport type RealtimeChannel from './RealtimeChannel'\nimport PresenceAdapter from './phoenix/presenceAdapter'\n\nexport type Presence<T extends { [key: string]: any } = {}> = {\n  presence_ref: string\n} & T\n\nexport type RealtimePresenceState<T extends { [key: string]: any } = {}> = {\n  [key: string]: Presence<T>[]\n}\n\nexport type RealtimePresenceJoinPayload<T extends { [key: string]: any }> = {\n  event: `${REALTIME_PRESENCE_LISTEN_EVENTS.JOIN}`\n  key: string\n  currentPresences: Presence<T>[]\n  newPresences: Presence<T>[]\n}\n\nexport type RealtimePresenceLeavePayload<T extends { [key: string]: any }> = {\n  event: `${REALTIME_PRESENCE_LISTEN_EVENTS.LEAVE}`\n  key: string\n  currentPresences: Presence<T>[]\n  leftPresences: Presence<T>[]\n}\n\nexport enum REALTIME_PRESENCE_LISTEN_EVENTS {\n  SYNC = 'sync',\n  JOIN = 'join',\n  LEAVE = 'leave',\n}\n\nexport type RealtimePresenceOptions = {\n  events?: { state: string; diff: string }\n}\n\nexport default class RealtimePresence {\n  get state() {\n    return this.presenceAdapter.state\n  }\n\n  private presenceAdapter: PresenceAdapter\n\n  /**\n   * Creates a Presence helper that keeps the local presence state in sync with the server.\n   *\n   * @param channel - The realtime channel to bind to.\n   * @param opts - Optional custom event names, e.g. `{ events: { state: 'state', diff: 'diff' } }`.\n   *\n   * @category Realtime\n   *\n   * @example Example for a presence channel\n   * ```ts\n   * const presence = new RealtimePresence(channel)\n   *\n   * channel.on('presence', ({ event, key }) => {\n   *   console.log(`Presence ${event} on ${key}`)\n   * })\n   * ```\n   */\n  constructor(\n    public channel: RealtimeChannel,\n    opts?: RealtimePresenceOptions\n  ) {\n    this.presenceAdapter = new PresenceAdapter(this.channel.channelAdapter, opts)\n  }\n}\n", "/**\n * Normalize the various shapes a channel error reason can take into a real `Error`.\n *\n * Transport-level channel errors arrive as a `CloseEvent`, a transport `Event`, an `Error`,\n * a string, or `undefined` depending on which path in the underlying socket fired. Server-reply\n * errors arrive as a payload object. This helper produces a consistent `Error` for every case\n * and preserves the original via `cause` so callers can still inspect the raw event.\n */\nexport function normalizeChannelError(reason: unknown): Error {\n  if (reason instanceof Error) {\n    return reason\n  }\n\n  if (typeof reason === 'string') {\n    return new Error(reason)\n  }\n\n  if (reason && typeof reason === 'object') {\n    const obj = reason as Record<string, unknown>\n\n    if (typeof obj.code === 'number') {\n      const detail = typeof obj.reason === 'string' && obj.reason ? ` (${obj.reason})` : ''\n      return new Error(`socket closed: ${obj.code}${detail}`, { cause: reason })\n    }\n\n    return new Error('channel error: transport failure', { cause: reason })\n  }\n\n  return new Error('channel error: connection lost')\n}\n", "import { Channel } from '@supabase/phoenix'\nimport { CHANNEL_STATES, MAX_PUSH_BUFFER_SIZE } from '../lib/constants'\nimport type { RealtimeChannelOptions } from '../RealtimeChannel'\nimport SocketAdapter from './socketAdapter'\nimport type {\n  ChannelBindingCallback,\n  ChannelOnMessage,\n  ChannelOnErrorCallback,\n  ChannelFilterBindings,\n  Params,\n  ChannelState,\n  Push,\n  Timer,\n} from './types'\n\nexport default class ChannelAdapter {\n  private channel: Channel\n  private socket: SocketAdapter\n\n  constructor(socket: SocketAdapter, topic: string, params: RealtimeChannelOptions) {\n    const phoenixParams = phoenixChannelParams(params)\n    this.channel = socket.getSocket().channel(topic, phoenixParams)\n    this.socket = socket\n  }\n\n  get state(): ChannelState {\n    return this.channel.state\n  }\n\n  set state(state: ChannelState) {\n    this.channel.state = state\n  }\n\n  get joinedOnce(): boolean {\n    return this.channel.joinedOnce\n  }\n\n  get joinPush(): Push {\n    return this.channel.joinPush\n  }\n\n  get rejoinTimer(): Timer {\n    return this.channel.rejoinTimer\n  }\n\n  on(event: string, callback: ChannelBindingCallback): number {\n    return this.channel.on(event, callback)\n  }\n\n  off(event: string, refNumber?: number) {\n    this.channel.off(event, refNumber)\n  }\n\n  subscribe(timeout?: number): Push {\n    return this.channel.join(timeout)\n  }\n\n  unsubscribe(timeout?: number): Push {\n    return this.channel.leave(timeout)\n  }\n\n  teardown() {\n    this.channel.teardown()\n  }\n\n  onClose(callback: ChannelBindingCallback) {\n    this.channel.onClose(callback)\n  }\n\n  onError(callback: ChannelOnErrorCallback): number {\n    return this.channel.onError(callback)\n  }\n\n  push(event: string, payload: { [key: string]: any }, timeout?: number): Push {\n    let push: Push\n\n    try {\n      push = this.channel.push(event, payload, timeout)\n    } catch (error) {\n      throw new Error(\n        `tried to push '${event}' to '${this.channel.topic}' before joining. Use channel.subscribe() before pushing events`\n      )\n    }\n\n    if (this.channel.pushBuffer.length > MAX_PUSH_BUFFER_SIZE) {\n      const removedPush = this.channel.pushBuffer.shift()!\n      removedPush.cancelTimeout()\n      this.socket.log(\n        'channel',\n        `discarded push due to buffer overflow: ${removedPush.event}`,\n        removedPush.payload()\n      )\n    }\n    return push\n  }\n\n  updateJoinPayload(payload: Record<string, any>) {\n    const oldPayload = this.channel.joinPush.payload()\n    this.channel.joinPush.payload = () => ({ ...oldPayload, ...payload })\n  }\n\n  canPush() {\n    return this.socket.isConnected() && this.state === CHANNEL_STATES.joined\n  }\n\n  isJoined() {\n    return this.state === CHANNEL_STATES.joined\n  }\n\n  isJoining() {\n    return this.state === CHANNEL_STATES.joining\n  }\n\n  isClosed() {\n    return this.state === CHANNEL_STATES.closed\n  }\n\n  isLeaving() {\n    return this.state === CHANNEL_STATES.leaving\n  }\n\n  updateFilterBindings(filterBindings: ChannelFilterBindings) {\n    this.channel.filterBindings = filterBindings\n  }\n\n  updatePayloadTransform(callback: ChannelOnMessage) {\n    this.channel.onMessage = callback\n  }\n\n  /**\n   * @internal\n   */\n  getChannel() {\n    return this.channel\n  }\n}\n\nfunction phoenixChannelParams(options: RealtimeChannelOptions): Params {\n  return {\n    config: {\n      ...{\n        broadcast: { ack: false, self: false },\n        presence: { key: '', enabled: false },\n        private: false,\n      },\n      ...options.config,\n    },\n  }\n}\n", "/**\n * Comparison operators accepted in a Postgres Changes `filter` string.\n *\n * These mirror the PostgREST operator surface and are evaluated server-side.\n * Any operator can be negated via {@link RealtimePostgresFilterBuilder.not}\n * (the `not.` prefix).\n *\n * This is the subset of PostgREST's `FilterOperator` (see `postgrest-js`) that\n * Realtime Postgres Changes supports. Containment, range and full-text search\n * operators (`cs`, `cd`, `ov`, range ops, `fts`, \u2026) are intentionally not\n * included because the Realtime server does not evaluate them.\n *\n * - `eq`, `neq`, `lt`, `lte`, `gt`, `gte` \u2014 comparison\n * - `in` \u2014 membership: `status=in.(active,pending)`\n * - `like`, `ilike` \u2014 pattern match (case-sensitive / insensitive): `title=like.%foo%`\n * - `is` \u2014 `IS` check against `null` / `true` / `false` / `unknown`: `deleted_at=is.null`\n * - `match`, `imatch` \u2014 POSIX regex match (`~` / `~*`)\n * - `isdistinct` \u2014 NULL-safe inequality (`IS DISTINCT FROM`)\n */\nexport type RealtimePostgresChangesFilterOperator =\n  | 'eq'\n  | 'neq'\n  | 'lt'\n  | 'lte'\n  | 'gt'\n  | 'gte'\n  | 'in'\n  | 'like'\n  | 'ilike'\n  | 'is'\n  | 'match'\n  | 'imatch'\n  | 'isdistinct'\n\n/** Scalar value accepted by a single filter operator. */\nexport type RealtimeFilterValue = string | number | boolean | null\n\n/** Value accepted by the `is` operator. */\nexport type RealtimeIsFilterValue = null | boolean | 'null' | 'true' | 'false' | 'unknown'\n\n// Reserved characters that force PostgREST-style quoting: `[,()]` (which the\n// server reads as condition/list delimiters) plus `\"`/`\\` (escaped inside quotes).\nconst PostgrestReservedCharsRegexp = /[,()\"\\\\]/\n\nconst needsQuoting = (value: string): boolean =>\n  PostgrestReservedCharsRegexp.test(value) || value !== value.trim()\n\nconst quote = (value: string): string => `\"${value.replace(/\\\\/g, '\\\\\\\\').replace(/\"/g, '\\\\\"')}\"`\n\nconst serializeScalar = (value: RealtimeFilterValue): string => {\n  const serialized = value === null ? 'null' : String(value)\n  return needsQuoting(serialized) ? quote(serialized) : serialized\n}\n\nconst serializeIsValue = (value: RealtimeIsFilterValue): string =>\n  value === null ? 'null' : String(value)\n\n// Builds the `operator.value` portion of a filter (everything after `column=`).\nconst serialize = (operator: RealtimePostgresChangesFilterOperator, value: unknown): string => {\n  if (operator === 'in') {\n    const values = Array.isArray(value) ? value : [value]\n    if (values.length === 0) {\n      throw new Error('Realtime `in` filter requires at least one value.')\n    }\n    const items = Array.from(new Set(values))\n      .map((v) => serializeScalar(v as RealtimeFilterValue))\n      .join(',')\n    return `in.(${items})`\n  }\n\n  if (operator === 'is') {\n    return `is.${serializeIsValue(value as RealtimeIsFilterValue)}`\n  }\n\n  return `${operator}.${serializeScalar(value as RealtimeFilterValue)}`\n}\n\n/**\n * Fluent builder for Postgres Changes `filter` strings.\n *\n * Each method appends a single `column=operator.value` condition. Multiple\n * conditions are combined with commas, which the Realtime server applies as an\n * `AND`. Pass an instance straight to `channel.on('postgres_changes', \u2026)` \u2014 the\n * SDK serializes it to a string automatically \u2014 or call {@link build} to obtain\n * the string yourself.\n *\n * The builder mirrors the `postgrest-js` filter API (`eq`, `neq`, `in`, `like`,\n * `not`, \u2026) for the operators that Realtime supports. Values containing reserved\n * characters (`,`, `(`, `)`, `\"`, `\\`) \u2014 or surrounding whitespace \u2014 are\n * automatically double-quoted and escaped the same way PostgREST does, so they\n * survive the server's filter parser; all other values are sent verbatim.\n *\n * The filter is snapshotted when passed to `channel.on(...)`; mutating the\n * builder afterwards does not affect an existing subscription. An empty builder\n * serializes to `''`, which the server treats as \"no filter\".\n *\n * @example\n * channel.on('postgres_changes', {\n *   event: '*',\n *   schema: 'public',\n *   table: 'users',\n *   filter: postgresChangesFilter().eq('id', 1).lt('age', 30), // \u2192 'id=eq.1,age=lt.30'\n * }, (payload) => { ... })\n */\nexport class RealtimePostgresFilterBuilder {\n  private readonly filters: string[] = []\n\n  private add(\n    column: string,\n    operator: RealtimePostgresChangesFilterOperator,\n    value: unknown,\n    negate = false\n  ): this {\n    const prefix = negate ? 'not.' : ''\n    this.filters.push(`${column}=${prefix}${serialize(operator, value)}`)\n    return this\n  }\n\n  /** Match rows where `column` equals `value` (`column=eq.value`). */\n  eq(column: string, value: RealtimeFilterValue): this {\n    return this.add(column, 'eq', value)\n  }\n\n  /** Match rows where `column` does not equal `value` (`column=neq.value`). */\n  neq(column: string, value: RealtimeFilterValue): this {\n    return this.add(column, 'neq', value)\n  }\n\n  /** Match rows where `column` is greater than `value` (`column=gt.value`). */\n  gt(column: string, value: RealtimeFilterValue): this {\n    return this.add(column, 'gt', value)\n  }\n\n  /** Match rows where `column` is greater than or equal to `value` (`column=gte.value`). */\n  gte(column: string, value: RealtimeFilterValue): this {\n    return this.add(column, 'gte', value)\n  }\n\n  /** Match rows where `column` is less than `value` (`column=lt.value`). */\n  lt(column: string, value: RealtimeFilterValue): this {\n    return this.add(column, 'lt', value)\n  }\n\n  /** Match rows where `column` is less than or equal to `value` (`column=lte.value`). */\n  lte(column: string, value: RealtimeFilterValue): this {\n    return this.add(column, 'lte', value)\n  }\n\n  /**\n   * Match rows where `column` is one of `values` (`column=in.(a,b,c)`).\n   * Requires at least one value; duplicates are removed. An element containing a\n   * reserved character is double-quoted (`in.(\"a,b\",c)`), so commas inside an\n   * element are preserved. `null` is intentionally not accepted (`IN (null)`\n   * never matches in SQL) \u2014 use `is`/`not('col','is',null)` for null checks.\n   */\n  in(column: string, values: ReadonlyArray<string | number | boolean>): this {\n    return this.add(column, 'in', values)\n  }\n\n  /** Match rows where `column` matches the case-sensitive `pattern` (`column=like.pattern`). */\n  like(column: string, pattern: string): this {\n    return this.add(column, 'like', pattern)\n  }\n\n  /** Match rows where `column` matches the case-insensitive `pattern` (`column=ilike.pattern`). */\n  ilike(column: string, pattern: string): this {\n    return this.add(column, 'ilike', pattern)\n  }\n\n  /** Match rows where `column` matches the POSIX regex `pattern` (`column=match.pattern`). */\n  match(column: string, pattern: string): this {\n    return this.add(column, 'match', pattern)\n  }\n\n  /** Match rows where `column` matches the case-insensitive POSIX regex `pattern` (`column=imatch.pattern`). */\n  imatch(column: string, pattern: string): this {\n    return this.add(column, 'imatch', pattern)\n  }\n\n  /**\n   * Match rows where `column` `IS` the given value (`column=is.null`).\n   * Accepts `null`, a boolean, or the keywords `'null' | 'true' | 'false' | 'unknown'`.\n   */\n  is(column: string, value: RealtimeIsFilterValue): this {\n    return this.add(column, 'is', value)\n  }\n\n  /** Match rows where `column` is distinct from `value` (`column=isdistinct.value`). NULL-safe inequality. */\n  isDistinct(column: string, value: RealtimeFilterValue): this {\n    return this.add(column, 'isdistinct', value)\n  }\n\n  /**\n   * Negate any operator with the `not.` prefix (`column=not.operator.value`).\n   * `in` takes an array, `is` takes an `IS` keyword/boolean/null, and every\n   * other operator takes a scalar value.\n   *\n   * @example\n   * postgresChangesFilter().not('status', 'in', ['draft', 'archived'])\n   * // \u2192 status=not.in.(draft,archived)\n   * postgresChangesFilter().not('deleted_at', 'is', null)\n   * // \u2192 deleted_at=not.is.null\n   */\n  not(column: string, operator: 'in', value: ReadonlyArray<string | number | boolean>): this\n  not(column: string, operator: 'is', value: RealtimeIsFilterValue): this\n  not(\n    column: string,\n    operator: Exclude<RealtimePostgresChangesFilterOperator, 'in' | 'is'>,\n    value: RealtimeFilterValue\n  ): this\n  not(\n    column: string,\n    operator: RealtimePostgresChangesFilterOperator,\n    value: RealtimeFilterValue | ReadonlyArray<string | number | boolean>\n  ): this {\n    return this.add(column, operator, value, true)\n  }\n\n  /**\n   * Serialize all conditions into the comma-separated (AND) filter string.\n   *\n   * Conditions are joined by commas, which the server applies as `AND`. A scalar\n   * value (or single `in` element) that contains a reserved character \u2014 `,`,\n   * `(`, `)`, `\"`, `\\` \u2014 or surrounding whitespace is double-quoted and escaped\n   * the way PostgREST does, so commas inside a value are preserved rather than\n   * read as a condition boundary.\n   */\n  build(): string {\n    return this.filters.join(',')\n  }\n\n  /** Alias for {@link build}; lets the builder be used wherever a string is expected. */\n  toString(): string {\n    return this.build()\n  }\n}\n\n/**\n * Create a {@link RealtimePostgresFilterBuilder} for composing a Postgres\n * Changes `filter`. Conditions are combined with `AND`.\n *\n * @example\n * import { postgresChangesFilter } from '@supabase/realtime-js'\n *\n * channel.on('postgres_changes', {\n *   event: 'UPDATE',\n *   schema: 'public',\n *   table: 'orders',\n *   filter: postgresChangesFilter().gt('amount', 100).eq('status', 'open'),\n * }, (payload) => { ... })\n */\nexport const postgresChangesFilter = (): RealtimePostgresFilterBuilder =>\n  new RealtimePostgresFilterBuilder()\n", "import {\n  CHANNEL_EVENTS,\n  CHANNEL_STATES,\n  DEFAULT_POSTGRES_CHANGES_WAIT_TIMEOUT,\n  POSTGRES_CHANGES_WAIT_ERROR_GRACE,\n} from './lib/constants'\nimport type { ChannelState } from './lib/constants'\nimport type RealtimeClient from './RealtimeClient'\nimport RealtimePresence, { REALTIME_PRESENCE_LISTEN_EVENTS } from './RealtimePresence'\nimport type {\n  RealtimePresenceJoinPayload,\n  RealtimePresenceLeavePayload,\n  RealtimePresenceState,\n} from './RealtimePresence'\nimport * as Transformers from './lib/transformers'\nimport { httpEndpointURL } from './lib/transformers'\nimport { normalizeChannelError } from './lib/normalizeChannelError'\nimport ChannelAdapter from './phoenix/channelAdapter'\nimport { ChannelBindingCallback, ChannelOnErrorCallback } from './phoenix/types'\nimport type { Timer } from './phoenix/types'\nimport { RealtimePostgresFilterBuilder } from './RealtimePostgresFilterBuilder'\nimport type { RealtimePostgresChangesFilterOperator } from './RealtimePostgresFilterBuilder'\n\nexport type { RealtimePostgresChangesFilterOperator } from './RealtimePostgresFilterBuilder'\nexport {\n  RealtimePostgresFilterBuilder,\n  postgresChangesFilter,\n} from './RealtimePostgresFilterBuilder'\n\ntype ReplayOption = {\n  since: number\n  limit?: number\n}\n\nexport type RealtimeChannelOptions = {\n  config: {\n    /**\n     * self option enables client to receive message it broadcast\n     * ack option instructs server to acknowledge that broadcast message was received\n     * replay option instructs server to replay broadcast messages\n     * replication_ready option instructs the server to emit a `system` event once the\n     * Postgres replication connection backing this channel is established and ready to\n     * stream changes. Listen for it with `channel.on('system', {}, (payload) => ...)`;\n     * the payload's `status` is `'ok'` (`message: 'Replication connection established'`)\n     * on success or `'error'` if the connection is not ready in time.\n     */\n    broadcast?: {\n      self?: boolean\n      ack?: boolean\n      replay?: ReplayOption\n      replication_ready?: boolean\n    }\n    /**\n     * key option is used to track presence payload across clients\n     *\n     * enabled controls whether this client receives presence state and updates from other\n     * clients \u2014 set it to true (or add an `.on('presence', ...)` listener, which enables it\n     * automatically) if you want to see who else is present. Without it, this client's\n     * `presenceState()` stays empty and no `presence` events fire for you, because the\n     * underlying presence state machine buffers incoming updates until it has received an\n     * initial snapshot, which is only requested when this flag is set.\n     *\n     * It does not gate the other direction: calling `track()` always makes this client\n     * visible to other subscribers that have presence enabled, regardless of this client's\n     * own `enabled` setting. On RLS-protected (private) channels, receiving presence updates\n     * additionally requires the `presence.read` policy to authorize this client.\n     */\n    presence?: { key?: string; enabled?: boolean }\n    /**\n     * defines if the channel is private or not and if RLS policies will be used to check data\n     */\n    private?: boolean\n    /**\n     * By default, `subscribe()` reports `SUBSCRIBED` as soon as the channel itself has joined,\n     * which can happen before the server has actually established the `postgres_changes`\n     * subscription (e.g. before the replication slot is streaming). Set `wait: true` to instead\n     * hold the `SUBSCRIBED` callback until the server confirms the postgres_changes subscription\n     * is active.\n     *\n     * If the subscription cannot be established, the server rejects the join and `subscribe()`\n     * reports `CHANNEL_ERROR` with the server's reason (e.g.\n     * `PostgresChangesSubscribeTimeout: ...` when the wait ran out, or\n     * `RealtimeDisabledForConfiguration: ...` when the table is not enabled for Realtime).\n     *\n     * Has no effect on a channel with no `postgres_changes` bindings.\n     *\n     * Setting `wait: true` automatically extends the channel's join timeout so it outlasts the\n     * server's held reply, so you don't need to pass a larger `timeout` to `subscribe()` yourself.\n     * As a side effect of how Phoenix tracks the join timeout, other pushes on the channel that\n     * do not pass an explicit timeout inherit the extended value too.\n     */\n    postgres_changes_options?: {\n      wait?: boolean\n      /**\n       * Milliseconds the server should wait for postgres_changes subscription confirmation when\n       * `wait` is `true`. Defaults to 15000, and the server clamps it to its own configured\n       * maximum (20s by default), so asking for more waits less.\n       */\n      timeout?: number\n    }\n  }\n}\n\ntype RealtimeChangesPayloadBase = {\n  schema: string\n  table: string\n}\n\ntype RealtimeBroadcastChangesPayloadBase = RealtimeChangesPayloadBase & {\n  id: string\n}\n\nexport type RealtimeBroadcastInsertPayload<T extends { [key: string]: any }> =\n  RealtimeBroadcastChangesPayloadBase & {\n    operation: `${REALTIME_POSTGRES_CHANGES_LISTEN_EVENT.INSERT}`\n    record: T\n    old_record: null\n  }\n\nexport type RealtimeBroadcastUpdatePayload<T extends { [key: string]: any }> =\n  RealtimeBroadcastChangesPayloadBase & {\n    operation: `${REALTIME_POSTGRES_CHANGES_LISTEN_EVENT.UPDATE}`\n    record: T\n    old_record: T\n  }\n\nexport type RealtimeBroadcastDeletePayload<T extends { [key: string]: any }> =\n  RealtimeBroadcastChangesPayloadBase & {\n    operation: `${REALTIME_POSTGRES_CHANGES_LISTEN_EVENT.DELETE}`\n    record: null\n    old_record: T\n  }\n\nexport type RealtimeBroadcastPayload<T extends { [key: string]: any }> =\n  | RealtimeBroadcastInsertPayload<T>\n  | RealtimeBroadcastUpdatePayload<T>\n  | RealtimeBroadcastDeletePayload<T>\n\ntype RealtimePostgresChangesPayloadBase = {\n  schema: string\n  table: string\n  commit_timestamp: string\n  errors: string[]\n}\n\nexport type RealtimePostgresInsertPayload<T extends { [key: string]: any }> =\n  RealtimePostgresChangesPayloadBase & {\n    eventType: `${REALTIME_POSTGRES_CHANGES_LISTEN_EVENT.INSERT}`\n    new: T\n    old: {}\n  }\n\nexport type RealtimePostgresUpdatePayload<T extends { [key: string]: any }> =\n  RealtimePostgresChangesPayloadBase & {\n    eventType: `${REALTIME_POSTGRES_CHANGES_LISTEN_EVENT.UPDATE}`\n    new: T\n    old: Partial<T>\n  }\n\nexport type RealtimePostgresDeletePayload<T extends { [key: string]: any }> =\n  RealtimePostgresChangesPayloadBase & {\n    eventType: `${REALTIME_POSTGRES_CHANGES_LISTEN_EVENT.DELETE}`\n    new: {}\n    old: Partial<T>\n  }\n\nexport type RealtimePostgresChangesPayload<T extends { [key: string]: any }> =\n  | RealtimePostgresInsertPayload<T>\n  | RealtimePostgresUpdatePayload<T>\n  | RealtimePostgresDeletePayload<T>\n\nexport type RealtimePostgresChangesFilter<T extends `${REALTIME_POSTGRES_CHANGES_LISTEN_EVENT}`> = {\n  /**\n   * The type of database change to listen to.\n   */\n  event: T\n  /**\n   * The database schema to listen to.\n   */\n  schema: string\n  /**\n   * The database table to listen to.\n   */\n  table?: string\n  /**\n   * Receive database changes only when the filter is matched.\n   *\n   * A filter is a `column=operator.value` expression, e.g. `id=eq.1` or\n   * `title=like.%foo%`. See {@link RealtimePostgresChangesFilterOperator} for\n   * the available operators.\n   *\n   * Multiple filters can be combined with commas; they are applied as an `AND`\n   * condition: `filter: 'id=gt.0,id=lt.100'`.\n   *\n   * Any operator can be negated with the `not.` prefix: `filter: 'status=not.in.(draft,archived)'`.\n   *\n   * The server splits conditions on commas outside quotes/parentheses. To\n   * include a reserved character (`,`, `(`, `)`) in a value, wrap it in double\n   * quotes PostgREST-style: `name=eq.\"a,b\"`. The {@link RealtimePostgresFilterBuilder}\n   * does this quoting for you.\n   *\n   * Instead of a raw string you can pass a {@link RealtimePostgresFilterBuilder}\n   * (via `postgresChangesFilter()`) for a type-checked, ergonomic way to compose filters; the\n   * SDK serializes it to a string automatically.\n   */\n  filter?: string | RealtimePostgresFilterBuilder\n  /**\n   * Restrict the change payload to a subset of columns instead of receiving the\n   * full row. Reduces payload size (helpful for large `bytea`/`jsonb` columns)\n   * and the data transferred per event.\n   *\n   * The listed columns must be selectable by the subscribing role.\n   *\n   * @example\n   * channel.on('postgres_changes', {\n   *   event: '*',\n   *   schema: 'public',\n   *   table: 'users',\n   *   select: ['id', 'first_name'],\n   * }, (payload) => {\n   *   // payload.new only contains { id, first_name }\n   * })\n   */\n  select?: string[]\n}\n\nexport type RealtimeChannelSendResponse = 'ok' | 'timed out' | 'error' | (string & {})\n\n/**\n * Payload of a `system` event emitted by the server.\n *\n * Most notably, when a channel is created with `config.broadcast.replication_ready: true`,\n * the server sends one of these once the Postgres replication connection is ready\n * (`status: 'ok'`) or fails to become ready in time (`status: 'error'`).\n */\nexport type RealtimeSystemPayload = {\n  /** The extension that produced the message, e.g. `'system'` or `'postgres_changes'`. */\n  extension: 'system' | 'postgres_changes' | (string & {})\n  /** `'ok'` on success, `'error'` on failure. */\n  status: 'ok' | 'error' | (string & {})\n  /** Human-readable description, e.g. `'Replication connection established'`. */\n  message: string\n  /** The channel (sub)topic the message refers to. */\n  channel: string\n}\n\nexport enum REALTIME_POSTGRES_CHANGES_LISTEN_EVENT {\n  ALL = '*',\n  INSERT = 'INSERT',\n  UPDATE = 'UPDATE',\n  DELETE = 'DELETE',\n}\n\nexport enum REALTIME_LISTEN_TYPES {\n  BROADCAST = 'broadcast',\n  PRESENCE = 'presence',\n  POSTGRES_CHANGES = 'postgres_changes',\n  SYSTEM = 'system',\n}\n\nexport enum REALTIME_SUBSCRIBE_STATES {\n  SUBSCRIBED = 'SUBSCRIBED',\n  TIMED_OUT = 'TIMED_OUT',\n  CLOSED = 'CLOSED',\n  CHANNEL_ERROR = 'CHANNEL_ERROR',\n}\n\nexport const REALTIME_CHANNEL_STATES = CHANNEL_STATES\n\ntype PostgresChangesFilters = {\n  postgres_changes: {\n    id: string\n    event: string\n    schema?: string\n    table?: string\n    filter?: string\n    select?: string[]\n  }[]\n}\n\n/**\n * The `postgres_changes` filter fields that determine whether the server collapses two\n * subscriptions into one. `filter` is always the serialized string form by the time it is compared.\n */\ntype PostgresChangesFilterShape = {\n  event?: string\n  schema?: string\n  table?: string\n  filter?: string\n  select?: string[]\n}\n\ntype Binding = {\n  type: string\n  filter: { [key: string]: any }\n  callback: ChannelBindingCallback\n  ref: number\n  id?: string\n}\n\n/** A channel is the basic building block of Realtime\n * and narrows the scope of data flow to subscribed clients.\n * You can think of a channel as a chatroom where participants are able to see who's online\n * and send and receive messages.\n */\nexport default class RealtimeChannel {\n  bindings: Record<string, Binding[]> = {}\n  subTopic: string\n  broadcastEndpointURL: string\n  private: boolean\n  presence: RealtimePresence\n  /** @internal */\n  channelAdapter: ChannelAdapter\n\n  get state() {\n    return this.channelAdapter.state\n  }\n\n  set state(state: ChannelState) {\n    this.channelAdapter.state = state\n  }\n\n  get joinedOnce() {\n    return this.channelAdapter.joinedOnce\n  }\n\n  get timeout() {\n    return this.socket.timeout\n  }\n\n  get joinPush() {\n    return this.channelAdapter.joinPush\n  }\n\n  get rejoinTimer(): Timer {\n    return this.channelAdapter.rejoinTimer\n  }\n\n  /**\n   * Creates a channel that can broadcast messages, sync presence, and listen to Postgres changes.\n   *\n   * The topic determines which realtime stream you are subscribing to. Config options let you\n   * enable acknowledgement for broadcasts, presence tracking, or private channels.\n   *\n   * @category Realtime\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 channel = supabase.channel('room1')\n   * channel\n   *   .on('broadcast', { event: 'cursor-pos' }, (payload) => console.log(payload))\n   *   .subscribe()\n   * ```\n   *\n   * @example Standalone import for bundle-sensitive environments\n   * ```ts\n   * import RealtimeClient from '@supabase/realtime-js'\n   *\n   * const client = new RealtimeClient('https://xyzcompany.supabase.co/realtime/v1', {\n   *   params: { apikey: 'your-publishable-key' },\n   * })\n   * const channel = new RealtimeChannel('realtime:public:messages', { config: {} }, client)\n   * ```\n   */\n  constructor(\n    /** Topic name can be any string. */\n    public topic: string,\n    public params: RealtimeChannelOptions = { config: {} },\n    public socket: RealtimeClient\n  ) {\n    this.subTopic = topic.replace(/^realtime:/i, '')\n    this.params.config = {\n      ...{\n        broadcast: { ack: false, self: false },\n        presence: { key: '', enabled: false },\n        private: false,\n      },\n      ...params.config,\n    }\n\n    this.channelAdapter = new ChannelAdapter(this.socket.socketAdapter, topic, this.params)\n    this.presence = new RealtimePresence(this)\n\n    this._onClose(() => {\n      this.socket._remove(this)\n    })\n\n    this._updateFilterTransform()\n\n    this.broadcastEndpointURL = httpEndpointURL(this.socket.socketAdapter.endPointURL())\n    this.private = this.params.config.private || false\n\n    if (!this.private && this.params.config?.broadcast?.replay) {\n      throw new Error(\n        `tried to use replay on public channel '${this.topic}'. It must be a private channel.`\n      )\n    }\n  }\n\n  /**\n   * Subscribe registers your client with the server.\n   *\n   * The optional `callback` receives a `status` and, on failure, an `err` argument.\n   * Log the full `err` so its `cause`, `name`, and any structured fields aren't hidden\n   * behind `err.message`.\n   *\n   * @category Realtime\n   *\n   * @example Handling errors\n   * ```js\n   * supabase.channel('room1').subscribe((status, err) => {\n   *   if (status === 'CHANNEL_ERROR' || status === 'TIMED_OUT') {\n   *     // Log the full error: its `cause` often holds the underlying reason.\n   *     console.error(status, err)\n   *   }\n   * })\n   * ```\n   */\n  subscribe(\n    callback?: (status: REALTIME_SUBSCRIBE_STATES, err?: Error) => void,\n    timeout = this.timeout\n  ): RealtimeChannel {\n    if (!this.socket.isConnected()) {\n      this.socket.connect()\n    }\n    if (this.channelAdapter.isClosed()) {\n      const {\n        config: { broadcast, presence, private: isPrivate, postgres_changes_options },\n      } = this.params\n\n      const postgres_changes = this.bindings.postgres_changes?.map((r) => r.filter) ?? []\n\n      const presence_enabled =\n        (!!this.bindings[REALTIME_LISTEN_TYPES.PRESENCE] &&\n          this.bindings[REALTIME_LISTEN_TYPES.PRESENCE].length > 0) ||\n        this.params.config.presence?.enabled === true\n      const accessTokenPayload: { access_token?: string } = {}\n      const config = {\n        broadcast,\n        presence: { ...presence, enabled: presence_enabled },\n        postgres_changes,\n        private: isPrivate,\n        ...(postgres_changes_options ? { postgres_changes_options } : {}),\n      }\n\n      if (this.socket.accessTokenValue) {\n        accessTokenPayload.access_token = this.socket.accessTokenValue\n      }\n\n      this._onError((reason: unknown) => {\n        callback?.(REALTIME_SUBSCRIBE_STATES.CHANNEL_ERROR, normalizeChannelError(reason))\n      })\n\n      this._onClose(() => callback?.(REALTIME_SUBSCRIBE_STATES.CLOSED))\n\n      this.updateJoinPayload({ ...{ config }, ...accessTokenPayload })\n\n      this._updateFilterMessage()\n\n      const joinTimeout =\n        postgres_changes_options?.wait && postgres_changes.length > 0\n          ? Math.max(\n              timeout,\n              (postgres_changes_options.timeout ?? DEFAULT_POSTGRES_CHANGES_WAIT_TIMEOUT) +\n                POSTGRES_CHANGES_WAIT_ERROR_GRACE\n            )\n          : timeout\n\n      this.channelAdapter\n        .subscribe(joinTimeout)\n        .receive('ok', async ({ postgres_changes }: PostgresChangesFilters) => {\n          // Only refresh auth if using callback-based tokens\n          if (!this.socket._isManualToken()) {\n            this.socket.setAuth()\n          }\n          if (postgres_changes === undefined) {\n            callback?.(REALTIME_SUBSCRIBE_STATES.SUBSCRIBED)\n            return\n          }\n\n          this._updatePostgresBindings(postgres_changes, callback)\n        })\n        .receive('error', (error: { [key: string]: any }) => {\n          this.state = CHANNEL_STATES.errored\n          const message = Object.values(error).join(', ') || 'error'\n          callback?.(REALTIME_SUBSCRIBE_STATES.CHANNEL_ERROR, new Error(message, { cause: error }))\n        })\n        .receive('timeout', () => {\n          callback?.(REALTIME_SUBSCRIBE_STATES.TIMED_OUT)\n        })\n    }\n    return this\n  }\n\n  private _updatePostgresBindings(\n    postgres_changes: PostgresChangesFilters['postgres_changes'],\n    callback?: (status: REALTIME_SUBSCRIBE_STATES, err?: Error) => void\n  ) {\n    const clientPostgresBindings = this.bindings.postgres_changes\n    const bindingsLen = clientPostgresBindings?.length ?? 0\n    const newPostgresBindings = []\n\n    for (let i = 0; i < bindingsLen; i++) {\n      const clientPostgresBinding = clientPostgresBindings[i]\n      const {\n        filter: { event, schema, table, filter },\n      } = clientPostgresBinding\n      const serverPostgresFilter = postgres_changes && postgres_changes[i]\n\n      if (\n        serverPostgresFilter &&\n        serverPostgresFilter.event === event &&\n        RealtimeChannel.isFilterValueEqual(serverPostgresFilter.schema, schema) &&\n        RealtimeChannel.isFilterValueEqual(serverPostgresFilter.table, table) &&\n        RealtimeChannel.isFilterValueEqual(serverPostgresFilter.filter, filter)\n      ) {\n        newPostgresBindings.push({\n          ...clientPostgresBinding,\n          id: serverPostgresFilter.id,\n        })\n      } else {\n        this.unsubscribe()\n        this.state = CHANNEL_STATES.errored\n\n        callback?.(\n          REALTIME_SUBSCRIBE_STATES.CHANNEL_ERROR,\n          new Error('mismatch between server and client bindings for postgres changes')\n        )\n        return\n      }\n    }\n\n    this.bindings.postgres_changes = newPostgresBindings\n\n    if (this.state != CHANNEL_STATES.errored && callback) {\n      callback(REALTIME_SUBSCRIBE_STATES.SUBSCRIBED)\n    }\n  }\n\n  /**\n   * Returns the current presence state for this channel.\n   *\n   * The shape is a map keyed by presence key (for example a user id) where each entry contains the\n   * tracked metadata for that user.\n   *\n   * @category Realtime\n   */\n  presenceState<T extends { [key: string]: any } = {}>(): RealtimePresenceState<T> {\n    return this.presence.state as RealtimePresenceState<T>\n  }\n\n  /**\n   * Sends the supplied payload to the presence tracker so other subscribers can see that this\n   * client is online. Use `untrack` to stop broadcasting presence for the same key.\n   *\n   * Tracking makes this client visible to other subscribers immediately, regardless of this\n   * channel's `config.presence.enabled` setting or whether it has a `presence` listener \u2014 that\n   * flag only affects whether *this* client receives presence updates from others (and, on\n   * RLS-protected channels, whether it's authorized to do so).\n   *\n   * @category Realtime\n   */\n  async track(\n    payload: { [key: string]: any },\n    opts: { [key: string]: any } = {}\n  ): Promise<RealtimeChannelSendResponse> {\n    return await this.send(\n      {\n        type: 'presence',\n        event: 'track',\n        payload,\n      },\n      opts\n    )\n  }\n\n  /**\n   * Removes the current presence state for this client.\n   *\n   * @category Realtime\n   */\n  async untrack(opts: { [key: string]: any } = {}): Promise<RealtimeChannelSendResponse> {\n    return await this.send(\n      {\n        type: 'presence',\n        event: 'untrack',\n      },\n      opts\n    )\n  }\n\n  /**\n   * Listen for presence events on this channel \u2014 when peers join, leave, or\n   * sync presence state.\n   */\n  on(\n    type: `${REALTIME_LISTEN_TYPES.PRESENCE}`,\n    filter: { event: `${REALTIME_PRESENCE_LISTEN_EVENTS.SYNC}` },\n    callback: () => void\n  ): RealtimeChannel\n  on<T extends { [key: string]: any }>(\n    type: `${REALTIME_LISTEN_TYPES.PRESENCE}`,\n    filter: { event: `${REALTIME_PRESENCE_LISTEN_EVENTS.JOIN}` },\n    callback: (payload: RealtimePresenceJoinPayload<T>) => void\n  ): RealtimeChannel\n  on<T extends { [key: string]: any }>(\n    type: `${REALTIME_LISTEN_TYPES.PRESENCE}`,\n    filter: { event: `${REALTIME_PRESENCE_LISTEN_EVENTS.LEAVE}` },\n    callback: (payload: RealtimePresenceLeavePayload<T>) => void\n  ): RealtimeChannel\n  on<T extends { [key: string]: any }>(\n    type: `${REALTIME_LISTEN_TYPES.PRESENCE}`,\n    filter: { event: '*' },\n    callback: (payload?: RealtimePresenceJoinPayload<T> | RealtimePresenceLeavePayload<T>) => void\n  ): RealtimeChannel\n  /**\n   * Listen for Postgres database changes (insert / update / delete) streamed\n   * over this channel.\n   */\n  on<T extends { [key: string]: any }>(\n    type: `${REALTIME_LISTEN_TYPES.POSTGRES_CHANGES}`,\n    filter: RealtimePostgresChangesFilter<`${REALTIME_POSTGRES_CHANGES_LISTEN_EVENT.ALL}`>,\n    callback: (payload: RealtimePostgresChangesPayload<T>) => void\n  ): RealtimeChannel\n  on<T extends { [key: string]: any }>(\n    type: `${REALTIME_LISTEN_TYPES.POSTGRES_CHANGES}`,\n    filter: RealtimePostgresChangesFilter<`${REALTIME_POSTGRES_CHANGES_LISTEN_EVENT.INSERT}`>,\n    callback: (payload: RealtimePostgresInsertPayload<T>) => void\n  ): RealtimeChannel\n  on<T extends { [key: string]: any }>(\n    type: `${REALTIME_LISTEN_TYPES.POSTGRES_CHANGES}`,\n    filter: RealtimePostgresChangesFilter<`${REALTIME_POSTGRES_CHANGES_LISTEN_EVENT.UPDATE}`>,\n    callback: (payload: RealtimePostgresUpdatePayload<T>) => void\n  ): RealtimeChannel\n  on<T extends { [key: string]: any }>(\n    type: `${REALTIME_LISTEN_TYPES.POSTGRES_CHANGES}`,\n    filter: RealtimePostgresChangesFilter<`${REALTIME_POSTGRES_CHANGES_LISTEN_EVENT.DELETE}`>,\n    callback: (payload: RealtimePostgresDeletePayload<T>) => void\n  ): RealtimeChannel\n  on<T extends { [key: string]: any }>(\n    type: `${REALTIME_LISTEN_TYPES.POSTGRES_CHANGES}`,\n    filter: RealtimePostgresChangesFilter<`${REALTIME_POSTGRES_CHANGES_LISTEN_EVENT}`>,\n    callback: (payload: RealtimePostgresChangesPayload<T>) => void\n  ): RealtimeChannel\n  /**\n   * Listen for broadcast messages sent on this channel.\n   *\n   * @param type One of \"broadcast\", \"presence\", or \"postgres_changes\".\n   * @param filter Custom object specific to the Realtime feature detailing which payloads to receive.\n   * @param callback Function to be invoked when event handler is triggered.\n   */\n  on(\n    type: `${REALTIME_LISTEN_TYPES.BROADCAST}`,\n    filter: { event: string },\n    callback: (payload: {\n      type: `${REALTIME_LISTEN_TYPES.BROADCAST}`\n      event: string\n      meta?: {\n        replayed?: boolean\n        id: string\n      }\n      [key: string]: any\n    }) => void\n  ): RealtimeChannel\n  on<T extends { [key: string]: any }>(\n    type: `${REALTIME_LISTEN_TYPES.BROADCAST}`,\n    filter: { event: string },\n    callback: (payload: {\n      type: `${REALTIME_LISTEN_TYPES.BROADCAST}`\n      event: string\n      meta?: {\n        replayed?: boolean\n        id: string\n      }\n      payload: T\n    }) => void\n  ): RealtimeChannel\n  on<T extends Record<string, unknown>>(\n    type: `${REALTIME_LISTEN_TYPES.BROADCAST}`,\n    filter: { event: REALTIME_POSTGRES_CHANGES_LISTEN_EVENT.ALL },\n    callback: (payload: {\n      type: `${REALTIME_LISTEN_TYPES.BROADCAST}`\n      event: REALTIME_POSTGRES_CHANGES_LISTEN_EVENT.ALL\n      payload: RealtimeBroadcastPayload<T>\n    }) => void\n  ): RealtimeChannel\n  on<T extends { [key: string]: any }>(\n    type: `${REALTIME_LISTEN_TYPES.BROADCAST}`,\n    filter: { event: REALTIME_POSTGRES_CHANGES_LISTEN_EVENT.INSERT },\n    callback: (payload: {\n      type: `${REALTIME_LISTEN_TYPES.BROADCAST}`\n      event: REALTIME_POSTGRES_CHANGES_LISTEN_EVENT.INSERT\n      payload: RealtimeBroadcastInsertPayload<T>\n    }) => void\n  ): RealtimeChannel\n  on<T extends { [key: string]: any }>(\n    type: `${REALTIME_LISTEN_TYPES.BROADCAST}`,\n    filter: { event: REALTIME_POSTGRES_CHANGES_LISTEN_EVENT.UPDATE },\n    callback: (payload: {\n      type: `${REALTIME_LISTEN_TYPES.BROADCAST}`\n      event: REALTIME_POSTGRES_CHANGES_LISTEN_EVENT.UPDATE\n      payload: RealtimeBroadcastUpdatePayload<T>\n    }) => void\n  ): RealtimeChannel\n  on<T extends { [key: string]: any }>(\n    type: `${REALTIME_LISTEN_TYPES.BROADCAST}`,\n    filter: { event: REALTIME_POSTGRES_CHANGES_LISTEN_EVENT.DELETE },\n    callback: (payload: {\n      type: `${REALTIME_LISTEN_TYPES.BROADCAST}`\n      event: REALTIME_POSTGRES_CHANGES_LISTEN_EVENT.DELETE\n      payload: RealtimeBroadcastDeletePayload<T>\n    }) => void\n  ): RealtimeChannel\n  /**\n   * Listen for `system` events on this channel.\n   *\n   * The payload follows the {@link RealtimeSystemPayload} shape. Opt in to the replication-ready\n   * notification with `config.broadcast.replication_ready: true` when creating the channel, then\n   * watch for `payload.status === 'ok'` to know the Postgres replication connection is ready.\n   *\n   * @example Know when the replication connection is ready\n   * ```js\n   * const channel = supabase.channel('room1', {\n   *   config: { broadcast: { replication_ready: true } },\n   * })\n   *\n   * channel\n   *   .on('postgres_changes', { event: '*', schema: 'public', table: 'messages' }, (payload) => {\n   *     console.log('Change received!', payload)\n   *   })\n   *   .on('system', {}, (payload) => {\n   *     if (payload.extension === 'system' && payload.status === 'ok') {\n   *       console.log('Replication connection is ready:', payload.message)\n   *     }\n   *   })\n   *   .subscribe()\n   * ```\n   */\n  on<T extends { [key: string]: any }>(\n    type: `${REALTIME_LISTEN_TYPES.SYSTEM}`,\n    filter: {},\n    callback: (payload: any) => void\n  ): RealtimeChannel\n  /**\n   * Listen to realtime events on this channel.\n   * @category Realtime\n   *\n   * @remarks\n   * - By default, Broadcast and Presence are enabled for all projects.\n   * - By default, listening to database changes is disabled for new projects due to database performance and security concerns. You can turn it on by managing Realtime's [replication](/docs/guides/api#realtime-api-overview).\n   * - You can receive the \"previous\" data for updates and deletes by setting the table's `REPLICA IDENTITY` to `FULL` (e.g., `ALTER TABLE your_table REPLICA IDENTITY FULL;`).\n   * - Row level security is not applied to delete statements. When RLS is enabled and replica identity is set to full, only the primary key is sent to clients.\n   *\n   * @example Listen to broadcast messages\n   * ```js\n   * const channel = supabase.channel(\"room1\")\n   *\n   * channel.on(\"broadcast\", { event: \"cursor-pos\" }, (payload) => {\n   *   console.log(\"Cursor position received!\", payload);\n   * }).subscribe((status) => {\n   *   if (status === \"SUBSCRIBED\") {\n   *     channel.send({\n   *       type: \"broadcast\",\n   *       event: \"cursor-pos\",\n   *       payload: { x: Math.random(), y: Math.random() },\n   *     });\n   *   }\n   * });\n   * ```\n   *\n   * @example Listen to presence sync\n   * ```js\n   * const channel = supabase.channel('room1')\n   * channel\n   *   .on('presence', { event: 'sync' }, () => {\n   *     console.log('Synced presence state: ', channel.presenceState())\n   *   })\n   *   .subscribe(async (status) => {\n   *     if (status === 'SUBSCRIBED') {\n   *       await channel.track({ online_at: new Date().toISOString() })\n   *     }\n   *   })\n   * ```\n   *\n   * @example Listen to presence join\n   * ```js\n   * const channel = supabase.channel('room1')\n   * channel\n   *   .on('presence', { event: 'join' }, ({ newPresences }) => {\n   *     console.log('Newly joined presences: ', newPresences)\n   *   })\n   *   .subscribe(async (status) => {\n   *     if (status === 'SUBSCRIBED') {\n   *       await channel.track({ online_at: new Date().toISOString() })\n   *     }\n   *   })\n   * ```\n   *\n   * @example Listen to presence leave\n   * ```js\n   * const channel = supabase.channel('room1')\n   * channel\n   *   .on('presence', { event: 'leave' }, ({ leftPresences }) => {\n   *     console.log('Newly left presences: ', leftPresences)\n   *   })\n   *   .subscribe(async (status) => {\n   *     if (status === 'SUBSCRIBED') {\n   *       await channel.track({ online_at: new Date().toISOString() })\n   *       await channel.untrack()\n   *     }\n   *   })\n   * ```\n   *\n   * Registering the same `postgres_changes` filter more than once on a channel is a no-op: the\n   * duplicate is ignored and an error is logged, since the server only ever creates one\n   * subscription per distinct filter.\n   *\n   * @example Listen to all database changes\n   * ```js\n   * supabase\n   *   .channel('room1')\n   *   .on('postgres_changes', { event: '*', schema: '*' }, payload => {\n   *     console.log('Change received!', payload)\n   *   })\n   *   .subscribe()\n   * ```\n   *\n   * @example Listen to a specific table\n   * ```js\n   * supabase\n   *   .channel('room1')\n   *   .on('postgres_changes', { event: '*', schema: 'public', table: 'countries' }, payload => {\n   *     console.log('Change received!', payload)\n   *   })\n   *   .subscribe()\n   * ```\n   *\n   * @example Listen to inserts\n   * ```js\n   * supabase\n   *   .channel('room1')\n   *   .on('postgres_changes', { event: 'INSERT', schema: 'public', table: 'countries' }, payload => {\n   *     console.log('Change received!', payload)\n   *   })\n   *   .subscribe()\n   * ```\n   *\n   * @exampleDescription Listen to updates\n   * By default, Supabase will send only the updated record. If you want to receive the previous values as well you can\n   * enable full replication for the table you are listening to:\n   *\n   * ```sql\n   * alter table \"your_table\" replica identity full;\n   * ```\n   *\n   * @example Listen to updates\n   * ```js\n   * supabase\n   *   .channel('room1')\n   *   .on('postgres_changes', { event: 'UPDATE', schema: 'public', table: 'countries' }, payload => {\n   *     console.log('Change received!', payload)\n   *   })\n   *   .subscribe()\n   * ```\n   *\n   * @exampleDescription Listen to deletes\n   * By default, Supabase does not send deleted records. If you want to receive the deleted record you can\n   * enable full replication for the table you are listening to:\n   *\n   * ```sql\n   * alter table \"your_table\" replica identity full;\n   * ```\n   *\n   * @example Listen to deletes\n   * ```js\n   * supabase\n   *   .channel('room1')\n   *   .on('postgres_changes', { event: 'DELETE', schema: 'public', table: 'countries' }, payload => {\n   *     console.log('Change received!', payload)\n   *   })\n   *   .subscribe()\n   * ```\n   *\n   * @exampleDescription Listen to multiple events\n   * You can chain listeners if you want to listen to multiple events for each table.\n   *\n   * @example Listen to multiple events\n   * ```js\n   * supabase\n   *   .channel('room1')\n   *   .on('postgres_changes', { event: 'INSERT', schema: 'public', table: 'countries' }, handleRecordInserted)\n   *   .on('postgres_changes', { event: 'DELETE', schema: 'public', table: 'countries' }, handleRecordDeleted)\n   *   .subscribe()\n   * ```\n   *\n   * @exampleDescription Listen to row level changes\n   * You can listen to individual rows using the format `{table}:{col}=eq.{val}` - where `{col}` is the column name, and `{val}` is the value which you want to match.\n   *\n   * @example Listen to row level changes\n   * ```js\n   * supabase\n   *   .channel('room1')\n   *   .on('postgres_changes', { event: 'UPDATE', schema: 'public', table: 'countries', filter: 'id=eq.200' }, handleRecordUpdated)\n   *   .subscribe()\n   * ```\n   */\n  on(\n    type: `${REALTIME_LISTEN_TYPES}`,\n    filter: { event: string; [key: string]: any },\n    callback: (payload: any) => void\n  ): RealtimeChannel {\n    const stateCheck = this.channelAdapter.isJoined() || this.channelAdapter.isJoining()\n    const typeCheck =\n      type === REALTIME_LISTEN_TYPES.PRESENCE || type === REALTIME_LISTEN_TYPES.POSTGRES_CHANGES\n\n    if (stateCheck && typeCheck) {\n      this.socket.log(\n        'channel',\n        `cannot add \\`${type}\\` callbacks for ${this.topic} after \\`subscribe()\\`.`\n      )\n      throw new Error(`cannot add \\`${type}\\` callbacks for ${this.topic} after \\`subscribe()\\`.`)\n    }\n    return this._on(type, filter, callback)\n  }\n  /**\n   * Sends a broadcast message explicitly via REST API.\n   *\n   * This method always uses the REST API endpoint regardless of WebSocket connection state.\n   * Useful when you want to guarantee REST delivery or when gradually migrating from implicit REST fallback.\n   *\n   * Payloads that are `ArrayBuffer` or `ArrayBufferView` (e.g. `Uint8Array`) are sent as\n   * `application/octet-stream`; all other payloads are JSON-encoded.\n   *\n   * @param event The name of the broadcast event\n   * @param payload Payload to be sent (required)\n   * @param opts Options including timeout\n   * @returns Promise resolving to object with success status, and error details if failed\n   *\n   * @category Realtime\n   */\n  async httpSend(\n    event: string,\n    payload: any,\n    opts: { timeout?: number } = {}\n  ): Promise<{ success: true } | { success: false; status: number; error: string }> {\n    if (payload === undefined || payload === null) {\n      return Promise.reject(new Error('Payload is required for httpSend()'))\n    }\n\n    const isBinary = payload instanceof ArrayBuffer || ArrayBuffer.isView(payload)\n\n    const headers: Record<string, string> = {\n      apikey: this.socket.apiKey ? this.socket.apiKey : '',\n      'Content-Type': isBinary ? 'application/octet-stream' : 'application/json',\n    }\n\n    if (this.socket.accessTokenValue) {\n      headers['Authorization'] = `Bearer ${this.socket.accessTokenValue}`\n    }\n\n    const url = new URL(this.broadcastEndpointURL)\n    url.pathname += `/${encodeURIComponent(this.subTopic)}/events/${encodeURIComponent(event)}`\n    if (this.private) {\n      url.searchParams.set('private', 'true')\n    }\n\n    const options = {\n      method: 'POST',\n      headers,\n      body: isBinary ? (payload as ArrayBuffer | ArrayBufferView) : JSON.stringify(payload),\n    }\n\n    const response = await this._fetchWithTimeout(\n      url.toString(),\n      options,\n      opts.timeout ?? this.timeout\n    )\n\n    if (response.status === 202) {\n      return { success: true }\n    }\n\n    if (response.status === 404) {\n      return Promise.reject(\n        new Error(\n          'httpSend() requires Realtime server v2.97.0 or newer; the endpoint returned 404. ' +\n            'Update your Supabase CLI to a recent version, or upgrade the Realtime server in your self-hosted setup. ' +\n            'See https://github.com/supabase/supabase-js/blob/master/packages/core/realtime-js/migrations/httpsend-server-version.md'\n        )\n      )\n    }\n\n    let errorMessage = response.statusText\n    try {\n      const errorBody = await response.json()\n      errorMessage = errorBody.error || errorBody.message || errorMessage\n    } catch {}\n\n    return Promise.reject(new Error(errorMessage))\n  }\n\n  /**\n   * Sends a message into the channel.\n   *\n   * @param args Arguments to send to channel\n   * @param args.type The type of event to send\n   * @param args.event The name of the event being sent\n   * @param args.payload Payload to be sent\n   * @param opts Options to be used during the send process\n   *\n   * @category Realtime\n   *\n   * @remarks\n   * - When using REST you don't need to subscribe to the channel\n   * - REST calls are only available from 2.37.0 onwards\n   * - If you create a channel only to send a REST broadcast, remove it from\n   *   the client when the send completes\n   *\n   * @example Send a message via websocket\n   * ```js\n   * const channel = supabase.channel('room1')\n   *\n   * channel.subscribe((status) => {\n   *   if (status === 'SUBSCRIBED') {\n   *     channel.send({\n   *       type: 'broadcast',\n   *       event: 'cursor-pos',\n   *       payload: { x: Math.random(), y: Math.random() },\n   *     })\n   *   }\n   * })\n   * ```\n   *\n   * @exampleResponse Send a message via websocket\n   * ```js\n   * ok | timed out | error\n   * ```\n   *\n   * @example Send a message via REST\n   * ```js\n   * const channel = supabase.channel('room1')\n   *\n   * try {\n   *   await channel.httpSend('cursor-pos', { x: Math.random(), y: Math.random() })\n   * } finally {\n   *   await supabase.removeChannel(channel)\n   * }\n   * ```\n   */\n  async send(\n    args: {\n      type: 'broadcast' | 'presence' | 'postgres_changes'\n      event: string\n      payload?: any\n      [key: string]: any\n    },\n    opts: { [key: string]: any } = {}\n  ): Promise<RealtimeChannelSendResponse> {\n    if (!this.channelAdapter.canPush() && args.type === 'broadcast') {\n      const fallbackWarning =\n        'Realtime send() is automatically falling back to REST API. ' +\n        'This behavior will be deprecated in the future. ' +\n        'Please use httpSend() explicitly for REST delivery.'\n\n      if (this.socket.hasLogger()) {\n        this.socket.log('channel', fallbackWarning)\n      } else {\n        console.warn(fallbackWarning)\n      }\n\n      const { event, payload: endpoint_payload } = args\n      const headers: Record<string, string> = {\n        apikey: this.socket.apiKey ? this.socket.apiKey : '',\n        'Content-Type': 'application/json',\n      }\n\n      if (this.socket.accessTokenValue) {\n        headers['Authorization'] = `Bearer ${this.socket.accessTokenValue}`\n      }\n\n      const options = {\n        method: 'POST',\n        headers,\n        body: JSON.stringify({\n          messages: [\n            {\n              topic: this.subTopic,\n              event,\n              payload: endpoint_payload,\n              private: this.private,\n            },\n          ],\n        }),\n      }\n\n      try {\n        const response = await this._fetchWithTimeout(\n          this.broadcastEndpointURL,\n          options,\n          opts.timeout ?? this.timeout\n        )\n\n        await response.body?.cancel()\n        return response.ok ? 'ok' : 'error'\n      } catch (error) {\n        if (error instanceof Error && error.name === 'AbortError') {\n          return 'timed out'\n        } else {\n          return 'error'\n        }\n      }\n    } else {\n      return new Promise((resolve) => {\n        const push = this.channelAdapter.push(args.type, args, opts.timeout || this.timeout)\n\n        if (args.type === 'broadcast' && !this.params?.config?.broadcast?.ack) {\n          resolve('ok')\n        }\n\n        push.receive('ok', () => resolve('ok'))\n        push.receive('error', () => resolve('error'))\n        push.receive('timeout', () => resolve('timed out'))\n      })\n    }\n  }\n\n  /**\n   * Updates the payload that will be sent the next time the channel joins (reconnects).\n   * Useful for rotating access tokens or updating config without re-creating the channel.\n   *\n   * @category Realtime\n   */\n  updateJoinPayload(payload: Record<string, any>) {\n    this.channelAdapter.updateJoinPayload(payload)\n  }\n\n  /**\n   * Leaves the channel.\n   *\n   * Unsubscribes from server events, and instructs channel to terminate on server.\n   * Triggers onClose() hooks.\n   *\n   * To receive leave acknowledgements, use the a `receive` hook to bind to the server ack, ie:\n   * channel.unsubscribe().receive(\"ok\", () => alert(\"left!\") )\n   *\n   * @category Realtime\n   */\n  async unsubscribe(timeout = this.timeout) {\n    return new Promise<RealtimeChannelSendResponse>((resolve) => {\n      this.channelAdapter\n        .unsubscribe(timeout)\n        .receive('ok', () => resolve('ok'))\n        .receive('timeout', () => resolve('timed out'))\n        .receive('error', () => resolve('error'))\n    })\n  }\n\n  /**\n   * Destroys and stops related timers.\n   *\n   * @category Realtime\n   */\n  teardown() {\n    this.channelAdapter.teardown()\n  }\n\n  /** @internal */\n  async _fetchWithTimeout(url: string, options: { [key: string]: any }, timeout: number) {\n    const controller = new AbortController()\n    const id = setTimeout(() => controller.abort(), timeout)\n\n    const response = await this.socket.fetch(url, {\n      ...options,\n      signal: controller.signal,\n    })\n\n    clearTimeout(id)\n\n    return response\n  }\n\n  /** @internal */\n  _on(type: string, filter: { [key: string]: any }, callback: ChannelBindingCallback) {\n    const typeLower = type.toLocaleLowerCase()\n\n    // Serialize a postgres_changes filter builder into its string form so the\n    // rest of the pipeline (join payload, server binding match) sees a string.\n    // Duck-type `build()` in addition to `instanceof` so a builder constructed\n    // against a duplicate copy of the package (separate module realm) still works.\n    const filterValue = filter?.filter\n    if (\n      filterValue instanceof RealtimePostgresFilterBuilder ||\n      (typeof filterValue === 'object' &&\n        filterValue !== null &&\n        typeof (filterValue as { build?: unknown }).build === 'function')\n    ) {\n      filter = { ...filter, filter: (filterValue as RealtimePostgresFilterBuilder).build() }\n    }\n\n    // The server collapses identical postgres_changes filters, so keeping a duplicate here would\n    // desync the client and server binding lists and make `subscribe()` fail with a mismatch.\n    if (typeLower === REALTIME_LISTEN_TYPES.POSTGRES_CHANGES) {\n      const duplicate = this.bindings[typeLower]?.find((bind) =>\n        RealtimeChannel.isSamePostgresFilter(bind.filter, filter)\n      )\n\n      if (duplicate) {\n        this.socket.log(\n          'error',\n          `duplicate \\`postgres_changes\\` binding for ${this.topic} ignored`,\n          filter\n        )\n        return this\n      }\n    }\n\n    const ref = this.channelAdapter.on(type, callback)\n\n    const binding: Binding = {\n      type: typeLower,\n      filter: filter,\n      callback: callback,\n      ref: ref,\n    }\n\n    if (this.bindings[typeLower]) {\n      this.bindings[typeLower].push(binding)\n    } else {\n      this.bindings[typeLower] = [binding]\n    }\n\n    this._updateFilterMessage()\n\n    return this\n  }\n\n  /**\n   * Registers a callback that will be executed when the channel closes.\n   *\n   * @internal\n   */\n  private _onClose(callback: ChannelBindingCallback) {\n    this.channelAdapter.onClose(callback)\n  }\n\n  /**\n   * Registers a callback that will be executed when the channel encounteres an error.\n   *\n   * @internal\n   */\n  private _onError(callback: ChannelOnErrorCallback) {\n    this.channelAdapter.onError(callback)\n  }\n\n  /** @internal */\n  private _updateFilterMessage() {\n    this.channelAdapter.updateFilterBindings((binding, payload: any, ref) => {\n      const typeLower = binding.event.toLocaleLowerCase()\n\n      if (this._notThisChannelEvent(typeLower, ref)) {\n        return false\n      }\n\n      const bind = this.bindings[typeLower]?.find((bind) => bind.ref === binding.ref)\n\n      if (!bind) {\n        return true\n      }\n\n      if (['broadcast', 'presence', 'postgres_changes'].includes(typeLower)) {\n        if ('id' in bind) {\n          const bindId = bind.id\n          const bindEvent = bind.filter?.event\n          return (\n            bindId &&\n            payload.ids?.includes(bindId) &&\n            (bindEvent === '*' ||\n              bindEvent?.toLocaleLowerCase() === payload.data?.type.toLocaleLowerCase())\n          )\n        } else {\n          const bindEvent = bind?.filter?.event?.toLocaleLowerCase()\n          return bindEvent === '*' || bindEvent === payload?.event?.toLocaleLowerCase()\n        }\n      } else {\n        return bind.type.toLocaleLowerCase() === typeLower\n      }\n    })\n  }\n\n  /** @internal */\n  private _notThisChannelEvent(event: string, ref?: string | null) {\n    const { close, error, leave, join } = CHANNEL_EVENTS\n    const events: string[] = [close, error, leave, join]\n    return ref && events.includes(event) && ref !== this.joinPush.ref\n  }\n\n  /** @internal */\n  private _updateFilterTransform() {\n    this.channelAdapter.updatePayloadTransform((event, payload: any, ref) => {\n      if (typeof payload === 'object' && 'ids' in payload) {\n        const postgresChanges = payload.data\n        const { schema, table, commit_timestamp, type, errors } = postgresChanges\n        const enrichedPayload = {\n          schema: schema,\n          table: table,\n          commit_timestamp: commit_timestamp,\n          eventType: type,\n          new: {},\n          old: {},\n          errors: errors,\n        }\n        return {\n          ...enrichedPayload,\n          ...this._getPayloadRecords(postgresChanges),\n        }\n      }\n\n      return payload\n    })\n  }\n\n  copyBindings(other: RealtimeChannel) {\n    if (this.joinedOnce) {\n      throw new Error('cannot copy bindings into joined channel')\n    }\n    for (const kind in other.bindings) {\n      for (const binding of other.bindings[kind]) {\n        this._on(binding.type, binding.filter, binding.callback)\n      }\n    }\n  }\n\n  /**\n   * Compares two optional filter values for equality.\n   * Treats undefined, null, and empty string as equivalent empty values.\n   * @internal\n   */\n  private static isFilterValueEqual(\n    serverValue: string | undefined | null,\n    clientValue: string | undefined\n  ): boolean {\n    const normalizedServer = serverValue ?? undefined\n    const normalizedClient = clientValue ?? undefined\n    return normalizedServer === normalizedClient\n  }\n\n  /**\n   * Two `postgres_changes` filters are the same when the server would collapse them into a single\n   * subscription.\n   * @internal\n   */\n  private static isSamePostgresFilter(\n    a: PostgresChangesFilterShape,\n    b: PostgresChangesFilterShape\n  ): boolean {\n    const selectA = a?.select?.join() ?? undefined\n    const selectB = b?.select?.join() ?? undefined\n\n    return (\n      a?.event === b?.event &&\n      RealtimeChannel.isFilterValueEqual(a?.schema, b?.schema) &&\n      RealtimeChannel.isFilterValueEqual(a?.table, b?.table) &&\n      RealtimeChannel.isFilterValueEqual(a?.filter, b?.filter) &&\n      selectA === selectB\n    )\n  }\n\n  /** @internal */\n  private _getPayloadRecords(payload: any) {\n    const records = {\n      new: {},\n      old: {},\n    }\n\n    if (payload.type === 'INSERT' || payload.type === 'UPDATE') {\n      records.new = Transformers.convertChangeData(payload.columns, payload.record)\n    }\n\n    if (payload.type === 'UPDATE' || payload.type === 'DELETE') {\n      records.old = Transformers.convertChangeData(payload.columns, payload.old_record)\n    }\n\n    return records\n  }\n}\n", "import { Socket } from '@supabase/phoenix'\nimport type {\n  Message,\n  SocketOnClose,\n  SocketOnMessage,\n  SocketOnOpen,\n  SocketOnError,\n  SocketOptions,\n  SocketStateChangeCallbacks,\n  Vsn,\n  Encode,\n  Decode,\n  HeartbeatCallback,\n  Timer,\n} from './types'\nimport { CONNECTION_STATE, ConnectionState } from '../lib/constants'\nimport type { HeartbeatTimer, WebSocketLikeConstructor } from '../RealtimeClient'\n\nexport default class SocketAdapter {\n  private socket: Socket\n\n  constructor(endPoint: string, options: SocketOptions) {\n    this.socket = new Socket(endPoint, options)\n  }\n\n  get timeout(): number {\n    return this.socket.timeout\n  }\n\n  get endPoint(): string {\n    return this.socket.endPoint\n  }\n\n  get transport(): WebSocketLikeConstructor {\n    return this.socket.transport as WebSocketLikeConstructor\n  }\n\n  get heartbeatIntervalMs(): number {\n    return this.socket.heartbeatIntervalMs\n  }\n\n  get heartbeatCallback(): HeartbeatCallback {\n    return this.socket.heartbeatCallback\n  }\n\n  set heartbeatCallback(callback: HeartbeatCallback) {\n    this.socket.heartbeatCallback = callback\n  }\n\n  get heartbeatTimer(): HeartbeatTimer {\n    return this.socket.heartbeatTimer\n  }\n\n  get pendingHeartbeatRef(): string | null {\n    return this.socket.pendingHeartbeatRef\n  }\n\n  get reconnectTimer(): Timer {\n    return this.socket.reconnectTimer\n  }\n\n  get vsn(): Vsn {\n    return this.socket.vsn\n  }\n\n  get encode(): Encode<void> {\n    return this.socket.encode\n  }\n\n  get decode(): Decode<void> {\n    return this.socket.decode\n  }\n\n  get reconnectAfterMs(): (tries: number) => number {\n    return this.socket.reconnectAfterMs\n  }\n\n  get sendBuffer(): (() => void)[] {\n    return this.socket.sendBuffer\n  }\n\n  get stateChangeCallbacks(): SocketStateChangeCallbacks {\n    return this.socket.stateChangeCallbacks\n  }\n\n  connect() {\n    this.socket.connect()\n  }\n\n  disconnect(\n    callback: () => void,\n    code?: number,\n    reason?: string,\n    timeout: number = 10000\n  ): Promise<'ok' | 'timeout'> {\n    return new Promise((resolve) => {\n      setTimeout(() => resolve('timeout'), timeout)\n      this.socket.disconnect(\n        () => {\n          callback()\n          resolve('ok')\n        },\n        code,\n        reason\n      )\n    })\n  }\n\n  push(data: Message<Record<string, unknown>>) {\n    this.socket.push(data)\n  }\n\n  log(kind: string, msg: string, data?: any) {\n    this.socket.log(kind, msg, data)\n  }\n\n  hasLogger(): boolean {\n    return this.socket.hasLogger()\n  }\n\n  makeRef(): string {\n    return this.socket.makeRef()\n  }\n\n  onOpen(callback: SocketOnOpen) {\n    this.socket.onOpen(callback)\n  }\n\n  onClose(callback: SocketOnClose) {\n    this.socket.onClose(callback)\n  }\n\n  onError(callback: SocketOnError) {\n    this.socket.onError(callback)\n  }\n\n  onMessage(callback: SocketOnMessage) {\n    this.socket.onMessage(callback)\n  }\n\n  isConnected() {\n    return this.socket.isConnected()\n  }\n\n  isConnecting() {\n    return this.socket.connectionState() == CONNECTION_STATE.connecting\n  }\n\n  isDisconnecting() {\n    return this.socket.connectionState() == CONNECTION_STATE.closing\n  }\n\n  connectionState(): ConnectionState {\n    // @ts-ignore - requires better typing and exposing type in phoenix\n    return this.socket.connectionState()\n  }\n\n  endPointURL(): string {\n    return this.socket.endPointURL()\n  }\n\n  sendHeartbeat() {\n    this.socket.sendHeartbeat()\n  }\n\n  /**\n   * @internal\n   */\n  getSocket() {\n    return this.socket\n  }\n}\n", "import WebSocketFactory, { WebSocketLike } from './lib/websocket-factory'\n\nimport {\n  CHANNEL_EVENTS,\n  CONNECTION_STATE,\n  DEFAULT_VERSION,\n  DEFAULT_TIMEOUT,\n  DEFAULT_VSN,\n  VSN_1_0_0,\n  VSN_2_0_0,\n} from './lib/constants'\n\nimport Serializer from './lib/serializer'\nimport { httpEndpointURL } from './lib/transformers'\nimport RealtimeChannel from './RealtimeChannel'\nimport type { RealtimeChannelOptions } from './RealtimeChannel'\nimport SocketAdapter from './phoenix/socketAdapter'\nimport type {\n  Message,\n  SocketOptions,\n  HeartbeatCallback,\n  Encode,\n  Decode,\n  Timer,\n  Vsn,\n} from './phoenix/types'\n\ntype Fetch = typeof fetch\n\nexport type LogLevel = 'info' | 'warn' | 'error' | (string & {})\n\nexport type RealtimeMessage = {\n  topic: string\n  event: string\n  payload: any\n  ref: string\n  join_ref?: string\n}\n\nexport type RealtimeRemoveChannelResponse = 'ok' | 'timed out' | 'error' | (string & {})\nexport type HeartbeatStatus = 'sent' | 'ok' | 'error' | 'timeout' | 'disconnected' | (string & {})\nexport type HeartbeatTimer = ReturnType<typeof setTimeout> | undefined\n\n// Connection-related constants\nconst CONNECTION_TIMEOUTS = {\n  HEARTBEAT_INTERVAL: 25000,\n  RECONNECT_DELAY: 10,\n  HEARTBEAT_TIMEOUT_FALLBACK: 100,\n} as const\n\nconst RECONNECT_INTERVALS = [1000, 2000, 5000, 10000] as const\nconst DEFAULT_RECONNECT_FALLBACK = 10000\n\n/**\n * Minimal WebSocket constructor interface that RealtimeClient can work with.\n * Supply a compatible implementation (native WebSocket, `ws`, etc) when running outside the browser.\n */\nexport interface WebSocketLikeConstructor {\n  new (address: string | URL, subprotocols?: string | string[] | undefined): WebSocketLike\n  // Allow additional properties that may exist on WebSocket constructors\n  [key: string]: any\n}\n\nexport type RealtimeClientOptions = {\n  transport?: WebSocketLikeConstructor\n  timeout?: number\n  heartbeatIntervalMs?: number\n  heartbeatCallback?: (status: HeartbeatStatus, latency?: number) => void\n  vsn?: string\n  logger?: (kind: string, msg: string, data?: any) => void\n  encode?: Encode<void>\n  decode?: Decode<void>\n  reconnectAfterMs?: (tries: number) => number\n  headers?: { [key: string]: string }\n  params?: { [key: string]: any }\n  //Deprecated: Use it in favour of correct casing `logLevel`\n  log_level?: LogLevel\n  logLevel?: LogLevel\n  fetch?: Fetch\n  worker?: boolean\n  workerUrl?: string\n  /**\n   * Callback returning a fresh token for channel subscription authorization and Realtime RLS.\n   *\n   * Called on connect and on every heartbeat (`heartbeatIntervalMs`, default 25000ms).\n   * The token must stay valid past the next call, or the server closes the channel at\n   * expiry with no automatic resubscribe. So, plan for some call time and overhead,\n   * i.e. if hearbeats happen every 25 seconds and your token is still valid for 27\n   * seconds it's probably safer to refresh right now rather than risk a race condition.\n   */\n  accessToken?: () => Promise<string | null>\n  disconnectOnEmptyChannelsAfterMs?: number\n  /**\n   * Storage compatible object used by the underlying socket for longpoll fallback history.\n   * Provide a custom implementation in environments where reading `globalThis.sessionStorage`\n   * throws (sandboxed iframes, in-app webviews, \"block third-party storage\" privacy modes).\n   * Defaults to `globalThis.sessionStorage` when accessible, otherwise an in-memory store.\n   */\n  sessionStorage?: Storage\n}\n\nfunction createMemorySessionStorage(): Storage {\n  const store = new Map<string, string>()\n  return {\n    get length() {\n      return store.size\n    },\n    clear() {\n      store.clear()\n    },\n    getItem(key: string) {\n      return store.has(key) ? (store.get(key) as string) : null\n    },\n    key(index: number) {\n      return Array.from(store.keys())[index] ?? null\n    },\n    removeItem(key: string) {\n      store.delete(key)\n    },\n    setItem(key: string, value: string) {\n      store.set(key, String(value))\n    },\n  }\n}\n\nfunction resolveSessionStorage(): Storage {\n  try {\n    if (typeof globalThis !== 'undefined' && globalThis.sessionStorage) {\n      return globalThis.sessionStorage\n    }\n  } catch {\n    // Property access on `sessionStorage` itself throws in restricted-storage browsers.\n  }\n  return createMemorySessionStorage()\n}\n\nconst WORKER_SCRIPT = `\n  addEventListener(\"message\", (e) => {\n    if (e.data.event === \"start\") {\n      setInterval(() => postMessage({ event: \"keepAlive\" }), e.data.interval);\n    }\n  });`\n\nexport default class RealtimeClient {\n  /** @internal */\n  socketAdapter: SocketAdapter\n  channels: RealtimeChannel[] = new Array()\n\n  accessTokenValue: string | null = null\n  accessToken: (() => Promise<string | null>) | null = null\n  apiKey: string | null = null\n\n  httpEndpoint: string = ''\n  /** @deprecated headers cannot be set on websocket connections */\n  headers?: { [key: string]: string } = {}\n  params?: { [key: string]: string } = {}\n\n  ref: number = 0\n\n  logLevel?: LogLevel\n\n  fetch: Fetch\n  worker?: boolean\n  workerUrl?: string\n  workerRef?: Worker\n\n  serializer: Serializer = new Serializer()\n\n  get endPoint() {\n    return this.socketAdapter.endPoint\n  }\n\n  get timeout() {\n    return this.socketAdapter.timeout\n  }\n\n  get transport() {\n    return this.socketAdapter.transport\n  }\n\n  get heartbeatCallback() {\n    return this.socketAdapter.heartbeatCallback\n  }\n\n  get heartbeatIntervalMs() {\n    return this.socketAdapter.heartbeatIntervalMs\n  }\n\n  get heartbeatTimer() {\n    if (this.worker) {\n      return this._workerHeartbeatTimer\n    }\n    return this.socketAdapter.heartbeatTimer\n  }\n\n  get pendingHeartbeatRef() {\n    if (this.worker) {\n      return this._pendingWorkerHeartbeatRef\n    }\n    return this.socketAdapter.pendingHeartbeatRef\n  }\n\n  get reconnectTimer(): Timer {\n    return this.socketAdapter.reconnectTimer\n  }\n\n  get vsn(): Vsn {\n    return this.socketAdapter.vsn\n  }\n\n  get encode() {\n    return this.socketAdapter.encode\n  }\n\n  get decode() {\n    return this.socketAdapter.decode\n  }\n\n  get reconnectAfterMs() {\n    return this.socketAdapter.reconnectAfterMs\n  }\n\n  get sendBuffer() {\n    return this.socketAdapter.sendBuffer\n  }\n\n  get stateChangeCallbacks(): {\n    open: [string, Function][]\n    close: [string, Function][]\n    error: [string, Function][]\n    message: [string, Function][]\n  } {\n    return this.socketAdapter.stateChangeCallbacks\n  }\n\n  private _manuallySetToken: boolean = false\n  private _authPromise: Promise<void> | null = null\n  private _authGeneration: number = 0\n  private _workerHeartbeatTimer: HeartbeatTimer = undefined\n  private _pendingWorkerHeartbeatRef: string | null = null\n  private _pendingDisconnectTimer: ReturnType<typeof setTimeout> | null = null\n  private _disconnectOnEmptyChannelsAfterMs: number = 0\n\n  /**\n   * Initializes the Socket.\n   *\n   * @param endPoint The string WebSocket endpoint, ie, \"ws://example.com/socket\", \"wss://example.com\", \"/socket\" (inherited host & protocol)\n   * @param options.transport The Websocket Transport, for example WebSocket. This can be a custom implementation\n   * @param options.timeout The default timeout in milliseconds to trigger push timeouts.\n   * @param options.params The optional params to pass when connecting.\n   * @param options.headers Deprecated: headers cannot be set on websocket connections and this option will be removed in the future.\n   * @param options.heartbeatIntervalMs The millisec interval to send a heartbeat message.\n   * @param options.heartbeatCallback The optional function to handle heartbeat status and latency.\n   * @param options.logger The optional function for specialized logging, ie: logger: (kind, msg, data) => { console.log(`${kind}: ${msg}`, data) }\n   * @param options.logLevel Sets the log level for Realtime\n   * @param options.encode The function to encode outgoing messages. Defaults to JSON: (payload, callback) => callback(JSON.stringify(payload))\n   * @param options.decode The function to decode incoming messages. Defaults to Serializer's decode.\n   * @param options.reconnectAfterMs he optional function that returns the millsec reconnect interval. Defaults to stepped backoff off.\n   * @param options.worker Use Web Worker to set a side flow. Defaults to false.\n   * @param options.workerUrl The URL of the worker script. Defaults to https://realtime.supabase.com/worker.js that includes a heartbeat event call to keep the connection alive.\n   * @param options.vsn The protocol version to use when connecting. Supported versions are \"1.0.0\" and \"2.0.0\". Defaults to \"2.0.0\".\n   *\n   * @category Realtime\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 channel = supabase.channel('room1')\n   * channel\n   *   .on('broadcast', { event: 'cursor-pos' }, (payload) => console.log(payload))\n   *   .subscribe()\n   * ```\n   *\n   * @example Standalone import for bundle-sensitive environments\n   * ```ts\n   * import RealtimeClient from '@supabase/realtime-js'\n   *\n   * const client = new RealtimeClient('https://xyzcompany.supabase.co/realtime/v1', {\n   *   params: { apikey: 'your-publishable-key' },\n   * })\n   * client.connect()\n   * ```\n   */\n  constructor(endPoint: string, options?: RealtimeClientOptions) {\n    // Validate required parameters\n    if (!options?.params?.apikey) {\n      throw new Error('API key is required to connect to Realtime')\n    }\n    this.apiKey = options.params.apikey\n\n    const socketAdapterOptions = this._initializeOptions(options)\n\n    this.socketAdapter = new SocketAdapter(endPoint, socketAdapterOptions)\n    this.httpEndpoint = httpEndpointURL(endPoint)\n\n    this.fetch = this._resolveFetch(options?.fetch)\n  }\n\n  /**\n   * Connects the socket, unless already connected.\n   *\n   * @category Realtime\n   */\n  connect(): void {\n    // Skip if already connecting, disconnecting, or connected\n    if (this.isConnecting() || this.isDisconnecting() || this.isConnected()) {\n      return\n    }\n\n    // Trigger auth if needed and not already in progress\n    // This ensures auth is called for standalone RealtimeClient usage\n    // while avoiding race conditions with SupabaseClient's immediate setAuth call\n    if (this.accessToken && !this._authPromise) {\n      this._setAuthSafely('connect')\n    }\n\n    this._setupConnectionHandlers()\n\n    try {\n      this.socketAdapter.connect()\n    } catch (error) {\n      const errorMessage = (error as Error).message\n      throw new Error(`WebSocket not available: ${errorMessage}`)\n    }\n\n    this._handleNodeJsRaceCondition()\n  }\n\n  /**\n   * Returns the URL of the websocket.\n   * @returns string The URL of the websocket.\n   *\n   * @category Realtime\n   */\n  endpointURL(): string {\n    return this.socketAdapter.endPointURL()\n  }\n\n  /**\n   * Disconnects the socket.\n   *\n   * @param code A numeric status code to send on disconnect.\n   * @param reason A custom reason for the disconnect.\n   *\n   * @category Realtime\n   */\n  async disconnect(code?: number, reason?: string) {\n    this._cancelPendingDisconnect()\n    if (this.isDisconnecting()) {\n      return 'ok'\n    }\n    return await this.socketAdapter.disconnect(\n      () => {\n        clearInterval(this._workerHeartbeatTimer)\n        this._terminateWorker()\n      },\n      code,\n      reason\n    )\n  }\n\n  /**\n   * Returns all created channels\n   *\n   * @category Realtime\n   */\n  getChannels(): RealtimeChannel[] {\n    return this.channels\n  }\n\n  /**\n   * Unsubscribes, removes and tears down a single channel\n   * @param channel A RealtimeChannel instance\n   *\n   * @category Realtime\n   */\n  async removeChannel(channel: RealtimeChannel): Promise<RealtimeRemoveChannelResponse> {\n    const status = await channel.unsubscribe()\n\n    if (status === 'ok') {\n      channel.teardown()\n    }\n\n    return status\n  }\n\n  /**\n   * Unsubscribes, removes and tears down all channels\n   *\n   * @category Realtime\n   */\n  async removeAllChannels(): Promise<RealtimeRemoveChannelResponse[]> {\n    const promises = this.channels.map(async (channel) => {\n      const result = await channel.unsubscribe()\n      channel.teardown()\n      return result\n    })\n\n    const result = await Promise.all(promises)\n    await this.disconnect()\n    return result\n  }\n\n  /**\n   * Logs the message.\n   *\n   * For customized logging, `this.logger` can be overridden in Client constructor.\n   *\n   * @category Realtime\n   */\n  log(kind: string, msg: string, data?: any) {\n    this.socketAdapter.log(kind, msg, data)\n  }\n\n  /**\n   * Returns true if a custom `logger` has been configured on this client.\n   *\n   * @category Realtime\n   */\n  hasLogger(): boolean {\n    return this.socketAdapter.hasLogger()\n  }\n\n  /**\n   * Returns the current state of the socket.\n   *\n   * @category Realtime\n   */\n  connectionState() {\n    return this.socketAdapter.connectionState() || CONNECTION_STATE.closed\n  }\n\n  /**\n   * Returns `true` is the connection is open.\n   *\n   * @category Realtime\n   */\n  isConnected(): boolean {\n    return this.socketAdapter.isConnected()\n  }\n\n  /**\n   * Returns `true` if the connection is currently connecting.\n   *\n   * @category Realtime\n   */\n  isConnecting(): boolean {\n    return this.socketAdapter.isConnecting()\n  }\n\n  /**\n   * Returns `true` if the connection is currently disconnecting.\n   *\n   * @category Realtime\n   */\n  isDisconnecting(): boolean {\n    return this.socketAdapter.isDisconnecting()\n  }\n\n  /**\n   * Creates (or reuses) a {@link RealtimeChannel} for the provided topic.\n   *\n   * Topics are automatically prefixed with `realtime:` to match the Realtime service.\n   * If a channel with the same topic already exists it will be returned instead of creating\n   * a duplicate connection.\n   *\n   * @category Realtime\n   */\n  channel(topic: string, params: RealtimeChannelOptions = { config: {} }): RealtimeChannel {\n    const realtimeTopic = `realtime:${topic}`\n    const exists = this.getChannels().find((c: RealtimeChannel) => c.topic === realtimeTopic)\n\n    if (!exists) {\n      const chan = new RealtimeChannel(`realtime:${topic}`, params, this)\n      this._cancelPendingDisconnect()\n      this.channels.push(chan)\n\n      return chan\n    } else {\n      return exists\n    }\n  }\n\n  /**\n   * Push out a message if the socket is connected.\n   *\n   * If the socket is not connected, the message gets enqueued within a local buffer, and sent out when a connection is next established.\n   *\n   * @category Realtime\n   */\n  push(data: RealtimeMessage): void {\n    this.socketAdapter.push(data)\n  }\n\n  /**\n   * Sets the JWT access token used for channel subscription authorization and Realtime RLS.\n   *\n   * If param is null it will use the `accessToken` callback function or the token set on the client.\n   *\n   * On callback used, it will set the value of the token internal to the client.\n   *\n   * When a token is explicitly provided AND no `accessToken` callback is configured,\n   * it will be preserved across channel operations (including removeChannel and\n   * resubscribe) and the client stays in manual-token mode.\n   *\n   * When an `accessToken` callback IS configured, the callback is the source of truth:\n   * the client remains in callback mode and continues to refresh from it on heartbeat,\n   * even after a bootstrap/override `setAuth(token)` call.\n   *\n   * The callback is called on connect and on every heartbeat (`heartbeatIntervalMs`,\n   * default 25000ms). Its token must stay valid past the next call, or the server closes\n   * the channel at expiry with no automatic resubscribe.\n   *\n   * @param token A JWT string to override the token set on the client.\n   *\n   * @example Setting the authorization header\n   * // Use a manual token (preserved across resubscribes when no accessToken callback is set)\n   * client.realtime.setAuth('my-custom-jwt')\n   *\n   * // Switch back to using the accessToken callback\n   * client.realtime.setAuth()\n   *\n   * @category Realtime\n   */\n  async setAuth(token: string | null = null): Promise<void> {\n    const authGeneration = ++this._authGeneration\n    const authPromise = this._performAuth(token, authGeneration)\n    if (authGeneration === this._authGeneration) {\n      this._authPromise = authPromise\n    }\n    try {\n      await authPromise\n    } finally {\n      if (this._authPromise === authPromise) {\n        this._authPromise = null\n      }\n    }\n  }\n\n  /**\n   * Returns true if the current access token was explicitly set via setAuth(token),\n   * false if it was obtained via the accessToken callback.\n   * @internal\n   */\n  _isManualToken(): boolean {\n    return this._manuallySetToken\n  }\n\n  /**\n   * Sends a heartbeat message if the socket is connected.\n   *\n   * @category Realtime\n   */\n  async sendHeartbeat() {\n    this.socketAdapter.sendHeartbeat()\n  }\n\n  /**\n   * Sets a callback that receives lifecycle events for internal heartbeat messages.\n   * Useful for instrumenting connection health (e.g. sent/ok/timeout).\n   *\n   * @category Realtime\n   */\n  onHeartbeat(callback: HeartbeatCallback) {\n    this.socketAdapter.heartbeatCallback = this._wrapHeartbeatCallback(callback)\n  }\n\n  /**\n   * Use either custom fetch, if provided, or default fetch to make HTTP requests\n   *\n   * @internal\n   */\n  _resolveFetch = (customFetch?: Fetch): Fetch => {\n    if (customFetch) {\n      return (...args) => customFetch(...args)\n    }\n    return (...args) => fetch(...args)\n  }\n\n  /**\n   * Return the next message ref, accounting for overflows\n   *\n   * @internal\n   */\n  _makeRef(): string {\n    return this.socketAdapter.makeRef()\n  }\n\n  /**\n   * Removes a channel from RealtimeClient\n   *\n   * @param channel An open subscription.\n   *\n   * @internal\n   */\n  _remove(channel: RealtimeChannel) {\n    this.channels = this.channels.filter((c) => c.topic !== channel.topic)\n    if (this.channels.length === 0) {\n      this.log('transport', 'no channels remaining, scheduling disconnect')\n      this._schedulePendingDisconnect()\n    }\n  }\n\n  /** @internal */\n  private _schedulePendingDisconnect() {\n    this._cancelPendingDisconnect()\n    if (this._disconnectOnEmptyChannelsAfterMs === 0) {\n      this.log('transport', 'disconnecting immediately - no channels')\n      this.disconnect()\n      return\n    }\n    this._pendingDisconnectTimer = setTimeout(() => {\n      this._pendingDisconnectTimer = null\n      if (this.channels.length === 0) {\n        this.log('transport', 'deferred disconnect fired - no channels, disconnecting')\n        this.disconnect()\n      }\n    }, this._disconnectOnEmptyChannelsAfterMs)\n    this.log(\n      'transport',\n      `deferred disconnect scheduled in ${this._disconnectOnEmptyChannelsAfterMs}ms`\n    )\n  }\n\n  /** @internal */\n  private _cancelPendingDisconnect() {\n    if (this._pendingDisconnectTimer !== null) {\n      this.log('transport', 'pending disconnect cancelled - channel activity detected')\n      clearTimeout(this._pendingDisconnectTimer)\n      this._pendingDisconnectTimer = null\n    }\n  }\n\n  /**\n   * Perform the actual auth operation\n   * @internal\n   */\n  private async _performAuth(token: string | null, authGeneration: number): Promise<void> {\n    let tokenToSend: string | null\n    let isManualToken = false\n\n    if (token) {\n      tokenToSend = token\n      // Track if this is a manually-provided token\n      isManualToken = true\n    } else if (this.accessToken) {\n      // Call the accessToken callback to get fresh token\n      try {\n        tokenToSend = await this.accessToken()\n      } catch (e) {\n        this.log('error', 'Error fetching access token from callback', e)\n        // Fall back to cached value if callback fails\n        tokenToSend = this.accessTokenValue\n      }\n    } else {\n      tokenToSend = this.accessTokenValue\n    }\n\n    if (authGeneration !== this._authGeneration) {\n      return\n    }\n\n    // Track whether this token was manually set or fetched via callback.\n    // The callback is the source of truth for token refresh\n    if (this.accessToken) {\n      this._manuallySetToken = false\n    } else if (isManualToken) {\n      this._manuallySetToken = true\n    }\n\n    if (this.accessTokenValue != tokenToSend) {\n      this.accessTokenValue = tokenToSend\n      this.channels.forEach((channel) => {\n        const payload = {\n          access_token: tokenToSend,\n          version: DEFAULT_VERSION,\n        }\n\n        channel.updateJoinPayload(payload)\n\n        if (channel.joinedOnce && channel.channelAdapter.isJoined()) {\n          channel.channelAdapter.push(CHANNEL_EVENTS.access_token, {\n            access_token: tokenToSend,\n          })\n        }\n      })\n    }\n  }\n\n  /**\n   * Wait for any in-flight auth operations to complete\n   * @internal\n   */\n  private async _waitForAuthIfNeeded(): Promise<void> {\n    if (this._authPromise) {\n      await this._authPromise\n    }\n  }\n\n  /**\n   * Safely call setAuth with standardized error handling\n   * @internal\n   */\n  private _setAuthSafely(context = 'general'): void {\n    // Only refresh auth if using callback-based tokens\n    if (!this._isManualToken()) {\n      this.setAuth().catch((e) => {\n        this.log('error', `Error setting auth in ${context}`, e)\n      })\n    }\n  }\n\n  /** @internal */\n  private _setupConnectionHandlers(): void {\n    this.socketAdapter.onOpen(() => {\n      const authPromise =\n        this._authPromise ||\n        (this.accessToken && !this.accessTokenValue ? this.setAuth() : Promise.resolve())\n\n      authPromise.catch((e) => {\n        this.log('error', 'error waiting for auth on connect', e)\n      })\n\n      if (this.worker && !this.workerRef) {\n        this._startWorkerHeartbeat()\n      }\n    })\n    this.socketAdapter.onClose(() => {\n      if (this.worker && this.workerRef) {\n        this._terminateWorker()\n      }\n    })\n    this.socketAdapter.onMessage((message: Message<any>) => {\n      if (message.ref && message.ref === this._pendingWorkerHeartbeatRef) {\n        this._pendingWorkerHeartbeatRef = null\n      }\n    })\n  }\n\n  /** @internal */\n  private _handleNodeJsRaceCondition() {\n    if (this.socketAdapter.isConnected()) {\n      // hack: ensure onConnOpen is called\n      this.socketAdapter.getSocket().onConnOpen()\n    }\n  }\n\n  /** @internal */\n  private _wrapHeartbeatCallback(heartbeatCallback?: HeartbeatCallback): HeartbeatCallback {\n    return (status, latency) => {\n      if (status === 'disconnected') return\n      if (status == 'sent') this._setAuthSafely()\n      if (heartbeatCallback) heartbeatCallback(status, latency)\n    }\n  }\n\n  /** @internal */\n  private _startWorkerHeartbeat() {\n    if (this.workerUrl) {\n      this.log('worker', `starting worker for from ${this.workerUrl}`)\n    } else {\n      this.log('worker', `starting default worker`)\n    }\n    const objectUrl = this._workerObjectUrl(this.workerUrl!)\n    this.workerRef = new Worker(objectUrl)\n    this.workerRef.onerror = (error) => {\n      this.log('worker', 'worker error', (error as ErrorEvent).message)\n      this._terminateWorker()\n      this.disconnect()\n    }\n    this.workerRef.onmessage = (event) => {\n      if (event.data.event === 'keepAlive') {\n        this.sendHeartbeat()\n      }\n    }\n    this.workerRef.postMessage({\n      event: 'start',\n      interval: this.heartbeatIntervalMs,\n    })\n  }\n\n  /**\n   * Terminate the Web Worker and clear the reference\n   * @internal\n   */\n  private _terminateWorker(): void {\n    if (this.workerRef) {\n      this.log('worker', 'terminating worker')\n      this.workerRef.terminate()\n      this.workerRef = undefined\n    }\n  }\n\n  /** @internal */\n  private _workerObjectUrl(url: string | undefined): string {\n    let result_url: string\n    if (url) {\n      result_url = url\n    } else {\n      const blob = new Blob([WORKER_SCRIPT], { type: 'application/javascript' })\n      result_url = URL.createObjectURL(blob)\n    }\n    return result_url\n  }\n\n  /**\n   * Initialize socket options with defaults\n   * @internal\n   */\n  private _initializeOptions(options?: RealtimeClientOptions): SocketOptions {\n    this.worker = options?.worker ?? false\n    this.accessToken = options?.accessToken ?? null\n\n    const result: SocketOptions = {}\n    result.timeout = options?.timeout ?? DEFAULT_TIMEOUT\n    result.heartbeatIntervalMs =\n      options?.heartbeatIntervalMs ?? CONNECTION_TIMEOUTS.HEARTBEAT_INTERVAL\n\n    this._disconnectOnEmptyChannelsAfterMs =\n      options?.disconnectOnEmptyChannelsAfterMs ??\n      2 * (options?.heartbeatIntervalMs ?? CONNECTION_TIMEOUTS.HEARTBEAT_INTERVAL)\n\n    // @ts-ignore - mismatch between phoenix and supabase\n    result.transport = options?.transport ?? WebSocketFactory.getWebSocketConstructor()\n    result.params = options?.params\n    result.logger = options?.logger\n    result.heartbeatCallback = this._wrapHeartbeatCallback(options?.heartbeatCallback)\n    result.sessionStorage = options?.sessionStorage ?? resolveSessionStorage()\n    result.reconnectAfterMs =\n      options?.reconnectAfterMs ??\n      ((tries: number) => {\n        return RECONNECT_INTERVALS[tries - 1] || DEFAULT_RECONNECT_FALLBACK\n      })\n\n    let defaultEncode: Encode<void>\n    let defaultDecode: Decode<void>\n\n    const vsn = options?.vsn ?? DEFAULT_VSN\n\n    switch (vsn) {\n      case VSN_1_0_0:\n        defaultEncode = (payload, callback) => {\n          return callback(JSON.stringify(payload))\n        }\n        defaultDecode = (payload, callback) => {\n          return callback(JSON.parse(payload as string))\n        }\n        break\n      case VSN_2_0_0:\n        defaultEncode = this.serializer.encode.bind(this.serializer)\n        defaultDecode = this.serializer.decode.bind(this.serializer)\n        break\n      default:\n        throw new Error(`Unsupported serializer version: ${result.vsn}`)\n    }\n\n    result.vsn = vsn\n    result.encode = options?.encode ?? defaultEncode\n    result.decode = options?.decode ?? defaultDecode\n\n    result.beforeReconnect = this._reconnectAuth.bind(this)\n\n    if (options?.logLevel || options?.log_level) {\n      this.logLevel = options.logLevel || options.log_level\n      result.params = { ...result.params, log_level: this.logLevel as string }\n    }\n\n    // Handle worker setup\n    if (this.worker) {\n      if (typeof window !== 'undefined' && !window.Worker) {\n        throw new Error('Web Worker is not supported')\n      }\n      this.workerUrl = options?.workerUrl\n      result.autoSendHeartbeat = !this.worker\n    }\n\n    return result\n  }\n\n  /** @internal */\n  private async _reconnectAuth() {\n    await this._waitForAuthIfNeeded()\n    if (!this.isConnected()) {\n      this.connect()\n    }\n  }\n}\n", "export interface IcebergErrorResponse {\n  error: {\n    message: string\n    type: string\n    code: number\n    stack?: string[]\n  }\n}\n\nexport class IcebergError extends Error {\n  readonly status: number\n  readonly icebergType?: string\n  readonly icebergCode?: number\n  readonly details?: unknown\n  readonly isCommitStateUnknown: boolean\n\n  constructor(\n    message: string,\n    opts: {\n      status: number\n      icebergType?: string\n      icebergCode?: number\n      details?: unknown\n    }\n  ) {\n    super(message)\n    this.name = 'IcebergError'\n    this.status = opts.status\n    this.icebergType = opts.icebergType\n    this.icebergCode = opts.icebergCode\n    this.details = opts.details\n\n    // Detect CommitStateUnknownException (500, 502, 504 during table commits)\n    this.isCommitStateUnknown =\n      opts.icebergType === 'CommitStateUnknownException' ||\n      ([500, 502, 504].includes(opts.status) && opts.icebergType?.includes('CommitState') === true)\n  }\n\n  /**\n   * Returns true if the error is a 404 Not Found error.\n   */\n  isNotFound(): boolean {\n    return this.status === 404\n  }\n\n  /**\n   * Returns true if the error is a 409 Conflict error.\n   */\n  isConflict(): boolean {\n    return this.status === 409\n  }\n\n  /**\n   * Returns true if the error is a 419 Authentication Timeout error.\n   */\n  isAuthenticationTimeout(): boolean {\n    return this.status === 419\n  }\n}\n", "export function buildUrl(\n  baseUrl: string,\n  path: string,\n  query?: Record<string, string | undefined>\n): string {\n  const url = new URL(path, baseUrl)\n\n  if (query) {\n    for (const [key, value] of Object.entries(query)) {\n      if (value !== undefined) {\n        url.searchParams.set(key, value)\n      }\n    }\n  }\n\n  return url.toString()\n}\n", "import { IcebergError, type IcebergErrorResponse } from '../errors/IcebergError'\nimport { buildUrl } from '../utils/url'\nimport type { AuthConfig, HttpClient, HttpRequest, HttpResponse } from './types'\n\nasync function buildAuthHeaders(auth?: AuthConfig): Promise<Record<string, string>> {\n  if (!auth || auth.type === 'none') {\n    return {}\n  }\n\n  if (auth.type === 'bearer') {\n    return { Authorization: `Bearer ${auth.token}` }\n  }\n\n  if (auth.type === 'header') {\n    return { [auth.name]: auth.value }\n  }\n\n  if (auth.type === 'custom') {\n    return await auth.getHeaders()\n  }\n\n  return {}\n}\n\nexport function createFetchClient(options: {\n  baseUrl: string\n  auth?: AuthConfig\n  fetchImpl?: typeof fetch\n}): HttpClient {\n  const fetchFn = options.fetchImpl ?? globalThis.fetch\n\n  return {\n    async request<T>({\n      method,\n      path,\n      query,\n      body,\n      headers,\n    }: HttpRequest): Promise<HttpResponse<T>> {\n      const url = buildUrl(options.baseUrl, path, query)\n      const authHeaders = await buildAuthHeaders(options.auth)\n\n      const res = await fetchFn(url, {\n        method,\n        headers: {\n          ...(body ? { 'Content-Type': 'application/json' } : {}),\n          ...authHeaders,\n          ...headers,\n        },\n        body: body ? JSON.stringify(body) : undefined,\n      })\n\n      const text = await res.text()\n      const isJson = (res.headers.get('content-type') || '').includes('application/json')\n      const data = isJson && text ? (JSON.parse(text) as T) : (text as T)\n\n      if (!res.ok) {\n        const errBody = isJson ? (data as IcebergErrorResponse) : undefined\n        const errorDetail = errBody?.error\n        throw new IcebergError(\n          errorDetail?.message ?? `Request failed with status ${res.status}`,\n          {\n            status: res.status,\n            icebergType: errorDetail?.type,\n            icebergCode: errorDetail?.code,\n            details: errBody,\n          }\n        )\n      }\n\n      return { status: res.status, headers: res.headers, data: data as T }\n    },\n  }\n}\n", "import type { HttpClient } from '../http/types'\nimport { IcebergError } from '../errors/IcebergError'\nimport type {\n  CreateNamespaceRequest,\n  CreateNamespaceResponse,\n  GetNamespaceResponse,\n  ListNamespacesResponse,\n  NamespaceIdentifier,\n  NamespaceMetadata,\n} from './types'\n\nfunction namespaceToPath(namespace: string[]): string {\n  return namespace.join('\\x1F')\n}\n\nexport class NamespaceOperations {\n  constructor(\n    private readonly client: HttpClient,\n    private readonly prefix: string = ''\n  ) {}\n\n  async listNamespaces(parent?: NamespaceIdentifier): Promise<NamespaceIdentifier[]> {\n    const query = parent ? { parent: namespaceToPath(parent.namespace) } : undefined\n\n    const response = await this.client.request<ListNamespacesResponse>({\n      method: 'GET',\n      path: `${this.prefix}/namespaces`,\n      query,\n    })\n\n    return response.data.namespaces.map((ns) => ({ namespace: ns }))\n  }\n\n  async createNamespace(\n    id: NamespaceIdentifier,\n    metadata?: NamespaceMetadata\n  ): Promise<CreateNamespaceResponse> {\n    const request: CreateNamespaceRequest = {\n      namespace: id.namespace,\n      properties: metadata?.properties,\n    }\n\n    const response = await this.client.request<CreateNamespaceResponse>({\n      method: 'POST',\n      path: `${this.prefix}/namespaces`,\n      body: request,\n    })\n\n    return response.data\n  }\n\n  async dropNamespace(id: NamespaceIdentifier): Promise<void> {\n    await this.client.request<void>({\n      method: 'DELETE',\n      path: `${this.prefix}/namespaces/${namespaceToPath(id.namespace)}`,\n    })\n  }\n\n  async loadNamespaceMetadata(id: NamespaceIdentifier): Promise<NamespaceMetadata> {\n    const response = await this.client.request<GetNamespaceResponse>({\n      method: 'GET',\n      path: `${this.prefix}/namespaces/${namespaceToPath(id.namespace)}`,\n    })\n\n    return {\n      properties: response.data.properties,\n    }\n  }\n\n  async namespaceExists(id: NamespaceIdentifier): Promise<boolean> {\n    try {\n      await this.client.request<void>({\n        method: 'HEAD',\n        path: `${this.prefix}/namespaces/${namespaceToPath(id.namespace)}`,\n      })\n      return true\n    } catch (error) {\n      if (error instanceof IcebergError && error.status === 404) {\n        return false\n      }\n      throw error\n    }\n  }\n\n  async createNamespaceIfNotExists(\n    id: NamespaceIdentifier,\n    metadata?: NamespaceMetadata\n  ): Promise<CreateNamespaceResponse | void> {\n    try {\n      return await this.createNamespace(id, metadata)\n    } catch (error) {\n      if (error instanceof IcebergError && error.status === 409) {\n        return\n      }\n      throw error\n    }\n  }\n}\n", "import type { HttpClient } from '../http/types'\nimport { IcebergError } from '../errors/IcebergError'\nimport type {\n  CreateTableRequest,\n  CommitTableResponse,\n  ListTablesResponse,\n  LoadTableResponse,\n  NamespaceIdentifier,\n  TableIdentifier,\n  TableMetadata,\n  UpdateTableRequest,\n  DropTableRequest,\n} from './types'\n\nfunction namespaceToPath(namespace: string[]): string {\n  return namespace.join('\\x1F')\n}\n\nexport class TableOperations {\n  constructor(\n    private readonly client: HttpClient,\n    private readonly prefix: string = '',\n    private readonly accessDelegation?: string\n  ) {}\n\n  async listTables(namespace: NamespaceIdentifier): Promise<TableIdentifier[]> {\n    const response = await this.client.request<ListTablesResponse>({\n      method: 'GET',\n      path: `${this.prefix}/namespaces/${namespaceToPath(namespace.namespace)}/tables`,\n    })\n\n    return response.data.identifiers\n  }\n\n  async createTable(\n    namespace: NamespaceIdentifier,\n    request: CreateTableRequest\n  ): Promise<TableMetadata> {\n    const headers: Record<string, string> = {}\n    if (this.accessDelegation) {\n      headers['X-Iceberg-Access-Delegation'] = this.accessDelegation\n    }\n\n    const response = await this.client.request<LoadTableResponse>({\n      method: 'POST',\n      path: `${this.prefix}/namespaces/${namespaceToPath(namespace.namespace)}/tables`,\n      body: request,\n      headers,\n    })\n\n    return response.data.metadata\n  }\n\n  async updateTable(id: TableIdentifier, request: UpdateTableRequest): Promise<CommitTableResponse> {\n    const response = await this.client.request<LoadTableResponse>({\n      method: 'POST',\n      path: `${this.prefix}/namespaces/${namespaceToPath(id.namespace)}/tables/${id.name}`,\n      body: request,\n    })\n\n    return {\n      'metadata-location': response.data['metadata-location'],\n      metadata: response.data.metadata,\n    }\n  }\n\n  async dropTable(id: TableIdentifier, options?: DropTableRequest): Promise<void> {\n    await this.client.request<void>({\n      method: 'DELETE',\n      path: `${this.prefix}/namespaces/${namespaceToPath(id.namespace)}/tables/${id.name}`,\n      query: { purgeRequested: String(options?.purge ?? false) },\n    })\n  }\n\n  async loadTable(id: TableIdentifier): Promise<TableMetadata> {\n    const headers: Record<string, string> = {}\n    if (this.accessDelegation) {\n      headers['X-Iceberg-Access-Delegation'] = this.accessDelegation\n    }\n\n    const response = await this.client.request<LoadTableResponse>({\n      method: 'GET',\n      path: `${this.prefix}/namespaces/${namespaceToPath(id.namespace)}/tables/${id.name}`,\n      headers,\n    })\n\n    return response.data.metadata\n  }\n\n  async tableExists(id: TableIdentifier): Promise<boolean> {\n    const headers: Record<string, string> = {}\n    if (this.accessDelegation) {\n      headers['X-Iceberg-Access-Delegation'] = this.accessDelegation\n    }\n\n    try {\n      await this.client.request<void>({\n        method: 'HEAD',\n        path: `${this.prefix}/namespaces/${namespaceToPath(id.namespace)}/tables/${id.name}`,\n        headers,\n      })\n      return true\n    } catch (error) {\n      if (error instanceof IcebergError && error.status === 404) {\n        return false\n      }\n      throw error\n    }\n  }\n\n  async createTableIfNotExists(\n    namespace: NamespaceIdentifier,\n    request: CreateTableRequest\n  ): Promise<TableMetadata> {\n    try {\n      return await this.createTable(namespace, request)\n    } catch (error) {\n      if (error instanceof IcebergError && error.status === 409) {\n        return await this.loadTable({ namespace: namespace.namespace, name: request.name })\n      }\n      throw error\n    }\n  }\n}\n", "import { createFetchClient } from '../http/createFetchClient'\nimport type { AuthConfig, HttpClient } from '../http/types'\nimport { NamespaceOperations } from './namespaces'\nimport { TableOperations } from './tables'\nimport type {\n  CreateTableRequest,\n  CreateNamespaceResponse,\n  CommitTableResponse,\n  NamespaceIdentifier,\n  NamespaceMetadata,\n  TableIdentifier,\n  TableMetadata,\n  UpdateTableRequest,\n  DropTableRequest,\n} from './types'\n\n/**\n * Access delegation mechanisms supported by the Iceberg REST Catalog.\n *\n * - `vended-credentials`: Server provides temporary credentials for data access\n * - `remote-signing`: Server signs requests on behalf of the client\n */\nexport type AccessDelegation = 'vended-credentials' | 'remote-signing'\n\n/**\n * Configuration options for the Iceberg REST Catalog client.\n */\nexport interface IcebergRestCatalogOptions {\n  /** Base URL of the Iceberg REST Catalog API */\n  baseUrl: string\n  /** Optional catalog name prefix for multi-catalog servers */\n  catalogName?: string\n  /** Authentication configuration */\n  auth?: AuthConfig\n  /** Custom fetch implementation (defaults to globalThis.fetch) */\n  fetch?: typeof fetch\n  /**\n   * Access delegation mechanisms to request from the server.\n   * When specified, the X-Iceberg-Access-Delegation header will be sent\n   * with supported operations (createTable, loadTable).\n   *\n   * @example ['vended-credentials']\n   * @example ['vended-credentials', 'remote-signing']\n   */\n  accessDelegation?: AccessDelegation[]\n}\n\n/**\n * Client for interacting with an Apache Iceberg REST Catalog.\n *\n * This class provides methods for managing namespaces and tables in an Iceberg catalog.\n * It handles authentication, request formatting, and error handling automatically.\n *\n * @example\n * ```typescript\n * const catalog = new IcebergRestCatalog({\n *   baseUrl: 'https://my-catalog.example.com/iceberg/v1',\n *   auth: { type: 'bearer', token: process.env.ICEBERG_TOKEN }\n * });\n *\n * // Create a namespace\n * await catalog.createNamespace({ namespace: ['analytics'] });\n *\n * // Create a table\n * await catalog.createTable(\n *   { namespace: ['analytics'] },\n *   {\n *     name: 'events',\n *     schema: { type: 'struct', fields: [...] }\n *   }\n * );\n * ```\n */\nexport class IcebergRestCatalog {\n  private readonly client: HttpClient\n  private readonly namespaceOps: NamespaceOperations\n  private readonly tableOps: TableOperations\n  private readonly accessDelegation?: string\n\n  /**\n   * Creates a new Iceberg REST Catalog client.\n   *\n   * @param options - Configuration options for the catalog client\n   */\n  constructor(options: IcebergRestCatalogOptions) {\n    let prefix = 'v1'\n    if (options.catalogName) {\n      prefix += `/${options.catalogName}`\n    }\n\n    const baseUrl = options.baseUrl.endsWith('/') ? options.baseUrl : `${options.baseUrl}/`\n\n    this.client = createFetchClient({\n      baseUrl,\n      auth: options.auth,\n      fetchImpl: options.fetch,\n    })\n\n    // Format accessDelegation as comma-separated string per spec\n    this.accessDelegation = options.accessDelegation?.join(',')\n\n    this.namespaceOps = new NamespaceOperations(this.client, prefix)\n    this.tableOps = new TableOperations(this.client, prefix, this.accessDelegation)\n  }\n\n  /**\n   * Lists all namespaces in the catalog.\n   *\n   * @param parent - Optional parent namespace to list children under\n   * @returns Array of namespace identifiers\n   *\n   * @example\n   * ```typescript\n   * // List all top-level namespaces\n   * const namespaces = await catalog.listNamespaces();\n   *\n   * // List namespaces under a parent\n   * const children = await catalog.listNamespaces({ namespace: ['analytics'] });\n   * ```\n   */\n  async listNamespaces(parent?: NamespaceIdentifier): Promise<NamespaceIdentifier[]> {\n    return this.namespaceOps.listNamespaces(parent)\n  }\n\n  /**\n   * Creates a new namespace in the catalog.\n   *\n   * @param id - Namespace identifier to create\n   * @param metadata - Optional metadata properties for the namespace\n   * @returns Response containing the created namespace and its properties\n   *\n   * @example\n   * ```typescript\n   * const response = await catalog.createNamespace(\n   *   { namespace: ['analytics'] },\n   *   { properties: { owner: 'data-team' } }\n   * );\n   * console.log(response.namespace); // ['analytics']\n   * console.log(response.properties); // { owner: 'data-team', ... }\n   * ```\n   */\n  async createNamespace(id: NamespaceIdentifier, metadata?: NamespaceMetadata): Promise<CreateNamespaceResponse> {\n    return this.namespaceOps.createNamespace(id, metadata)\n  }\n\n  /**\n   * Drops a namespace from the catalog.\n   *\n   * The namespace must be empty (contain no tables) before it can be dropped.\n   *\n   * @param id - Namespace identifier to drop\n   *\n   * @example\n   * ```typescript\n   * await catalog.dropNamespace({ namespace: ['analytics'] });\n   * ```\n   */\n  async dropNamespace(id: NamespaceIdentifier): Promise<void> {\n    await this.namespaceOps.dropNamespace(id)\n  }\n\n  /**\n   * Loads metadata for a namespace.\n   *\n   * @param id - Namespace identifier to load\n   * @returns Namespace metadata including properties\n   *\n   * @example\n   * ```typescript\n   * const metadata = await catalog.loadNamespaceMetadata({ namespace: ['analytics'] });\n   * console.log(metadata.properties);\n   * ```\n   */\n  async loadNamespaceMetadata(id: NamespaceIdentifier): Promise<NamespaceMetadata> {\n    return this.namespaceOps.loadNamespaceMetadata(id)\n  }\n\n  /**\n   * Lists all tables in a namespace.\n   *\n   * @param namespace - Namespace identifier to list tables from\n   * @returns Array of table identifiers\n   *\n   * @example\n   * ```typescript\n   * const tables = await catalog.listTables({ namespace: ['analytics'] });\n   * console.log(tables); // [{ namespace: ['analytics'], name: 'events' }, ...]\n   * ```\n   */\n  async listTables(namespace: NamespaceIdentifier): Promise<TableIdentifier[]> {\n    return this.tableOps.listTables(namespace)\n  }\n\n  /**\n   * Creates a new table in the catalog.\n   *\n   * @param namespace - Namespace to create the table in\n   * @param request - Table creation request including name, schema, partition spec, etc.\n   * @returns Table metadata for the created table\n   *\n   * @example\n   * ```typescript\n   * const metadata = await catalog.createTable(\n   *   { namespace: ['analytics'] },\n   *   {\n   *     name: 'events',\n   *     schema: {\n   *       type: 'struct',\n   *       fields: [\n   *         { id: 1, name: 'id', type: 'long', required: true },\n   *         { id: 2, name: 'timestamp', type: 'timestamp', required: true }\n   *       ],\n   *       'schema-id': 0\n   *     },\n   *     'partition-spec': {\n   *       'spec-id': 0,\n   *       fields: [\n   *         { source_id: 2, field_id: 1000, name: 'ts_day', transform: 'day' }\n   *       ]\n   *     }\n   *   }\n   * );\n   * ```\n   */\n  async createTable(\n    namespace: NamespaceIdentifier,\n    request: CreateTableRequest\n  ): Promise<TableMetadata> {\n    return this.tableOps.createTable(namespace, request)\n  }\n\n  /**\n   * Updates an existing table's metadata.\n   *\n   * Can update the schema, partition spec, or properties of a table.\n   *\n   * @param id - Table identifier to update\n   * @param request - Update request with fields to modify\n   * @returns Response containing the metadata location and updated table metadata\n   *\n   * @example\n   * ```typescript\n   * const response = await catalog.updateTable(\n   *   { namespace: ['analytics'], name: 'events' },\n   *   {\n   *     properties: { 'read.split.target-size': '134217728' }\n   *   }\n   * );\n   * console.log(response['metadata-location']); // s3://...\n   * console.log(response.metadata); // TableMetadata object\n   * ```\n   */\n  async updateTable(id: TableIdentifier, request: UpdateTableRequest): Promise<CommitTableResponse> {\n    return this.tableOps.updateTable(id, request)\n  }\n\n  /**\n   * Drops a table from the catalog.\n   *\n   * @param id - Table identifier to drop\n   *\n   * @example\n   * ```typescript\n   * await catalog.dropTable({ namespace: ['analytics'], name: 'events' });\n   * ```\n   */\n  async dropTable(id: TableIdentifier, options?: DropTableRequest): Promise<void> {\n    await this.tableOps.dropTable(id, options)\n  }\n\n  /**\n   * Loads metadata for a table.\n   *\n   * @param id - Table identifier to load\n   * @returns Table metadata including schema, partition spec, location, etc.\n   *\n   * @example\n   * ```typescript\n   * const metadata = await catalog.loadTable({ namespace: ['analytics'], name: 'events' });\n   * console.log(metadata.schema);\n   * console.log(metadata.location);\n   * ```\n   */\n  async loadTable(id: TableIdentifier): Promise<TableMetadata> {\n    return this.tableOps.loadTable(id)\n  }\n\n  /**\n   * Checks if a namespace exists in the catalog.\n   *\n   * @param id - Namespace identifier to check\n   * @returns True if the namespace exists, false otherwise\n   *\n   * @example\n   * ```typescript\n   * const exists = await catalog.namespaceExists({ namespace: ['analytics'] });\n   * console.log(exists); // true or false\n   * ```\n   */\n  async namespaceExists(id: NamespaceIdentifier): Promise<boolean> {\n    return this.namespaceOps.namespaceExists(id)\n  }\n\n  /**\n   * Checks if a table exists in the catalog.\n   *\n   * @param id - Table identifier to check\n   * @returns True if the table exists, false otherwise\n   *\n   * @example\n   * ```typescript\n   * const exists = await catalog.tableExists({ namespace: ['analytics'], name: 'events' });\n   * console.log(exists); // true or false\n   * ```\n   */\n  async tableExists(id: TableIdentifier): Promise<boolean> {\n    return this.tableOps.tableExists(id)\n  }\n\n  /**\n   * Creates a namespace if it does not exist.\n   *\n   * If the namespace already exists, returns void. If created, returns the response.\n   *\n   * @param id - Namespace identifier to create\n   * @param metadata - Optional metadata properties for the namespace\n   * @returns Response containing the created namespace and its properties, or void if it already exists\n   *\n   * @example\n   * ```typescript\n   * const response = await catalog.createNamespaceIfNotExists(\n   *   { namespace: ['analytics'] },\n   *   { properties: { owner: 'data-team' } }\n   * );\n   * if (response) {\n   *   console.log('Created:', response.namespace);\n   * } else {\n   *   console.log('Already exists');\n   * }\n   * ```\n   */\n  async createNamespaceIfNotExists(\n    id: NamespaceIdentifier,\n    metadata?: NamespaceMetadata\n  ): Promise<CreateNamespaceResponse | void> {\n    return this.namespaceOps.createNamespaceIfNotExists(id, metadata)\n  }\n\n  /**\n   * Creates a table if it does not exist.\n   *\n   * If the table already exists, returns its metadata instead.\n   *\n   * @param namespace - Namespace to create the table in\n   * @param request - Table creation request including name, schema, partition spec, etc.\n   * @returns Table metadata for the created or existing table\n   *\n   * @example\n   * ```typescript\n   * const metadata = await catalog.createTableIfNotExists(\n   *   { namespace: ['analytics'] },\n   *   {\n   *     name: 'events',\n   *     schema: {\n   *       type: 'struct',\n   *       fields: [\n   *         { id: 1, name: 'id', type: 'long', required: true },\n   *         { id: 2, name: 'timestamp', type: 'timestamp', required: true }\n   *       ],\n   *       'schema-id': 0\n   *     }\n   *   }\n   * );\n   * ```\n   */\n  async createTableIfNotExists(\n    namespace: NamespaceIdentifier,\n    request: CreateTableRequest\n  ): Promise<TableMetadata> {\n    return this.tableOps.createTableIfNotExists(namespace, request)\n  }\n}\n", "export interface NamespaceIdentifier {\n  namespace: string[]\n}\n\nexport interface NamespaceMetadata {\n  properties: Record<string, string>\n}\n\nexport interface TableIdentifier {\n  namespace: string[]\n  name: string\n}\n\n/**\n * Primitive types in Iceberg - all represented as strings.\n * Parameterized types use string format: decimal(precision,scale) and fixed[length]\n *\n * Note: The OpenAPI spec defines PrimitiveType as `type: string`, so any string is valid.\n * We include known types for autocomplete, plus a catch-all for flexibility.\n */\nexport type PrimitiveType =\n  | 'boolean'\n  | 'int'\n  | 'long'\n  | 'float'\n  | 'double'\n  | 'string'\n  | 'timestamp'\n  | 'date'\n  | 'time'\n  | 'timestamptz'\n  | 'uuid'\n  | 'binary'\n  | `decimal(${number},${number})`\n  | `fixed[${number}]`\n  | (string & {}) // catch-all for any format (e.g., \"decimal(10, 2)\" with spaces) and future types\n\n/**\n * Regex patterns for parsing parameterized types.\n * These allow flexible whitespace matching.\n */\nconst DECIMAL_REGEX = /^decimal\\s*\\(\\s*(\\d+)\\s*,\\s*(\\d+)\\s*\\)$/\nconst FIXED_REGEX = /^fixed\\s*\\[\\s*(\\d+)\\s*\\]$/\n\n/**\n * Parse a decimal type string into its components.\n * Handles any whitespace formatting (e.g., \"decimal(10,2)\", \"decimal(10, 2)\", \"decimal( 10 , 2 )\").\n *\n * @param type - The type string to parse\n * @returns Object with precision and scale, or null if not a valid decimal type\n */\nexport function parseDecimalType(type: string): { precision: number; scale: number } | null {\n  const match = type.match(DECIMAL_REGEX)\n  if (!match) return null\n  return {\n    precision: parseInt(match[1], 10),\n    scale: parseInt(match[2], 10),\n  }\n}\n\n/**\n * Parse a fixed type string into its length.\n * Handles any whitespace formatting (e.g., \"fixed[16]\", \"fixed[ 16 ]\").\n *\n * @param type - The type string to parse\n * @returns Object with length, or null if not a valid fixed type\n */\nexport function parseFixedType(type: string): { length: number } | null {\n  const match = type.match(FIXED_REGEX)\n  if (!match) return null\n  return {\n    length: parseInt(match[1], 10),\n  }\n}\n\n/**\n * Check if a type string is a decimal type.\n */\nexport function isDecimalType(type: string): boolean {\n  return DECIMAL_REGEX.test(type)\n}\n\n/**\n * Check if a type string is a fixed type.\n */\nexport function isFixedType(type: string): boolean {\n  return FIXED_REGEX.test(type)\n}\n\n/**\n * Compare two Iceberg type strings for equality, ignoring whitespace differences.\n * This is useful when comparing types from user input vs catalog responses,\n * as catalogs may normalize whitespace differently.\n *\n * @param a - First type string\n * @param b - Second type string\n * @returns true if the types are equivalent\n */\nexport function typesEqual(a: string, b: string): boolean {\n  // For decimal types, compare parsed values\n  const decimalA = parseDecimalType(a)\n  const decimalB = parseDecimalType(b)\n  if (decimalA && decimalB) {\n    return decimalA.precision === decimalB.precision && decimalA.scale === decimalB.scale\n  }\n\n  // For fixed types, compare parsed values\n  const fixedA = parseFixedType(a)\n  const fixedB = parseFixedType(b)\n  if (fixedA && fixedB) {\n    return fixedA.length === fixedB.length\n  }\n\n  // For other types, direct string comparison\n  return a === b\n}\n\n/**\n * Struct type - a nested structure containing fields.\n * Used for nested records within a field.\n */\nexport interface StructType {\n  type: 'struct'\n  fields: StructField[]\n}\n\n/**\n * List type - an array of elements.\n */\nexport interface ListType {\n  type: 'list'\n  'element-id': number\n  element: IcebergType\n  'element-required': boolean\n}\n\n/**\n * Map type - a key-value mapping.\n */\nexport interface MapType {\n  type: 'map'\n  'key-id': number\n  key: IcebergType\n  'value-id': number\n  value: IcebergType\n  'value-required': boolean\n}\n\n/**\n * Union of all Iceberg types.\n * Can be a primitive type (string) or a complex type (struct, list, map).\n */\nexport type IcebergType = PrimitiveType | StructType | ListType | MapType\n\n/**\n * Primitive type values for default values.\n * Represents the possible values for initial-default and write-default.\n */\nexport type PrimitiveTypeValue = boolean | number | string\n\n/**\n * A field within a struct (used in nested StructType).\n */\nexport interface StructField {\n  id: number\n  name: string\n  type: IcebergType\n  required: boolean\n  doc?: string\n  'initial-default'?: PrimitiveTypeValue\n  'write-default'?: PrimitiveTypeValue\n}\n\n/**\n * A field within a table schema (top-level).\n * Equivalent to StructField but kept for backwards compatibility.\n */\nexport interface TableField {\n  id: number\n  name: string\n  type: IcebergType\n  required: boolean\n  doc?: string\n  'initial-default'?: PrimitiveTypeValue\n  'write-default'?: PrimitiveTypeValue\n}\n\nexport interface TableSchema {\n  type: 'struct'\n  fields: TableField[]\n  'schema-id'?: number\n  'identifier-field-ids'?: number[]\n}\n\nexport interface PartitionField {\n  source_id: number\n  field_id: number\n  name: string\n  transform: string\n}\n\nexport interface PartitionSpec {\n  'spec-id': number\n  fields: PartitionField[]\n}\n\nexport interface SortField {\n  source_id: number\n  transform: string\n  direction: 'asc' | 'desc'\n  null_order: 'nulls-first' | 'nulls-last'\n}\n\nexport interface SortOrder {\n  'order-id': number\n  fields: SortField[]\n}\n\nexport interface CreateTableRequest {\n  name: string\n  schema: TableSchema\n  'partition-spec'?: PartitionSpec\n  'write-order'?: SortOrder\n  properties?: Record<string, string>\n  'stage-create'?: boolean\n}\n\nexport interface UpdateTableRequest {\n  schema?: TableSchema\n  'partition-spec'?: PartitionSpec\n  properties?: Record<string, string>\n}\n\nexport interface DropTableRequest {\n  purge?: boolean\n}\n\nexport interface TableMetadata {\n  name?: string\n  location: string\n  schemas: TableSchema[]\n  'current-schema-id': number\n  'partition-specs': PartitionSpec[]\n  'default-spec-id'?: number\n  'sort-orders': SortOrder[]\n  'default-sort-order-id'?: number\n  properties: Record<string, string>\n  'metadata-location'?: string\n  'current-snapshot-id'?: number\n  snapshots?: unknown[]\n  'snapshot-log'?: unknown[]\n  'metadata-log'?: unknown[]\n  refs?: Record<string, unknown>\n  'last-updated-ms'?: number\n  'last-column-id'?: number\n  'last-sequence-number'?: number\n  'table-uuid'?: string\n  'format-version'?: number\n  'last-partition-id'?: number\n}\n\nexport interface CreateNamespaceRequest {\n  namespace: string[]\n  properties?: Record<string, string>\n}\n\nexport interface CreateNamespaceResponse {\n  namespace: string[]\n  properties?: Record<string, string>\n}\n\nexport interface GetNamespaceResponse {\n  namespace: string[]\n  properties: Record<string, string>\n}\n\nexport interface ListNamespacesResponse {\n  namespaces: string[][]\n  'next-page-token'?: string\n}\n\nexport interface ListTablesResponse {\n  identifiers: TableIdentifier[]\n  'next-page-token'?: string\n}\n\nexport interface LoadTableResponse {\n  'metadata-location': string\n  metadata: TableMetadata\n  config?: Record<string, string>\n}\n\nexport interface CommitTableResponse {\n  'metadata-location': string\n  metadata: TableMetadata\n}\n\n/**\n * Gets the current (active) schema from table metadata.\n *\n * @param metadata - Table metadata containing schemas array and current-schema-id\n * @returns The current table schema, or undefined if not found\n */\nexport function getCurrentSchema(metadata: TableMetadata): TableSchema | undefined {\n  return metadata.schemas.find((s) => s['schema-id'] === metadata['current-schema-id'])\n}\n", "/**\n * Namespace type for error classes\n * Determines the error class names and type guards\n */\nexport type ErrorNamespace = 'storage' | 'vectors'\n\n/**\n * Base error class for all Storage errors\n * Supports both 'storage' and 'vectors' namespaces\n */\nexport class StorageError extends Error {\n  protected __isStorageError = true\n  protected namespace: ErrorNamespace\n  status: number | undefined\n  statusCode: string | undefined\n\n  constructor(\n    message: string,\n    namespace: ErrorNamespace = 'storage',\n    status?: number,\n    statusCode?: string\n  ) {\n    super(message)\n    this.namespace = namespace\n    this.name = namespace === 'vectors' ? 'StorageVectorsError' : 'StorageError'\n    this.status = status\n    this.statusCode = statusCode\n  }\n\n  toJSON(): {\n    name: string\n    message: string\n    status: number | undefined\n    statusCode: string | undefined\n  } {\n    return {\n      name: this.name,\n      message: this.message,\n      status: this.status,\n      statusCode: this.statusCode,\n    }\n  }\n}\n\n/**\n * Type guard to check if an error is a StorageError\n * @param error - The error to check\n * @returns True if the error is a StorageError\n */\nexport function isStorageError(error: unknown): error is StorageError {\n  return typeof error === 'object' && error !== null && '__isStorageError' in error\n}\n\n/**\n * API error returned from Storage service\n * Includes HTTP status code and service-specific error code\n */\nexport class StorageApiError extends StorageError {\n  override status: number\n  override statusCode: string\n  /**\n   * Service-specific error code from the Storage API response body, such as\n   * `NoSuchKey`, `AccessDenied` or `ResourceAlreadyExists`. Use this to branch\n   * on the specific error rather than parsing the message.\n   * @see https://supabase.com/docs/guides/storage/debugging/error-codes\n   */\n  code: string | undefined\n\n  constructor(\n    message: string,\n    status: number,\n    statusCode: string,\n    namespace: ErrorNamespace = 'storage',\n    code?: string\n  ) {\n    super(message, namespace, status, statusCode)\n    this.name = namespace === 'vectors' ? 'StorageVectorsApiError' : 'StorageApiError'\n    this.status = status\n    this.statusCode = statusCode\n    this.code = code\n  }\n\n  toJSON(): {\n    name: string\n    message: string\n    status: number | undefined\n    statusCode: string | undefined\n    code: string | undefined\n  } {\n    return {\n      ...super.toJSON(),\n      code: this.code,\n    }\n  }\n}\n\n/**\n * Unknown error that doesn't match expected error patterns\n * Wraps the original error for debugging\n */\nexport class StorageUnknownError extends StorageError {\n  originalError: unknown\n\n  constructor(message: string, originalError: unknown, namespace: ErrorNamespace = 'storage') {\n    super(message, namespace)\n    this.name = namespace === 'vectors' ? 'StorageVectorsUnknownError' : 'StorageUnknownError'\n    this.originalError = originalError\n  }\n}\n\n// ============================================================================\n// Backward Compatibility Exports for Vectors\n// ============================================================================\n\n/**\n * @deprecated Use StorageError with namespace='vectors' instead\n * Alias for backward compatibility with existing vector storage code\n */\nexport class StorageVectorsError extends StorageError {\n  constructor(message: string) {\n    super(message, 'vectors')\n  }\n}\n\n/**\n * Type guard to check if an error is a StorageVectorsError\n * @param error - The error to check\n * @returns True if the error is a StorageVectorsError\n */\nexport function isStorageVectorsError(error: unknown): error is StorageVectorsError {\n  return isStorageError(error) && (error as StorageError)['namespace'] === 'vectors'\n}\n\n/**\n * @deprecated Use StorageApiError with namespace='vectors' instead\n * Alias for backward compatibility with existing vector storage code\n */\nexport class StorageVectorsApiError extends StorageApiError {\n  constructor(message: string, status: number, statusCode: string) {\n    super(message, status, statusCode, 'vectors')\n  }\n}\n\n/**\n * @deprecated Use StorageUnknownError with namespace='vectors' instead\n * Alias for backward compatibility with existing vector storage code\n */\nexport class StorageVectorsUnknownError extends StorageUnknownError {\n  constructor(message: string, originalError: unknown) {\n    super(message, originalError, 'vectors')\n  }\n}\n\n/**\n * Error codes specific to S3 Vectors API\n * Maps AWS service errors to application-friendly error codes\n */\nexport enum StorageVectorsErrorCode {\n  /** Internal server fault (HTTP 500) */\n  InternalError = 'InternalError',\n  /** Resource already exists / conflict (HTTP 409) */\n  S3VectorConflictException = 'S3VectorConflictException',\n  /** Resource not found (HTTP 404) */\n  S3VectorNotFoundException = 'S3VectorNotFoundException',\n  /** Delete bucket while not empty (HTTP 400) */\n  S3VectorBucketNotEmpty = 'S3VectorBucketNotEmpty',\n  /** Exceeds bucket quota/limit (HTTP 400) */\n  S3VectorMaxBucketsExceeded = 'S3VectorMaxBucketsExceeded',\n  /** Exceeds index quota/limit (HTTP 400) */\n  S3VectorMaxIndexesExceeded = 'S3VectorMaxIndexesExceeded',\n}\n", "/**\n * Sets a header with case-insensitive deduplication.\n * Removes any existing headers whose name matches (case-insensitive),\n * then sets the value under the lowercase key. Does not mutate the input object.\n *\n * @param headers - Existing headers object\n * @param name - Header name to set (stored as lowercase)\n * @param value - Header value\n * @returns New headers object with the header set\n */\nexport function setHeader(\n  headers: Record<string, string>,\n  name: string,\n  value: string\n): Record<string, string> {\n  const result = { ...headers }\n  const nameLower = name.toLowerCase()\n\n  for (const key of Object.keys(result)) {\n    if (key.toLowerCase() === nameLower) {\n      delete result[key]\n    }\n  }\n\n  result[nameLower] = value\n  return result\n}\n\n/**\n * Normalizes all header keys to lowercase with case-insensitive deduplication.\n * When duplicate keys exist (differing only in case), the last value wins.\n * Does not mutate the input object.\n *\n * @param headers - Headers object to normalize\n * @returns New headers object with all keys lowercased\n */\nexport function normalizeHeaders(headers: Record<string, string>): Record<string, string> {\n  const result: Record<string, string> = {}\n  for (const [key, value] of Object.entries(headers)) {\n    result[key.toLowerCase()] = value\n  }\n  return result\n}\n", "type Fetch = typeof fetch\n\n/**\n * Resolves the fetch implementation to use\n * Uses custom fetch if provided, otherwise uses native fetch\n *\n * @param customFetch - Optional custom fetch implementation\n * @returns Resolved fetch function\n */\nexport const resolveFetch = (customFetch?: Fetch): Fetch => {\n  if (customFetch) {\n    return (...args) => customFetch(...args)\n  }\n  return (...args) => fetch(...args)\n}\n\n/**\n * Resolves the Response constructor to use\n * Returns native Response constructor\n *\n * @returns Response constructor\n */\nexport const resolveResponse = (): typeof Response => {\n  return Response\n}\n\n/**\n * Determine if input is a plain object\n * An object is plain if it's created by either {}, new Object(), or Object.create(null)\n *\n * @param value - Value to check\n * @returns True if value is a plain object\n * @source https://github.com/sindresorhus/is-plain-obj\n */\nexport const isPlainObject = (value: object): boolean => {\n  if (typeof value !== 'object' || value === null) {\n    return false\n  }\n\n  const prototype = Object.getPrototypeOf(value)\n  return (\n    (prototype === null ||\n      prototype === Object.prototype ||\n      Object.getPrototypeOf(prototype) === null) &&\n    !(Symbol.toStringTag in value) &&\n    !(Symbol.iterator in value)\n  )\n}\n\n/**\n * Recursively converts object keys from snake_case to camelCase\n * Used for normalizing API responses\n *\n * @param item - Object to convert\n * @returns Converted object with camelCase keys\n */\nexport const recursiveToCamel = (item: Record<string, any>): unknown => {\n  if (Array.isArray(item)) {\n    return item.map((el) => recursiveToCamel(el))\n  } else if (typeof item === 'function' || item !== Object(item)) {\n    return item\n  }\n\n  const result: Record<string, any> = {}\n  Object.entries(item).forEach(([key, value]) => {\n    const newKey = key.replace(/([-_][a-z])/gi, (c) => c.toUpperCase().replace(/[-_]/g, ''))\n    result[newKey] = recursiveToCamel(value)\n  })\n\n  return result\n}\n\n/**\n * Validates if a given bucket name is valid according to Supabase Storage API rules\n * Mirrors backend validation from: storage/src/storage/limits.ts:isValidBucketName()\n *\n * Rules:\n * - Length: 1-100 characters\n * - Allowed characters: alphanumeric (a-z, A-Z, 0-9), underscore (_), and safe special characters\n * - Safe special characters: ! - . * ' ( ) space & $ @ = ; : + , ?\n * - Forbidden: path separators (/, \\), path traversal (..), leading/trailing whitespace\n *\n * AWS S3 Reference: https://docs.aws.amazon.com/AmazonS3/latest/userguide/object-keys.html\n *\n * @param bucketName - The bucket name to validate\n * @returns true if valid, false otherwise\n */\nexport const isValidBucketName = (bucketName: string): boolean => {\n  if (!bucketName || typeof bucketName !== 'string') {\n    return false\n  }\n\n  // Check length constraints (1-100 characters)\n  if (bucketName.length === 0 || bucketName.length > 100) {\n    return false\n  }\n\n  // Check for leading/trailing whitespace\n  if (bucketName.trim() !== bucketName) {\n    return false\n  }\n\n  // Explicitly reject path separators (security)\n  // Note: Consecutive periods (..) are allowed by backend - the AWS restriction\n  // on relative paths applies to object keys, not bucket names\n  if (bucketName.includes('/') || bucketName.includes('\\\\')) {\n    return false\n  }\n\n  // Validate against allowed character set\n  // Pattern matches backend regex: /^(\\w|!|-|\\.|\\*|'|\\(|\\)| |&|\\$|@|=|;|:|\\+|,|\\?)*$/\n  // This explicitly excludes path separators (/, \\) and other problematic characters\n  const bucketNameRegex = /^[\\w!.\\*'() &$@=;:+,?-]+$/\n  return bucketNameRegex.test(bucketName)\n}\n\n/**\n * Normalizes a number array to float32 format\n * Ensures all vector values are valid 32-bit floats\n *\n * @param values - Array of numbers to normalize\n * @returns Normalized float32 array\n */\nexport const normalizeToFloat32 = (values: number[]): number[] => {\n  // Use Float32Array to ensure proper precision\n  return Array.from(new Float32Array(values))\n}\n\n/**\n * Validates vector dimensions match expected dimension\n * Throws error if dimensions don't match\n *\n * @param vector - Vector data to validate\n * @param expectedDimension - Expected vector dimension\n * @throws Error if dimensions don't match\n */\nexport const validateVectorDimension = (\n  vector: { float32: number[] },\n  expectedDimension?: number\n): void => {\n  if (expectedDimension !== undefined && vector.float32.length !== expectedDimension) {\n    throw new Error(\n      `Vector dimension mismatch: expected ${expectedDimension}, got ${vector.float32.length}`\n    )\n  }\n}\n\n/**\n * Percent-encodes each segment of a storage path so URL delimiters within a\n * key (e.g. `?`, `#`) can't be interpreted as a querystring/fragment start.\n *\n * Splits on `/` so real path separators stay literal — the storage server\n * routes on them and decodes each segment back to the original key.\n *\n * @param path - A bucket id or `bucketId/objectKey` path\n * @returns The path with each `/`-delimited segment percent-encoded\n */\nexport const encodeStoragePath = (path: string): string =>\n  path.split('/').map(encodeURIComponent).join('/')\n", "import { StorageApiError, StorageError, StorageUnknownError, ErrorNamespace } from './errors'\nimport { setHeader } from './headers'\nimport { isPlainObject, resolveResponse } from './helpers'\nimport { FetchParameters } from '../types'\n\nexport type Fetch = typeof fetch\n\n/**\n * Options for fetch requests\n */\nexport interface FetchOptions {\n  headers?: {\n    [key: string]: string\n  }\n  duplex?: string\n  noResolveJson?: boolean\n}\n\n/**\n * HTTP methods supported by the API\n */\nexport type RequestMethodType = 'GET' | 'POST' | 'PUT' | 'DELETE' | 'HEAD'\n\n/**\n * Extracts error message from various error response formats\n * @param err - Error object from API\n * @returns Human-readable error message\n */\nconst _getErrorMessage = (err: unknown): string => {\n  if (typeof err === 'object' && err !== null) {\n    const e = err as Record<string, unknown>\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    if (typeof e.error === 'object' && e.error !== null) {\n      const nested = e.error as Record<string, unknown>\n      if (typeof nested.message === 'string') return nested.message\n    }\n  }\n  return JSON.stringify(err)\n}\n\n/**\n * Handles fetch errors and converts them to Storage error types\n * @param error - The error caught from fetch\n * @param reject - Promise rejection function\n * @param options - Fetch options that may affect error handling\n * @param namespace - Error namespace ('storage' or 'vectors')\n */\nconst handleError = async (\n  error: unknown,\n  reject: (reason: StorageError) => void,\n  options: FetchOptions | undefined,\n  namespace: ErrorNamespace\n) => {\n  // Structural detection of json() method, present in all Response implementations\n  // (native, node-fetch, cross-fetch, undici) and absent from standard Error objects.\n  // Checking 'ok' or 'status' via `in` is unreliable across fetch polyfills/realms.\n  const isResponseLike =\n    error !== null &&\n    typeof error === 'object' &&\n    'json' in error &&\n    typeof (error as Record<string, unknown>).json === 'function'\n\n  if (isResponseLike) {\n    const responseError = error as Response\n    // Defensive coercion: some fetch polyfills have historically returned status as a string.\n    let status = parseInt(String(responseError.status), 10)\n    if (!Number.isFinite(status)) {\n      status = 500\n    }\n\n    responseError\n      .json()\n      .then(\n        (err: { statusCode?: string; code?: string; error?: string; message?: string } | null) => {\n          const statusCode = err?.statusCode || err?.code || status + ''\n          reject(\n            new StorageApiError(_getErrorMessage(err), status, statusCode, namespace, err?.code)\n          )\n        }\n      )\n      .catch(() => {\n        const statusCode = status + ''\n        const message = responseError.statusText || `HTTP ${status} error`\n        reject(new StorageApiError(message, status, statusCode, namespace))\n      })\n  } else {\n    reject(new StorageUnknownError(_getErrorMessage(error), error, namespace))\n  }\n}\n\n/**\n * Builds request parameters for fetch calls\n * @param method - HTTP method\n * @param options - Custom fetch options\n * @param parameters - Additional fetch parameters like AbortSignal\n * @param body - Request body (will be JSON stringified if plain object)\n * @returns Complete fetch request parameters\n */\nconst _getRequestParams = (\n  method: RequestMethodType,\n  options?: FetchOptions,\n  parameters?: FetchParameters,\n  body?: object\n) => {\n  const params: { [k: string]: any } = { method, headers: options?.headers || {} }\n\n  if (method === 'GET' || method === 'HEAD' || !body) {\n    return { ...params, ...parameters }\n  }\n\n  if (isPlainObject(body)) {\n    const headers = options?.headers || {}\n    let contentType: string | undefined\n\n    for (const [key, value] of Object.entries(headers)) {\n      if (key.toLowerCase() === 'content-type') {\n        contentType = value\n      }\n    }\n\n    params.headers = setHeader(headers, 'Content-Type', contentType ?? 'application/json')\n    params.body = JSON.stringify(body)\n  } else {\n    params.body = body\n  }\n\n  if (options?.duplex) {\n    params.duplex = options.duplex\n  }\n\n  return { ...params, ...parameters }\n}\n\n/**\n * Internal request handler that wraps fetch with error handling\n * @param fetcher - Fetch function to use\n * @param method - HTTP method\n * @param url - Request URL\n * @param options - Custom fetch options\n * @param parameters - Additional fetch parameters\n * @param body - Request body\n * @param namespace - Error namespace ('storage' or 'vectors')\n * @returns Promise with parsed response or error\n */\nasync function _handleRequest(\n  fetcher: Fetch,\n  method: RequestMethodType,\n  url: string,\n  options: FetchOptions | undefined,\n  parameters: FetchParameters | undefined,\n  body: object | undefined,\n  namespace: ErrorNamespace\n): Promise<any> {\n  return new Promise((resolve, reject) => {\n    fetcher(url, _getRequestParams(method, options, parameters, body))\n      .then((result) => {\n        if (!result.ok) throw result\n        if (options?.noResolveJson) return result\n\n        // AWS S3 Vectors API returns 200 OK with content-length: 0 for successful mutations\n        // (putVectors, deleteVectors) instead of 204 or JSON response. This is AWS's design choice\n        // for performance optimization of bulk operations (up to 500 vectors per request).\n        // We handle this to prevent \"Unexpected end of JSON input\" errors when calling result.json()\n        if (namespace === 'vectors') {\n          const contentType = result.headers.get('content-type')\n          const contentLength = result.headers.get('content-length')\n\n          // Return empty object for explicitly empty responses\n          if (contentLength === '0' || result.status === 204) {\n            return {}\n          }\n\n          // Return empty object if no JSON content type\n          if (!contentType || !contentType.includes('application/json')) {\n            return {}\n          }\n        }\n\n        return result.json()\n      })\n      .then((data) => resolve(data))\n      .catch((error) => handleError(error, reject, options, namespace))\n  })\n}\n\n/**\n * Creates a fetch API with the specified namespace\n * @param namespace - Error namespace ('storage' or 'vectors')\n * @returns Object with HTTP method functions\n */\nexport function createFetchApi(namespace: ErrorNamespace = 'storage') {\n  return {\n    /**\n     * Performs a GET request\n     * @param fetcher - Fetch function to use\n     * @param url - Request URL\n     * @param options - Custom fetch options\n     * @param parameters - Additional fetch parameters\n     * @returns Promise with parsed response\n     */\n    get: async (\n      fetcher: Fetch,\n      url: string,\n      options?: FetchOptions,\n      parameters?: FetchParameters\n    ): Promise<any> => {\n      return _handleRequest(fetcher, 'GET', url, options, parameters, undefined, namespace)\n    },\n\n    /**\n     * Performs a POST request\n     * @param fetcher - Fetch function to use\n     * @param url - Request URL\n     * @param body - Request body to be JSON stringified\n     * @param options - Custom fetch options\n     * @param parameters - Additional fetch parameters\n     * @returns Promise with parsed response\n     */\n    post: async (\n      fetcher: Fetch,\n      url: string,\n      body: object,\n      options?: FetchOptions,\n      parameters?: FetchParameters\n    ): Promise<any> => {\n      return _handleRequest(fetcher, 'POST', url, options, parameters, body, namespace)\n    },\n\n    /**\n     * Performs a PUT request\n     * @param fetcher - Fetch function to use\n     * @param url - Request URL\n     * @param body - Request body to be JSON stringified\n     * @param options - Custom fetch options\n     * @param parameters - Additional fetch parameters\n     * @returns Promise with parsed response\n     */\n    put: async (\n      fetcher: Fetch,\n      url: string,\n      body: object,\n      options?: FetchOptions,\n      parameters?: FetchParameters\n    ): Promise<any> => {\n      return _handleRequest(fetcher, 'PUT', url, options, parameters, body, namespace)\n    },\n\n    /**\n     * Performs a HEAD request\n     * @param fetcher - Fetch function to use\n     * @param url - Request URL\n     * @param options - Custom fetch options\n     * @param parameters - Additional fetch parameters\n     * @returns Promise with Response object (not JSON parsed)\n     */\n    head: async (\n      fetcher: Fetch,\n      url: string,\n      options?: FetchOptions,\n      parameters?: FetchParameters\n    ): Promise<any> => {\n      return _handleRequest(\n        fetcher,\n        'HEAD',\n        url,\n        {\n          ...options,\n          noResolveJson: true,\n        },\n        parameters,\n        undefined,\n        namespace\n      )\n    },\n\n    /**\n     * Performs a DELETE request\n     * @param fetcher - Fetch function to use\n     * @param url - Request URL\n     * @param body - Request body to be JSON stringified\n     * @param options - Custom fetch options\n     * @param parameters - Additional fetch parameters\n     * @returns Promise with parsed response\n     */\n    remove: async (\n      fetcher: Fetch,\n      url: string,\n      body: object,\n      options?: FetchOptions,\n      parameters?: FetchParameters\n    ): Promise<any> => {\n      return _handleRequest(fetcher, 'DELETE', url, options, parameters, body, namespace)\n    },\n  }\n}\n\n// Default exports for backward compatibility with 'storage' namespace\nconst defaultApi = createFetchApi('storage')\nexport const { get, post, put, head, remove } = defaultApi\n\n// Vectors API with 'vectors' namespace for proper error handling\nexport const vectorsApi = createFetchApi('vectors')\n", "import { ErrorNamespace, isStorageError, StorageError } from './errors'\nimport { Fetch } from './fetch'\nimport { normalizeHeaders, setHeader as setHeaderUtil } from './headers'\nimport { resolveFetch } from './helpers'\n\n/**\n * @ignore\n * Base API client class for all Storage API classes\n * Provides common infrastructure for error handling and configuration\n *\n * @typeParam TError - The error type (StorageError or subclass)\n */\nexport default abstract class BaseApiClient<TError extends StorageError = StorageError> {\n  protected url: string\n  protected headers: { [key: string]: string }\n  protected fetch: Fetch\n  protected shouldThrowOnError = false\n  protected namespace: ErrorNamespace\n\n  /**\n   * Creates a new BaseApiClient instance\n   * @param url - Base URL for API requests\n   * @param headers - Default headers for API requests\n   * @param fetch - Optional custom fetch implementation\n   * @param namespace - Error namespace ('storage' or 'vectors')\n   */\n  constructor(\n    url: string,\n    headers: { [key: string]: string } = {},\n    fetch?: Fetch,\n    namespace: ErrorNamespace = 'storage'\n  ) {\n    this.url = url\n    this.headers = normalizeHeaders(headers)\n    this.fetch = resolveFetch(fetch)\n    this.namespace = namespace\n  }\n\n  /**\n   * Enable throwing errors instead of returning them.\n   * When enabled, errors are thrown instead of returned in { data, error } format.\n   *\n   * @returns this - For method chaining\n   */\n  public throwOnError(): this {\n    this.shouldThrowOnError = true\n    return this\n  }\n\n  /**\n   * Set an HTTP header for the request.\n   * Creates a shallow copy of headers to avoid mutating shared state.\n   *\n   * @param name - Header name\n   * @param value - Header value\n   * @returns this - For method chaining\n   */\n  public setHeader(name: string, value: string): this {\n    this.headers = setHeaderUtil(this.headers, name, value)\n    return this\n  }\n\n  /**\n   * Handles API operation with standardized error handling\n   * Eliminates repetitive try-catch blocks across all API methods\n   *\n   * This wrapper:\n   * 1. Executes the operation\n   * 2. Returns { data, error: null } on success\n   * 3. Returns { data: null, error } on failure (if shouldThrowOnError is false)\n   * 4. Throws error on failure (if shouldThrowOnError is true)\n   *\n   * @typeParam T - The expected data type from the operation\n   * @param operation - Async function that performs the API call\n   * @returns Promise with { data, error } tuple\n   *\n   * @example Handling an operation\n   * ```typescript\n   * async listBuckets() {\n   *   return this.handleOperation(async () => {\n   *     return await get(this.fetch, `${this.url}/bucket`, {\n   *       headers: this.headers,\n   *     })\n   *   })\n   * }\n   * ```\n   */\n  protected async handleOperation<T>(\n    operation: () => Promise<T>\n  ): Promise<{ data: T; error: null } | { data: null; error: TError }> {\n    try {\n      const data = await operation()\n      return { data, error: null }\n    } catch (error) {\n      if (this.shouldThrowOnError) {\n        throw error\n      }\n      if (isStorageError(error)) {\n        return { data: null, error: error as TError }\n      }\n      throw error\n    }\n  }\n}\n", "import { isStorageError } from '../lib/common/errors'\nimport { DownloadResult } from '../lib/types'\n\nexport default class StreamDownloadBuilder implements Promise<DownloadResult<ReadableStream>> {\n  readonly [Symbol.toStringTag]: string = 'StreamDownloadBuilder'\n  private promise: Promise<DownloadResult<ReadableStream>> | null = null\n\n  constructor(\n    private downloadFn: () => Promise<Response>,\n    private shouldThrowOnError: boolean\n  ) {}\n\n  then<TResult1 = DownloadResult<ReadableStream>, TResult2 = never>(\n    onfulfilled?:\n      | ((value: DownloadResult<ReadableStream>) => TResult1 | PromiseLike<TResult1>)\n      | null,\n    onrejected?: ((reason: any) => TResult2 | PromiseLike<TResult2>) | null\n  ): Promise<TResult1 | TResult2> {\n    return this.getPromise().then(onfulfilled, onrejected)\n  }\n\n  catch<TResult = never>(\n    onrejected?: ((reason: any) => TResult | PromiseLike<TResult>) | null\n  ): Promise<DownloadResult<ReadableStream> | TResult> {\n    return this.getPromise().catch(onrejected)\n  }\n\n  finally(onfinally?: (() => void) | null): Promise<DownloadResult<ReadableStream>> {\n    return this.getPromise().finally(onfinally)\n  }\n\n  private getPromise(): Promise<DownloadResult<ReadableStream>> {\n    if (!this.promise) {\n      this.promise = this.execute()\n    }\n    return this.promise\n  }\n\n  private async execute(): Promise<DownloadResult<ReadableStream>> {\n    try {\n      const result = await this.downloadFn()\n\n      return {\n        data: result.body as ReadableStream,\n        error: null,\n      }\n    } catch (error) {\n      if (this.shouldThrowOnError) {\n        throw error\n      }\n\n      if (isStorageError(error)) {\n        return { data: null, error }\n      }\n\n      throw error\n    }\n  }\n}\n", "import { isStorageError } from '../lib/common/errors'\nimport { DownloadResult } from '../lib/types'\nimport StreamDownloadBuilder from './StreamDownloadBuilder'\n\nexport default class BlobDownloadBuilder implements Promise<DownloadResult<Blob>> {\n  readonly [Symbol.toStringTag]: string = 'BlobDownloadBuilder'\n  private promise: Promise<DownloadResult<Blob>> | null = null\n\n  constructor(\n    private downloadFn: () => Promise<Response>,\n    private shouldThrowOnError: boolean\n  ) {}\n\n  asStream(): StreamDownloadBuilder {\n    return new StreamDownloadBuilder(this.downloadFn, this.shouldThrowOnError)\n  }\n\n  then<TResult1 = DownloadResult<Blob>, TResult2 = never>(\n    onfulfilled?: ((value: DownloadResult<Blob>) => TResult1 | PromiseLike<TResult1>) | null,\n    onrejected?: ((reason: any) => TResult2 | PromiseLike<TResult2>) | null\n  ): Promise<TResult1 | TResult2> {\n    return this.getPromise().then(onfulfilled, onrejected)\n  }\n\n  catch<TResult = never>(\n    onrejected?: ((reason: any) => TResult | PromiseLike<TResult>) | null\n  ): Promise<DownloadResult<Blob> | TResult> {\n    return this.getPromise().catch(onrejected)\n  }\n\n  finally(onfinally?: (() => void) | null): Promise<DownloadResult<Blob>> {\n    return this.getPromise().finally(onfinally)\n  }\n\n  private getPromise(): Promise<DownloadResult<Blob>> {\n    if (!this.promise) {\n      this.promise = this.execute()\n    }\n    return this.promise\n  }\n\n  private async execute(): Promise<DownloadResult<Blob>> {\n    try {\n      const result = await this.downloadFn()\n\n      return {\n        data: await result.blob(),\n        error: null,\n      }\n    } catch (error) {\n      if (this.shouldThrowOnError) {\n        throw error\n      }\n\n      if (isStorageError(error)) {\n        return { data: null, error }\n      }\n\n      throw error\n    }\n  }\n}\n", "import {\n  StorageApiError,\n  StorageError,\n  StorageUnknownError,\n  isStorageError,\n} from '../lib/common/errors'\nimport { get, head, post, put, remove, Fetch } from '../lib/common/fetch'\nimport { setHeader } from '../lib/common/headers'\nimport { encodeStoragePath, recursiveToCamel } from '../lib/common/helpers'\nimport BaseApiClient from '../lib/common/BaseApiClient'\nimport {\n  FileObject,\n  FileOptions,\n  SearchOptions,\n  FetchParameters,\n  TransformOptions,\n  DestinationOptions,\n  CopyOptions,\n  FileObjectV2,\n  Camelize,\n  SearchV2Options,\n  SearchV2Result,\n  PurgeCacheOptions,\n  DeleteObjectEntry,\n} from '../lib/types'\nimport BlobDownloadBuilder from './BlobDownloadBuilder'\n\nconst DEFAULT_SEARCH_OPTIONS = {\n  limit: 100,\n  offset: 0,\n  sortBy: {\n    column: 'name',\n    order: 'asc',\n  },\n}\n\nconst DEFAULT_FILE_OPTIONS: FileOptions = {\n  cacheControl: '3600',\n  contentType: 'text/plain;charset=UTF-8',\n  upsert: false,\n}\n\ntype FileBody =\n  | ArrayBuffer\n  | ArrayBufferView\n  | Blob\n  | Buffer\n  | File\n  | FormData\n  | NodeJS.ReadableStream\n  | ReadableStream<Uint8Array>\n  | URLSearchParams\n  | string\n\nexport default class StorageFileApi extends BaseApiClient<StorageError> {\n  protected bucketId: string | undefined\n\n  constructor(\n    url: string,\n    headers: { [key: string]: string } = {},\n    bucketId?: string,\n    fetch?: Fetch\n  ) {\n    super(url, headers, fetch, 'storage')\n    this.bucketId = bucketId\n  }\n\n  /**\n   * Uploads a file to an existing bucket or replaces an existing file at the specified path with a new one.\n   *\n   * @param method HTTP method.\n   * @param path The relative file path. Should be of the format `folder/subfolder/filename.png`. The bucket must already exist before attempting to upload.\n   * @param fileBody The body of the file to be stored in the bucket.\n   */\n  private async uploadOrUpdate(\n    method: 'POST' | 'PUT',\n    path: string,\n    fileBody: FileBody,\n    fileOptions?: FileOptions\n  ): Promise<\n    | {\n        data: { id: string; path: string; fullPath: string }\n        error: null\n      }\n    | {\n        data: null\n        error: StorageError\n      }\n  > {\n    return this.handleOperation(async () => {\n      let body\n      const options = { ...DEFAULT_FILE_OPTIONS, ...fileOptions }\n      let headers: Record<string, string> = {\n        ...this.headers,\n        ...(method === 'POST' && { 'x-upsert': String(options.upsert as boolean) }),\n      }\n\n      const metadata = options.metadata\n\n      if (\n        (typeof Blob !== 'undefined' && fileBody instanceof Blob) ||\n        (typeof FormData !== 'undefined' && fileBody instanceof FormData)\n      ) {\n        body = this.prepareUploadFormData(fileBody, options)\n      } else {\n        body = fileBody\n        headers['cache-control'] = `max-age=${options.cacheControl}`\n        headers['content-type'] = options.contentType as string\n\n        if (options.contentEncoding) {\n          headers['content-encoding'] = options.contentEncoding\n        }\n\n        if (metadata) {\n          headers['x-metadata'] = this.toBase64(this.encodeMetadata(metadata))\n        }\n\n        // Node.js streams require duplex option for fetch in Node 20+\n        // Check for both web ReadableStream and Node.js streams\n        const isStream =\n          (typeof ReadableStream !== 'undefined' && body instanceof ReadableStream) ||\n          (body && typeof body === 'object' && 'pipe' in body && typeof body.pipe === 'function')\n\n        if (isStream && !options.duplex) {\n          options.duplex = 'half'\n        }\n      }\n\n      if (fileOptions?.headers) {\n        for (const [key, value] of Object.entries(fileOptions.headers)) {\n          headers = setHeader(headers, key, value)\n        }\n      }\n\n      const cleanPath = this._removeEmptyFolders(path)\n      const _path = this._getFinalPath(cleanPath)\n      const data = await (method == 'PUT' ? put : post)(\n        this.fetch,\n        `${this.url}/object/${_path}`,\n        body as object,\n        { headers, ...(options?.duplex ? { duplex: options.duplex } : {}) }\n      )\n\n      return { path: cleanPath, id: data.Id, fullPath: data.Key }\n    })\n  }\n\n  /**\n   * Uploads a file to an existing bucket.\n   *\n   * @category Storage\n   * @subcategory File Buckets\n   * @param path The file path, including the file name. Should be of the format `folder/subfolder/filename.png`. The bucket must already exist before attempting to upload.\n   * @param fileBody The body of the file to be stored in the bucket.\n   * @param fileOptions Optional file upload options including cacheControl, contentType, contentEncoding, upsert, and metadata.\n   * @returns Promise with response containing file path, id, and fullPath or error\n   *\n   * @example Upload file\n   * ```js\n   * const avatarFile = event.target.files[0]\n   * const { data, error } = await supabase\n   *   .storage\n   *   .from('avatars')\n   *   .upload('public/avatar1.png', avatarFile, {\n   *     cacheControl: '3600',\n   *     upsert: false\n   *   })\n   * ```\n   *\n   * Response:\n   * ```json\n   * {\n   *   \"data\": {\n   *     \"path\": \"public/avatar1.png\",\n   *     \"fullPath\": \"avatars/public/avatar1.png\"\n   *   },\n   *   \"error\": null\n   * }\n   * ```\n   *\n   * @example Upload file using `ArrayBuffer` from base64 file data\n   * ```js\n   * import { decode } from 'base64-arraybuffer'\n   *\n   * const { data, error } = await supabase\n   *   .storage\n   *   .from('avatars')\n   *   .upload('public/avatar1.png', decode('base64FileData'), {\n   *     contentType: 'image/png'\n   *   })\n   * ```\n   *\n   * @example Handling errors\n   * ```js\n   * const { data, error } = await supabase\n   *   .storage\n   *   .from('avatars')\n   *   .upload('public/avatar1.png', avatarFile)\n   *\n   * if (error) {\n   *   // Log the full error so fields like `statusCode` and `error` (the\n   *   // Storage error name, e.g. \"Duplicate\") aren't hidden behind `error.message`.\n   *   console.error(error)\n   *   return\n   * }\n   * ```\n   *\n   * @remarks\n   * - RLS policy permissions required:\n   *   - `buckets` table permissions: none\n   *   - `objects` table permissions: only `insert` when you are uploading new files and `select`, `insert` and `update` when you are upserting files\n   * - Refer to the [Storage guide](/docs/guides/storage/security/access-control) on how access control works\n   * - For React Native, using either `Blob`, `File` or `FormData` does not work as intended. Upload file using `ArrayBuffer` from base64 file data instead, see example below.\n   */\n  async upload(\n    path: string,\n    fileBody: FileBody,\n    fileOptions?: FileOptions\n  ): Promise<\n    | {\n        data: { id: string; path: string; fullPath: string }\n        error: null\n      }\n    | {\n        data: null\n        error: StorageError\n      }\n  > {\n    return this.uploadOrUpdate('POST', path, fileBody, fileOptions)\n  }\n\n  /**\n   * Upload a file with a token generated from `createSignedUploadUrl`.\n   *\n   * @category Storage\n   * @subcategory File Buckets\n   * @param path The file path, including the file name. Should be of the format `folder/subfolder/filename.png`. The bucket must already exist before attempting to upload.\n   * @param token The token generated from `createSignedUploadUrl`\n   * @param fileBody The body of the file to be stored in the bucket.\n   * @param fileOptions HTTP headers (cacheControl, contentType, contentEncoding, etc.).\n   * **Note:** The `upsert` option has no effect here. To enable upsert behavior,\n   * pass `{ upsert: true }` when calling `createSignedUploadUrl()` instead.\n   * @returns Promise with response containing file path and fullPath or error\n   *\n   * @example Upload to a signed URL\n   * ```js\n   * const { data, error } = await supabase\n   *   .storage\n   *   .from('avatars')\n   *   .uploadToSignedUrl('folder/cat.jpg', 'token-from-createSignedUploadUrl', file)\n   * ```\n   *\n   * Response:\n   * ```json\n   * {\n   *   \"data\": {\n   *     \"path\": \"folder/cat.jpg\",\n   *     \"fullPath\": \"avatars/folder/cat.jpg\"\n   *   },\n   *   \"error\": null\n   * }\n   * ```\n   *\n   * @remarks\n   * - RLS policy permissions required:\n   *   - `buckets` table permissions: none\n   *   - `objects` table permissions: none\n   * - Refer to the [Storage guide](/docs/guides/storage/security/access-control) on how access control works\n   */\n  async uploadToSignedUrl(\n    path: string,\n    token: string,\n    fileBody: FileBody,\n    fileOptions?: FileOptions\n  ) {\n    const cleanPath = this._removeEmptyFolders(path)\n    const _path = this._getFinalPath(cleanPath)\n\n    const url = new URL(this.url + `/object/upload/sign/${_path}`)\n    url.searchParams.set('token', token)\n\n    return this.handleOperation(async () => {\n      let body\n      const options = { ...DEFAULT_FILE_OPTIONS, ...fileOptions }\n      let headers: Record<string, string> = {\n        ...this.headers,\n        ...{ 'x-upsert': String(options.upsert as boolean) },\n      }\n\n      const metadata = options.metadata\n\n      if (\n        (typeof Blob !== 'undefined' && fileBody instanceof Blob) ||\n        (typeof FormData !== 'undefined' && fileBody instanceof FormData)\n      ) {\n        body = this.prepareUploadFormData(fileBody, options)\n      } else {\n        body = fileBody\n        headers['cache-control'] = `max-age=${options.cacheControl}`\n        headers['content-type'] = options.contentType as string\n        if (options.contentEncoding) {\n          headers['content-encoding'] = options.contentEncoding\n        }\n\n        if (metadata) {\n          headers['x-metadata'] = this.toBase64(this.encodeMetadata(metadata))\n        }\n\n        const isStream =\n          (typeof ReadableStream !== 'undefined' && body instanceof ReadableStream) ||\n          (body && typeof body === 'object' && 'pipe' in body && typeof body.pipe === 'function')\n\n        if (isStream && !options.duplex) {\n          options.duplex = 'half'\n        }\n      }\n\n      if (fileOptions?.headers) {\n        for (const [key, value] of Object.entries(fileOptions.headers)) {\n          headers = setHeader(headers, key, value)\n        }\n      }\n\n      const data = await put(this.fetch, url.toString(), body as object, {\n        headers,\n        ...(options?.duplex ? { duplex: options.duplex } : {}),\n      })\n\n      return { path: cleanPath, fullPath: data.Key }\n    })\n  }\n\n  /**\n   * Creates a signed upload URL.\n   * Signed upload URLs can be used to upload files to the bucket without further authentication.\n   * They are valid for 2 hours.\n   *\n   * @category Storage\n   * @subcategory File Buckets\n   * @param path The file path, including the current file name. For example `folder/image.png`.\n   * @param options.upsert If set to true, allows the file to be overwritten if it already exists.\n   * @returns Promise with response containing signed upload URL, token, and path or error\n   *\n   * @example Create Signed Upload URL\n   * ```js\n   * const { data, error } = await supabase\n   *   .storage\n   *   .from('avatars')\n   *   .createSignedUploadUrl('folder/cat.jpg')\n   * ```\n   *\n   * Response:\n   * ```json\n   * {\n   *   \"data\": {\n   *     \"signedUrl\": \"https://example.supabase.co/storage/v1/object/upload/sign/avatars/folder/cat.jpg?token=<TOKEN>\",\n   *     \"path\": \"folder/cat.jpg\",\n   *     \"token\": \"<TOKEN>\"\n   *   },\n   *   \"error\": null\n   * }\n   * ```\n   *\n   * @remarks\n   * - RLS policy permissions required:\n   *   - `buckets` table permissions: none\n   *   - `objects` table permissions: `insert`\n   * - Refer to the [Storage guide](/docs/guides/storage/security/access-control) on how access control works\n   */\n  async createSignedUploadUrl(\n    path: string,\n    options?: { upsert: boolean }\n  ): Promise<\n    | {\n        data: { signedUrl: string; token: string; path: string }\n        error: null\n      }\n    | {\n        data: null\n        error: StorageError\n      }\n  > {\n    return this.handleOperation(async () => {\n      let _path = this._getFinalPath(path)\n\n      const headers = { ...this.headers }\n\n      if (options?.upsert) {\n        headers['x-upsert'] = 'true'\n      }\n\n      const data = await post(\n        this.fetch,\n        `${this.url}/object/upload/sign/${_path}`,\n        {},\n        { headers }\n      )\n\n      const url = new URL(this.url + data.url)\n\n      const token = url.searchParams.get('token')\n\n      if (!token) {\n        throw new StorageError('No token returned by API')\n      }\n\n      return { signedUrl: url.toString(), path, token }\n    })\n  }\n\n  /**\n   * Replaces an existing file at the specified path with a new one.\n   *\n   * @category Storage\n   * @subcategory File Buckets\n   * @param path The relative file path. Should be of the format `folder/subfolder/filename.png`. The bucket must already exist before attempting to update.\n   * @param fileBody The body of the file to be stored in the bucket.\n   * @param fileOptions Optional file upload options including cacheControl, contentType, contentEncoding, and metadata.\n   * **Note:** The `upsert` option has no effect here. `update()` always replaces the\n   * file at the given path, so the `x-upsert` header is not sent. To control upsert\n   * behavior, use `upload()` instead.\n   * @returns Promise with response containing file path, id, and fullPath or error\n   *\n   * @example Update file\n   * ```js\n   * const avatarFile = event.target.files[0]\n   * const { data, error } = await supabase\n   *   .storage\n   *   .from('avatars')\n   *   .update('public/avatar1.png', avatarFile, {\n   *     cacheControl: '3600'\n   *   })\n   * ```\n   *\n   * Response:\n   * ```json\n   * {\n   *   \"data\": {\n   *     \"path\": \"public/avatar1.png\",\n   *     \"fullPath\": \"avatars/public/avatar1.png\"\n   *   },\n   *   \"error\": null\n   * }\n   * ```\n   *\n   * @example Update file using `ArrayBuffer` from base64 file data\n   * ```js\n   * import {decode} from 'base64-arraybuffer'\n   *\n   * const { data, error } = await supabase\n   *   .storage\n   *   .from('avatars')\n   *   .update('public/avatar1.png', decode('base64FileData'), {\n   *     contentType: 'image/png'\n   *   })\n   * ```\n   *\n   * @remarks\n   * - RLS policy permissions required:\n   *   - `buckets` table permissions: none\n   *   - `objects` table permissions: `update` and `select`\n   * - `update()` always replaces the file at the given path regardless of the `upsert` option.\n   * - Refer to the [Storage guide](/docs/guides/storage/security/access-control) on how access control works\n   * - For React Native, using either `Blob`, `File` or `FormData` does not work as intended. Update file using `ArrayBuffer` from base64 file data instead, see example below.\n   */\n  async update(\n    path: string,\n    fileBody:\n      | ArrayBuffer\n      | ArrayBufferView\n      | Blob\n      | Buffer\n      | File\n      | FormData\n      | NodeJS.ReadableStream\n      | ReadableStream<Uint8Array>\n      | URLSearchParams\n      | string,\n    fileOptions?: FileOptions\n  ): Promise<\n    | {\n        data: { id: string; path: string; fullPath: string }\n        error: null\n      }\n    | {\n        data: null\n        error: StorageError\n      }\n  > {\n    return this.uploadOrUpdate('PUT', path, fileBody, fileOptions)\n  }\n\n  /**\n   * Moves an existing file to a new path in the same bucket.\n   *\n   * @category Storage\n   * @subcategory File Buckets\n   * @param fromPath The original file path, including the current file name. For example `folder/image.png`.\n   * @param toPath The new file path, including the new file name. For example `folder/image-new.png`.\n   * @param options The destination options.\n   * @param options.sourceVersionId The version id of the source object to move.\n   * @returns Promise with response containing success message or error\n   *\n   * @example Move file\n   * ```js\n   * const { data, error } = await supabase\n   *   .storage\n   *   .from('avatars')\n   *   .move('public/avatar1.png', 'private/avatar2.png')\n   * ```\n   *\n   * Response:\n   * ```json\n   * {\n   *   \"data\": {\n   *     \"message\": \"Successfully moved\"\n   *   },\n   *   \"error\": null\n   * }\n   * ```\n   *\n   * @remarks\n   * - RLS policy permissions required:\n   *   - `buckets` table permissions: none\n   *   - `objects` table permissions: `update` and `select`\n   * - Refer to the [Storage guide](/docs/guides/storage/security/access-control) on how access control works\n   */\n  async move(\n    fromPath: string,\n    toPath: string,\n    options?: DestinationOptions\n  ): Promise<\n    | {\n        data: { message: string }\n        error: null\n      }\n    | {\n        data: null\n        error: StorageError\n      }\n  > {\n    return this.handleOperation(async () => {\n      return await post(\n        this.fetch,\n        `${this.url}/object/move`,\n        {\n          bucketId: this.bucketId,\n          sourceKey: fromPath,\n          destinationKey: toPath,\n          destinationBucket: options?.destinationBucket,\n          sourceVersionId: options?.sourceVersionId,\n        },\n        { headers: this.headers }\n      )\n    })\n  }\n\n  /**\n   * Copies an existing file to a new path in the same bucket.\n   *\n   * @category Storage\n   * @subcategory File Buckets\n   * @param fromPath The original file path, including the current file name. For example `folder/image.png`.\n   * @param toPath The new file path, including the new file name. For example `folder/image-copy.png`.\n   * @param options The destination and metadata options.\n   * @param options.sourceVersionId The version id of the source object to copy.\n   * @param options.copyMetadata Whether to copy the source metadata. Defaults to true. Set to false to apply metadata overrides; custom user metadata is not copied when false.\n   * @param options.metadata File metadata overrides, applied only when copyMetadata is false. Unspecified fields retain their source values.\n   * @returns Promise with response containing copied file path or error\n   *\n   * @example Copy file\n   * ```js\n   * const { data, error } = await supabase\n   *   .storage\n   *   .from('avatars')\n   *   .copy('public/avatar1.png', 'private/avatar2.png')\n   * ```\n   *\n   * Response:\n   * ```json\n   * {\n   *   \"data\": {\n   *     \"path\": \"avatars/private/avatar2.png\"\n   *   },\n   *   \"error\": null\n   * }\n   * ```\n   *\n   * @example Copy file with content encoding\n   * ```js\n   * const { data, error } = await supabase\n   *   .storage\n   *   .from('documents')\n   *   .copy('source.txt.gz', 'copy.txt.gz', {\n   *     copyMetadata: false,\n   *     metadata: { contentEncoding: 'gzip' },\n   *   })\n   * ```\n   * The source must already contain gzip-encoded bytes. Copying changes metadata only.\n   *\n   * @remarks\n   * - RLS policy permissions required:\n   *   - `buckets` table permissions: none\n   *   - `objects` table permissions: `insert` and `select`\n   * - Refer to the [Storage guide](/docs/guides/storage/security/access-control) on how access control works\n   */\n  async copy(\n    fromPath: string,\n    toPath: string,\n    options?: CopyOptions | DestinationOptions\n  ): Promise<\n    | {\n        data: { path: string }\n        error: null\n      }\n    | {\n        data: null\n        error: StorageError\n      }\n  > {\n    return this.handleOperation(async () => {\n      const copyOptions = options as CopyOptions | undefined\n      const data = await post(\n        this.fetch,\n        `${this.url}/object/copy`,\n        {\n          bucketId: this.bucketId,\n          sourceKey: fromPath,\n          destinationKey: toPath,\n          destinationBucket: options?.destinationBucket,\n          sourceVersionId: options?.sourceVersionId,\n          copyMetadata:\n            typeof copyOptions?.copyMetadata === 'boolean' ? copyOptions.copyMetadata : undefined,\n          metadata: copyOptions?.copyMetadata === false ? copyOptions.metadata : undefined,\n        },\n        { headers: this.headers }\n      )\n      return { path: data.Key }\n    })\n  }\n\n  /**\n   * Creates a signed URL. Use a signed URL to share a file for a fixed amount of time.\n   *\n   * @category Storage\n   * @subcategory File Buckets\n   * @param path The file path, including the current file name. For example `folder/image.png`.\n   * @param expiresIn The number of seconds until the signed URL expires. For example, `60` for a URL which is valid for one minute.\n   * @param options.download triggers the file as a download if set to true. Set this parameter as the name of the file if you want to trigger the download with a different filename.\n   * @param options.transform Transform the asset before serving it to the client.\n   * @param options.cacheNonce Append a cache nonce parameter to the URL to invalidate the cache.\n   * @param options.versionId Create a signed URL for a specific object version rather than the current one.\n   * @returns Promise with response containing signed URL or error\n   *\n   * @example Create Signed URL\n   * ```js\n   * const { data, error } = await supabase\n   *   .storage\n   *   .from('avatars')\n   *   .createSignedUrl('folder/avatar1.png', 60)\n   * ```\n   *\n   * Response:\n   * ```json\n   * {\n   *   \"data\": {\n   *     \"signedUrl\": \"https://example.supabase.co/storage/v1/object/sign/avatars/folder/avatar1.png?token=<TOKEN>\"\n   *   },\n   *   \"error\": null\n   * }\n   * ```\n   *\n   * @example Create a signed URL for an asset with transformations\n   * ```js\n   * const { data } = await supabase\n   *   .storage\n   *   .from('avatars')\n   *   .createSignedUrl('folder/avatar1.png', 60, {\n   *     transform: {\n   *       width: 100,\n   *       height: 100,\n   *     }\n   *   })\n   * ```\n   *\n   * @example Create a signed URL which triggers the download of the asset\n   * ```js\n   * const { data } = await supabase\n   *   .storage\n   *   .from('avatars')\n   *   .createSignedUrl('folder/avatar1.png', 60, {\n   *     download: true,\n   *   })\n   * ```\n   *\n   * @remarks\n   * - RLS policy permissions required:\n   *   - `buckets` table permissions: none\n   *   - `objects` table permissions: `select`\n   * - Refer to the [Storage guide](/docs/guides/storage/security/access-control) on how access control works\n   */\n  async createSignedUrl(\n    path: string,\n    expiresIn: number,\n    options?: {\n      download?: string | boolean\n      transform?: TransformOptions\n      cacheNonce?: string\n      versionId?: string\n    }\n  ): Promise<\n    | {\n        data: { signedUrl: string }\n        error: null\n      }\n    | {\n        data: null\n        error: StorageError\n      }\n  > {\n    return this.handleOperation(async () => {\n      let _path = this._getFinalPath(path)\n\n      const hasTransform =\n        typeof options?.transform === 'object' &&\n        options.transform !== null &&\n        Object.keys(options.transform).length > 0\n\n      let data = await post(\n        this.fetch,\n        `${this.url}/object/sign/${_path}`,\n        {\n          expiresIn,\n          ...(hasTransform ? { transform: options!.transform } : {}),\n          ...(options?.versionId != null ? { versionId: options.versionId } : {}),\n        },\n        { headers: this.headers }\n      )\n\n      const query = new URLSearchParams()\n      if (options?.download)\n        query.set('download', options.download === true ? '' : options.download)\n      if (options?.cacheNonce != null) query.set('cacheNonce', String(options.cacheNonce))\n      const queryString = query.toString()\n\n      // `data.signedURL` contains a `token` query parameter, so append extra params with `&`\n      // only when we actually have something to add.\n      const signedUrl = encodeURI(\n        `${this.url}${data.signedURL}${queryString ? `&${queryString}` : ''}`\n      )\n\n      return { signedUrl }\n    })\n  }\n\n  /**\n   * Creates multiple signed URLs. Use a signed URL to share a file for a fixed amount of time.\n   *\n   * @category Storage\n   * @subcategory File Buckets\n   * @param paths The file paths to be downloaded, including the current file names. For example `['folder/image.png', 'folder2/image2.png']`.\n   * @param expiresIn The number of seconds until the signed URLs expire. For example, `60` for URLs which are valid for one minute.\n   * @param options.download triggers the file as a download if set to true. Set this parameter as the name of the file if you want to trigger the download with a different filename.\n   * @param options.cacheNonce Append a cache nonce parameter to the URL to invalidate the cache.\n   * @returns Promise with response containing array of objects with signedUrl, path, and error or error\n   *\n   * @example Create Signed URLs\n   * ```js\n   * const { data, error } = await supabase\n   *   .storage\n   *   .from('avatars')\n   *   .createSignedUrls(['folder/avatar1.png', 'folder/avatar2.png'], 60)\n   * ```\n   *\n   * Response:\n   * ```json\n   * {\n   *   \"data\": [\n   *     {\n   *       \"error\": null,\n   *       \"path\": \"folder/avatar1.png\",\n   *       \"signedURL\": \"/object/sign/avatars/folder/avatar1.png?token=<TOKEN>\",\n   *       \"signedUrl\": \"https://example.supabase.co/storage/v1/object/sign/avatars/folder/avatar1.png?token=<TOKEN>\"\n   *     },\n   *     {\n   *       \"error\": null,\n   *       \"path\": \"folder/avatar2.png\",\n   *       \"signedURL\": \"/object/sign/avatars/folder/avatar2.png?token=<TOKEN>\",\n   *       \"signedUrl\": \"https://example.supabase.co/storage/v1/object/sign/avatars/folder/avatar2.png?token=<TOKEN>\"\n   *     }\n   *   ],\n   *   \"error\": null\n   * }\n   * ```\n   *\n   * @remarks\n   * - RLS policy permissions required:\n   *   - `buckets` table permissions: none\n   *   - `objects` table permissions: `select`\n   * - Refer to the [Storage guide](/docs/guides/storage/security/access-control) on how access control works\n   */\n  async createSignedUrls(\n    paths: string[],\n    expiresIn: number,\n    options?: { download?: string | boolean; cacheNonce?: string }\n  ): Promise<\n    | {\n        data: {\n          error: string | null\n          path: string | null\n          signedURL: string | null\n          signedUrl: string | null\n        }[]\n        error: null\n      }\n    | {\n        data: null\n        error: StorageError\n      }\n  > {\n    return this.handleOperation(async () => {\n      const data = await post(\n        this.fetch,\n        `${this.url}/object/sign/${this.bucketId}`,\n        { expiresIn, paths },\n        { headers: this.headers }\n      )\n\n      const query = new URLSearchParams()\n\n      if (options?.download)\n        query.set('download', options.download === true ? '' : options.download)\n      if (options?.cacheNonce != null) query.set('cacheNonce', String(options.cacheNonce))\n\n      const queryString = query.toString()\n\n      return data.map(\n        (datum: { error: string | null; path: string | null; signedURL: string | null }) => ({\n          ...datum,\n          signedUrl: datum.signedURL\n            ? encodeURI(`${this.url}${datum.signedURL}${queryString ? `&${queryString}` : ''}`)\n            : null,\n        })\n      )\n    })\n  }\n\n  /**\n   * Downloads a file from a private bucket. For public buckets, make a request to the URL returned from `getPublicUrl` instead.\n   *\n   * @category Storage\n   * @subcategory File Buckets\n   * @param path The full path and file name of the file to be downloaded. For example `folder/image.png`.\n   * @param options Optional settings: `transform` to transform the asset before serving it to the client, `cacheNonce` to append a cache nonce parameter to the URL to invalidate the cache, and `versionId` to download a specific object version.\n   * @param parameters Additional fetch parameters like signal for cancellation. Supports standard fetch options including cache control.\n   * @returns BlobDownloadBuilder instance for downloading the file\n   *\n   * @example Download file\n   * ```js\n   * const { data, error } = await supabase\n   *   .storage\n   *   .from('avatars')\n   *   .download('folder/avatar1.png')\n   * ```\n   *\n   * Response:\n   * ```json\n   * {\n   *   \"data\": <BLOB>,\n   *   \"error\": null\n   * }\n   * ```\n   *\n   * @example Download file with transformations\n   * ```js\n   * const { data, error } = await supabase\n   *   .storage\n   *   .from('avatars')\n   *   .download('folder/avatar1.png', {\n   *     transform: {\n   *       width: 100,\n   *       height: 100,\n   *       quality: 80\n   *     }\n   *   })\n   * ```\n   *\n   * @example Download with cache control (useful in Edge Functions)\n   * ```js\n   * const { data, error } = await supabase\n   *   .storage\n   *   .from('avatars')\n   *   .download('folder/avatar1.png', {}, { cache: 'no-store' })\n   * ```\n   *\n   * @example Download with abort signal\n   * ```js\n   * const controller = new AbortController()\n   * setTimeout(() => controller.abort(), 5000)\n   *\n   * const { data, error } = await supabase\n   *   .storage\n   *   .from('avatars')\n   *   .download('folder/avatar1.png', {}, { signal: controller.signal })\n   * ```\n   *\n   * @remarks\n   * - RLS policy permissions required:\n   *   - `buckets` table permissions: none\n   *   - `objects` table permissions: `select`\n   * - Refer to the [Storage guide](/docs/guides/storage/security/access-control) on how access control works\n   */\n  download<\n    Options extends { transform?: TransformOptions; cacheNonce?: string; versionId?: string },\n  >(path: string, options?: Options, parameters?: FetchParameters): BlobDownloadBuilder {\n    const wantsTransformation =\n      typeof options?.transform === 'object' &&\n      options.transform !== null &&\n      Object.keys(options.transform).length > 0\n    const renderPath = wantsTransformation ? 'render/image/authenticated' : 'object'\n\n    const query = new URLSearchParams()\n    if (options?.transform) this.applyTransformOptsToQuery(query, options.transform)\n    if (options?.cacheNonce != null) query.set('cacheNonce', String(options.cacheNonce))\n    if (options?.versionId != null) query.set('versionId', String(options.versionId))\n    const queryString = query.toString()\n\n    const _path = this._getFinalPath(path)\n    const downloadFn = () =>\n      get(\n        this.fetch,\n        `${this.url}/${renderPath}/${_path}${queryString ? `?${queryString}` : ''}`,\n        {\n          headers: this.headers,\n          noResolveJson: true,\n        },\n        parameters\n      )\n    return new BlobDownloadBuilder(downloadFn, this.shouldThrowOnError)\n  }\n\n  /**\n   * Retrieves the details of an existing file.\n   *\n   * Returns detailed file metadata including size, content type, and timestamps.\n   * Note: The API returns `last_modified` field, not `updated_at`.\n   *\n   * @category Storage\n   * @subcategory File Buckets\n   * @param path The file path, including the file name. For example `folder/image.png`.\n   * @param options Optional settings, including `versionId` to retrieve a specific object version.\n   * @returns Promise with response containing file metadata or error\n   *\n   * @example Get file info\n   * ```js\n   * const { data, error } = await supabase\n   *   .storage\n   *   .from('avatars')\n   *   .info('folder/avatar1.png')\n   *\n   * if (data) {\n   *   console.log('Last modified:', data.lastModified)\n   *   console.log('Size:', data.size)\n   * }\n   * ```\n   */\n  async info(\n    path: string,\n    options?: { versionId?: string }\n  ): Promise<\n    | {\n        data: Camelize<FileObjectV2>\n        error: null\n      }\n    | {\n        data: null\n        error: StorageError\n      }\n  > {\n    const _path = this._getFinalPath(path)\n    const query = new URLSearchParams()\n    if (options?.versionId != null) query.set('versionId', String(options.versionId))\n    const queryString = query.toString()\n\n    return this.handleOperation(async () => {\n      const data = await get(\n        this.fetch,\n        `${this.url}/object/info/${_path}${queryString ? `?${queryString}` : ''}`,\n        {\n          headers: this.headers,\n        }\n      )\n\n      return recursiveToCamel(data) as Camelize<FileObjectV2>\n    })\n  }\n\n  /**\n   * Checks the existence of a file.\n   *\n   * @category Storage\n   * @subcategory File Buckets\n   * @param path The file path, including the file name. For example `folder/image.png`.\n   * @returns Promise with response containing boolean indicating file existence or error\n   *\n   * @example Check file existence\n   * ```js\n   * const { data, error } = await supabase\n   *   .storage\n   *   .from('avatars')\n   *   .exists('folder/avatar1.png')\n   * ```\n   */\n  async exists(path: string): Promise<\n    | {\n        data: boolean\n        error: null\n      }\n    | {\n        data: boolean\n        error: StorageError\n      }\n  > {\n    const _path = this._getFinalPath(path)\n\n    try {\n      await head(this.fetch, `${this.url}/object/${_path}`, {\n        headers: this.headers,\n      })\n\n      return { data: true, error: null }\n    } catch (error) {\n      if (this.shouldThrowOnError) {\n        throw error\n      }\n      if (isStorageError(error)) {\n        // HEAD requests produce StorageApiError (via handleError) or StorageUnknownError (legacy)\n        const status =\n          error instanceof StorageApiError\n            ? error.status\n            : error instanceof StorageUnknownError\n              ? (error.originalError as { status: number })?.status\n              : undefined\n\n        if (status !== undefined && [400, 404].includes(status)) {\n          return { data: false, error }\n        }\n      }\n\n      throw error\n    }\n  }\n\n  /**\n   * A simple convenience function to get the URL for an asset in a public bucket. If you do not want to use this function, you can construct the public URL by concatenating the bucket URL with the path to the asset.\n   * This function does not verify if the bucket is public. If a public URL is created for a bucket which is not public, you will not be able to download the asset.\n   *\n   * @category Storage\n   * @subcategory File Buckets\n   * @param path The path and name of the file to generate the public URL for. For example `folder/image.png`.\n   * @param options.download Triggers the file as a download if set to true. Set this parameter as the name of the file if you want to trigger the download with a different filename.\n   * @param options.transform Transform the asset before serving it to the client.\n   * @param options.cacheNonce Append a cache nonce parameter to the URL to invalidate the cache.\n   * @param options.versionId Return the URL for a specific object version rather than the current one.\n   * @returns Object with public URL\n   *\n   * @example Returns the URL for an asset in a public bucket\n   * ```js\n   * const { data } = supabase\n   *   .storage\n   *   .from('public-bucket')\n   *   .getPublicUrl('folder/avatar1.png')\n   * ```\n   *\n   * Response:\n   * ```json\n   * {\n   *   \"data\": {\n   *     \"publicUrl\": \"https://example.supabase.co/storage/v1/object/public/public-bucket/folder/avatar1.png\"\n   *   }\n   * }\n   * ```\n   *\n   * @example Returns the URL for an asset in a public bucket with transformations\n   * ```js\n   * const { data } = supabase\n   *   .storage\n   *   .from('public-bucket')\n   *   .getPublicUrl('folder/avatar1.png', {\n   *     transform: {\n   *       width: 100,\n   *       height: 100,\n   *     }\n   *   })\n   * ```\n   *\n   * @example Returns the URL which triggers the download of an asset in a public bucket\n   * ```js\n   * const { data } = supabase\n   *   .storage\n   *   .from('public-bucket')\n   *   .getPublicUrl('folder/avatar1.png', {\n   *     download: true,\n   *   })\n   * ```\n   *\n   * @remarks\n   * - The bucket needs to be set to public, either via [updateBucket()](/docs/reference/javascript/storage-updatebucket) or by going to Storage on [supabase.com/dashboard](https://supabase.com/dashboard), clicking the overflow menu on a bucket and choosing \"Make public\"\n   * - RLS policy permissions required:\n   *   - `buckets` table permissions: none\n   *   - `objects` table permissions: none\n   * - Refer to the [Storage guide](/docs/guides/storage/security/access-control) on how access control works\n   */\n  getPublicUrl(\n    path: string,\n    options?: {\n      download?: string | boolean\n      transform?: TransformOptions\n      cacheNonce?: string\n      versionId?: string\n    }\n  ): { data: { publicUrl: string } } {\n    const _path = this._getFinalPath(path)\n\n    const query = new URLSearchParams()\n    if (options?.download) query.set('download', options.download === true ? '' : options.download)\n    if (options?.transform) this.applyTransformOptsToQuery(query, options.transform)\n    if (options?.cacheNonce != null) query.set('cacheNonce', String(options.cacheNonce))\n    if (options?.versionId != null) query.set('versionId', String(options.versionId))\n    const queryString = query.toString()\n\n    const wantsTransformation =\n      typeof options?.transform === 'object' &&\n      options.transform !== null &&\n      Object.keys(options.transform).length > 0\n    const renderPath = wantsTransformation ? 'render/image' : 'object'\n\n    return {\n      data: {\n        publicUrl:\n          encodeURI(`${this.url}/${renderPath}/public/${_path}`) +\n          (queryString ? `?${queryString}` : ''),\n      },\n    }\n  }\n\n  /**\n   * Deletes files within the same bucket\n   *\n   * Returns an array of FileObject entries for the deleted files. Note that deprecated\n   * fields like `bucket_id` may or may not be present in the response - do not rely on them.\n   *\n   * @category Storage\n   * @subcategory File Buckets\n   * @param paths An array of files to delete. Each entry is either a path (deletes whichever\n   * version is currently at that path, e.g. `'folder/image.png'`), or `{ path, versionId }` to\n   * delete an exact version current or archived (e.g. `{ path: 'folder/image.png', versionId: '...' }`).\n   * @returns Promise with response containing array of deleted file objects or error\n   *\n   * @example Delete file\n   * ```js\n   * const { data, error } = await supabase\n   *   .storage\n   *   .from('avatars')\n   *   .remove(['folder/avatar1.png'])\n   * ```\n   *\n   * Response:\n   * ```json\n   * {\n   *   \"data\": [],\n   *   \"error\": null\n   * }\n   * ```\n   *\n   * @example Delete a specific object version\n   * ```js\n   * const { data, error } = await supabase\n   *   .storage\n   *   .from('avatars')\n   *   .remove([{ path: 'folder/avatar1.png', versionId: 'noncurrent-version-id' }])\n   * ```\n   *\n   * @remarks\n   * - RLS policy permissions required:\n   *   - `buckets` table permissions: none\n   *   - `objects` table permissions: `delete` and `select`\n   * - Refer to the [Storage guide](/docs/guides/storage/security/access-control) on how access control works\n   */\n  async remove(paths: DeleteObjectEntry[]): Promise<\n    | {\n        data: FileObject[]\n        error: null\n      }\n    | {\n        data: null\n        error: StorageError\n      }\n  > {\n    return this.handleOperation(async () => {\n      return await remove(\n        this.fetch,\n        `${this.url}/object/${this.bucketId}`,\n        { prefixes: paths },\n        { headers: this.headers }\n      )\n    })\n  }\n\n  /**\n   * Purges the CDN cache for a single object in this bucket.\n   *\n   * Maps to `DELETE /cdn/{bucket}/{path}` on the Storage API. The server\n   * issues a CDN invalidation for the object and returns `{ message: 'success' }`.\n   *\n   * **Requires the `service_role` key.** The underlying endpoint enforces\n   * `service_role` JWT — calls made with the anon key or a user JWT will be\n   * rejected by the server.\n   *\n   * **Hosted CDN feature.** On self-hosted Supabase, the Storage service must\n   * have `CDN_PURGE_ENDPOINT_URL` configured and the `purgeCache` tenant\n   * feature enabled, otherwise the server returns an error.\n   *\n   * Operates on a single object path. There is no wildcard or recursion: pass\n   * the exact path of the object you want invalidated.\n   *\n   * @category Storage\n   * @subcategory File Buckets\n   * @param path The path (relative to the bucket) of the object to purge, e.g. `folder/avatar.png`.\n   * @param options Optional purge cache options.\n   * @param options.transformations If true, purges only transformations (resized/formatted variants), leaving the original cached file intact.\n   * @param parameters Optional fetch parameters such as an `AbortController` signal.\n   * @returns Promise with `{ data: { message }, error: null }` on success or `{ data: null, error }` on failure.\n   *\n   * @example Purge a single cached object\n   * ```js\n   * const { data, error } = await supabase\n   *   .storage\n   *   .from('avatars')\n   *   .purgeCache('folder/avatar1.png')\n   * ```\n   *\n   * @example Purge only transformations for a single object\n   * ```js\n   * const { data, error } = await supabase\n   *   .storage\n   *   .from('avatars')\n   *   .purgeCache('folder/avatar1.png', { transformations: true })\n   * ```\n   */\n  async purgeCache(\n    path: string,\n    options?: PurgeCacheOptions,\n    parameters?: FetchParameters\n  ): Promise<\n    | {\n        data: { message: string }\n        error: null\n      }\n    | {\n        data: null\n        error: StorageError\n      }\n  > {\n    return this.handleOperation(async () => {\n      const _path = encodeStoragePath(this._getFinalPath(path))\n      const query = new URLSearchParams()\n      if (options?.transformations) {\n        query.set('transformations', 'true')\n      }\n      const queryString = query.toString()\n\n      return await remove(\n        this.fetch,\n        `${this.url}/cdn/${_path}${queryString ? `?${queryString}` : ''}`,\n        {},\n        { headers: this.headers },\n        parameters\n      )\n    })\n  }\n\n  /**\n   * Get file metadata\n   * @param id the file id to retrieve metadata\n   */\n  // async getMetadata(\n  //   id: string\n  // ): Promise<\n  //   | {\n  //       data: Metadata\n  //       error: null\n  //     }\n  //   | {\n  //       data: null\n  //       error: StorageError\n  //     }\n  // > {\n  //   try {\n  //     const data = await get(this.fetch, `${this.url}/metadata/${id}`, { headers: this.headers })\n  //     return { data, error: null }\n  //   } catch (error) {\n  //     if (isStorageError(error)) {\n  //       return { data: null, error }\n  //     }\n\n  //     throw error\n  //   }\n  // }\n\n  /**\n   * Update file metadata\n   * @param id the file id to update metadata\n   * @param meta the new file metadata\n   */\n  // async updateMetadata(\n  //   id: string,\n  //   meta: Metadata\n  // ): Promise<\n  //   | {\n  //       data: Metadata\n  //       error: null\n  //     }\n  //   | {\n  //       data: null\n  //       error: StorageError\n  //     }\n  // > {\n  //   try {\n  //     const data = await post(\n  //       this.fetch,\n  //       `${this.url}/metadata/${id}`,\n  //       { ...meta },\n  //       { headers: this.headers }\n  //     )\n  //     return { data, error: null }\n  //   } catch (error) {\n  //     if (isStorageError(error)) {\n  //       return { data: null, error }\n  //     }\n\n  //     throw error\n  //   }\n  // }\n\n  /**\n   * Lists all the files and folders within a path of the bucket.\n   *\n   * **Important:** For folder entries, fields like `id`, `updated_at`, `created_at`,\n   * `last_accessed_at`, and `metadata` will be `null`. Only files have these fields populated.\n   * Additionally, deprecated fields like `bucket_id`, `owner`, and `buckets` are NOT returned\n   * by this method.\n   *\n   * @category Storage\n   * @subcategory File Buckets\n   * @param path The folder path.\n   * @param options Search options including limit (defaults to 100), offset, sortBy, and search\n   * @param parameters Optional fetch parameters including signal for cancellation\n   * @returns Promise with response containing array of files/folders or error\n   *\n   * @example List files in a bucket\n   * ```js\n   * const { data, error } = await supabase\n   *   .storage\n   *   .from('avatars')\n   *   .list('folder', {\n   *     limit: 100,\n   *     offset: 0,\n   *     sortBy: { column: 'name', order: 'asc' },\n   *   })\n   *\n   * // Handle files vs folders\n   * data?.forEach(item => {\n   *   if (item.id !== null) {\n   *     // It's a file\n   *     console.log('File:', item.name, 'Size:', item.metadata?.size)\n   *   } else {\n   *     // It's a folder\n   *     console.log('Folder:', item.name)\n   *   }\n   * })\n   * ```\n   *\n   * Response:\n   * ```json\n   * {\n   *   \"data\": [\n   *     {\n   *       \"name\": \"avatar1.png\",\n   *       \"id\": \"e668cf7f-821b-4a2f-9dce-7dfa5dd1cfd2\",\n   *       \"updated_at\": \"2024-05-22T23:06:05.580Z\",\n   *       \"created_at\": \"2024-05-22T23:04:34.443Z\",\n   *       \"last_accessed_at\": \"2024-05-22T23:04:34.443Z\",\n   *       \"metadata\": {\n   *         \"eTag\": \"\\\"c5e8c553235d9af30ef4f6e280790b92\\\"\",\n   *         \"size\": 32175,\n   *         \"mimetype\": \"image/png\",\n   *         \"cacheControl\": \"max-age=3600\",\n   *         \"lastModified\": \"2024-05-22T23:06:05.574Z\",\n   *         \"contentLength\": 32175,\n   *         \"httpStatusCode\": 200\n   *       }\n   *     }\n   *   ],\n   *   \"error\": null\n   * }\n   * ```\n   *\n   * @example Search files in a bucket\n   * ```js\n   * const { data, error } = await supabase\n   *   .storage\n   *   .from('avatars')\n   *   .list('folder', {\n   *     limit: 100,\n   *     offset: 0,\n   *     sortBy: { column: 'name', order: 'asc' },\n   *     search: 'jon'\n   *   })\n   * ```\n   *\n   * @remarks\n   * - RLS policy permissions required:\n   *   - `buckets` table permissions: none\n   *   - `objects` table permissions: `select`\n   * - Refer to the [Storage guide](/docs/guides/storage/security/access-control) on how access control works\n   */\n  async list(\n    path?: string,\n    options?: SearchOptions,\n    parameters?: FetchParameters\n  ): Promise<\n    | {\n        data: FileObject[]\n        error: null\n      }\n    | {\n        data: null\n        error: StorageError\n      }\n  > {\n    return this.handleOperation(async () => {\n      // Deep-merge `sortBy` so overriding only one of its keys (e.g. `column`) keeps the\n      // default for the other (e.g. `order`), matching how the top-level defaults behave.\n      const sortBy = options?.sortBy\n        ? { ...DEFAULT_SEARCH_OPTIONS.sortBy, ...options.sortBy }\n        : DEFAULT_SEARCH_OPTIONS.sortBy\n      const body = { ...DEFAULT_SEARCH_OPTIONS, ...options, sortBy, prefix: path || '' }\n      return await post(\n        this.fetch,\n        `${this.url}/object/list/${this.bucketId}`,\n        body,\n        { headers: this.headers },\n        parameters\n      )\n    })\n  }\n\n  /**\n   * Lists all the files and folders within a bucket using the V2 API with pagination support.\n   *\n   * **Important:** Folder entries in the `folders` array only contain `name` and optionally `key` —\n   * they have no `id`, timestamps, or `metadata` fields. Full file metadata is only available\n   * on entries in the `objects` array.\n   *\n   * @experimental this method signature might change in the future\n   *\n   * @category Storage\n   * @subcategory File Buckets\n   * @param options Search options including prefix, cursor for pagination, limit, with_delimiter\n   * @param parameters Optional fetch parameters including signal for cancellation\n   * @returns Promise with response containing folders/objects arrays with pagination info or error\n   *\n   * @example List files with pagination\n   * ```js\n   * const { data, error } = await supabase\n   *   .storage\n   *   .from('avatars')\n   *   .listV2({\n   *     prefix: 'folder/',\n   *     limit: 100,\n   *   })\n   *\n   * // Handle pagination\n   * if (data?.hasNext) {\n   *   const nextPage = await supabase\n   *     .storage\n   *     .from('avatars')\n   *     .listV2({\n   *       prefix: 'folder/',\n   *       cursor: data.nextCursor,\n   *     })\n   * }\n   *\n   * // Handle files vs folders\n   * data?.objects.forEach(file => {\n   *   if (file.id !== null) {\n   *     console.log('File:', file.name, 'Size:', file.metadata?.size)\n   *   }\n   * })\n   * data?.folders.forEach(folder => {\n   *   console.log('Folder:', folder.name)\n   * })\n   * ```\n   */\n  async listV2(\n    options?: SearchV2Options,\n    parameters?: FetchParameters\n  ): Promise<\n    | {\n        data: SearchV2Result\n        error: null\n      }\n    | {\n        data: null\n        error: StorageError\n      }\n  > {\n    return this.handleOperation(async () => {\n      const body = { ...options }\n      return await post(\n        this.fetch,\n        `${this.url}/object/list-v2/${this.bucketId}`,\n        body,\n        { headers: this.headers },\n        parameters\n      )\n    })\n  }\n\n  private prepareUploadFormData(fileBody: Blob | FormData, options: FileOptions): FormData {\n    const body = new FormData()\n    const files: [string, Blob][] = []\n\n    // Storage reads metadata before consuming the file stream.\n    if (fileBody instanceof FormData) {\n      fileBody.forEach((value, name) => {\n        if (typeof value === 'string') {\n          body.append(name, value)\n        } else {\n          files.push([name, value])\n        }\n      })\n    } else {\n      files.push(['', fileBody])\n    }\n\n    if (!body.has('cacheControl')) {\n      body.append('cacheControl', options.cacheControl as string)\n    }\n    if (options.metadata && !body.has('metadata')) {\n      body.append('metadata', this.encodeMetadata(options.metadata))\n    }\n    if (options.contentEncoding && !body.has('contentEncoding')) {\n      body.append('contentEncoding', options.contentEncoding)\n    }\n    for (const [name, file] of files) {\n      body.append(name, file)\n    }\n    return body\n  }\n\n  protected encodeMetadata(metadata: Record<string, any>) {\n    return JSON.stringify(metadata)\n  }\n\n  toBase64(data: string) {\n    if (typeof Buffer !== 'undefined') {\n      return Buffer.from(data).toString('base64')\n    }\n    return btoa(data)\n  }\n\n  private _getFinalPath(path: string) {\n    return `${this.bucketId}/${path.replace(/^\\/+/, '')}`\n  }\n\n  private _removeEmptyFolders(path: string) {\n    return path.replace(/^\\/|\\/$/g, '').replace(/\\/+/g, '/')\n  }\n\n  /** Modifies the `query`, appending values the from `transform` */\n  private applyTransformOptsToQuery(\n    query: URLSearchParams,\n    transform: TransformOptions\n  ): URLSearchParams {\n    if (transform.width) query.set('width', transform.width.toString())\n    if (transform.height) query.set('height', transform.height.toString())\n    if (transform.resize) query.set('resize', transform.resize)\n    if (transform.format) query.set('format', transform.format)\n    if (transform.quality) query.set('quality', transform.quality.toString())\n\n    return query\n  }\n}\n", "// 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.118.0'\n", "import { version } from './version'\nexport const DEFAULT_HEADERS = {\n  'X-Client-Info': `storage-js/${version}`,\n}\n", "import { DEFAULT_HEADERS } from '../lib/constants'\nimport { StorageError } from '../lib/common/errors'\nimport { Fetch, get, post, put, remove } from '../lib/common/fetch'\nimport { encodeStoragePath } from '../lib/common/helpers'\nimport BaseApiClient from '../lib/common/BaseApiClient'\nimport {\n  Bucket,\n  BucketLifecycleConfiguration,\n  BucketType,\n  CreateSettableVersioningStatus,\n  FetchParameters,\n  ListBucketOptions,\n  PurgeCacheOptions,\n  UpdateSettableVersioningStatus,\n} from '../lib/types'\nimport { StorageClientOptions } from '../StorageClient'\n\nexport default class StorageBucketApi extends BaseApiClient<StorageError> {\n  constructor(\n    url: string,\n    headers: { [key: string]: string } = {},\n    fetch?: Fetch,\n    opts?: StorageClientOptions\n  ) {\n    const baseUrl = new URL(url)\n\n    // if legacy uri is used, replace with new storage host (disables request buffering to allow > 50GB uploads)\n    // \"project-ref.supabase.co\" becomes \"project-ref.storage.supabase.co\"\n    if (opts?.useNewHostname) {\n      const isSupabaseHost = /supabase\\.(co|in|red)$/.test(baseUrl.hostname)\n      if (isSupabaseHost && !baseUrl.hostname.includes('storage.supabase.')) {\n        baseUrl.hostname = baseUrl.hostname.replace('supabase.', 'storage.supabase.')\n      }\n    }\n\n    const finalUrl = baseUrl.href.replace(/\\/$/, '')\n    const finalHeaders = { ...DEFAULT_HEADERS, ...headers }\n\n    super(finalUrl, finalHeaders, fetch, 'storage')\n  }\n\n  /**\n   * Retrieves the details of all Storage buckets within an existing project.\n   *\n   * @category Storage\n   * @subcategory File Buckets\n   * @param options Query parameters for listing buckets\n   * @param options.limit Maximum number of buckets to return\n   * @param options.offset Number of buckets to skip\n   * @param options.sortColumn Column to sort by ('id', 'name', 'created_at', 'updated_at')\n   * @param options.sortOrder Sort order ('asc' or 'desc')\n   * @param options.search Search term to filter bucket names\n   * @returns Promise with response containing array of buckets or error\n   *\n   * @example List buckets\n   * ```js\n   * const { data, error } = await supabase\n   *   .storage\n   *   .listBuckets()\n   * ```\n   *\n   * @example List buckets with options\n   * ```js\n   * const { data, error } = await supabase\n   *   .storage\n   *   .listBuckets({\n   *     limit: 10,\n   *     offset: 0,\n   *     sortColumn: 'created_at',\n   *     sortOrder: 'desc',\n   *     search: 'prod'\n   *   })\n   * ```\n   *\n   * @remarks\n   * - RLS policy permissions required:\n   *   - `buckets` table permissions: `select`\n   *   - `objects` table permissions: none\n   * - Refer to the [Storage guide](/docs/guides/storage/security/access-control) on how access control works\n   */\n  async listBuckets(options?: ListBucketOptions): Promise<\n    | {\n        data: Bucket[]\n        error: null\n      }\n    | {\n        data: null\n        error: StorageError\n      }\n  > {\n    return this.handleOperation(async () => {\n      const queryString = this.listBucketOptionsToQueryString(options)\n      return await get(this.fetch, `${this.url}/bucket${queryString}`, {\n        headers: this.headers,\n      })\n    })\n  }\n\n  /**\n   * Retrieves the details of an existing Storage bucket.\n   *\n   * @category Storage\n   * @subcategory File Buckets\n   * @param id The unique identifier of the bucket you would like to retrieve.\n   * @returns Promise with response containing bucket details or error\n   *\n   * @example Get bucket\n   * ```js\n   * const { data, error } = await supabase\n   *   .storage\n   *   .getBucket('avatars')\n   * ```\n   *\n   * Response:\n   * ```json\n   * {\n   *   \"data\": {\n   *     \"id\": \"avatars\",\n   *     \"name\": \"avatars\",\n   *     \"owner\": \"\",\n   *     \"public\": false,\n   *     \"file_size_limit\": 1024,\n   *     \"allowed_mime_types\": [\n   *       \"image/png\"\n   *     ],\n   *     \"created_at\": \"2024-05-22T22:26:05.100Z\",\n   *     \"updated_at\": \"2024-05-22T22:26:05.100Z\"\n   *   },\n   *   \"error\": null\n   * }\n   * ```\n   *\n   * @remarks\n   * - RLS policy permissions required:\n   *   - `buckets` table permissions: `select`\n   *   - `objects` table permissions: none\n   * - Refer to the [Storage guide](/docs/guides/storage/security/access-control) on how access control works\n   */\n  async getBucket(id: string): Promise<\n    | {\n        data: Bucket\n        error: null\n      }\n    | {\n        data: null\n        error: StorageError\n      }\n  > {\n    return this.handleOperation(async () => {\n      return await get(this.fetch, `${this.url}/bucket/${id}`, { headers: this.headers })\n    })\n  }\n\n  /**\n   * Creates a new Storage bucket\n   *\n   * @category Storage\n   * @subcategory File Buckets\n   * @param id A unique identifier for the bucket you are creating.\n   * @param options.public The visibility of the bucket. Public buckets don't require an authorization token to download objects, but still require a valid token for all other operations. By default, buckets are private.\n   * @param options.fileSizeLimit specifies the max file size in bytes that can be uploaded to this bucket.\n   * The global file size limit takes precedence over this value.\n   * The default value is null, which doesn't set a per bucket file size limit.\n   * @param options.allowedMimeTypes specifies the allowed mime types that this bucket can accept during upload.\n   * The default value is null, which allows files with all mime types to be uploaded.\n   * Each mime type specified can be a wildcard, e.g. image/*, or a specific mime type, e.g. image/png.\n   * @param options.type (private-beta) specifies the bucket type. see `BucketType` for more details.\n   *   - default bucket type is `STANDARD`\n   * @param options.versioningStatus the bucket's initial object versioning status.\n   * The default value is `DISABLED`\n   * @returns Promise with response containing newly created bucket name or error\n   *\n   * @example Create bucket\n   * ```js\n   * const { data, error } = await supabase\n   *   .storage\n   *   .createBucket('avatars', {\n   *     public: false,\n   *     allowedMimeTypes: ['image/png'],\n   *     fileSizeLimit: 1024\n   *   })\n   * ```\n   *\n   * Response:\n   * ```json\n   * {\n   *   \"data\": {\n   *     \"name\": \"avatars\"\n   *   },\n   *   \"error\": null\n   * }\n   * ```\n   *\n   * @remarks\n   * - RLS policy permissions required:\n   *   - `buckets` table permissions: `insert`\n   *   - `objects` table permissions: none\n   * - Refer to the [Storage guide](/docs/guides/storage/security/access-control) on how access control works\n   */\n  async createBucket(\n    id: string,\n    options: {\n      public: boolean\n      fileSizeLimit?: number | string | null\n      allowedMimeTypes?: string[] | null\n      type?: BucketType\n      versioningStatus?: CreateSettableVersioningStatus\n    } = {\n      public: false,\n    }\n  ): Promise<\n    | {\n        data: Pick<Bucket, 'name'>\n        error: null\n      }\n    | {\n        data: null\n        error: StorageError\n      }\n  > {\n    return this.handleOperation(async () => {\n      return await post(\n        this.fetch,\n        `${this.url}/bucket`,\n        {\n          id,\n          name: id,\n          type: options.type,\n          public: options.public,\n          file_size_limit: options.fileSizeLimit,\n          allowed_mime_types: options.allowedMimeTypes,\n          versioning_status: options.versioningStatus,\n        },\n        { headers: this.headers }\n      )\n    })\n  }\n\n  /**\n   * Updates a Storage bucket\n   *\n   * @category Storage\n   * @subcategory File Buckets\n   * @param id A unique identifier for the bucket you are updating.\n   * @param options.public The visibility of the bucket. Public buckets don't require an authorization token to download objects, but still require a valid token for all other operations.\n   * @param options.fileSizeLimit specifies the max file size in bytes that can be uploaded to this bucket.\n   * The global file size limit takes precedence over this value.\n   * The default value is null, which doesn't set a per bucket file size limit.\n   * @param options.allowedMimeTypes specifies the allowed mime types that this bucket can accept during upload.\n   * The default value is null, which allows files with all mime types to be uploaded.\n   * Each mime type specified can be a wildcard, e.g. image/*, or a specific mime type, e.g. image/png.\n   * @param options.versioningStatus the bucket's new object versioning status. `DISABLED` is not\n   * valid here, there's no transition back to it once versioning has been touched.\n   * @returns Promise with response containing success message or error\n   *\n   * @example Update bucket\n   * ```js\n   * const { data, error } = await supabase\n   *   .storage\n   *   .updateBucket('avatars', {\n   *     public: false,\n   *     allowedMimeTypes: ['image/png'],\n   *     fileSizeLimit: 1024\n   *   })\n   * ```\n   *\n   * Response:\n   * ```json\n   * {\n   *   \"data\": {\n   *     \"message\": \"Successfully updated\"\n   *   },\n   *   \"error\": null\n   * }\n   * ```\n   *\n   * @remarks\n   * - RLS policy permissions required:\n   *   - `buckets` table permissions: `select` and `update`\n   *   - `objects` table permissions: none\n   * - Refer to the [Storage guide](/docs/guides/storage/security/access-control) on how access control works\n   */\n  async updateBucket(\n    id: string,\n    options: {\n      public: boolean\n      fileSizeLimit?: number | string | null\n      allowedMimeTypes?: string[] | null\n      versioningStatus?: UpdateSettableVersioningStatus\n    }\n  ): Promise<\n    | {\n        data: { message: string }\n        error: null\n      }\n    | {\n        data: null\n        error: StorageError\n      }\n  > {\n    return this.handleOperation(async () => {\n      return await put(\n        this.fetch,\n        `${this.url}/bucket/${id}`,\n        {\n          id,\n          name: id,\n          public: options.public,\n          file_size_limit: options.fileSizeLimit,\n          allowed_mime_types: options.allowedMimeTypes,\n          versioning_status: options.versioningStatus,\n        },\n        { headers: this.headers }\n      )\n    })\n  }\n\n  /**\n   * Removes all objects inside a single bucket.\n   *\n   * @category Storage\n   * @subcategory File Buckets\n   * @param id The unique identifier of the bucket you would like to empty.\n   * @returns Promise with success message or error\n   *\n   * @example Empty bucket\n   * ```js\n   * const { data, error } = await supabase\n   *   .storage\n   *   .emptyBucket('avatars')\n   * ```\n   *\n   * Response:\n   * ```json\n   * {\n   *   \"data\": {\n   *     \"message\": \"Successfully emptied\"\n   *   },\n   *   \"error\": null\n   * }\n   * ```\n   *\n   * @remarks\n   * - RLS policy permissions required:\n   *   - `buckets` table permissions: `select`\n   *   - `objects` table permissions: `select` and `delete`\n   * - Refer to the [Storage guide](/docs/guides/storage/security/access-control) on how access control works\n   */\n  async emptyBucket(id: string): Promise<\n    | {\n        data: { message: string }\n        error: null\n      }\n    | {\n        data: null\n        error: StorageError\n      }\n  > {\n    return this.handleOperation(async () => {\n      return await post(this.fetch, `${this.url}/bucket/${id}/empty`, {}, { headers: this.headers })\n    })\n  }\n\n  /**\n   * Deletes an existing bucket. A bucket can't be deleted with existing objects inside it.\n   * You must first `empty()` the bucket.\n   *\n   * @category Storage\n   * @subcategory File Buckets\n   * @param id The unique identifier of the bucket you would like to delete.\n   * @returns Promise with success message or error\n   *\n   * @example Delete bucket\n   * ```js\n   * const { data, error } = await supabase\n   *   .storage\n   *   .deleteBucket('avatars')\n   * ```\n   *\n   * Response:\n   * ```json\n   * {\n   *   \"data\": {\n   *     \"message\": \"Successfully deleted\"\n   *   },\n   *   \"error\": null\n   * }\n   * ```\n   *\n   * @remarks\n   * - RLS policy permissions required:\n   *   - `buckets` table permissions: `select` and `delete`\n   *   - `objects` table permissions: none\n   * - Refer to the [Storage guide](/docs/guides/storage/security/access-control) on how access control works\n   */\n  async deleteBucket(id: string): Promise<\n    | {\n        data: { message: string }\n        error: null\n      }\n    | {\n        data: null\n        error: StorageError\n      }\n  > {\n    return this.handleOperation(async () => {\n      return await remove(this.fetch, `${this.url}/bucket/${id}`, {}, { headers: this.headers })\n    })\n  }\n\n  /**\n   * Returns the lifecycle policy stored on a bucket.\n   *\n   * Fails with `NoSuchLifecycleConfiguration` when the bucket has no policy.\n   *\n   * These rules expire previous versions of objects, not the current one.\n   * Turn versioning on or there is nothing for the policy to act on.\n   * Standard buckets only. Returns `FeatureNotEnabled` if lifecycle is off\n   * for the project.\n   *\n   * @category Storage\n   * @subcategory File Buckets\n   * @param id The unique identifier of the bucket.\n   * @returns Promise with the lifecycle configuration or error\n   *\n   * @example Get lifecycle configuration\n   * ```js\n   * const { data, error } = await supabase\n   *   .storage\n   *   .getBucketLifecycle('avatars')\n   * ```\n   *\n   * Response:\n   * ```json\n   * {\n   *   \"data\": {\n   *     \"rules\": [\n   *       {\n   *         \"id\": \"expire-history\",\n   *         \"status\": \"Enabled\",\n   *         \"filter\": {},\n   *         \"noncurrentVersionExpiration\": {\n   *           \"noncurrentDays\": 30,\n   *           \"newerNoncurrentVersions\": 2\n   *         }\n   *       }\n   *     ]\n   *   },\n   *   \"error\": null\n   * }\n   * ```\n   *\n   * @remarks\n   * - RLS policy permissions required:\n   *   - `buckets` table permissions: `select`\n   *   - `objects` table permissions: none\n   * - Refer to the [Storage guide](/docs/guides/storage/security/access-control) on how access control works\n   */\n  async getBucketLifecycle(id: string): Promise<\n    | {\n        data: BucketLifecycleConfiguration\n        error: null\n      }\n    | {\n        data: null\n        error: StorageError\n      }\n  > {\n    return this.handleOperation(async () => {\n      return await get(this.fetch, this.bucketLifecycleUrl(id), { headers: this.headers })\n    })\n  }\n\n  /**\n   * Replaces the lifecycle policy on a bucket.\n   *\n   * The `rules` array you send is the whole policy. Anything previously stored\n   * is overwritten. Send at least one rule. Call {@link deleteBucketLifecycle}\n   * to remove the policy.\n   *\n   * Each rule currently supports only `noncurrentVersionExpiration`. `filter`\n   * is required and must be `{}`. Prefix filters, tag filters, and current-object\n   * expiration are rejected. Rule IDs must be unique. Omit `id` and the\n   * server generates one.\n   *\n   * Standard buckets only. Returns `FeatureNotEnabled` if lifecycle is off\n   * for the project.\n   *\n   * @category Storage\n   * @subcategory File Buckets\n   * @param id The unique identifier of the bucket.\n   * @param configuration The full lifecycle configuration to store.\n   * @returns Promise with the stored configuration or error\n   *\n   * @example Replace lifecycle configuration\n   * ```js\n   * const { data, error } = await supabase\n   *   .storage\n   *   .updateBucketLifecycle('avatars', {\n   *     rules: [\n   *       {\n   *         id: 'expire-history',\n   *         status: 'Enabled',\n   *         filter: {},\n   *         noncurrentVersionExpiration: {\n   *           noncurrentDays: 30,\n   *           newerNoncurrentVersions: 2,\n   *         },\n   *       },\n   *     ],\n   *   })\n   * ```\n   *\n   * @remarks\n   * - RLS policy permissions required:\n   *   - `buckets` table permissions: `select` and `update`\n   *   - `objects` table permissions: none\n   * - Refer to the [Storage guide](/docs/guides/storage/security/access-control) on how access control works\n   */\n  async updateBucketLifecycle(\n    id: string,\n    configuration: BucketLifecycleConfiguration\n  ): Promise<\n    | {\n        data: BucketLifecycleConfiguration\n        error: null\n      }\n    | {\n        data: null\n        error: StorageError\n      }\n  > {\n    return this.handleOperation(async () => {\n      return await put(this.fetch, this.bucketLifecycleUrl(id), configuration, {\n        headers: this.headers,\n      })\n    })\n  }\n\n  /**\n   * Removes the lifecycle policy from a bucket.\n   *\n   * Safe to call when no policy is stored. The response is still success.\n   * Standard buckets only. Returns `FeatureNotEnabled` if lifecycle is off\n   * for the project.\n   *\n   * @category Storage\n   * @subcategory File Buckets\n   * @param id The unique identifier of the bucket.\n   * @returns Promise with success message or error\n   *\n   * @example Delete lifecycle configuration\n   * ```js\n   * const { data, error } = await supabase\n   *   .storage\n   *   .deleteBucketLifecycle('avatars')\n   * ```\n   *\n   * Response:\n   * ```json\n   * {\n   *   \"data\": {\n   *     \"message\": \"Successfully deleted\"\n   *   },\n   *   \"error\": null\n   * }\n   * ```\n   *\n   * @remarks\n   * - RLS policy permissions required:\n   *   - `buckets` table permissions: `select` and `update`\n   *   - `objects` table permissions: none\n   * - Refer to the [Storage guide](/docs/guides/storage/security/access-control) on how access control works\n   */\n  async deleteBucketLifecycle(id: string): Promise<\n    | {\n        data: { message: string }\n        error: null\n      }\n    | {\n        data: null\n        error: StorageError\n      }\n  > {\n    return this.handleOperation(async () => {\n      return await remove(this.fetch, this.bucketLifecycleUrl(id), {}, { headers: this.headers })\n    })\n  }\n\n  /**\n   * Purges the CDN cache for an entire bucket.\n   *\n   * Maps to `DELETE /cdn/{bucket}` on the Storage API. The server\n   * issues a CDN invalidation for the bucket and returns `{ message: 'success' }`.\n   *\n   * **Requires the `service_role` key.** The underlying endpoint enforces\n   * `service_role` JWT — calls made with the anon key or a user JWT will be\n   * rejected by the server.\n   *\n   * **Hosted CDN feature.** On self-hosted Supabase, the Storage service must\n   * have `CDN_PURGE_ENDPOINT_URL` configured and the `purgeCache` tenant\n   * feature enabled, otherwise the server returns an error.\n   *\n   * @category Storage\n   * @subcategory File Buckets\n   * @param id The unique identifier of the bucket you would like to purge from cache.\n   * @param options Optional purge cache options.\n   * @param options.transformations If true, purges only transformations (resized/formatted variants), leaving original cached files intact.\n   * @param parameters Optional fetch parameters such as an `AbortController` signal.\n   * @returns Promise with `{ data: { message }, error: null }` on success or `{ data: null, error }` on failure.\n   *\n   * @example Purge cache for an entire bucket\n   * ```js\n   * const { data, error } = await supabase\n   *   .storage\n   *   .purgeBucketCache('avatars')\n   * ```\n   *\n   * @example Purge only transformations for an entire bucket\n   * ```js\n   * const { data, error } = await supabase\n   *   .storage\n   *   .purgeBucketCache('avatars', { transformations: true })\n   * ```\n   */\n  async purgeBucketCache(\n    id: string,\n    options?: PurgeCacheOptions,\n    parameters?: FetchParameters\n  ): Promise<\n    | {\n        data: { message: string }\n        error: null\n      }\n    | {\n        data: null\n        error: StorageError\n      }\n  > {\n    return this.handleOperation(async () => {\n      const query = new URLSearchParams()\n      if (options?.transformations) {\n        query.set('transformations', 'true')\n      }\n      const queryString = query.toString()\n\n      return await remove(\n        this.fetch,\n        `${this.url}/cdn/${encodeStoragePath(id)}${queryString ? `?${queryString}` : ''}`,\n        {},\n        { headers: this.headers },\n        parameters\n      )\n    })\n  }\n\n  private bucketLifecycleUrl(id: string): string {\n    return `${this.url}/bucket/${encodeStoragePath(id)}/lifecycle`\n  }\n\n  private listBucketOptionsToQueryString(options?: ListBucketOptions): string {\n    const params: Record<string, string> = {}\n    if (options) {\n      if ('limit' in options) {\n        params.limit = String(options.limit)\n      }\n      if ('offset' in options) {\n        params.offset = String(options.offset)\n      }\n      if (options.search) {\n        params.search = options.search\n      }\n      if (options.sortColumn) {\n        params.sortColumn = options.sortColumn\n      }\n      if (options.sortOrder) {\n        params.sortOrder = options.sortOrder\n      }\n    }\n    return Object.keys(params).length > 0 ? '?' + new URLSearchParams(params).toString() : ''\n  }\n}\n", "import { IcebergRestCatalog, IcebergError } from 'iceberg-js'\nimport { DEFAULT_HEADERS } from '../lib/constants'\nimport { StorageError } from '../lib/common/errors'\nimport { Fetch, get, post, remove } from '../lib/common/fetch'\nimport { isValidBucketName } from '../lib/common/helpers'\nimport BaseApiClient from '../lib/common/BaseApiClient'\nimport { AnalyticBucket } from '../lib/types'\n\ntype WrapAsyncMethod<T> = T extends (...args: infer A) => Promise<infer R>\n  ? (...args: A) => Promise<{ data: R; error: null } | { data: null; error: IcebergError }>\n  : T\n\nexport type WrappedIcebergRestCatalog = {\n  [K in keyof IcebergRestCatalog]: WrapAsyncMethod<IcebergRestCatalog[K]>\n}\n\n/**\n * Client class for managing Analytics Buckets using Iceberg tables\n * Provides methods for creating, listing, and deleting analytics buckets\n */\nexport default class StorageAnalyticsClient extends BaseApiClient<StorageError> {\n  /**\n   * @alpha\n   *\n   * Creates a new StorageAnalyticsClient instance\n   *\n   * **Public alpha:** This API is part of a public alpha release and may not be available to your account type.\n   *\n   * @category Storage\n   * @subcategory Analytics Buckets\n   * @param url - The base URL for the storage API\n   * @param headers - HTTP headers to include in requests\n   * @param fetch - Optional custom fetch implementation\n   *\n   * @example Using supabase-js (recommended)\n   * ```typescript\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.storage.analytics.listBuckets()\n   * ```\n   *\n   * @example Standalone import for bundle-sensitive environments\n   * ```typescript\n   * import { StorageAnalyticsClient } from '@supabase/storage-js'\n   *\n   * const client = new StorageAnalyticsClient(url, headers)\n   * ```\n   */\n  constructor(url: string, headers: { [key: string]: string } = {}, fetch?: Fetch) {\n    const finalUrl = url.replace(/\\/$/, '')\n    const finalHeaders = { ...DEFAULT_HEADERS, ...headers }\n    super(finalUrl, finalHeaders, fetch, 'storage')\n  }\n\n  /**\n   * @alpha\n   *\n   * Creates a new analytics bucket using Iceberg tables\n   * Analytics buckets are optimized for analytical queries and data processing\n   *\n   * **Public alpha:** This API is part of a public alpha release and may not be available to your account type.\n   *\n   * @category Storage\n   * @subcategory Analytics Buckets\n   * @param name A unique name for the bucket you are creating\n   * @returns Promise with response containing newly created analytics bucket or error\n   *\n   * @example Create analytics bucket\n   * ```js\n   * const { data, error } = await supabase\n   *   .storage\n   *   .analytics\n   *   .createBucket('analytics-data')\n   * ```\n   *\n   * Response:\n   * ```json\n   * {\n   *   \"data\": {\n   *     \"name\": \"analytics-data\",\n   *     \"type\": \"ANALYTICS\",\n   *     \"format\": \"iceberg\",\n   *     \"created_at\": \"2024-05-22T22:26:05.100Z\",\n   *     \"updated_at\": \"2024-05-22T22:26:05.100Z\"\n   *   },\n   *   \"error\": null\n   * }\n   * ```\n   *\n   * @remarks\n   * - Creates a new analytics bucket using Iceberg tables\n   * - Analytics buckets are optimized for analytical queries and data processing\n   */\n  async createBucket(name: string): Promise<\n    | {\n        data: AnalyticBucket\n        error: null\n      }\n    | {\n        data: null\n        error: StorageError\n      }\n  > {\n    return this.handleOperation(async () => {\n      return await post(this.fetch, `${this.url}/bucket`, { name }, { headers: this.headers })\n    })\n  }\n\n  /**\n   * @alpha\n   *\n   * Retrieves the details of all Analytics Storage buckets within an existing project\n   * Only returns buckets of type 'ANALYTICS'\n   *\n   * **Public alpha:** This API is part of a public alpha release and may not be available to your account type.\n   *\n   * @category Storage\n   * @subcategory Analytics Buckets\n   * @param options Query parameters for listing buckets\n   * @param options.limit Maximum number of buckets to return\n   * @param options.offset Number of buckets to skip\n   * @param options.sortColumn Column to sort by ('name', 'created_at', 'updated_at')\n   * @param options.sortOrder Sort order ('asc' or 'desc')\n   * @param options.search Search term to filter bucket names\n   * @returns Promise with response containing array of analytics buckets or error\n   *\n   * @example List analytics buckets\n   * ```js\n   * const { data, error } = await supabase\n   *   .storage\n   *   .analytics\n   *   .listBuckets({\n   *     limit: 10,\n   *     offset: 0,\n   *     sortColumn: 'created_at',\n   *     sortOrder: 'desc'\n   *   })\n   * ```\n   *\n   * Response:\n   * ```json\n   * {\n   *   \"data\": [\n   *     {\n   *       \"name\": \"analytics-data\",\n   *       \"type\": \"ANALYTICS\",\n   *       \"format\": \"iceberg\",\n   *       \"created_at\": \"2024-05-22T22:26:05.100Z\",\n   *       \"updated_at\": \"2024-05-22T22:26:05.100Z\"\n   *     }\n   *   ],\n   *   \"error\": null\n   * }\n   * ```\n   *\n   * @remarks\n   * - Retrieves the details of all Analytics Storage buckets within an existing project\n   * - Only returns buckets of type 'ANALYTICS'\n   */\n  async listBuckets(options?: {\n    limit?: number\n    offset?: number\n    sortColumn?: 'name' | 'created_at' | 'updated_at'\n    sortOrder?: 'asc' | 'desc'\n    search?: string\n  }): Promise<\n    | {\n        data: AnalyticBucket[]\n        error: null\n      }\n    | {\n        data: null\n        error: StorageError\n      }\n  > {\n    return this.handleOperation(async () => {\n      // Build query string from options\n      const queryParams = new URLSearchParams()\n      if (options?.limit !== undefined) queryParams.set('limit', options.limit.toString())\n      if (options?.offset !== undefined) queryParams.set('offset', options.offset.toString())\n      if (options?.sortColumn) queryParams.set('sortColumn', options.sortColumn)\n      if (options?.sortOrder) queryParams.set('sortOrder', options.sortOrder)\n      if (options?.search) queryParams.set('search', options.search)\n\n      const queryString = queryParams.toString()\n      const url = queryString ? `${this.url}/bucket?${queryString}` : `${this.url}/bucket`\n\n      return await get(this.fetch, url, { headers: this.headers })\n    })\n  }\n\n  /**\n   * @alpha\n   *\n   * Deletes an existing analytics bucket\n   * A bucket can't be deleted with existing objects inside it\n   * You must first empty the bucket before deletion\n   *\n   * **Public alpha:** This API is part of a public alpha release and may not be available to your account type.\n   *\n   * @category Storage\n   * @subcategory Analytics Buckets\n   * @param bucketName The unique identifier of the bucket you would like to delete\n   * @returns Promise with response containing success message or error\n   *\n   * @example Delete analytics bucket\n   * ```js\n   * const { data, error } = await supabase\n   *   .storage\n   *   .analytics\n   *   .deleteBucket('analytics-data')\n   * ```\n   *\n   * Response:\n   * ```json\n   * {\n   *   \"data\": {\n   *     \"message\": \"Successfully deleted\"\n   *   },\n   *   \"error\": null\n   * }\n   * ```\n   *\n   * @remarks\n   * - Deletes an analytics bucket\n   */\n  async deleteBucket(bucketName: string): Promise<\n    | {\n        data: { message: string }\n        error: null\n      }\n    | {\n        data: null\n        error: StorageError\n      }\n  > {\n    return this.handleOperation(async () => {\n      return await remove(\n        this.fetch,\n        `${this.url}/bucket/${bucketName}`,\n        {},\n        { headers: this.headers }\n      )\n    })\n  }\n\n  /**\n   * @alpha\n   *\n   * Get an Iceberg REST Catalog client configured for a specific analytics bucket\n   * Use this to perform advanced table and namespace operations within the bucket\n   * The returned client provides full access to the Apache Iceberg REST Catalog API\n   * with the Supabase `{ data, error }` pattern for consistent error handling on all operations.\n   *\n   * **Public alpha:** This API is part of a public alpha release and may not be available to your account type.\n   *\n   * @category Storage\n   * @subcategory Analytics Buckets\n   * @param bucketName - The name of the analytics bucket (warehouse) to connect to\n   * @returns The wrapped Iceberg catalog client\n   * @throws {StorageError} If the bucket name is invalid\n   *\n   * @example Get catalog and create table\n   * ```js\n   * // First, create an analytics bucket\n   * const { data: bucket, error: bucketError } = await supabase\n   *   .storage\n   *   .analytics\n   *   .createBucket('analytics-data')\n   *\n   * // Get the Iceberg catalog for that bucket\n   * const catalog = supabase.storage.analytics.from('analytics-data')\n   *\n   * // Create a namespace\n   * const { error: nsError } = await catalog.createNamespace({ namespace: ['default'] })\n   *\n   * // Create a table with schema\n   * const { data: tableMetadata, error: tableError } = await catalog.createTable(\n   *   { namespace: ['default'] },\n   *   {\n   *     name: 'events',\n   *     schema: {\n   *       type: 'struct',\n   *       fields: [\n   *         { id: 1, name: 'id', type: 'long', required: true },\n   *         { id: 2, name: 'timestamp', type: 'timestamp', required: true },\n   *         { id: 3, name: 'user_id', type: 'string', required: false }\n   *       ],\n   *       'schema-id': 0,\n   *       'identifier-field-ids': [1]\n   *     },\n   *     'partition-spec': {\n   *       'spec-id': 0,\n   *       fields: []\n   *     },\n   *     'write-order': {\n   *       'order-id': 0,\n   *       fields: []\n   *     },\n   *     properties: {\n   *       'write.format.default': 'parquet'\n   *     }\n   *   }\n   * )\n   * ```\n   *\n   * @example List tables in namespace\n   * ```js\n   * const catalog = supabase.storage.analytics.from('analytics-data')\n   *\n   * // List all tables in the default namespace\n   * const { data: tables, error: listError } = await catalog.listTables({ namespace: ['default'] })\n   * if (listError) {\n   *   if (listError.isNotFound()) {\n   *     console.log('Namespace not found')\n   *   }\n   *   return\n   * }\n   * console.log(tables) // [{ namespace: ['default'], name: 'events' }]\n   * ```\n   *\n   * @example Working with namespaces\n   * ```js\n   * const catalog = supabase.storage.analytics.from('analytics-data')\n   *\n   * // List all namespaces\n   * const { data: namespaces } = await catalog.listNamespaces()\n   *\n   * // Create namespace with properties\n   * await catalog.createNamespace(\n   *   { namespace: ['production'] },\n   *   { properties: { owner: 'data-team', env: 'prod' } }\n   * )\n   * ```\n   *\n   * @example Cleanup operations\n   * ```js\n   * const catalog = supabase.storage.analytics.from('analytics-data')\n   *\n   * // Drop table with purge option (removes all data)\n   * const { error: dropError } = await catalog.dropTable(\n   *   { namespace: ['default'], name: 'events' },\n   *   { purge: true }\n   * )\n   *\n   * if (dropError?.isNotFound()) {\n   *   console.log('Table does not exist')\n   * }\n   *\n   * // Drop namespace (must be empty)\n   * await catalog.dropNamespace({ namespace: ['default'] })\n   * ```\n   *\n   * @remarks\n   * This method provides a bridge between Supabase's bucket management and the standard\n   * Apache Iceberg REST Catalog API. The bucket name maps to the Iceberg warehouse parameter.\n   * All authentication and configuration is handled automatically using your Supabase credentials.\n   *\n   * **Error Handling**: Invalid bucket names throw immediately. All catalog\n   * operations return `{ data, error }` where errors are `IcebergError` instances from iceberg-js.\n   * Use helper methods like `error.isNotFound()` or check `error.status` for specific error handling.\n   * Use `.throwOnError()` on the analytics client if you prefer exceptions for catalog operations.\n   *\n   * **Cleanup Operations**: When using `dropTable`, the `purge: true` option permanently\n   * deletes all table data. Without it, the table is marked as deleted but data remains.\n   *\n   * **Library Dependency**: The returned catalog wraps `IcebergRestCatalog` from iceberg-js.\n   * For complete API documentation and advanced usage, refer to the\n   * [iceberg-js documentation](https://supabase.github.io/iceberg-js/).\n   */\n  from(bucketName: string): WrappedIcebergRestCatalog {\n    // Validate bucket name using same rules as Supabase Storage API backend\n    if (!isValidBucketName(bucketName)) {\n      throw new StorageError(\n        'Invalid bucket name: File, folder, and bucket names must follow AWS object key naming guidelines ' +\n          'and should avoid the use of any other characters.'\n      )\n    }\n\n    // Construct the Iceberg REST Catalog URL\n    // The base URL is /storage/v1/iceberg\n    // Note: IcebergRestCatalog from iceberg-js automatically adds /v1/ prefix to API paths\n    // so we should NOT append /v1 here (it would cause double /v1/v1/ in the URL)\n    const catalog = new IcebergRestCatalog({\n      baseUrl: this.url,\n      catalogName: bucketName, // Maps to the warehouse parameter in Supabase's implementation\n      auth: {\n        type: 'custom',\n        getHeaders: async () => this.headers,\n      },\n      fetch: this.fetch,\n    })\n\n    const shouldThrowOnError = this.shouldThrowOnError\n\n    const wrappedCatalog = new Proxy(catalog, {\n      get(target, prop: keyof IcebergRestCatalog) {\n        const value = target[prop]\n        if (typeof value !== 'function') {\n          return value\n        }\n\n        return async (...args: unknown[]) => {\n          try {\n            const data = await (value as Function).apply(target, args)\n            return { data, error: null }\n          } catch (error) {\n            if (shouldThrowOnError) {\n              throw error\n            }\n            return { data: null, error: error as IcebergError }\n          }\n        }\n      },\n    }) as unknown as WrappedIcebergRestCatalog\n\n    return wrappedCatalog\n  }\n}\n", "import { DEFAULT_HEADERS } from '../lib/constants'\nimport { StorageError } from '../lib/common/errors'\nimport { Fetch, vectorsApi } from '../lib/common/fetch'\nimport BaseApiClient from '../lib/common/BaseApiClient'\nimport {\n  ApiResponse,\n  VectorIndex,\n  ListIndexesOptions,\n  ListIndexesResponse,\n  VectorDataType,\n  DistanceMetric,\n  MetadataConfiguration,\n} from '../lib/types'\n\n/**\n * @alpha\n *\n * Options for creating a vector index\n *\n * **Public alpha:** This API is part of a public alpha release and may not be available to your account type.\n */\nexport interface CreateIndexOptions {\n  vectorBucketName: string\n  indexName: string\n  dataType: VectorDataType\n  dimension: number\n  distanceMetric: DistanceMetric\n  metadataConfiguration?: MetadataConfiguration\n}\n\n/**\n * @hidden\n * Base implementation for vector index operations.\n * Use {@link VectorBucketScope} via `supabase.storage.vectors.from('bucket')` instead.\n */\nexport default class VectorIndexApi extends BaseApiClient<StorageError> {\n  /** Creates a new VectorIndexApi instance */\n  constructor(url: string, headers: { [key: string]: string } = {}, fetch?: Fetch) {\n    const finalUrl = url.replace(/\\/$/, '')\n    const finalHeaders = { ...DEFAULT_HEADERS, 'Content-Type': 'application/json', ...headers }\n    super(finalUrl, finalHeaders, fetch, 'vectors')\n  }\n\n  /** Creates a new vector index within a bucket */\n  async createIndex(options: CreateIndexOptions): Promise<ApiResponse<undefined>> {\n    return this.handleOperation(async () => {\n      const data = await vectorsApi.post(this.fetch, `${this.url}/CreateIndex`, options, {\n        headers: this.headers,\n      })\n      return data || {}\n    })\n  }\n\n  /** Retrieves metadata for a specific vector index */\n  async getIndex(\n    vectorBucketName: string,\n    indexName: string\n  ): Promise<ApiResponse<{ index: VectorIndex }>> {\n    return this.handleOperation(async () => {\n      return await vectorsApi.post(\n        this.fetch,\n        `${this.url}/GetIndex`,\n        { vectorBucketName, indexName },\n        { headers: this.headers }\n      )\n    })\n  }\n\n  /** Lists vector indexes within a bucket with optional filtering and pagination */\n  async listIndexes(options: ListIndexesOptions): Promise<ApiResponse<ListIndexesResponse>> {\n    return this.handleOperation(async () => {\n      return await vectorsApi.post(this.fetch, `${this.url}/ListIndexes`, options, {\n        headers: this.headers,\n      })\n    })\n  }\n\n  /** Deletes a vector index and all its data */\n  async deleteIndex(vectorBucketName: string, indexName: string): Promise<ApiResponse<undefined>> {\n    return this.handleOperation(async () => {\n      const data = await vectorsApi.post(\n        this.fetch,\n        `${this.url}/DeleteIndex`,\n        { vectorBucketName, indexName },\n        { headers: this.headers }\n      )\n      return data || {}\n    })\n  }\n}\n", "import { DEFAULT_HEADERS } from '../lib/constants'\nimport { StorageError } from '../lib/common/errors'\nimport { Fetch, vectorsApi } from '../lib/common/fetch'\nimport BaseApiClient from '../lib/common/BaseApiClient'\nimport {\n  ApiResponse,\n  PutVectorsOptions,\n  GetVectorsOptions,\n  GetVectorsResponse,\n  DeleteVectorsOptions,\n  ListVectorsOptions,\n  ListVectorsResponse,\n  QueryVectorsOptions,\n  QueryVectorsResponse,\n} from '../lib/types'\n\n/**\n * @hidden\n * Base implementation for vector data operations.\n * Use {@link VectorIndexScope} via `supabase.storage.vectors.from('bucket').index('idx')` instead.\n */\nexport default class VectorDataApi extends BaseApiClient<StorageError> {\n  /** Creates a new VectorDataApi instance */\n  constructor(url: string, headers: { [key: string]: string } = {}, fetch?: Fetch) {\n    const finalUrl = url.replace(/\\/$/, '')\n    const finalHeaders = { ...DEFAULT_HEADERS, 'Content-Type': 'application/json', ...headers }\n    super(finalUrl, finalHeaders, fetch, 'vectors')\n  }\n\n  /** Inserts or updates vectors in batch (1-500 per request) */\n  async putVectors(options: PutVectorsOptions): Promise<ApiResponse<undefined>> {\n    // Validate batch size\n    if (options.vectors.length < 1 || options.vectors.length > 500) {\n      throw new Error('Vector batch size must be between 1 and 500 items')\n    }\n\n    return this.handleOperation(async () => {\n      const data = await vectorsApi.post(this.fetch, `${this.url}/PutVectors`, options, {\n        headers: this.headers,\n      })\n      return data || {}\n    })\n  }\n\n  /** Retrieves vectors by their keys in batch */\n  async getVectors(options: GetVectorsOptions): Promise<ApiResponse<GetVectorsResponse>> {\n    return this.handleOperation(async () => {\n      return await vectorsApi.post(this.fetch, `${this.url}/GetVectors`, options, {\n        headers: this.headers,\n      })\n    })\n  }\n\n  /** Lists vectors in an index with pagination */\n  async listVectors(options: ListVectorsOptions): Promise<ApiResponse<ListVectorsResponse>> {\n    // Validate segment configuration\n    if (options.segmentCount !== undefined) {\n      if (options.segmentCount < 1 || options.segmentCount > 16) {\n        throw new Error('segmentCount must be between 1 and 16')\n      }\n      if (options.segmentIndex !== undefined) {\n        if (options.segmentIndex < 0 || options.segmentIndex >= options.segmentCount) {\n          throw new Error(`segmentIndex must be between 0 and ${options.segmentCount - 1}`)\n        }\n      }\n    }\n\n    return this.handleOperation(async () => {\n      return await vectorsApi.post(this.fetch, `${this.url}/ListVectors`, options, {\n        headers: this.headers,\n      })\n    })\n  }\n\n  /** Queries for similar vectors using approximate nearest neighbor search */\n  async queryVectors(options: QueryVectorsOptions): Promise<ApiResponse<QueryVectorsResponse>> {\n    return this.handleOperation(async () => {\n      return await vectorsApi.post(this.fetch, `${this.url}/QueryVectors`, options, {\n        headers: this.headers,\n      })\n    })\n  }\n\n  /** Deletes vectors by their keys in batch (1-500 per request) */\n  async deleteVectors(options: DeleteVectorsOptions): Promise<ApiResponse<undefined>> {\n    // Validate batch size\n    if (options.keys.length < 1 || options.keys.length > 500) {\n      throw new Error('Keys batch size must be between 1 and 500 items')\n    }\n\n    return this.handleOperation(async () => {\n      const data = await vectorsApi.post(this.fetch, `${this.url}/DeleteVectors`, options, {\n        headers: this.headers,\n      })\n      return data || {}\n    })\n  }\n}\n", "import { DEFAULT_HEADERS } from '../lib/constants'\nimport { StorageError } from '../lib/common/errors'\nimport { Fetch, vectorsApi } from '../lib/common/fetch'\nimport BaseApiClient from '../lib/common/BaseApiClient'\nimport {\n  ApiResponse,\n  VectorBucket,\n  ListVectorBucketsOptions,\n  ListVectorBucketsResponse,\n} from '../lib/types'\n\n/**\n * @hidden\n * Base implementation for vector bucket operations.\n * Use {@link StorageVectorsClient} via `supabase.storage.vectors` instead.\n */\nexport default class VectorBucketApi extends BaseApiClient<StorageError> {\n  /** Creates a new VectorBucketApi instance */\n  constructor(url: string, headers: { [key: string]: string } = {}, fetch?: Fetch) {\n    const finalUrl = url.replace(/\\/$/, '')\n    const finalHeaders = { ...DEFAULT_HEADERS, 'Content-Type': 'application/json', ...headers }\n    super(finalUrl, finalHeaders, fetch, 'vectors')\n  }\n\n  /** Creates a new vector bucket */\n  async createBucket(vectorBucketName: string): Promise<ApiResponse<undefined>> {\n    return this.handleOperation(async () => {\n      const data = await vectorsApi.post(\n        this.fetch,\n        `${this.url}/CreateVectorBucket`,\n        { vectorBucketName },\n        { headers: this.headers }\n      )\n      return data || {}\n    })\n  }\n\n  /** Retrieves metadata for a specific vector bucket */\n  async getBucket(vectorBucketName: string): Promise<ApiResponse<{ vectorBucket: VectorBucket }>> {\n    return this.handleOperation(async () => {\n      return await vectorsApi.post(\n        this.fetch,\n        `${this.url}/GetVectorBucket`,\n        { vectorBucketName },\n        { headers: this.headers }\n      )\n    })\n  }\n\n  /** Lists vector buckets with optional filtering and pagination */\n  async listBuckets(\n    options: ListVectorBucketsOptions = {}\n  ): Promise<ApiResponse<ListVectorBucketsResponse>> {\n    return this.handleOperation(async () => {\n      return await vectorsApi.post(this.fetch, `${this.url}/ListVectorBuckets`, options, {\n        headers: this.headers,\n      })\n    })\n  }\n\n  /** Deletes a vector bucket (must be empty first) */\n  async deleteBucket(vectorBucketName: string): Promise<ApiResponse<undefined>> {\n    return this.handleOperation(async () => {\n      const data = await vectorsApi.post(\n        this.fetch,\n        `${this.url}/DeleteVectorBucket`,\n        { vectorBucketName },\n        { headers: this.headers }\n      )\n      return data || {}\n    })\n  }\n}\n", "import VectorIndexApi, { CreateIndexOptions } from './VectorIndexApi'\nimport VectorDataApi from './VectorDataApi'\nimport { Fetch } from '../lib/common/fetch'\nimport VectorBucketApi from './VectorBucketApi'\nimport {\n  ApiResponse,\n  DeleteVectorsOptions,\n  GetVectorsOptions,\n  ListIndexesOptions,\n  ListVectorsOptions,\n  ListVectorBucketsOptions,\n  ListVectorBucketsResponse,\n  PutVectorsOptions,\n  QueryVectorsOptions,\n  VectorBucket,\n} from '../lib/types'\n\n/**\n *\n * @alpha\n *\n * Configuration options for the Storage Vectors client\n *\n * **Public alpha:** This API is part of a public alpha release and may not be available to your account type.\n */\nexport interface StorageVectorsClientOptions {\n  /**\n   * Custom headers to include in all requests\n   */\n  headers?: { [key: string]: string }\n  /**\n   * Custom fetch implementation (optional)\n   * Useful for testing or custom request handling\n   */\n  fetch?: Fetch\n}\n\n/**\n *\n * @alpha\n *\n * Main client for interacting with S3 Vectors API\n * Provides access to bucket, index, and vector data operations\n *\n * **Public alpha:** This API is part of a public alpha release and may not be available to your account type.\n *\n * **Usage Patterns:**\n *\n * ```typescript\n * const { data, error } = await supabase\n *  .storage\n *  .vectors\n *  .createBucket('embeddings-prod')\n *\n * // Access index operations via buckets\n * const bucket = supabase.storage.vectors.from('embeddings-prod')\n * await bucket.createIndex({\n *   indexName: 'documents',\n *   dataType: 'float32',\n *   dimension: 1536,\n *   distanceMetric: 'cosine'\n * })\n *\n * // Access vector operations via index\n * const index = bucket.index('documents')\n * await index.putVectors({\n *   vectors: [\n *     { key: 'doc-1', data: { float32: [...] }, metadata: { title: 'Intro' } }\n *   ]\n * })\n *\n * // Query similar vectors\n * const { data } = await index.queryVectors({\n *   queryVector: { float32: [...] },\n *   topK: 5,\n *   returnDistance: true\n * })\n * ```\n */\nexport class StorageVectorsClient extends VectorBucketApi {\n  /**\n   * @alpha\n   *\n   * Creates a StorageVectorsClient that can manage buckets, indexes, and vectors.\n   *\n   * **Public alpha:** This API is part of a public alpha release and may not be available to your account type.\n   *\n   * @category Storage\n   * @subcategory Vector Buckets\n   * @param url - Base URL of the Storage Vectors REST API.\n   * @param options.headers - Optional headers (for example `Authorization`) applied to every request.\n   * @param options.fetch - Optional custom `fetch` implementation for non-browser runtimes.\n   *\n   * @example Using supabase-js (recommended)\n   * ```typescript\n   * import { createClient } from '@supabase/supabase-js'\n   *\n   * const supabase = createClient('https://xyzcompany.supabase.co', 'your-publishable-key')\n   * const bucket = supabase.storage.vectors.from('embeddings-prod')\n   * ```\n   *\n   * @example Standalone import for bundle-sensitive environments\n   * ```typescript\n   * import { StorageVectorsClient } from '@supabase/storage-js'\n   *\n   * const client = new StorageVectorsClient(url, options)\n   * ```\n   */\n  constructor(url: string, options: StorageVectorsClientOptions = {}) {\n    super(url, options.headers || {}, options.fetch)\n  }\n\n  /**\n   *\n   * @alpha\n   *\n   * Access operations for a specific vector bucket\n   * Returns a scoped client for index and vector operations within the bucket\n   *\n   * **Public alpha:** This API is part of a public alpha release and may not be available to your account type.\n   *\n   * @category Storage\n   * @subcategory Vector Buckets\n   * @param vectorBucketName - Name of the vector bucket\n   * @returns Bucket-scoped client with index and vector operations\n   *\n   * @example Accessing a vector bucket\n   * ```typescript\n   * const bucket = supabase.storage.vectors.from('embeddings-prod')\n   * ```\n   */\n  from(vectorBucketName: string): VectorBucketScope {\n    return new VectorBucketScope(this.url, this.headers, vectorBucketName, this.fetch)\n  }\n\n  /**\n   *\n   * @alpha\n   *\n   * Creates a new vector bucket\n   * Vector buckets are containers for vector indexes and their data\n   *\n   * **Public alpha:** This API is part of a public alpha release and may not be available to your account type.\n   *\n   * @category Storage\n   * @subcategory Vector Buckets\n   * @param vectorBucketName - Unique name for the vector bucket\n   * @returns Promise with empty response on success or error\n   *\n   * @example Creating a vector bucket\n   * ```typescript\n   * const { data, error } = await supabase\n   *   .storage\n   *   .vectors\n   *   .createBucket('embeddings-prod')\n   * ```\n   */\n  async createBucket(vectorBucketName: string): Promise<ApiResponse<undefined>> {\n    return super.createBucket(vectorBucketName)\n  }\n\n  /**\n   *\n   * @alpha\n   *\n   * Retrieves metadata for a specific vector bucket\n   *\n   * **Public alpha:** This API is part of a public alpha release and may not be available to your account type.\n   *\n   * @category Storage\n   * @subcategory Vector Buckets\n   * @param vectorBucketName - Name of the vector bucket\n   * @returns Promise with bucket metadata or error\n   *\n   * @example Get bucket metadata\n   * ```typescript\n   * const { data, error } = await supabase\n   *   .storage\n   *   .vectors\n   *   .getBucket('embeddings-prod')\n   *\n   * console.log('Bucket created:', data?.vectorBucket.creationTime)\n   * ```\n   */\n  async getBucket(vectorBucketName: string): Promise<ApiResponse<{ vectorBucket: VectorBucket }>> {\n    return super.getBucket(vectorBucketName)\n  }\n\n  /**\n   *\n   * @alpha\n   *\n   * Lists all vector buckets with optional filtering and pagination\n   *\n   * **Public alpha:** This API is part of a public alpha release and may not be available to your account type.\n   *\n   * @category Storage\n   * @subcategory Vector Buckets\n   * @param options - Optional filters (prefix, maxResults, nextToken)\n   * @returns Promise with list of buckets or error\n   *\n   * @example List vector buckets\n   * ```typescript\n   * const { data, error } = await supabase\n   *   .storage\n   *   .vectors\n   *   .listBuckets({ prefix: 'embeddings-' })\n   *\n   * data?.vectorBuckets.forEach(bucket => {\n   *   console.log(bucket.vectorBucketName)\n   * })\n   * ```\n   */\n  async listBuckets(\n    options: ListVectorBucketsOptions = {}\n  ): Promise<ApiResponse<ListVectorBucketsResponse>> {\n    return super.listBuckets(options)\n  }\n\n  /**\n   *\n   * @alpha\n   *\n   * Deletes a vector bucket (bucket must be empty)\n   * All indexes must be deleted before deleting the bucket\n   *\n   * **Public alpha:** This API is part of a public alpha release and may not be available to your account type.\n   *\n   * @category Storage\n   * @subcategory Vector Buckets\n   * @param vectorBucketName - Name of the vector bucket to delete\n   * @returns Promise with empty response on success or error\n   *\n   * @example Delete a vector bucket\n   * ```typescript\n   * const { data, error } = await supabase\n   *   .storage\n   *   .vectors\n   *   .deleteBucket('embeddings-old')\n   * ```\n   */\n  async deleteBucket(vectorBucketName: string): Promise<ApiResponse<undefined>> {\n    return super.deleteBucket(vectorBucketName)\n  }\n}\n\n/**\n *\n * @alpha\n *\n * Scoped client for operations within a specific vector bucket\n * Provides index management and access to vector operations\n *\n * **Public alpha:** This API is part of a public alpha release and may not be available to your account type.\n */\nexport class VectorBucketScope extends VectorIndexApi {\n  private vectorBucketName: string\n\n  /**\n   * @alpha\n   *\n   * Creates a helper that automatically scopes all index operations to the provided bucket.\n   *\n   * **Public alpha:** This API is part of a public alpha release and may not be available to your account type.\n   *\n   * @category Storage\n   * @subcategory Vector Buckets\n   * @example Creating a vector bucket scope\n   * ```typescript\n   * const bucket = supabase.storage.vectors.from('embeddings-prod')\n   * ```\n   */\n  constructor(\n    url: string,\n    headers: { [key: string]: string },\n    vectorBucketName: string,\n    fetch?: Fetch\n  ) {\n    super(url, headers, fetch)\n    this.vectorBucketName = vectorBucketName\n  }\n\n  /**\n   *\n   * @alpha\n   *\n   * Creates a new vector index in this bucket\n   * Convenience method that automatically includes the bucket name\n   *\n   * **Public alpha:** This API is part of a public alpha release and may not be available to your account type.\n   *\n   * @category Storage\n   * @subcategory Vector Buckets\n   * @param options - Index configuration (vectorBucketName is automatically set)\n   * @returns Promise with empty response on success or error\n   *\n   * @example Creating a vector index\n   * ```typescript\n   * const bucket = supabase.storage.vectors.from('embeddings-prod')\n   * await bucket.createIndex({\n   *   indexName: 'documents-openai',\n   *   dataType: 'float32',\n   *   dimension: 1536,\n   *   distanceMetric: 'cosine',\n   *   metadataConfiguration: {\n   *     nonFilterableMetadataKeys: ['raw_text']\n   *   }\n   * })\n   * ```\n   */\n  override async createIndex(options: Omit<CreateIndexOptions, 'vectorBucketName'>) {\n    return super.createIndex({\n      ...options,\n      vectorBucketName: this.vectorBucketName,\n    })\n  }\n\n  /**\n   *\n   * @alpha\n   *\n   * Lists indexes in this bucket\n   * Convenience method that automatically includes the bucket name\n   *\n   * **Public alpha:** This API is part of a public alpha release and may not be available to your account type.\n   *\n   * @category Storage\n   * @subcategory Vector Buckets\n   * @param options - Listing options (vectorBucketName is automatically set)\n   * @returns Promise with response containing indexes array and pagination token or error\n   *\n   * @example List indexes\n   * ```typescript\n   * const bucket = supabase.storage.vectors.from('embeddings-prod')\n   * const { data } = await bucket.listIndexes({ prefix: 'documents-' })\n   * ```\n   */\n  override async listIndexes(options: Omit<ListIndexesOptions, 'vectorBucketName'> = {}) {\n    return super.listIndexes({\n      ...options,\n      vectorBucketName: this.vectorBucketName,\n    })\n  }\n\n  /**\n   *\n   * @alpha\n   *\n   * Retrieves metadata for a specific index in this bucket\n   * Convenience method that automatically includes the bucket name\n   *\n   * **Public alpha:** This API is part of a public alpha release and may not be available to your account type.\n   *\n   * @category Storage\n   * @subcategory Vector Buckets\n   * @param indexName - Name of the index to retrieve\n   * @returns Promise with index metadata or error\n   *\n   * @example Get index metadata\n   * ```typescript\n   * const bucket = supabase.storage.vectors.from('embeddings-prod')\n   * const { data } = await bucket.getIndex('documents-openai')\n   * console.log('Dimension:', data?.index.dimension)\n   * ```\n   */\n  override async getIndex(indexName: string) {\n    return super.getIndex(this.vectorBucketName, indexName)\n  }\n\n  /**\n   *\n   * @alpha\n   *\n   * Deletes an index from this bucket\n   * Convenience method that automatically includes the bucket name\n   *\n   * **Public alpha:** This API is part of a public alpha release and may not be available to your account type.\n   *\n   * @category Storage\n   * @subcategory Vector Buckets\n   * @param indexName - Name of the index to delete\n   * @returns Promise with empty response on success or error\n   *\n   * @example Delete an index\n   * ```typescript\n   * const bucket = supabase.storage.vectors.from('embeddings-prod')\n   * await bucket.deleteIndex('old-index')\n   * ```\n   */\n  override async deleteIndex(indexName: string) {\n    return super.deleteIndex(this.vectorBucketName, indexName)\n  }\n\n  /**\n   *\n   * @alpha\n   *\n   * Access operations for a specific index within this bucket\n   * Returns a scoped client for vector data operations\n   *\n   * **Public alpha:** This API is part of a public alpha release and may not be available to your account type.\n   *\n   * @category Storage\n   * @subcategory Vector Buckets\n   * @param indexName - Name of the index\n   * @returns Index-scoped client with vector data operations\n   *\n   * @example Accessing an index\n   * ```typescript\n   * const index = supabase.storage.vectors.from('embeddings-prod').index('documents-openai')\n   *\n   * // Insert vectors\n   * await index.putVectors({\n   *   vectors: [\n   *     { key: 'doc-1', data: { float32: [...] }, metadata: { title: 'Intro' } }\n   *   ]\n   * })\n   *\n   * // Query similar vectors\n   * const { data } = await index.queryVectors({\n   *   queryVector: { float32: [...] },\n   *   topK: 5\n   * })\n   * ```\n   */\n  index(indexName: string): VectorIndexScope {\n    return new VectorIndexScope(\n      this.url,\n      this.headers,\n      this.vectorBucketName,\n      indexName,\n      this.fetch\n    )\n  }\n}\n\n/**\n *\n * @alpha\n *\n * Scoped client for operations within a specific vector index\n * Provides vector data operations (put, get, list, query, delete)\n *\n * **Public alpha:** This API is part of a public alpha release and may not be available to your account type.\n */\nexport class VectorIndexScope extends VectorDataApi {\n  private vectorBucketName: string\n  private indexName: string\n\n  /**\n   *\n   * @alpha\n   *\n   * Creates a helper that automatically scopes all vector operations to the provided bucket/index names.\n   *\n   * **Public alpha:** This API is part of a public alpha release and may not be available to your account type.\n   *\n   * @category Storage\n   * @subcategory Vector Buckets\n   * @example Creating a vector index scope\n   * ```typescript\n   * const index = supabase.storage.vectors.from('embeddings-prod').index('documents-openai')\n   * ```\n   */\n  constructor(\n    url: string,\n    headers: { [key: string]: string },\n    vectorBucketName: string,\n    indexName: string,\n    fetch?: Fetch\n  ) {\n    super(url, headers, fetch)\n    this.vectorBucketName = vectorBucketName\n    this.indexName = indexName\n  }\n\n  /**\n   *\n   * @alpha\n   *\n   * Inserts or updates vectors in this index\n   * Convenience method that automatically includes bucket and index names\n   *\n   * **Public alpha:** This API is part of a public alpha release and may not be available to your account type.\n   *\n   * @category Storage\n   * @subcategory Vector Buckets\n   * @param options - Vector insertion options (bucket and index names automatically set)\n   * @returns Promise with empty response on success or error\n   *\n   * @example Insert vectors into an index\n   * ```typescript\n   * const index = supabase.storage.vectors.from('embeddings-prod').index('documents-openai')\n   * await index.putVectors({\n   *   vectors: [\n   *     {\n   *       key: 'doc-1',\n   *       data: { float32: [0.1, 0.2, ...] },\n   *       metadata: { title: 'Introduction', page: 1 }\n   *     }\n   *   ]\n   * })\n   * ```\n   */\n  override async putVectors(options: Omit<PutVectorsOptions, 'vectorBucketName' | 'indexName'>) {\n    return super.putVectors({\n      ...options,\n      vectorBucketName: this.vectorBucketName,\n      indexName: this.indexName,\n    })\n  }\n\n  /**\n   *\n   * @alpha\n   *\n   * Retrieves vectors by keys from this index\n   * Convenience method that automatically includes bucket and index names\n   *\n   * **Public alpha:** This API is part of a public alpha release and may not be available to your account type.\n   *\n   * @category Storage\n   * @subcategory Vector Buckets\n   * @param options - Vector retrieval options (bucket and index names automatically set)\n   * @returns Promise with response containing vectors array or error\n   *\n   * @example Get vectors by keys\n   * ```typescript\n   * const index = supabase.storage.vectors.from('embeddings-prod').index('documents-openai')\n   * const { data } = await index.getVectors({\n   *   keys: ['doc-1', 'doc-2'],\n   *   returnMetadata: true\n   * })\n   * ```\n   */\n  override async getVectors(options: Omit<GetVectorsOptions, 'vectorBucketName' | 'indexName'>) {\n    return super.getVectors({\n      ...options,\n      vectorBucketName: this.vectorBucketName,\n      indexName: this.indexName,\n    })\n  }\n\n  /**\n   *\n   * @alpha\n   *\n   * Lists vectors in this index with pagination\n   * Convenience method that automatically includes bucket and index names\n   *\n   * **Public alpha:** This API is part of a public alpha release and may not be available to your account type.\n   *\n   * @category Storage\n   * @subcategory Vector Buckets\n   * @param options - Listing options (bucket and index names automatically set)\n   * @returns Promise with response containing vectors array and pagination token or error\n   *\n   * @example List vectors with pagination\n   * ```typescript\n   * const index = supabase.storage.vectors.from('embeddings-prod').index('documents-openai')\n   * const { data } = await index.listVectors({\n   *   maxResults: 500,\n   *   returnMetadata: true\n   * })\n   * ```\n   */\n  override async listVectors(\n    options: Omit<ListVectorsOptions, 'vectorBucketName' | 'indexName'> = {}\n  ) {\n    return super.listVectors({\n      ...options,\n      vectorBucketName: this.vectorBucketName,\n      indexName: this.indexName,\n    })\n  }\n\n  /**\n   *\n   * @alpha\n   *\n   * Queries for similar vectors in this index\n   * Convenience method that automatically includes bucket and index names\n   *\n   * **Public alpha:** This API is part of a public alpha release and may not be available to your account type.\n   *\n   * @category Storage\n   * @subcategory Vector Buckets\n   * @param options - Query options (bucket and index names automatically set)\n   * @returns Promise with response containing vectors ordered by distance, an optional pagination token, or an error\n   *\n   * @example Query similar vectors\n   * ```typescript\n   * const index = supabase.storage.vectors.from('embeddings-prod').index('documents-openai')\n   * const { data } = await index.queryVectors({\n   *   queryVector: { float32: [0.1, 0.2, ...] },\n   *   topK: 5,\n   *   filter: { category: 'technical' },\n   *   returnDistance: true,\n   *   returnMetadata: true\n   * })\n   * ```\n   */\n  override async queryVectors(\n    options: Omit<QueryVectorsOptions, 'vectorBucketName' | 'indexName'>\n  ) {\n    return super.queryVectors({\n      ...options,\n      vectorBucketName: this.vectorBucketName,\n      indexName: this.indexName,\n    })\n  }\n\n  /**\n   *\n   * @alpha\n   *\n   * Deletes vectors by keys from this index\n   * Convenience method that automatically includes bucket and index names\n   *\n   * **Public alpha:** This API is part of a public alpha release and may not be available to your account type.\n   *\n   * @category Storage\n   * @subcategory Vector Buckets\n   * @param options - Deletion options (bucket and index names automatically set)\n   * @returns Promise with empty response on success or error\n   *\n   * @example Delete vectors by keys\n   * ```typescript\n   * const index = supabase.storage.vectors.from('embeddings-prod').index('documents-openai')\n   * await index.deleteVectors({\n   *   keys: ['doc-1', 'doc-2', 'doc-3']\n   * })\n   * ```\n   */\n  override async deleteVectors(\n    options: Omit<DeleteVectorsOptions, 'vectorBucketName' | 'indexName'>\n  ) {\n    return super.deleteVectors({\n      ...options,\n      vectorBucketName: this.vectorBucketName,\n      indexName: this.indexName,\n    })\n  }\n}\n", "import StorageFileApi from './packages/StorageFileApi'\nimport StorageBucketApi from './packages/StorageBucketApi'\nimport StorageAnalyticsClient from './packages/StorageAnalyticsClient'\nimport { Fetch } from './lib/common/fetch'\nimport { StorageVectorsClient } from './packages/StorageVectorsClient'\n\nexport interface StorageClientOptions {\n  useNewHostname?: boolean\n}\n\nexport class StorageClient extends StorageBucketApi {\n  /**\n   * Creates a client for Storage buckets, files, analytics, and vectors.\n   *\n   * @category Storage\n   * @subcategory File Buckets\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 avatars = supabase.storage.from('avatars')\n   * ```\n   *\n   * @example Standalone import for bundle-sensitive environments\n   * ```ts\n   * import { StorageClient } from '@supabase/storage-js'\n   *\n   * const storage = new StorageClient('https://xyzcompany.supabase.co/storage/v1', {\n   *   apikey: 'your-publishable-key',\n   * })\n   * const avatars = storage.from('avatars')\n   * ```\n   */\n  constructor(\n    url: string,\n    headers: { [key: string]: string } = {},\n    fetch?: Fetch,\n    opts?: StorageClientOptions\n  ) {\n    super(url, headers, fetch, opts)\n  }\n\n  /**\n   * Perform file operation in a bucket.\n   *\n   * @category Storage\n   * @subcategory File Buckets\n   *\n   * @param id The bucket id to operate on.\n   *\n   * @example Accessing a bucket\n   * ```typescript\n   * const avatars = supabase.storage.from('avatars')\n   * ```\n   */\n  from(id: string): StorageFileApi {\n    return new StorageFileApi(this.url, this.headers, id, this.fetch)\n  }\n\n  /**\n   *\n   * @alpha\n   *\n   * Access vector storage operations.\n   *\n   * **Public alpha:** This API is part of a public alpha release and may not be available to your account type.\n   *\n   * @category Storage\n   * @subcategory Vector Buckets\n   *\n   * @returns A StorageVectorsClient instance configured with the current storage settings.\n   */\n  get vectors(): StorageVectorsClient {\n    return new StorageVectorsClient(this.url + '/vector', {\n      headers: this.headers,\n      fetch: this.fetch,\n    })\n  }\n\n  /**\n   *\n   * @alpha\n   *\n   * Access analytics storage operations using Iceberg tables.\n   *\n   * **Public alpha:** This API is part of a public alpha release and may not be available to your account type.\n   *\n   * @category Storage\n   * @subcategory Analytics Buckets\n   *\n   * @returns A StorageAnalyticsClient instance configured with the current storage settings.\n   */\n  get analytics(): StorageAnalyticsClient {\n    return new StorageAnalyticsClient(this.url + '/iceberg', this.headers, this.fetch)\n  }\n}\n", "// 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.118.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 \u2014 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 & {}) | 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 & {}) | 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' && error !== null && '__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) && 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) && 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 & {}) | 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) && 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 & {}) | 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) && 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) && 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) && 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 & {}) | 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) && 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 = (() => {\n  const charMap: number[] = new Array(128)\n\n  for (let i = 0; i < charMap.length; i += 1) {\n    charMap[i] = -1\n  }\n\n  for (let i = 0; i < IGNORE_BASE64URL.length; i += 1) {\n    charMap[IGNORE_BASE64URL[i].charCodeAt(0)] = -2\n  }\n\n  for (let i = 0; i < 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) => void\n) {\n  if (byte !== null) {\n    state.queue = (state.queue << 8) | byte\n    state.queuedBits += 8\n\n    while (state.queuedBits >= 6) {\n      const pos = (state.queue >> (state.queuedBits - 6)) & 63\n      emit(TO_BASE64URL[pos])\n      state.queuedBits -= 6\n    }\n  } else if (state.queuedBits > 0) {\n    state.queue = state.queue << (6 - state.queuedBits)\n    state.queuedBits = 6\n\n    while (state.queuedBits >= 6) {\n      const pos = (state.queue >> (state.queuedBits - 6)) & 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) => void\n) {\n  const bits = FROM_BASE64URL[charCode]\n\n  if (bits > -1) {\n    // valid Base64-URL character\n    state.queue = (state.queue << 6) | bits\n    state.queuedBits += 6\n\n    while (state.queuedBits >= 8) {\n      emit((state.queue >> (state.queuedBits - 8)) & 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) => {\n    base64.push(char)\n  }\n\n  const state = { queue: 0, queuedBits: 0 }\n\n  stringToUTF8(str, (byte: number) => {\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) => {\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) => {\n    stringFromUTF8(byte, utf8State, utf8Emit)\n  }\n\n  for (let i = 0; i < 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) => void) {\n  if (codepoint <= 0x7f) {\n    emit(codepoint)\n    return\n  } else if (codepoint <= 0x7ff) {\n    emit(0xc0 | (codepoint >> 6))\n    emit(0x80 | (codepoint & 0x3f))\n    return\n  } else if (codepoint <= 0xffff) {\n    emit(0xe0 | (codepoint >> 12))\n    emit(0x80 | ((codepoint >> 6) & 0x3f))\n    emit(0x80 | (codepoint & 0x3f))\n    return\n  } else if (codepoint <= 0x10ffff) {\n    emit(0xf0 | (codepoint >> 18))\n    emit(0x80 | ((codepoint >> 12) & 0x3f))\n    emit(0x80 | ((codepoint >> 6) & 0x3f))\n    emit(0x80 | (codepoint & 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) => void) {\n  for (let i = 0; i < str.length; i += 1) {\n    let codepoint = str.charCodeAt(i)\n\n    if (codepoint > 0xd7ff && codepoint <= 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) & 0xffff\n      const lowSurrogate = (str.charCodeAt(i + 1) - 0xdc00) & 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) => void\n) {\n  if (state.utf8seq === 0) {\n    if (byte <= 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 < 6; leadingBit += 1) {\n      if (((byte >> (7 - leadingBit)) & 1) === 0) {\n        state.utf8seq = leadingBit\n        break\n      }\n    }\n\n    if (state.utf8seq === 2) {\n      state.codepoint = byte & 31\n    } else if (state.utf8seq === 3) {\n      state.codepoint = byte & 15\n    } else if (state.utf8seq === 4) {\n      state.codepoint = byte & 7\n    } else {\n      throw new Error('Invalid UTF-8 sequence')\n    }\n\n    state.utf8seq -= 1\n  } else if (state.utf8seq > 0) {\n    if (byte <= 0x7f) {\n      throw new Error('Invalid UTF-8 sequence')\n    }\n\n    state.codepoint = (state.codepoint << 6) | (byte & 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) => {\n    result.push(byte)\n  }\n\n  for (let i = 0; i < 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) => 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) => {\n    result.push(char)\n  }\n\n  bytes.forEach((byte) => 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 = () => typeof window !== 'undefined' && 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 = () => {\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 && url.hash[0] === '#') {\n    try {\n      const hashSearchParams = new URLSearchParams(url.hash.substring(1))\n      hashSearchParams.forEach((value, key) => {\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) => {\n    result[key] = value\n  })\n\n  return result\n}\n\ntype Fetch = typeof fetch\n\nexport const resolveFetch = (customFetch?: Fetch): Fetch => {\n  if (customFetch) {\n    return (...args) => customFetch(...args)\n  }\n  return (...args) => fetch(...args)\n}\n\nexport const looksLikeFetchResponse = (maybeResponse: unknown): maybeResponse is Response => {\n  return (\n    typeof maybeResponse === 'object' &&\n    maybeResponse !== null &&\n    'status' in maybeResponse &&\n    'ok' in maybeResponse &&\n    'json' in maybeResponse &&\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<void> => {\n  await storage.setItem(key, JSON.stringify(data))\n}\n\nexport const getItemAsync = async (storage: SupportedStorage, key: string): Promise<unknown> => {\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<void> => {\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<T = any> {\n  public static promiseConstructor: PromiseConstructor = Promise\n\n  public readonly promise!: PromiseLike<T>\n\n  public readonly resolve!: (value?: T | PromiseLike<T>) => void\n\n  public readonly reject!: (reason?: any) => 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) => {\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 < 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<null> {\n  return await new Promise((accept) => {\n    setTimeout(() => 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<T>(\n  fn: (attempt: number) => Promise<T>,\n  isRetryable: (attempt: number, error: any | null, result?: T) => boolean\n): Promise<T> {\n  const promise = new Promise<T>((accept, reject) => {\n    // eslint-disable-next-line @typescript-eslint/no-extra-semi\n    ;(async () => {\n      for (let attempt = 0; attempt < 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 < 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) => String.fromCharCode(c))\n    .join('')\n}\n\nexport async function generatePKCEChallenge(verifier: string) {\n  const hasCryptoSupport =\n    typeof crypto !== 'undefined' &&\n    typeof crypto.subtle !== 'undefined' &&\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' && PKCE_FLOW_ID_PATTERN.test(flowId) ? flowId : null\n}\n\nexport function generatePKCEFlowId(): string {\n  if (typeof crypto !== 'undefined' && 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 < 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 `<key>.<number>` 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) =>\n  `${storageKey}-flow-${flowId}-code-verifier`\n\nconst pkceFlowIndexKey = (storageKey: string) => `${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<string[]> {\n  const index = await getItemAsync(storage, pkceFlowIndexKey(storageKey))\n  return Array.isArray(index)\n    ? index.filter((id): id is string => 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 \u2014 its slot\n * is addressed directly by key \u2014 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) => void\n): Promise<void> {\n  await setItemAsync(storage, pkceVerifierSlotKey(storageKey, flowId), verifier)\n\n  const index = (await getPKCEFlowIndex(storage, storageKey)).filter((id) => id !== flowId)\n  index.push(flowId)\n  while (index.length > 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 \u2014 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<{ verifier: string | null; flowId: string | null }> {\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<void> {\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) => id !== flowId)\n  if (remaining.length !== index.length) {\n    if (remaining.length > 0) {\n      await setItemAsync(storage, pkceFlowIndexKey(storageKey), remaining)\n    } else {\n      await removeItemAsync(storage, pkceFlowIndexKey(storageKey))\n    }\n  }\n\n  if (slotValue != null && 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) \u2014 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<void> {\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('&')\n      .filter(\n        (pair) =>\n          pair !== '' && pair !== PKCE_FLOW_ID_PARAM && !pair.startsWith(`${PKCE_FLOW_ID_PARAM}=`)\n      )\n    base = remaining.length > 0 ? `${path}?${remaining.join('&')}` : path\n  }\n\n  const separator = base.includes('?') ? '&' : '?'\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) => void\n): Promise<[string, string, string]> {\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 <= timeNow) {\n    throw new Error('JWT has expired')\n  }\n}\n\nexport function getAlgorithm(\n  alg: 'HS256' | 'RS256' | 'ES256' | (string & {})\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) => {\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) => {\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) => {\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) => {\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 && 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<T>(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 \u2014 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 \u2014 link properties + User fields flattened into one object. */\ntype GoTrueGenerateLinkData = GenerateLinkProperties & Record<string, any>\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 => {\n  if (typeof err === 'object' && err !== null) {\n    const e = err as Record<string, unknown>\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 \u2014 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 &&\n    responseAPIVersion.getTime() >= API_VERSIONS['2024-01-01'].timestamp &&\n    typeof data === 'object' &&\n    data &&\n    typeof data.code === 'string'\n  ) {\n    errorCode = data.code\n  } else if (typeof data === 'object' && data && 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' &&\n      data &&\n      typeof data.weak_password === 'object' &&\n      data.weak_password &&\n      Array.isArray(data.weak_password.reasons) &&\n      data.weak_password.reasons.length &&\n      data.weak_password.reasons.reduce((a: boolean, i: any) => a && 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) => {\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) => 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<any> {\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) \u2014 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 &&\n    data.weak_password &&\n    typeof data.weak_password === 'object' &&\n    Array.isArray(data.weak_password.reasons) &&\n    data.weak_password.reasons.length &&\n    data.weak_password.message &&\n    typeof data.weak_password.message === 'string' &&\n    data.weak_password.reasons.reduce((a: boolean, i: unknown) => a && 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<string, any>): 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 && !!data.refresh_token && !!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 = <R>(name: string, acquireTimeout: number, fn: () => Promise<R>) => Promise<R>\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) => {\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 }) => 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[]) => 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 \u2014 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 \u2014 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 \u2014 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 \u2014 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<T> = 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<T, K extends keyof T> = Omit<T, K>\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<T, ErrorType extends Error = AuthError> =\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<T> =\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<{\n  user: User | null\n  session: Session | null\n}>\n\nexport type AuthResponsePassword = RequestResultSafeDestructure<{\n  user: User | null\n  session: Session | null\n  weak_password?: WeakPassword | null\n}>\n\n/**\n * AuthOtpResponse is returned when OTP is used.\n *\n * {@link AuthResponse}\n */\nexport type AuthOtpResponse = RequestResultSafeDestructure<{\n  user: null\n  session: null\n  messageId?: string | null\n}>\n\nexport type AuthTokenResponse = RequestResultSafeDestructure<{\n  user: User\n  session: Session\n}>\n\nexport type AuthTokenResponsePassword = RequestResultSafeDestructure<{\n  user: User\n  session: Session\n  weakPassword?: WeakPassword\n}>\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 \u2014 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<{\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}>\n\nexport type UserResponse = RequestResultSafeDestructure<{\n  user: User\n}>\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 & {})\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<\n  Type extends FactorType = FactorType,\n  Status extends FactorVerificationStatus = (typeof FactorVerificationStatuses)[number],\n> = {\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<FactorType, 'verified'> | Factor<FactorType, 'unverified'>)[]\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<UserAttributes, 'data'> {\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 \"\u00B5s\"), \"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) => {}\n   */\n  callback: (event: AuthChangeEvent, session: Session | null) => void\n  /**\n   * Call this to remove the listener.\n   */\n  unsubscribe: () => 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 & {\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 & {\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 & {})\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 & {})\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[]) => Promise<SolanaSignInOutput | SolanaSignInOutput[]>\n  publicKey?: {\n    toBase58: () => string\n  } | null\n\n  signMessage?: (message: Uint8Array, encoding?: 'utf8' | string) => Promise<Uint8Array> | 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<\n          Omit<SolanaSignInInput, 'version' | 'chain' | 'domain' | 'uri' | 'statement'>\n        >\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<\n          Omit<EthereumSignInInput, 'version' | 'domain' | 'uri' | 'statement'>\n        >\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 & {})\nexport type EmailOtpType =\n  | 'signup'\n  | 'invite'\n  | 'magiclink'\n  | 'recovery'\n  | 'email_change'\n  | 'email'\n  | (string & {})\n\nexport type ResendParams =\n  | {\n      type: Extract<EmailOtpType, 'signup' | 'email_change'>\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<MobileOtpType, 'sms' | 'phone_change'>\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<GenerateLinkOptions, 'data' | 'redirectTo'>\n}\n\nexport type GenerateInviteOrMagiclinkParams = {\n  type: 'invite' | 'magiclink'\n  /** The user's email */\n  email: string\n  options?: Pick<GenerateLinkOptions, 'data' | 'redirectTo'>\n}\n\nexport type GenerateRecoveryLinkParams = {\n  type: 'recovery'\n  /** The user's email */\n  email: string\n  options?: Pick<GenerateLinkOptions, 'redirectTo'>\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<GenerateLinkOptions, 'redirectTo'>\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<{\n  properties: GenerateLinkProperties\n  user: User\n}>\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}&token={hashed_token}&redirect_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 & MFAVerifyTOTPParamFields\n\ntype MFAVerifyPhoneParamFields = MFAVerifyTOTPParamFields\n\nexport type MFAVerifyPhoneParams = MFAVerifyParamsBase & MFAVerifyPhoneParamFields\n\ntype MFAVerifyWebauthnParamFieldsBase = {\n  /** Relying party ID */\n  rpId: string\n  /** Relying party origins */\n  rpOrigins?: string[]\n}\n\ntype MFAVerifyWebauthnCredentialParamFields<T extends 'create' | 'request' = 'create' | 'request'> =\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<T extends 'create' | 'request' = 'create' | 'request'> = {\n  webauthn: MFAVerifyWebauthnParamFieldsBase & MFAVerifyWebauthnCredentialParamFields<T>\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<T extends 'create' | 'request' = 'create' | 'request'> =\n  MFAVerifyParamsBase & MFAVerifyWebauthnParamFields<T>\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<Channel extends MFATOTPChannel = MFATOTPChannel> = {\n  /** Messaging channel to use (e.g. whatsapp or sms). Only relevant for phone factors */\n  channel: Channel\n}\n\nexport type MFAChallengePhoneParams = MFAChallengeParamsBase & 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 & MFAChallengeWebauthnParamFields\n\nexport type MFAChallengeParams =\n  | MFAChallengeTOTPParams\n  | MFAChallengePhoneParams\n  | MFAChallengeWebauthnParams\n\ntype MFAChallengeAndVerifyParamsBase = Omit<MFAVerifyParamsBase, 'challengeId'>\n\ntype MFAChallengeAndVerifyTOTPParamFields = MFAVerifyTOTPParamFields\n\ntype MFAChallengeAndVerifyTOTPParams = MFAChallengeAndVerifyParamsBase &\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<AuthMFAVerifyResponseData>\n\nexport type AuthMFAEnrollResponse =\n  | AuthMFAEnrollTOTPResponse\n  | AuthMFAEnrollPhoneResponse\n  | AuthMFAEnrollWebauthnResponse\n\nexport type AuthMFAUnenrollResponse = RequestResult<{\n  /** ID of the factor that was successfully unenrolled. */\n  id: string\n}>\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<AuthMFARecoveryCodesStatusResponseData>\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<AuthMFARecoveryCodesGenerateResponseData>\n\ntype AuthMFAChallengeResponseBase<T extends FactorType> = {\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<\n  AuthMFAChallengeResponseBase<'totp'> & AuthMFAChallengeTOTPResponseFields\n>\n\ntype AuthMFAChallengePhoneResponseFields = {\n  /** no extra fields for now, kept for consistency and for possible future changes  */\n}\n\nexport type AuthMFAChallengePhoneResponse = RequestResult<\n  AuthMFAChallengeResponseBase<'phone'> & AuthMFAChallengePhoneResponseFields\n>\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<\n  AuthMFAChallengeResponseBase<'webauthn'> & AuthMFAChallengeWebauthnResponseFields\n>\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<'webauthn'> &\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<AuthMFAChallengeWebauthnResponseDataJSON>\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<T extends typeof FactorTypes = typeof FactorTypes> =\n  RequestResult<\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    } & {\n      [K in T[number]]: Factor<K, 'verified'>[]\n    }\n  >\n\nexport type AuthenticatorAssuranceLevels = 'aal1' | 'aal2' | (string & {})\n\nexport type AuthMFAGetAuthenticatorAssuranceLevelResponse = RequestResult<{\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}>\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: '<FACTOR_ID>',\n   *     type: 'recovery_code',\n   *     total: 10,\n   *     remaining: 7\n   *   },\n   *   error: null\n   * }\n   * ```\n   */\n  getStatus(): Promise<AuthMFARecoveryCodesStatusResponse>\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) => code.match(/.{1,4}/g).join('-'))\n   * ```\n   *\n   * @exampleResponse Generate recovery codes\n   * ```json\n   * {\n   *   data: {\n   *     id: '<FACTOR_ID>',\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<AuthMFARecoveryCodesGenerateResponse>\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: '<ACCESS_TOKEN>',\n   *     token_type: 'bearer',\n   *     expires_in: 3600,\n   *     refresh_token: '<REFRESH_TOKEN>',\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: '<TOTP_FACTOR_ID>',\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: '<RECOVERY_CODES_FACTOR_ID>',\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<AuthMFAVerifyResponse>\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: '<FACTOR_ID>',\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<AuthMFARecoveryCodesGenerateResponse>\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: '<FACTOR_ID>'\n   *   },\n   *   error: null\n   * }\n   * ```\n   */\n  unenroll(): Promise<AuthMFAUnenrollResponse>\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   * <Image src={data.totp.qr_code} alt={data.totp.uri} layout=\"fill\"></Image>\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: '<ID>',\n   *     type: 'totp'\n   *     totp: {\n   *       qr_code: '<QR_CODE_AS_SVG_DATA>',\n   *       secret: '<SECRET>',\n   *       uri: '<URI>',\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: '<ID>',\n   *     type: 'phone',\n   *     friendly_name?: 'Important app',\n   *     phone: '+5787123456'\n   *   },\n   *   error: null\n   * }\n   * ```\n   */\n  enroll(params: MFAEnrollTOTPParams): Promise<AuthMFAEnrollTOTPResponse>\n  enroll(params: MFAEnrollPhoneParams): Promise<AuthMFAEnrollPhoneResponse>\n  enroll(params: MFAEnrollWebauthnParams): Promise<AuthMFAEnrollWebauthnResponse>\n  enroll(params: MFAEnrollParams): Promise<AuthMFAEnrollResponse>\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: '<ID>',\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: '<ID>',\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: '<ID>',\n   *     expires_at: 1700000000\n   *   },\n   *   error: null\n   * }\n   * ```\n   */\n  challenge(params: MFAChallengeTOTPParams): Promise<Prettify<AuthMFAChallengeTOTPResponse>>\n  challenge(params: MFAChallengePhoneParams): Promise<Prettify<AuthMFAChallengePhoneResponse>>\n  challenge(params: MFAChallengeWebauthnParams): Promise<Prettify<AuthMFAChallengeWebauthnResponse>>\n  challenge(params: MFAChallengeParams): Promise<AuthMFAChallengeResponse>\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: '<ACCESS_TOKEN>',\n   *     token_type: 'Bearer',\n   *     expires_in: 3600,\n   *     refresh_token: '<REFRESH_TOKEN>',\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\": '<ID>',\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<AuthMFAVerifyResponse>\n  verify(params: MFAVerifyPhoneParams): Promise<AuthMFAVerifyResponse>\n  verify(params: MFAVerifyWebauthnParams): Promise<AuthMFAVerifyResponse>\n  verify(params: MFAVerifyParams): Promise<AuthMFAVerifyResponse>\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: '<FACTOR_ID>'\n   *   },\n   *   error: null\n   * }\n   * ```\n   */\n  unenroll(params: MFAUnenrollParams): Promise<AuthMFAUnenrollResponse>\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: '<ACCESS_TOKEN>',\n   *     token_type: 'Bearer',\n   *     expires_in: 3600,\n   *     refresh_token: '<REFRESH_TOKEN>',\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\": '<ID>',\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<AuthMFAVerifyResponse>\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<AuthMFAListFactorsResponse>\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 login,\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<AuthMFAGetAuthenticatorAssuranceLevelResponse>\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<{\n  /** ID of the factor that was successfully deleted. */\n  id: string\n}>\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<{\n  /** All factors attached to the user. */\n  factors: Factor[]\n}>\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: '<ID>',\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<AuthMFAAdminListFactorsResponse>\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<AuthMFAAdminDeleteFactorResponse>\n}\n\ntype AnyFunction = (...args: any[]) => any\ntype MaybePromisify<T> = T | Promise<T>\n\ntype PromisifyMethods<T> = {\n  [K in keyof T]: T[K] extends AnyFunction\n    ? (...args: Parameters<T[K]>) => MaybePromisify<ReturnType<T[K]>>\n    : T[K]\n}\n\nexport type SupportedStorage = PromisifyMethods<\n  Pick<Storage, 'getItem' | 'setItem' | 'removeItem'>\n> & {\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<Session>\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<T extends FactorType> = {\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<'totp'> & 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<'phone'> & 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<'webauthn'> & MFAEnrollWebauthnFields\n\ntype AuthMFAEnrollResponseBase<T extends FactorType> = {\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<\n  AuthMFAEnrollResponseBase<'totp'> & AuthMFAEnrollTOTPResponseFields\n>\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<\n  AuthMFAEnrollResponseBase<'phone'> & AuthMFAEnrollPhoneResponseFields\n>\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<\n  AuthMFAEnrollResponseBase<'webauthn'> & AuthMFAEnrollWebauthnFields\n>\n\nexport type JwtHeader = {\n  alg: 'RS256' | 'ES256' | 'HS256' | (string & {})\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 & {})\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 & {})\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<OAuthClient>\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 } & 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<OAuthClientListResponse>\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<OAuthClientResponse>\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<OAuthClientResponse>\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<OAuthClientResponse>\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<{ data: null; error: AuthError | null }>\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<OAuthClientResponse>\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<string, any>\n  /** Additional parameters sent with the authorization request */\n  authorization_params?: Record<string, string>\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<string, any>\n  /** Additional parameters sent with the authorization request */\n  authorization_params?: Record<string, string>\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<string, any>\n  /** Additional parameters sent with the authorization request */\n  authorization_params?: Record<string, string>\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<CustomOAuthProvider>\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<CustomProviderListResponse>\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<CustomProviderResponse>\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<CustomProviderResponse>\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<CustomProviderResponse>\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<{ data: null; error: AuthError | null }>\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&state=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<\n  OAuthAuthorizationDetails | OAuthRedirect\n>\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<OAuthRedirect>\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<OAuthGrant[]>\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<{}>\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<AuthOAuthAuthorizationDetailsResponse>\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<AuthOAuthConsentResponse>\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<AuthOAuthConsentResponse>\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<AuthOAuthGrantsResponse>\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<AuthOAuthRevokeGrantResponse>\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<PasskeyRegistrationOptionsResponse>\nexport type AuthPasskeyRegistrationVerifyResponse = RequestResult<\n  PasskeyMetadata,\n  WebAuthnError | AuthError\n>\nexport type AuthPasskeyAuthenticationOptionsResponse =\n  RequestResult<PasskeyAuthenticationOptionsResponse>\nexport type AuthPasskeyAuthenticationVerifyResponse = RequestResult<\n  { session: Session | null; user: User | null },\n  WebAuthnError | AuthError\n>\nexport type AuthPasskeyListResponse = RequestResult<PasskeyListItem[]>\nexport type AuthPasskeyUpdateResponse = RequestResult<PasskeyListItem>\nexport type AuthPasskeyDeleteResponse = RequestResult<null>\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<AuthPasskeyRegistrationOptionsResponse>\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<AuthPasskeyRegistrationVerifyResponse>\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<AuthPasskeyAuthenticationOptionsResponse>\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<AuthPasskeyAuthenticationVerifyResponse>\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<AuthPasskeyListResponse>\n\n  /**\n   * Updates a passkey's friendly name.\n   *\n   * @category Auth\n   * @subcategory Auth Passkey\n   */\n  update(params: PasskeyUpdateParams): Promise<AuthPasskeyUpdateResponse>\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<AuthPasskeyDeleteResponse>\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<AuthPasskeyListResponse>\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<AuthPasskeyDeleteResponse>\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<{ data: null; error: AuthError | null }> {\n    if (SIGN_OUT_SCOPES.indexOf(scope) < 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<UserResponse> {\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\": \"<LINK_TO_SEND_TO_USER>\",\n   *       \"email_otp\": \"999999\",\n   *       \"hashed_token\": \"<HASHED_TOKEN\",\n   *       \"redirect_to\": \"<REDIRECT_URL>\",\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<GenerateLinkResponse> {\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<UserResponse> {\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<\n    | { data: { users: User[]; aud: string } & Pagination; error: null }\n    | { data: { users: [] }; error: AuthError }\n  > {\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 > 0) {\n        links.forEach((link: string) => {\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<UserResponse> {\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<UserResponse> {\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   *\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   *   },\n   *   \"error\": null\n   * }\n   * ```\n   */\n  async deleteUser(id: string, shouldSoftDelete = false): Promise<UserResponse> {\n    validateUUID(id)\n\n    try {\n      return await _request(this.fetch, 'DELETE', `${this.url}/admin/users/${id}`, {\n        headers: this.headers,\n        body: {\n          should_soft_delete: shouldSoftDelete,\n        },\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  private async _listFactors(\n    params: AuthMFAAdminListFactorsParams\n  ): Promise<AuthMFAAdminListFactorsResponse> {\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) => {\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<AuthMFAAdminDeleteFactorResponse> {\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<OAuthClientListResponse> {\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 > 0) {\n        links.forEach((link: string) => {\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<OAuthClientResponse> {\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) => {\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<OAuthClientResponse> {\n    try {\n      return await _request(this.fetch, 'GET', `${this.url}/admin/oauth/clients/${clientId}`, {\n        headers: this.headers,\n        xform: (client: any) => {\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<OAuthClientResponse> {\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) => {\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<{ data: null; error: AuthError | null }> {\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<OAuthClientResponse> {\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) => {\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<CustomProviderListResponse> {\n    try {\n      const query: Record<string, string> = {}\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) => {\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<CustomProviderResponse> {\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) => {\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<CustomProviderResponse> {\n    try {\n      return await _request(this.fetch, 'GET', `${this.url}/admin/custom-providers/${identifier}`, {\n        headers: this.headers,\n        xform: (provider: any) => {\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<CustomProviderResponse> {\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) => {\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<{ data: null; error: AuthError | null }> {\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<AuthPasskeyListResponse> {\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) => ({ 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<AuthPasskeyDeleteResponse> {\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) => {\n      return store[key] || null\n    },\n\n    setItem: (key, value) => {\n      store[key] = value\n    },\n\n    removeItem: (key) => {\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 &&\n    supportsLocalStorage() &&\n    globalThis.localStorage &&\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<R>(\n  name: string,\n  acquireTimeout: number,\n  fn: () => Promise<R>\n): Promise<R> {\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<typeof setTimeout> | undefined\n\n  if (acquireTimeout > 0) {\n    acquireTimeoutTimer = setTimeout(() => {\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) => {\n        if (lock) {\n          // Lock acquired \u2014 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 && typeof e === 'object' && 'name' in e && e.name === 'AbortError') {\n      if (abortController.signal.aborted) {\n        // OUR timeout fired \u2014 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(() =>\n          globalThis.navigator.locks.request(\n            name,\n            {\n              mode: 'exclusive',\n              steal: true,\n            },\n            async (lock) => {\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 \u2014 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<any> } = {}\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 () => {\n *   await runMigration()\n * })\n * ```\n */\nexport async function processLock<R>(\n  name: string,\n  acquireTimeout: number,\n  fn: () => Promise<R>\n): Promise<R> {\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 () => {\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 () => {\n    let timeoutId: ReturnType<typeof setTimeout> | null = null\n\n    try {\n      // Wait for either previous operation or timeout\n      const timeoutPromise =\n        acquireTimeout >= 0\n          ? new Promise((_, reject) => {\n              timeoutId = setTimeout(() => {\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) => 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 () => {\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<event extends keyof EIP1193EventMap>(event: event, listener: EIP1193EventMap[event]): void\n  removeListener<event extends keyof EIP1193EventMap>(\n    event: event,\n    listener: EIP1193EventMap[event]\n  ): void\n}\n\nexport type EIP1193RequestFn = (args: { method: string; params?: unknown }) => Promise<unknown>\n\nexport type EIP1193Provider = EIP1193Events & {\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) => 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 && nonce.length < 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' && error !== null && '__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<CredentialCreationOptions, 'publicKey'> & {\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' &&\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) => 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 < 1 || publicKey.user.id.byteLength > 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<CredentialRequestOptions, 'publicKey'> & {\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' &&\n    'parseCreationOptionsFromJSON' in PublicKeyCredential &&\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 && excludeCredentials.length > 0) {\n    result.excludeCredentials = new Array(excludeCredentials.length)\n\n    for (let i = 0; i < 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' &&\n    'parseRequestOptionsFromJSON' in PublicKeyCredential &&\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 && allowCredentials.length > 0) {\n    result.allowCredentials = new Array(allowCredentials.length)\n\n    for (let i = 0; i < 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 && 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 & {\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 && 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 & {\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() &&\n    'PublicKeyCredential' in window &&\n    window.PublicKeyCredential &&\n    'credentials' in navigator &&\n    typeof navigator?.credentials?.create === 'function' &&\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<RequestResult<RegistrationCredential, WebAuthnError>>} 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<CredentialCreationOptions, 'publicKey'> & {\n    publicKey: PublicKeyCredentialCreationOptionsFuture\n  }\n): Promise<RequestResult<RegistrationCredential, WebAuthnError>> {\n  try {\n    const response = await navigator.credentials.create(\n      /** we assert the type here until typescript types are updated */\n      options as Parameters<typeof navigator.credentials.create>[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<RequestResult<AuthenticationCredential, WebAuthnError>>} 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<CredentialRequestOptions, 'publicKey'> & {\n    publicKey: PublicKeyCredentialRequestOptionsFuture\n  }\n): Promise<RequestResult<AuthenticationCredential, WebAuthnError>> {\n  try {\n    const response = await navigator.credentials.get(\n      /** we assert the type here until typescript types are updated */\n      options as Parameters<typeof navigator.credentials.get>[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<PublicKeyCredentialCreationOptionsFuture> = {\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<PublicKeyCredentialRequestOptionsFuture> = {\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<T>(...sources: Partial<T>[]): T {\n  const isObject = (val: unknown): val is Record<string, unknown> =>\n    val !== null && typeof val === 'object' && !Array.isArray(val)\n\n  const isArrayBufferLike = (val: unknown): val is ArrayBuffer | ArrayBufferView =>\n    val instanceof ArrayBuffer || ArrayBuffer.isView(val)\n\n  const result: Partial<T> = {}\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<PublicKeyCredentialCreationOptionsFuture>\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<PublicKeyCredentialRequestOptionsFuture>\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<MFAEnrollWebauthnParams, 'factorType'>} params - Enrollment parameters (friendlyName required)\n   * @returns {Promise<AuthMFAEnrollWebauthnResponse>} 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<MFAEnrollWebauthnParams, 'factorType'>\n  ): Promise<AuthMFAEnrollWebauthnResponse> {\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 & { 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<RequestResult>} 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 & { friendlyName?: string; signal?: AbortSignal },\n    overrides?:\n      | {\n          create?: Partial<PublicKeyCredentialCreationOptionsFuture>\n          request?: never\n        }\n      | {\n          create?: never\n          request?: Partial<PublicKeyCredentialRequestOptionsFuture>\n        }\n  ): Promise<\n    RequestResult<\n      { factorId: string; challengeId: string } & {\n        webauthn: StrictOmit<\n          MFAVerifyWebauthnParamFields<'create' | 'request'>['webauthn'],\n          'rpId' | 'rpOrigins'\n        >\n      },\n      WebAuthnError | AuthError\n    >\n  > {\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<T>['webauthn']} params.webauthn - WebAuthn credential response\n   * @returns {Promise<AuthMFAVerifyResponse>} 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<T extends 'create' | 'request'>({\n    challengeId,\n    factorId,\n    webauthn,\n  }: {\n    challengeId: string\n    factorId: string\n    webauthn: MFAVerifyWebauthnParams<T>['webauthn']\n  }): Promise<AuthMFAVerifyResponse> {\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<RequestResult<AuthMFAVerifyResponseData, WebAuthnError | AuthError>>} 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<RequestResult<AuthMFAVerifyResponseData, WebAuthnError | AuthError>> {\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<RequestResult<AuthMFAVerifyResponseData, WebAuthnError | AuthError>>} 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<PublicKeyCredentialCreationOptionsFuture>\n  ): Promise<RequestResult<AuthMFAVerifyResponseData, WebAuthnError | AuthError>> {\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) =>\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) =>\n                v.factor_type === 'webauthn' &&\n                v.friendly_name === friendlyName &&\n                v.status === 'unverified'\n            )\n          )\n          .then((factor) => (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<\n  Required<GoTrueClientOptions>,\n  'fetch' | 'storage' | 'userStorage' | 'lock'\n> = {\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<R>(name: string, acquireTimeout: number, fn: () => Promise<R>): Promise<R> {\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 \u2014 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<string, number> = {}\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<string | symbol, Subscription> = new Map()\n  protected autoRefreshTicker: ReturnType<typeof setInterval> | null = null\n  protected autoRefreshTickTimeout: ReturnType<typeof setTimeout> | null = null\n  protected visibilityChangedCallback: (() => Promise<any>) | null = null\n  protected refreshingDeferred: Deferred<CallRefreshTokenResult> | 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<InitializeResult> | 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 \u2014 they fire\n   * immediately. Flushed (in order) by `initialize()` after `initializePromise`\n   * settles.\n   */\n  private _pendingInitNotifications: Array<{\n    event: AuthChangeEvent\n    session: Session | null\n    broadcast: boolean\n  }> | null = null\n  protected detectSessionInUrl:\n    | boolean\n    | ((url: URL, params: { [parameter: string]: string }) => 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<any>[] = []\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[]) => 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 > 0 && 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 \u2014 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() && globalThis.BroadcastChannel && this.persistSession && 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) => {\n        this._debug('received broadcast notification from other tab or client', event)\n\n        // Another tab successfully refreshed or signed in \u2014 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) => {\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<T extends { error: any }>(result: T): T {\n    if (this.throwOnError && result && 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` \u2014 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<InitializeResult> {\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() \u2014 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 () => {\n      if (this.lock != null) {\n        // TODO(v3): remove legacy lock path\n        return await this._acquireLock(this.lockAcquireTimeout, async () => {\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 \u2014 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<InitializeResult> {\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() && this.detectSessionInUrl && 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 () => {\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\": \"<ACCESS_TOKEN>\",\n   *       \"token_type\": \"bearer\",\n   *       \"expires_in\": 3600,\n   *       \"expires_at\": 1700000000,\n   *       \"refresh_token\": \"<REFRESH_TOKEN>\",\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<AuthResponse> {\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\": \"<ACCESS_TOKEN>\",\n   *       \"token_type\": \"bearer\",\n   *       \"expires_in\": 3600,\n   *       \"expires_at\": 1700000000,\n   *       \"refresh_token\": \"<REFRESH_TOKEN>\",\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<AuthResponse> {\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 login.\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\": \"<ACCESS_TOKEN>\",\n   *       \"token_type\": \"bearer\",\n   *       \"expires_in\": 3600,\n   *       \"expires_at\": 1700000000,\n   *       \"refresh_token\": \"<REFRESH_TOKEN>\",\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<AuthTokenResponsePassword> {\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 Login (OAuth) providers](/docs/guides/auth#configure-third-party-providers).\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: <PROVIDER_URL_TO_REDIRECT_TO>,\n   *     flowId: <PKCE_FLOW_ID_OR_NULL>\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) => {\n   *   if (session && session.provider_token) {\n   *     window.localStorage.setItem('oauth_provider_token', session.provider_token)\n   *   }\n   *\n   *   if (session && 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<OAuthResponse> {\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 \u2014 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: '<ACCESS_TOKEN>',\n   *       token_type: 'bearer',\n   *       expires_in: 3600,\n   *       expires_at: 1700000000,\n   *       refresh_token: '<REFRESH_TOKEN>',\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   *             \"<OTHER_PROVIDER>\"\n   *           ]\n   *         },\n   *         user_metadata: {\n   *           email: 'email@email.com',\n   *           email_verified: true,\n   *           full_name: 'User Name',\n   *           iss: '<ISS>',\n   *           name: 'User Name',\n   *           phone_verified: false,\n   *           provider_id: '<PROVIDER_ID>',\n   *           sub: '<SUB>'\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\": \"<ID>\",\n   *             \"user_id\": \"<USER_ID>\",\n   *             \"identity_data\": {\n   *               \"email\": \"example@email.com\",\n   *               \"email_verified\": true,\n   *               \"full_name\": \"User Name\",\n   *               \"iss\": \"<ISS>\",\n   *               \"name\": \"User Name\",\n   *               \"phone_verified\": false,\n   *               \"provider_id\": \"<PROVIDER_ID>\",\n   *               \"sub\": \"<SUB>\"\n   *             },\n   *             \"provider\": \"<PROVIDER>\",\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: '<PROVIDER_TOKEN>',\n   *       provider_refresh_token: '<PROVIDER_REFRESH_TOKEN>'\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   *           \"<OTHER_PROVIDER>\"\n   *         ]\n   *       },\n   *       user_metadata: {\n   *         email: 'email@email.com',\n   *         email_verified: true,\n   *         full_name: 'User Name',\n   *         iss: '<ISS>',\n   *         name: 'User Name',\n   *         phone_verified: false,\n   *         provider_id: '<PROVIDER_ID>',\n   *         sub: '<SUB>'\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\": \"<ID>\",\n   *           \"user_id\": \"<USER_ID>\",\n   *           \"identity_data\": {\n   *             \"email\": \"example@email.com\",\n   *             \"email_verified\": true,\n   *             \"full_name\": \"User Name\",\n   *             \"iss\": \"<ISS>\",\n   *             \"name\": \"User Name\",\n   *             \"phone_verified\": false,\n   *             \"provider_id\": \"<PROVIDER_ID>\",\n   *             \"sub\": \"<SUB>\"\n   *           },\n   *           \"provider\": \"<PROVIDER>\",\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<AuthTokenResponse> {\n    await this.initializePromise\n\n    if (this.lock != null) {\n      // TODO(v3): remove legacy lock path\n      return this._acquireLock(this.lockAcquireTimeout, async () => {\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) & 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: '<sign in with ethereum message>',\n   *     signature: '<hex of the ethereum signature over the message>',\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   *     <>\n   *       {wallet.connected ? (\n   *         <button\n   *           onClick={() => {\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   *         >\n   *           Sign in with Solana\n   *         </button>\n   *       ) : (\n   *         <WalletMultiButton />\n   *       )}\n   *     </>\n   *   )\n   * }\n   *\n   * function App() {\n   *   const endpoint = clusterApiUrl('devnet')\n   *   const wallets = useMemo(() => [], [])\n   *\n   *   return (\n   *     <ConnectionProvider endpoint={endpoint}>\n   *       <WalletProvider wallets={wallets}>\n   *         <WalletModalProvider>\n   *           <SignInButton />\n   *         </WalletModalProvider>\n   *       </WalletProvider>\n   *     </ConnectionProvider>\n   *   )\n   * }\n   * ```\n   */\n  async signInWithWeb3(credentials: Web3Credentials): Promise<\n    | {\n        data: { session: Session; user: User }\n        error: null\n      }\n    | { data: { session: null; user: null }; error: AuthError }\n  > {\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<\n    | { data: { session: Session; user: User }; error: null }\n    | { data: { session: null; user: null }; error: AuthError }\n  > {\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 &&\n          typeof windowAny.ethereum === 'object' &&\n          'request' in windowAny.ethereum &&\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) => accs as string[])\n        .catch(() => {\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 &&\n          typeof windowAny.solana === 'object' &&\n          (('signIn' in windowAny.solana && typeof windowAny.solana.signIn === 'function') ||\n            ('signMessage' in windowAny.solana &&\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 && 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) && output[0] && typeof output[0] === 'object') {\n          outputToProcess = output[0]\n        } else if (\n          output &&\n          typeof output === 'object' &&\n          'signedMessage' in output &&\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 &&\n          'signature' in outputToProcess &&\n          (typeof outputToProcess.signedMessage === 'string' ||\n            outputToProcess.signedMessage instanceof Uint8Array) &&\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) => `- ${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<\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  > {\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 && !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 \u2014 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 && !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 && 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\": \"<ACCESS_TOKEN>\",\n   *       \"token_type\": \"bearer\",\n   *       \"expires_in\": 3600,\n   *       \"expires_at\": 1700000000,\n   *       \"refresh_token\": \"<REFRESH_TOKEN>\",\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<AuthTokenResponse> {\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 login.\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<AuthOtpResponse> {\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` \u2013 Used when verifying a one-time password (OTP) sent via SMS during sign-up or sign-in.\n   *   2. `phone_change` \u2013 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` \u2013 Used when verifying an OTP sent to the user's email during sign-up or sign-in.\n   *   2. `recovery` \u2013 Used when verifying an OTP sent for account recovery, typically after a password reset request.\n   *   3. `invite` \u2013 Used when verifying an OTP sent as part of an invitation to join a project or organization.\n   *   4. `email_change` \u2013 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\": \"<ACCESS_TOKEN>\",\n   *       \"token_type\": \"bearer\",\n   *       \"expires_in\": 3600,\n   *       \"expires_at\": 1700000000,\n   *       \"refresh_token\": \"<REFRESH_TOKEN>\",\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<AuthResponse> {\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<SSOResponse> {\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 && isBrowser() && !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<AuthResponse> {\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 () => {\n        return await this._reauthenticate()\n      })\n    }\n\n    return await this._reauthenticate()\n  }\n\n  private async _reauthenticate(): Promise<AuthResponse> {\n    try {\n      return await this._useSession(async (result) => {\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<AuthOtpResponse> {\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\": \"<ACCESS_TOKEN>\",\n   *       \"token_type\": \"bearer\",\n   *       \"expires_in\": 3600,\n   *       \"expires_at\": 1700000000,\n   *       \"refresh_token\": \"<REFRESH_TOKEN>\",\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 () => {\n        return this._useSession(async (result) => {\n          return result\n        })\n      })\n    }\n\n    return await this._useSession(async (result) => {\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<R>(acquireTimeout: number, fn: () => Promise<R>): Promise<R> {\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 () => {\n          await last\n          return await fn()\n        })()\n\n        this.pendingInLock.push(\n          (async () => {\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 () => {\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 () => {\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<R>(\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    ) => Promise<R>\n  ): Promise<R> {\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<\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  > {\n    this._debug('#__loadSession()', 'begin')\n\n    if (this.lock != null && !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() < 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 &&\n          this._isValidSession(stored) &&\n          stored.expires_at &&\n          stored.expires_at * 1000 > 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<Session> {\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 && session.user && !(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<UserResponse> {\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 () => {\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<UserResponse> {\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) => {\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 && !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<UserResponse> {\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 () => {\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<UserResponse> {\n    let flowId: string | null = null\n    try {\n      return await this._useSession(async (result) => {\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' && 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\": \"<ACCESS_TOKEN>\",\n   *       \"refresh_token\": \"<REFRESH_TOKEN>\",\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<AuthResponse> {\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 () => {\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<AuthResponse> {\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 <= 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\": \"<ACCESS_TOKEN>\",\n   *       \"token_type\": \"bearer\",\n   *       \"expires_in\": 3600,\n   *       \"expires_at\": 1700000000,\n   *       \"refresh_token\": \"<REFRESH_TOKEN>\",\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<AuthResponse> {\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 () => {\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<AuthResponse> {\n    try {\n      return await this._useSession(async (result) => {\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<\n    | {\n        data: { session: Session; redirectType: string | null }\n        error: null\n      }\n    | { data: { session: null; redirectType: null }; error: AuthError }\n  > {\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 <= 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 >= 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 < 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<boolean> {\n    if (!params.code) {\n      return false\n    }\n\n    const flowId = validatePKCEFlowId(params[PKCE_FLOW_ID_PARAM])\n    if (\n      flowId &&\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 and log them out - removing all items from localstorage and then trigger a `\"SIGNED_OUT\"` event.\n   *\n   * For server-side management, you can revoke all refresh tokens for a user by passing a user's JWT through to `auth.api.signOut(JWT: string)`.\n   * There is no way to revoke a user's access token jwt until it expires. It is recommended to set a shorter expiry on the jwt for this reason.\n   *\n   * If using `others` scope, no `SIGNED_OUT` event is fired!\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   * - Since Supabase Auth uses JWTs for authentication, the access token JWT will be valid until it's expired. When the user signs out, Supabase revokes the refresh token and deletes the JWT from the client-side. This does not revoke the JWT and it will still be valid until it expires.\n   *\n   * @example Sign out of every device (global \u2013 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<{ error: AuthError | null }> {\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 () => {\n        return await this._signOut(options)\n      })\n    }\n\n    return await this._signOut(options)\n  }\n\n  protected async _signOut(\n    { scope }: SignOut = { scope: 'global' }\n  ): Promise<{ error: AuthError | null }> {\n    return await this._useSession(async (result) => {\n      const removeCurrentSession = async () => {\n        await this._removeSession()\n      }\n      const { data, error: sessionError } = result\n      if (sessionError && !isAuthSessionMissingError(sessionError)) {\n        return this._returnResult({ error: sessionError })\n      }\n      const accessToken = data.session?.access_token\n      if (accessToken) {\n        const { error } = await this.admin.signOut(accessToken, scope)\n        if (error) {\n          // ignore 404s since user might not exist anymore\n          // ignore 401s since an invalid or expired JWT should sign out the current session\n          if (\n            !(\n              (isAuthApiError(error) &&\n                (error.status === 404 || error.status === 401 || error.status === 403)) ||\n              isAuthSessionMissingError(error)\n            )\n          ) {\n            if (scope !== 'others') {\n              await removeCurrentSession()\n            }\n            return this._returnResult({ error })\n          }\n        }\n      }\n      if (scope !== 'others') {\n        await removeCurrentSession()\n      }\n      return 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) => 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) => Promise<void>): {\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) => {\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) => {\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) => {\n   *       Object.entries(storage)\n   *         .forEach(([key]) => {\n   *           storage.removeItem(key)\n   *         })\n   *     })\n   *   }\n   * })\n   * ```\n   *\n   * @exampleDescription Store OAuth provider tokens on sign in\n   * When using [OAuth (Social Login)](/docs/guides/auth/social-login) 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-login/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) => {\n   *   if (session && session.provider_token) {\n   *     window.localStorage.setItem('oauth_provider_token', session.provider_token)\n   *   }\n   *\n   *   if (session && 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(() => {\n   *     const {data: { subscription }} = supabase.auth.onAuthStateChange(\n   *       (event, session) => {\n   *         if (event === 'SIGNED_OUT') {\n   *           setSession(null)\n   *         } else if (session) {\n   *           setSession(session)\n   *         }\n   *       })\n   *\n   *     return () => {\n   *       subscription.unsubscribe()\n   *     }\n   *   }, [])\n   *\n   *   return (\n   *     <SessionContext.Provider value={session}>\n   *       <App />\n   *     </SessionContext.Provider>\n   *   )\n   * }\n   * ```\n   *\n   * @example Listen to password recovery events\n   * ```js\n   * supabase.auth.onAuthStateChange((event, session) => {\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) => {\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) => {\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) => {\n   *   if (event === 'USER_UPDATED') console.log('USER_UPDATED', session)\n   * })\n   * ```\n   */\n  onAuthStateChange(\n    callback: (event: AuthChangeEvent, session: Session | null) => void | Promise<void>\n  ): {\n    data: { subscription: Subscription }\n  } {\n    const id: string | symbol = generateCallbackId()\n    const subscription: Subscription = {\n      id,\n      callback,\n      unsubscribe: () => {\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 () => {\n      await this.initializePromise\n\n      if (this.lock != null) {\n        // TODO(v3): remove legacy lock path\n        await this._acquireLock(this.lockAcquireTimeout, async () => {\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<void> {\n    return await this._useSession(async (result) => {\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) &&\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 \u2014 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(() => {\n   *    supabase.auth.onAuthStateChange(async (event, session) => {\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<\n    | {\n        data: {}\n        error: null\n      }\n    | { data: null; error: AuthError }\n  > {\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<\n    | {\n        data: {\n          identities: UserIdentity[]\n        }\n        error: null\n      }\n    | { data: null; error: AuthError }\n  > {\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<OAuthResponse>\n\n  /**\n   * Links an OIDC identity to an existing user.\n   */\n  async linkIdentity(credentials: SignInWithIdTokenCredentials): Promise<AuthTokenResponse>\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: <PROVIDER_URL_TO_REDIRECT_TO>,\n   *     flowId: <PKCE_FLOW_ID_OR_NULL>\n   *   },\n   *   error: null\n   * }\n   * ```\n   */\n  async linkIdentity(credentials: any): Promise<any> {\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<OAuthResponse> {\n    let flowId: string | null = null\n    try {\n      const { data, error } = await this._useSession(async (result) => {\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() && !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<AuthTokenResponse> {\n    return await this._useSession(async (result) => {\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 => 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<\n    | {\n        data: {}\n        error: null\n      }\n    | { data: null; error: AuthError }\n  > {\n    try {\n      return await this._useSession(async (result) => {\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<AuthResponse> {\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) => {\n          if (attempt > 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) => {\n          const nextBackOffInterval = 200 * Math.pow(2, attempt)\n          return (\n            error &&\n            isAuthRetryableFetchError(error) &&\n            // retryable only if the request can be sent before the backoff overflows the tick duration\n            Date.now() + nextBackOffInterval - startedAt < 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' &&\n      maybeSession !== null &&\n      'access_token' in maybeSession &&\n      'refresh_token' in maybeSession &&\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() && !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 && 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 && Object.is(this.storage, this.userStorage) && !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 -> 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 && !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 && 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() < 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 && 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 \u2014 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 &&\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 && 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<CallRefreshTokenResult> {\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 &&\n      this.lastRefreshFailure.refreshToken === refreshToken &&\n      Date.now() < 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<CallRefreshTokenResult>()\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 \u2014\n      // concurrent callers attach their own handlers via `.promise` and still\n      // observe the rejection.\n      this.refreshingDeferred.promise.then(undefined, () => {})\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 \u2014 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 &&\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 \u2014 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 \u2192 _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` \u2014 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 \u2014 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 \u2014 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 \u2014 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 && storedNow.expires_at * 1000 > Date.now()\n          )\n\n          if (accessTokenStillValid) {\n            this._debug(\n              debugName,\n              'proactive refresh failed, access token still valid \u2014 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 && 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 && broadcast) {\n        this.broadcastChannel.postMessage({ event, session })\n      }\n\n      const errors: unknown[] = []\n      const promises = Array.from(this.stateChangeEmitters.values()).map(async (x) => {\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 > 0) {\n        for (let i = 0; i < 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 && (sessionToProcess.user as any).__isUserNotAvailableProxy === true\n    if (this.userStorage) {\n      if (!userIsProxy && 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<Session, 'user'> & { 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 \u2014\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 \u2014 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 && isBrowser() && 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(() => this._autoRefreshTokenTick(), AUTO_REFRESH_TICK_DURATION_MS)\n    this.autoRefreshTicker = ticker\n\n    if (ticker && typeof ticker === 'object' && 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' && typeof Deno.unrefTimer === 'function') {\n      // similar like for NodeJS, but with the Deno API\n      // https://deno.land/api@latest?unstable&s=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 () => {\n      await this.initializePromise\n      await this._autoRefreshTokenTick()\n    }, 0)\n    this.autoRefreshTickTimeout = timeout\n\n    if (timeout && typeof timeout === 'object' && typeof timeout.unref === 'function') {\n      timeout.unref()\n      // @ts-expect-error TS has no context of Deno\n    } else if (typeof Deno !== 'undefined' && 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) => {\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) => {\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(() => {\n   *   const client = createClient(...)\n   *   return () => { client.auth.dispose() }\n   * }, [])\n   * ```\n   */\n  async dispose(): Promise<void> {\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 \u2014\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 () => {\n          try {\n            const now = Date.now()\n            try {\n              return await this._useSession(async (result) => {\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 <= 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) => {\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 <= 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 <= 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 () => {\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 -> 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 () => {\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 && 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('&')}`, 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<[string, string, string]> {\n    return getCodeChallengeAndMethod(\n      this.storage,\n      this.storageKey,\n      isPasswordRecovery,\n      (evictedFlowId) =>\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<AuthMFAUnenrollResponse> {\n    try {\n      return await this._useSession(async (result) => {\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<AuthMFAEnrollTOTPResponse>\n  private async _enroll(params: MFAEnrollPhoneParams): Promise<AuthMFAEnrollPhoneResponse>\n  private async _enroll(params: MFAEnrollWebauthnParams): Promise<AuthMFAEnrollWebauthnResponse>\n  private async _enroll(params: MFAEnrollParams): Promise<AuthMFAEnrollResponse> {\n    try {\n      return await this._useSession(async (result) => {\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' && data.type === 'totp' && 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<AuthMFAVerifyResponse>\n  private async _verify(params: MFAVerifyPhoneParams): Promise<AuthMFAVerifyResponse>\n  private async _verify<T extends 'create' | 'request'>(\n    params: MFAVerifyWebauthnParams<T>\n  ): Promise<AuthMFAVerifyResponse>\n  private async _verify(params: MFAVerifyParams): Promise<AuthMFAVerifyResponse> {\n    const run = async (): Promise<AuthMFAVerifyResponse> => {\n      try {\n        return await this._useSession(async (result) => {\n          const { data: sessionData, error: sessionError } = result\n          if (sessionError) {\n            return this._returnResult({ data: null, error: sessionError })\n          }\n\n          const body: StrictOmit<\n            | Exclude<MFAVerifyParams, MFAVerifyWebauthnParams>\n            /** Exclude out the webauthn params from here because we're going to need to serialize them in the response */\n            | Prettify<\n                StrictOmit<MFAVerifyWebauthnParams, 'webauthn'> & {\n                  webauthn: Prettify<\n                    StrictOmit<MFAVerifyWebauthnParamFields['webauthn'], 'credential_response'> & {\n                      credential_response: PublicKeyCredentialJSON\n                    }\n                  >\n                }\n              >,\n            /*  Exclude challengeId because the backend expects snake_case, and exclude factorId since it's passed in the path params */\n            'challengeId' | 'factorId'\n          > & {\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<Prettify<AuthMFAChallengeTOTPResponse>>\n  private async _challenge(\n    params: MFAChallengePhoneParams\n  ): Promise<Prettify<AuthMFAChallengePhoneResponse>>\n  private async _challenge(\n    params: MFAChallengeWebauthnParams\n  ): Promise<Prettify<AuthMFAChallengeWebauthnResponse>>\n  private async _challenge(params: MFAChallengeParams): Promise<AuthMFAChallengeResponse> {\n    const run = async (): Promise<AuthMFAChallengeResponse> => {\n      try {\n        return await this._useSession(async (result) => {\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<AuthMFAChallengeResponse, AuthMFAChallengeWebauthnResponse>\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<AuthMFAVerifyResponse> {\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<AuthMFAListFactorsResponse> {\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' &&\n        factor.factor_type in data &&\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<AuthMFAGetAuthenticatorAssuranceLevelResponse> {\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) => factor.status === 'verified') ?? []\n\n        if (verifiedFactors.length > 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) => factor.status === 'verified') ?? []\n\n    if (verifiedFactors.length > 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<AuthMFARecoveryCodesStatusResponse> {\n    assertRecoveryCodesExperimentalEnabled(this.experimental)\n    try {\n      return await this._useSession(async (result) => {\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<AuthMFARecoveryCodesGenerateResponse> {\n    assertRecoveryCodesExperimentalEnabled(this.experimental)\n    try {\n      return await this._useSession(async (result) => {\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<AuthMFAVerifyResponse> {\n    assertRecoveryCodesExperimentalEnabled(this.experimental)\n    const run = async (): Promise<AuthMFAVerifyResponse> => {\n      try {\n        return await this._useSession(async (result) => {\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<AuthMFARecoveryCodesGenerateResponse> {\n    assertRecoveryCodesExperimentalEnabled(this.experimental)\n    try {\n      return await this._useSession(async (result) => {\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<AuthMFAUnenrollResponse> {\n    assertRecoveryCodesExperimentalEnabled(this.experimental)\n    try {\n      return await this._useSession(async (result) => {\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<AuthOAuthAuthorizationDetailsResponse> {\n    try {\n      return await this._useSession(async (result) => {\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) => ({ 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<AuthOAuthConsentResponse> {\n    try {\n      return await this._useSession(async (result) => {\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) => ({ data, error: null }),\n          }\n        )\n\n        if (response.data && response.data.redirect_url) {\n          // Automatically redirect in browser unless skipBrowserRedirect is true\n          if (isBrowser() && !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<AuthOAuthConsentResponse> {\n    try {\n      return await this._useSession(async (result) => {\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) => ({ data, error: null }),\n          }\n        )\n\n        if (response.data && response.data.redirect_url) {\n          // Automatically redirect in browser unless skipBrowserRedirect is true\n          if (isBrowser() && !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<AuthOAuthGrantsResponse> {\n    try {\n      return await this._useSession(async (result) => {\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) => ({ 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<AuthOAuthRevokeGrantResponse> {\n    try {\n      return await this._useSession(async (result) => {\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<JWK | null> {\n    // try fetching from the supplied jwks\n    let jwk = jwks.keys.find((key) => 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) => key.kid === kid)\n\n    // jwk exists and jwks isn't stale\n    if (jwk && this.jwks_cached_at + JWKS_TTL > 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) => 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<\n    | {\n        data: { claims: JwtPayload; header: JwtHeader; signature: Uint8Array }\n        error: null\n      }\n    | { data: null; error: AuthError }\n    | { data: null; error: null }\n  > {\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 && '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   * // <input autocomplete=\"username webauthn\" /> 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<AuthPasskeyAuthenticationVerifyResponse> {\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<AuthPasskeyRegistrationVerifyResponse> {\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<AuthPasskeyRegistrationOptionsResponse> {\n    try {\n      return await this._useSession(async (result) => {\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<AuthPasskeyRegistrationVerifyResponse> {\n    try {\n      return await this._useSession(async (result) => {\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<AuthPasskeyAuthenticationOptionsResponse> {\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<AuthPasskeyAuthenticationVerifyResponse> {\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<AuthPasskeyListResponse> {\n    try {\n      return await this._useSession(async (result) => {\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) => ({ 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<AuthPasskeyUpdateResponse> {\n    try {\n      return await this._useSession(async (result) => {\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<AuthPasskeyDeleteResponse> {\n    try {\n      return await this._useSession(async (result) => {\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 GoTrueClient from './GoTrueClient'\n\nconst AuthClient = GoTrueClient\n\nexport default AuthClient\n", "// 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.118.0'\n", "// constants.ts\nimport { RealtimeClientOptions } from '@supabase/realtime-js'\nimport { SupabaseAuthClientOptions, TracePropagationOptions } from './types'\nimport { version } from './version'\n\nlet JS_ENV = ''\nlet JS_RUNTIME_VERSION: string | undefined\n// @ts-ignore\nif (typeof Deno !== 'undefined') {\n  JS_ENV = 'deno'\n  // @ts-ignore\n  JS_RUNTIME_VERSION = Deno.version?.deno\n} else if (typeof document !== 'undefined') {\n  JS_ENV = 'web'\n} else if (typeof navigator !== 'undefined' && navigator.product === 'ReactNative') {\n  JS_ENV = 'react-native'\n} else {\n  JS_ENV = 'node'\n  const _process = (globalThis as any)['process']\n  JS_RUNTIME_VERSION = _process?.['version']?.replace(/^v/, '')\n}\n\nconst _runtimeMeta = [`runtime=${JS_ENV}`]\nif (JS_RUNTIME_VERSION) {\n  _runtimeMeta.push(`runtime-version=${JS_RUNTIME_VERSION}`)\n}\n\nexport const DEFAULT_HEADERS = {\n  'X-Client-Info': `supabase-js/${version}; ${_runtimeMeta.join('; ')}`,\n}\n\nexport const DEFAULT_GLOBAL_OPTIONS = {\n  headers: DEFAULT_HEADERS,\n}\n\nexport const DEFAULT_DB_OPTIONS = {\n  schema: 'public',\n}\n\nexport const DEFAULT_AUTH_OPTIONS: SupabaseAuthClientOptions = {\n  autoRefreshToken: true,\n  persistSession: true,\n  detectSessionInUrl: true,\n  flowType: 'implicit',\n}\n\nexport const DEFAULT_REALTIME_OPTIONS: RealtimeClientOptions = {}\n\nexport const DEFAULT_TRACE_PROPAGATION_OPTIONS: TracePropagationOptions = {\n  enabled: false,\n  respectSamplingDecision: true,\n}\n", "/**\n * Parse W3C traceparent header according to the specification.\n *\n * The traceparent header format is: version-traceid-parentid-traceflags\n * - version: 2 hex digits (currently always \"00\")\n * - traceid: 32 hex digits (128-bit trace identifier)\n * - parentid: 16 hex digits (64-bit span/parent identifier)\n * - traceflags: 2 hex digits (8-bit flags, bit 0 is sampled flag)\n *\n * @param traceparent - The traceparent header value\n * @returns Parsed traceparent object, or null if invalid format\n *\n * @see https://www.w3.org/TR/trace-context/#traceparent-header\n *\n * @example\n * ```typescript\n * const parsed = parseTraceParent('00-0af7651916cd43dd8448eb211c80319c-b7ad6b7169203331-01')\n *\n * console.log(parsed)\n * // {\n * //   version: '00',\n * //   traceId: '0af7651916cd43dd8448eb211c80319c',\n * //   parentId: 'b7ad6b7169203331',\n * //   traceFlags: '01',\n * //   isSampled: true\n * // }\n * ```\n */\nexport function parseTraceParent(traceparent) {\n    if (!traceparent || typeof traceparent !== 'string') {\n        return null;\n    }\n    // Split by hyphen\n    const parts = traceparent.split('-');\n    // Must have exactly 4 parts\n    if (parts.length !== 4) {\n        return null;\n    }\n    const [version, traceId, parentId, traceFlags] = parts;\n    // Validate field lengths according to W3C spec\n    if (version.length !== 2 ||\n        traceId.length !== 32 ||\n        parentId.length !== 16 ||\n        traceFlags.length !== 2) {\n        return null;\n    }\n    // Validate that all fields are valid hexadecimal\n    const hexRegex = /^[0-9a-f]+$/i;\n    if (!hexRegex.test(version) ||\n        !hexRegex.test(traceId) ||\n        !hexRegex.test(parentId) ||\n        !hexRegex.test(traceFlags)) {\n        return null;\n    }\n    // Validate that trace-id and parent-id are not all zeros (invalid per spec)\n    if (traceId === '00000000000000000000000000000000' || parentId === '0000000000000000') {\n        return null;\n    }\n    // Parse sampling decision from trace-flags (bit 0)\n    const flags = parseInt(traceFlags, 16);\n    const isSampled = (flags & 0x01) === 0x01;\n    return {\n        version,\n        traceId,\n        parentId,\n        traceFlags,\n        isSampled,\n    };\n}\n//# sourceMappingURL=parse.js.map", "/**\n * Check if trace context should be propagated to the target URL.\n *\n * This function checks if the target URL matches any of the configured\n * propagation targets. Targets can be:\n * - String: Exact hostname match or wildcard domain (*.example.com)\n * - RegExp: Pattern matching hostname\n * - Function: Custom logic to determine if URL should receive trace context\n *\n * @param targetUrl - The URL to check\n * @param targets - Array of propagation targets\n * @returns True if trace context should be propagated, false otherwise\n *\n * @example\n * ```typescript\n * const targets = [\n *   'myproject.supabase.co',           // Exact match\n *   '*.supabase.co',                   // Wildcard domain\n *   /.*\\.supabase\\.co$/,               // Regex pattern\n *   (url) => url.hostname === 'localhost' // Custom function\n * ]\n *\n * shouldPropagateToTarget('https://myproject.supabase.co/rest/v1/table', targets)\n * // true\n *\n * shouldPropagateToTarget('https://evil.com/api', targets)\n * // false\n * ```\n */\nexport function shouldPropagateToTarget(targetUrl, targets) {\n    if (!targetUrl || !targets || targets.length === 0) {\n        return false;\n    }\n    let url;\n    if (targetUrl instanceof URL) {\n        url = targetUrl;\n    }\n    else {\n        try {\n            url = new URL(targetUrl);\n        }\n        catch (error) {\n            // Invalid URL\n            return false;\n        }\n    }\n    // Check each target\n    for (const target of targets) {\n        try {\n            if (typeof target === 'string') {\n                // String matcher: exact match or wildcard domain\n                if (matchStringTarget(url.hostname, target)) {\n                    return true;\n                }\n            }\n            else if (target instanceof RegExp) {\n                // Regex matcher\n                if (target.test(url.hostname)) {\n                    return true;\n                }\n            }\n            else if (typeof target === 'function') {\n                // Function matcher\n                if (target(url)) {\n                    return true;\n                }\n            }\n        }\n        catch (error) {\n            // Ignore errors from individual matchers and continue\n            continue;\n        }\n    }\n    return false;\n}\n/**\n * Match hostname against string target (exact match or wildcard)\n *\n * @param hostname - The hostname to check\n * @param target - The target pattern (exact or wildcard)\n * @returns True if hostname matches target\n */\nfunction matchStringTarget(hostname, target) {\n    // Exact match\n    if (target === hostname) {\n        return true;\n    }\n    // Wildcard domain match (*.example.com)\n    if (target.startsWith('*.')) {\n        const domain = target.slice(2); // Remove \"*.\"\n        // Check if hostname ends with the domain\n        if (hostname.endsWith(domain)) {\n            // Ensure it's either an exact match or has a subdomain\n            // (prevents \"notexample.com\" from matching \"*.example.com\")\n            if (hostname === domain || hostname.endsWith('.' + domain)) {\n                return true;\n            }\n        }\n    }\n    return false;\n}\n//# sourceMappingURL=validate.js.map", "/**\n * Generate default propagation targets based on the Supabase project URL.\n *\n * By default, trace context is only propagated to Supabase domains for\n * security. This prevents leaking trace context to potentially malicious\n * third-party services.\n *\n * Wildcard strings (e.g. `*.supabase.co`) are matched with linear string\n * operations rather than regex, avoiding ReDoS risk.\n *\n * @param supabaseUrl - The Supabase project URL\n * @returns Array of default propagation targets\n */\nexport function getDefaultPropagationTargets(supabaseUrl) {\n    const targets = [];\n    // Add exact project hostname\n    try {\n        const url = new URL(supabaseUrl);\n        targets.push(url.hostname);\n    }\n    catch (error) {\n        // Invalid URL, skip exact hostname\n    }\n    // Supabase cloud domains. Use wildcard strings (not regex) — these are\n    // matched by linear hostname-suffix checks, so there is no ReDoS surface.\n    targets.push('*.supabase.co', '*.supabase.in');\n    // Localhost and loopback addresses for local development.\n    targets.push('localhost', '127.0.0.1', '[::1]');\n    return targets;\n}\n//# sourceMappingURL=defaults.js.map", "import {\n  parseTraceParent,\n  shouldPropagateToTarget,\n  getDefaultPropagationTargets,\n  type TraceContext,\n  type TracePropagationTarget,\n} from '@supabase/tracing'\nimport { getTraceContextExtractor } from './tracingRegistry'\nimport type { TracePropagationOptions } from './types'\n\ntype Fetch = typeof fetch\n\nexport const resolveFetch = (customFetch?: Fetch): Fetch => {\n  if (customFetch) {\n    return (...args: Parameters<Fetch>) => customFetch(...args)\n  }\n  return (...args: Parameters<Fetch>) => fetch(...args)\n}\n\nexport const resolveHeadersConstructor = () => {\n  return Headers\n}\n\n/**\n * New-format Supabase API keys (`sb_publishable_…` / `sb_secret_…`) are not JWTs and\n * must never be sent as a Bearer token — they belong only in the `apikey` header.\n * All other keys (legacy JWT keys, `sb_temp_…` temporary keys, unrecognized `sb_`\n * subtypes) keep the Bearer fallback.\n */\nconst isNewApiKey = (key: string): boolean =>\n  key.startsWith('sb_publishable_') || key.startsWith('sb_secret_')\n\nconst TEMP_KEY_PREFIX = 'sb_temp_'\n\nconst warnedKeySubtypes = new Set<string>()\n\n/**\n * Warn (once per subtype) when an `sb_` key isn't a subtype this SDK version recognizes.\n * Never throws — the server, not the SDK, decides key validity. The key value is never\n * included in the message.\n */\nexport const checkApiKeyFormat = (key: string): void => {\n  if (!key.startsWith('sb_') || isNewApiKey(key) || key.startsWith(TEMP_KEY_PREFIX)) {\n    return\n  }\n  const subtype = key.match(/^sb_[a-zA-Z0-9]+_/)?.[0] ?? 'unknown'\n  if (warnedKeySubtypes.has(subtype)) {\n    return\n  }\n  warnedKeySubtypes.add(subtype)\n  console.warn(\n    '@supabase/supabase-js: Unrecognized Supabase API key format. The client will proceed ' +\n      'and send this key as-is; if you see authentication errors you may need to upgrade ' +\n      '@supabase/supabase-js to a version that recognizes this key type.'\n  )\n}\n\nexport const fetchWithAuth = (\n  supabaseKey: string,\n  supabaseUrl: string,\n  getAccessToken: () => Promise<string | null>,\n  customFetch?: Fetch,\n  tracePropagationOptions?: TracePropagationOptions,\n  options?: { omitApiKeyAsBearer?: boolean }\n): Fetch => {\n  const fetch = resolveFetch(customFetch)\n  const HeadersConstructor = resolveHeadersConstructor()\n\n  // Pre-compute trace propagation state once. When disabled, the per-request\n  // path skips all tracing work with a single truthy check.\n  const traceEnabled = tracePropagationOptions?.enabled === true\n  const respectSampling = tracePropagationOptions?.respectSamplingDecision !== false\n  const traceTargets: TracePropagationTarget[] | null = traceEnabled\n    ? getDefaultPropagationTargets(supabaseUrl)\n    : null\n\n  // Whether the API key may be used as the `Authorization` Bearer fallback when there is no\n  // session token. Disabled for Edge Functions with a new-format key (see `isNewApiKey`).\n  // Static per instance, so it is computed once here rather than on every request.\n  const allowKeyAsBearer = !(options?.omitApiKeyAsBearer && isNewApiKey(supabaseKey))\n\n  return async (input, init) => {\n    const realToken = await getAccessToken()\n    let headers = new HeadersConstructor(init?.headers)\n\n    if (!headers.has('apikey')) {\n      headers.set('apikey', supabaseKey)\n    }\n\n    if (!headers.has('Authorization')) {\n      const bearer = realToken ?? (allowKeyAsBearer ? supabaseKey : null)\n      if (bearer) {\n        headers.set('Authorization', `Bearer ${bearer}`)\n      }\n    }\n\n    if (traceTargets) {\n      const traceHeaders = getTraceHeaders(input, traceTargets, respectSampling)\n\n      if (traceHeaders) {\n        if (traceHeaders.traceparent && !headers.has('traceparent')) {\n          headers.set('traceparent', traceHeaders.traceparent)\n        }\n        if (traceHeaders.tracestate && !headers.has('tracestate')) {\n          headers.set('tracestate', traceHeaders.tracestate)\n        }\n        if (traceHeaders.baggage && !headers.has('baggage')) {\n          headers.set('baggage', traceHeaders.baggage)\n        }\n      }\n    }\n\n    return fetch(input, { ...init, headers })\n  }\n}\n\nlet warnedMissingTracingRuntime = false\nlet warnedNonW3CPropagator = false\n\n/**\n * For tests only. Resets the one-time missing-tracing-runtime warning.\n *\n * @internal\n */\nexport function _resetTracingRuntimeWarning(): void {\n  warnedMissingTracingRuntime = false\n}\n\n/**\n * For tests only. Resets the one-time non-W3C-propagator warning.\n *\n * @internal\n */\nexport function _resetNonW3CPropagatorWarning(): void {\n  warnedNonW3CPropagator = false\n}\n\nfunction getTraceHeaders(\n  input: RequestInfo | URL,\n  targets: TracePropagationTarget[],\n  respectSampling: boolean\n): TraceContext | null {\n  // Read the registry before the target check so the warning fires on the\n  // first request with tracing enabled, not only on Supabase-target ones.\n  // Reading per request (one globalThis property access) deliberately\n  // supports late registration: with ESM evaluation order, `createClient`\n  // can run in a module evaluated before the application entry point's\n  // `import '@supabase/supabase-js/tracing'`.\n  const extractTraceContext = getTraceContextExtractor()\n\n  if (!extractTraceContext) {\n    if (!warnedMissingTracingRuntime) {\n      warnedMissingTracingRuntime = true\n      console.warn(\n        '@supabase/supabase-js: tracePropagation is enabled but the tracing runtime is not loaded, ' +\n          \"so trace headers will not be attached. Add `import '@supabase/supabase-js/tracing'` at \" +\n          'your application entry point (requires the OpenTelemetry API package to be installed). ' +\n          'The CDN/UMD build does not support trace propagation.'\n      )\n    }\n    return null\n  }\n\n  const targetUrl: string | URL =\n    typeof input === 'string' ? input : input instanceof URL ? input : input.url\n\n  if (!shouldPropagateToTarget(targetUrl, targets)) {\n    return null\n  }\n\n  const traceContext = extractTraceContext()\n\n  if (!traceContext || !traceContext.traceparent) {\n    // An active propagator that writes vendor headers but no W3C\n    // `traceparent` (e.g. Sentry without `propagateTraceparent: true`) is\n    // otherwise indistinguishable from \"no active trace\" — warn once so the\n    // user learns why no trace headers are attached. An empty carrier means\n    // no active trace: normal, stay silent.\n    if (traceContext?.carrierKeys?.length && !warnedNonW3CPropagator) {\n      warnedNonW3CPropagator = true\n      const sentryHint = traceContext.carrierKeys.includes('sentry-trace')\n        ? ' Sentry detected: set `propagateTraceparent: true` in Sentry.init() to emit it.'\n        : ' Configure your tracing SDK to emit W3C trace context on outgoing requests.'\n      console.warn(\n        '@supabase/supabase-js: tracePropagation is enabled and a tracing SDK is active, but its ' +\n          `propagator wrote [${traceContext.carrierKeys.join(', ')}] and no W3C traceparent header, ` +\n          'so trace headers will not be attached.' +\n          sentryHint\n      )\n    }\n    return null\n  }\n\n  if (respectSampling) {\n    const parsed = parseTraceParent(traceContext.traceparent)\n    if (parsed && !parsed.isSampled) {\n      // Unsampled traces still carry `traceparent` so Supabase logs get a\n      // trace_id to correlate on; the flag stays `00`, so downstream tracing\n      // never records it as sampled. `tracestate` and `baggage` (the\n      // vendor/application data channels) are withheld on these requests.\n      return { traceparent: traceContext.traceparent }\n    }\n  }\n\n  return traceContext\n}\n", "// helpers.ts\nimport { SupabaseClientOptions, TracePropagationOptions } from './types'\n\nfunction normalizeTracePropagation(\n  value: TracePropagationOptions | boolean | undefined\n): TracePropagationOptions | undefined {\n  return typeof value === 'boolean' ? { enabled: value } : value\n}\n\nexport function uuid() {\n  return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {\n    var r = (Math.random() * 16) | 0,\n      v = c == 'x' ? r : (r & 0x3) | 0x8\n    return v.toString(16)\n  })\n}\n\nexport function ensureTrailingSlash(url: string): string {\n  return url.endsWith('/') ? url : url + '/'\n}\n\nexport const isBrowser = () => typeof window !== 'undefined'\n\nlet warnedTopLevelSchema = false\n\n/**\n * Warn (once per process) when `schema` is passed at the top level of the client options\n * instead of under `db`. A top-level `schema` is not part of the options shape and is\n * ignored, so queries silently go to the default schema. Never throws.\n *\n * Only `undefined` counts as unset, matching `db.schema`, where any other value is sent\n * as the profile header.\n */\nexport function checkTopLevelSchemaOption(options: unknown): void {\n  if (warnedTopLevelSchema) {\n    return\n  }\n  if (\n    typeof options !== 'object' ||\n    options === null ||\n    !('schema' in options) ||\n    (options as { schema?: unknown }).schema === undefined\n  ) {\n    return\n  }\n  warnedTopLevelSchema = true\n  console.warn(\n    '@supabase/supabase-js: The \"schema\" option must be nested under \"db\", ' +\n      \"e.g. createClient(url, key, { db: { schema: 'myschema' } }). \" +\n      'A top-level \"schema\" is ignored and queries go to the default schema.'\n  )\n}\n\n/**\n * For tests only. Resets the one-time top-level `schema` warning.\n *\n * @internal\n */\nexport function _resetTopLevelSchemaWarning(): void {\n  warnedTopLevelSchema = false\n}\n\nexport type ResolvedSupabaseClientOptions<SchemaName> = Omit<\n  Required<SupabaseClientOptions<SchemaName>>,\n  'tracePropagation'\n> & {\n  tracePropagation: TracePropagationOptions\n}\n\nexport function applySettingDefaults<\n  Database = any,\n  SchemaName extends string & keyof Database = 'public' extends keyof Database\n    ? 'public'\n    : string & keyof Database,\n>(\n  options: SupabaseClientOptions<SchemaName>,\n  defaults: SupabaseClientOptions<any>\n): ResolvedSupabaseClientOptions<SchemaName> {\n  const {\n    db: dbOptions,\n    auth: authOptions,\n    realtime: realtimeOptions,\n    global: globalOptions,\n  } = options\n  const {\n    db: DEFAULT_DB_OPTIONS,\n    auth: DEFAULT_AUTH_OPTIONS,\n    realtime: DEFAULT_REALTIME_OPTIONS,\n    global: DEFAULT_GLOBAL_OPTIONS,\n  } = defaults\n\n  // Accept either a boolean shorthand or an options object on both sides.\n  const tracePropagationOptions = normalizeTracePropagation(options.tracePropagation)\n  const DEFAULT_TRACE_PROPAGATION_OPTIONS = normalizeTracePropagation(defaults.tracePropagation)\n\n  const result: ResolvedSupabaseClientOptions<SchemaName> = {\n    db: {\n      ...DEFAULT_DB_OPTIONS,\n      ...dbOptions,\n    },\n    auth: {\n      ...DEFAULT_AUTH_OPTIONS,\n      ...authOptions,\n    },\n    realtime: {\n      ...DEFAULT_REALTIME_OPTIONS,\n      ...realtimeOptions,\n    },\n    storage: {},\n    global: {\n      ...DEFAULT_GLOBAL_OPTIONS,\n      ...globalOptions,\n      headers: {\n        ...(DEFAULT_GLOBAL_OPTIONS?.headers ?? {}),\n        ...(globalOptions?.headers ?? {}),\n      },\n    },\n    tracePropagation: {\n      enabled:\n        tracePropagationOptions?.enabled ?? DEFAULT_TRACE_PROPAGATION_OPTIONS?.enabled ?? false,\n      respectSamplingDecision:\n        tracePropagationOptions?.respectSamplingDecision ??\n        DEFAULT_TRACE_PROPAGATION_OPTIONS?.respectSamplingDecision ??\n        true,\n    },\n    accessToken: async () => '',\n  }\n\n  if (options.accessToken) {\n    result.accessToken = options.accessToken\n  } else {\n    // hack around Required<>\n    delete (result as any).accessToken\n  }\n\n  return result\n}\n\n/**\n * Validates a Supabase client URL\n *\n * @param {string} supabaseUrl - The Supabase client URL string.\n * @returns {URL} - The validated base URL.\n * @throws {Error}\n */\nexport function validateSupabaseUrl(supabaseUrl: string): URL {\n  const trimmedUrl = supabaseUrl?.trim()\n\n  if (!trimmedUrl) {\n    throw new Error('supabaseUrl is required.')\n  }\n\n  if (!trimmedUrl.match(/^https?:\\/\\//i)) {\n    throw new Error('Invalid supabaseUrl: Must be a valid HTTP or HTTPS URL.')\n  }\n\n  try {\n    return new URL(ensureTrailingSlash(trimmedUrl))\n  } catch {\n    throw Error('Invalid supabaseUrl: Provided URL is malformed.')\n  }\n}\n", "import { AuthClient } from '@supabase/auth-js'\nimport { SupabaseAuthClientOptions } from './types'\n\nexport class SupabaseAuthClient extends AuthClient {\n  constructor(options: SupabaseAuthClientOptions) {\n    super(options)\n  }\n}\n", "import type { AuthChangeEvent } from '@supabase/auth-js'\nimport { FunctionsClient } from '@supabase/functions-js'\nimport {\n  PostgrestClient,\n  type PostgrestFilterBuilder,\n  type PostgrestOpenApiSpec,\n  type PostgrestQueryBuilder,\n  type PostgrestSingleResponse,\n} from '@supabase/postgrest-js'\nimport {\n  type RealtimeChannel,\n  type RealtimeChannelOptions,\n  RealtimeClient,\n  type RealtimeClientOptions,\n  type RealtimeRemoveChannelResponse,\n} from '@supabase/realtime-js'\nimport { StorageClient as SupabaseStorageClient } from '@supabase/storage-js'\nimport {\n  DEFAULT_AUTH_OPTIONS,\n  DEFAULT_DB_OPTIONS,\n  DEFAULT_GLOBAL_OPTIONS,\n  DEFAULT_REALTIME_OPTIONS,\n  DEFAULT_TRACE_PROPAGATION_OPTIONS,\n} from './lib/constants'\nimport { checkApiKeyFormat, fetchWithAuth } from './lib/fetch'\nimport {\n  applySettingDefaults,\n  checkTopLevelSchemaOption,\n  validateSupabaseUrl,\n  type ResolvedSupabaseClientOptions,\n} from './lib/helpers'\nimport { SupabaseAuthClient } from './lib/SupabaseAuthClient'\nimport type {\n  Fetch,\n  GenericSchema,\n  SupabaseAuthClientOptions,\n  SupabaseClientOptions,\n} from './lib/types'\nimport { GetRpcFunctionFilterBuilderByArgs } from './lib/rest/types/common/rpc'\n\n/**\n * Supabase Client.\n *\n * An isomorphic Javascript client for interacting with Postgres.\n */\nexport default class SupabaseClient<\n  Database = any,\n  // The second type parameter is also used for specifying db_schema, so we\n  // support both cases.\n  // TODO: Allow setting db_schema from ClientOptions.\n  SchemaNameOrClientOptions extends\n    | (string & keyof Omit<Database, '__InternalSupabase'>)\n    | { PostgrestVersion: string } = 'public' extends keyof Omit<Database, '__InternalSupabase'>\n    ? 'public'\n    : string & keyof Omit<Database, '__InternalSupabase'>,\n  SchemaName extends string & keyof Omit<Database, '__InternalSupabase'> =\n    SchemaNameOrClientOptions extends string & keyof Omit<Database, '__InternalSupabase'>\n      ? SchemaNameOrClientOptions\n      : 'public' extends keyof Omit<Database, '__InternalSupabase'>\n        ? 'public'\n        : string & keyof Omit<Omit<Database, '__InternalSupabase'>, '__InternalSupabase'>,\n  Schema extends Omit<Database, '__InternalSupabase'>[SchemaName] extends GenericSchema\n    ? Omit<Database, '__InternalSupabase'>[SchemaName]\n    : never = Omit<Database, '__InternalSupabase'>[SchemaName] extends GenericSchema\n    ? Omit<Database, '__InternalSupabase'>[SchemaName]\n    : never,\n  ClientOptions extends { PostgrestVersion: string } = SchemaNameOrClientOptions extends string &\n    keyof Omit<Database, '__InternalSupabase'>\n    ? // If the version isn't explicitly set, look for it in the __InternalSupabase object to infer the right version\n      Database extends { __InternalSupabase: { PostgrestVersion: string } }\n      ? Database['__InternalSupabase']\n      : // otherwise default to 12\n        { PostgrestVersion: '12' }\n    : SchemaNameOrClientOptions extends { PostgrestVersion: string }\n      ? SchemaNameOrClientOptions\n      : never,\n> {\n  /**\n   * Supabase Auth allows you to create and manage user sessions for access to data that is secured by access policies.\n   */\n  auth: SupabaseAuthClient\n  realtime: RealtimeClient\n  /**\n   * Supabase Storage allows you to manage user-generated content, such as photos or videos.\n   */\n  storage: SupabaseStorageClient\n\n  protected realtimeUrl: URL\n  protected authUrl: URL\n  protected storageUrl: URL\n  protected functionsUrl: URL\n  protected rest: PostgrestClient<Database, ClientOptions, SchemaName>\n  protected storageKey: string\n  protected fetch?: Fetch\n  protected functionsFetch?: Fetch\n  protected changedAccessToken?: string\n  protected accessToken?: () => Promise<string | null>\n\n  protected headers: Record<string, string>\n  protected settings?: ResolvedSupabaseClientOptions<SchemaName>\n\n  /**\n   * Create a new client for use in the browser.\n   *\n   * @category Initializing\n   *\n   * @param supabaseUrl The unique Supabase URL which is supplied when you create a new project in your project dashboard.\n   * @param supabaseKey The unique Supabase Key which is supplied when you create a new project in your project dashboard.\n   * @param options Optional configuration for the client:\n   * - `db.schema` — You can switch in between schemas. The schema needs to be on the list of exposed schemas inside Supabase.\n   * - `auth.autoRefreshToken` — Set to `true` if you want to automatically refresh the token before expiring.\n   * - `auth.persistSession` — Set to `true` if you want to automatically save the user session into local storage.\n   * - `auth.detectSessionInUrl` — Set to `true` if you want to automatically detect OAuth grants in the URL and sign in the user.\n   * - `realtime` — Options passed along to the realtime-js constructor.\n   * - `storage` — Options passed along to the storage-js constructor.\n   * - `global.fetch` — A custom fetch implementation.\n   * - `global.headers` — Any additional headers to send with each network request.\n   *\n   * @example Creating a client\n   * ```js\n   * import { createClient } from '@supabase/supabase-js'\n   *\n   * // Create a single supabase client for interacting with your database\n   * const supabase = createClient('https://xyzcompany.supabase.co', 'your-publishable-key')\n   * ```\n   *\n   * @example With a custom domain\n   * ```js\n   * import { createClient } from '@supabase/supabase-js'\n   *\n   * // Use a custom domain as the supabase URL\n   * const supabase = createClient('https://my-custom-domain.com', 'your-publishable-key')\n   * ```\n   *\n   * @example With additional parameters\n   * ```js\n   * import { createClient } from '@supabase/supabase-js'\n   *\n   * const options = {\n   *   db: {\n   *     schema: 'public',\n   *   },\n   *   auth: {\n   *     autoRefreshToken: true,\n   *     persistSession: true,\n   *     detectSessionInUrl: true\n   *   },\n   *   global: {\n   *     headers: { 'x-my-custom-header': 'my-app-name' },\n   *   },\n   * }\n   * const supabase = createClient(\"https://xyzcompany.supabase.co\", \"your-publishable-key\", options)\n   * ```\n   *\n   * @exampleDescription With custom schemas\n   * By default the API server points to the `public` schema. You can enable other database schemas within the Dashboard.\n   * Go to [Settings > API > Exposed schemas](/dashboard/project/_/settings/api) and add the schema which you want to expose to the API.\n   *\n   * Note: each client connection can only access a single schema, so the code above can access the `other_schema` schema but cannot access the `public` schema.\n   *\n   * @example With custom schemas\n   * ```js\n   * import { createClient } from '@supabase/supabase-js'\n   *\n   * const supabase = createClient('https://xyzcompany.supabase.co', 'your-publishable-key', {\n   *   // Provide a custom schema. Defaults to \"public\".\n   *   db: { schema: 'other_schema' }\n   * })\n   * ```\n   *\n   * @exampleDescription Custom fetch implementation\n   * `supabase-js` uses the runtime's global `fetch` to make HTTP requests,\n   * but an alternative `fetch` implementation can be provided as an option.\n   * This is useful in environments where the global `fetch` is unavailable or where you want to customize request behavior.\n   *\n   * @example Custom fetch implementation\n   * ```js\n   * import { createClient } from '@supabase/supabase-js'\n   *\n   * const supabase = createClient('https://xyzcompany.supabase.co', 'your-publishable-key', {\n   *   global: { fetch: fetch.bind(globalThis) }\n   * })\n   * ```\n   *\n   * @exampleDescription React Native options with AsyncStorage\n   * For React Native we recommend using `AsyncStorage` as the storage implementation for Supabase Auth.\n   *\n   * @example React Native options with AsyncStorage\n   * ```js\n   * import 'react-native-url-polyfill/auto'\n   * import { createClient } from '@supabase/supabase-js'\n   * import AsyncStorage from \"@react-native-async-storage/async-storage\";\n   *\n   * const supabase = createClient(\"https://xyzcompany.supabase.co\", \"your-publishable-key\", {\n   *   auth: {\n   *     storage: AsyncStorage,\n   *     autoRefreshToken: true,\n   *     persistSession: true,\n   *     detectSessionInUrl: false,\n   *   },\n   * });\n   * ```\n   *\n   * @exampleDescription React Native options with Expo SecureStore\n   * If you wish to encrypt the user's session information, you can use `aes-js` and store the encryption key in Expo SecureStore.\n   * The `aes-js` library, a reputable JavaScript-only implementation of the AES encryption algorithm in CTR mode.\n   * A new 256-bit encryption key is generated using the `react-native-get-random-values` library.\n   * This key is stored inside Expo's SecureStore, while the value is encrypted and placed inside AsyncStorage.\n   *\n   * Please make sure that:\n   * - You keep the `expo-secure-store`, `aes-js` and `react-native-get-random-values` libraries up-to-date.\n   * - Choose the correct [`SecureStoreOptions`](https://docs.expo.dev/versions/latest/sdk/securestore/#securestoreoptions) for your app's needs.\n   *   E.g. [`SecureStore.WHEN_UNLOCKED`](https://docs.expo.dev/versions/latest/sdk/securestore/#securestorewhen_unlocked) regulates when the data can be accessed.\n   * - Carefully consider optimizations or other modifications to the above example, as those can lead to introducing subtle security vulnerabilities.\n   *\n   * @example React Native options with Expo SecureStore\n   * ```ts\n   * import 'react-native-url-polyfill/auto'\n   * import { createClient } from '@supabase/supabase-js'\n   * import AsyncStorage from '@react-native-async-storage/async-storage';\n   * import * as SecureStore from 'expo-secure-store';\n   * import * as aesjs from 'aes-js';\n   * import 'react-native-get-random-values';\n   *\n   * // As Expo's SecureStore does not support values larger than 2048\n   * // bytes, an AES-256 key is generated and stored in SecureStore, while\n   * // it is used to encrypt/decrypt values stored in AsyncStorage.\n   * class LargeSecureStore {\n   *   private async _encrypt(key: string, value: string) {\n   *     const encryptionKey = crypto.getRandomValues(new Uint8Array(256 / 8));\n   *\n   *     const cipher = new aesjs.ModeOfOperation.ctr(encryptionKey, new aesjs.Counter(1));\n   *     const encryptedBytes = cipher.encrypt(aesjs.utils.utf8.toBytes(value));\n   *\n   *     await SecureStore.setItemAsync(key, aesjs.utils.hex.fromBytes(encryptionKey));\n   *\n   *     return aesjs.utils.hex.fromBytes(encryptedBytes);\n   *   }\n   *\n   *   private async _decrypt(key: string, value: string) {\n   *     const encryptionKeyHex = await SecureStore.getItemAsync(key);\n   *     if (!encryptionKeyHex) {\n   *       return encryptionKeyHex;\n   *     }\n   *\n   *     const cipher = new aesjs.ModeOfOperation.ctr(aesjs.utils.hex.toBytes(encryptionKeyHex), new aesjs.Counter(1));\n   *     const decryptedBytes = cipher.decrypt(aesjs.utils.hex.toBytes(value));\n   *\n   *     return aesjs.utils.utf8.fromBytes(decryptedBytes);\n   *   }\n   *\n   *   async getItem(key: string) {\n   *     const encrypted = await AsyncStorage.getItem(key);\n   *     if (!encrypted) { return encrypted; }\n   *\n   *     return await this._decrypt(key, encrypted);\n   *   }\n   *\n   *   async removeItem(key: string) {\n   *     await AsyncStorage.removeItem(key);\n   *     await SecureStore.deleteItemAsync(key);\n   *   }\n   *\n   *   async setItem(key: string, value: string) {\n   *     const encrypted = await this._encrypt(key, value);\n   *\n   *     await AsyncStorage.setItem(key, encrypted);\n   *   }\n   * }\n   *\n   * const supabase = createClient(\"https://xyzcompany.supabase.co\", \"your-publishable-key\", {\n   *   auth: {\n   *     storage: new LargeSecureStore(),\n   *     autoRefreshToken: true,\n   *     persistSession: true,\n   *     detectSessionInUrl: false,\n   *   },\n   * });\n   * ```\n   *\n   * @example With a database query\n   * ```ts\n   * import { createClient } from '@supabase/supabase-js'\n   *\n   * const supabase = createClient('https://xyzcompany.supabase.co', 'your-publishable-key')\n   *\n   * const { data } = await supabase.from('profiles').select('*')\n   * ```\n   *\n   * @exampleDescription With OpenTelemetry tracing\n   * Opt in to W3C trace context propagation so the `trace_id` from your\n   * client-side spans is attached to Supabase requests and appears in API\n   * Gateway and Edge Function logs. Requires `@opentelemetry/api` to be\n   * installed in your application and the tracing runtime to be loaded via\n   * `import '@supabase/supabase-js/tracing'`. See [Tracing with the JS SDK](https://supabase.com/docs/guides/telemetry/client-side-tracing).\n   *\n   * @example With OpenTelemetry tracing\n   * ```ts\n   * import '@supabase/supabase-js/tracing'\n   * import { createClient } from '@supabase/supabase-js'\n   * import { trace } from '@opentelemetry/api'\n   *\n   * const supabase = createClient('https://xyzcompany.supabase.co', 'your-publishable-key', {\n   *   tracePropagation: true,\n   * })\n   *\n   * const tracer = trace.getTracer('my-app')\n   *\n   * await tracer.startActiveSpan('fetch-users', async (span) => {\n   *   // Outgoing request carries the active trace context.\n   *   const { data, error } = await supabase.from('users').select('*')\n   *   span.end()\n   * })\n   * ```\n   */\n  constructor(\n    protected supabaseUrl: string,\n    protected supabaseKey: string,\n    options?: SupabaseClientOptions<SchemaName>\n  ) {\n    const baseUrl = validateSupabaseUrl(supabaseUrl)\n    if (!supabaseKey) throw new Error('supabaseKey is required.')\n    checkApiKeyFormat(supabaseKey)\n    checkTopLevelSchemaOption(options)\n\n    this.realtimeUrl = new URL('realtime/v1', baseUrl)\n    this.realtimeUrl.protocol = this.realtimeUrl.protocol.replace('http', 'ws')\n    this.authUrl = new URL('auth/v1', baseUrl)\n    this.storageUrl = new URL('storage/v1', baseUrl)\n    this.functionsUrl = new URL('functions/v1', baseUrl)\n\n    // default storage key uses the supabase project ref as a namespace\n    const defaultStorageKey = `sb-${baseUrl.hostname.split('.')[0]}-auth-token`\n    const DEFAULTS = {\n      db: DEFAULT_DB_OPTIONS,\n      realtime: DEFAULT_REALTIME_OPTIONS,\n      auth: { ...DEFAULT_AUTH_OPTIONS, storageKey: defaultStorageKey },\n      global: DEFAULT_GLOBAL_OPTIONS,\n      tracePropagation: DEFAULT_TRACE_PROPAGATION_OPTIONS,\n    }\n\n    const settings = applySettingDefaults(options ?? {}, DEFAULTS)\n    this.settings = settings\n\n    this.storageKey = settings.auth.storageKey ?? ''\n    this.headers = settings.global.headers ?? {}\n\n    if (!settings.accessToken) {\n      this.auth = this._initSupabaseAuthClient(\n        settings.auth ?? {},\n        this.headers,\n        settings.global.fetch\n      )\n    } else {\n      this.accessToken = settings.accessToken\n\n      this.auth = new Proxy<SupabaseAuthClient>({} as any, {\n        get: (_, prop) => {\n          throw new Error(\n            `@supabase/supabase-js: Supabase Client is configured with the accessToken option, accessing supabase.auth.${String(\n              prop\n            )} is not possible`\n          )\n        },\n      })\n    }\n\n    // The fetch wrappers receive the raw session token (null when there is no session) and\n    // decide the `Authorization` fallback themselves, so the API-key fallback lives in one place.\n    this.fetch = fetchWithAuth(\n      supabaseKey,\n      supabaseUrl,\n      this._getSessionToken.bind(this),\n      settings.global.fetch,\n      settings.tracePropagation\n    )\n    // Edge Functions use a dedicated fetch that never falls back to a new-format API key in\n    // the Authorization header (see `isNewApiKey` in ./lib/fetch). Other services use `this.fetch`.\n    this.functionsFetch = fetchWithAuth(\n      supabaseKey,\n      supabaseUrl,\n      this._getSessionToken.bind(this),\n      settings.global.fetch,\n      settings.tracePropagation,\n      { omitApiKeyAsBearer: true }\n    )\n    this.realtime = this._initRealtimeClient({\n      headers: this.headers,\n      accessToken: this._getAccessToken.bind(this),\n      fetch: this.fetch,\n      ...settings.realtime,\n    })\n    if (this.accessToken) {\n      // Start auth immediately to avoid race condition with channel subscriptions\n      // Wrap Promise to avoid Firefox extension cross-context Promise access errors\n      Promise.resolve(this.accessToken())\n        .then((token) => this.realtime.setAuth(token))\n        .catch((e) => console.warn('Failed to set initial Realtime auth token:', e))\n    }\n\n    this.rest = new PostgrestClient(new URL('rest/v1', baseUrl).href, {\n      headers: this.headers,\n      schema: settings.db.schema,\n      fetch: this.fetch,\n      timeout: settings.db.timeout,\n      urlLengthLimit: settings.db.urlLengthLimit,\n      retry: settings.db.retry,\n    })\n\n    this.storage = new SupabaseStorageClient(\n      this.storageUrl.href,\n      this.headers,\n      this.fetch,\n      options?.storage\n    )\n\n    if (!settings.accessToken) {\n      this._listenForAuthEvents()\n    }\n  }\n\n  /**\n   * Supabase Functions allows you to deploy and invoke edge functions.\n   */\n  get functions(): FunctionsClient {\n    return new FunctionsClient(this.functionsUrl.href, {\n      headers: this.headers,\n      customFetch: this.functionsFetch,\n    })\n  }\n\n  // NOTE: signatures must be kept in sync with PostgrestClient.from\n  from<\n    TableName extends string & keyof Schema['Tables'],\n    Table extends Schema['Tables'][TableName],\n  >(relation: TableName): PostgrestQueryBuilder<ClientOptions, Schema, Table, TableName>\n  from<ViewName extends string & keyof Schema['Views'], View extends Schema['Views'][ViewName]>(\n    relation: ViewName\n  ): PostgrestQueryBuilder<ClientOptions, Schema, View, ViewName>\n  /**\n   * Perform a query on a table or a view.\n   *\n   * @param relation - The table or view name to query\n   */\n  from(relation: string): PostgrestQueryBuilder<ClientOptions, Schema, any> {\n    return this.rest.from(relation)\n  }\n\n  // NOTE: signatures must be kept in sync with PostgrestClient.schema\n  /**\n   * Select a schema to query or perform an function (rpc) call.\n   *\n   * The schema needs to be on the list of exposed schemas inside Supabase.\n   *\n   * @param schema - The schema to query\n   */\n  schema<DynamicSchema extends string & keyof Omit<Database, '__InternalSupabase'>>(\n    schema: DynamicSchema\n  ): PostgrestClient<\n    Database,\n    ClientOptions,\n    DynamicSchema,\n    Database[DynamicSchema] extends GenericSchema ? Database[DynamicSchema] : any\n  > {\n    return this.rest.schema<DynamicSchema>(schema)\n  }\n\n  // NOTE: signatures must be kept in sync with PostgrestClient.getOpenApiSpec\n  /**\n   * Fetch the OpenAPI description PostgREST publishes for this client's schema.\n   *\n   * The document lists only the tables, views and functions the caller's role\n   * holds privileges on. The request carries the same `apikey` and\n   * `Authorization` headers as every other query, so the description is scoped\n   * to the signed-in user. Call `.schema()` first to describe a schema other\n   * than the client default.\n   *\n   * @example\n   * ```ts\n   * const { data, error } = await supabase.getOpenApiSpec()\n   * ```\n   */\n  getOpenApiSpec(): Promise<PostgrestSingleResponse<PostgrestOpenApiSpec>> {\n    return this.rest.getOpenApiSpec()\n  }\n\n  // NOTE: signatures must be kept in sync with PostgrestClient.rpc\n  /**\n   * Perform a function call.\n   *\n   * @param fn - The function name to call\n   * @param args - The arguments to pass to the function call\n   * @param options - Named parameters\n   * @param options.head - When set to `true`, `data` will not be returned.\n   * Useful if you only need the count.\n   * @param options.get - When set to `true`, the function will be called with\n   * read-only access mode.\n   * @param options.count - Count algorithm to use to count rows returned by the\n   * function. Only applicable for [set-returning\n   * functions](https://www.postgresql.org/docs/current/functions-srf.html).\n   *\n   * `\"exact\"`: Exact but slow count algorithm. Performs a `COUNT(*)` under the\n   * hood.\n   *\n   * `\"planned\"`: Approximated but fast count algorithm. Uses the Postgres\n   * statistics under the hood.\n   *\n   * `\"estimated\"`: Uses exact count for low numbers and planned count for high\n   * numbers.\n   */\n  rpc<\n    FnName extends string & keyof Schema['Functions'],\n    Args extends Schema['Functions'][FnName]['Args'] = never,\n    FilterBuilder extends GetRpcFunctionFilterBuilderByArgs<Schema, FnName, Args> =\n      GetRpcFunctionFilterBuilderByArgs<Schema, FnName, Args>,\n  >(\n    fn: FnName,\n    args: Args = {} as Args,\n    options: {\n      head?: boolean\n      get?: boolean\n      count?: 'exact' | 'planned' | 'estimated'\n    } = {\n      head: false,\n      get: false,\n      count: undefined,\n    }\n  ): PostgrestFilterBuilder<\n    ClientOptions,\n    Schema,\n    FilterBuilder['Row'],\n    FilterBuilder['Result'],\n    FilterBuilder['RelationName'],\n    FilterBuilder['Relationships'],\n    'RPC'\n  > {\n    return this.rest.rpc(fn, args, options) as unknown as PostgrestFilterBuilder<\n      ClientOptions,\n      Schema,\n      FilterBuilder['Row'],\n      FilterBuilder['Result'],\n      FilterBuilder['RelationName'],\n      FilterBuilder['Relationships'],\n      'RPC'\n    >\n  }\n\n  /**\n   * Creates a Realtime channel with Broadcast, Presence, and Postgres Changes.\n   *\n   * @param {string} name - The name of the Realtime channel.\n   * @param {Object} opts - The options to pass to the Realtime channel.\n   *\n   * @category Realtime\n   */\n  channel(name: string, opts: RealtimeChannelOptions = { config: {} }): RealtimeChannel {\n    return this.realtime.channel(name, opts)\n  }\n\n  /**\n   * Returns all Realtime channels.\n   *\n   * @category Realtime\n   *\n   * @example Get all channels\n   * ```js\n   * const channels = supabase.getChannels()\n   * ```\n   */\n  getChannels(): RealtimeChannel[] {\n    return this.realtime.getChannels()\n  }\n\n  /**\n   * Unsubscribes and removes Realtime channel from Realtime client.\n   *\n   * @param {RealtimeChannel} channel - The name of the Realtime channel.\n   *\n   *\n   * @category Realtime\n   *\n   * @remarks\n   * - Removing a channel is a great way to maintain the performance of your project's Realtime service as well as your database if you're listening to Postgres changes. Supabase will automatically handle cleanup 30 seconds after a client is disconnected, but unused channels may cause degradation as more clients are simultaneously subscribed.\n   *\n   * @example Removes a channel\n   * ```js\n   * supabase.removeChannel(myChannel)\n   * ```\n   */\n  removeChannel(channel: RealtimeChannel): Promise<RealtimeRemoveChannelResponse> {\n    return this.realtime.removeChannel(channel)\n  }\n\n  /**\n   * Unsubscribes and removes all Realtime channels from Realtime client.\n   *\n   * @category Realtime\n   *\n   * @remarks\n   * - Removing channels is a great way to maintain the performance of your project's Realtime service as well as your database if you're listening to Postgres changes. Supabase will automatically handle cleanup 30 seconds after a client is disconnected, but unused channels may cause degradation as more clients are simultaneously subscribed.\n   *\n   * @example Remove all channels\n   * ```js\n   * supabase.removeAllChannels()\n   * ```\n   */\n  removeAllChannels(): Promise<RealtimeRemoveChannelResponse[]> {\n    return this.realtime.removeAllChannels()\n  }\n\n  /**\n   * The raw session token — the custom `accessToken` result or the signed-in user's JWT —\n   * or `null` when there is no session. Unlike {@link _getAccessToken} it does not fall back\n   * to `supabaseKey`, so callers can distinguish \"no session\" from \"has session\".\n   */\n  private async _getSessionToken(): Promise<string | null> {\n    if (this.accessToken) {\n      return await this.accessToken()\n    }\n\n    const { data } = await this.auth.getSession()\n\n    return data.session?.access_token ?? null\n  }\n\n  private async _getAccessToken() {\n    return (await this._getSessionToken()) ?? this.supabaseKey\n  }\n\n  private _initSupabaseAuthClient(\n    {\n      autoRefreshToken,\n      persistSession,\n      detectSessionInUrl,\n      storage,\n      userStorage,\n      storageKey,\n      flowType,\n      lock,\n      debug,\n      throwOnError,\n      experimental,\n      lockAcquireTimeout,\n      skipAutoInitialize,\n    }: SupabaseAuthClientOptions,\n    headers?: Record<string, string>,\n    fetch?: Fetch\n  ) {\n    const authHeaders = {\n      Authorization: `Bearer ${this.supabaseKey}`,\n      apikey: `${this.supabaseKey}`,\n    }\n    return new SupabaseAuthClient({\n      url: this.authUrl.href,\n      headers: { ...authHeaders, ...headers },\n      storageKey: storageKey,\n      autoRefreshToken,\n      persistSession,\n      detectSessionInUrl,\n      storage,\n      userStorage,\n      flowType,\n      lock,\n      debug,\n      throwOnError,\n      experimental,\n      fetch,\n      lockAcquireTimeout,\n      skipAutoInitialize,\n      // auth checks if there is a custom authorizaiton header using this flag\n      // so it knows whether to return an error when getUser is called with no session\n      hasCustomAuthorizationHeader: Object.keys(this.headers).some(\n        (key) => key.toLowerCase() === 'authorization'\n      ),\n    })\n  }\n\n  private _initRealtimeClient(options: RealtimeClientOptions) {\n    return new RealtimeClient(this.realtimeUrl.href, {\n      ...options,\n      params: { ...{ apikey: this.supabaseKey }, ...options?.params },\n    })\n  }\n\n  private _listenForAuthEvents() {\n    const data = this.auth.onAuthStateChange((event, session) => {\n      this._handleTokenChanged(event, 'CLIENT', session?.access_token)\n    })\n    return data\n  }\n\n  private _handleTokenChanged(\n    event: AuthChangeEvent,\n    source: 'CLIENT' | 'STORAGE',\n    token?: string\n  ) {\n    if (\n      (event === 'TOKEN_REFRESHED' || event === 'SIGNED_IN' || event === 'INITIAL_SESSION') &&\n      this.changedAccessToken !== token\n    ) {\n      this.changedAccessToken = token\n      this.realtime.setAuth(token)\n    } else if (event === 'SIGNED_OUT') {\n      this.realtime.setAuth()\n      if (source == 'STORAGE') this.auth.signOut()\n      this.changedAccessToken = undefined\n    }\n  }\n}\n", "import SupabaseClient from './SupabaseClient'\nimport type { SupabaseClientOptions } from './lib/types'\n\nexport * from '@supabase/auth-js'\nexport type { User as AuthUser, Session as AuthSession } from '@supabase/auth-js'\nexport type {\n  PostgrestResponse,\n  PostgrestSingleResponse,\n  PostgrestMaybeSingleResponse,\n  PostgrestOpenApiSpec,\n  PostgrestBuilder,\n  PostgrestFilterBuilder,\n  PostgrestTransformBuilder,\n  PostgrestQueryBuilder,\n} from '@supabase/postgrest-js'\nexport { PostgrestError } from '@supabase/postgrest-js'\nexport { StorageApiError } from '@supabase/storage-js'\nexport type { FunctionInvokeOptions } from '@supabase/functions-js'\nexport {\n  FunctionsHttpError,\n  FunctionsFetchError,\n  FunctionsRelayError,\n  FunctionsError,\n  FunctionRegion,\n} from '@supabase/functions-js'\nexport * from '@supabase/realtime-js'\nexport { default as SupabaseClient } from './SupabaseClient'\nexport type {\n  SupabaseClientOptions,\n  TracePropagationOptions,\n  QueryResult,\n  QueryData,\n  QueryError,\n  DatabaseWithoutInternals,\n} from './lib/types'\n\n/**\n * Creates a new Supabase Client.\n *\n * @example Creating a Supabase client\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.from('profiles').select('*')\n * ```\n */\nexport const createClient = <\n  Database = any,\n  SchemaNameOrClientOptions extends\n    | (string & keyof Omit<Database, '__InternalSupabase'>)\n    | { PostgrestVersion: string } = 'public' extends keyof Omit<Database, '__InternalSupabase'>\n    ? 'public'\n    : string & keyof Omit<Database, '__InternalSupabase'>,\n  SchemaName extends string & keyof Omit<Database, '__InternalSupabase'> =\n    SchemaNameOrClientOptions extends string & keyof Omit<Database, '__InternalSupabase'>\n      ? SchemaNameOrClientOptions\n      : 'public' extends keyof Omit<Database, '__InternalSupabase'>\n        ? 'public'\n        : string & keyof Omit<Omit<Database, '__InternalSupabase'>, '__InternalSupabase'>,\n>(\n  supabaseUrl: string,\n  supabaseKey: string,\n  options?: SupabaseClientOptions<SchemaName>\n): SupabaseClient<Database, SchemaNameOrClientOptions, SchemaName> => {\n  return new SupabaseClient<Database, SchemaNameOrClientOptions, SchemaName>(\n    supabaseUrl,\n    supabaseKey,\n    options\n  )\n}\n\n// Check for Node.js <= 20 deprecation\nfunction shouldShowDeprecationWarning(): boolean {\n  // Skip in browser and Deno environments\n  if (typeof window !== 'undefined' || (globalThis as any)['Deno'] !== undefined) {\n    return false\n  }\n\n  // Skip if process is not available (e.g., Edge Runtime)\n  // Use dynamic property access to avoid Next.js Edge Runtime static analysis warnings\n  const _process = (globalThis as any)['process']\n  if (!_process) {\n    return false\n  }\n\n  const processVersion = _process['version']\n  if (processVersion === undefined || processVersion === null) {\n    return false\n  }\n\n  const versionMatch = processVersion.match(/^v(\\d+)\\./)\n  if (!versionMatch) {\n    return false\n  }\n\n  const majorVersion = parseInt(versionMatch[1], 10)\n  return majorVersion <= 20\n}\n\nif (shouldShowDeprecationWarning()) {\n  console.warn(\n    `⚠️  Node.js 20 and below are deprecated and will no longer be supported in future versions of @supabase/supabase-js. ` +\n      `Please upgrade to Node.js 22 or later. ` +\n      `For more information, visit: https://github.com/orgs/supabase/discussions/45715`\n  )\n}\n", "import {Capacitor} from '@capacitor/core';\nimport {Filesystem,Directory,Encoding} from '@capacitor/filesystem';\nimport {Share} from '@capacitor/share';\nlet queue=Promise.resolve();\nexport const serial=fn=>{const p=queue.then(fn,fn);queue=p.catch(()=>{});return p;};\nconst filename=key=>'ledger-'+key.replace(/[^a-zA-Z0-9_-]/g,'_')+'.json';\nasync function nativeSlots(key){const slots=[];let corrupt=0;for(const slot of ['a','b']){try{const raw=(await Filesystem.readFile({path:filename(key)+'.'+slot,directory:Directory.Data,encoding:Encoding.UTF8})).data;try{const value=JSON.parse(raw);if(value.storageVersion!==1||!Number.isSafeInteger(value.generation))throw new Error('Invalid storage record');slots.push({...value,slot});}catch{corrupt++;}}catch(e){if(!/not exist|not found|ENOENT/i.test(e.message||''))throw e;}}if(!slots.length&&corrupt)throw new Error('Both saved copies could not be read. They have not been overwritten. Restore a backup.');return slots.sort((a,b)=>b.generation-a.generation);}\nasync function db(){return new Promise((resolve,reject)=>{const r=indexedDB.open('character-ledger',1);r.onupgradeneeded=()=>r.result.createObjectStore('records');r.onsuccess=()=>resolve(r.result);r.onerror=()=>reject(r.error);});}\nexport async function readRecord(key){\n if(Capacitor.isNativePlatform()){\n  return (await nativeSlots(key))[0]?.payload||null;\n }\n const conn=await db();return new Promise((resolve,reject)=>{const tx=conn.transaction('records');const r=tx.objectStore('records').get(key);r.onsuccess=()=>resolve(r.result||null);r.onerror=()=>reject(r.error);tx.oncomplete=()=>conn.close();});\n}\nexport async function writeRecord(key,value){\n if(Capacitor.isNativePlatform()){\n  // Alternate generations so an interrupted write cannot erase the last complete save.\n  const previous=(await nativeSlots(key))[0];const slot=previous?.slot==='a'?'b':'a';\n  await Filesystem.writeFile({path:filename(key)+'.'+slot,directory:Directory.Data,encoding:Encoding.UTF8,data:JSON.stringify({storageVersion:1,generation:(previous?.generation||0)+1,payload:value})});return;\n }\n const conn=await db();return new Promise((resolve,reject)=>{const tx=conn.transaction('records','readwrite');tx.objectStore('records').put(value,key);tx.oncomplete=()=>{conn.close();resolve();};tx.onerror=()=>{conn.close();reject(tx.error);};tx.onabort=()=>reject(tx.error||new Error('Save was interrupted.'));});\n}\nexport async function exportFile(data,name,type='application/json'){\n if(Capacitor.isNativePlatform()){\n  let raw;if(data instanceof Blob){raw=await new Promise((resolve,reject)=>{const r=new FileReader();r.onload=()=>resolve(r.result.split(',')[1]);r.onerror=reject;r.readAsDataURL(data);});}else raw=data;\n  const safe=name.replace(/[^a-zA-Z0-9._ -]/g,'_');const result=await Filesystem.writeFile({path:safe,directory:Directory.Cache,data:raw,...(data instanceof Blob?{}:{encoding:Encoding.UTF8})});\n  await Share.share({title:name,files:[result.uri],dialogTitle:'Save or share file'});return;\n }\n const blob=data instanceof Blob?data:new Blob([data],{type});const url=URL.createObjectURL(blob);const a=document.createElement('a');a.href=url;a.download=name;document.body.append(a);a.click();a.remove();setTimeout(()=>URL.revokeObjectURL(url),60000);\n}\n", "import { registerPlugin } from '@capacitor/core';\nimport { exposeSynapse } from '@capacitor/synapse';\n\nimport type { FilesystemPlugin } from './definitions';\n\nconst Filesystem = registerPlugin<FilesystemPlugin>('Filesystem', {\n  web: () => import('./web').then((m) => new m.FilesystemWeb()),\n});\n\nexposeSynapse();\n\nexport * from './definitions';\nexport { Filesystem };\n", "function s(t) {\n  t.CapacitorUtils.Synapse = new Proxy(\n    {},\n    {\n      get(e, n) {\n        return new Proxy({}, {\n          get(w, o) {\n            return (c, p, r) => {\n              const i = t.Capacitor.Plugins[n];\n              if (i === void 0) {\n                r(new Error(`Capacitor plugin ${n} not found`));\n                return;\n              }\n              if (typeof i[o] != \"function\") {\n                r(new Error(`Method ${o} not found in Capacitor plugin ${n}`));\n                return;\n              }\n              (async () => {\n                try {\n                  const a = await i[o](c);\n                  p(a);\n                } catch (a) {\n                  r(a);\n                }\n              })();\n            };\n          }\n        });\n      }\n    }\n  );\n}\nfunction u(t) {\n  t.CapacitorUtils.Synapse = new Proxy(\n    {},\n    {\n      get(e, n) {\n        return t.cordova.plugins[n];\n      }\n    }\n  );\n}\nfunction f(t = !1) {\n  typeof window > \"u\" || (window.CapacitorUtils = window.CapacitorUtils || {}, window.Capacitor !== void 0 && !t ? s(window) : window.cordova !== void 0 && u(window));\n}\nexport {\n  f as exposeSynapse\n};\n", "import { registerPlugin } from '@capacitor/core';\n\nimport type { SharePlugin } from './definitions';\n\nconst Share = registerPlugin<SharePlugin>('Share', {\n  web: () => import('./web').then((m) => new m.ShareWeb()),\n});\n\nexport * from './definitions';\nexport { Share };\n", "const equal=(a,b)=>JSON.stringify(a)===JSON.stringify(b);\nexport function mergeCollection(base,local,remote,newId=()=>crypto.randomUUID()){\n const result=structuredClone(remote),conflicts=[];\n for(const key of ['characters','library']){\n  const b=new Map((base[key]||[]).map(x=>[x.id,x])),l=new Map((local[key]||[]).map(x=>[x.id,x])),r=new Map((remote[key]||[]).map(x=>[x.id,x])),out=[];\n  for(const id of new Set([...b.keys(),...l.keys(),...r.keys()])){\n   const before=b.get(id),mine=l.get(id),theirs=r.get(id);\n   if(equal(mine,theirs)){if(mine)out.push(mine);continue;}\n   if(equal(mine,before)){if(theirs)out.push(theirs);continue;}\n   if(equal(theirs,before)){if(mine)out.push(mine);continue;}\n   if(theirs)out.push(theirs);\n   if(mine){out.push({...mine,id:newId(),name:mine.name+' (conflict copy)'});conflicts.push(mine.name);}\n   else if(theirs)conflicts.push(theirs.name+' (edited elsewhere; deletion not applied)');\n  }\n  result[key]=out;\n }\n if(local.adventure!==base.adventure){if(remote.adventure===base.adventure)result.adventure=local.adventure;else if(local.adventure!==remote.adventure){result.nameConflicts=[...(remote.nameConflicts||[]),local.adventure];conflicts.push('Adventure name: '+local.adventure);}}\n return {document:result,conflicts};\n}\nexport function validateCollection(s){\n if(!s||s.format!=='character-ledger'||s.version!==1||typeof s.adventure!=='string'||s.adventure.length>300||!Array.isArray(s.characters)||s.characters.length>2000)throw new Error('Not a valid Character Ledger collection.');\n const ids=new Set();for(const c of s.characters){if(!c||typeof c.id!=='string'||ids.has(c.id)||typeof c.name!=='string'||!c.name.trim()||c.name.length>250||!['PC','NPC'].includes(c.kind)||!c.fields||typeof c.fields!=='object'||Array.isArray(c.fields))throw new Error('Invalid character record.');ids.add(c.id);for(const v of Object.values(c.fields))if(typeof v!=='string'||v.length>500000)throw new Error('Invalid character field.');if(c.source&&(typeof c.source.data!=='string'||typeof c.source.name!=='string'||c.source.data.length>42000000||!/^[A-Za-z0-9+/]*={0,2}$/.test(c.source.data)))throw new Error('Invalid attached file.');}\n if(s.library!=null&&(!Array.isArray(s.library)||s.library.some(x=>!x||typeof x.id!=='string'||typeof x.name!=='string'||typeof x.description!=='string')))throw new Error('Invalid custom library.');\n if(JSON.stringify(s).length>50000000)throw new Error('This collection exceeds the 50 MB sync limit. Split it into smaller adventures.');return s;\n}\n", "import {createClient} from '@supabase/supabase-js';\nimport {readRecord,writeRecord,serial} from './storage.mjs';\nimport {mergeCollection,validateCollection} from './merge.mjs';\nexport let cloud=null,user=null,activeId='local',role='owner';\nlet envelope,key='guest-local',profile={active:'local',entries:[]};\nexport let syncStatus='Stored on this device';\nconst empty=()=>({format:'character-ledger',version:1,revision:0,adventure:'',characters:[],library:[]});\nexport async function init(){const config=await(await fetch('./config.json')).json();if(config.supabaseUrl&&config.supabasePublishableKey){cloud=createClient(config.supabaseUrl,config.supabasePublishableKey);const {data}=await cloud.auth.getSession();user=data.session?.user||null;}profile=await readRecord('profile-'+(user?.id||'guest'))||{active:'local',entries:[]};await switchCollection(profile.active,profile.entries.find(x=>x.id===profile.active)?.role||'owner');}\nexport async function switchCollection(id,nextRole='owner'){\n return serial(async()=>{const nextKey=(user?.id||'guest')+'-'+id;let next=await readRecord(nextKey);if(!next){const doc=empty();next={document:doc,base:doc,remoteRevision:0,dirty:false};if(id!=='local'){const {data,error}=await cloud.from('ledger_collections').select('document,revision').eq('id',id).single();if(error)throw error;next={document:data.document,base:data.document,remoteRevision:data.revision,dirty:false};}else if(user){const guest=await readRecord('guest-local');if(guest?.document?.characters?.length)next=structuredClone(guest);}await writeRecord(nextKey,next);}validateCollection(next.document);activeId=id;role=nextRole;key=nextKey;envelope=next;profile.active=id;await writeRecord('profile-'+(user?.id||'guest'),profile);syncStatus=envelope.dirty?'Saved here; waiting to sync':'Stored on this device';return structuredClone(envelope.document);});\n}\nexport async function getState(){return serial(async()=>structuredClone(envelope.document));}\nexport async function saveState(next){return serial(async()=>{validateCollection(next);if(role==='viewer')throw new Error('You have viewer access to this adventure.');if(next.revision!==envelope.document.revision)throw new Error('This sheet changed while your editor was open. Keep your changes, refresh and review both versions.');const doc={...next,revision:next.revision+1,savedAt:new Date().toISOString()};const updated={...envelope,document:doc,dirty:activeId!=='local'};await writeRecord(key,updated);envelope=updated;syncStatus=updated.dirty?'Saved here; waiting to sync':'Saved on this device';return structuredClone(doc);});}\nexport async function sync(){return serial(async()=>{\n if(!cloud||!user||activeId==='local')return {changed:false};\n const {data:remote,error}=await cloud.from('ledger_collections').select('document,revision').eq('id',activeId).single();if(error){syncStatus='Saved here; sync unavailable';throw error;}\n if(!envelope.dirty){if(remote.revision===envelope.remoteRevision){syncStatus='Synced';return {changed:false};}const doc={...remote.document,revision:envelope.document.revision+1};const next={document:doc,base:doc,remoteRevision:remote.revision,dirty:false};await writeRecord(key,next);envelope=next;syncStatus='Synced';return {changed:true};}\n let doc=envelope.document,conflicts=[];if(remote.revision!==envelope.remoteRevision){const merged=mergeCollection(envelope.base,doc,remote.document);doc=merged.document;conflicts=merged.conflicts;}\n validateCollection(doc);\n const {data,error:writeError}=await cloud.rpc('ledger_save',{collection_id:activeId,expected_revision:remote.revision,new_document:doc});if(writeError){syncStatus='Saved here; sync will retry';throw writeError;}\n doc={...doc,revision:envelope.document.revision+1};const next={document:doc,base:doc,remoteRevision:data,dirty:false};await writeRecord(key,next);envelope=next;syncStatus=conflicts.length?'Synced; conflict copies need review':'Synced';return {changed:true,conflicts};\n});}\nexport async function signIn(email,password){if(!cloud)throw new Error('Cloud setup is not configured in this build yet.');const {data,error}=await cloud.auth.signInWithPassword({email,password});if(error)throw error;user=data.user;profile=await readRecord('profile-'+user.id)||{active:'local',entries:[]};await switchCollection(profile.active,profile.entries.find(x=>x.id===profile.active)?.role||'owner');}\nexport async function signUp(email,password){if(!cloud)throw new Error('Cloud setup is not configured in this build yet.');const {error}=await cloud.auth.signUp({email,password});if(error)throw error;return 'Check your email to confirm your account, then sign in.';}\nexport async function signOut(){if(cloud)await cloud.auth.signOut();user=null;profile={active:'local',entries:[]};await switchCollection('local');}\nexport async function collections(){if(!cloud||!user)return [];try{const {data,error}=await cloud.rpc('ledger_list');if(error)throw error;profile.entries=data;await writeRecord('profile-'+user.id,profile);if(activeId!=='local'){const current=data.find(x=>x.id===activeId);role=current?.role||'viewer';}return data;}catch(e){if(profile.entries.length)return profile.entries;throw e;}}\nexport async function publishLocal(){if(!user)throw new Error('Sign in first.');const doc=await getState();const {data,error}=await cloud.rpc('ledger_create',{new_document:doc});if(error)throw error;await switchCollection(data,'owner');return data;}\nexport async function invite(email,access){const {data,error}=await cloud.rpc('ledger_invite',{collection_id:activeId,invite_email:email,invite_role:access});if(error)throw error;return data;}\nexport async function join(code){const {data,error}=await cloud.rpc('ledger_join',{invite_code:code.trim()});if(error)throw error;const items=await collections();await switchCollection(data,items.find(x=>x.id===data)?.role||'viewer');}\nexport async function members(){const {data,error}=await cloud.rpc('ledger_members',{collection_id:activeId});if(error)throw error;return data;}\nexport async function removeMember(memberId){const {error}=await cloud.rpc('ledger_remove_member',{collection_id:activeId,member_id:memberId});if(error)throw error;}\n", "import * as repo from './repository.mjs';\nconst esc=s=>String(s??'').replace(/[&<>\"']/g,c=>({'&':'&amp;','<':'&lt;','>':'&gt;','\"':'&quot;',\"'\":'&#39;'}[c]));\nexport function setupAccount({onChange,canSwitch}){\n const dialog=document.createElement('dialog');dialog.id='accountDialog';document.body.append(dialog);\n let notice='';\n const run=async action=>{try{if(!canSwitch())throw new Error('Save or close your current edit first.');await action();await onChange();await render();}catch(e){notice=e.message;const el=dialog.querySelector('[data-status]');if(el)el.textContent=notice;}};\n async function render(){\n  let list=[];try{list=await repo.collections();}catch(e){notice='Offline: cached collection remains available. '+e.message;}\n  dialog.innerHTML=`<header class=\"dialog-header\"><div><span class=\"eyebrow\">YOUR ADVENTURES</span><h2>Account & sharing</h2></div><button class=\"icon\" data-close aria-label=\"Close\">\u2715</button></header><p data-status role=\"status\">${esc(notice)}</p>${!repo.cloud?'<p>Cloud setup is pending for this build. Characters and backups work on this device; sharing and automatic sync will become available when the private database is connected.</p>':!repo.user?`<p>Sign in with the same account on your other devices to sync your adventures. Friends can use their own accounts to join an invitation.</p><form id=\"accountSignIn\"><label>Email<input name=\"email\" type=\"email\" required autocomplete=\"email\"></label><label>Password<input name=\"password\" type=\"password\" required minlength=\"8\" autocomplete=\"current-password\"></label><div class=\"action-row\"><button class=\"primary\" name=\"action\" value=\"signin\">Sign in</button><button name=\"action\" value=\"signup\">Create account</button></div></form>`:`<p>Signed in as <strong>${esc(repo.user.email)}</strong>. Local changes remain on this device until they sync successfully.</p><label>Adventure<select id=\"collectionSelect\"><option value=\"local\" ${repo.activeId==='local'?'selected':''}>Local collection (not shared)</option>${list.map(x=>`<option value=\"${esc(x.id)}\" ${repo.activeId===x.id?'selected':''}>${esc(x.name||'Untitled adventure')} \u00B7 ${esc(x.role)}</option>`).join('')}</select></label><div class=\"action-row\"><button id=\"syncNow\">Sync now</button><button id=\"signOut\">Sign out</button></div>${repo.activeId==='local'?'<button id=\"publishLocal\" class=\"primary full\">Sync this collection to my account</button>':`<p class=\"subtle\">Your access: ${esc(repo.role)}. Changes sync automatically while the app is open and connected.</p>`}<form id=\"joinForm\"><h3>Join a friend's adventure</h3><label>Invitation code<input name=\"code\" required autocomplete=\"off\"></label><button>Join adventure</button></form>${repo.activeId!=='local'&&repo.role==='owner'?`<form id=\"inviteForm\"><h3>Invite a friend</h3><label>Friend's account email<input type=\"email\" name=\"email\" required></label><label>Access<select name=\"role\"><option value=\"editor\">Editor: upload and edit characters</option><option value=\"viewer\">Viewer: read only</option></select></label><button>Create invitation code</button><p class=\"subtle\">Send the generated code to your friend. It works only with their confirmed account email and expires after seven days.</p></form><textarea id=\"inviteCode\" aria-label=\"Invitation code\" readonly hidden></textarea><button id=\"showMembers\">Manage members</button><div id=\"members\"></div>`:''}`}`;\n  dialog.querySelector('[data-close]').onclick=()=>dialog.close();\n  const q=id=>dialog.querySelector('#'+id);\n  if(q('accountSignIn'))q('accountSignIn').onsubmit=e=>{e.preventDefault();const fd=new FormData(e.target);const type=e.submitter.value;run(async()=>{if(type==='signin'){await repo.signIn(fd.get('email'),fd.get('password'));notice='Signed in.';}else notice=await repo.signUp(fd.get('email'),fd.get('password'));});};\n  if(q('collectionSelect'))q('collectionSelect').onchange=e=>run(async()=>{const id=e.target.value;await repo.switchCollection(id,list.find(x=>x.id===id)?.role||'owner');notice='Adventure opened.';});\n  if(q('signOut'))q('signOut').onclick=()=>run(async()=>{await repo.signOut();notice='Signed out. Cloud collections remain saved under your account on this device.';});\n  if(q('syncNow'))q('syncNow').onclick=()=>run(async()=>{const r=await repo.sync();notice=r.conflicts?.length?'Sync finished. Conflict copies were kept for review.':repo.syncStatus;});\n  if(q('publishLocal'))q('publishLocal').onclick=()=>run(async()=>{await repo.publishLocal();notice='Collection is now connected to your account.';});\n  if(q('joinForm'))q('joinForm').onsubmit=e=>{e.preventDefault();const code=new FormData(e.target).get('code');run(async()=>{await repo.join(code);notice='Joined adventure.';});};\n  if(q('inviteForm'))q('inviteForm').onsubmit=async e=>{e.preventDefault();const fd=new FormData(e.target);try{const code=await repo.invite(fd.get('email'),fd.get('role'));q('inviteCode').hidden=false;q('inviteCode').value=code;q('inviteCode').select();}catch(err){dialog.querySelector('[data-status]').textContent=err.message;}};\n  if(q('showMembers'))q('showMembers').onclick=async()=>{try{const people=await repo.members();q('members').innerHTML=people.length?people.map(p=>`<div class=\"member-row\"><span>${esc(p.email)} \u00B7 ${esc(p.role)}</span><button data-remove=\"${esc(p.user_id)}\">Remove access</button></div>`).join(''):'<p>No friends have joined yet.</p>';q('members').onclick=async e=>{const b=e.target.closest('[data-remove]');if(b&&confirm('Remove this member\u2019s cloud access? Previously downloaded copies cannot be remotely erased.')){try{await repo.removeMember(b.dataset.remove);b.parentElement.remove();}catch(err){dialog.querySelector('[data-status]').textContent=err.message;}}};}catch(e){dialog.querySelector('[data-status]').textContent=e.message;}};\n }\n document.getElementById('phoneButton').onclick=async()=>{document.body.classList.remove('menu-open');document.getElementById('scrim').hidden=true;await render();dialog.showModal();};\n}\n", "export async function loadRules(){const names=['Classes','Levels','Spells','Features','Subclasses'];const data=await Promise.all(names.map(async n=>{const r=await fetch('./rules/'+n+'.json');if(!r.ok)throw new Error('The bundled rules could not be read.');return r.json();}));return Object.fromEntries(names.map((n,i)=>[n.toLowerCase(),data[i]]));}\nexport const slug=s=>s.toLowerCase().trim().replace(/[^a-z0-9]+/g,'-');\nexport function inferredClasses(character,rules,library=[]){\n if(character.progression?.classes?.length)return structuredClone(character.progression.classes);\n const text=character.fields.classLevel||'';const found=[];for(const cls of [...rules.classes,...library.filter(e=>e.kind==='class').map(e=>({index:slug(e.name),name:e.name}))]){const escaped=cls.name.replace(/[.*+?^${}()|[\\]\\\\]/g,'\\\\$&');const re=new RegExp('\\\\b'+escaped+'\\\\s*(?:level\\\\s*)?(\\\\d{1,2})\\\\b','i');const m=text.match(re);if(m)found.push({index:cls.index,name:cls.name,level:Number(m[1]),subclass:''});}return found;\n}\nexport function levelPlan(character,classes,target,subclass,rules,library=[]){\n const cls=rules.classes.find(c=>c.index===target)||library.filter(e=>e.kind==='class').map(e=>({index:slug(e.name),name:e.name,hit_die:Number(e.hitDie)||8,custom:true})).find(e=>e.index===target);\n if(!cls)throw new Error('Choose a class.');\n const total=classes.reduce((n,c)=>n+c.level,0),previous=classes.find(c=>c.index===target)?.level||0,next=previous+1;\n if(total>=20)throw new Error('The 2014 class tables end at character level 20.');\n if(classes.some(c=>!Number.isInteger(c.level)||c.level<1||c.level>20))throw new Error('Check the current class levels.');\n const table=rules.levels.find(l=>l.class.index===target&&!l.subclass&&l.level===next);\n const subtable=rules.levels.find(l=>l.subclass?.index===subclass&&l.level===next);\n const refs=[...(table?.features||[]),...(subtable?.features||[])];\n const features=refs.map(ref=>rules.features.find(f=>f.index===ref.index)||{name:ref.name,desc:['Check the class reference for this feature.']});\n for(const e of library.filter(e=>e.kind==='feature'&&slug(e.className||'')===target&&Number(e.level)===next&&(!e.subclass||slug(e.subclass)===subclass)))features.push({name:e.name,desc:[e.description]});\n const before=rules.levels.find(l=>l.class.index===target&&!l.subclass&&l.level===previous);\n const asi=(table?.ability_score_bonuses||0)>(before?.ability_score_bonuses||0);\n return {cls,total,previous,next,table,features,asi,proficiency:2+Math.floor(total/4),subclass};\n}\nconst mod=n=>Math.floor((Number(n)-10)/2);\nfunction slotSummary(classes,rules){\n const parts=[];const casters=classes.filter(c=>['bard','cleric','druid','sorcerer','wizard'].includes(c.index)||(['paladin','ranger'].includes(c.index)&&c.level>=2));\n let table;\n if(casters.length===1)table=rules.levels.find(l=>!l.subclass&&l.class.index===casters[0].index&&l.level===casters[0].level)?.spellcasting;\n else if(casters.length>1){const effective=casters.reduce((n,c)=>n+(['paladin','ranger'].includes(c.index)?Math.floor(c.level/2):c.level),0);table=rules.levels.find(l=>!l.subclass&&l.class.index==='wizard'&&l.level===effective)?.spellcasting;}\n if(table)parts.push('Spell slots: '+Array.from({length:9},(_,i)=>[i+1,table['spell_slots_level_'+(i+1)]||0]).filter(([,n])=>n).map(([l,n])=>`level ${l}: ${n}`).join('; '));\n const warlock=classes.find(c=>c.index==='warlock');if(warlock){const p=rules.levels.find(l=>!l.subclass&&l.class.index==='warlock'&&l.level===warlock.level)?.spellcasting;if(p)parts.push('Pact Magic (short-rest slots): '+Array.from({length:9},(_,i)=>[i+1,p['spell_slots_level_'+(i+1)]||0]).filter(([,n])=>n).map(([l,n])=>`level ${l}: ${n}`).join('; '));}\n return parts.join('\\n');\n}\nexport function applyLevel(character,classes,plan,choices,rules){\n const c=structuredClone(character),f=c.fields,originalCon=f.con;\n if(!/^\\d+$/.test(f.maxHp)||!/^\\d+$/.test(f.con))throw new Error('Enter numeric maximum HP and Constitution in the sheet first.');\n const increases=choices.increases||{};const points=Object.values(increases).reduce((n,v)=>n+Number(v),0);\n if(plan.asi&&!choices.feat&&points!==2)throw new Error('Allocate two ability-score points or enter a feat choice.');\n if(!plan.asi&&points)throw new Error('This level does not grant an ability-score improvement.');\n if(choices.feat&&points)throw new Error('Choose a feat or an ability-score improvement, not both.');\n for(const [k,amount]of Object.entries(increases)){if(!['str','dex','con','int','wis','cha'].includes(k)||!Number.isInteger(amount)||amount<0||amount>2)throw new Error('Invalid ability increase.');if(amount){if(!/^\\d+$/.test(f[k]))throw new Error('Enter a numeric '+k.toUpperCase()+' score first.');if(Number(f[k])+amount>20)throw new Error('An ability-score improvement cannot raise a score above 20.');f[k]=String(Number(f[k])+amount);}}\n if(plan.cls.index==='barbarian'&&plan.next===20){for(const k of ['str','con']){if(!/^\\d+$/.test(f[k]))throw new Error('Enter numeric STR and CON for Primal Champion.');f[k]=String(Math.min(24,Number(f[k])+4));}}\n const roll=Number(choices.hitDie);if(!Number.isInteger(roll)||roll<1||roll>plan.cls.hit_die)throw new Error('Enter a hit-die result between 1 and '+plan.cls.hit_die+'.');\n const extra=Number(choices.extraHp||0);if(!Number.isInteger(extra)||Math.abs(extra)>100)throw new Error('Check the additional HP adjustment.');\n const gain=Math.max(1,roll+mod(f.con))+(mod(f.con)-mod(originalCon))*plan.total+extra;\n if(Number(f.maxHp)+gain<1)throw new Error('Maximum HP must remain positive.');\n f.maxHp=String(Number(f.maxHp)+gain);if(choices.increaseCurrent&&/^\\d+$/.test(f.hp))f.hp=String(Math.min(Number(f.maxHp),Number(f.hp)+gain));\n const updated=structuredClone(classes),existing=updated.find(x=>x.index===plan.cls.index);if(existing){existing.level=plan.next;existing.subclass=plan.subclass;}else updated.push({index:plan.cls.index,name:plan.cls.name,level:1,subclass:plan.subclass});\n c.progression={classes:updated};f.classLevel=updated.map(x=>x.name+' '+x.level).join(' / ');f.proficiency='+'+plan.proficiency;\n const additions=plan.features.map(x=>`${x.name}\\n${(x.desc||[]).join('\\n')}`).join('\\n\\n');f.traits=[f.traits,additions,choices.feat?'Feat choice: '+choices.feat:'',choices.decisions?'Level-up choices: '+choices.decisions:''].filter(Boolean).join('\\n\\n');\n const slots=slotSummary(updated,rules);if(slots)f.spellSlots=slots;\n const record=[`${plan.cls.name} ${plan.previous} \u2192 ${plan.next}: maximum HP ${gain>=0?'+':''}${gain}; proficiency +${plan.proficiency}.`,plan.table?.spellcasting?'Class spellcasting totals: '+JSON.stringify(plan.table.spellcasting):'',plan.table?.class_specific?'Class resources: '+JSON.stringify(plan.table.class_specific):'',choices.decisions].filter(Boolean).join('\\n');f.notes=[f.notes,record].filter(Boolean).join('\\n\\n');\n return c;\n}\nexport function spellText(spell){return [spell.name,`Level ${spell.level} ${spell.school?.name||''} | ${spell.casting_time||''} | Range: ${spell.range||''}`,`Components: ${(spell.components||[]).join(', ')}${spell.material?' ('+spell.material+')':''}`,`Duration: ${spell.duration||''}${spell.concentration?' (concentration)':''}${spell.ritual?' | Ritual':''}`,...(spell.desc||[]),...(spell.higher_level||[])].join('\\n');}\n", "import {loadRules,spellText,slug,inferredClasses,levelPlan,applyLevel} from './rules.mjs';\nimport {abilities,labels} from './model.mjs';\nconst esc=s=>String(s??'').replace(/[&<>\"']/g,c=>({'&':'&amp;','<':'&lt;','>':'&gt;','\"':'&quot;',\"'\":'&#39;'}[c]));\nlet rulesPromise;\nconst rules=()=>rulesPromise??=loadRules();\nexport function setupLibrary({getState,getSelected,commit,refresh}){\n const dialog=document.createElement('dialog');dialog.id='libraryDialog';document.body.append(dialog);\n const levelDialog=document.createElement('dialog');document.body.append(levelDialog);\n let query='',classFilter='',levelFilter='',mode='spells';\n async function open(){await render();dialog.showModal();}\n async function render(){\n  const r=await rules(),state=getState(),custom=state.library||[],selected=getSelected();\n  dialog.innerHTML=`<header class=\"dialog-header\"><div><span class=\"eyebrow\">2014 FIFTH EDITION</span><h2>Rules & spell library</h2></div><button data-close class=\"icon\" aria-label=\"Close\">\u2715</button></header><p class=\"subtle\">${r.spells.length} SRD spells, 12 classes and their SRD subclasses are built in. Add your own material for other options; custom entries are saved with this adventure.</p><div class=\"action-row\"><button data-mode=\"spells\">Spells</button><button data-mode=\"features\">Features</button><button data-mode=\"custom\">My material</button><button id=\"addMaterial\">\uFF0B Add material</button><button id=\"importMaterial\">Import library JSON</button><input id=\"materialFile\" type=\"file\" accept=\".json\" hidden></div><div class=\"library-filters\"><input id=\"librarySearch\" aria-label=\"Search library\" placeholder=\"Search ${mode}\" value=\"${esc(query)}\"><select id=\"libraryClass\" aria-label=\"Filter by class\"><option value=\"\">All classes</option>${r.classes.map(c=>`<option value=\"${c.index}\" ${classFilter===c.index?'selected':''}>${c.name}</option>`).join('')}</select><select id=\"libraryLevel\" aria-label=\"Filter by level\"><option value=\"\">All levels</option>${Array.from({length:mode==='spells'?10:21},(_,i)=>`<option value=\"${i}\" ${String(i)===levelFilter?'selected':''}>${i===0?'Cantrip / unspecified':'Level '+i}</option>`).join('')}</select></div><p id=\"libraryMessage\" role=\"status\"></p><p class=\"subtle\">${selected?'Add entries to '+esc(selected.name)+'.':'Select a character first to add entries to a sheet.'}</p><div id=\"libraryResults\"></div><p class=\"subtle\"><a href=\"ATTRIBUTION.txt\" target=\"_blank\">Rules sources and attribution</a></p>`;\n  const q=id=>dialog.querySelector('#'+id);\n  dialog.querySelector('[data-close]').onclick=()=>dialog.close();\n  dialog.querySelectorAll('[data-mode]').forEach(b=>b.onclick=()=>{mode=b.dataset.mode;query='';levelFilter='';render();});\n  q('librarySearch').oninput=e=>{query=e.target.value;results();};q('libraryClass').onchange=e=>{classFilter=e.target.value;results();};q('libraryLevel').onchange=e=>{levelFilter=e.target.value;results();};\n  q('addMaterial').onclick=customForm;\n  q('importMaterial').onclick=()=>q('materialFile').click();q('materialFile').onchange=async e=>{try{const f=e.target.files[0];if(!f)return;if(f.size>5*1024*1024)throw new Error('Use a library file smaller than 5 MB.');let entries=JSON.parse(await f.text());if(entries.entries)entries=entries.entries;if(!Array.isArray(entries))throw new Error('Expected an array of custom entries.');entries=entries.map(validateEntry);const current=getState();await commit({...current,library:[...(current.library||[]),...entries]});refresh();await render();}catch(err){q('libraryMessage').textContent=err.message;}};\n  function results(){\n   const entries=mode==='spells'?[...r.spells.map(s=>({id:s.index,name:s.name,level:s.level,classNames:s.classes.map(c=>c.index),text:spellText(s),kind:'spell'})),...custom.filter(e=>e.kind==='spell').map(convert)]:mode==='features'?[...r.features.map(f=>({id:f.index,name:f.name,level:f.level,classNames:[f.class.index],text:f.name+'\\n'+f.desc.join('\\n\\n'),kind:'feature'})),...custom.filter(e=>e.kind==='feature').map(convert)]:custom.map(convert);\n   const found=entries.filter(e=>e.name.toLowerCase().includes(query.toLowerCase())&&(!classFilter||e.classNames.includes(classFilter))&&(!levelFilter||String(e.level)===levelFilter));\n   q('libraryResults').innerHTML=found.slice(0,80).map(e=>`<details class=\"library-entry\"><summary><strong>${esc(e.name)}</strong><span>${e.kind==='spell'&&e.level===0?'Cantrip':'Level '+(e.level||'custom')}</span></summary><p>${esc(e.text)}</p>${['spell','feature'].includes(e.kind)?`<button data-add=\"${esc(e.id)}\" ${selected?'':'disabled'}>Add to ${esc(selected?.name||'character')}</button>`:''}${mode==='custom'?`<button data-delete=\"${esc(e.id)}\" class=\"danger\">Remove custom entry</button>`:''}</details>`).join('')||'<p>No matching entries.</p>';\n   if(found.length>80)q('libraryResults').insertAdjacentHTML('beforeend','<p class=\"subtle\">Showing 80 results. Narrow your search to see more.</p>');\n   q('libraryResults').onclick=async event=>{const b=event.target.closest('[data-add]'),del=event.target.closest('[data-delete]');try{if(b){const entry=found.find(x=>x.id===b.dataset.add),c=getSelected();if(!c)throw new Error('Select a character first.');const key=entry.kind==='spell'?'spells':'traits';if((c.fields[key]||'').split('\\n').includes(entry.name))throw new Error('An entry with this name is already on the sheet.');const current=getState();const updated={...c,fields:{...c.fields,[key]:[c.fields[key],entry.text].filter(Boolean).join('\\n\\n')}};await commit({...current,characters:current.characters.map(x=>x.id===c.id?updated:x)});refresh();q('libraryMessage').textContent=entry.name+' added. Spell eligibility and prepared/known limits remain your choice.';}else if(del&&confirm('Remove this entry from the custom library? Existing character copies will stay.')){const current=getState();await commit({...current,library:current.library.filter(e=>e.id!==del.dataset.delete)});refresh();await render();}}catch(e){q('libraryMessage').textContent=e.message;}};\n  }\n  results();\n }\n function convert(e){return {...e,classNames:(e.className||'').split(',').map(slug),text:e.name+'\\n'+e.description};}\n function validateEntry(e){if(!e||!['spell','feature','class','subclass'].includes(e.kind)||typeof e.name!=='string'||!e.name.trim()||typeof e.description!=='string')throw new Error('Each custom entry needs kind (spell, feature, class or subclass), name and description.');return {id:crypto.randomUUID(),kind:e.kind,name:e.name.trim().slice(0,200),description:e.description.slice(0,500000),className:String(e.className||''),subclass:String(e.subclass||''),level:Number(e.level)||0,hitDie:Number(e.hitDie)||8,source:String(e.source||'User-supplied')};}\n function customForm(){\n  const d=document.createElement('dialog');document.body.append(d);d.innerHTML=`<form><header class=\"dialog-header\"><h2>Add custom material</h2><button type=\"button\" data-close class=\"icon\">\u2715</button></header><div class=\"form-grid\"><label>Type<select name=\"kind\"><option value=\"spell\">Spell</option><option value=\"feature\">Class / subclass feature</option><option value=\"class\">Class</option><option value=\"subclass\">Subclass</option></select></label><label class=\"wide\">Name<input name=\"name\" required maxlength=\"200\"></label><label>Class name(s)<input name=\"className\" placeholder=\"Wizard\"></label><label>Subclass name<input name=\"subclass\"></label><label>Spell level / feature gained at level<input name=\"level\" type=\"number\" min=\"0\" max=\"20\" value=\"0\"></label><label>Class hit die<select name=\"hitDie\"><option>6</option><option selected>8</option><option>10</option><option>12</option></select></label><label class=\"wide\">Description or pasted rules<textarea name=\"description\" required rows=\"10\"></textarea></label><label class=\"wide\">Source note<input name=\"source\" placeholder=\"My homebrew / source reference\"></label></div><p class=\"subtle\">For custom progression, add a class and separate feature entries with its class name and the level each feature is gained. Add the subclass name to subclass-specific features. Custom spell-slot tables and other calculations remain manual.</p><p data-error role=\"alert\"></p><div class=\"dialog-actions\"><button class=\"primary\">Save to library</button></div></form>`;d.querySelector('[data-close]').onclick=()=>{d.close();d.remove();};d.querySelector('form').onsubmit=async e=>{e.preventDefault();try{const entry=validateEntry(Object.fromEntries(new FormData(e.target)));const current=getState();await commit({...current,library:[...(current.library||[]),entry]});refresh();d.close();d.remove();await render();}catch(err){d.querySelector('[data-error]').textContent=err.message;}};d.showModal();\n }\n async function levelUp(){\n  const r=await rules(),c=getSelected();if(!c)return;const state=getState(),library=state.library||[],classes=inferredClasses(c,r,library),allClasses=[...r.classes,...library.filter(e=>e.kind==='class').map(e=>({index:slug(e.name),name:e.name,hit_die:e.hitDie}))];\n  levelDialog.innerHTML=`<form id=\"levelForm\"><header class=\"dialog-header\"><div><span class=\"eyebrow\">2014 LEVEL-UP REVIEW</span><h2>Level up ${esc(c.name)}</h2></div><button type=\"button\" data-close class=\"icon\">\u2715</button></header><p>Confirm your current classes and levels, then choose the class gaining a level. Features, maximum HP, proficiency and supported spell-slot totals will be added after your review.</p><label>Current classes (one per line: class name, level)<textarea id=\"currentClasses\" rows=\"3\">${esc(classes.map(x=>x.name+', '+x.level).join('\\n'))}</textarea></label><div class=\"form-grid\"><label>Gain a level in<select id=\"levelClass\">${allClasses.map(x=>`<option value=\"${x.index}\">${esc(x.name)}</option>`).join('')}</select></label><label>Subclass<select id=\"levelSubclass\"></select></label></div><button type=\"button\" id=\"previewLevel\">Review this level</button><div id=\"levelPreview\"></div><p id=\"levelError\" role=\"alert\"></p><div class=\"dialog-actions\"><button class=\"primary\" id=\"applyLevel\" disabled>Apply level-up</button></div></form>`;\n  const q=id=>levelDialog.querySelector('#'+id);let plan,currentClasses;\n  if(classes.length)q('levelClass').value=classes[0].index;\n  function subclasses(){const target=q('levelClass').value,existing=classes.find(x=>x.index===target);const options=[...r.subclasses.filter(s=>s.class.index===target).map(s=>({id:s.index,name:s.name})),...library.filter(e=>e.kind==='subclass'&&slug(e.className)===target).map(e=>({id:slug(e.name),name:e.name}))];q('levelSubclass').innerHTML='<option value=\"\">None / not in library</option>'+options.map(s=>`<option value=\"${s.id}\" ${existing?.subclass===s.id?'selected':''}>${esc(s.name)}</option>`).join('');invalidate();}\n  function invalidate(){plan=null;q('applyLevel').disabled=true;q('levelPreview').innerHTML='';}\n  q('levelClass').onchange=subclasses;q('levelSubclass').onchange=invalidate;q('currentClasses').oninput=invalidate;subclasses();\n  levelDialog.querySelector('[data-close]').onclick=()=>levelDialog.close();\n  q('previewLevel').onclick=()=>{try{\n   currentClasses=q('currentClasses').value.split('\\n').filter(l=>l.trim()).map(line=>{const m=line.match(/^\\s*(.+?)\\s*,\\s*(\\d{1,2})\\s*$/);if(!m)throw new Error('Use one \u201CClass name, level\u201D per line.');const cls=allClasses.find(x=>x.name.toLowerCase()===m[1].toLowerCase());if(!cls)throw new Error('Add '+m[1]+' to the custom class library first.');return {index:cls.index,name:cls.name,level:Number(m[2]),subclass:classes.find(x=>x.index===cls.index)?.subclass||''};});if(new Set(currentClasses.map(x=>x.index)).size!==currentClasses.length)throw new Error('List each class only once.');\n   plan=levelPlan(c,currentClasses,q('levelClass').value,q('levelSubclass').value,r,library);\n   q('levelPreview').innerHTML=`<h3>${esc(plan.cls.name)} ${plan.previous} \u2192 ${plan.next}</h3><p>Proficiency bonus: +${plan.proficiency}. Hit die: d${plan.cls.hit_die}.</p><div class=\"notice\">Review multiclass prerequisites, subclass eligibility, proficiencies, attack/save bonuses and spell choices against your rules. These are not inferred safely from arbitrary imported text. Custom casting subclasses and custom spell-slot progression require manual adjustment.</div>${plan.features.map(f=>`<details class=\"library-entry\"><summary>${esc(f.name)}</summary><p>${esc(f.desc.join('\\n\\n'))}</p></details>`).join('')||'<p>No named feature at this level in the bundled progression.</p>'}<div class=\"form-grid\"><label>HP die result (or fixed amount)<input name=\"hitDie\" type=\"number\" min=\"1\" max=\"${plan.cls.hit_die}\" value=\"${plan.total===0?plan.cls.hit_die:Math.floor(plan.cls.hit_die/2)+1}\" required></label><label>Other HP adjustment<input name=\"extraHp\" type=\"number\" value=\"0\" min=\"-100\" max=\"100\"></label><label class=\"wide check-label\"><input type=\"checkbox\" name=\"increaseCurrent\" checked> Also increase current HP by the gain</label>${plan.asi?`<div class=\"form-section\">Ability-score improvement or feat</div>${abilities.map(k=>`<label>${labels[k]} increase<input name=\"asi_${k}\" type=\"number\" min=\"0\" max=\"2\" value=\"0\"></label>`).join('')}<label class=\"wide\">Or feat name and effects to record<textarea name=\"feat\" rows=\"3\"></textarea></label>`:''}<label class=\"wide\">Choices and follow-up adjustments<textarea name=\"decisions\" required placeholder=\"Record subclass choices, spells to learn/prepare, or other decisions. Enter \u2018No choices this level\u2019 if appropriate.\"></textarea></label><label class=\"wide check-label\"><input type=\"checkbox\" required> I reviewed the features and any prerequisites or manual adjustments.</label></div>`;q('applyLevel').disabled=false;q('levelError').textContent='';\n  }catch(e){q('levelError').textContent=e.message;}};\n  q('levelForm').onsubmit=async e=>{e.preventDefault();if(!plan)return;q('applyLevel').disabled=true;try{const fd=new FormData(e.target),increases=Object.fromEntries(abilities.map(k=>[k,Number(fd.get('asi_'+k)||0)]));const updated=applyLevel(c,currentClasses,plan,{hitDie:Number(fd.get('hitDie')),extraHp:Number(fd.get('extraHp')),increaseCurrent:fd.has('increaseCurrent'),increases,feat:String(fd.get('feat')||''),decisions:String(fd.get('decisions')||'')},r);await commit({...state,characters:state.characters.map(x=>x.id===c.id?updated:x)});refresh();levelDialog.close();}catch(err){q('levelError').textContent=err.message;}finally{q('applyLevel').disabled=false;}};\n  levelDialog.showModal();\n }\n document.getElementById('libraryButton').onclick=()=>{document.body.classList.remove('menu-open');document.getElementById('scrim').hidden=true;open().catch(e=>alert(e.message));};\n return {open,levelUp,isOpen:()=>dialog.open||levelDialog.open};\n}\n", "import {blank,labels,abilities,modifier,fromText,splitCharacterText} from './model.mjs';\r\nimport {importFile} from './import.mjs';\r\nimport * as repo from './repository.mjs';\r\nimport {exportFile} from './storage.mjs';\r\nimport {setupAccount} from './account.mjs';\r\nimport {setupLibrary} from './library.mjs';\r\nconst $=id=>document.getElementById(id),esc=s=>String(s??'').replace(/[&<>\"']/g,c=>({'&':'&amp;','<':'&lt;','>':'&gt;','\"':'&quot;',\"'\":'&#39;'}[c]));\r\nlet state,selected=null,filter='PC',draft=null,editRevision=null,busy=false,nameTimer,library,pasteQueue=[];\r\nasync function api(path,method='GET',data){if(path==='state')return method==='PUT'?repo.saveState(data):repo.getState();throw new Error('Unknown operation.');}\r\nfunction message(text){$('message').textContent=text;$('message').hidden=!text;}\r\nfunction status(text){$('status').textContent=text;}\r\nasync function load(){state=await api('state');if(!selected||!state.characters.some(c=>c.id===selected))selected=state.characters.find(c=>c.kind===filter)?.id||null;render();status(repo.syncStatus);}\r\nasync function commit(next){if(busy)throw new Error('A save is still in progress. Please try again in a moment.');busy=true;status('Saving on this device\u2026');try{state=await api('state','PUT',next);status(repo.syncStatus);message('');return state;}catch(e){status('Not saved');message(e.message);throw e;}finally{busy=false;}}\r\nfunction render(){\r\n if(document.activeElement!==$('adventure'))$('adventure').value=state.adventure;\r\n $('pcCount').textContent=state.characters.filter(c=>c.kind==='PC').length;$('npcCount').textContent=state.characters.filter(c=>c.kind==='NPC').length;\r\n $('pcFilter').classList.toggle('active',filter==='PC');$('npcFilter').classList.toggle('active',filter==='NPC');\r\n const list=state.characters.filter(c=>c.kind===filter&&c.name.toLowerCase().includes($('search').value.toLowerCase()));\r\n $('characters').innerHTML=list.length?list.map(c=>`<button class=\"character-tab ${c.id===selected?'selected':''}\" data-id=\"${esc(c.id)}\" ${c.id===selected?'aria-current=\"page\"':''}><span class=\"initials\">${esc(c.name.split(/\\s+/).map(p=>p[0]).slice(0,2).join('').toUpperCase())}</span><span><strong>${esc(c.name)}</strong><small>${esc(c.fields.classLevel||c.fields.ancestry||(c.kind==='PC'?'Player character':'Non-player character'))}</small></span></button>`).join(''):`<p class=\"subtle\">${$('search').value?'No matching characters.':`No ${filter==='PC'?'player':'non-player'} characters yet.`}</p>`;\r\n $('breadcrumb').textContent=(state.adventure||'YOUR ADVENTURE')+' / '+(filter==='PC'?'PLAYER CHARACTERS':'NON-PLAYER CHARACTERS');\r\n renderSheet();\r\n}\r\nfunction renderSheet(){\r\n const c=state.characters.find(c=>c.id===selected);\r\n if(!c){$('sheet').innerHTML=`<div class=\"empty-state\"><div class=\"seal\">\u2727</div><span class=\"eyebrow\">THE ADVENTURE STARTS HERE</span><h1>Everyone in your story.<br>All in one place.</h1><p>Bring in a character sheet or paste a stat block. Keep your players, allies and adversaries together in a collection saved on this device.</p><div class=\"empty-actions\"><button class=\"primary\" id=\"emptyImport\">Import a character</button><button id=\"emptyPaste\">Paste character text</button></div><div class=\"format-list\">PDF \u00B7 SPREADSHEETS \u00B7 JSON \u00B7 PASTED TEXT</div></div>`;$('emptyImport').onclick=()=>$('importFile').click();$('emptyPaste').onclick=openPaste;return;}\r\n const f=c.fields;const display=k=>esc(f[k]||'Not entered');\r\n const stats=[['Armour class',f.ac,'AC'],['Hit points',f.hp?(f.hp+(f.maxHp?' / '+f.maxHp:'')):(f.maxHp?'? / '+f.maxHp:''),f.tempHp?f.tempHp+' temporary':'CURRENT / MAXIMUM'],['Speed',f.speed,'MOVEMENT'],['Initiative',f.initiative,'BONUS']];\r\n const sections=['attacks','spells','saves','skills','traits','equipment','notes'];\r\n $('sheet').innerHTML=`<div class=\"sheet-heading\"><div><span class=\"tag\">${c.kind==='PC'?'PLAYER CHARACTER':'NON-PLAYER CHARACTER'}</span><h1>${esc(c.name)}</h1><p>${esc([f.ancestry,f.classLevel].filter(Boolean).join(' \u00B7 ')||'Add character details to complete this sheet.')}</p></div><button id=\"editCharacter\">Edit sheet</button></div><div class=\"stats\">${stats.map(([title,value,hint])=>`<div class=\"stat\"><small>${title}</small><strong>${esc(value||'\u00B7')}</strong><span class=\"hint\">${esc(hint)}</span></div>`).join('')}</div><div class=\"abilities\">${abilities.map(k=>`<div class=\"ability\"><small>${k.toUpperCase()}</small><strong>${esc(f[k]||'\u00B7')}</strong><span>${modifier(f[k]||'')||'Not entered'}</span></div>`).join('')}</div><div class=\"meta-grid\">${['background','alignment','proficiency',...(c.kind==='NPC'?['cr']:[])].map(k=>`<div><small>${labels[k]}</small><strong>${display(k)}</strong></div>`).join('')}</div><div class=\"sheet-grid\">${sections.map(k=>`<section class=\"card\"><h3>${labels[k]}</h3><p class=\"${f[k]?'':'empty'}\">${esc(f[k]||'No details entered yet.')}</p></section>`).join('')}</div><div class=\"source-panel\"><span class=\"eyebrow\">ORIGINAL INFORMATION</span>${c.source?`<div class=\"source-actions\"><button id=\"downloadOriginal\">Download original file</button><span>${esc(c.source.name)}</span></div>`:''}<details><summary>View original extracted or pasted text</summary><pre>${esc(f.sourceText||'This character was created manually. No source text is attached.')}</pre></details></div><div class=\"bottom-actions\"><button id=\"printSheet\">Print sheet</button><button id=\"deleteCharacter\" class=\"danger\">Delete character</button></div>`;\r\n $('editCharacter').onclick=()=>edit(c);$('printSheet').onclick=()=>window.print();$('deleteCharacter').onclick=()=>remove(c);if(c.source)$('downloadOriginal').onclick=()=>downloadOriginal(c.source);\r\n const actions=document.createElement('div');actions.className='sheet-tools';actions.innerHTML='<button id=\"pickSpell\">Add spells / features</button>'+(c.kind==='PC'?'<button id=\"levelUpButton\" class=\"primary\">Level up</button>':'');$('sheet').querySelector('.sheet-heading').after(actions);$('pickSpell').onclick=()=>library.open().catch(e=>message(e.message));if($('levelUpButton'))$('levelUpButton').onclick=()=>library.levelUp().catch(e=>message(e.message));\r\n if(f.spellSlots){const slots=document.createElement('section');slots.className='card';slots.innerHTML='<h3>Spell slots</h3><p>'+esc(f.spellSlots)+'</p>';$('sheet').querySelector('.sheet-grid').prepend(slots);}\r\n}\r\nfunction edit(c,notice=''){\r\n draft=structuredClone(c);editRevision=state.revision;$('editTitle').textContent=state.characters.some(x=>x.id===c.id)?'Edit character':'Review character';$('importNotice').textContent=notice;$('importNotice').hidden=!notice;$('editError').textContent='';\r\n const small=['ancestry','classLevel','background','alignment','cr','ac','hp','maxHp','tempHp','speed','initiative','proficiency',...abilities];\r\n $('editFields').innerHTML=`<div class=\"form-grid\"><label class=\"name-field\">Character name<input name=\"name\" required maxlength=\"200\" value=\"${esc(c.name)}\"></label><label>Category<select name=\"kind\"><option value=\"PC\" ${c.kind==='PC'?'selected':''}>PC</option><option value=\"NPC\" ${c.kind==='NPC'?'selected':''}>NPC</option></select></label><div class=\"form-section\">Identity & statistics</div>${small.map(k=>`<label>${labels[k]}<input name=\"${k}\" value=\"${esc(c.fields[k]||'')}\" ${abilities.includes(k)?'inputmode=\"numeric\"':''}></label>`).join('')}<div class=\"form-section\">Abilities, equipment & notes</div>${['saves','skills','attacks','spells','spellSlots','equipment','traits','notes'].map(k=>`<label class=\"wide\">${labels[k]}<textarea name=\"${k}\" maxlength=\"500000\">${esc(c.fields[k]||'')}</textarea></label>`).join('')}<details class=\"wide\"><summary>Original extracted or pasted text</summary><textarea name=\"sourceText\" aria-label=\"Original extracted or pasted text\" rows=\"9\" maxlength=\"500000\">${esc(c.fields.sourceText||'')}</textarea></details></div>`;\r\n $('editor').showModal();$('editor').scrollTop=0;\r\n}\r\nfunction closeEdit(){if(busy)return;if(confirm('Close this editor without saving the changes?')){$('editor').close();draft=null;pasteQueue=[];}}\r\n$('editor').addEventListener('cancel',e=>{e.preventDefault();closeEdit();});$('cancelEdit').onclick=closeEdit;$('cancelEditBottom').onclick=closeEdit;\r\n$('editForm').onsubmit=async e=>{\r\n e.preventDefault();const fd=new FormData(e.target);const c={...draft,name:String(fd.get('name')).trim(),kind:fd.get('kind'),fields:{...draft.fields}};if(!c.name)return;\r\n for(const k of Object.keys(labels))c.fields[k]=String(fd.get(k)||'').trim();\r\n if(c.fields.classLevel!==draft.fields.classLevel)delete c.progression;\r\n $('saveEdit').disabled=true;\r\n try{const next={...state,revision:editRevision,characters:state.characters.some(x=>x.id===c.id)?state.characters.map(x=>x.id===c.id?c:x):[...state.characters,c]};await commit(next);selected=c.id;filter=c.kind;$('editor').close();draft=null;render();if(pasteQueue.length)reviewNextPaste();}catch(err){$('editError').textContent=err.message;}finally{$('saveEdit').disabled=false;}\r\n};\r\nasync function remove(c){if(!confirm(`Delete ${c.name} and the attached original from this collection? Export a backup first if you want to keep a copy.`))return;try{await commit({...state,characters:state.characters.filter(x=>x.id!==c.id)});selected=state.characters.find(x=>x.kind===filter)?.id||null;render();}catch{}}\r\nfunction menu(open){document.body.classList.toggle('menu-open',open);$('scrim').hidden=!open;}\r\n$('menuButton').onclick=()=>menu(true);$('closeMenu').onclick=()=>menu(false);$('scrim').onclick=()=>menu(false);\r\n$('characters').onclick=e=>{const b=e.target.closest('[data-id]');if(b){selected=b.dataset.id;render();menu(false);window.scrollTo(0,0);}};\r\nfor(const k of ['PC','NPC'])$(k==='PC'?'pcFilter':'npcFilter').onclick=()=>{filter=k;selected=state.characters.find(c=>c.kind===k)?.id||null;render();};\r\n$('search').oninput=render;$('addButton').onclick=()=>{menu(false);edit(blank('',filter));};\r\n$('adventure').oninput=()=>{clearTimeout(nameTimer);status('Adventure name not saved yet');nameTimer=setTimeout(()=>saveName().catch(e=>message(e.message)),700);};\r\nasync function saveName(){const value=$('adventure').value;if(value===state.adventure)return;if(busy)throw new Error('A save is still in progress. Please save the adventure name again in a moment.');await commit({...state,adventure:value});render();}\r\n$('adventure').onblur=()=>{clearTimeout(nameTimer);saveName().catch(e=>message(e.message));};\r\n$('refreshButton').onclick=async()=>{if($('adventure').value!==state.adventure&&!confirm('Reload the collection and discard the unsaved adventure name?'))return;try{await load();$('adventure').value=state.adventure;message('Collection refreshed.');}catch(e){message(e.message);}};\r\n$('importButton').onclick=()=>$('importFile').click();\r\n$('importFile').onchange=async e=>{const file=e.target.files[0];if(!file)return;$('importButton').disabled=true;message('Reading '+file.name+'\u2026');try{const result=await importFile(file,filter);message('');menu(false);edit(result.character,result.notice);}catch(err){message('Import could not be completed: '+err.message+' You can also create a character manually or paste its text.');}finally{$('importButton').disabled=false;e.target.value='';}};\r\nfunction openPaste(){menu(false);$('pasteDialog').showModal();}$('pasteButton').onclick=openPaste;$('closePaste').onclick=()=>$('pasteDialog').close();\r\n$('pasteForm').onsubmit=e=>{e.preventDefault();const text=$('pasteText').value;if(!text.trim())return;pasteQueue=splitCharacterText(text).map(block=>fromText(block,blank('',filter)));$('pasteDialog').close();reviewNextPaste();};\r\nfunction reviewNextPaste(){const c=pasteQueue.shift();edit(c,'Review '+(c.name||'this character')+' before saving. '+(pasteQueue.length?pasteQueue.length+' more character sheet(s) will follow. ':'')+'Custom rules are preserved as written. Original text is retained below.');}\r\nasync function download(data,name,type='application/json'){await exportFile(data,name,type);}\r\nfunction downloadOriginal(source){const bytes=Uint8Array.from(atob(source.data),c=>c.charCodeAt(0));download(new Blob([bytes],{type:source.type||'application/octet-stream'}),source.name).catch(e=>message('Export was not completed: '+e.message));}\r\n$('backupButton').onclick=async()=>{try{await saveName();const latest=await api('state');await download(JSON.stringify(latest,null,2),`character-ledger-backup-${new Date().toISOString().slice(0,10)}.json`);message('Backup export opened. Save the file to keep a separate copy of your adventure, characters and original files.');}catch(e){message(e.message);}};\r\n$('restoreButton').onclick=()=>$('restoreFile').click();$('restoreFile').onchange=async e=>{const file=e.target.files[0];if(!file)return;try{if(file.size>220*1024*1024)throw new Error('Backup is too large.');const incoming=JSON.parse(await file.text());if(incoming.format!=='character-ledger'||incoming.version!==1||!Array.isArray(incoming.characters))throw new Error('Choose a Character Ledger backup JSON file.');if(!confirm(`Replace the current collection with \u201C${incoming.adventure||'Untitled adventure'}\u201D (${incoming.characters.length} characters)? Export your current collection first if needed.`))return;await commit({...incoming,revision:state.revision});selected=null;render();message('Backup restored and saved on this device.');}catch(err){message('Restore failed: '+err.message);}finally{e.target.value='';}};\r\nasync function start(){try{await repo.init();library=setupLibrary({getState:()=>state,getSelected:()=>state.characters.find(c=>c.id===selected),commit,refresh:render});await load();$('login').hidden=true;$('app').hidden=false;setupAccount({onChange:async()=>{selected=null;await load();},canSwitch:()=>!draft&&!busy&&!library.isOpen()&&$('adventure').value===state.adventure});}catch(e){$('app').hidden=false;message('Could not open saved data: '+e.message);}}\r\nwindow.addEventListener('beforeunload',e=>{if(busy||draft||(state&&$('adventure').value!==state.adventure)){e.preventDefault();e.returnValue='';}});\r\nsetInterval(async()=>{if(!state||busy||document.hidden||draft||library?.isOpen()||document.activeElement===$('adventure')||$('adventure').value!==state.adventure)return;try{const result=await repo.sync();if(result.changed)await load();status(repo.syncStatus);if(result.conflicts?.length)message('Both versions were retained for review: '+result.conflicts.join(', '));}catch{status(repo.syncStatus);}},15000);\r\nstart();\r\n"],
  "mappings": ";;;;;;;;;;;IAAW,eAkBE,oBAQA,eCzBA,iBA2JA,qBC3JA,WASA,gBCLA,WCIP,QAOA,QACO,2BA0DA,kBAQA,kBAcP,sBAcA,gBA8BO,kBAwCA,wBAiFA,eAQF,iBA0BA,eAeE,qBAcA;;;AJpUb,KAAC,SAAUA,gBAAe;AAOtB,MAAAA,eAAc,eAAe,IAAI;AAQjC,MAAAA,eAAc,aAAa,IAAI;IACnC,GAAG,kBAAkB,gBAAgB,CAAA,EAAG;AACjC,IAAM,qBAAN,cAAiC,MAAM;MAC1C,YAAYC,UAAS,MAAM,MAAM;AAC7B,cAAMA,QAAO;AACb,aAAK,UAAUA;AACf,aAAK,OAAO;AACZ,aAAK,OAAO;MACpB;IACA;AACO,IAAM,gBAAgB,CAAC,QAAQ;AAClC,UAAI,IAAI;AACR,UAAI,QAAQ,QAAQ,QAAQ,SAAS,SAAS,IAAI,eAAe;AAC7D,eAAO;MACf,YACc,MAAM,KAAK,QAAQ,QAAQ,QAAQ,SAAS,SAAS,IAAI,YAAY,QAAQ,OAAO,SAAS,SAAS,GAAG,qBAAqB,QAAQ,OAAO,SAAS,SAAS,GAAG,QAAQ;AAChL,eAAO;MACf,OACS;AACD,eAAO;MACf;IACA;ACpCO,IAAM,kBAAkB,CAAC,QAAQ;AACpC,YAAM,oBAAoB,IAAI,2BAA2B;AACzD,YAAM,MAAM,IAAI,aAAa,CAAA;AAC7B,YAAM,UAAW,IAAI,UAAU,IAAI,WAAW,CAAA;AAC9C,YAAM,cAAc,MAAM;AACtB,eAAO,sBAAsB,OAAO,kBAAkB,OAAO,cAAc,GAAG;MACtF;AACI,YAAM,mBAAmB,MAAM,YAAW,MAAO;AACjD,YAAM,oBAAoB,CAAC,eAAe;AACtC,cAAM,SAAS,kBAAkB,IAAI,UAAU;AAC/C,YAA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EAAE,OAAO;AAAA,EAAE;AAAC;AAC3c,OAAO,iBAAiB,gBAAe,OAAG;AAAC,MAAG,QAAM,SAAQ,SAAO,EAAE,WAAW,EAAE,UAAQ,MAAM,WAAW;AAAC,MAAE,eAAe;AAAE,MAAE,cAAY;AAAA,EAAG;AAAC,CAAC;AAClJ,YAAY,YAAS;AAAC,MAAG,CAAC,SAAO,QAAM,SAAS,UAAQ,SAAO,SAAS,OAAO,KAAG,SAAS,kBAAgB,EAAE,WAAW,KAAG,EAAE,WAAW,EAAE,UAAQ,MAAM,UAAU;AAAO,MAAG;AAAC,UAAM,SAAO,MAAW,KAAK;AAAE,QAAG,OAAO,QAAQ,OAAM,KAAK;AAAE,WAAY,UAAU;AAAE,QAAG,OAAO,WAAW,OAAO,SAAQ,6CAA2C,OAAO,UAAU,KAAK,IAAI,CAAC;AAAA,EAAE,QAAM;AAAC,WAAY,UAAU;AAAA,EAAE;AAAC,GAAE,IAAK;AACtZ,MAAM;",
  "names": ["ExceptionCode", "message", "handleError", "registerPlugin", "remove", "p", "resolve", "key", "headers", "SystemBarsStyle", "SystemBarType", "Directory", "Encoding", "status", "resolve", "db", "entry", "toPath", "ctime", "filename", "web_exports", "init_web", "s", "key", "start", "resolve", "s", "resolve", "message", "FunctionRegion", "key", "resolve", "status", "headers: Record<string, string>", "res: Response", "fetchError: any", "key", "res", "this", "count: number | null", "s", "fetch", "head", "PostgrestClient", "init", "requestHeaders: Record<string, string>", "body: string", "get", "method: 'HEAD' | 'GET' | 'POST'", "body: unknown | undefined", "message", "key", "PostgresTypes", "closure", "global", "DEFAULT_VSN", "DEFAULT_TIMEOUT", "CHANNEL_STATES", "CHANNEL_EVENTS", "status", "key", "state", "message", "fallbackTransportName", "key", "state", "REALTIME_PRESENCE_LISTEN_EVENTS", "state", "PostgrestReservedCharsRegexp", "REALTIME_POSTGRES_CHANGES_LISTEN_EVENT", "REALTIME_LISTEN_TYPES", "REALTIME_SUBSCRIBE_STATES", "state", "postgres_changes", "message", "filter", "resolve", "_b", "_a", "bind", "join", "resolve", "key", "status", "result", "message", "message", "key", "namespaceToPath", "message", "status", "_objectSpread2", "_objectSpread2", "key", "result: Record<string, string>", "resolveFetch", "result: Record<string, any>", "status", "params: { [k: string]: any }", "contentType: string | undefined", "resolve", "fetch", "setHeaderUtil", "this", "downloadFn: () => Promise<Response>", "shouldThrowOnError: boolean", "DEFAULT_FILE_OPTIONS: FileOptions", "headers: Record<string, string>", "files: [string, Blob][]", "version", "params: Record<string, string>", "version", "DEFAULT_HEADERS", "version", "message", "status", "message", "status", "message", "state", "state", "key", "resolveFetch", "sleep", "verifier", "user", "_getErrorMessage", "handleError", "_getRequestParams", "_handleRequest", "user", "fetch", "resolveFetch", "key", "message", "version", "message", "user", "key", "factor", "DEFAULT_HEADERS", "message", "resolveFetch", "version", "queue", "user", "expiresAt", "error", "data", "_a", "sleep", "payload", "currentLevel", "nextLevel", "verifiedFactors", "currentAuthenticationMethods", "key", "version", "JS_RUNTIME_VERSION: string | undefined", "DEFAULT_HEADERS", "DEFAULT_AUTH_OPTIONS: SupabaseAuthClientOptions", "DEFAULT_REALTIME_OPTIONS: RealtimeClientOptions", "DEFAULT_TRACE_PROPAGATION_OPTIONS: TracePropagationOptions", "resolveFetch", "key", "fetch", "traceTargets: TracePropagationTarget[] | null", "init", "_objectSpread2", "DEFAULT_DB_OPTIONS", "DEFAULT_AUTH_OPTIONS", "DEFAULT_REALTIME_OPTIONS", "DEFAULT_GLOBAL_OPTIONS", "DEFAULT_TRACE_PROPAGATION_OPTIONS", "result: ResolvedSupabaseClientOptions<SchemaName>", "supabaseUrl: string", "supabaseKey: string", "SupabaseStorageClient", "this", "key", "resolve", "key", "s", "doc", "next", "s", "render", "s", "rules", "library", "f", "e", "esc", "s", "getState", "commit", "render", "state", "selected", "f", "key", "library", "esc", "s", "c", "f", "remove"]
}
