@insforge/sdk 1.4.2 → 1.4.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,6 +1,7 @@
1
- import { A as AuthSession, I as InsForgeConfig, e as AuthRefreshResponse, d as InsForgeError } from './types-Dk-44JJf.js';
2
- import { UserSchema, CreateUserRequest, CreateUserResponse, CreateSessionRequest, CreateSessionResponse, OAuthProvidersSchema, RefreshSessionResponse, GetProfileResponse, SendVerificationEmailRequest, VerifyEmailRequest, VerifyEmailResponse, SendResetPasswordEmailRequest, ExchangeResetPasswordTokenRequest, ExchangeResetPasswordTokenResponse, ResetPasswordResponse, GetPublicAuthConfigResponse, StorageFileSchema, ListObjectsResponseSchema, ChatCompletionRequest, ImageGenerationRequest, EmbeddingsRequest, SubscribeResponse, SocketMessage, SendRawEmailRequest, SendEmailResponse, StripeEnvironment, CreateCheckoutSessionBody, CreateCheckoutSessionResponse, CreateCustomerPortalSessionBody, CreateCustomerPortalSessionResponse, RazorpayEnvironment, CreateRazorpayOrderBody, CreateRazorpayOrderResponse, VerifyRazorpayOrderBody, VerifyRazorpayOrderResponse, CreateRazorpaySubscriptionBody, CreateRazorpaySubscriptionResponse, VerifyRazorpaySubscriptionBody, VerifyRazorpaySubscriptionResponse, CancelRazorpaySubscriptionBodyInput, CancelRazorpaySubscriptionResponse, PauseRazorpaySubscriptionResponse, ResumeRazorpaySubscriptionResponse } from '@insforge/shared-schemas';
1
+ import { A as AuthSession, I as InsForgeConfig, e as AuthRefreshResponse, d as InsForgeError } from './types-MKmYAYeg.mjs';
2
+ import { UserSchema, CreateUserRequest, CreateUserResponse, CreateSessionRequest, CreateSessionResponse, OAuthProvidersSchema, RefreshSessionResponse, GetProfileResponse, SendVerificationEmailRequest, VerifyEmailRequest, VerifyEmailResponse, SendResetPasswordEmailRequest, ExchangeResetPasswordTokenRequest, ExchangeResetPasswordTokenResponse, ResetPasswordResponse, GetPublicAuthConfigResponse, StorageFileSchema, ListObjectsResponseSchema, ChatCompletionRequest, ImageGenerationRequest, EmbeddingsRequest, SubscribeResponse, SocketMessage, PresenceMember, SendRawEmailRequest, SendEmailResponse, StripeEnvironment, CreateCheckoutSessionBody, CreateCheckoutSessionResponse, CreateCustomerPortalSessionBody, CreateCustomerPortalSessionResponse, RazorpayEnvironment, CreateRazorpayOrderBody, CreateRazorpayOrderResponse, VerifyRazorpayOrderBody, VerifyRazorpayOrderResponse, CreateRazorpaySubscriptionBody, CreateRazorpaySubscriptionResponse, VerifyRazorpaySubscriptionBody, VerifyRazorpaySubscriptionResponse, CancelRazorpaySubscriptionBodyInput, CancelRazorpaySubscriptionResponse, PauseRazorpaySubscriptionResponse, ResumeRazorpaySubscriptionResponse } from '@insforge/shared-schemas';
3
3
  import * as _supabase_postgrest_js from '@supabase/postgrest-js';
4
+ import { PostgrestClient } from '@supabase/postgrest-js';
4
5
 
5
6
  type LogFunction = (message: string, ...args: any[]) => void;
6
7
  /**
@@ -72,15 +73,22 @@ declare class Logger {
72
73
  * Memory-only token storage.
73
74
  */
74
75
 
76
+ declare const AuthChangeEvent: {
77
+ readonly SIGNED_IN: "signedIn";
78
+ readonly SIGNED_OUT: "signedOut";
79
+ readonly TOKEN_REFRESHED: "tokenRefreshed";
80
+ };
81
+ type AuthChangeEvent = (typeof AuthChangeEvent)[keyof typeof AuthChangeEvent];
82
+ type AuthStateChangeCallback = (event: AuthChangeEvent) => void;
75
83
  declare class TokenManager {
76
84
  private accessToken;
77
85
  private user;
78
- onTokenChange: (() => void) | null;
86
+ private authStateChangeCallbacks;
79
87
  constructor();
80
88
  /**
81
89
  * Save session in memory
82
90
  */
83
- saveSession(session: AuthSession): void;
91
+ saveSession(session: AuthSession, event?: AuthChangeEvent): void;
84
92
  /**
85
93
  * Get current session
86
94
  */
@@ -92,7 +100,7 @@ declare class TokenManager {
92
100
  /**
93
101
  * Set access token
94
102
  */
95
- setAccessToken(token: string): void;
103
+ setAccessToken(token: string, event?: AuthChangeEvent): void;
96
104
  /**
97
105
  * Get user
98
106
  */
@@ -105,6 +113,8 @@ declare class TokenManager {
105
113
  * Clear in-memory session
106
114
  */
107
115
  clearSession(): void;
116
+ onAuthStateChange(callback: AuthStateChangeCallback): () => void;
117
+ private notifyAuthStateChange;
108
118
  }
109
119
 
110
120
  type JsonRequestBody = Record<string, unknown> | unknown[] | null;
@@ -193,6 +203,8 @@ declare class HttpClient {
193
203
  /** Returns the current default headers including the authorization header if set. */
194
204
  getHeaders(): Record<string, string>;
195
205
  refreshAccessToken(): Promise<AuthRefreshResponse>;
206
+ /** Returns a token safe to use for a new connection handshake. */
207
+ getValidAccessToken(leewaySeconds?: number): Promise<string | null>;
196
208
  private refreshAndSaveSession;
197
209
  private clearAuthSession;
198
210
  }
@@ -221,6 +233,8 @@ declare class Auth {
221
233
  private authCallbackHandled;
222
234
  constructor(http: HttpClient, tokenManager: TokenManager, options?: AuthOptions);
223
235
  private isServerMode;
236
+ /** Subscribe to SDK authentication state changes. */
237
+ onAuthStateChange(callback: AuthStateChangeCallback): () => void;
224
238
  /**
225
239
  * Save session from API response
226
240
  * Handles token storage, CSRF token, and HTTP auth header
@@ -362,7 +376,22 @@ declare class Auth {
362
376
  */
363
377
  declare class Database {
364
378
  private postgrest;
365
- constructor(httpClient: HttpClient);
379
+ constructor(httpClient: HttpClient, defaultSchema?: string);
380
+ /**
381
+ * Select a non-default Postgres schema for the chained query. Maps to
382
+ * PostgREST's `Accept-Profile` (reads) / `Content-Profile` (writes) header.
383
+ * The schema must be exposed by the backend.
384
+ *
385
+ * @example
386
+ * const { data } = await client.database
387
+ * .schema('analytics')
388
+ * .from('events')
389
+ * .select('*');
390
+ *
391
+ * @example
392
+ * await client.database.schema('analytics').rpc('rollup', { day: '2026-01-01' });
393
+ */
394
+ schema(schemaName: string): PostgrestClient<any, any, string, any>;
366
395
  /**
367
396
  * Create a query builder for a table
368
397
  *
@@ -778,135 +807,42 @@ declare class Functions {
778
807
  type ConnectionState = 'disconnected' | 'connecting' | 'connected';
779
808
  type EventCallback<T = unknown> = (payload: T) => void;
780
809
  /**
781
- * Realtime module for subscribing to channels and handling real-time events
782
- *
783
- * @example
784
- * ```typescript
785
- * const { realtime } = client;
786
- *
787
- * // Connect to the realtime server
788
- * await realtime.connect();
789
- *
790
- * // Subscribe to a channel
791
- * const response = await realtime.subscribe('orders:123');
792
- * if (!response.ok) {
793
- * console.error('Failed to subscribe:', response.error);
794
- * }
795
- *
796
- * // Listen for specific events
797
- * realtime.on('order_updated', (payload) => {
798
- * console.log('Order updated:', payload);
799
- * });
800
- *
801
- * // Listen for connection events
802
- * realtime.on('connect', () => console.log('Connected!'));
803
- * realtime.on('connect_error', (err) => console.error('Connection failed:', err));
804
- * realtime.on('disconnect', (reason) => console.log('Disconnected:', reason));
805
- * realtime.on('error', (error) => console.error('Realtime error:', error));
806
- *
807
- * // Publish a message to a channel
808
- * await realtime.publish('orders:123', 'status_changed', { status: 'shipped' });
809
- *
810
- * // Unsubscribe and disconnect when done
811
- * realtime.unsubscribe('orders:123');
812
- * realtime.disconnect();
813
- * ```
810
+ * Socket.IO realtime client. Authentication is evaluated for every handshake,
811
+ * while an established socket remains authenticated until it disconnects.
814
812
  */
815
813
  declare class Realtime {
816
814
  private baseUrl;
817
815
  private tokenManager;
816
+ private anonKey?;
817
+ private getValidAccessToken;
818
818
  private socket;
819
819
  private connectPromise;
820
- private subscribedChannels;
820
+ private connectionAttempt;
821
+ private nextConnectionAttemptId;
822
+ private subscriptions;
821
823
  private eventListeners;
822
- private anonKey?;
823
- constructor(baseUrl: string, tokenManager: TokenManager, anonKey?: string);
824
+ constructor(baseUrl: string, tokenManager: TokenManager, anonKey?: string | undefined, getValidAccessToken?: () => Promise<string | null>);
824
825
  private notifyListeners;
825
- /**
826
- * Connect to the realtime server
827
- * @returns Promise that resolves when connected
828
- */
826
+ private getHandshakeToken;
829
827
  connect(): Promise<void>;
830
- /**
831
- * Disconnect from the realtime server
832
- */
833
828
  disconnect(): void;
834
- /**
835
- * Handle token changes (e.g., after auth refresh)
836
- * Updates socket auth so reconnects use the new token
837
- * If connected, triggers reconnect to apply new token immediately
838
- */
839
- private onTokenChange;
840
- /**
841
- * Check if connected to the realtime server
842
- */
829
+ private reconnectForAuthChange;
830
+ private handleDisconnect;
831
+ private resubscribeChannels;
832
+ private requestSubscription;
833
+ private settleSubscription;
834
+ private applyPresenceEvent;
843
835
  get isConnected(): boolean;
844
- /**
845
- * Get the current connection state
846
- */
847
836
  get connectionState(): ConnectionState;
848
- /**
849
- * Get the socket ID (if connected)
850
- */
851
837
  get socketId(): string | undefined;
852
- /**
853
- * Subscribe to a channel
854
- *
855
- * Automatically connects if not already connected.
856
- *
857
- * @param channel - Channel name (e.g., 'orders:123', 'broadcast')
858
- * @returns Promise with the subscription response
859
- */
860
838
  subscribe(channel: string): Promise<SubscribeResponse>;
861
- /**
862
- * Unsubscribe from a channel (fire-and-forget)
863
- *
864
- * @param channel - Channel name to unsubscribe from
865
- */
866
839
  unsubscribe(channel: string): void;
867
- /**
868
- * Publish a message to a channel
869
- *
870
- * @param channel - Channel name
871
- * @param event - Event name
872
- * @param payload - Message payload
873
- */
874
840
  publish<T = unknown>(channel: string, event: string, payload: T): Promise<void>;
875
- /**
876
- * Listen for events
877
- *
878
- * Reserved event names:
879
- * - 'connect' - Fired when connected to the server
880
- * - 'connect_error' - Fired when connection fails (payload: Error)
881
- * - 'disconnect' - Fired when disconnected (payload: reason string)
882
- * - 'error' - Fired when a realtime error occurs (payload: RealtimeErrorPayload)
883
- *
884
- * All other events receive a `SocketMessage` payload with metadata.
885
- *
886
- * @param event - Event name to listen for
887
- * @param callback - Callback function when event is received
888
- */
889
841
  on<T = SocketMessage>(event: string, callback: EventCallback<T>): void;
890
- /**
891
- * Remove a listener for a specific event
892
- *
893
- * @param event - Event name
894
- * @param callback - The callback function to remove
895
- */
896
842
  off<T = SocketMessage>(event: string, callback: EventCallback<T>): void;
897
- /**
898
- * Listen for an event only once, then automatically remove the listener
899
- *
900
- * @param event - Event name to listen for
901
- * @param callback - Callback function when event is received
902
- */
903
843
  once<T = SocketMessage>(event: string, callback: EventCallback<T>): void;
904
- /**
905
- * Get all currently subscribed channels
906
- *
907
- * @returns Array of channel names
908
- */
909
844
  getSubscribedChannels(): string[];
845
+ getPresenceState(channel: string): PresenceMember[];
910
846
  }
911
847
 
912
848
  /**
@@ -1014,6 +950,7 @@ declare class Payments {
1014
950
  constructor(http: HttpClient);
1015
951
  }
1016
952
 
953
+ type AccessTokenChangeEvent = typeof AuthChangeEvent.SIGNED_IN | typeof AuthChangeEvent.TOKEN_REFRESHED;
1017
954
  /**
1018
955
  * Main InsForge SDK Client
1019
956
  *
@@ -1083,27 +1020,30 @@ declare class InsForgeClient {
1083
1020
  /**
1084
1021
  * Set the access token used by every SDK surface. Updates both the HTTP
1085
1022
  * client (database / storage / functions / AI / emails) and the realtime
1086
- * token manager (which fires `onTokenChange` to reconnect the WebSocket
1087
- * with the new bearer). Pass `null` to clear.
1023
+ * token manager. Pass `null` to sign out. By default a token replacement is
1024
+ * treated as a sign-in boundary and reconnects realtime. Pass
1025
+ * `AuthChangeEvent.TOKEN_REFRESHED` for a same-identity refresh to preserve a live socket; the
1026
+ * refreshed token is then used at the next handshake.
1088
1027
  *
1089
1028
  * Use this when an external auth provider (Better Auth, Clerk, Auth0,
1090
1029
  * WorkOS, Kinde, Stytch, …) issues the JWT and you need to keep the
1091
1030
  * long-lived InsForge client in sync. Without this, you'd have to call
1092
1031
  * `client.getHttpClient().setAuthToken(token)` AND reach into the private
1093
- * `client.realtime.tokenManager.setAccessToken(token)` separately
1094
- * forgetting the second one silently breaks realtime auth.
1032
+ * realtime token manager separately.
1095
1033
  *
1096
1034
  * @example
1097
1035
  * ```typescript
1036
+ * import { AuthChangeEvent } from '@insforge/sdk';
1037
+ *
1098
1038
  * // Refresh a third-party-issued JWT periodically
1099
1039
  * const { token } = await fetch('/api/insforge-token').then((r) => r.json());
1100
- * client.setAccessToken(token);
1040
+ * client.setAccessToken(token, AuthChangeEvent.TOKEN_REFRESHED);
1101
1041
  *
1102
1042
  * // Sign-out
1103
1043
  * client.setAccessToken(null);
1104
1044
  * ```
1105
1045
  */
1106
- setAccessToken(token: string | null): void;
1046
+ setAccessToken(token: string | null, event?: AccessTokenChangeEvent): void;
1107
1047
  }
1108
1048
 
1109
- export { Auth as A, type ConnectionState as C, Database as D, Emails as E, Functions as F, HttpClient as H, InsForgeClient as I, Logger as L, Payments as P, Realtime as R, Storage as S, TokenManager as T, StorageBucket as a, type StorageResponse as b, AI as c, type FunctionInvokeOptions as d, type PaymentsResponse as e, type EventCallback as f };
1049
+ export { type AccessTokenChangeEvent as A, type ConnectionState as C, Database as D, Emails as E, Functions as F, HttpClient as H, InsForgeClient as I, Logger as L, Payments as P, Realtime as R, Storage as S, Auth as a, StorageBucket as b, type StorageResponse as c, AI as d, type FunctionInvokeOptions as e, type PaymentsResponse as f, type EventCallback as g, AuthChangeEvent as h, type AuthStateChangeCallback as i };
@@ -1,6 +1,7 @@
1
- import { A as AuthSession, I as InsForgeConfig, e as AuthRefreshResponse, d as InsForgeError } from './types-Dk-44JJf.mjs';
2
- import { UserSchema, CreateUserRequest, CreateUserResponse, CreateSessionRequest, CreateSessionResponse, OAuthProvidersSchema, RefreshSessionResponse, GetProfileResponse, SendVerificationEmailRequest, VerifyEmailRequest, VerifyEmailResponse, SendResetPasswordEmailRequest, ExchangeResetPasswordTokenRequest, ExchangeResetPasswordTokenResponse, ResetPasswordResponse, GetPublicAuthConfigResponse, StorageFileSchema, ListObjectsResponseSchema, ChatCompletionRequest, ImageGenerationRequest, EmbeddingsRequest, SubscribeResponse, SocketMessage, SendRawEmailRequest, SendEmailResponse, StripeEnvironment, CreateCheckoutSessionBody, CreateCheckoutSessionResponse, CreateCustomerPortalSessionBody, CreateCustomerPortalSessionResponse, RazorpayEnvironment, CreateRazorpayOrderBody, CreateRazorpayOrderResponse, VerifyRazorpayOrderBody, VerifyRazorpayOrderResponse, CreateRazorpaySubscriptionBody, CreateRazorpaySubscriptionResponse, VerifyRazorpaySubscriptionBody, VerifyRazorpaySubscriptionResponse, CancelRazorpaySubscriptionBodyInput, CancelRazorpaySubscriptionResponse, PauseRazorpaySubscriptionResponse, ResumeRazorpaySubscriptionResponse } from '@insforge/shared-schemas';
1
+ import { A as AuthSession, I as InsForgeConfig, e as AuthRefreshResponse, d as InsForgeError } from './types-MKmYAYeg.js';
2
+ import { UserSchema, CreateUserRequest, CreateUserResponse, CreateSessionRequest, CreateSessionResponse, OAuthProvidersSchema, RefreshSessionResponse, GetProfileResponse, SendVerificationEmailRequest, VerifyEmailRequest, VerifyEmailResponse, SendResetPasswordEmailRequest, ExchangeResetPasswordTokenRequest, ExchangeResetPasswordTokenResponse, ResetPasswordResponse, GetPublicAuthConfigResponse, StorageFileSchema, ListObjectsResponseSchema, ChatCompletionRequest, ImageGenerationRequest, EmbeddingsRequest, SubscribeResponse, SocketMessage, PresenceMember, SendRawEmailRequest, SendEmailResponse, StripeEnvironment, CreateCheckoutSessionBody, CreateCheckoutSessionResponse, CreateCustomerPortalSessionBody, CreateCustomerPortalSessionResponse, RazorpayEnvironment, CreateRazorpayOrderBody, CreateRazorpayOrderResponse, VerifyRazorpayOrderBody, VerifyRazorpayOrderResponse, CreateRazorpaySubscriptionBody, CreateRazorpaySubscriptionResponse, VerifyRazorpaySubscriptionBody, VerifyRazorpaySubscriptionResponse, CancelRazorpaySubscriptionBodyInput, CancelRazorpaySubscriptionResponse, PauseRazorpaySubscriptionResponse, ResumeRazorpaySubscriptionResponse } from '@insforge/shared-schemas';
3
3
  import * as _supabase_postgrest_js from '@supabase/postgrest-js';
4
+ import { PostgrestClient } from '@supabase/postgrest-js';
4
5
 
5
6
  type LogFunction = (message: string, ...args: any[]) => void;
6
7
  /**
@@ -72,15 +73,22 @@ declare class Logger {
72
73
  * Memory-only token storage.
73
74
  */
74
75
 
76
+ declare const AuthChangeEvent: {
77
+ readonly SIGNED_IN: "signedIn";
78
+ readonly SIGNED_OUT: "signedOut";
79
+ readonly TOKEN_REFRESHED: "tokenRefreshed";
80
+ };
81
+ type AuthChangeEvent = (typeof AuthChangeEvent)[keyof typeof AuthChangeEvent];
82
+ type AuthStateChangeCallback = (event: AuthChangeEvent) => void;
75
83
  declare class TokenManager {
76
84
  private accessToken;
77
85
  private user;
78
- onTokenChange: (() => void) | null;
86
+ private authStateChangeCallbacks;
79
87
  constructor();
80
88
  /**
81
89
  * Save session in memory
82
90
  */
83
- saveSession(session: AuthSession): void;
91
+ saveSession(session: AuthSession, event?: AuthChangeEvent): void;
84
92
  /**
85
93
  * Get current session
86
94
  */
@@ -92,7 +100,7 @@ declare class TokenManager {
92
100
  /**
93
101
  * Set access token
94
102
  */
95
- setAccessToken(token: string): void;
103
+ setAccessToken(token: string, event?: AuthChangeEvent): void;
96
104
  /**
97
105
  * Get user
98
106
  */
@@ -105,6 +113,8 @@ declare class TokenManager {
105
113
  * Clear in-memory session
106
114
  */
107
115
  clearSession(): void;
116
+ onAuthStateChange(callback: AuthStateChangeCallback): () => void;
117
+ private notifyAuthStateChange;
108
118
  }
109
119
 
110
120
  type JsonRequestBody = Record<string, unknown> | unknown[] | null;
@@ -193,6 +203,8 @@ declare class HttpClient {
193
203
  /** Returns the current default headers including the authorization header if set. */
194
204
  getHeaders(): Record<string, string>;
195
205
  refreshAccessToken(): Promise<AuthRefreshResponse>;
206
+ /** Returns a token safe to use for a new connection handshake. */
207
+ getValidAccessToken(leewaySeconds?: number): Promise<string | null>;
196
208
  private refreshAndSaveSession;
197
209
  private clearAuthSession;
198
210
  }
@@ -221,6 +233,8 @@ declare class Auth {
221
233
  private authCallbackHandled;
222
234
  constructor(http: HttpClient, tokenManager: TokenManager, options?: AuthOptions);
223
235
  private isServerMode;
236
+ /** Subscribe to SDK authentication state changes. */
237
+ onAuthStateChange(callback: AuthStateChangeCallback): () => void;
224
238
  /**
225
239
  * Save session from API response
226
240
  * Handles token storage, CSRF token, and HTTP auth header
@@ -362,7 +376,22 @@ declare class Auth {
362
376
  */
363
377
  declare class Database {
364
378
  private postgrest;
365
- constructor(httpClient: HttpClient);
379
+ constructor(httpClient: HttpClient, defaultSchema?: string);
380
+ /**
381
+ * Select a non-default Postgres schema for the chained query. Maps to
382
+ * PostgREST's `Accept-Profile` (reads) / `Content-Profile` (writes) header.
383
+ * The schema must be exposed by the backend.
384
+ *
385
+ * @example
386
+ * const { data } = await client.database
387
+ * .schema('analytics')
388
+ * .from('events')
389
+ * .select('*');
390
+ *
391
+ * @example
392
+ * await client.database.schema('analytics').rpc('rollup', { day: '2026-01-01' });
393
+ */
394
+ schema(schemaName: string): PostgrestClient<any, any, string, any>;
366
395
  /**
367
396
  * Create a query builder for a table
368
397
  *
@@ -778,135 +807,42 @@ declare class Functions {
778
807
  type ConnectionState = 'disconnected' | 'connecting' | 'connected';
779
808
  type EventCallback<T = unknown> = (payload: T) => void;
780
809
  /**
781
- * Realtime module for subscribing to channels and handling real-time events
782
- *
783
- * @example
784
- * ```typescript
785
- * const { realtime } = client;
786
- *
787
- * // Connect to the realtime server
788
- * await realtime.connect();
789
- *
790
- * // Subscribe to a channel
791
- * const response = await realtime.subscribe('orders:123');
792
- * if (!response.ok) {
793
- * console.error('Failed to subscribe:', response.error);
794
- * }
795
- *
796
- * // Listen for specific events
797
- * realtime.on('order_updated', (payload) => {
798
- * console.log('Order updated:', payload);
799
- * });
800
- *
801
- * // Listen for connection events
802
- * realtime.on('connect', () => console.log('Connected!'));
803
- * realtime.on('connect_error', (err) => console.error('Connection failed:', err));
804
- * realtime.on('disconnect', (reason) => console.log('Disconnected:', reason));
805
- * realtime.on('error', (error) => console.error('Realtime error:', error));
806
- *
807
- * // Publish a message to a channel
808
- * await realtime.publish('orders:123', 'status_changed', { status: 'shipped' });
809
- *
810
- * // Unsubscribe and disconnect when done
811
- * realtime.unsubscribe('orders:123');
812
- * realtime.disconnect();
813
- * ```
810
+ * Socket.IO realtime client. Authentication is evaluated for every handshake,
811
+ * while an established socket remains authenticated until it disconnects.
814
812
  */
815
813
  declare class Realtime {
816
814
  private baseUrl;
817
815
  private tokenManager;
816
+ private anonKey?;
817
+ private getValidAccessToken;
818
818
  private socket;
819
819
  private connectPromise;
820
- private subscribedChannels;
820
+ private connectionAttempt;
821
+ private nextConnectionAttemptId;
822
+ private subscriptions;
821
823
  private eventListeners;
822
- private anonKey?;
823
- constructor(baseUrl: string, tokenManager: TokenManager, anonKey?: string);
824
+ constructor(baseUrl: string, tokenManager: TokenManager, anonKey?: string | undefined, getValidAccessToken?: () => Promise<string | null>);
824
825
  private notifyListeners;
825
- /**
826
- * Connect to the realtime server
827
- * @returns Promise that resolves when connected
828
- */
826
+ private getHandshakeToken;
829
827
  connect(): Promise<void>;
830
- /**
831
- * Disconnect from the realtime server
832
- */
833
828
  disconnect(): void;
834
- /**
835
- * Handle token changes (e.g., after auth refresh)
836
- * Updates socket auth so reconnects use the new token
837
- * If connected, triggers reconnect to apply new token immediately
838
- */
839
- private onTokenChange;
840
- /**
841
- * Check if connected to the realtime server
842
- */
829
+ private reconnectForAuthChange;
830
+ private handleDisconnect;
831
+ private resubscribeChannels;
832
+ private requestSubscription;
833
+ private settleSubscription;
834
+ private applyPresenceEvent;
843
835
  get isConnected(): boolean;
844
- /**
845
- * Get the current connection state
846
- */
847
836
  get connectionState(): ConnectionState;
848
- /**
849
- * Get the socket ID (if connected)
850
- */
851
837
  get socketId(): string | undefined;
852
- /**
853
- * Subscribe to a channel
854
- *
855
- * Automatically connects if not already connected.
856
- *
857
- * @param channel - Channel name (e.g., 'orders:123', 'broadcast')
858
- * @returns Promise with the subscription response
859
- */
860
838
  subscribe(channel: string): Promise<SubscribeResponse>;
861
- /**
862
- * Unsubscribe from a channel (fire-and-forget)
863
- *
864
- * @param channel - Channel name to unsubscribe from
865
- */
866
839
  unsubscribe(channel: string): void;
867
- /**
868
- * Publish a message to a channel
869
- *
870
- * @param channel - Channel name
871
- * @param event - Event name
872
- * @param payload - Message payload
873
- */
874
840
  publish<T = unknown>(channel: string, event: string, payload: T): Promise<void>;
875
- /**
876
- * Listen for events
877
- *
878
- * Reserved event names:
879
- * - 'connect' - Fired when connected to the server
880
- * - 'connect_error' - Fired when connection fails (payload: Error)
881
- * - 'disconnect' - Fired when disconnected (payload: reason string)
882
- * - 'error' - Fired when a realtime error occurs (payload: RealtimeErrorPayload)
883
- *
884
- * All other events receive a `SocketMessage` payload with metadata.
885
- *
886
- * @param event - Event name to listen for
887
- * @param callback - Callback function when event is received
888
- */
889
841
  on<T = SocketMessage>(event: string, callback: EventCallback<T>): void;
890
- /**
891
- * Remove a listener for a specific event
892
- *
893
- * @param event - Event name
894
- * @param callback - The callback function to remove
895
- */
896
842
  off<T = SocketMessage>(event: string, callback: EventCallback<T>): void;
897
- /**
898
- * Listen for an event only once, then automatically remove the listener
899
- *
900
- * @param event - Event name to listen for
901
- * @param callback - Callback function when event is received
902
- */
903
843
  once<T = SocketMessage>(event: string, callback: EventCallback<T>): void;
904
- /**
905
- * Get all currently subscribed channels
906
- *
907
- * @returns Array of channel names
908
- */
909
844
  getSubscribedChannels(): string[];
845
+ getPresenceState(channel: string): PresenceMember[];
910
846
  }
911
847
 
912
848
  /**
@@ -1014,6 +950,7 @@ declare class Payments {
1014
950
  constructor(http: HttpClient);
1015
951
  }
1016
952
 
953
+ type AccessTokenChangeEvent = typeof AuthChangeEvent.SIGNED_IN | typeof AuthChangeEvent.TOKEN_REFRESHED;
1017
954
  /**
1018
955
  * Main InsForge SDK Client
1019
956
  *
@@ -1083,27 +1020,30 @@ declare class InsForgeClient {
1083
1020
  /**
1084
1021
  * Set the access token used by every SDK surface. Updates both the HTTP
1085
1022
  * client (database / storage / functions / AI / emails) and the realtime
1086
- * token manager (which fires `onTokenChange` to reconnect the WebSocket
1087
- * with the new bearer). Pass `null` to clear.
1023
+ * token manager. Pass `null` to sign out. By default a token replacement is
1024
+ * treated as a sign-in boundary and reconnects realtime. Pass
1025
+ * `AuthChangeEvent.TOKEN_REFRESHED` for a same-identity refresh to preserve a live socket; the
1026
+ * refreshed token is then used at the next handshake.
1088
1027
  *
1089
1028
  * Use this when an external auth provider (Better Auth, Clerk, Auth0,
1090
1029
  * WorkOS, Kinde, Stytch, …) issues the JWT and you need to keep the
1091
1030
  * long-lived InsForge client in sync. Without this, you'd have to call
1092
1031
  * `client.getHttpClient().setAuthToken(token)` AND reach into the private
1093
- * `client.realtime.tokenManager.setAccessToken(token)` separately
1094
- * forgetting the second one silently breaks realtime auth.
1032
+ * realtime token manager separately.
1095
1033
  *
1096
1034
  * @example
1097
1035
  * ```typescript
1036
+ * import { AuthChangeEvent } from '@insforge/sdk';
1037
+ *
1098
1038
  * // Refresh a third-party-issued JWT periodically
1099
1039
  * const { token } = await fetch('/api/insforge-token').then((r) => r.json());
1100
- * client.setAccessToken(token);
1040
+ * client.setAccessToken(token, AuthChangeEvent.TOKEN_REFRESHED);
1101
1041
  *
1102
1042
  * // Sign-out
1103
1043
  * client.setAccessToken(null);
1104
1044
  * ```
1105
1045
  */
1106
- setAccessToken(token: string | null): void;
1046
+ setAccessToken(token: string | null, event?: AccessTokenChangeEvent): void;
1107
1047
  }
1108
1048
 
1109
- export { Auth as A, type ConnectionState as C, Database as D, Emails as E, Functions as F, HttpClient as H, InsForgeClient as I, Logger as L, Payments as P, Realtime as R, Storage as S, TokenManager as T, StorageBucket as a, type StorageResponse as b, AI as c, type FunctionInvokeOptions as d, type PaymentsResponse as e, type EventCallback as f };
1049
+ export { type AccessTokenChangeEvent as A, type ConnectionState as C, Database as D, Emails as E, Functions as F, HttpClient as H, InsForgeClient as I, Logger as L, Payments as P, Realtime as R, Storage as S, Auth as a, StorageBucket as b, type StorageResponse as c, AI as d, type FunctionInvokeOptions as e, type PaymentsResponse as f, type EventCallback as g, AuthChangeEvent as h, type AuthStateChangeCallback as i };
package/dist/index.d.mts CHANGED
@@ -1,7 +1,7 @@
1
- import { I as InsForgeClient } from './client-C-qBRoea.mjs';
2
- export { c as AI, A as Auth, C as ConnectionState, D as Database, E as Emails, f as EventCallback, d as FunctionInvokeOptions, F as Functions, H as HttpClient, L as Logger, P as Payments, e as PaymentsResponse, R as Realtime, S as Storage, a as StorageBucket, b as StorageResponse, T as TokenManager } from './client-C-qBRoea.mjs';
3
- import { I as InsForgeConfig, a as InsForgeAdminConfig } from './types-Dk-44JJf.mjs';
4
- export { b as ApiError, A as AuthSession, d as InsForgeError, c as InsForgeErrorCode } from './types-Dk-44JJf.mjs';
1
+ import { I as InsForgeClient } from './client-BZyLCjO1.mjs';
2
+ export { d as AI, A as AccessTokenChangeEvent, a as Auth, h as AuthChangeEvent, i as AuthStateChangeCallback, C as ConnectionState, D as Database, E as Emails, g as EventCallback, e as FunctionInvokeOptions, F as Functions, H as HttpClient, L as Logger, P as Payments, f as PaymentsResponse, R as Realtime, S as Storage, b as StorageBucket, c as StorageResponse } from './client-BZyLCjO1.mjs';
3
+ import { I as InsForgeConfig, a as InsForgeAdminConfig } from './types-MKmYAYeg.mjs';
4
+ export { b as ApiError, A as AuthSession, d as InsForgeError, c as InsForgeErrorCode } from './types-MKmYAYeg.mjs';
5
5
  export { AuthErrorResponse, CreateSessionRequest, CreateUserRequest, RealtimeErrorPayload, SendRawEmailRequest as SendEmailOptions, SendEmailResponse, SocketMessage, SubscribeResponse, UserSchema } from '@insforge/shared-schemas';
6
6
  import '@supabase/postgrest-js';
7
7
 
package/dist/index.d.ts CHANGED
@@ -1,7 +1,7 @@
1
- import { I as InsForgeClient } from './client-BR9o-WUm.js';
2
- export { c as AI, A as Auth, C as ConnectionState, D as Database, E as Emails, f as EventCallback, d as FunctionInvokeOptions, F as Functions, H as HttpClient, L as Logger, P as Payments, e as PaymentsResponse, R as Realtime, S as Storage, a as StorageBucket, b as StorageResponse, T as TokenManager } from './client-BR9o-WUm.js';
3
- import { I as InsForgeConfig, a as InsForgeAdminConfig } from './types-Dk-44JJf.js';
4
- export { b as ApiError, A as AuthSession, d as InsForgeError, c as InsForgeErrorCode } from './types-Dk-44JJf.js';
1
+ import { I as InsForgeClient } from './client-Dh7GOydb.js';
2
+ export { d as AI, A as AccessTokenChangeEvent, a as Auth, h as AuthChangeEvent, i as AuthStateChangeCallback, C as ConnectionState, D as Database, E as Emails, g as EventCallback, e as FunctionInvokeOptions, F as Functions, H as HttpClient, L as Logger, P as Payments, f as PaymentsResponse, R as Realtime, S as Storage, b as StorageBucket, c as StorageResponse } from './client-Dh7GOydb.js';
3
+ import { I as InsForgeConfig, a as InsForgeAdminConfig } from './types-MKmYAYeg.js';
4
+ export { b as ApiError, A as AuthSession, d as InsForgeError, c as InsForgeErrorCode } from './types-MKmYAYeg.js';
5
5
  export { AuthErrorResponse, CreateSessionRequest, CreateUserRequest, RealtimeErrorPayload, SendRawEmailRequest as SendEmailOptions, SendEmailResponse, SocketMessage, SubscribeResponse, UserSchema } from '@insforge/shared-schemas';
6
6
  import '@supabase/postgrest-js';
7
7