@insforge/sdk 1.0.1-refresh.2 → 1.0.1-refresh.3

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/index.d.mts CHANGED
@@ -115,7 +115,7 @@ declare class HttpClient {
115
115
  *
116
116
  * Implements the Strategy Pattern for token storage:
117
117
  * - SecureSessionStorage: In-memory tokens + httpOnly cookie refresh (XSS-resistant)
118
- * - PersistentSessionStorage: localStorage-based storage (legacy/fallback)
118
+ * - LocalSessionStorage: localStorage-based storage (legacy/fallback)
119
119
  */
120
120
 
121
121
  /**
@@ -169,7 +169,7 @@ declare class SecureSessionStorage implements SessionStorageStrategy {
169
169
  private hasAuthFlag;
170
170
  }
171
171
  /**
172
- * Persistent Session Storage Strategy
172
+ * Local Session Storage Strategy
173
173
  *
174
174
  * Stores tokens in localStorage for persistence across page reloads.
175
175
  * Used for legacy backends or environments where httpOnly cookies aren't available.
@@ -177,8 +177,8 @@ declare class SecureSessionStorage implements SessionStorageStrategy {
177
177
  * Note: This approach exposes tokens to XSS attacks. Use SecureSessionStorage
178
178
  * when possible.
179
179
  */
180
- declare class PersistentSessionStorage implements SessionStorageStrategy {
181
- readonly strategyId = "persistent";
180
+ declare class LocalSessionStorage implements SessionStorageStrategy {
181
+ readonly strategyId = "local";
182
182
  private storage;
183
183
  constructor(storage?: TokenStorage);
184
184
  saveSession(session: AuthSession): void;
@@ -192,62 +192,62 @@ declare class PersistentSessionStorage implements SessionStorageStrategy {
192
192
  }
193
193
 
194
194
  /**
195
- * Backend Capability Discovery for InsForge SDK
195
+ * Backend Configuration for InsForge SDK
196
196
  *
197
- * Discovers backend capabilities via the /api/health endpoint
198
- * and creates appropriate storage strategies based on those capabilities.
197
+ * Fetches backend configuration via the /api/health endpoint
198
+ * and creates appropriate storage strategies based on that configuration.
199
199
  */
200
200
 
201
201
  /**
202
- * Backend capabilities returned from /api/health
202
+ * Backend configuration returned from /api/health
203
203
  */
204
- interface BackendCapabilities {
204
+ interface BackendConfig {
205
205
  /** Whether backend supports secure httpOnly cookie storage for refresh tokens */
206
206
  secureSessionStorage: boolean;
207
207
  /** Whether backend supports token refresh endpoint */
208
208
  refreshTokens: boolean;
209
209
  }
210
210
  /**
211
- * Discover backend capabilities from the /api/health endpoint
211
+ * Fetch backend configuration from the /api/health endpoint
212
212
  *
213
213
  * This is the primary method for determining which features the backend supports.
214
214
  * The SDK uses this information to select appropriate storage strategies.
215
215
  *
216
216
  * @param baseUrl - The backend base URL
217
217
  * @param fetchImpl - Optional custom fetch implementation
218
- * @returns Backend capabilities object
218
+ * @returns Backend configuration object
219
219
  *
220
220
  * @example
221
221
  * ```typescript
222
- * const capabilities = await discoverCapabilities('https://api.example.com');
223
- * if (capabilities.secureSessionStorage) {
222
+ * const config = await discoverBackendConfig('https://api.example.com');
223
+ * if (config.secureSessionStorage) {
224
224
  * // Use secure storage strategy
225
225
  * }
226
226
  * ```
227
227
  */
228
- declare function discoverCapabilities(baseUrl: string, fetchImpl?: typeof fetch): Promise<BackendCapabilities>;
228
+ declare function discoverBackendConfig(baseUrl: string, fetchImpl?: typeof fetch): Promise<BackendConfig>;
229
229
  /**
230
- * Create the appropriate session storage strategy based on backend capabilities
230
+ * Create the appropriate session storage strategy based on backend configuration
231
231
  *
232
232
  * This is the factory function that implements the Strategy Pattern.
233
233
  * It selects the storage implementation based on what the backend supports.
234
234
  *
235
- * @param capabilities - Backend capabilities from discoverCapabilities()
236
- * @param storage - Optional custom storage adapter (for PersistentSessionStorage)
235
+ * @param config - Backend configuration from discoverBackendConfig()
236
+ * @param storage - Optional custom storage adapter (for LocalSessionStorage)
237
237
  * @returns Appropriate SessionStorageStrategy implementation
238
238
  *
239
239
  * @example
240
240
  * ```typescript
241
- * const capabilities = await discoverCapabilities(baseUrl);
242
- * const storage = createSessionStorage(capabilities);
241
+ * const config = await discoverBackendConfig(baseUrl);
242
+ * const storage = createSessionStorage(config);
243
243
  * storage.saveSession({ accessToken: '...', user: {...} });
244
244
  * ```
245
245
  */
246
- declare function createSessionStorage(capabilities: BackendCapabilities, storage?: TokenStorage): SessionStorageStrategy;
246
+ declare function createSessionStorage(config: BackendConfig, storage?: TokenStorage): SessionStorageStrategy;
247
247
  /**
248
- * Get default capabilities (useful for testing or manual override)
248
+ * Get default backend configuration (useful for testing or manual override)
249
249
  */
250
- declare function getDefaultCapabilities(): BackendCapabilities;
250
+ declare function getDefaultBackendConfig(): BackendConfig;
251
251
 
252
252
  /**
253
253
  * Token Manager for InsForge SDK
@@ -260,14 +260,14 @@ declare function getDefaultCapabilities(): BackendCapabilities;
260
260
  * TokenManager - Manages session storage using the Strategy Pattern
261
261
  *
262
262
  * The actual storage implementation is delegated to a SessionStorageStrategy.
263
- * By default, uses PersistentSessionStorage until a strategy is explicitly set
263
+ * By default, uses LocalSessionStorage until a strategy is explicitly set
264
264
  * via setStrategy() during client initialization.
265
265
  */
266
266
  declare class TokenManager {
267
267
  private strategy;
268
268
  /**
269
269
  * Create a new TokenManager
270
- * @param storage - Optional custom storage adapter (used for initial PersistentSessionStorage)
270
+ * @param storage - Optional custom storage adapter (used for initial LocalSessionStorage)
271
271
  */
272
272
  constructor(storage?: TokenStorage);
273
273
  /**
@@ -334,32 +334,67 @@ type ProfileData = Record<string, any> & {
334
334
  * Supports any fields that exist in the profile table
335
335
  */
336
336
  type UpdateProfileData = Partial<Record<string, any>>;
337
+ /**
338
+ * Auth state change event types
339
+ * Following Supabase pattern for consistency
340
+ */
341
+ type AuthStateChangeEvent = 'INITIAL_SESSION' | 'SIGNED_IN' | 'SIGNED_OUT' | 'TOKEN_REFRESHED';
342
+ /**
343
+ * Auth state change callback type
344
+ */
345
+ type AuthStateChangeCallback = (event: AuthStateChangeEvent, session: AuthSession | null) => void;
337
346
  declare class Auth {
338
347
  private http;
339
348
  private tokenManager;
340
349
  private database;
341
- private initPromise;
342
- constructor(http: HttpClient, tokenManager: TokenManager);
350
+ private authStateListeners;
351
+ private initializePromise;
352
+ constructor(http: HttpClient, tokenManager: TokenManager, initializePromise?: Promise<void>);
343
353
  /**
344
- * Check if an error represents an authentication failure
345
- * Used to determine appropriate HTTP status code (401 vs 500)
354
+ * Subscribe to auth state changes
355
+ *
356
+ * New subscribers will receive an INITIAL_SESSION event after initialization completes.
357
+ * This ensures no race condition where subscribers miss the initial state.
358
+ *
359
+ * @param callback - Function called when auth state changes
360
+ * @returns Unsubscribe function
361
+ *
362
+ * @example
363
+ * ```typescript
364
+ * const { data: { subscription } } = client.auth.onAuthStateChange((event, session) => {
365
+ * if (event === 'SIGNED_IN') {
366
+ * console.log('User signed in:', session?.user.email);
367
+ * } else if (event === 'SIGNED_OUT') {
368
+ * console.log('User signed out');
369
+ * }
370
+ * });
371
+ *
372
+ * // Later: unsubscribe
373
+ * subscription.unsubscribe();
374
+ * ```
346
375
  */
347
- private isAuthenticationError;
376
+ onAuthStateChange(callback: AuthStateChangeCallback): {
377
+ data: {
378
+ subscription: {
379
+ unsubscribe: () => void;
380
+ };
381
+ };
382
+ };
348
383
  /**
349
- * Set the initialization promise that auth operations should wait for
350
- * This ensures TokenManager mode is set before any auth operations
384
+ * Emit auth state change to all listeners
385
+ * @internal
351
386
  */
352
- setInitPromise(promise: Promise<void>): void;
387
+ _emitAuthStateChange(event: AuthStateChangeEvent, session: AuthSession | null): void;
353
388
  /**
354
- * Wait for initialization to complete (if set)
389
+ * Check if an error represents an authentication failure
390
+ * Used to determine appropriate HTTP status code (401 vs 500)
355
391
  */
356
- private waitForInit;
392
+ private isAuthenticationError;
357
393
  /**
358
- * Automatically detect and handle OAuth callback parameters in the URL
359
- * This runs after initialization to seamlessly complete the OAuth flow
360
- * Matches the backend's OAuth callback response (backend/src/api/routes/auth.ts:540-544)
394
+ * Detect and handle OAuth callback parameters in the URL.
395
+ * Called by client after initialization.
361
396
  */
362
- private detectAuthCallbackAsync;
397
+ detectAuthCallback(): void;
363
398
  /**
364
399
  * Sign up a new user
365
400
  */
@@ -821,50 +856,43 @@ declare class Functions {
821
856
  /**
822
857
  * Main InsForge SDK Client
823
858
  *
859
+ * The client automatically initializes in the background and emits auth state changes.
860
+ * Subscribe to `auth.onAuthStateChange` to be notified when initialization completes.
861
+ *
824
862
  * @example
825
863
  * ```typescript
826
864
  * import { InsForgeClient } from '@insforge/sdk';
827
865
  *
866
+ * // Create client - synchronous, immediately usable
828
867
  * const client = new InsForgeClient({
829
868
  * baseUrl: 'http://localhost:7130'
830
869
  * });
831
870
  *
832
- * // Wait for initialization (optional but recommended)
833
- * await client.initialize();
834
- *
835
- * // Authentication
836
- * const session = await client.auth.signUp({
837
- * email: 'user@example.com',
838
- * password: 'password123',
839
- * name: 'John Doe'
871
+ * // Subscribe to auth state changes
872
+ * client.auth.onAuthStateChange((event, session) => {
873
+ * console.log('Auth event:', event);
874
+ * if (session) {
875
+ * console.log('User:', session.user.email);
876
+ * }
840
877
  * });
841
878
  *
842
- * // Database operations
843
- * const { data, error } = await client.database
844
- * .from('posts')
845
- * .select('*')
846
- * .eq('user_id', session.user.id)
847
- * .order('created_at', { ascending: false })
848
- * .limit(10);
849
- *
850
- * // Insert data
851
- * const { data: newPost } = await client.database
852
- * .from('posts')
853
- * .insert({ title: 'Hello', content: 'World' })
854
- * .single();
855
- *
856
- * // Invoke edge functions
857
- * const { data, error } = await client.functions.invoke('my-function', {
858
- * body: { message: 'Hello from SDK' }
879
+ * // Client is immediately usable for auth operations
880
+ * const { data, error } = await client.auth.signInWithPassword({
881
+ * email: 'user@example.com',
882
+ * password: 'password123'
859
883
  * });
860
884
  * ```
861
885
  */
862
886
  declare class InsForgeClient {
863
887
  private http;
864
888
  private tokenManager;
865
- private initialized;
866
- private initializationPromise;
867
- private capabilities;
889
+ private backendConfig;
890
+ /**
891
+ * Promise that resolves when initialization is complete.
892
+ * Use this to ensure operations wait for the client to be ready.
893
+ */
894
+ private initializePromise;
895
+ private initializeResolve;
868
896
  readonly auth: Auth;
869
897
  readonly database: Database;
870
898
  readonly storage: Storage;
@@ -872,43 +900,54 @@ declare class InsForgeClient {
872
900
  readonly functions: Functions;
873
901
  constructor(config?: InsForgeConfig);
874
902
  /**
875
- * Initialize the client by discovering backend capabilities
876
- * This is called automatically on construction but can be awaited for guaranteed initialization
877
- *
878
- * @example
879
- * ```typescript
880
- * const client = new InsForgeClient({ baseUrl: 'https://api.example.com' });
881
- * await client.initialize(); // Wait for capability discovery
882
- * ```
903
+ * Internal async initialization - discovers backend config and recovers session.
904
+ * Emits INITIAL_SESSION event when complete.
905
+ * @internal
883
906
  */
884
- initialize(): Promise<void>;
907
+ private _initializeAsync;
885
908
  /**
886
- * Internal async initialization - discovers capabilities and configures storage strategy
909
+ * Wait for client initialization to complete
910
+ * @returns Promise that resolves when initialization is done
887
911
  */
888
- private initializeAsync;
912
+ waitForInitialization(): Promise<void>;
889
913
  /**
890
914
  * Get the underlying HTTP client for custom requests
891
- *
892
- * @example
893
- * ```typescript
894
- * const httpClient = client.getHttpClient();
895
- * const customData = await httpClient.get('/api/custom-endpoint');
896
- * ```
897
915
  */
898
916
  getHttpClient(): HttpClient;
899
917
  /**
900
- * Get the discovered backend capabilities
918
+ * Get the discovered backend configuration
901
919
  */
902
- getCapabilities(): BackendCapabilities | null;
920
+ getBackendConfig(): BackendConfig | null;
903
921
  /**
904
922
  * Get the current storage strategy identifier
905
923
  */
906
924
  getStorageStrategy(): string;
907
- /**
908
- * Check if the client has been fully initialized
909
- */
910
- isInitialized(): boolean;
911
925
  }
926
+ /**
927
+ * Create an InsForge client.
928
+ * This is a convenience alias for `new InsForgeClient(config)`.
929
+ *
930
+ * Note: The client initializes asynchronously in the background.
931
+ * Subscribe to `auth.onAuthStateChange` to be notified when ready.
932
+ *
933
+ * @example
934
+ * ```typescript
935
+ * import { createClient } from '@insforge/sdk';
936
+ *
937
+ * const client = createClient({
938
+ * baseUrl: 'http://localhost:7130'
939
+ * });
940
+ *
941
+ * // Subscribe to auth state changes
942
+ * client.auth.onAuthStateChange((event, session) => {
943
+ * if (event === 'INITIAL_SESSION') {
944
+ * // Initialization complete
945
+ * console.log('Ready!', session ? 'Logged in' : 'Not logged in');
946
+ * }
947
+ * });
948
+ * ```
949
+ */
950
+ declare function createClient(config?: InsForgeConfig): InsForgeClient;
912
951
 
913
952
  /**
914
953
  * @insforge/sdk - TypeScript SDK for InsForge Backend-as-a-Service
@@ -916,6 +955,4 @@ declare class InsForgeClient {
916
955
  * @packageDocumentation
917
956
  */
918
957
 
919
- declare function createClient(config: InsForgeConfig): InsForgeClient;
920
-
921
- export { AI, type ApiError, Auth, type AuthSession, type BackendCapabilities, type InsForgeConfig as ClientOptions, Database, type FunctionInvokeOptions, Functions, HttpClient, InsForgeClient, type InsForgeConfig, InsForgeError, PersistentSessionStorage, type ProfileData, SecureSessionStorage, type SessionStorageStrategy, Storage, StorageBucket, type StorageResponse, TokenManager, type TokenStorage, type UpdateProfileData, createClient, createSessionStorage, InsForgeClient as default, discoverCapabilities, getDefaultCapabilities };
958
+ export { AI, type ApiError, Auth, type AuthSession, type AuthStateChangeCallback, type AuthStateChangeEvent, type BackendConfig, type InsForgeConfig as ClientOptions, Database, type FunctionInvokeOptions, Functions, HttpClient, InsForgeClient, type InsForgeConfig, InsForgeError, LocalSessionStorage, type ProfileData, SecureSessionStorage, type SessionStorageStrategy, Storage, StorageBucket, type StorageResponse, TokenManager, type TokenStorage, type UpdateProfileData, createClient, createSessionStorage, InsForgeClient as default, discoverBackendConfig, getDefaultBackendConfig };