diff --git a/packages/core/auth-js/src/GoTrueAdminApi.ts b/packages/core/auth-js/src/GoTrueAdminApi.ts index 8826fd1fc..0fcce624f 100644 --- a/packages/core/auth-js/src/GoTrueAdminApi.ts +++ b/packages/core/auth-js/src/GoTrueAdminApi.ts @@ -45,6 +45,19 @@ export default class GoTrueAdminApi { } protected fetch: Fetch + /** + * Creates an admin API client that can be used to manage users and OAuth clients. + * + * @example + * ```ts + * import { GoTrueAdminApi } from '@supabase/auth-js' + * + * const admin = new GoTrueAdminApi({ + * url: 'https://xyzcompany.supabase.co/auth/v1', + * headers: { Authorization: `Bearer ${process.env.SUPABASE_SERVICE_ROLE_KEY}` }, + * }) + * ``` + */ constructor({ url = '', headers = {}, diff --git a/packages/core/auth-js/src/GoTrueClient.ts b/packages/core/auth-js/src/GoTrueClient.ts index f23bc954e..37915b581 100644 --- a/packages/core/auth-js/src/GoTrueClient.ts +++ b/packages/core/auth-js/src/GoTrueClient.ts @@ -275,6 +275,17 @@ export default class GoTrueClient { /** * Create a new client for use in the browser. + * + * @example + * ```ts + * import { GoTrueClient } from '@supabase/auth-js' + * + * const auth = new GoTrueClient({ + * url: 'https://xyzcompany.supabase.co/auth/v1', + * headers: { apikey: 'public-anon-key' }, + * storageKey: 'supabase-auth', + * }) + * ``` */ constructor(options: GoTrueClientOptions) { const settings = { ...DEFAULT_OPTIONS, ...options } diff --git a/packages/core/auth-js/src/lib/errors.ts b/packages/core/auth-js/src/lib/errors.ts index e271dad84..28270e0a8 100644 --- a/packages/core/auth-js/src/lib/errors.ts +++ b/packages/core/auth-js/src/lib/errors.ts @@ -1,6 +1,16 @@ import { WeakPasswordReasons } from './types' import { ErrorCode } from './error-codes' +/** + * Base error thrown by Supabase Auth helpers. + * + * @example + * ```ts + * import { AuthError } from '@supabase/auth-js' + * + * throw new AuthError('Unexpected auth error', 500, 'unexpected') + * ``` + */ export class AuthError extends Error { /** * Error code associated with the error. Most errors coming from @@ -27,6 +37,16 @@ export function isAuthError(error: unknown): error is AuthError { return typeof error === 'object' && error !== null && '__isAuthError' in error } +/** + * Error returned directly from the GoTrue REST API. + * + * @example + * ```ts + * import { AuthApiError } from '@supabase/auth-js' + * + * throw new AuthApiError('Invalid credentials', 400, 'invalid_credentials') + * ``` + */ export class AuthApiError extends AuthError { status: number @@ -42,6 +62,20 @@ export function isAuthApiError(error: unknown): error is AuthApiError { return isAuthError(error) && error.name === 'AuthApiError' } +/** + * Wraps non-standard errors so callers can inspect the root cause. + * + * @example + * ```ts + * import { AuthUnknownError } from '@supabase/auth-js' + * + * try { + * await someAuthCall() + * } catch (err) { + * throw new AuthUnknownError('Auth failed', err) + * } + * ``` + */ export class AuthUnknownError extends AuthError { originalError: unknown @@ -52,6 +86,16 @@ export class AuthUnknownError extends AuthError { } } +/** + * Flexible error class used to create named auth errors at runtime. + * + * @example + * ```ts + * import { CustomAuthError } from '@supabase/auth-js' + * + * throw new CustomAuthError('My custom auth error', 'MyAuthError', 400, 'custom_code') + * ``` + */ export class CustomAuthError extends AuthError { name: string status: number @@ -63,6 +107,16 @@ export class CustomAuthError extends AuthError { } } +/** + * Error thrown when an operation requires a session but none is present. + * + * @example + * ```ts + * import { AuthSessionMissingError } from '@supabase/auth-js' + * + * throw new AuthSessionMissingError() + * ``` + */ export class AuthSessionMissingError extends CustomAuthError { constructor() { super('Auth session missing!', 'AuthSessionMissingError', 400, undefined) @@ -73,18 +127,51 @@ export function isAuthSessionMissingError(error: any): error is AuthSessionMissi return isAuthError(error) && error.name === 'AuthSessionMissingError' } +/** + * Error thrown when the token response is malformed. + * + * @example + * ```ts + * import { AuthInvalidTokenResponseError } from '@supabase/auth-js' + * + * throw new AuthInvalidTokenResponseError() + * ``` + */ export class AuthInvalidTokenResponseError extends CustomAuthError { constructor() { super('Auth session or user missing', 'AuthInvalidTokenResponseError', 500, undefined) } } +/** + * Error thrown when email/password credentials are invalid. + * + * @example + * ```ts + * import { AuthInvalidCredentialsError } from '@supabase/auth-js' + * + * throw new AuthInvalidCredentialsError('Email or password is incorrect') + * ``` + */ export class AuthInvalidCredentialsError extends CustomAuthError { constructor(message: string) { super(message, 'AuthInvalidCredentialsError', 400, undefined) } } +/** + * Error thrown when implicit grant redirects contain an error. + * + * @example + * ```ts + * import { AuthImplicitGrantRedirectError } from '@supabase/auth-js' + * + * throw new AuthImplicitGrantRedirectError('OAuth redirect failed', { + * error: 'access_denied', + * code: 'oauth_error', + * }) + * ``` + */ export class AuthImplicitGrantRedirectError extends CustomAuthError { details: { error: string; code: string } | null = null constructor(message: string, details: { error: string; code: string } | null = null) { @@ -108,6 +195,16 @@ export function isAuthImplicitGrantRedirectError( return isAuthError(error) && error.name === 'AuthImplicitGrantRedirectError' } +/** + * Error thrown during PKCE code exchanges. + * + * @example + * ```ts + * import { AuthPKCEGrantCodeExchangeError } from '@supabase/auth-js' + * + * throw new AuthPKCEGrantCodeExchangeError('PKCE exchange failed') + * ``` + */ export class AuthPKCEGrantCodeExchangeError extends CustomAuthError { details: { error: string; code: string } | null = null @@ -126,6 +223,16 @@ export class AuthPKCEGrantCodeExchangeError extends CustomAuthError { } } +/** + * Error thrown when a transient fetch issue occurs. + * + * @example + * ```ts + * import { AuthRetryableFetchError } from '@supabase/auth-js' + * + * throw new AuthRetryableFetchError('Service temporarily unavailable', 503) + * ``` + */ export class AuthRetryableFetchError extends CustomAuthError { constructor(message: string, status: number) { super(message, 'AuthRetryableFetchError', status, undefined) @@ -141,6 +248,16 @@ export function isAuthRetryableFetchError(error: unknown): error is AuthRetryabl * weak. Inspect the reasons to identify what password strength rules are * inadequate. */ +/** + * Error thrown when a supplied password is considered weak. + * + * @example + * ```ts + * import { AuthWeakPasswordError } from '@supabase/auth-js' + * + * throw new AuthWeakPasswordError('Password too short', 400, ['min_length']) + * ``` + */ export class AuthWeakPasswordError extends CustomAuthError { /** * Reasons why the password is deemed weak. @@ -158,6 +275,16 @@ export function isAuthWeakPasswordError(error: unknown): error is AuthWeakPasswo return isAuthError(error) && error.name === 'AuthWeakPasswordError' } +/** + * Error thrown when a JWT cannot be verified or parsed. + * + * @example + * ```ts + * import { AuthInvalidJwtError } from '@supabase/auth-js' + * + * throw new AuthInvalidJwtError('Token signature is invalid') + * ``` + */ export class AuthInvalidJwtError extends CustomAuthError { constructor(message: string) { super(message, 'AuthInvalidJwtError', 400, 'invalid_jwt') diff --git a/packages/core/auth-js/src/lib/locks.ts b/packages/core/auth-js/src/lib/locks.ts index 6ed715a04..5dc448e2b 100644 --- a/packages/core/auth-js/src/lib/locks.ts +++ b/packages/core/auth-js/src/lib/locks.ts @@ -19,6 +19,17 @@ export const internals = { * An error thrown when a lock cannot be acquired after some amount of time. * * Use the {@link #isAcquireTimeout} property instead of checking with `instanceof`. + * + * @example + * ```ts + * import { LockAcquireTimeoutError } from '@supabase/auth-js' + * + * class CustomLockError extends LockAcquireTimeoutError { + * constructor() { + * super('Lock timed out') + * } + * } + * ``` */ export abstract class LockAcquireTimeoutError extends Error { public readonly isAcquireTimeout = true @@ -28,7 +39,27 @@ export abstract class LockAcquireTimeoutError extends Error { } } +/** + * Error thrown when the browser Navigator Lock API fails to acquire a lock. + * + * @example + * ```ts + * import { NavigatorLockAcquireTimeoutError } from '@supabase/auth-js' + * + * throw new NavigatorLockAcquireTimeoutError('Lock timed out') + * ``` + */ export class NavigatorLockAcquireTimeoutError extends LockAcquireTimeoutError {} +/** + * Error thrown when the process-level lock helper cannot acquire a lock. + * + * @example + * ```ts + * import { ProcessLockAcquireTimeoutError } from '@supabase/auth-js' + * + * throw new ProcessLockAcquireTimeoutError('Lock timed out') + * ``` + */ export class ProcessLockAcquireTimeoutError extends LockAcquireTimeoutError {} /** @@ -55,6 +86,12 @@ export class ProcessLockAcquireTimeoutError extends LockAcquireTimeoutError {} * will time out after so many milliseconds. An error is * a timeout if it has `isAcquireTimeout` set to true. * @param fn The operation to run once the lock is acquired. + * @example + * ```ts + * await navigatorLock('sync-user', 1000, async () => { + * await refreshSession() + * }) + * ``` */ export async function navigatorLock( name: string, @@ -167,6 +204,12 @@ const PROCESS_LOCKS: { [name: string]: Promise } = {} * will time out after so many milliseconds. An error is * a timeout if it has `isAcquireTimeout` set to true. * @param fn The operation to run once the lock is acquired. + * @example + * ```ts + * await processLock('migrate', 5000, async () => { + * await runMigration() + * }) + * ``` */ export async function processLock( name: string, diff --git a/packages/core/functions-js/src/FunctionsClient.ts b/packages/core/functions-js/src/FunctionsClient.ts index 203a1ad3b..8e1387c55 100644 --- a/packages/core/functions-js/src/FunctionsClient.ts +++ b/packages/core/functions-js/src/FunctionsClient.ts @@ -9,12 +9,28 @@ import { FunctionsResponse, } from './types' +/** + * Client for invoking Supabase Edge Functions. + */ export class FunctionsClient { protected url: string protected headers: Record protected region: FunctionRegion protected fetch: Fetch + /** + * Creates a new Functions client bound to an Edge Functions URL. + * + * @example + * ```ts + * import { FunctionsClient, FunctionRegion } from '@supabase/functions-js' + * + * const functions = new FunctionsClient('https://xyzcompany.supabase.co/functions/v1', { + * headers: { apikey: 'public-anon-key' }, + * region: FunctionRegion.UsEast1, + * }) + * ``` + */ constructor( url: string, { @@ -36,6 +52,10 @@ export class FunctionsClient { /** * Updates the authorization header * @param token - the new jwt token sent in the authorisation header + * @example + * ```ts + * functions.setAuth(session.access_token) + * ``` */ setAuth(token: string) { this.headers.Authorization = `Bearer ${token}` @@ -45,6 +65,12 @@ export class FunctionsClient { * Invokes a function * @param functionName - The name of the Function to invoke. * @param options - Options for invoking the Function. + * @example + * ```ts + * const { data, error } = await functions.invoke('hello-world', { + * body: { name: 'Ada' }, + * }) + * ``` */ async invoke( functionName: string, diff --git a/packages/core/functions-js/src/types.ts b/packages/core/functions-js/src/types.ts index dc5f35e29..494c3d9c6 100644 --- a/packages/core/functions-js/src/types.ts +++ b/packages/core/functions-js/src/types.ts @@ -15,6 +15,18 @@ export interface FunctionsResponseFailure { } export type FunctionsResponse = FunctionsResponseSuccess | FunctionsResponseFailure +/** + * Base error for Supabase Edge Function invocations. + * + * @example + * ```ts + * import { FunctionsError } from '@supabase/functions-js' + * + * throw new FunctionsError('Unexpected error invoking function', 'FunctionsError', { + * requestId: 'abc123', + * }) + * ``` + */ export class FunctionsError extends Error { context: any constructor(message: string, name = 'FunctionsError', context?: any) { @@ -24,18 +36,48 @@ export class FunctionsError extends Error { } } +/** + * Error thrown when the network request to an Edge Function fails. + * + * @example + * ```ts + * import { FunctionsFetchError } from '@supabase/functions-js' + * + * throw new FunctionsFetchError({ requestId: 'abc123' }) + * ``` + */ export class FunctionsFetchError extends FunctionsError { constructor(context: any) { super('Failed to send a request to the Edge Function', 'FunctionsFetchError', context) } } +/** + * Error thrown when the Supabase relay cannot reach the Edge Function. + * + * @example + * ```ts + * import { FunctionsRelayError } from '@supabase/functions-js' + * + * throw new FunctionsRelayError({ region: 'us-east-1' }) + * ``` + */ export class FunctionsRelayError extends FunctionsError { constructor(context: any) { super('Relay Error invoking the Edge Function', 'FunctionsRelayError', context) } } +/** + * Error thrown when the Edge Function returns a non-2xx status code. + * + * @example + * ```ts + * import { FunctionsHttpError } from '@supabase/functions-js' + * + * throw new FunctionsHttpError({ status: 500 }) + * ``` + */ export class FunctionsHttpError extends FunctionsError { constructor(context: any) { super('Edge Function returned a non-2xx status code', 'FunctionsHttpError', context) diff --git a/packages/core/postgrest-js/src/PostgrestBuilder.ts b/packages/core/postgrest-js/src/PostgrestBuilder.ts index f7d05bb34..3547fd409 100644 --- a/packages/core/postgrest-js/src/PostgrestBuilder.ts +++ b/packages/core/postgrest-js/src/PostgrestBuilder.ts @@ -28,6 +28,19 @@ export default abstract class PostgrestBuilder< protected fetch: Fetch protected isMaybeSingle: boolean + /** + * Creates a builder configured for a specific PostgREST request. + * + * @example + * ```ts + * import PostgrestQueryBuilder from '@supabase/postgrest-js' + * + * const builder = new PostgrestQueryBuilder( + * new URL('https://xyzcompany.supabase.co/rest/v1/users'), + * { headers: new Headers({ apikey: 'public-anon-key' }) } + * ) + * ``` + */ constructor(builder: { method: 'GET' | 'HEAD' | 'POST' | 'PATCH' | 'DELETE' url: URL diff --git a/packages/core/postgrest-js/src/PostgrestClient.ts b/packages/core/postgrest-js/src/PostgrestClient.ts index a743c65e8..a20c9cf9a 100644 --- a/packages/core/postgrest-js/src/PostgrestClient.ts +++ b/packages/core/postgrest-js/src/PostgrestClient.ts @@ -48,6 +48,15 @@ export default class PostgrestClient< * @param options.headers - Custom headers * @param options.schema - Postgres schema to switch to * @param options.fetch - Custom fetch + * @example + * ```ts + * import PostgrestClient from '@supabase/postgrest-js' + * + * const postgrest = new PostgrestClient('https://xyzcompany.supabase.co/rest/v1', { + * headers: { apikey: 'public-anon-key' }, + * schema: 'public', + * }) + * ``` */ constructor( url: string, diff --git a/packages/core/postgrest-js/src/PostgrestError.ts b/packages/core/postgrest-js/src/PostgrestError.ts index 8e0c27486..151f9943b 100644 --- a/packages/core/postgrest-js/src/PostgrestError.ts +++ b/packages/core/postgrest-js/src/PostgrestError.ts @@ -8,6 +8,19 @@ export default class PostgrestError extends Error { hint: string code: string + /** + * @example + * ```ts + * import PostgrestError from '@supabase/postgrest-js' + * + * throw new PostgrestError({ + * message: 'Row level security prevented the request', + * details: 'RLS denied the insert', + * hint: 'Check your policies', + * code: 'PGRST301', + * }) + * ``` + */ constructor(context: { message: string; details: string; hint: string; code: string }) { super(context.message) this.name = 'PostgrestError' diff --git a/packages/core/postgrest-js/src/PostgrestQueryBuilder.ts b/packages/core/postgrest-js/src/PostgrestQueryBuilder.ts index a82310078..a8c55142f 100644 --- a/packages/core/postgrest-js/src/PostgrestQueryBuilder.ts +++ b/packages/core/postgrest-js/src/PostgrestQueryBuilder.ts @@ -21,6 +21,19 @@ export default class PostgrestQueryBuilder< signal?: AbortSignal fetch?: Fetch + /** + * Creates a query builder scoped to a Postgres table or view. + * + * @example + * ```ts + * import PostgrestQueryBuilder from '@supabase/postgrest-js' + * + * const query = new PostgrestQueryBuilder( + * new URL('https://xyzcompany.supabase.co/rest/v1/users'), + * { headers: { apikey: 'public-anon-key' } } + * ) + * ``` + */ constructor( url: URL, { diff --git a/packages/core/realtime-js/src/RealtimeChannel.ts b/packages/core/realtime-js/src/RealtimeChannel.ts index 3f4e90169..4bf49e686 100644 --- a/packages/core/realtime-js/src/RealtimeChannel.ts +++ b/packages/core/realtime-js/src/RealtimeChannel.ts @@ -181,6 +181,22 @@ export default class RealtimeChannel { subTopic: string private: boolean + /** + * Creates a channel that can broadcast messages, sync presence, and listen to Postgres changes. + * + * The topic determines which realtime stream you are subscribing to. Config options let you + * enable acknowledgement for broadcasts, presence tracking, or private channels. + * + * @example + * ```ts + * import RealtimeClient from '@supabase/realtime-js' + * + * const client = new RealtimeClient('https://xyzcompany.supabase.co/realtime/v1', { + * params: { apikey: 'public-anon-key' }, + * }) + * const channel = new RealtimeChannel('realtime:public:messages', { config: {} }, client) + * ``` + */ constructor( /** Topic name can be any string. */ public topic: string, @@ -353,10 +369,20 @@ export default class RealtimeChannel { return this } + /** + * Returns the current presence state for this channel. + * + * The shape is a map keyed by presence key (for example a user id) where each entry contains the + * tracked metadata for that user. + */ presenceState(): RealtimePresenceState { return this.presence.state as RealtimePresenceState } + /** + * Sends the supplied payload to the presence tracker so other subscribers can see that this + * client is online. Use `untrack` to stop broadcasting presence for the same key. + */ async track( payload: { [key: string]: any }, opts: { [key: string]: any } = {} @@ -371,6 +397,9 @@ export default class RealtimeChannel { ) } + /** + * Removes the current presence state for this client. + */ async untrack(opts: { [key: string]: any } = {}): Promise { return await this.send( { @@ -647,6 +676,10 @@ export default class RealtimeChannel { } } + /** + * Updates the payload that will be sent the next time the channel joins (reconnects). + * Useful for rotating access tokens or updating config without re-creating the channel. + */ updateJoinPayload(payload: { [key: string]: any }): void { this.joinPush.updatePayload(payload) } diff --git a/packages/core/realtime-js/src/RealtimeClient.ts b/packages/core/realtime-js/src/RealtimeClient.ts index 226fdc5da..19db54fa6 100755 --- a/packages/core/realtime-js/src/RealtimeClient.ts +++ b/packages/core/realtime-js/src/RealtimeClient.ts @@ -55,6 +55,10 @@ const CONNECTION_TIMEOUTS = { const RECONNECT_INTERVALS = [1000, 2000, 5000, 10000] as const const DEFAULT_RECONNECT_FALLBACK = 10000 +/** + * Minimal WebSocket constructor interface that RealtimeClient can work with. + * Supply a compatible implementation (native WebSocket, `ws`, etc) when running outside the browser. + */ export interface WebSocketLikeConstructor { new (address: string | URL, subprotocols?: string | string[] | undefined): WebSocketLike // Allow additional properties that may exist on WebSocket constructors @@ -159,6 +163,15 @@ export default class RealtimeClient { * @param options.reconnectAfterMs he optional function that returns the millsec reconnect interval. Defaults to stepped backoff off. * @param options.worker Use Web Worker to set a side flow. Defaults to false. * @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. + * @example + * ```ts + * import RealtimeClient from '@supabase/realtime-js' + * + * const client = new RealtimeClient('https://xyzcompany.supabase.co/realtime/v1', { + * params: { apikey: 'public-anon-key' }, + * }) + * client.connect() + * ``` */ constructor(endPoint: string, options?: RealtimeClientOptions) { // Validate required parameters @@ -355,6 +368,13 @@ export default class RealtimeClient { return this._connectionState === 'disconnecting' } + /** + * Creates (or reuses) a {@link RealtimeChannel} for the provided topic. + * + * Topics are automatically prefixed with `realtime:` to match the Realtime service. + * If a channel with the same topic already exists it will be returned instead of creating + * a duplicate connection. + */ channel(topic: string, params: RealtimeChannelOptions = { config: {} }): RealtimeChannel { const realtimeTopic = `realtime:${topic}` const exists = this.getChannels().find((c: RealtimeChannel) => c.topic === realtimeTopic) @@ -458,6 +478,10 @@ export default class RealtimeClient { this._setAuthSafely('heartbeat') } + /** + * Sets a callback that receives lifecycle events for internal heartbeat messages. + * Useful for instrumenting connection health (e.g. sent/ok/timeout/disconnected). + */ onHeartbeat(callback: (status: HeartbeatStatus) => void): void { this.heartbeatCallback = callback } diff --git a/packages/core/realtime-js/src/RealtimePresence.ts b/packages/core/realtime-js/src/RealtimePresence.ts index 2dd29e8d9..aaa5d2156 100644 --- a/packages/core/realtime-js/src/RealtimePresence.ts +++ b/packages/core/realtime-js/src/RealtimePresence.ts @@ -72,11 +72,19 @@ export default class RealtimePresence { } /** - * Initializes the Presence. + * Creates a Presence helper that keeps the local presence state in sync with the server. * - * @param channel - The RealtimeChannel - * @param opts - The options, - * for example `{events: {state: 'state', diff: 'diff'}}` + * @param channel - The realtime channel to bind to. + * @param opts - Optional custom event names, e.g. `{ events: { state: 'state', diff: 'diff' } }`. + * + * @example + * ```ts + * const presence = new RealtimePresence(channel) + * + * channel.on('presence', ({ event, key }) => { + * console.log(`Presence ${event} on ${key}`) + * }) + * ``` */ constructor( public channel: RealtimeChannel, diff --git a/packages/core/realtime-js/src/lib/websocket-factory.ts b/packages/core/realtime-js/src/lib/websocket-factory.ts index 7aa93cfac..2289c5bec 100644 --- a/packages/core/realtime-js/src/lib/websocket-factory.ts +++ b/packages/core/realtime-js/src/lib/websocket-factory.ts @@ -7,7 +7,13 @@ export interface WebSocketLike { readonly url: string readonly protocol: string + /** + * Closes the socket, optionally providing a close code and reason. + */ close(code?: number, reason?: string): void + /** + * Sends data through the socket using the underlying implementation. + */ send(data: string | ArrayBufferLike | Blob | ArrayBufferView): void onopen: ((this: any, ev: Event) => any) | null @@ -15,7 +21,13 @@ export interface WebSocketLike { onclose: ((this: any, ev: CloseEvent) => any) | null onerror: ((this: any, ev: Event) => any) | null + /** + * Registers an event listener on the socket (compatible with browser WebSocket API). + */ addEventListener(type: string, listener: EventListener): void + /** + * Removes a previously registered event listener. + */ removeEventListener(type: string, listener: EventListener): void // Add additional properties that may exist on WebSocket implementations @@ -32,7 +44,14 @@ export interface WebSocketEnvironment { workaround?: string } +/** + * Utilities for creating WebSocket instances across runtimes. + */ export class WebSocketFactory { + /** + * Static-only utility – prevent instantiation. + */ + private constructor() {} private static detectEnvironment(): WebSocketEnvironment { if (typeof WebSocket !== 'undefined') { return { type: 'native', constructor: WebSocket } @@ -115,6 +134,15 @@ export class WebSocketFactory { } } + /** + * Returns the best available WebSocket constructor for the current runtime. + * + * @example + * ```ts + * const WS = WebSocketFactory.getWebSocketConstructor() + * const socket = new WS('wss://realtime.supabase.co/socket') + * ``` + */ public static getWebSocketConstructor(): typeof WebSocket { const env = this.detectEnvironment() if (env.constructor) { @@ -127,11 +155,29 @@ export class WebSocketFactory { throw new Error(errorMessage) } + /** + * Creates a WebSocket using the detected constructor. + * + * @example + * ```ts + * const socket = WebSocketFactory.createWebSocket('wss://realtime.supabase.co/socket') + * ``` + */ public static createWebSocket(url: string | URL, protocols?: string | string[]): WebSocketLike { const WS = this.getWebSocketConstructor() return new WS(url, protocols) } + /** + * Detects whether the runtime can establish WebSocket connections. + * + * @example + * ```ts + * if (!WebSocketFactory.isWebSocketSupported()) { + * console.warn('Falling back to long polling') + * } + * ``` + */ public static isWebSocketSupported(): boolean { try { const env = this.detectEnvironment() diff --git a/packages/core/storage-js/src/StorageClient.ts b/packages/core/storage-js/src/StorageClient.ts index 25da7fc07..10456214c 100644 --- a/packages/core/storage-js/src/StorageClient.ts +++ b/packages/core/storage-js/src/StorageClient.ts @@ -9,6 +9,19 @@ export interface StorageClientOptions { } export class StorageClient extends StorageBucketApi { + /** + * Creates a client for Storage buckets, files, analytics, and vectors. + * + * @example + * ```ts + * import { StorageClient } from '@supabase/storage-js' + * + * const storage = new StorageClient('https://xyzcompany.supabase.co/storage/v1', { + * apikey: 'public-anon-key', + * }) + * const avatars = storage.from('avatars') + * ``` + */ constructor( url: string, headers: { [key: string]: string } = {}, @@ -30,6 +43,8 @@ export class StorageClient extends StorageBucketApi { /** * Access vector storage operations. * + * **Private alpha:** This API is part of a private alpha release and may change or be removed without notice. + * * @returns A StorageVectorsClient instance configured with the current storage settings. */ get vectors(): StorageVectorsClient { diff --git a/packages/core/storage-js/src/lib/vectors/StorageVectorsClient.ts b/packages/core/storage-js/src/lib/vectors/StorageVectorsClient.ts index 9ce309b50..4f6f66582 100644 --- a/packages/core/storage-js/src/lib/vectors/StorageVectorsClient.ts +++ b/packages/core/storage-js/src/lib/vectors/StorageVectorsClient.ts @@ -13,6 +13,8 @@ import { /** * Configuration options for the Storage Vectors client + * + * **Private alpha:** Vector storage APIs are currently in private alpha and may not be accessible. */ export interface StorageVectorsClientOptions { /** @@ -30,6 +32,8 @@ export interface StorageVectorsClientOptions { * Main client for interacting with S3 Vectors API * Provides access to bucket, index, and vector data operations * + * **Private alpha:** Vector storage APIs are currently in private alpha and may not be accessible. + * * **Usage Patterns:** * * 1. **Via StorageClient (recommended for most use cases):** @@ -82,6 +86,15 @@ export interface StorageVectorsClientOptions { * ``` */ export class StorageVectorsClient extends VectorBucketApi { + /** + * Creates a StorageVectorsClient that can manage buckets, indexes, and vectors. + * + * **Private alpha:** Vector storage APIs are currently in private alpha and may not be accessible. + * + * @param url - Base URL of the Storage Vectors REST API. + * @param options.headers - Optional headers (for example `Authorization`) applied to every request. + * @param options.fetch - Optional custom `fetch` implementation for non-browser runtimes. + */ constructor(url: string, options: StorageVectorsClientOptions = {}) { super(url, options.headers || {}, options.fetch) } @@ -90,6 +103,8 @@ export class StorageVectorsClient extends VectorBucketApi { * Access operations for a specific vector bucket * Returns a scoped client for index and vector operations within the bucket * + * **Private alpha:** Vector storage APIs are currently in private alpha and may not be accessible. + * * @param vectorBucketName - Name of the vector bucket * @returns Bucket-scoped client with index and vector operations * @@ -117,10 +132,17 @@ export class StorageVectorsClient extends VectorBucketApi { /** * Scoped client for operations within a specific vector bucket * Provides index management and access to vector operations + * + * **Private alpha:** Vector storage APIs are currently in private alpha and may not be accessible. */ export class VectorBucketScope extends VectorIndexApi { private vectorBucketName: string + /** + * Creates a helper that automatically scopes all index operations to the provided bucket. + * + * **Private alpha:** Vector storage APIs are currently in private alpha and may not be accessible. + */ constructor( url: string, headers: { [key: string]: string }, @@ -135,6 +157,8 @@ export class VectorBucketScope extends VectorIndexApi { * Creates a new vector index in this bucket * Convenience method that automatically includes the bucket name * + * **Private alpha:** Vector storage APIs are currently in private alpha and may not be accessible. + * * @param options - Index configuration (vectorBucketName is automatically set) * @returns Promise with empty response on success or error * @@ -163,6 +187,8 @@ export class VectorBucketScope extends VectorIndexApi { * Lists indexes in this bucket * Convenience method that automatically includes the bucket name * + * **Private alpha:** Vector storage APIs are currently in private alpha and may not be accessible. + * * @param options - Listing options (vectorBucketName is automatically set) * @returns Promise with list of indexes or error * @@ -183,6 +209,8 @@ export class VectorBucketScope extends VectorIndexApi { * Retrieves metadata for a specific index in this bucket * Convenience method that automatically includes the bucket name * + * **Private alpha:** Vector storage APIs are currently in private alpha and may not be accessible. + * * @param indexName - Name of the index to retrieve * @returns Promise with index metadata or error * @@ -201,6 +229,8 @@ export class VectorBucketScope extends VectorIndexApi { * Deletes an index from this bucket * Convenience method that automatically includes the bucket name * + * **Private alpha:** Vector storage APIs are currently in private alpha and may not be accessible. + * * @param indexName - Name of the index to delete * @returns Promise with empty response on success or error * @@ -218,6 +248,8 @@ export class VectorBucketScope extends VectorIndexApi { * Access operations for a specific index within this bucket * Returns a scoped client for vector data operations * + * **Private alpha:** Vector storage APIs are currently in private alpha and may not be accessible. + * * @param indexName - Name of the index * @returns Index-scoped client with vector data operations * @@ -253,11 +285,18 @@ export class VectorBucketScope extends VectorIndexApi { /** * Scoped client for operations within a specific vector index * Provides vector data operations (put, get, list, query, delete) + * + * **Private alpha:** Vector storage APIs are currently in private alpha and may not be accessible. */ export class VectorIndexScope extends VectorDataApi { private vectorBucketName: string private indexName: string + /** + * Creates a helper that automatically scopes all vector operations to the provided bucket/index names. + * + * **Private alpha:** Vector storage APIs are currently in private alpha and may not be accessible. + */ constructor( url: string, headers: { [key: string]: string }, @@ -274,6 +313,8 @@ export class VectorIndexScope extends VectorDataApi { * Inserts or updates vectors in this index * Convenience method that automatically includes bucket and index names * + * **Private alpha:** Vector storage APIs are currently in private alpha and may not be accessible. + * * @param options - Vector insertion options (bucket and index names automatically set) * @returns Promise with empty response on success or error * @@ -303,6 +344,8 @@ export class VectorIndexScope extends VectorDataApi { * Retrieves vectors by keys from this index * Convenience method that automatically includes bucket and index names * + * **Private alpha:** Vector storage APIs are currently in private alpha and may not be accessible. + * * @param options - Vector retrieval options (bucket and index names automatically set) * @returns Promise with array of vectors or error * @@ -327,6 +370,8 @@ export class VectorIndexScope extends VectorDataApi { * Lists vectors in this index with pagination * Convenience method that automatically includes bucket and index names * + * **Private alpha:** Vector storage APIs are currently in private alpha and may not be accessible. + * * @param options - Listing options (bucket and index names automatically set) * @returns Promise with array of vectors and pagination token * @@ -353,6 +398,8 @@ export class VectorIndexScope extends VectorDataApi { * Queries for similar vectors in this index * Convenience method that automatically includes bucket and index names * + * **Private alpha:** Vector storage APIs are currently in private alpha and may not be accessible. + * * @param options - Query options (bucket and index names automatically set) * @returns Promise with array of similar vectors ordered by distance * @@ -382,6 +429,8 @@ export class VectorIndexScope extends VectorDataApi { * Deletes vectors by keys from this index * Convenience method that automatically includes bucket and index names * + * **Private alpha:** Vector storage APIs are currently in private alpha and may not be accessible. + * * @param options - Deletion options (bucket and index names automatically set) * @returns Promise with empty response on success or error * diff --git a/packages/core/storage-js/src/lib/vectors/VectorBucketApi.ts b/packages/core/storage-js/src/lib/vectors/VectorBucketApi.ts index c4a49d2ce..7da9d8af3 100644 --- a/packages/core/storage-js/src/lib/vectors/VectorBucketApi.ts +++ b/packages/core/storage-js/src/lib/vectors/VectorBucketApi.ts @@ -12,6 +12,8 @@ import { /** * API class for managing Vector Buckets * Provides methods for creating, reading, listing, and deleting vector buckets + * + * **Private alpha:** Vector storage APIs are currently in private alpha and may not be accessible. */ export default class VectorBucketApi { protected url: string @@ -21,9 +23,16 @@ export default class VectorBucketApi { /** * Creates a new VectorBucketApi instance + * + * **Private alpha:** Vector storage APIs are currently in private alpha and may not be accessible. * @param url - The base URL for the storage vectors API * @param headers - HTTP headers to include in requests * @param fetch - Optional custom fetch implementation + * + * @example + * ```typescript + * const client = new VectorBucketApi(url, headers) + * ``` */ constructor(url: string, headers: { [key: string]: string } = {}, fetch?: Fetch) { this.url = url.replace(/\/$/, '') @@ -35,6 +44,8 @@ export default class VectorBucketApi { * Enable throwing errors instead of returning them in the response * When enabled, failed operations will throw instead of returning { data: null, error } * + * **Private alpha:** Vector storage APIs are currently in private alpha and may not be accessible. + * * @returns This instance for method chaining * @example * ```typescript @@ -52,6 +63,8 @@ export default class VectorBucketApi { * Creates a new vector bucket * Vector buckets are containers for vector indexes and their data * + * **Private alpha:** Vector storage APIs are currently in private alpha and may not be accessible. + * * @param vectorBucketName - Unique name for the vector bucket * @returns Promise with empty response on success or error * @@ -92,6 +105,8 @@ export default class VectorBucketApi { * Retrieves metadata for a specific vector bucket * Returns bucket configuration including encryption settings and creation time * + * **Private alpha:** Vector storage APIs are currently in private alpha and may not be accessible. + * * @param vectorBucketName - Name of the vector bucket to retrieve * @returns Promise with bucket metadata or error * @@ -107,9 +122,7 @@ export default class VectorBucketApi { * } * ``` */ - async getBucket( - vectorBucketName: string - ): Promise> { + async getBucket(vectorBucketName: string): Promise> { try { const data = await post( this.fetch, @@ -133,6 +146,8 @@ export default class VectorBucketApi { * Lists vector buckets with optional filtering and pagination * Supports prefix-based filtering and paginated results * + * **Private alpha:** Vector storage APIs are currently in private alpha and may not be accessible. + * * @param options - Listing options * @param options.prefix - Filter buckets by name prefix * @param options.maxResults - Maximum results per page (default: 100) @@ -178,6 +193,8 @@ export default class VectorBucketApi { * Deletes a vector bucket * Bucket must be empty before deletion (all indexes must be removed first) * + * **Private alpha:** Vector storage APIs are currently in private alpha and may not be accessible. + * * @param vectorBucketName - Name of the vector bucket to delete * @returns Promise with empty response on success or error * diff --git a/packages/core/storage-js/src/lib/vectors/VectorDataApi.ts b/packages/core/storage-js/src/lib/vectors/VectorDataApi.ts index 99d6f33e3..e31da2407 100644 --- a/packages/core/storage-js/src/lib/vectors/VectorDataApi.ts +++ b/packages/core/storage-js/src/lib/vectors/VectorDataApi.ts @@ -17,6 +17,8 @@ import { /** * API class for managing Vector Data within Vector Indexes * Provides methods for inserting, querying, listing, and deleting vector embeddings + * + * **Private alpha:** Vector storage APIs are currently in private alpha and may not be accessible. */ export default class VectorDataApi { protected url: string @@ -24,6 +26,15 @@ export default class VectorDataApi { protected fetch: Fetch protected shouldThrowOnError = false + /** + * Creates a VectorDataApi bound to a Storage Vectors deployment. + * + * **Private alpha:** Vector storage APIs are currently in private alpha and may not be accessible. + * + * @param url - Base URL for the Storage Vectors API. + * @param headers - Default headers (for example authentication tokens). + * @param fetch - Optional custom `fetch` implementation for non-browser runtimes. + */ constructor(url: string, headers: { [key: string]: string } = {}, fetch?: Fetch) { this.url = url.replace(/\/$/, '') this.headers = { ...DEFAULT_HEADERS, ...headers } @@ -34,6 +45,8 @@ export default class VectorDataApi { * Enable throwing errors instead of returning them in the response * When enabled, failed operations will throw instead of returning { data: null, error } * + * **Private alpha:** Vector storage APIs are currently in private alpha and may not be accessible. + * * @returns This instance for method chaining * @example * ```typescript @@ -51,6 +64,8 @@ export default class VectorDataApi { * Inserts or updates vectors in batch (upsert operation) * Accepts 1-500 vectors per request. Larger batches should be split * + * **Private alpha:** Vector storage APIs are currently in private alpha and may not be accessible. + * * @param options - Vector insertion options * @param options.vectorBucketName - Name of the parent vector bucket * @param options.indexName - Name of the target index @@ -109,6 +124,8 @@ export default class VectorDataApi { * Optionally includes vector data and/or metadata in response * Additional permissions required when returning data or metadata * + * **Private alpha:** Vector storage APIs are currently in private alpha and may not be accessible. + * * @param options - Vector retrieval options * @param options.vectorBucketName - Name of the parent vector bucket * @param options.indexName - Name of the index @@ -157,6 +174,8 @@ export default class VectorDataApi { * Supports parallel scanning via segment configuration for high-throughput scenarios * Additional permissions required when returning data or metadata * + * **Private alpha:** Vector storage APIs are currently in private alpha and may not be accessible. + * * @param options - Vector listing options * @param options.vectorBucketName - Name of the parent vector bucket * @param options.indexName - Name of the index @@ -237,6 +256,8 @@ export default class VectorDataApi { * Returns top-K most similar vectors based on the configured distance metric * Supports optional metadata filtering (requires GetVectors permission) * + * **Private alpha:** Vector storage APIs are currently in private alpha and may not be accessible. + * * @param options - Query options * @param options.vectorBucketName - Name of the parent vector bucket * @param options.indexName - Name of the index @@ -295,6 +316,8 @@ export default class VectorDataApi { * Deletes vectors by their keys in batch * Accepts 1-500 keys per request * + * **Private alpha:** Vector storage APIs are currently in private alpha and may not be accessible. + * * @param options - Vector deletion options * @param options.vectorBucketName - Name of the parent vector bucket * @param options.indexName - Name of the index diff --git a/packages/core/storage-js/src/lib/vectors/VectorIndexApi.ts b/packages/core/storage-js/src/lib/vectors/VectorIndexApi.ts index 8f9bca0f6..0c629901d 100644 --- a/packages/core/storage-js/src/lib/vectors/VectorIndexApi.ts +++ b/packages/core/storage-js/src/lib/vectors/VectorIndexApi.ts @@ -14,6 +14,8 @@ import { /** * Options for creating a vector index + * + * **Private alpha:** Vector storage APIs are currently in private alpha and may not be accessible. */ export interface CreateIndexOptions { vectorBucketName: string @@ -27,6 +29,8 @@ export interface CreateIndexOptions { /** * API class for managing Vector Indexes within Vector Buckets * Provides methods for creating, reading, listing, and deleting vector indexes + * + * **Private alpha:** Vector storage APIs are currently in private alpha and may not be accessible. */ export default class VectorIndexApi { protected url: string @@ -34,6 +38,15 @@ export default class VectorIndexApi { protected fetch: Fetch protected shouldThrowOnError = false + /** + * Creates an API client for managing vector indexes. + * + * **Private alpha:** Vector storage APIs are currently in private alpha and may not be accessible. + * + * @param url - Base URL for the Storage Vectors API. + * @param headers - Default headers sent with each request. + * @param fetch - Optional custom `fetch` implementation for non-browser runtimes. + */ constructor(url: string, headers: { [key: string]: string } = {}, fetch?: Fetch) { this.url = url.replace(/\/$/, '') this.headers = { ...DEFAULT_HEADERS, ...headers } @@ -44,6 +57,8 @@ export default class VectorIndexApi { * Enable throwing errors instead of returning them in the response * When enabled, failed operations will throw instead of returning { data: null, error } * + * **Private alpha:** Vector storage APIs are currently in private alpha and may not be accessible. + * * @returns This instance for method chaining * @example * ```typescript @@ -61,6 +76,8 @@ export default class VectorIndexApi { * Creates a new vector index within a bucket * Defines the schema for vectors including dimensionality, distance metric, and metadata config * + * **Private alpha:** Vector storage APIs are currently in private alpha and may not be accessible. + * * @param options - Index configuration * @param options.vectorBucketName - Name of the parent vector bucket * @param options.indexName - Unique name for the index within the bucket @@ -111,6 +128,8 @@ export default class VectorIndexApi { * Retrieves metadata for a specific vector index * Returns index configuration including dimension, distance metric, and metadata settings * + * **Private alpha:** Vector storage APIs are currently in private alpha and may not be accessible. + * * @param vectorBucketName - Name of the parent vector bucket * @param indexName - Name of the index to retrieve * @returns Promise with index metadata or error @@ -155,6 +174,8 @@ export default class VectorIndexApi { * Lists vector indexes within a bucket with optional filtering and pagination * Supports prefix-based filtering and paginated results * + * **Private alpha:** Vector storage APIs are currently in private alpha and may not be accessible. + * * @param options - Listing options * @param options.vectorBucketName - Name of the parent vector bucket * @param options.prefix - Filter indexes by name prefix @@ -206,6 +227,8 @@ export default class VectorIndexApi { * Deletes a vector index and all its data * This operation removes the index schema and all vectors stored in the index * + * **Private alpha:** Vector storage APIs are currently in private alpha and may not be accessible. + * * @param vectorBucketName - Name of the parent vector bucket * @param indexName - Name of the index to delete * @returns Promise with empty response on success or error diff --git a/packages/core/supabase-js/src/SupabaseClient.ts b/packages/core/supabase-js/src/SupabaseClient.ts index 21bce0a62..6defb4eb2 100644 --- a/packages/core/supabase-js/src/SupabaseClient.ts +++ b/packages/core/supabase-js/src/SupabaseClient.ts @@ -101,6 +101,13 @@ export default class SupabaseClient< * @param options.storage Options passed along to the storage-js constructor. * @param options.global.fetch A custom fetch implementation. * @param options.global.headers Any additional headers to send with each network request. + * @example + * ```ts + * import { createClient } from '@supabase/supabase-js' + * + * const supabase = createClient('https://xyzcompany.supabase.co', 'public-anon-key') + * const { data } = await supabase.from('profiles').select('*') + * ``` */ constructor( protected supabaseUrl: string, diff --git a/packages/core/supabase-js/src/index.ts b/packages/core/supabase-js/src/index.ts index a15d151ed..8dd77772d 100644 --- a/packages/core/supabase-js/src/index.ts +++ b/packages/core/supabase-js/src/index.ts @@ -23,6 +23,14 @@ export type { SupabaseClientOptions, QueryResult, QueryData, QueryError } from ' /** * Creates a new Supabase Client. + * + * @example + * ```ts + * import { createClient } from '@supabase/supabase-js' + * + * const supabase = createClient('https://xyzcompany.supabase.co', 'public-anon-key') + * const { data, error } = await supabase.from('profiles').select('*') + * ``` */ export const createClient = < Database = any,