dreamboard 0.1.21 → 0.1.23
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{chunk-EYYWGWTO.js → chunk-2RCUHMGL.js} +343 -1911
- package/dist/chunk-2RCUHMGL.js.map +1 -0
- package/dist/{chunk-MOVHYB6E.js → chunk-GN7232BY.js} +1025 -695
- package/dist/chunk-GN7232BY.js.map +1 -0
- package/dist/{chunk-BMYC6772.js → chunk-H3O43F5P.js} +9765 -3068
- package/dist/chunk-H3O43F5P.js.map +1 -0
- package/dist/dev-host/dev-api-proxy-plugin.ts +330 -0
- package/dist/dev-host/dev-diagnostics.ts +62 -0
- package/dist/dev-host/dev-fallback-stylesheet.ts +50 -0
- package/dist/dev-host/dev-host-controller.ts +686 -0
- package/dist/dev-host/dev-host-player-query.ts +17 -0
- package/dist/dev-host/dev-host-session-transport.ts +52 -0
- package/dist/dev-host/dev-host-storage.ts +56 -0
- package/dist/dev-host/dev-log-relay-plugin.ts +469 -0
- package/dist/dev-host/dev-runtime-config.ts +14 -0
- package/dist/dev-host/dev-runtime-platform.ts +419 -0
- package/dist/dev-host/dev-virtual-modules-plugin.ts +63 -0
- package/dist/dev-host/host-main.css +182 -0
- package/dist/dev-host/host-main.tsx +754 -0
- package/dist/dev-host/index.html +56 -0
- package/dist/dev-host/plugin-main.ts +55 -0
- package/dist/dev-host/plugin.html +24 -0
- package/dist/dev-host/start-dev-server.ts +138 -0
- package/dist/dev-host/virtual-modules.d.ts +27 -0
- package/dist/dist-FEPN3BDN.js +16543 -0
- package/dist/dist-FEPN3BDN.js.map +1 -0
- package/dist/{dist-WJRJNFLI.js → dist-FRURQI7Q.js} +4 -2
- package/dist/index.js +3 -3
- package/dist/internal.js +159 -124
- package/dist/internal.js.map +1 -1
- package/dist/runtime-packages/tailwind-config/shared-styles.css +146 -0
- package/dist/runtime-packages/ui/src/components/.gitkeep +0 -0
- package/dist/runtime-packages/ui/src/components/accordion.tsx +66 -0
- package/dist/runtime-packages/ui/src/components/ai-elements/actions.tsx +65 -0
- package/dist/runtime-packages/ui/src/components/ai-elements/artifact.tsx +147 -0
- package/dist/runtime-packages/ui/src/components/ai-elements/branch.tsx +215 -0
- package/dist/runtime-packages/ui/src/components/ai-elements/canvas.tsx +22 -0
- package/dist/runtime-packages/ui/src/components/ai-elements/chain-of-thought.tsx +228 -0
- package/dist/runtime-packages/ui/src/components/ai-elements/code-block.tsx +179 -0
- package/dist/runtime-packages/ui/src/components/ai-elements/confirmation.tsx +158 -0
- package/dist/runtime-packages/ui/src/components/ai-elements/connection.tsx +28 -0
- package/dist/runtime-packages/ui/src/components/ai-elements/context.tsx +408 -0
- package/dist/runtime-packages/ui/src/components/ai-elements/controls.tsx +18 -0
- package/dist/runtime-packages/ui/src/components/ai-elements/conversation.tsx +97 -0
- package/dist/runtime-packages/ui/src/components/ai-elements/edge.tsx +140 -0
- package/dist/runtime-packages/ui/src/components/ai-elements/image.tsx +24 -0
- package/dist/runtime-packages/ui/src/components/ai-elements/inline-citation.tsx +287 -0
- package/dist/runtime-packages/ui/src/components/ai-elements/loader.tsx +96 -0
- package/dist/runtime-packages/ui/src/components/ai-elements/message.tsx +463 -0
- package/dist/runtime-packages/ui/src/components/ai-elements/node.tsx +71 -0
- package/dist/runtime-packages/ui/src/components/ai-elements/open-in-chat.tsx +365 -0
- package/dist/runtime-packages/ui/src/components/ai-elements/panel.tsx +15 -0
- package/dist/runtime-packages/ui/src/components/ai-elements/plan.tsx +142 -0
- package/dist/runtime-packages/ui/src/components/ai-elements/prompt-input.tsx +1380 -0
- package/dist/runtime-packages/ui/src/components/ai-elements/queue.tsx +274 -0
- package/dist/runtime-packages/ui/src/components/ai-elements/reasoning.tsx +182 -0
- package/dist/runtime-packages/ui/src/components/ai-elements/response.tsx +22 -0
- package/dist/runtime-packages/ui/src/components/ai-elements/shimmer.tsx +64 -0
- package/dist/runtime-packages/ui/src/components/ai-elements/sources.tsx +77 -0
- package/dist/runtime-packages/ui/src/components/ai-elements/suggestion.tsx +53 -0
- package/dist/runtime-packages/ui/src/components/ai-elements/task.tsx +87 -0
- package/dist/runtime-packages/ui/src/components/ai-elements/tool.tsx +165 -0
- package/dist/runtime-packages/ui/src/components/ai-elements/toolbar.tsx +16 -0
- package/dist/runtime-packages/ui/src/components/ai-elements/web-preview.tsx +263 -0
- package/dist/runtime-packages/ui/src/components/alert-dialog.tsx +157 -0
- package/dist/runtime-packages/ui/src/components/alert.tsx +66 -0
- package/dist/runtime-packages/ui/src/components/avatar.tsx +53 -0
- package/dist/runtime-packages/ui/src/components/badge.tsx +46 -0
- package/dist/runtime-packages/ui/src/components/button-group.tsx +83 -0
- package/dist/runtime-packages/ui/src/components/button.tsx +65 -0
- package/dist/runtime-packages/ui/src/components/card.tsx +92 -0
- package/dist/runtime-packages/ui/src/components/carousel.tsx +241 -0
- package/dist/runtime-packages/ui/src/components/collapsible.tsx +33 -0
- package/dist/runtime-packages/ui/src/components/command.tsx +184 -0
- package/dist/runtime-packages/ui/src/components/context-menu.tsx +252 -0
- package/dist/runtime-packages/ui/src/components/counter.tsx +11 -0
- package/dist/runtime-packages/ui/src/components/dialog.tsx +146 -0
- package/dist/runtime-packages/ui/src/components/drawer.tsx +132 -0
- package/dist/runtime-packages/ui/src/components/dropdown-menu.tsx +257 -0
- package/dist/runtime-packages/ui/src/components/form.tsx +168 -0
- package/dist/runtime-packages/ui/src/components/header.tsx +13 -0
- package/dist/runtime-packages/ui/src/components/hover-card.tsx +44 -0
- package/dist/runtime-packages/ui/src/components/input-group.tsx +178 -0
- package/dist/runtime-packages/ui/src/components/input.tsx +21 -0
- package/dist/runtime-packages/ui/src/components/item.tsx +193 -0
- package/dist/runtime-packages/ui/src/components/label.tsx +24 -0
- package/dist/runtime-packages/ui/src/components/navigation-menu.tsx +168 -0
- package/dist/runtime-packages/ui/src/components/popover.tsx +55 -0
- package/dist/runtime-packages/ui/src/components/progress.tsx +31 -0
- package/dist/runtime-packages/ui/src/components/radio-group.tsx +45 -0
- package/dist/runtime-packages/ui/src/components/resizable.tsx +56 -0
- package/dist/runtime-packages/ui/src/components/scroll-area.tsx +58 -0
- package/dist/runtime-packages/ui/src/components/select.tsx +187 -0
- package/dist/runtime-packages/ui/src/components/separator.tsx +28 -0
- package/dist/runtime-packages/ui/src/components/skeleton.tsx +13 -0
- package/dist/runtime-packages/ui/src/components/sonner.tsx +25 -0
- package/dist/runtime-packages/ui/src/components/spinner.tsx +16 -0
- package/dist/runtime-packages/ui/src/components/switch.tsx +31 -0
- package/dist/runtime-packages/ui/src/components/table.tsx +137 -0
- package/dist/runtime-packages/ui/src/components/tabs.tsx +74 -0
- package/dist/runtime-packages/ui/src/components/textarea.tsx +23 -0
- package/dist/runtime-packages/ui/src/components/theme-provider.tsx +73 -0
- package/dist/runtime-packages/ui/src/components/tooltip.tsx +61 -0
- package/dist/runtime-packages/ui/src/components/ui/file-upload.tsx +195 -0
- package/dist/runtime-packages/ui/src/hooks/.gitkeep +0 -0
- package/dist/runtime-packages/ui/src/index.ts +68 -0
- package/dist/runtime-packages/ui/src/lib/utils.ts +6 -0
- package/dist/runtime-packages/ui-host-runtime/src/actor-principal.ts +68 -0
- package/dist/runtime-packages/ui-host-runtime/src/components/host-controls.tsx +359 -0
- package/dist/runtime-packages/ui-host-runtime/src/components/host-feedback-toaster.tsx +274 -0
- package/dist/runtime-packages/ui-host-runtime/src/components/host-feedback.tsx +214 -0
- package/dist/runtime-packages/ui-host-runtime/src/components/host-session-metadata.tsx +135 -0
- package/dist/runtime-packages/ui-host-runtime/src/components/index.ts +5 -0
- package/dist/runtime-packages/ui-host-runtime/src/components/perf-overlay.tsx +194 -0
- package/dist/runtime-packages/ui-host-runtime/src/host-controls.tsx +1 -0
- package/dist/runtime-packages/ui-host-runtime/src/host-feedback.tsx +1 -0
- package/dist/runtime-packages/ui-host-runtime/src/host-session-transport.ts +162 -0
- package/dist/runtime-packages/ui-host-runtime/src/index.ts +2 -0
- package/dist/runtime-packages/ui-host-runtime/src/logger.ts +11 -0
- package/dist/runtime-packages/ui-host-runtime/src/perf.ts +253 -0
- package/dist/runtime-packages/ui-host-runtime/src/plugin-bridge.ts +195 -0
- package/dist/runtime-packages/ui-host-runtime/src/plugin-health-check.ts +138 -0
- package/dist/runtime-packages/ui-host-runtime/src/plugin-messages.ts +159 -0
- package/dist/runtime-packages/ui-host-runtime/src/plugin-session-gateway.ts +524 -0
- package/dist/runtime-packages/ui-host-runtime/src/runtime/index.ts +12 -0
- package/dist/runtime-packages/ui-host-runtime/src/screenshot/projection-to-snapshot.ts +122 -0
- package/dist/runtime-packages/ui-host-runtime/src/screenshot/static-store-api.ts +26 -0
- package/dist/runtime-packages/ui-host-runtime/src/session-ingress-controller.ts +477 -0
- package/dist/runtime-packages/ui-host-runtime/src/session-ingress.ts +209 -0
- package/dist/runtime-packages/ui-host-runtime/src/session-live-runtime.ts +112 -0
- package/dist/runtime-packages/ui-host-runtime/src/session-model.ts +318 -0
- package/dist/runtime-packages/ui-host-runtime/src/session-projection.ts +211 -0
- package/dist/runtime-packages/ui-host-runtime/src/session-state-reducer.ts +814 -0
- package/dist/runtime-packages/ui-host-runtime/src/sse-manager.ts +334 -0
- package/dist/runtime-packages/ui-host-runtime/src/unified-session-store.ts +180 -0
- package/dist/scaffold/assets/static/app/tsconfig.framework.json +3 -1
- package/dist/scaffold/assets/static/ui/tsconfig.framework.json +7 -19
- package/package.json +52 -17
- package/skills/dreamboard/SKILL.md +41 -75
- package/LICENSE +0 -89
- package/NOTICE +0 -1
- package/dist/chunk-BMYC6772.js.map +0 -1
- package/dist/chunk-EYYWGWTO.js.map +0 -1
- package/dist/chunk-MOVHYB6E.js.map +0 -1
- package/dist/scaffold/assets/static/ui/App.tsx +0 -22
- package/dist/src-CUL7EGGG.js +0 -634
- package/dist/src-CUL7EGGG.js.map +0 -1
- package/skills/dreamboard/references/authoring-lifecycle.md +0 -102
- package/skills/dreamboard/references/board-surfaces.md +0 -36
- package/skills/dreamboard/references/board-topology.md +0 -443
- package/skills/dreamboard/references/boards-and-topology.md +0 -100
- package/skills/dreamboard/references/card-actions.md +0 -107
- package/skills/dreamboard/references/cli.md +0 -120
- package/skills/dreamboard/references/core-concepts.md +0 -514
- package/skills/dreamboard/references/custom-renderers.md +0 -26
- package/skills/dreamboard/references/derived-values.md +0 -55
- package/skills/dreamboard/references/effects.md +0 -111
- package/skills/dreamboard/references/game-contract.md +0 -89
- package/skills/dreamboard/references/game-definition.md +0 -89
- package/skills/dreamboard/references/game-shell.md +0 -80
- package/skills/dreamboard/references/hand-surfaces.md +0 -33
- package/skills/dreamboard/references/index.md +0 -112
- package/skills/dreamboard/references/inputs-and-targets.md +0 -160
- package/skills/dreamboard/references/interactions.md +0 -158
- package/skills/dreamboard/references/manifest-fields.md +0 -137
- package/skills/dreamboard/references/manifest.md +0 -81
- package/skills/dreamboard/references/package-surfaces.md +0 -69
- package/skills/dreamboard/references/phases.md +0 -145
- package/skills/dreamboard/references/prompts-and-choices.md +0 -55
- package/skills/dreamboard/references/quickstart.md +0 -71
- package/skills/dreamboard/references/rule-authoring.md +0 -144
- package/skills/dreamboard/references/setup-bootstrap.md +0 -78
- package/skills/dreamboard/references/stages-and-zones.md +0 -59
- package/skills/dreamboard/references/static-views.md +0 -67
- package/skills/dreamboard/references/table-queries-and-ops.md +0 -103
- package/skills/dreamboard/references/testing-bases.md +0 -147
- package/skills/dreamboard/references/testing-generated-contracts.md +0 -142
- package/skills/dreamboard/references/testing-runtime-assertions.md +0 -124
- package/skills/dreamboard/references/testing-scenarios.md +0 -148
- package/skills/dreamboard/references/testing-ui-tests.md +0 -174
- package/skills/dreamboard/references/testing.md +0 -161
- package/skills/dreamboard/references/ui-architecture.md +0 -137
- package/skills/dreamboard/references/ui-components.md +0 -34
- package/skills/dreamboard/references/views.md +0 -72
- package/skills/dreamboard/references/workspace-layout.md +0 -136
- /package/dist/{dist-WJRJNFLI.js.map → dist-FRURQI7Q.js.map} +0 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../../node_modules/.pnpm/tslib@2.8.1/node_modules/tslib/tslib.js","../../../node_modules/.pnpm/tslib@2.8.1/node_modules/tslib/modules/index.js","../../../node_modules/.pnpm/@supabase+functions-js@2.103.0/node_modules/@supabase/functions-js/src/helper.ts","../../../node_modules/.pnpm/@supabase+functions-js@2.103.0/node_modules/@supabase/functions-js/src/types.ts","../../../node_modules/.pnpm/@supabase+functions-js@2.103.0/node_modules/@supabase/functions-js/src/FunctionsClient.ts","../../../node_modules/.pnpm/@supabase+postgrest-js@2.103.0/node_modules/@supabase/postgrest-js/src/types/common/common.ts","../../../node_modules/.pnpm/@supabase+postgrest-js@2.103.0/node_modules/@supabase/postgrest-js/src/PostgrestError.ts","../../../node_modules/.pnpm/@supabase+postgrest-js@2.103.0/node_modules/@supabase/postgrest-js/src/PostgrestBuilder.ts","../../../node_modules/.pnpm/@supabase+postgrest-js@2.103.0/node_modules/@supabase/postgrest-js/src/PostgrestTransformBuilder.ts","../../../node_modules/.pnpm/@supabase+postgrest-js@2.103.0/node_modules/@supabase/postgrest-js/src/PostgrestFilterBuilder.ts","../../../node_modules/.pnpm/@supabase+postgrest-js@2.103.0/node_modules/@supabase/postgrest-js/src/PostgrestQueryBuilder.ts","../../../node_modules/.pnpm/@supabase+postgrest-js@2.103.0/node_modules/@supabase/postgrest-js/src/PostgrestClient.ts","../../../node_modules/.pnpm/@supabase+postgrest-js@2.103.0/node_modules/@supabase/postgrest-js/src/index.ts","../../../node_modules/.pnpm/@supabase+realtime-js@2.103.0/node_modules/@supabase/realtime-js/src/lib/websocket-factory.ts","../../../node_modules/.pnpm/@supabase+realtime-js@2.103.0/node_modules/@supabase/realtime-js/src/lib/version.ts","../../../node_modules/.pnpm/@supabase+realtime-js@2.103.0/node_modules/@supabase/realtime-js/src/lib/constants.ts","../../../node_modules/.pnpm/@supabase+realtime-js@2.103.0/node_modules/@supabase/realtime-js/src/lib/serializer.ts","../../../node_modules/.pnpm/@supabase+realtime-js@2.103.0/node_modules/@supabase/realtime-js/src/lib/transformers.ts","../../../node_modules/.pnpm/@supabase+phoenix@0.4.0/node_modules/@supabase/phoenix/assets/js/phoenix/utils.js","../../../node_modules/.pnpm/@supabase+phoenix@0.4.0/node_modules/@supabase/phoenix/assets/js/phoenix/constants.js","../../../node_modules/.pnpm/@supabase+phoenix@0.4.0/node_modules/@supabase/phoenix/assets/js/phoenix/push.js","../../../node_modules/.pnpm/@supabase+phoenix@0.4.0/node_modules/@supabase/phoenix/assets/js/phoenix/timer.js","../../../node_modules/.pnpm/@supabase+phoenix@0.4.0/node_modules/@supabase/phoenix/assets/js/phoenix/channel.js","../../../node_modules/.pnpm/@supabase+phoenix@0.4.0/node_modules/@supabase/phoenix/assets/js/phoenix/ajax.js","../../../node_modules/.pnpm/@supabase+phoenix@0.4.0/node_modules/@supabase/phoenix/assets/js/phoenix/longpoll.js","../../../node_modules/.pnpm/@supabase+phoenix@0.4.0/node_modules/@supabase/phoenix/assets/js/phoenix/presence.js","../../../node_modules/.pnpm/@supabase+phoenix@0.4.0/node_modules/@supabase/phoenix/assets/js/phoenix/serializer.js","../../../node_modules/.pnpm/@supabase+phoenix@0.4.0/node_modules/@supabase/phoenix/assets/js/phoenix/socket.js","../../../node_modules/.pnpm/@supabase+realtime-js@2.103.0/node_modules/@supabase/realtime-js/src/phoenix/presenceAdapter.ts","../../../node_modules/.pnpm/@supabase+realtime-js@2.103.0/node_modules/@supabase/realtime-js/src/RealtimePresence.ts","../../../node_modules/.pnpm/@supabase+realtime-js@2.103.0/node_modules/@supabase/realtime-js/src/phoenix/channelAdapter.ts","../../../node_modules/.pnpm/@supabase+realtime-js@2.103.0/node_modules/@supabase/realtime-js/src/RealtimeChannel.ts","../../../node_modules/.pnpm/@supabase+realtime-js@2.103.0/node_modules/@supabase/realtime-js/src/phoenix/socketAdapter.ts","../../../node_modules/.pnpm/@supabase+realtime-js@2.103.0/node_modules/@supabase/realtime-js/src/RealtimeClient.ts","../../../node_modules/.pnpm/iceberg-js@0.8.1/node_modules/iceberg-js/src/errors/IcebergError.ts","../../../node_modules/.pnpm/iceberg-js@0.8.1/node_modules/iceberg-js/src/utils/url.ts","../../../node_modules/.pnpm/iceberg-js@0.8.1/node_modules/iceberg-js/src/http/createFetchClient.ts","../../../node_modules/.pnpm/iceberg-js@0.8.1/node_modules/iceberg-js/src/catalog/namespaces.ts","../../../node_modules/.pnpm/iceberg-js@0.8.1/node_modules/iceberg-js/src/catalog/tables.ts","../../../node_modules/.pnpm/iceberg-js@0.8.1/node_modules/iceberg-js/src/catalog/IcebergRestCatalog.ts","../../../node_modules/.pnpm/iceberg-js@0.8.1/node_modules/iceberg-js/src/catalog/types.ts","../../../node_modules/.pnpm/@supabase+storage-js@2.103.0/node_modules/@supabase/storage-js/src/lib/common/errors.ts","../../../node_modules/.pnpm/@supabase+storage-js@2.103.0/node_modules/@supabase/storage-js/src/lib/common/helpers.ts","../../../node_modules/.pnpm/@supabase+storage-js@2.103.0/node_modules/@supabase/storage-js/src/lib/common/fetch.ts","../../../node_modules/.pnpm/@supabase+storage-js@2.103.0/node_modules/@supabase/storage-js/src/lib/common/BaseApiClient.ts","../../../node_modules/.pnpm/@supabase+storage-js@2.103.0/node_modules/@supabase/storage-js/src/packages/StreamDownloadBuilder.ts","../../../node_modules/.pnpm/@supabase+storage-js@2.103.0/node_modules/@supabase/storage-js/src/packages/BlobDownloadBuilder.ts","../../../node_modules/.pnpm/@supabase+storage-js@2.103.0/node_modules/@supabase/storage-js/src/packages/StorageFileApi.ts","../../../node_modules/.pnpm/@supabase+storage-js@2.103.0/node_modules/@supabase/storage-js/src/lib/version.ts","../../../node_modules/.pnpm/@supabase+storage-js@2.103.0/node_modules/@supabase/storage-js/src/lib/constants.ts","../../../node_modules/.pnpm/@supabase+storage-js@2.103.0/node_modules/@supabase/storage-js/src/packages/StorageBucketApi.ts","../../../node_modules/.pnpm/@supabase+storage-js@2.103.0/node_modules/@supabase/storage-js/src/packages/StorageAnalyticsClient.ts","../../../node_modules/.pnpm/@supabase+storage-js@2.103.0/node_modules/@supabase/storage-js/src/packages/VectorIndexApi.ts","../../../node_modules/.pnpm/@supabase+storage-js@2.103.0/node_modules/@supabase/storage-js/src/packages/VectorDataApi.ts","../../../node_modules/.pnpm/@supabase+storage-js@2.103.0/node_modules/@supabase/storage-js/src/packages/VectorBucketApi.ts","../../../node_modules/.pnpm/@supabase+storage-js@2.103.0/node_modules/@supabase/storage-js/src/packages/StorageVectorsClient.ts","../../../node_modules/.pnpm/@supabase+storage-js@2.103.0/node_modules/@supabase/storage-js/src/StorageClient.ts","../../../node_modules/.pnpm/@supabase+auth-js@2.103.0/node_modules/@supabase/auth-js/src/lib/version.ts","../../../node_modules/.pnpm/@supabase+auth-js@2.103.0/node_modules/@supabase/auth-js/src/lib/constants.ts","../../../node_modules/.pnpm/@supabase+auth-js@2.103.0/node_modules/@supabase/auth-js/src/lib/errors.ts","../../../node_modules/.pnpm/@supabase+auth-js@2.103.0/node_modules/@supabase/auth-js/src/lib/base64url.ts","../../../node_modules/.pnpm/@supabase+auth-js@2.103.0/node_modules/@supabase/auth-js/src/lib/helpers.ts","../../../node_modules/.pnpm/@supabase+auth-js@2.103.0/node_modules/@supabase/auth-js/src/lib/fetch.ts","../../../node_modules/.pnpm/@supabase+auth-js@2.103.0/node_modules/@supabase/auth-js/src/lib/types.ts","../../../node_modules/.pnpm/@supabase+auth-js@2.103.0/node_modules/@supabase/auth-js/src/GoTrueAdminApi.ts","../../../node_modules/.pnpm/@supabase+auth-js@2.103.0/node_modules/@supabase/auth-js/src/lib/local-storage.ts","../../../node_modules/.pnpm/@supabase+auth-js@2.103.0/node_modules/@supabase/auth-js/src/lib/locks.ts","../../../node_modules/.pnpm/@supabase+auth-js@2.103.0/node_modules/@supabase/auth-js/src/lib/polyfills.ts","../../../node_modules/.pnpm/@supabase+auth-js@2.103.0/node_modules/@supabase/auth-js/src/lib/web3/ethereum.ts","../../../node_modules/.pnpm/@supabase+auth-js@2.103.0/node_modules/@supabase/auth-js/src/lib/webauthn.errors.ts","../../../node_modules/.pnpm/@supabase+auth-js@2.103.0/node_modules/@supabase/auth-js/src/lib/webauthn.ts","../../../node_modules/.pnpm/@supabase+auth-js@2.103.0/node_modules/@supabase/auth-js/src/GoTrueClient.ts","../../../node_modules/.pnpm/@supabase+auth-js@2.103.0/node_modules/@supabase/auth-js/src/AuthAdminApi.ts","../../../node_modules/.pnpm/@supabase+auth-js@2.103.0/node_modules/@supabase/auth-js/src/AuthClient.ts","../../../node_modules/.pnpm/@supabase+supabase-js@2.103.0/node_modules/@supabase/supabase-js/src/lib/version.ts","../../../node_modules/.pnpm/@supabase+supabase-js@2.103.0/node_modules/@supabase/supabase-js/src/lib/constants.ts","../../../node_modules/.pnpm/@supabase+supabase-js@2.103.0/node_modules/@supabase/supabase-js/src/lib/fetch.ts","../../../node_modules/.pnpm/@supabase+supabase-js@2.103.0/node_modules/@supabase/supabase-js/src/lib/helpers.ts","../../../node_modules/.pnpm/@supabase+supabase-js@2.103.0/node_modules/@supabase/supabase-js/src/lib/SupabaseAuthClient.ts","../../../node_modules/.pnpm/@supabase+supabase-js@2.103.0/node_modules/@supabase/supabase-js/src/SupabaseClient.ts","../../../node_modules/.pnpm/@supabase+supabase-js@2.103.0/node_modules/@supabase/supabase-js/src/index.ts"],"sourcesContent":["/******************************************************************************\r\nCopyright (c) Microsoft Corporation.\r\n\r\nPermission to use, copy, modify, and/or distribute this software for any\r\npurpose with or without fee is hereby granted.\r\n\r\nTHE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH\r\nREGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY\r\nAND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,\r\nINDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM\r\nLOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR\r\nOTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR\r\nPERFORMANCE OF THIS SOFTWARE.\r\n***************************************************************************** */\r\n/* global global, define, Symbol, Reflect, Promise, SuppressedError, Iterator */\r\nvar __extends;\r\nvar __assign;\r\nvar __rest;\r\nvar __decorate;\r\nvar __param;\r\nvar __esDecorate;\r\nvar __runInitializers;\r\nvar __propKey;\r\nvar __setFunctionName;\r\nvar __metadata;\r\nvar __awaiter;\r\nvar __generator;\r\nvar __exportStar;\r\nvar __values;\r\nvar __read;\r\nvar __spread;\r\nvar __spreadArrays;\r\nvar __spreadArray;\r\nvar __await;\r\nvar __asyncGenerator;\r\nvar __asyncDelegator;\r\nvar __asyncValues;\r\nvar __makeTemplateObject;\r\nvar __importStar;\r\nvar __importDefault;\r\nvar __classPrivateFieldGet;\r\nvar __classPrivateFieldSet;\r\nvar __classPrivateFieldIn;\r\nvar __createBinding;\r\nvar __addDisposableResource;\r\nvar __disposeResources;\r\nvar __rewriteRelativeImportExtension;\r\n(function (factory) {\r\n var root = typeof global === \"object\" ? global : typeof self === \"object\" ? self : typeof this === \"object\" ? this : {};\r\n if (typeof define === \"function\" && define.amd) {\r\n define(\"tslib\", [\"exports\"], function (exports) { factory(createExporter(root, createExporter(exports))); });\r\n }\r\n else if (typeof module === \"object\" && typeof module.exports === \"object\") {\r\n factory(createExporter(root, createExporter(module.exports)));\r\n }\r\n else {\r\n factory(createExporter(root));\r\n }\r\n function createExporter(exports, previous) {\r\n if (exports !== root) {\r\n if (typeof Object.create === \"function\") {\r\n Object.defineProperty(exports, \"__esModule\", { value: true });\r\n }\r\n else {\r\n exports.__esModule = true;\r\n }\r\n }\r\n return function (id, v) { return exports[id] = previous ? previous(id, v) : v; };\r\n }\r\n})\r\n(function (exporter) {\r\n var extendStatics = Object.setPrototypeOf ||\r\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\r\n function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };\r\n\r\n __extends = function (d, b) {\r\n if (typeof b !== \"function\" && b !== null)\r\n throw new TypeError(\"Class extends value \" + String(b) + \" is not a constructor or null\");\r\n extendStatics(d, b);\r\n function __() { this.constructor = d; }\r\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\r\n };\r\n\r\n __assign = Object.assign || function (t) {\r\n for (var s, i = 1, n = arguments.length; i < n; i++) {\r\n s = arguments[i];\r\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];\r\n }\r\n return t;\r\n };\r\n\r\n __rest = function (s, e) {\r\n var t = {};\r\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)\r\n t[p] = s[p];\r\n if (s != null && typeof Object.getOwnPropertySymbols === \"function\")\r\n for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {\r\n if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))\r\n t[p[i]] = s[p[i]];\r\n }\r\n return t;\r\n };\r\n\r\n __decorate = function (decorators, target, key, desc) {\r\n var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;\r\n if (typeof Reflect === \"object\" && typeof Reflect.decorate === \"function\") r = Reflect.decorate(decorators, target, key, desc);\r\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;\r\n return c > 3 && r && Object.defineProperty(target, key, r), r;\r\n };\r\n\r\n __param = function (paramIndex, decorator) {\r\n return function (target, key) { decorator(target, key, paramIndex); }\r\n };\r\n\r\n __esDecorate = function (ctor, descriptorIn, decorators, contextIn, initializers, extraInitializers) {\r\n function accept(f) { if (f !== void 0 && typeof f !== \"function\") throw new TypeError(\"Function expected\"); return f; }\r\n var kind = contextIn.kind, key = kind === \"getter\" ? \"get\" : kind === \"setter\" ? \"set\" : \"value\";\r\n var target = !descriptorIn && ctor ? contextIn[\"static\"] ? ctor : ctor.prototype : null;\r\n var descriptor = descriptorIn || (target ? Object.getOwnPropertyDescriptor(target, contextIn.name) : {});\r\n var _, done = false;\r\n for (var i = decorators.length - 1; i >= 0; i--) {\r\n var context = {};\r\n for (var p in contextIn) context[p] = p === \"access\" ? {} : contextIn[p];\r\n for (var p in contextIn.access) context.access[p] = contextIn.access[p];\r\n context.addInitializer = function (f) { if (done) throw new TypeError(\"Cannot add initializers after decoration has completed\"); extraInitializers.push(accept(f || null)); };\r\n var result = (0, decorators[i])(kind === \"accessor\" ? { get: descriptor.get, set: descriptor.set } : descriptor[key], context);\r\n if (kind === \"accessor\") {\r\n if (result === void 0) continue;\r\n if (result === null || typeof result !== \"object\") throw new TypeError(\"Object expected\");\r\n if (_ = accept(result.get)) descriptor.get = _;\r\n if (_ = accept(result.set)) descriptor.set = _;\r\n if (_ = accept(result.init)) initializers.unshift(_);\r\n }\r\n else if (_ = accept(result)) {\r\n if (kind === \"field\") initializers.unshift(_);\r\n else descriptor[key] = _;\r\n }\r\n }\r\n if (target) Object.defineProperty(target, contextIn.name, descriptor);\r\n done = true;\r\n };\r\n\r\n __runInitializers = function (thisArg, initializers, value) {\r\n var useValue = arguments.length > 2;\r\n for (var i = 0; i < initializers.length; i++) {\r\n value = useValue ? initializers[i].call(thisArg, value) : initializers[i].call(thisArg);\r\n }\r\n return useValue ? value : void 0;\r\n };\r\n\r\n __propKey = function (x) {\r\n return typeof x === \"symbol\" ? x : \"\".concat(x);\r\n };\r\n\r\n __setFunctionName = function (f, name, prefix) {\r\n if (typeof name === \"symbol\") name = name.description ? \"[\".concat(name.description, \"]\") : \"\";\r\n return Object.defineProperty(f, \"name\", { configurable: true, value: prefix ? \"\".concat(prefix, \" \", name) : name });\r\n };\r\n\r\n __metadata = function (metadataKey, metadataValue) {\r\n if (typeof Reflect === \"object\" && typeof Reflect.metadata === \"function\") return Reflect.metadata(metadataKey, metadataValue);\r\n };\r\n\r\n __awaiter = function (thisArg, _arguments, P, generator) {\r\n function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\r\n return new (P || (P = Promise))(function (resolve, reject) {\r\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\r\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\r\n function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\r\n step((generator = generator.apply(thisArg, _arguments || [])).next());\r\n });\r\n };\r\n\r\n __generator = function (thisArg, body) {\r\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);\r\n return g.next = verb(0), g[\"throw\"] = verb(1), g[\"return\"] = verb(2), typeof Symbol === \"function\" && (g[Symbol.iterator] = function() { return this; }), g;\r\n function verb(n) { return function (v) { return step([n, v]); }; }\r\n function step(op) {\r\n if (f) throw new TypeError(\"Generator is already executing.\");\r\n while (g && (g = 0, op[0] && (_ = 0)), _) try {\r\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;\r\n if (y = 0, t) op = [op[0] & 2, t.value];\r\n switch (op[0]) {\r\n case 0: case 1: t = op; break;\r\n case 4: _.label++; return { value: op[1], done: false };\r\n case 5: _.label++; y = op[1]; op = [0]; continue;\r\n case 7: op = _.ops.pop(); _.trys.pop(); continue;\r\n default:\r\n if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }\r\n if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }\r\n if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }\r\n if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }\r\n if (t[2]) _.ops.pop();\r\n _.trys.pop(); continue;\r\n }\r\n op = body.call(thisArg, _);\r\n } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }\r\n if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };\r\n }\r\n };\r\n\r\n __exportStar = function(m, o) {\r\n for (var p in m) if (p !== \"default\" && !Object.prototype.hasOwnProperty.call(o, p)) __createBinding(o, m, p);\r\n };\r\n\r\n __createBinding = Object.create ? (function(o, m, k, k2) {\r\n if (k2 === undefined) k2 = k;\r\n var desc = Object.getOwnPropertyDescriptor(m, k);\r\n if (!desc || (\"get\" in desc ? !m.__esModule : desc.writable || desc.configurable)) {\r\n desc = { enumerable: true, get: function() { return m[k]; } };\r\n }\r\n Object.defineProperty(o, k2, desc);\r\n }) : (function(o, m, k, k2) {\r\n if (k2 === undefined) k2 = k;\r\n o[k2] = m[k];\r\n });\r\n\r\n __values = function (o) {\r\n var s = typeof Symbol === \"function\" && Symbol.iterator, m = s && o[s], i = 0;\r\n if (m) return m.call(o);\r\n if (o && typeof o.length === \"number\") return {\r\n next: function () {\r\n if (o && i >= o.length) o = void 0;\r\n return { value: o && o[i++], done: !o };\r\n }\r\n };\r\n throw new TypeError(s ? \"Object is not iterable.\" : \"Symbol.iterator is not defined.\");\r\n };\r\n\r\n __read = function (o, n) {\r\n var m = typeof Symbol === \"function\" && o[Symbol.iterator];\r\n if (!m) return o;\r\n var i = m.call(o), r, ar = [], e;\r\n try {\r\n while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);\r\n }\r\n catch (error) { e = { error: error }; }\r\n finally {\r\n try {\r\n if (r && !r.done && (m = i[\"return\"])) m.call(i);\r\n }\r\n finally { if (e) throw e.error; }\r\n }\r\n return ar;\r\n };\r\n\r\n /** @deprecated */\r\n __spread = function () {\r\n for (var ar = [], i = 0; i < arguments.length; i++)\r\n ar = ar.concat(__read(arguments[i]));\r\n return ar;\r\n };\r\n\r\n /** @deprecated */\r\n __spreadArrays = function () {\r\n for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length;\r\n for (var r = Array(s), k = 0, i = 0; i < il; i++)\r\n for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)\r\n r[k] = a[j];\r\n return r;\r\n };\r\n\r\n __spreadArray = function (to, from, pack) {\r\n if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {\r\n if (ar || !(i in from)) {\r\n if (!ar) ar = Array.prototype.slice.call(from, 0, i);\r\n ar[i] = from[i];\r\n }\r\n }\r\n return to.concat(ar || Array.prototype.slice.call(from));\r\n };\r\n\r\n __await = function (v) {\r\n return this instanceof __await ? (this.v = v, this) : new __await(v);\r\n };\r\n\r\n __asyncGenerator = function (thisArg, _arguments, generator) {\r\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\r\n var g = generator.apply(thisArg, _arguments || []), i, q = [];\r\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;\r\n function awaitReturn(f) { return function (v) { return Promise.resolve(v).then(f, reject); }; }\r\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]); } }\r\n function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }\r\n function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }\r\n function fulfill(value) { resume(\"next\", value); }\r\n function reject(value) { resume(\"throw\", value); }\r\n function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }\r\n };\r\n\r\n __asyncDelegator = function (o) {\r\n var i, p;\r\n return i = {}, verb(\"next\"), verb(\"throw\", function (e) { throw e; }), verb(\"return\"), i[Symbol.iterator] = function () { return this; }, i;\r\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; }\r\n };\r\n\r\n __asyncValues = function (o) {\r\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\r\n var m = o[Symbol.asyncIterator], i;\r\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);\r\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); }); }; }\r\n function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }\r\n };\r\n\r\n __makeTemplateObject = function (cooked, raw) {\r\n if (Object.defineProperty) { Object.defineProperty(cooked, \"raw\", { value: raw }); } else { cooked.raw = raw; }\r\n return cooked;\r\n };\r\n\r\n var __setModuleDefault = Object.create ? (function(o, v) {\r\n Object.defineProperty(o, \"default\", { enumerable: true, value: v });\r\n }) : function(o, v) {\r\n o[\"default\"] = v;\r\n };\r\n\r\n var ownKeys = function(o) {\r\n ownKeys = Object.getOwnPropertyNames || function (o) {\r\n var ar = [];\r\n for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;\r\n return ar;\r\n };\r\n return ownKeys(o);\r\n };\r\n\r\n __importStar = function (mod) {\r\n if (mod && mod.__esModule) return mod;\r\n var result = {};\r\n if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== \"default\") __createBinding(result, mod, k[i]);\r\n __setModuleDefault(result, mod);\r\n return result;\r\n };\r\n\r\n __importDefault = function (mod) {\r\n return (mod && mod.__esModule) ? mod : { \"default\": mod };\r\n };\r\n\r\n __classPrivateFieldGet = function (receiver, state, kind, f) {\r\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a getter\");\r\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\");\r\n return kind === \"m\" ? f : kind === \"a\" ? f.call(receiver) : f ? f.value : state.get(receiver);\r\n };\r\n\r\n __classPrivateFieldSet = function (receiver, state, value, kind, f) {\r\n if (kind === \"m\") throw new TypeError(\"Private method is not writable\");\r\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a setter\");\r\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\");\r\n return (kind === \"a\" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;\r\n };\r\n\r\n __classPrivateFieldIn = function (state, receiver) {\r\n if (receiver === null || (typeof receiver !== \"object\" && typeof receiver !== \"function\")) throw new TypeError(\"Cannot use 'in' operator on non-object\");\r\n return typeof state === \"function\" ? receiver === state : state.has(receiver);\r\n };\r\n\r\n __addDisposableResource = function (env, value, async) {\r\n if (value !== null && value !== void 0) {\r\n if (typeof value !== \"object\" && typeof value !== \"function\") throw new TypeError(\"Object expected.\");\r\n var dispose, inner;\r\n if (async) {\r\n if (!Symbol.asyncDispose) throw new TypeError(\"Symbol.asyncDispose is not defined.\");\r\n dispose = value[Symbol.asyncDispose];\r\n }\r\n if (dispose === void 0) {\r\n if (!Symbol.dispose) throw new TypeError(\"Symbol.dispose is not defined.\");\r\n dispose = value[Symbol.dispose];\r\n if (async) inner = dispose;\r\n }\r\n if (typeof dispose !== \"function\") throw new TypeError(\"Object not disposable.\");\r\n if (inner) dispose = function() { try { inner.call(this); } catch (e) { return Promise.reject(e); } };\r\n env.stack.push({ value: value, dispose: dispose, async: async });\r\n }\r\n else if (async) {\r\n env.stack.push({ async: true });\r\n }\r\n return value;\r\n };\r\n\r\n var _SuppressedError = typeof SuppressedError === \"function\" ? SuppressedError : function (error, suppressed, message) {\r\n var e = new Error(message);\r\n return e.name = \"SuppressedError\", e.error = error, e.suppressed = suppressed, e;\r\n };\r\n\r\n __disposeResources = function (env) {\r\n function fail(e) {\r\n env.error = env.hasError ? new _SuppressedError(e, env.error, \"An error was suppressed during disposal.\") : e;\r\n env.hasError = true;\r\n }\r\n var r, s = 0;\r\n function next() {\r\n while (r = env.stack.pop()) {\r\n try {\r\n if (!r.async && s === 1) return s = 0, env.stack.push(r), Promise.resolve().then(next);\r\n if (r.dispose) {\r\n var result = r.dispose.call(r.value);\r\n if (r.async) return s |= 2, Promise.resolve(result).then(next, function(e) { fail(e); return next(); });\r\n }\r\n else s |= 1;\r\n }\r\n catch (e) {\r\n fail(e);\r\n }\r\n }\r\n if (s === 1) return env.hasError ? Promise.reject(env.error) : Promise.resolve();\r\n if (env.hasError) throw env.error;\r\n }\r\n return next();\r\n };\r\n\r\n __rewriteRelativeImportExtension = function (path, preserveJsx) {\r\n if (typeof path === \"string\" && /^\\.\\.?\\//.test(path)) {\r\n return path.replace(/\\.(tsx)$|((?:\\.d)?)((?:\\.[^./]+?)?)\\.([cm]?)ts$/i, function (m, tsx, d, ext, cm) {\r\n return tsx ? preserveJsx ? \".jsx\" : \".js\" : d && (!ext || !cm) ? m : (d + ext + \".\" + cm.toLowerCase() + \"js\");\r\n });\r\n }\r\n return path;\r\n };\r\n\r\n exporter(\"__extends\", __extends);\r\n exporter(\"__assign\", __assign);\r\n exporter(\"__rest\", __rest);\r\n exporter(\"__decorate\", __decorate);\r\n exporter(\"__param\", __param);\r\n exporter(\"__esDecorate\", __esDecorate);\r\n exporter(\"__runInitializers\", __runInitializers);\r\n exporter(\"__propKey\", __propKey);\r\n exporter(\"__setFunctionName\", __setFunctionName);\r\n exporter(\"__metadata\", __metadata);\r\n exporter(\"__awaiter\", __awaiter);\r\n exporter(\"__generator\", __generator);\r\n exporter(\"__exportStar\", __exportStar);\r\n exporter(\"__createBinding\", __createBinding);\r\n exporter(\"__values\", __values);\r\n exporter(\"__read\", __read);\r\n exporter(\"__spread\", __spread);\r\n exporter(\"__spreadArrays\", __spreadArrays);\r\n exporter(\"__spreadArray\", __spreadArray);\r\n exporter(\"__await\", __await);\r\n exporter(\"__asyncGenerator\", __asyncGenerator);\r\n exporter(\"__asyncDelegator\", __asyncDelegator);\r\n exporter(\"__asyncValues\", __asyncValues);\r\n exporter(\"__makeTemplateObject\", __makeTemplateObject);\r\n exporter(\"__importStar\", __importStar);\r\n exporter(\"__importDefault\", __importDefault);\r\n exporter(\"__classPrivateFieldGet\", __classPrivateFieldGet);\r\n exporter(\"__classPrivateFieldSet\", __classPrivateFieldSet);\r\n exporter(\"__classPrivateFieldIn\", __classPrivateFieldIn);\r\n exporter(\"__addDisposableResource\", __addDisposableResource);\r\n exporter(\"__disposeResources\", __disposeResources);\r\n exporter(\"__rewriteRelativeImportExtension\", __rewriteRelativeImportExtension);\r\n});\r\n\r\n0 && (module.exports = {\r\n __extends: __extends,\r\n __assign: __assign,\r\n __rest: __rest,\r\n __decorate: __decorate,\r\n __param: __param,\r\n __esDecorate: __esDecorate,\r\n __runInitializers: __runInitializers,\r\n __propKey: __propKey,\r\n __setFunctionName: __setFunctionName,\r\n __metadata: __metadata,\r\n __awaiter: __awaiter,\r\n __generator: __generator,\r\n __exportStar: __exportStar,\r\n __createBinding: __createBinding,\r\n __values: __values,\r\n __read: __read,\r\n __spread: __spread,\r\n __spreadArrays: __spreadArrays,\r\n __spreadArray: __spreadArray,\r\n __await: __await,\r\n __asyncGenerator: __asyncGenerator,\r\n __asyncDelegator: __asyncDelegator,\r\n __asyncValues: __asyncValues,\r\n __makeTemplateObject: __makeTemplateObject,\r\n __importStar: __importStar,\r\n __importDefault: __importDefault,\r\n __classPrivateFieldGet: __classPrivateFieldGet,\r\n __classPrivateFieldSet: __classPrivateFieldSet,\r\n __classPrivateFieldIn: __classPrivateFieldIn,\r\n __addDisposableResource: __addDisposableResource,\r\n __disposeResources: __disposeResources,\r\n __rewriteRelativeImportExtension: __rewriteRelativeImportExtension,\r\n});\r\n","import tslib from '../tslib.js';\r\nconst {\r\n __extends,\r\n __assign,\r\n __rest,\r\n __decorate,\r\n __param,\r\n __esDecorate,\r\n __runInitializers,\r\n __propKey,\r\n __setFunctionName,\r\n __metadata,\r\n __awaiter,\r\n __generator,\r\n __exportStar,\r\n __createBinding,\r\n __values,\r\n __read,\r\n __spread,\r\n __spreadArrays,\r\n __spreadArray,\r\n __await,\r\n __asyncGenerator,\r\n __asyncDelegator,\r\n __asyncValues,\r\n __makeTemplateObject,\r\n __importStar,\r\n __importDefault,\r\n __classPrivateFieldGet,\r\n __classPrivateFieldSet,\r\n __classPrivateFieldIn,\r\n __addDisposableResource,\r\n __disposeResources,\r\n __rewriteRelativeImportExtension,\r\n} = tslib;\r\nexport {\r\n __extends,\r\n __assign,\r\n __rest,\r\n __decorate,\r\n __param,\r\n __esDecorate,\r\n __runInitializers,\r\n __propKey,\r\n __setFunctionName,\r\n __metadata,\r\n __awaiter,\r\n __generator,\r\n __exportStar,\r\n __createBinding,\r\n __values,\r\n __read,\r\n __spread,\r\n __spreadArrays,\r\n __spreadArray,\r\n __await,\r\n __asyncGenerator,\r\n __asyncDelegator,\r\n __asyncValues,\r\n __makeTemplateObject,\r\n __importStar,\r\n __importDefault,\r\n __classPrivateFieldGet,\r\n __classPrivateFieldSet,\r\n __classPrivateFieldIn,\r\n __addDisposableResource,\r\n __disposeResources,\r\n __rewriteRelativeImportExtension,\r\n};\r\nexport default tslib;\r\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() {\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\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: 'public-anon-key' },\n * region: FunctionRegion.UsEast1,\n * })\n * ```\n *\n * @category Functions\n *\n * @example Creating a Functions client\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: 'public-anon-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 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 Functions\n *\n * @remarks\n * - Requires an Authorization header.\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.\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.log('Function returned an error', errorMessage)\n * } else if (error instanceof FunctionsRelayError) {\n * console.log('Relay error:', error.message)\n * } else if (error instanceof FunctionsFetchError) {\n * console.log('Fetch error:', error.message)\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 Example 7\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\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 if (\n functionArgs &&\n ((headers && !Object.prototype.hasOwnProperty.call(headers, 'Content-Type')) || !headers)\n ) {\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'] = '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 signal.addEventListener('abort', () => timeoutController!.abort())\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 let responseType = (response.headers.get('Content-Type') ?? 'text/plain').split(';')[0].trim()\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 }\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\nexport type GenericUpdatableView = {\n Row: Record<string, unknown>\n Insert: Record<string, unknown>\n Update: Record<string, unknown>\n Relationships: GenericRelationship[]\n}\n\nexport type GenericNonUpdatableView = {\n Row: Record<string, unknown>\n Relationships: GenericRelationship[]\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","/**\n * Error format\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() {\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","import type {\n PostgrestSingleResponse,\n PostgrestResponseSuccess,\n CheckMatchingArrayTypes,\n MergePartialResult,\n IsValidResultOverride,\n} from './types/types'\nimport {\n ClientServerOptions,\n Fetch,\n DEFAULT_MAX_RETRIES,\n getRetryDelay,\n RETRYABLE_STATUS_CODES,\n RETRYABLE_METHODS,\n} from './types/common/common'\nimport PostgrestError from './PostgrestError'\nimport { ContainsNull } from './select-query-parser/types'\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 default abstract class PostgrestBuilder<\n ClientOptions extends ClientServerOptions,\n Result,\n ThrowOnError extends boolean = false,\n> implements\n PromiseLike<\n ThrowOnError extends true ? PostgrestResponseSuccess<Result> : PostgrestSingleResponse<Result>\n >\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\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: 'public-anon-key' }) }\n * )\n * ```\n *\n * @category Database\n *\n * @example Creating a Postgrest query builder\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: 'public-anon-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 */\n throwOnError(): this & PostgrestBuilder<ClientOptions, Result, true> {\n this.shouldThrowOnError = true\n return this as this & 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 *\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 for the request.\n *\n * @category Database\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 *\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 let attemptCount = 0\n\n while (true) {\n const requestHeaders = new Headers(this.headers)\n if (attemptCount > 0) {\n requestHeaders.set('X-Retry-Count', String(attemptCount))\n }\n\n // Only wrap the fetch call itself — processResponse errors must never trigger retries\n let res: Response\n try {\n res = await _fetch(this.url.toString(), {\n method: this.method,\n headers: requestHeaders,\n body: JSON.stringify(this.body),\n signal: this.signal,\n })\n } catch (fetchError: any) {\n // Never retry aborted requests\n if (fetchError?.name === 'AbortError' || fetchError?.code === 'ABORT_ERR') {\n throw fetchError\n }\n\n // Don't retry network errors for non-idempotent methods\n if (!RETRYABLE_METHODS.includes(this.method as (typeof RETRYABLE_METHODS)[number])) {\n throw fetchError\n }\n\n // Check if we should retry network errors\n if (this.retryEnabled && attemptCount < DEFAULT_MAX_RETRIES) {\n const delay = getRetryDelay(attemptCount)\n attemptCount++\n await sleep(delay, this.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(this.method, res.status, attemptCount, this.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, this.signal)\n continue\n }\n\n return await this.processResponse(res)\n }\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 data = JSON.parse(body)\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 } 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 */\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 *\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 Example 5\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> extends PostgrestBuilder<ClientOptions, Result> {\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 *\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\": \"Created\"\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 > {\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 >\n }\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 *\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 `count`.\n *\n * @param count - 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 *\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 count: 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, `${count}`)\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 *\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 *\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\": 400,\n * \"statusText\": \"Bad Request\"\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 *\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 > {\n this.headers.set('Accept', 'application/vnd.pgrst.object+json')\n return this as unknown as PostgrestBuilder<ClientOptions, ResultOne>\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 *\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> {\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>\n }\n\n /**\n * Return `data` as a string in CSV format.\n *\n * @category Database\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> {\n this.headers.set('Accept', 'text/csv')\n return this as unknown as PostgrestBuilder<ClientOptions, string>\n }\n\n /**\n * Return `data` as an object in [GeoJSON](https://geojson.org) format.\n *\n * @category Database\n */\n geojson(): PostgrestBuilder<ClientOptions, Record<string, unknown>> {\n this.headers.set('Accept', 'application/geo+json')\n return this as unknown as PostgrestBuilder<ClientOptions, Record<string, unknown>>\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 *\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<ClientOptions, Record<string, unknown>[]>\n } else {\n return this as unknown as PostgrestBuilder<ClientOptions, string>\n }\n }\n\n /**\n * Rollback the query.\n *\n * `data` will still be returned, but the query is not committed.\n *\n * @category Database\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 *\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 > {\n return this as unknown as PostgrestTransformBuilder<\n ClientOptions,\n Schema,\n Row,\n CheckMatchingArrayTypes<Result, NewResult>,\n RelationName,\n Relationships,\n Method\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 value - The maximum number of rows that can be affected\n *\n * @category Database\n */\n maxAffected(value: 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=${value}`)\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\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> extends PostgrestTransformBuilder<\n ClientOptions,\n Schema,\n Row,\n Result,\n RelationName,\n Relationships,\n Method\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 *\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 * @param column - The column to filter on\n * @param value - The value to filter with\n *\n * @category Database\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 gt<ColumnName extends string & keyof Row>(column: ColumnName, value: Row[ColumnName]): this\n gt(column: string, value: unknown): this\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 *\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(column: string, value: unknown): this {\n this.url.searchParams.append(column, `gt.${value}`)\n return this\n }\n\n gte<ColumnName extends string & keyof Row>(column: ColumnName, value: Row[ColumnName]): this\n gte(column: string, value: unknown): this\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 *\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(column: string, value: unknown): this {\n this.url.searchParams.append(column, `gte.${value}`)\n return this\n }\n\n lt<ColumnName extends string & keyof Row>(column: ColumnName, value: Row[ColumnName]): this\n lt(column: string, value: unknown): this\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 *\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(column: string, value: unknown): this {\n this.url.searchParams.append(column, `lt.${value}`)\n return this\n }\n\n lte<ColumnName extends string & keyof Row>(column: ColumnName, value: Row[ColumnName]): this\n lte(column: string, value: unknown): this\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 *\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(column: string, value: unknown): this {\n this.url.searchParams.append(column, `lte.${value}`)\n return this\n }\n\n like<ColumnName extends string & keyof Row>(column: ColumnName, pattern: string): this\n like(column: string, pattern: string): this\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 *\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(column: string, pattern: string): this {\n this.url.searchParams.append(column, `like.${pattern}`)\n return this\n }\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 /**\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 */\n likeAllOf(column: string, patterns: readonly string[]): this {\n this.url.searchParams.append(column, `like(all).{${patterns.join(',')}}`)\n return this\n }\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 /**\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 */\n likeAnyOf(column: string, patterns: readonly string[]): this {\n this.url.searchParams.append(column, `like(any).{${patterns.join(',')}}`)\n return this\n }\n\n ilike<ColumnName extends string & keyof Row>(column: ColumnName, pattern: string): this\n ilike(column: string, pattern: string): this\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 *\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(column: string, pattern: string): this {\n this.url.searchParams.append(column, `ilike.${pattern}`)\n return this\n }\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 /**\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 */\n ilikeAllOf(column: string, patterns: readonly string[]): this {\n this.url.searchParams.append(column, `ilike(all).{${patterns.join(',')}}`)\n return this\n }\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 /**\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 */\n ilikeAnyOf(column: string, patterns: readonly string[]): this {\n this.url.searchParams.append(column, `ilike(any).{${patterns.join(',')}}`)\n return this\n }\n\n regexMatch<ColumnName extends string & keyof Row>(column: ColumnName, pattern: string): this\n regexMatch(column: string, pattern: string): this\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(column: string, pattern: string): this {\n this.url.searchParams.append(column, `match.${pattern}`)\n return this\n }\n\n regexIMatch<ColumnName extends string & keyof Row>(column: ColumnName, pattern: string): this\n regexIMatch(column: string, pattern: string): this\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(column: string, pattern: string): this {\n this.url.searchParams.append(column, `imatch.${pattern}`)\n return this\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 /**\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 *\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(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 *\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 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 /**\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 *\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(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 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 /**\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 *\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(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 rangeGt<ColumnName extends string & keyof Row>(column: ColumnName, range: string): this\n rangeGt(column: string, range: string): this\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 *\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(column: string, range: string): this {\n this.url.searchParams.append(column, `sr.${range}`)\n return this\n }\n\n rangeGte<ColumnName extends string & keyof Row>(column: ColumnName, range: string): this\n rangeGte(column: string, range: string): this\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 *\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(column: string, range: string): this {\n this.url.searchParams.append(column, `nxl.${range}`)\n return this\n }\n\n rangeLt<ColumnName extends string & keyof Row>(column: ColumnName, range: string): this\n rangeLt(column: string, range: string): this\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 *\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(column: string, range: string): this {\n this.url.searchParams.append(column, `sl.${range}`)\n return this\n }\n\n rangeLte<ColumnName extends string & keyof Row>(column: ColumnName, range: string): this\n rangeLte(column: string, range: string): this\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 *\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(column: string, range: string): this {\n this.url.searchParams.append(column, `nxr.${range}`)\n return this\n }\n\n rangeAdjacent<ColumnName extends string & keyof Row>(column: ColumnName, range: string): this\n rangeAdjacent(column: string, range: string): this\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 *\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(column: string, range: string): this {\n this.url.searchParams.append(column, `adj.${range}`)\n return this\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 /**\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 *\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(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 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 /**\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 *\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(\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 match<ColumnName extends string & keyof Row>(query: Record<ColumnName, Row[ColumnName]>): this\n match(query: Record<string, unknown>): this\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 *\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(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 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 *\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(column: string, operator: string, value: unknown): this {\n this.url.searchParams.append(column, `not.${operator}.${value}`)\n return this\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 *\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 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 /**\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 *\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(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 Creating a Postgrest query builder\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: 'public-anon-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 * @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'\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 // TODO(v3): Make `defaultToNull` consistent for both single & bulk inserts.\n insert<Row extends Relation extends { Insert: unknown } ? Relation['Insert'] : never>(\n values: RejectExcessProperties<\n Relation extends { Insert: unknown } ? Relation['Insert'] : never,\n Row\n >,\n options?: {\n count?: 'exact' | 'planned' | 'estimated'\n }\n ): PostgrestFilterBuilder<\n ClientOptions,\n Schema,\n Relation['Row'],\n null,\n RelationName,\n Relationships,\n 'POST'\n >\n insert<Row extends Relation extends { Insert: unknown } ? Relation['Insert'] : never>(\n values: RejectExcessProperties<\n Relation extends { Insert: unknown } ? Relation['Insert'] : never,\n Row\n >[],\n options?: {\n count?: 'exact' | 'planned' | 'estimated'\n defaultToNull?: boolean\n }\n ): PostgrestFilterBuilder<\n ClientOptions,\n Schema,\n Relation['Row'],\n null,\n RelationName,\n Relationships,\n 'POST'\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\": \"Created\"\n * }\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\": \"Created\"\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\": \"Conflict\"\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'\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 // TODO(v3): Make `defaultToNull` consistent for both single & bulk upserts.\n upsert<Row extends Relation extends { Insert: unknown } ? Relation['Insert'] : never>(\n values: RejectExcessProperties<\n Relation extends { Insert: unknown } ? Relation['Insert'] : never,\n Row\n >,\n options?: {\n onConflict?: string\n ignoreDuplicates?: boolean\n count?: 'exact' | 'planned' | 'estimated'\n }\n ): PostgrestFilterBuilder<\n ClientOptions,\n Schema,\n Relation['Row'],\n null,\n RelationName,\n Relationships,\n 'POST'\n >\n upsert<Row extends Relation extends { Insert: unknown } ? Relation['Insert'] : never>(\n values: RejectExcessProperties<\n Relation extends { Insert: unknown } ? Relation['Insert'] : never,\n Row\n >[],\n options?: {\n onConflict?: string\n ignoreDuplicates?: boolean\n count?: 'exact' | 'planned' | 'estimated'\n defaultToNull?: boolean\n }\n ): PostgrestFilterBuilder<\n ClientOptions,\n Schema,\n Relation['Row'],\n null,\n RelationName,\n Relationships,\n 'POST'\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\": \"Created\"\n * }\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\": \"Created\"\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\": \"Conflict\"\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'\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\": \"No Content\"\n * }\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'\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\": \"No Content\"\n * }\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\": \"No Content\"\n * }\n * ```\n */\n delete({\n count,\n }: {\n count?: 'exact' | 'planned' | 'estimated'\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'\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 &\n keyof Omit<Database, '__InternalSupabase'> = 'public' extends keyof Omit<\n Database,\n '__InternalSupabase'\n >\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\n * ```ts\n * import { PostgrestClient } from '@supabase/postgrest-js'\n *\n * const postgrest = new PostgrestClient('https://xyzcompany.supabase.co/rest/v1', {\n * headers: { apikey: 'public-anon-key' },\n * schema: 'public',\n * timeout: 30000, // 30 second timeout\n * })\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 Creating a Postgrest client\n * ```ts\n * import { PostgrestClient } from '@supabase/postgrest-js'\n *\n * const postgrest = new PostgrestClient('https://xyzcompany.supabase.co/rest/v1', {\n * headers: { apikey: 'public-anon-key' },\n * schema: 'public',\n * })\n * ```\n *\n * @example With timeout\n * ```ts\n * import { PostgrestClient } from '@supabase/postgrest-js'\n *\n * const postgrest = new PostgrestClient('https://xyzcompany.supabase.co/rest/v1', {\n * headers: { apikey: 'public-anon-key' },\n * schema: 'public',\n * timeout: 30000, // 30 second timeout\n * retry: false, // Disable automatic retries\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 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 * @category Database\n */\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 * 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<\n Schema,\n FnName,\n 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'\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} 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' | 'ws' | 'cloudflare' | 'unsupported'\n constructor?: any\n error?: string\n workaround?: string\n}\n\n/**\n * Utilities for creating WebSocket instances across runtimes.\n */\nexport class WebSocketFactory {\n /**\n * Static-only utility – prevent instantiation.\n */\n private constructor() {}\n private static detectEnvironment(): WebSocketEnvironment {\n if (typeof WebSocket !== 'undefined') {\n return { type: 'native', constructor: WebSocket }\n }\n\n if (typeof globalThis !== 'undefined' && typeof (globalThis as any).WebSocket !== 'undefined') {\n return { type: 'native', constructor: (globalThis as any).WebSocket }\n }\n\n if (typeof global !== 'undefined' && typeof (global as any).WebSocket !== 'undefined') {\n return { type: 'native', constructor: (global as any).WebSocket }\n }\n\n if (\n typeof globalThis !== 'undefined' &&\n typeof (globalThis as any).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' && (globalThis as any).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 any)['process']\n if (_process) {\n const processVersions = _process['versions']\n if (processVersions && processVersions['node']) {\n // Remove 'v' prefix if present and parse the major version\n const versionString = processVersions['node']\n const nodeVersion = parseInt(versionString.replace(/^v/, '').split('.')[0])\n\n // Node.js 22+ should have native WebSocket\n if (nodeVersion >= 22) {\n // Check if native WebSocket is available (should be in Node.js 22+)\n if (typeof globalThis.WebSocket !== 'undefined') {\n return { type: 'native', constructor: globalThis.WebSocket }\n }\n // If not available, user needs to provide it\n return {\n type: 'unsupported',\n error: `Node.js ${nodeVersion} detected but native WebSocket not found.`,\n workaround: 'Provide a WebSocket implementation via the transport option.',\n }\n }\n\n // Node.js < 22 doesn't have native WebSocket\n return {\n type: 'unsupported',\n error: `Node.js ${nodeVersion} detected without native WebSocket support.`,\n workaround:\n 'For Node.js < 22, install \"ws\" package and provide it via the transport option:\\n' +\n 'import ws from \"ws\"\\n' +\n 'new RealtimeClient(url, { transport: ws })',\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.constructor) {\n return env.constructor\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' || env.type === 'ws'\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.103.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\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'\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 const topic = message.topic\n const ref = message.ref ?? ''\n const joinRef = message.join_ref ?? ''\n const userEvent = 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 = Object.keys(rest).length === 0 ? '' : JSON.stringify(rest)\n\n // Validate 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 let view = new DataView(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 Array.from(joinRef, (char) => view.setUint8(offset++, char.charCodeAt(0)))\n Array.from(ref, (char) => view.setUint8(offset++, char.charCodeAt(0)))\n Array.from(topic, (char) => view.setUint8(offset++, char.charCodeAt(0)))\n Array.from(userEvent, (char) => view.setUint8(offset++, char.charCodeAt(0)))\n Array.from(metadata, (char) => view.setUint8(offset++, char.charCodeAt(0)))\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\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} 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){\n this.awaitingBatchAck = true\n this.ajax(\"POST\", {\"Content-Type\": \"application/x-ndjson\"}, messages.join(\"\\n\"), () => this.onerror(\"timeout\"), resp => {\n this.awaitingBatchAck = false\n if(!resp || resp.status !== 200){\n this.onerror(resp && resp.status)\n this.closeAndRetry(1011, \"internal server error\", false)\n } else if(this.batchBuffer.length > 0){\n this.batchSend(this.batchBuffer)\n this.batchBuffer = []\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 = {}\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.clone(currentState)\n let joins = {}\n let leaves = {}\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 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 /**\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 metaLength = this.META_LENGTH + join_ref.length + ref.length + topic.length + event.length\n let header = new ArrayBuffer(this.HEADER_LENGTH + metaLength)\n let view = new DataView(header)\n let offset = 0\n\n view.setUint8(offset++, this.KINDS.push) // kind\n view.setUint8(offset++, join_ref.length)\n view.setUint8(offset++, ref.length)\n view.setUint8(offset++, topic.length)\n view.setUint8(offset++, event.length)\n Array.from(join_ref, char => view.setUint8(offset++, char.charCodeAt(0)))\n Array.from(ref, char => view.setUint8(offset++, char.charCodeAt(0)))\n Array.from(topic, char => view.setUint8(offset++, char.charCodeAt(0)))\n Array.from(event, char => view.setUint8(offset++, char.charCodeAt(0)))\n\n var combined = new Uint8Array(header.byteLength + payload.byteLength)\n combined.set(new Uint8Array(header), 0)\n combined.set(new Uint8Array(payload), header.byteLength)\n\n return combined.buffer\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 /** @type{Storage} */\n this.sessionStore = opts.sessionStorage || (global && global.sessionStorage)\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\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()\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()\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)\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()\n }\n }\n\n /**\n * @private\n */\n triggerChanError(){\n this.channels.forEach(channel => {\n if(!(channel.isErrored() || channel.isLeaving() || channel.isClosed())){\n channel.trigger(CHANNEL_EVENTS.error)\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 presence['presence_ref'] = presence['phx_ref']\n\n delete presence['phx_ref']\n delete presence['phx_ref_prev']\n\n return presence\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","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 `tried to push '${event}' to '${this.channel.topic}' before joining. Use channel.subscribe() before pushing events`\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","import { CHANNEL_EVENTS, CHANNEL_STATES } 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 ChannelAdapter from './phoenix/channelAdapter'\nimport { ChannelBindingCallback, ChannelOnErrorCallback } from './phoenix/types'\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 */\n broadcast?: { self?: boolean; ack?: boolean; replay?: ReplayOption }\n /**\n * key option is used to track presence payload across clients\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}\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 when filter is matched.\n */\n filter?: string\n}\n\nexport type RealtimeChannelSendResponse = 'ok' | 'timed out' | 'error'\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 }[]\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() {\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 Example for a public channel\n * ```ts\n * import RealtimeClient from '@supabase/realtime-js'\n *\n * const client = new RealtimeClient('https://xyzcompany.supabase.co/realtime/v1', {\n * params: { apikey: 'public-anon-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 `tried to use replay on public channel '${this.topic}'. It must be a private channel.`\n }\n }\n\n /**\n * Subscribe registers your client with the server\n * @category Realtime\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 },\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 }\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, reason as Error)\n })\n\n this._onClose(() => callback?.(REALTIME_SUBSCRIBE_STATES.CLOSED))\n\n this.updateJoinPayload({ ...{ config }, ...accessTokenPayload })\n\n this._updateFilterMessage()\n\n this.channelAdapter\n .subscribe(timeout)\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 callback?.(\n REALTIME_SUBSCRIBE_STATES.CHANNEL_ERROR,\n new Error(JSON.stringify(Object.values(error).join(', ') || 'error'))\n )\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 * @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.timeout || this.timeout\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 * Creates an event handler that listens to changes.\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 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 * The following is placed here to display on supabase.com/docs/reference/javascript/subscribe.\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 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 * @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]: string },\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 * @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('Payload is required for httpSend()')\n }\n\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: payload,\n private: this.private,\n },\n ],\n }),\n }\n\n const response = await this._fetchWithTimeout(\n this.broadcastEndpointURL,\n options,\n opts.timeout ?? this.timeout\n )\n\n if (response.status === 202) {\n return { success: true }\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 *\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 * supabase\n * .channel('room1')\n * .httpSend('cursor-pos', { x: Math.random(), y: Math.random() })\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 console.warn(\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\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: any) {\n if (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 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 /** @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 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 { Message, SocketOptions, HeartbeatCallback, Encode, Decode } from './phoenix/types'\n\ntype Fetch = typeof fetch\n\nexport type LogLevel = 'info' | 'warn' | 'error'\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'\nexport type HeartbeatStatus = 'sent' | 'ok' | 'error' | 'timeout' | 'disconnected'\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 accessToken?: () => Promise<string | null>\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() {\n return this.socketAdapter.reconnectTimer\n }\n\n get 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 _workerHeartbeatTimer: HeartbeatTimer = undefined\n private _pendingWorkerHeartbeatRef: string | null = null\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 httpEndpoint The string HTTP endpoint, ie, \"https://example.com\", \"/\" (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 Example for a public channel\n * ```ts\n * import RealtimeClient from '@supabase/realtime-js'\n *\n * const client = new RealtimeClient('https://xyzcompany.supabase.co/realtime/v1', {\n * params: { apikey: 'public-anon-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\n // Provide helpful error message based on environment\n if (errorMessage.includes('Node.js')) {\n throw new Error(\n `${errorMessage}\\n\\n` +\n 'To use Realtime in Node.js, you need to provide a WebSocket implementation:\\n\\n' +\n 'Option 1: Use Node.js 22+ which has native WebSocket support\\n' +\n 'Option 2: Install and provide the \"ws\" package:\\n\\n' +\n ' npm install ws\\n\\n' +\n ' import ws from \"ws\"\\n' +\n ' const client = new RealtimeClient(url, {\\n' +\n ' ...options,\\n' +\n ' transport: ws\\n' +\n ' })'\n )\n }\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 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 if (this.channels.length === 0) {\n this.disconnect()\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 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 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.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, it will be preserved across channel operations\n * (including removeChannel and resubscribe). The `accessToken` callback will not be\n * invoked until `setAuth()` is called without arguments.\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, ignores accessToken callback)\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 this._authPromise = this._performAuth(token)\n try {\n await this._authPromise\n } finally {\n this._authPromise = null\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/disconnected).\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 }\n\n /**\n * Perform the actual auth operation\n * @internal\n */\n private async _performAuth(token: string | null = null): 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 // Track whether this token was manually set or fetched via callback\n if (isManualToken) {\n this._manuallySetToken = true\n } else if (this.accessToken) {\n // If we used the callback, clear the manual flag\n this._manuallySetToken = false\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 tokenToSend && 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 == '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 // @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.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\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 constructor(\n message: string,\n status: number,\n statusCode: string,\n namespace: ErrorNamespace = 'storage'\n ) {\n super(message, namespace, status, statusCode)\n this.name = namespace === 'vectors' ? 'StorageVectorsApiError' : 'StorageApiError'\n this.status = status\n this.statusCode = statusCode\n }\n\n toJSON() {\n return {\n name: this.name,\n message: this.message,\n status: this.status,\n statusCode: this.statusCode,\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","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","import { StorageApiError, StorageUnknownError, ErrorNamespace } from './errors'\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: any): string =>\n err.msg ||\n err.message ||\n err.error_description ||\n (typeof err.error === 'string' ? err.error : err.error?.message) ||\n JSON.stringify(err)\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?: any) => 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 && typeof error === 'object' && typeof (error as any).json === 'function'\n\n if (isResponseLike) {\n const responseError = error as any\n let status = parseInt(responseError.status, 10)\n if (!Number.isFinite(status)) {\n status = 500\n }\n\n responseError\n .json()\n .then((err: any) => {\n const statusCode = err?.statusCode || err?.code || status + ''\n reject(new StorageApiError(_getErrorMessage(err), status, statusCode, namespace))\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 = setRequestHeader(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\nfunction setRequestHeader(headers: Record<string, string>, name: string, value: string) {\n const nextHeaders = { ...headers }\n\n for (const key of Object.keys(nextHeaders)) {\n if (key.toLowerCase() === name.toLowerCase()) {\n delete nextHeaders[key]\n }\n }\n\n nextHeaders[name] = value\n return nextHeaders\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 { 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 = Object.fromEntries(Object.entries(headers).map(([k, v]) => [k.toLowerCase(), v]))\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 = { ...this.headers, [name.toLowerCase()]: 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 PromiseLike<DownloadResult<ReadableStream>> {\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.execute().then(onfulfilled, onrejected)\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 { 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 FileObjectV2,\n Camelize,\n SearchV2Options,\n SearchV2Result,\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 (typeof Blob !== 'undefined' && fileBody instanceof Blob) {\n body = new FormData()\n body.append('cacheControl', options.cacheControl as string)\n if (metadata) {\n body.append('metadata', this.encodeMetadata(metadata))\n }\n body.append('', fileBody)\n } else if (typeof FormData !== 'undefined' && fileBody instanceof FormData) {\n body = fileBody\n // Only append if not already present\n if (!body.has('cacheControl')) {\n body.append('cacheControl', options.cacheControl as string)\n }\n if (metadata && !body.has('metadata')) {\n body.append('metadata', this.encodeMetadata(metadata))\n }\n } else {\n body = fileBody\n headers['cache-control'] = `max-age=${options.cacheControl}`\n headers['content-type'] = options.contentType as string\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 headers = { ...headers, ...fileOptions.headers }\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 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, 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 * @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 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, 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 const headers: Record<string, string> = {\n ...this.headers,\n ...{ 'x-upsert': String(options.upsert as boolean) },\n }\n\n if (typeof Blob !== 'undefined' && fileBody instanceof Blob) {\n body = new FormData()\n body.append('cacheControl', options.cacheControl as string)\n body.append('', fileBody)\n } else if (typeof FormData !== 'undefined' && fileBody instanceof FormData) {\n body = fileBody\n body.append('cacheControl', options.cacheControl as string)\n } else {\n body = fileBody\n headers['cache-control'] = `max-age=${options.cacheControl}`\n headers['content-type'] = options.contentType as string\n }\n\n const data = await put(this.fetch, url.toString(), body as object, { headers })\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 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 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, upsert, and metadata.\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 * upsert: true\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 * - 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 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 * @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 },\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 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 options.\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 * @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?: 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 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 },\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 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 * @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 }\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 { expiresIn, ...(hasTransform ? { transform: options!.transform } : {}) },\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 // When transforms are requested the signed URL must use the render endpoint.\n // Some storage-api versions return /object/sign/ even for transform requests,\n // so we normalise the path on the client side.\n const returnedPath =\n hasTransform && data.signedURL.includes('/object/sign/')\n ? data.signedURL.replace('/object/sign/', '/render/image/sign/')\n : data.signedURL\n\n // `returnedPath` contains a `token` query parameter, so append extra params with `&` only\n // when we actually have something to add.\n const signedUrl = encodeURI(\n `${this.url}${returnedPath}${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 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: { error: string | null; path: string | null; signedUrl: string }[]\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((datum: { signedURL: string }) => ({\n ...datum,\n signedUrl: datum.signedURL\n ? encodeURI(`${this.url}${datum.signedURL}${queryString ? `&${queryString}` : ''}`)\n : null,\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 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.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 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<Options extends { transform?: TransformOptions; cacheNonce?: string }>(\n path: string,\n options?: Options,\n parameters?: FetchParameters\n ): BlobDownloadBuilder {\n const wantsTransformation = typeof options?.transform !== 'undefined'\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 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 File Buckets\n * @param path The file path, including the file name. For example `folder/image.png`.\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(path: string): 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\n return this.handleOperation(async () => {\n const data = await get(this.fetch, `${this.url}/object/info/${_path}`, {\n headers: this.headers,\n })\n\n return recursiveToCamel(data) as Camelize<FileObjectV2>\n })\n }\n\n /**\n * Checks the existence of a file.\n *\n * @category 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 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 * @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 }\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 const queryString = query.toString()\n\n const wantsTransformation = typeof options?.transform !== 'undefined'\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 File Buckets\n * @param paths An array of files to delete, including the path and file name. For example [`'folder/image.png'`].\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 * @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: string[]): 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 * 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 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 const body = { ...DEFAULT_SEARCH_OPTIONS, ...options, 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 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 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.103.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 BaseApiClient from '../lib/common/BaseApiClient'\nimport { Bucket, BucketType, ListBucketOptions } 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 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 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 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 * @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 } = {\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 },\n { headers: this.headers }\n )\n })\n }\n\n /**\n * Updates a Storage bucket\n *\n * @category 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 * @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 }\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 },\n { headers: this.headers }\n )\n })\n }\n\n /**\n * Removes all objects inside a single bucket.\n *\n * @category 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 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 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 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 Creating a StorageAnalyticsClient instance\n * ```typescript\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 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 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 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 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 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 Creating a StorageVectorsClient instance\n * ```typescript\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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 Vector Buckets\n * @param options - Query options (bucket and index names automatically set)\n * @returns Promise with response containing matches array of similar vectors ordered by distance or 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 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 File Buckets\n * @example Creating a Storage client\n * ```ts\n * import { StorageClient } from '@supabase/storage-js'\n *\n * const storage = new StorageClient('https://xyzcompany.supabase.co/storage/v1', {\n * apikey: 'public-anon-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 File Buckets\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 Vector Buckets\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 Analytics Buckets\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.103.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\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\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 #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\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 return {\n name: this.name,\n message: this.message,\n status: this.status,\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 return {\n name: this.name,\n message: this.message,\n status: this.status,\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 * 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\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 { API_VERSION_HEADER_NAME, BASE64URL_REGEX } 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: any) {\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 return value\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: any) {\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\nexport async function getCodeChallengeAndMethod(\n storage: SupportedStorage,\n storageKey: string,\n isPasswordRecovery = false\n) {\n const codeVerifier = generatePKCEVerifier()\n let storedCodeVerifier = codeVerifier\n if (isPasswordRecovery) {\n storedCodeVerifier += '/PASSWORD_RECOVERY'\n }\n await setItemAsync(storage, `${storageKey}-code-verifier`, storedCodeVerifier)\n const codeChallenge = await generatePKCEChallenge(codeVerifier)\n const codeChallengeMethod = codeVerifier === codeChallenge ? 'plain' : 's256'\n return [codeChallenge, codeChallengeMethod]\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: any) {\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'\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}$/\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 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 SSOResponse,\n GenerateLinkProperties,\n GenerateLinkResponse,\n User,\n UserResponse,\n} from './types'\nimport {\n AuthApiError,\n AuthRetryableFetchError,\n AuthWeakPasswordError,\n AuthUnknownError,\n AuthSessionMissingError,\n} from './errors'\n\nexport type Fetch = typeof fetch\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' | 'DELETE'\n\nconst _getErrorMessage = (err: any): string =>\n err.msg || err.message || err.error_description || err.error || JSON.stringify(err)\n\nconst NETWORK_ERROR_CODES = [502, 503, 504]\n\nexport async function handleError(error: unknown) {\n if (!looksLikeFetchResponse(error)) {\n throw new AuthRetryableFetchError(_getErrorMessage(error), 0)\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(error), error.status)\n }\n\n let data: any\n try {\n data = await error.json()\n } catch (e: any) {\n throw new AuthUnknownError(_getErrorMessage(e), e)\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: any\n\n try {\n result = await fetcher(url, {\n ...requestParams,\n })\n } catch (e) {\n console.error(e)\n\n // fetch failed, likely due to a network or CORS error\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: any) {\n await handleError(e)\n }\n}\n\nexport function _sessionResponse(data: any): AuthResponse {\n let session = null\n if (hasSession(data)) {\n session = { ...data }\n\n if (!data.expires_at) {\n session.expires_at = expiresAt(data.expires_in)\n }\n }\n\n const user: User = data.user ?? (data as User)\n return { data: { session, user }, error: null }\n}\n\nexport function _sessionResponsePassword(data: any): 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: any) => 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: any): UserResponse {\n const user: User = data.user ?? (data as User)\n return { data: { user }, error: null }\n}\n\nexport function _ssoResponse(data: any): SSOResponse {\n return { data, error: null }\n}\n\nexport function _generateLinkResponse(data: any): 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: User = { ...rest }\n return {\n data: {\n properties,\n user,\n },\n error: null,\n }\n}\n\nexport function _noResolveJsonResponse(data: any): 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: any): 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} 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 * `navigatorLock` (Web Locks API) is used in browser environments when\n * `persistSession` is true. Falls back to an in-process lock for non-browser\n * environments (e.g. React Native).\n *\n * @experimental\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 a cross-tab synchronization lock.\n *\n * When multiple browser tabs or windows use the auth client simultaneously, they coordinate\n * via the Web Locks API to prevent race conditions during session refresh and other operations.\n * This timeout controls how long to wait before attempting lock recovery.\n *\n * - **Positive value**: Wait up to this many milliseconds. If the lock is still held, attempt\n * automatic recovery by stealing it (the previous holder is evicted, its callback continues\n * to completion without exclusive access). This recovers from orphaned locks caused by\n * React Strict Mode double-mount, storage API hangs, or aborted operations.\n * - **Zero (0)**: Fail immediately if the lock is unavailable; throws `LockAcquireTimeoutError`\n * (check `error.isAcquireTimeout === true`).\n * - **Negative value**: Wait indefinitely — can cause permanent deadlocks if the lock is orphaned.\n *\n * @default 5000\n *\n * @example\n * ```ts\n * const client = createClient(url, key, {\n * auth: {\n * lockAcquireTimeout: 5000, // 5 seconds, then steal orphaned lock\n * },\n * })\n * ```\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\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 * {@see 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 * {@see 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 error: null\n }\n | {\n data: {\n provider: Provider\n url: 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 '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'] as const\n\n/**\n * Type of factor. `totp` and `phone` supported with this version\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 GoTrueMFAAdminApi#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` and `phone` supported with this version\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 \"µs\"), \"ms\", \"s\", \"m\", \"h\".\n *\n * For example, some possible durations include: '300ms', '2h45m'.\n *\n * Setting the ban duration to 'none' lifts the ban on the user.\n */\n ban_duration?: string | 'none'\n\n /**\n * The `role` claim set in the user's access token JWT.\n *\n * When a user signs up, this role is set to `authenticated` by default. You should only modify the `role` if you need to provision several levels of admin access that have different permissions on individual columns in your database.\n *\n * Setting this role to `service_role` is not recommended as it grants the user admin privileges.\n */\n role?: string\n\n /**\n * The `password_hash` for the user's password.\n *\n * Allows you to specify a password hash for the user. This is useful for migrating a user's password hash from another service.\n *\n * Supports bcrypt, scrypt (firebase), and argon2 password hashes.\n */\n password_hash?: string\n\n /**\n * The `id` for the user.\n *\n * Allows you to overwrite the default `id` set for the user.\n */\n id?: string\n}\n\nexport interface Subscription {\n /**\n * A unique identifier for this subscription, set by the client.\n * This is an internal identifier used for managing callbacks and should not be\n * relied upon by application code. Use the unsubscribe() method to remove listeners.\n */\n id: string | symbol\n /**\n * The function to call every time there is an event. eg: (eventName) => {}\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 = Prettify<\n 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>\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'\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'\nexport type EmailOtpType = 'signup' | 'invite' | 'magiclink' | 'recovery' | 'email_change' | 'email'\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 = Prettify<MFAVerifyParamsBase & MFAVerifyTOTPParamFields>\n\ntype MFAVerifyPhoneParamFields = MFAVerifyTOTPParamFields\n\nexport type MFAVerifyPhoneParams = Prettify<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 Prettify<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 = Prettify<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 = Prettify<\n MFAChallengeParamsBase & MFAChallengePhoneParamFields\n>\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 = Prettify<\n MFAChallengeParamsBase & MFAChallengeWebauthnParamFields\n>\n\nexport type MFAChallengeParams =\n | MFAChallengeTOTPParams\n | MFAChallengePhoneParams\n | MFAChallengeWebauthnParams\n\ntype MFAChallengeAndVerifyParamsBase = Omit<MFAVerifyParamsBase, 'challengeId'>\n\ntype MFAChallengeAndVerifyTOTPParamFields = MFAVerifyTOTPParamFields\n\ntype MFAChallengeAndVerifyTOTPParams = Prettify<\n MFAChallengeAndVerifyParamsBase & MFAChallengeAndVerifyTOTPParamFields\n>\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\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 Prettify<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 Prettify<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 Prettify<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 = Prettify<\n AuthMFAChallengeResponseBase<'webauthn'> & AuthMFAChallengeWebauthnResponseFieldsJSON\n>\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: Prettify<Factor>[]\n\n // Dynamically create a property for each factor type with only verified factors\n } & {\n [K in T[number]]: Prettify<Factor<K, 'verified'>>[]\n }\n >\n\nexport type AuthenticatorAssuranceLevels = 'aal1' | 'aal2'\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 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 *\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 *\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 *\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 *\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 *\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 */\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 *\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/**\n * @expermental\n */\nexport type AuthMFAAdminDeleteFactorResponse = RequestResult<{\n /** ID of the factor that was successfully deleted. */\n id: string\n}>\n/**\n * @expermental\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 * @expermental\n */\nexport type AuthMFAAdminListFactorsResponse = RequestResult<{\n /** All factors attached to the user. */\n factors: Factor[]\n}>\n\n/**\n * @expermental\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 * @expermental\n */\nexport interface GoTrueAdminMFAApi {\n /**\n * Lists all factors associated to a user.\n *\n *\n * @category Auth\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 * @expermental\n *\n * @category Auth\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 = Prettify<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 = Prettify<\n MFAEnrollParamsBase<'phone'> & MFAEnrollPhoneParamFields\n>\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 = Prettify<\n MFAEnrollParamsBase<'webauthn'> & MFAEnrollWebauthnFields\n>\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 Prettify<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 Prettify<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 Prettify<AuthMFAEnrollResponseBase<'webauthn'> & AuthMFAEnrollWebauthnFields>\n>\n\nexport type JwtHeader = {\n alg: 'RS256' | 'ES256' | 'HS256'\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'\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'\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 */\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 */\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 */\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 */\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 */\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 */\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 /** 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 /** 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 /** 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 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 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 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 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 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 */\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 */\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 */\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 */\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 */\n revokeGrant(options: { clientId: string }): Promise<AuthOAuthRevokeGrantResponse>\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} 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 protected url: string\n protected headers: {\n [key: string]: string\n }\n protected fetch: Fetch\n\n /**\n * Creates an admin API client that can be used to manage users and OAuth clients.\n *\n * @example\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_SERVICE_ROLE_KEY}` },\n * })\n * ```\n */\n constructor({\n url = '',\n headers = {},\n fetch,\n }: {\n url: string\n headers?: {\n [key: string]: string\n }\n fetch?: Fetch\n }) {\n this.url = url\n this.headers = headers\n this.fetch = resolveFetch(fetch)\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 }\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 */\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 *\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 email The user's email.\n * @param options.password User password. For signup only.\n * @param options.data Optional user metadata. For signup only.\n * @param options.redirectTo The redirect url which should be appended to the generated link\n *\n * @category Auth\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 *\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 *\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 *\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 *\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 *\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","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","import { supportsLocalStorage } from './helpers'\n\n/**\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 * Use the {@link #isAcquireTimeout} property instead of checking with `instanceof`.\n *\n * @example\n * ```ts\n * import { LockAcquireTimeoutError } from '@supabase/auth-js'\n *\n * class CustomLockError extends LockAcquireTimeoutError {\n * constructor() {\n * super('Lock timed out')\n * }\n * }\n * ```\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 * Error thrown when the browser Navigator Lock API fails to acquire a lock.\n *\n * @example\n * ```ts\n * import { NavigatorLockAcquireTimeoutError } from '@supabase/auth-js'\n *\n * throw new NavigatorLockAcquireTimeoutError('Lock timed out')\n * ```\n */\nexport class NavigatorLockAcquireTimeoutError extends LockAcquireTimeoutError {}\n/**\n * Error thrown when the process-level lock helper cannot acquire a lock.\n *\n * @example\n * ```ts\n * import { ProcessLockAcquireTimeoutError } from '@supabase/auth-js'\n *\n * throw new ProcessLockAcquireTimeoutError('Lock timed out')\n * ```\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 * @example\n * ```ts\n * await navigatorLock('sync-user', 1000, async () => {\n * await refreshSession()\n * })\n * ```\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 — 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: any) {\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: any) {\n // Always clear the acquire timeout once the request settles, so it cannot\n // fire later and incorrectly abort/log after a rejection.\n if (acquireTimeout > 0) {\n clearTimeout(acquireTimeoutTimer)\n }\n\n if (e?.name === 'AbortError' && acquireTimeout > 0) {\n if (abortController.signal.aborted) {\n // OUR timeout fired — the lock is genuinely orphaned. Steal it.\n //\n // The lock acquisition was aborted because the timeout fired while the\n // request was still pending. This typically means another lock holder is\n // not releasing the lock, possibly due to React Strict Mode's\n // double-mount/unmount behavior or a component unmounting mid-operation,\n // leaving an orphaned lock.\n //\n // Recovery: use { steal: true } to forcefully acquire the lock. Per the\n // Web Locks API spec, this releases any currently held lock with the same\n // name and grants the request immediately, preempting any queued requests.\n // The previous holder's callback continues running to completion but no\n // longer holds the lock for exclusion purposes.\n //\n // See: https://github.com/supabase/supabase/issues/42505\n if (internals.debug) {\n console.log(\n '@supabase/gotrue-js: navigatorLock: acquire timeout, recovering by stealing lock',\n name\n )\n }\n\n console.warn(\n `@supabase/gotrue-js: Lock \"${name}\" was not released within ${acquireTimeout}ms. ` +\n 'This may indicate an orphaned lock from a component unmount (e.g., React Strict Mode). ' +\n 'Forcefully acquiring the lock to recover.'\n )\n\n return await Promise.resolve().then(() =>\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 — 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 * @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: any) {\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 && e.isAcquireTimeout) {\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: any) {\n if (e && e.isAcquireTimeout) {\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\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 */\nfunction 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 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 STORAGE_KEY,\n} from './lib/constants'\nimport {\n AuthError,\n AuthImplicitGrantRedirectError,\n AuthInvalidCredentialsError,\n AuthInvalidJwtError,\n AuthInvalidTokenResponseError,\n AuthPKCECodeVerifierMissingError,\n AuthPKCEGrantCodeExchangeError,\n AuthSessionMissingError,\n AuthUnknownError,\n isAuthApiError,\n isAuthError,\n isAuthImplicitGrantRedirectError,\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 decodeJWT,\n deepClone,\n Deferred,\n generateCallbackId,\n getAlgorithm,\n getCodeChallengeAndMethod,\n getItemAsync,\n insecureUserWarningProxy,\n isBrowser,\n parseParametersFromURL,\n removeItemAsync,\n resolveFetch,\n retryable,\n setItemAsync,\n sleep,\n supportsLocalStorage,\n userNotAvailableProxy,\n validateExp,\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 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 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} from './lib/types'\nimport {\n createSiweMessage,\n fromHex,\n getAddress,\n Hex,\n SiweMessage,\n toHex,\n} from './lib/web3/ethereum'\nimport {\n deserializeCredentialCreationOptions,\n deserializeCredentialRequestOptions,\n serializeCredentialCreationResponse,\n serializeCredentialRequestResponse,\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\n skipAutoInitialize: false,\n}\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\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 * 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 * 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 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 protected lock: LockFunc\n protected lockAcquired = false\n protected pendingInLock: Promise<any>[] = []\n protected throwOnError: boolean\n protected lockAcquireTimeout: number\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\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: 'public-anon-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.admin = new GoTrueAdminApi({\n url: settings.url,\n headers: settings.headers,\n fetch: settings.fetch,\n })\n\n this.url = settings.url\n this.headers = settings.headers\n this.fetch = resolveFetch(settings.fetch)\n this.lock = settings.lock || lockNoOp\n this.detectSessionInUrl = settings.detectSessionInUrl\n this.flowType = settings.flowType\n this.hasCustomAuthorizationHeader = settings.hasCustomAuthorizationHeader\n this.throwOnError = settings.throwOnError\n this.lockAcquireTimeout = settings.lockAcquireTimeout\n\n if (settings.lock) {\n this.lock = settings.lock\n } else if (this.persistSession && isBrowser() && globalThis?.navigator?.locks) {\n this.lock = navigatorLock\n } else {\n this.lock = lockNoOp\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 }\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 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: any) {\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 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 * Initializes the client session either from the url or from storage.\n * This method is automatically called when instantiating the client, but should also be called\n * manually when checking for an error from an auth redirect (oauth, magiclink, password recovery, etc).\n *\n * @category Auth\n */\n async initialize(): Promise<InitializeResult> {\n if (this.initializePromise) {\n return await this.initializePromise\n }\n\n this.initializePromise = (async () => {\n return await this._acquireLock(this.lockAcquireTimeout, async () => {\n return await this._initialize()\n })\n })()\n\n return await this.initializePromise\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 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] = await getCodeChallengeAndMethod(\n this.storage,\n this.storageKey\n )\n }\n res = await _request(this.fetch, 'POST', `${this.url}/signup`, {\n headers: this.headers,\n redirectTo: options?.emailRedirectTo,\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 removeItemAsync(this.storage, `${this.storageKey}-code-verifier`)\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 removeItemAsync(this.storage, `${this.storageKey}-code-verifier`)\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 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 * },\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 *\n * @example Exchange Auth Code\n * ```js\n * supabase.auth.exchangeCodeForSession('34e770dd-9ff9-416c-87fa-43b31d7ef225')\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(authCode: string): Promise<AuthTokenResponse> {\n await this.initializePromise\n\n return this._acquireLock(this.lockAcquireTimeout, async () => {\n return this._exchangeCodeForSession(authCode)\n })\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(authCode: string): 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 storageItem = await getItemAsync(this.storage, `${this.storageKey}-code-verifier`)\n const [codeVerifier, redirectType] = ((storageItem ?? '') as string).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 removeItemAsync(this.storage, `${this.storageKey}-code-verifier`)\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('SIGNED_IN', data.session)\n }\n return this._returnResult({ data: { ...data, redirectType: redirectType ?? null }, error })\n } catch (error) {\n await removeItemAsync(this.storage, `${this.storageKey}-code-verifier`)\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 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] = await getCodeChallengeAndMethod(\n this.storage,\n this.storageKey\n )\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: options?.emailRedirectTo,\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 removeItemAsync(this.storage, `${this.storageKey}-code-verifier`)\n if (isAuthError(error)) {\n return this._returnResult({ data: { user: null, session: null }, error })\n }\n\n throw error\n }\n }\n\n /**\n * Log in a user given a User supplied OTP or TokenHash received through mobile or email.\n *\n * @category Auth\n *\n * @remarks\n * - The `verifyOtp` method takes in different verification types.\n * - If a phone number is used, the type can either be:\n * 1. `sms` – Used when verifying a one-time password (OTP) sent via SMS during sign-up or sign-in.\n * 2. `phone_change` – Used when verifying an OTP sent to a new phone number during a phone number update process.\n * - If an email address is used, the type can be one of the following (note: `signup` and `magiclink` types are deprecated):\n * 1. `email` – Used when verifying an OTP sent to the user's email during sign-up or sign-in.\n * 2. `recovery` – Used when verifying an OTP sent for account recovery, typically after a password reset request.\n * 3. `invite` – Used when verifying an OTP sent as part of an invitation to join a project or organization.\n * 4. `email_change` – Used when verifying an OTP sent to a new email address during an email update process.\n * - The verification type used should be determined based on the corresponding auth method called before `verifyOtp` to sign up / sign-in a user.\n * - The `TokenHash` is contained in the [email templates](/docs/guides/auth/auth-email-templates) and can be used to sign in. You may wish to use the hash for the PKCE flow for Server Side Auth. Read [the Password-based Auth guide](/docs/guides/auth/passwords) for more details.\n *\n * @example Verify Signup One-Time Password (OTP)\n * ```js\n * const { data, error } = await supabase.auth.verifyOtp({ email, token, type: 'email'})\n * ```\n *\n * @exampleResponse Verify Signup One-Time Password (OTP)\n * ```json\n * {\n * \"data\": {\n * \"user\": {\n * \"id\": \"11111111-1111-1111-1111-111111111111\",\n * \"aud\": \"authenticated\",\n * \"role\": \"authenticated\",\n * \"email\": \"example@email.com\",\n * \"email_confirmed_at\": \"2024-01-01T00:00:00Z\",\n * \"phone\": \"\",\n * \"confirmed_at\": \"2024-01-01T00:00:00Z\",\n * \"recovery_sent_at\": \"2024-01-01T00:00:00Z\",\n * \"last_sign_in_at\": \"2024-01-01T00:00:00Z\",\n * \"app_metadata\": {\n * \"provider\": \"email\",\n * \"providers\": [\n * \"email\"\n * ]\n * },\n * \"user_metadata\": {\n * \"email\": \"example@email.com\",\n * \"email_verified\": false,\n * \"phone_verified\": false,\n * \"sub\": \"11111111-1111-1111-1111-111111111111\"\n * },\n * \"identities\": [\n * {\n * \"identity_id\": \"22222222-2222-2222-2222-222222222222\",\n * \"id\": \"11111111-1111-1111-1111-111111111111\",\n * \"user_id\": \"11111111-1111-1111-1111-111111111111\",\n * \"identity_data\": {\n * \"email\": \"example@email.com\",\n * \"email_verified\": false,\n * \"phone_verified\": false,\n * \"sub\": \"11111111-1111-1111-1111-111111111111\"\n * },\n * \"provider\": \"email\",\n * \"last_sign_in_at\": \"2024-01-01T00:00:00Z\",\n * \"created_at\": \"2024-01-01T00:00:00Z\",\n * \"updated_at\": \"2024-01-01T00:00:00Z\",\n * \"email\": \"example@email.com\"\n * }\n * ],\n * \"created_at\": \"2024-01-01T00:00:00Z\",\n * \"updated_at\": \"2024-01-01T00:00:00Z\",\n * \"is_anonymous\": false\n * },\n * \"session\": {\n * \"access_token\": \"<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 = 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 try {\n let codeChallenge: string | null = null\n let codeChallengeMethod: string | null = null\n if (this.flowType === 'pkce') {\n ;[codeChallenge, codeChallengeMethod] = await getCodeChallengeAndMethod(\n this.storage,\n this.storageKey\n )\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: params.options?.redirectTo ?? undefined,\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 removeItemAsync(this.storage, `${this.storageKey}-code-verifier`)\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 return await this._acquireLock(this.lockAcquireTimeout, async () => {\n return await this._reauthenticate()\n })\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 try {\n const endpoint = `${this.url}/resend`\n if ('email' in credentials) {\n const { email, type, options } = credentials\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 },\n redirectTo: options?.emailRedirectTo,\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 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 #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 * - When using in a browser, this function is synchronized across all tabs using the [LockManager](https://developer.mozilla.org/en-US/docs/Web/API/LockManager) API. In other environments make sure you've defined a proper `lock` property, if necessary, to make sure there are no race conditions while the session is being refreshed.\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 const result = await this._acquireLock(this.lockAcquireTimeout, async () => {\n return this._useSession(async (result) => {\n return result\n })\n })\n\n return result\n }\n\n /**\n * Acquires a global lock based on the storage key.\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: any) {\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 #getSession} inside the library. It is\n * semantically usually what you want, as getting a session involves some\n * processing afterwards that requires only one client operating on the\n * session at once across multiple tabs or processes.\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 // the use of __loadSession here is the only correct use of the function!\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 {@link #_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.lockAcquired) {\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 if (this.userStorage) {\n const maybeUser: { user?: User | null } | null = (await getItemAsync(\n this.userStorage,\n this.storageKey + '-user'\n )) as any\n\n if (maybeUser?.user) {\n currentSession.user = maybeUser.user\n } else {\n currentSession.user = userNotAvailableProxy()\n }\n }\n\n // Wrap the user object with a warning proxy on the server\n // This warns when properties of the user are accessed, not when session.user itself is accessed\n if (\n this.storage.isServer &&\n currentSession.user &&\n !(currentSession.user as any).__isUserNotAvailableProxy\n ) {\n const suppressWarningRef = { value: this.suppressGetSessionWarning }\n currentSession.user = insecureUserWarningProxy(currentSession.user, suppressWarningRef)\n\n // Update the client-level suppression flag when the proxy suppresses the warning\n if (suppressWarningRef.value) {\n this.suppressGetSessionWarning = true\n }\n }\n\n return { data: { session: currentSession }, error: null }\n }\n\n const { data: session, error } = await this._callRefreshToken(currentSession.refresh_token)\n if (error) {\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 * 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 const result = await this._acquireLock(this.lockAcquireTimeout, async () => {\n return 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 await removeItemAsync(this.storage, `${this.storageKey}-code-verifier`)\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 return await this._acquireLock(this.lockAcquireTimeout, async () => {\n return await this._updateUser(attributes, options)\n })\n }\n\n protected async _updateUser(\n attributes: UserAttributes,\n options: {\n emailRedirectTo?: string | undefined\n } = {}\n ): Promise<UserResponse> {\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] = await getCodeChallengeAndMethod(\n this.storage,\n this.storageKey\n )\n }\n\n const { data, error: userError } = await _request(this.fetch, 'PUT', `${this.url}/user`, {\n headers: this.headers,\n redirectTo: options?.emailRedirectTo,\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 removeItemAsync(this.storage, `${this.storageKey}-code-verifier`)\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 return await this._acquireLock(this.lockAcquireTimeout, async () => {\n return await this._setSession(currentSession)\n })\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 return await this._acquireLock(this.lockAcquireTimeout, async () => {\n return await this._refreshSession(currentSession)\n })\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 if (error) throw error\n\n const url = new URL(window.location.href)\n url.searchParams.delete('code')\n\n window.history.replaceState(window.history.state, '', url.toString())\n\n return { data: { session: data.session, redirectType: null }, error: null }\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(params.access_token || params.error_description)\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 const currentStorageContent = await getItemAsync(\n this.storage,\n `${this.storageKey}-code-verifier`\n )\n\n return !!(params.code && 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 * @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 all other sessions that the user is logged into as well. Customize this behavior by passing a scope parameter.\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 (all sessions)\n * ```js\n * const { error } = await supabase.auth.signOut()\n * ```\n *\n * @example Sign out (current session)\n * ```js\n * const { error } = await supabase.auth.signOut({ scope: 'local' })\n * ```\n *\n * @example Sign out (other sessions)\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 return await this._acquireLock(this.lockAcquireTimeout, async () => {\n return await this._signOut(options)\n })\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 { 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 return this._returnResult({ error })\n }\n }\n }\n if (scope !== 'others') {\n await this._removeSession()\n await removeItemAsync(this.storage, `${this.storageKey}-code-verifier`)\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 * Avoid using an async function inside `onAuthStateChange` as you might end\n * up with a deadlock. The callback function runs inside an exclusive lock,\n * so calling other Supabase Client APIs that also try to acquire the\n * exclusive lock, might cause a deadlock. This behavior is observable across\n * tabs. In the next major library version, this behavior will not be supported.\n *\n * Receive a notification every time an auth event happens.\n *\n * @param callback A callback function to be invoked when an auth event happens.\n * @deprecated Due to the possibility of deadlocks with async functions as callbacks, use the version without an async function.\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 * - **Important:** A callback can be an `async` function and it runs synchronously during the processing of the changes causing the event. You can easily create a dead-lock by using `await` on a call to another method of the Supabase library.\n * - Avoid using `async` functions as callbacks.\n * - Limit the number of `await` calls in `async` callbacks.\n * - Do not use other Supabase functions in the callback function. If you must, dispatch the functions once the callback has finished executing. Use this as a quick way to achieve this:\n * ```js\n * supabase.auth.onAuthStateChange((event, session) => {\n * setTimeout(async () => {\n * // await on other Supabase function here\n * // this runs right after the callback has finished\n * }, 0)\n * })\n * ```\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 await this._acquireLock(this.lockAcquireTimeout, async () => {\n 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 (isAuthSessionMissingError(err)) {\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\n if (this.flowType === 'pkce') {\n ;[codeChallenge, codeChallengeMethod] = await getCodeChallengeAndMethod(\n this.storage,\n this.storageKey,\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: options.redirectTo,\n })\n } catch (error) {\n await removeItemAsync(this.storage, `${this.storageKey}-code-verifier`)\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 * },\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 try {\n const { data, error } = await this._useSession(async (result) => {\n const { data, error } = result\n if (error) throw error\n const url: string = 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 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 },\n error: null,\n })\n } catch (error) {\n if (isAuthError(error)) {\n return this._returnResult({ data: { provider: credentials.provider, url: null }, error })\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 removeItemAsync(this.storage, `${this.storageKey}-code-verifier`)\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 const debugName = `#_refreshAccessToken(${refreshToken.substring(0, 5)}...)`\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: string = 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 }, 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 console.error(error)\n\n if (!isAuthRetryableFetchError(error)) {\n this._debug(\n debugName,\n 'refresh failed with a non-retryable error, removing the session',\n error\n )\n await this._removeSession()\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 console.error(err)\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 const debugName = `#_callRefreshToken(${refreshToken.substring(0, 5)}...)`\n\n this._debug(debugName, 'begin')\n\n try {\n this.refreshingDeferred = new Deferred<CallRefreshTokenResult>()\n\n const { data, error } = await this._refreshAccessToken(refreshToken)\n if (error) throw error\n if (!data.session) throw new AuthSessionMissingError()\n\n await this._saveSession(data.session)\n await this._notifyAllSubscribers('TOKEN_REFRESHED', data.session)\n\n const result = { data: data.session, error: 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 await this._removeSession()\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 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: any[] = []\n const promises = Array.from(this.stateChangeEmitters.values()).map(async (x) => {\n try {\n await x.callback(event, session)\n } catch (e: any) {\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 await removeItemAsync(this.storage, `${this.storageKey}-code-verifier`)\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 this._debug('#_removeSession()')\n\n this.suppressGetSessionWarning = false\n\n await removeItemAsync(this.storage, this.storageKey)\n await removeItemAsync(this.storage, this.storageKey + '-code-verifier')\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 * {@see #startAutoRefresh}\n * {@see #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 #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 #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 * {@see #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 #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 * Runs the auto refresh token tick.\n */\n private async _autoRefreshTokenTick() {\n this._debug('#_autoRefreshTokenTick()', 'begin')\n\n try {\n await this._acquireLock(0, async () => {\n try {\n const now = Date.now()\n\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 // 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: any) {\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: any) {\n if (e.isAcquireTimeout || e instanceof LockAcquireTimeoutError) {\n this._debug('auto refresh token tick lock not available')\n } else {\n throw e\n }\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 immediately... but to do that we need to acquire\n // the lock first asynchronously\n await this.initializePromise\n\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\n // visibility has changed while waiting for the lock, abort\n return\n }\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 const urlParams: string[] = [`provider=${encodeURIComponent(provider)}`]\n if (options?.redirectTo) {\n urlParams.push(`redirect_to=${encodeURIComponent(options.redirectTo)}`)\n }\n if (options?.scopes) {\n urlParams.push(`scopes=${encodeURIComponent(options.scopes)}`)\n }\n if (this.flowType === 'pkce') {\n const [codeChallenge, codeChallengeMethod] = await getCodeChallengeAndMethod(\n this.storage,\n this.storageKey\n )\n\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}?${urlParams.join('&')}`\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 * {@see 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 * {@see 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 return this._acquireLock(this.lockAcquireTimeout, async () => {\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\n /**\n * {@see 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 return this._acquireLock(this.lockAcquireTimeout, async () => {\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\n /**\n * {@see GoTrueMFAApi#challengeAndVerify}\n */\n private async _challengeAndVerify(\n params: MFAChallengeAndVerifyParams\n ): Promise<AuthMFAVerifyResponse> {\n // both _challenge and _verify independently acquire the lock, so no need\n // to acquire it here\n\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 * {@see GoTrueMFAApi#listFactors}\n */\n private async _listFactors(): Promise<AuthMFAListFactorsResponse> {\n // use #getUser instead of #_getUser as the former acquires a lock\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 }\n\n // loop over the factors ONCE\n for (const factor of user?.factors ?? []) {\n data.all.push(factor)\n if (factor.status === 'verified') {\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 * {@see 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 * 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 #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 {@link\n * #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 #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 validateExp(payload.exp)\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","import GoTrueAdminApi from './GoTrueAdminApi'\n\nconst AuthAdminApi = GoTrueAdminApi\n\nexport default AuthAdminApi\n","import GoTrueClient from './GoTrueClient'\n\nconst AuthClient = GoTrueClient\n\nexport default AuthClient\n","// 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.103.0'\n","// constants.ts\nimport { RealtimeClientOptions } from '@supabase/realtime-js'\nimport { SupabaseAuthClientOptions } from './types'\nimport { version } from './version'\n\nlet JS_ENV = ''\n// @ts-ignore\nif (typeof Deno !== 'undefined') {\n JS_ENV = '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}\n\nexport const DEFAULT_HEADERS = { 'X-Client-Info': `supabase-js-${JS_ENV}/${version}` }\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","type 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\nexport const fetchWithAuth = (\n supabaseKey: string,\n getAccessToken: () => Promise<string | null>,\n customFetch?: Fetch\n): Fetch => {\n const fetch = resolveFetch(customFetch)\n const HeadersConstructor = resolveHeadersConstructor()\n\n return async (input, init) => {\n const accessToken = (await getAccessToken()) ?? supabaseKey\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 headers.set('Authorization', `Bearer ${accessToken}`)\n }\n\n return fetch(input, { ...init, headers })\n }\n}\n","// helpers.ts\nimport { SupabaseClientOptions } from './types'\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\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): Required<SupabaseClientOptions<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 const result: Required<SupabaseClientOptions<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 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 PostgrestQueryBuilder,\n} from '@supabase/postgrest-js'\nimport {\n type RealtimeChannel,\n type RealtimeChannelOptions,\n RealtimeClient,\n type RealtimeClientOptions,\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} from './lib/constants'\nimport { fetchWithAuth } from './lib/fetch'\nimport { applySettingDefaults, validateSupabaseUrl } 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 &\n keyof Omit<Database, '__InternalSupabase'> = SchemaNameOrClientOptions extends string &\n 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 changedAccessToken?: string\n protected accessToken?: () => Promise<string | null>\n\n protected headers: Record<string, string>\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.db.schema You can switch in between schemas. The schema needs to be on the list of exposed schemas inside Supabase.\n * @param options.auth.autoRefreshToken Set to \"true\" if you want to automatically refresh the token before expiring.\n * @param options.auth.persistSession Set to \"true\" if you want to automatically save the user session into local storage.\n * @param options.auth.detectSessionInUrl Set to \"true\" if you want to automatically detects OAuth grants in the URL and signs in the user.\n * @param options.realtime Options passed along to realtime-js constructor.\n * @param options.storage Options passed along to the storage-js constructor.\n * @param options.global.fetch A custom fetch implementation.\n * @param options.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', 'publishable-or-anon-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', 'publishable-or-anon-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\", \"publishable-or-anon-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', 'publishable-or-anon-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 [`cross-fetch`](https://www.npmjs.com/package/cross-fetch) library to make HTTP requests,\n * but an alternative `fetch` implementation can be provided as an option.\n * This is most useful in environments where `cross-fetch` is not compatible (for instance Cloudflare Workers).\n *\n * @example Custom fetch implementation\n * ```js\n * import { createClient } from '@supabase/supabase-js'\n *\n * const supabase = createClient('https://xyzcompany.supabase.co', 'publishable-or-anon-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\", \"publishable-or-anon-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\", \"publishable-or-anon-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', 'public-anon-key')\n *\n * const { data } = await supabase.from('profiles').select('*')\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\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 }\n\n const settings = applySettingDefaults(options ?? {}, DEFAULTS)\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 this.fetch = fetchWithAuth(supabaseKey, this._getAccessToken.bind(this), settings.global.fetch)\n this.realtime = this._initRealtimeClient({\n headers: this.headers,\n accessToken: this._getAccessToken.bind(this),\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 })\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.fetch,\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.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<\n Schema,\n FnName,\n 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 */\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 Initializing\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 Initializing\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<'ok' | 'timed out' | 'error'> {\n return this.realtime.removeChannel(channel)\n }\n\n /**\n * Unsubscribes and removes all Realtime channels from Realtime client.\n *\n * @category Initializing\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<('ok' | 'timed out' | 'error')[]> {\n return this.realtime.removeAllChannels()\n }\n\n private async _getAccessToken() {\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 ?? 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 }: 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 fetch,\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') &&\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 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 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', 'public-anon-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 &\n keyof Omit<Database, '__InternalSupabase'> = SchemaNameOrClientOptions extends string &\n 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 <= 18 deprecation\nfunction shouldShowDeprecationWarning(): boolean {\n // Skip in browser environments\n if (typeof window !== '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 <= 18\n}\n\nif (shouldShowDeprecationWarning()) {\n console.warn(\n `⚠️ Node.js 18 and below are deprecated and will no longer be supported in future versions of @supabase/supabase-js. ` +\n `Please upgrade to Node.js 20 or later. ` +\n `For more information, visit: https://github.com/orgs/supabase/discussions/37217`\n )\n}\n"],"mappings":";;;;;;;AAAA;AAAA;AAAA;AAeA,QAAIA;AACJ,QAAIC;AACJ,QAAIC;AACJ,QAAIC;AACJ,QAAIC;AACJ,QAAIC;AACJ,QAAIC;AACJ,QAAIC;AACJ,QAAIC;AACJ,QAAIC;AACJ,QAAIC;AACJ,QAAIC;AACJ,QAAIC;AACJ,QAAIC;AACJ,QAAIC;AACJ,QAAIC;AACJ,QAAIC;AACJ,QAAIC;AACJ,QAAIC;AACJ,QAAIC;AACJ,QAAIC;AACJ,QAAIC;AACJ,QAAIC;AACJ,QAAIC;AACJ,QAAIC;AACJ,QAAIC;AACJ,QAAIC;AACJ,QAAIC;AACJ,QAAIC;AACJ,QAAIC;AACJ,QAAIC;AACJ,QAAIC;AACJ,KAAC,SAAU,SAAS;AAChB,UAAI,OAAO,OAAO,WAAW,WAAW,SAAS,OAAO,SAAS,WAAW,OAAO,OAAO,SAAS,WAAW,OAAO,CAAC;AACtH,UAAI,OAAO,WAAW,cAAc,OAAO,KAAK;AAC5C,eAAO,SAAS,CAAC,SAAS,GAAG,SAAUC,UAAS;AAAE,kBAAQ,eAAe,MAAM,eAAeA,QAAO,CAAC,CAAC;AAAA,QAAG,CAAC;AAAA,MAC/G,WACS,OAAO,WAAW,YAAY,OAAO,OAAO,YAAY,UAAU;AACvE,gBAAQ,eAAe,MAAM,eAAe,OAAO,OAAO,CAAC,CAAC;AAAA,MAChE,OACK;AACD,gBAAQ,eAAe,IAAI,CAAC;AAAA,MAChC;AACA,eAAS,eAAeA,UAAS,UAAU;AACvC,YAAIA,aAAY,MAAM;AAClB,cAAI,OAAO,OAAO,WAAW,YAAY;AACrC,mBA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,SAAA,SAAU,QAAS,YAAA;;;EAK/C,oBACN,OACA,QACA,OACA;AACA,SACG,UAAU,qBAAqB,UAAU,gBAC1C,KAAK,uBAAuB,OAC5B;AACA,WAAK,qBAAqB;AAC1B,WAAK,SAAS,QAAQ,KAAA;eACb,UAAU,cAAc;AACjC,WAAK,SAAS,QAAA;AACd,UAAI,UAAU,UAAW,MAAK,KAAK,QAAA;AACnC,WAAK,qBAAqB;;;;ACvjBhC,IAAa,eAAA,CAeX,aACA,aACA,YACoE;AACpE,SAAO,IAAI,eACT,aACA,aACA,OAAA;;AAKJ,SAAS,+BAAwC;AAE/C,MAAI,OAAO,WAAW,YACpB,QAAO;AAKT,QAAM,WAAY,WAAmB,SAAA;AACrC,MAAI,CAAC,SACH,QAAO;AAGT,QAAM,iBAAiB,SAAS,SAAA;AAChC,MAAI,mBAAmB,UAAa,mBAAmB,KACrD,QAAO;AAGT,QAAM,eAAe,eAAe,MAAM,WAAA;AAC1C,MAAI,CAAC,aACH,QAAO;AAIT,SADqB,SAAS,aAAa,CAAA,GAAI,EAAA,KACxB;;AAGzB,IAAI,6BAAA,EACF,SAAQ,KACN,uPAAA;","names":["__extends","__assign","__rest","__decorate","__param","__esDecorate","__runInitializers","__propKey","__setFunctionName","__metadata","__awaiter","__generator","__exportStar","__values","__read","__spread","__spreadArrays","__spreadArray","__await","__asyncGenerator","__asyncDelegator","__asyncValues","__makeTemplateObject","__importStar","__importDefault","__classPrivateFieldGet","__classPrivateFieldSet","__classPrivateFieldIn","__createBinding","__addDisposableResource","__disposeResources","__rewriteRelativeImportExtension","exports","v","ownKeys","o","tslib","FunctionRegion","this","res: Response","fetchError: any","res","count: number | null","fetch","head","PostgrestClient","get","method: 'HEAD' | 'GET' | 'POST'","body: unknown | undefined","PostgresTypes","closure","global","DEFAULT_VSN","DEFAULT_TIMEOUT","CHANNEL_STATES","CHANNEL_EVENTS","fallbackTransportName","REALTIME_PRESENCE_LISTEN_EVENTS","REALTIME_POSTGRES_CHANGES_LISTEN_EVENT","REALTIME_LISTEN_TYPES","REALTIME_SUBSCRIBE_STATES","postgres_changes","_b","_a","bind","result","namespaceToPath","resolveFetch","result: Record<string, any>","params: { [k: string]: any }","_objectSpread2","contentType: string | undefined","fetch","this","downloadFn: () => Promise<Response>","shouldThrowOnError: boolean","DEFAULT_FILE_OPTIONS: FileOptions","headers: Record<string, string>","version","params: Record<string, string>","version","DEFAULT_HEADERS","version","resolveFetch","sleep","_getErrorMessage","handleError","_getRequestParams","_handleRequest","fetch","resolveFetch","version","factor","DEFAULT_HEADERS","resolveFetch","version","result","expiresAt","error","data","_a","sleep","payload","currentLevel","nextLevel","verifiedFactors","currentAuthenticationMethods","version","DEFAULT_HEADERS","DEFAULT_AUTH_OPTIONS: SupabaseAuthClientOptions","DEFAULT_REALTIME_OPTIONS: RealtimeClientOptions","resolveFetch","fetch","_objectSpread2","DEFAULT_DB_OPTIONS","DEFAULT_AUTH_OPTIONS","DEFAULT_REALTIME_OPTIONS","DEFAULT_GLOBAL_OPTIONS","result: Required<SupabaseClientOptions<SchemaName>>","supabaseUrl: string","supabaseKey: string","SupabaseStorageClient","this"]}
|