@insforge/sdk 1.2.3 → 1.2.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.
@@ -0,0 +1,1049 @@
1
+ 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 } from '@insforge/shared-schemas';
2
+ export { AuthErrorResponse, CreateSessionRequest, CreateUserRequest, RealtimeErrorPayload, SendRawEmailRequest as SendEmailOptions, SendEmailResponse, SocketMessage, SubscribeResponse, UserSchema } from '@insforge/shared-schemas';
3
+ import * as _supabase_postgrest_js from '@supabase/postgrest-js';
4
+
5
+ /**
6
+ * InsForge SDK Types - only SDK-specific types here
7
+ * Use @insforge/shared-schemas directly for API types
8
+ */
9
+
10
+ interface InsForgeConfig {
11
+ /**
12
+ * The base URL of the InsForge backend API
13
+ * @default "http://localhost:7130"
14
+ */
15
+ baseUrl?: string;
16
+ /**
17
+ * Anonymous API key (optional)
18
+ * Used for public/unauthenticated requests when no user token is set
19
+ */
20
+ anonKey?: string;
21
+ /**
22
+ * Edge Function Token (optional)
23
+ * Use this when running in edge functions/serverless with a user's JWT token
24
+ * This token will be used for all authenticated requests
25
+ */
26
+ edgeFunctionToken?: string;
27
+ /**
28
+ * Direct URL to Deno Subhosting functions (optional)
29
+ * When provided, SDK will try this URL first for function invocations.
30
+ * Falls back to proxy URL if subhosting returns 404.
31
+ * @example "https://{appKey}.functions.insforge.app"
32
+ */
33
+ functionsUrl?: string;
34
+ /**
35
+ * Custom fetch implementation (useful for Node.js environments)
36
+ */
37
+ fetch?: typeof fetch;
38
+ /**
39
+ * Enable server-side auth mode (SSR/Node runtime)
40
+ * In this mode auth endpoints use `client_type=mobile` and refresh_token body flow.
41
+ * @default false
42
+ */
43
+ isServerMode?: boolean;
44
+ /**
45
+ * Custom headers to include with every request
46
+ */
47
+ headers?: Record<string, string>;
48
+ /**
49
+ * Enable debug logging for HTTP requests and responses.
50
+ * When true, request/response details are logged to the console.
51
+ * Can also be a custom log function for advanced use cases.
52
+ * @default false
53
+ */
54
+ debug?: boolean | ((message: string, ...args: any[]) => void);
55
+ /**
56
+ * Request timeout in milliseconds.
57
+ * Requests that exceed this duration will be aborted.
58
+ * Set to 0 to disable timeout.
59
+ * @default 30000
60
+ */
61
+ timeout?: number;
62
+ /**
63
+ * Maximum number of retry attempts for failed requests.
64
+ * Retries are triggered on network errors and server errors (5xx).
65
+ * Client errors (4xx) are never retried.
66
+ * Set to 0 to disable retries.
67
+ * @default 3
68
+ */
69
+ retryCount?: number;
70
+ /**
71
+ * Initial delay in milliseconds before the first retry.
72
+ * The delay doubles with each subsequent attempt (exponential backoff)
73
+ * with ±15% jitter to prevent thundering herd.
74
+ * @default 500
75
+ */
76
+ retryDelay?: number;
77
+ /**
78
+ * Automatically refresh the access token when a request fails with 401 INVALID_TOKEN.
79
+ * When true, the SDK will attempt a token refresh and retry the original request.
80
+ * @default true
81
+ */
82
+ autoRefreshToken?: boolean;
83
+ }
84
+ interface AuthSession {
85
+ user: UserSchema;
86
+ accessToken: string;
87
+ expiresAt?: Date;
88
+ }
89
+ interface AuthRefreshResponse {
90
+ user: UserSchema;
91
+ accessToken: string;
92
+ csrfToken?: string;
93
+ refreshToken?: string;
94
+ }
95
+ interface ApiError {
96
+ error: string;
97
+ message: string;
98
+ statusCode: number;
99
+ nextActions?: string;
100
+ }
101
+ declare class InsForgeError extends Error {
102
+ statusCode: number;
103
+ error: string;
104
+ nextActions?: string;
105
+ constructor(message: string, statusCode: number, error: string, nextActions?: string);
106
+ static fromApiError(apiError: ApiError): InsForgeError;
107
+ }
108
+
109
+ type LogFunction = (message: string, ...args: any[]) => void;
110
+ /**
111
+ * Debug logger for the InsForge SDK.
112
+ * Logs HTTP request/response details with automatic redaction of sensitive data.
113
+ *
114
+ * @example
115
+ * ```typescript
116
+ * // Enable via SDK config
117
+ * const client = new InsForgeClient({ debug: true });
118
+ *
119
+ * // Or with a custom log function
120
+ * const client = new InsForgeClient({
121
+ * debug: (msg) => myLogger.info(msg)
122
+ * });
123
+ * ```
124
+ */
125
+ declare class Logger {
126
+ /** Whether debug logging is currently enabled */
127
+ enabled: boolean;
128
+ private customLog;
129
+ /**
130
+ * Creates a new Logger instance.
131
+ * @param debug - Set to true to enable console logging, or pass a custom log function
132
+ */
133
+ constructor(debug?: boolean | LogFunction);
134
+ /**
135
+ * Logs a debug message at the info level.
136
+ * @param message - The message to log
137
+ * @param args - Additional arguments to pass to the log function
138
+ */
139
+ log(message: string, ...args: any[]): void;
140
+ /**
141
+ * Logs a debug message at the warning level.
142
+ * @param message - The message to log
143
+ * @param args - Additional arguments to pass to the log function
144
+ */
145
+ warn(message: string, ...args: any[]): void;
146
+ /**
147
+ * Logs a debug message at the error level.
148
+ * @param message - The message to log
149
+ * @param args - Additional arguments to pass to the log function
150
+ */
151
+ error(message: string, ...args: any[]): void;
152
+ /**
153
+ * Logs an outgoing HTTP request with method, URL, headers, and body.
154
+ * Sensitive headers and body fields are automatically redacted.
155
+ * @param method - HTTP method (GET, POST, etc.)
156
+ * @param url - The full request URL
157
+ * @param headers - Request headers (sensitive values will be redacted)
158
+ * @param body - Request body (sensitive fields will be masked)
159
+ */
160
+ logRequest(method: string, url: string, headers?: Record<string, string>, body?: any): void;
161
+ /**
162
+ * Logs an incoming HTTP response with method, URL, status, duration, and body.
163
+ * Error responses (4xx/5xx) are logged at the error level.
164
+ * @param method - HTTP method (GET, POST, etc.)
165
+ * @param url - The full request URL
166
+ * @param status - HTTP response status code
167
+ * @param durationMs - Request duration in milliseconds
168
+ * @param body - Response body (sensitive fields will be masked, large bodies truncated)
169
+ */
170
+ logResponse(method: string, url: string, status: number, durationMs: number, body?: any): void;
171
+ }
172
+
173
+ /**
174
+ * Token Manager for InsForge SDK
175
+ *
176
+ * Memory-only token storage.
177
+ */
178
+
179
+ declare class TokenManager {
180
+ private accessToken;
181
+ private user;
182
+ onTokenChange: (() => void) | null;
183
+ constructor();
184
+ /**
185
+ * Save session in memory
186
+ */
187
+ saveSession(session: AuthSession): void;
188
+ /**
189
+ * Get current session
190
+ */
191
+ getSession(): AuthSession | null;
192
+ /**
193
+ * Get access token
194
+ */
195
+ getAccessToken(): string | null;
196
+ /**
197
+ * Set access token
198
+ */
199
+ setAccessToken(token: string): void;
200
+ /**
201
+ * Get user
202
+ */
203
+ getUser(): UserSchema | null;
204
+ /**
205
+ * Set user
206
+ */
207
+ setUser(user: UserSchema): void;
208
+ /**
209
+ * Clear in-memory session
210
+ */
211
+ clearSession(): void;
212
+ }
213
+
214
+ type JsonRequestBody = Record<string, unknown> | unknown[] | null;
215
+ interface RequestOptions extends Omit<RequestInit, 'body'> {
216
+ params?: Record<string, string>;
217
+ body?: RequestInit['body'] | JsonRequestBody;
218
+ /** Allow retrying non-idempotent requests (POST, PATCH). Off by default to prevent duplicate writes. */
219
+ idempotent?: boolean;
220
+ }
221
+ /**
222
+ * HTTP client with built-in retry, timeout, and exponential backoff support.
223
+ * Handles authentication, request serialization, and error normalization.
224
+ */
225
+ declare class HttpClient {
226
+ readonly baseUrl: string;
227
+ readonly fetch: typeof fetch;
228
+ private defaultHeaders;
229
+ private anonKey;
230
+ private userToken;
231
+ private logger;
232
+ private autoRefreshToken;
233
+ private isRefreshing;
234
+ private refreshPromise;
235
+ private tokenManager;
236
+ private refreshToken;
237
+ private timeout;
238
+ private retryCount;
239
+ private retryDelay;
240
+ /**
241
+ * Creates a new HttpClient instance.
242
+ * @param config - SDK configuration including baseUrl, timeout, retry settings, and fetch implementation.
243
+ * @param tokenManager - Token manager for session persistence.
244
+ * @param logger - Optional logger instance for request/response debugging.
245
+ */
246
+ constructor(config: InsForgeConfig, tokenManager?: TokenManager, logger?: Logger);
247
+ /**
248
+ * Builds a full URL from a path and optional query parameters.
249
+ * Normalizes PostgREST select parameters for proper syntax.
250
+ */
251
+ private buildUrl;
252
+ /** Checks if an HTTP status code is eligible for retry (5xx server errors). */
253
+ private isRetryableStatus;
254
+ /**
255
+ * Computes the delay before the next retry using exponential backoff with jitter.
256
+ * @param attempt - The current retry attempt number (1-based).
257
+ * @returns Delay in milliseconds.
258
+ */
259
+ private computeRetryDelay;
260
+ /**
261
+ * Performs an HTTP request with automatic retry and timeout handling.
262
+ * Retries on network errors and 5xx server errors with exponential backoff.
263
+ * Client errors (4xx) and timeouts are thrown immediately without retry.
264
+ * @param method - HTTP method (GET, POST, PUT, PATCH, DELETE).
265
+ * @param path - API path relative to the base URL.
266
+ * @param options - Optional request configuration including headers, body, and query params.
267
+ * @returns Parsed response data.
268
+ * @throws {InsForgeError} On timeout, network failure, or HTTP error responses.
269
+ */
270
+ private handleRequest;
271
+ request<T>(method: string, path: string, options?: RequestOptions): Promise<T>;
272
+ /** Performs a GET request. */
273
+ get<T>(path: string, options?: RequestOptions): Promise<T>;
274
+ /** Performs a POST request with an optional JSON body. */
275
+ post<T>(path: string, body?: any, options?: RequestOptions): Promise<T>;
276
+ /** Performs a PUT request with an optional JSON body. */
277
+ put<T>(path: string, body?: any, options?: RequestOptions): Promise<T>;
278
+ /** Performs a PATCH request with an optional JSON body. */
279
+ patch<T>(path: string, body?: any, options?: RequestOptions): Promise<T>;
280
+ /** Performs a DELETE request. */
281
+ delete<T>(path: string, options?: RequestOptions): Promise<T>;
282
+ /** Sets or clears the user authentication token for subsequent requests. */
283
+ setAuthToken(token: string | null): void;
284
+ setRefreshToken(token: string | null): void;
285
+ /** Returns the current default headers including the authorization header if set. */
286
+ getHeaders(): Record<string, string>;
287
+ handleTokenRefresh(): Promise<AuthRefreshResponse>;
288
+ }
289
+
290
+ /**
291
+ * Auth module for InsForge SDK
292
+ * Handles authentication, sessions, profiles, and email verification
293
+ */
294
+
295
+ interface AuthOptions {
296
+ isServerMode?: boolean;
297
+ }
298
+ declare class Auth {
299
+ private http;
300
+ private tokenManager;
301
+ private options;
302
+ private authCallbackHandled;
303
+ constructor(http: HttpClient, tokenManager: TokenManager, options?: AuthOptions);
304
+ private isServerMode;
305
+ /**
306
+ * Save session from API response
307
+ * Handles token storage, CSRF token, and HTTP auth header
308
+ */
309
+ private saveSessionFromResponse;
310
+ /**
311
+ * Detect and handle OAuth callback parameters in URL
312
+ * Supports PKCE flow (insforge_code)
313
+ */
314
+ private detectAuthCallback;
315
+ signUp(request: CreateUserRequest): Promise<{
316
+ data: CreateUserResponse | null;
317
+ error: InsForgeError | null;
318
+ }>;
319
+ signInWithPassword(request: CreateSessionRequest): Promise<{
320
+ data: CreateSessionResponse | null;
321
+ error: InsForgeError | null;
322
+ }>;
323
+ signOut(): Promise<{
324
+ error: InsForgeError | null;
325
+ }>;
326
+ /**
327
+ * Sign in with OAuth provider using PKCE flow
328
+ */
329
+ signInWithOAuth(options: {
330
+ provider: OAuthProvidersSchema | string;
331
+ redirectTo?: string;
332
+ skipBrowserRedirect?: boolean;
333
+ }): Promise<{
334
+ data: {
335
+ url?: string;
336
+ provider?: string;
337
+ codeVerifier?: string;
338
+ };
339
+ error: InsForgeError | null;
340
+ }>;
341
+ /**
342
+ * Exchange OAuth authorization code for tokens (PKCE flow)
343
+ * Called automatically on initialization when insforge_code is in URL
344
+ */
345
+ exchangeOAuthCode(code: string, codeVerifier?: string): Promise<{
346
+ data: CreateSessionResponse | null;
347
+ error: InsForgeError | null;
348
+ }>;
349
+ /**
350
+ * Sign in with an ID token from a native SDK (Google One Tap, etc.)
351
+ * Use this for native mobile apps or Google One Tap on web.
352
+ *
353
+ * @param credentials.provider - The identity provider (currently only 'google' is supported)
354
+ * @param credentials.token - The ID token from the native SDK
355
+ */
356
+ signInWithIdToken(credentials: {
357
+ provider: 'google';
358
+ token: string;
359
+ }): Promise<{
360
+ data: CreateSessionResponse | null;
361
+ error: InsForgeError | null;
362
+ }>;
363
+ /**
364
+ * Refresh the current auth session.
365
+ *
366
+ * Browser mode:
367
+ * - Uses httpOnly refresh cookie and optional CSRF header.
368
+ *
369
+ * Server mode (`isServerMode: true`):
370
+ * - Uses mobile auth flow and requires `refreshToken` in request body.
371
+ */
372
+ refreshSession(options?: {
373
+ refreshToken?: string;
374
+ }): Promise<{
375
+ data: RefreshSessionResponse | null;
376
+ error: InsForgeError | null;
377
+ }>;
378
+ /**
379
+ * Get current user, automatically waits for pending OAuth callback
380
+ */
381
+ getCurrentUser(): Promise<{
382
+ data: {
383
+ user: UserSchema | null;
384
+ };
385
+ error: InsForgeError | null;
386
+ }>;
387
+ getProfile(userId: string): Promise<{
388
+ data: GetProfileResponse | null;
389
+ error: InsForgeError | null;
390
+ }>;
391
+ setProfile(profile: Record<string, unknown>): Promise<{
392
+ data: GetProfileResponse | null;
393
+ error: InsForgeError | null;
394
+ }>;
395
+ resendVerificationEmail(request: SendVerificationEmailRequest): Promise<{
396
+ data: {
397
+ success: boolean;
398
+ message: string;
399
+ } | null;
400
+ error: InsForgeError | null;
401
+ }>;
402
+ verifyEmail(request: VerifyEmailRequest): Promise<{
403
+ data: VerifyEmailResponse | null;
404
+ error: InsForgeError | null;
405
+ }>;
406
+ sendResetPasswordEmail(request: SendResetPasswordEmailRequest): Promise<{
407
+ data: {
408
+ success: boolean;
409
+ message: string;
410
+ } | null;
411
+ error: InsForgeError | null;
412
+ }>;
413
+ exchangeResetPasswordToken(request: ExchangeResetPasswordTokenRequest): Promise<{
414
+ data: ExchangeResetPasswordTokenResponse | null;
415
+ error: InsForgeError | null;
416
+ }>;
417
+ resetPassword(request: {
418
+ newPassword: string;
419
+ otp: string;
420
+ }): Promise<{
421
+ data: ResetPasswordResponse | null;
422
+ error: InsForgeError | null;
423
+ }>;
424
+ getPublicAuthConfig(): Promise<{
425
+ data: GetPublicAuthConfigResponse | null;
426
+ error: InsForgeError | null;
427
+ }>;
428
+ }
429
+
430
+ /**
431
+ * Database client using postgrest-js
432
+ * Drop-in replacement with FULL PostgREST capabilities
433
+ */
434
+ declare class Database {
435
+ private postgrest;
436
+ constructor(httpClient: HttpClient, tokenManager: TokenManager);
437
+ /**
438
+ * Create a query builder for a table
439
+ *
440
+ * @example
441
+ * // Basic query
442
+ * const { data, error } = await client.database
443
+ * .from('posts')
444
+ * .select('*')
445
+ * .eq('user_id', userId);
446
+ *
447
+ * // With count (Supabase style!)
448
+ * const { data, error, count } = await client.database
449
+ * .from('posts')
450
+ * .select('*', { count: 'exact' })
451
+ * .range(0, 9);
452
+ *
453
+ * // Just get count, no data
454
+ * const { count } = await client.database
455
+ * .from('posts')
456
+ * .select('*', { count: 'exact', head: true });
457
+ *
458
+ * // Complex queries with OR
459
+ * const { data } = await client.database
460
+ * .from('posts')
461
+ * .select('*, users!inner(*)')
462
+ * .or('status.eq.active,status.eq.pending');
463
+ *
464
+ * // All features work:
465
+ * - Nested selects
466
+ * - Foreign key expansion
467
+ * - OR/AND/NOT conditions
468
+ * - Count with head
469
+ * - Range pagination
470
+ * - Upserts
471
+ */
472
+ from(table: string): _supabase_postgrest_js.PostgrestQueryBuilder<any, any, any, string, unknown>;
473
+ /**
474
+ * Call a PostgreSQL function (RPC)
475
+ *
476
+ * @example
477
+ * // Call a function with parameters
478
+ * const { data, error } = await client.database
479
+ * .rpc('get_user_stats', { user_id: 123 });
480
+ *
481
+ * // Call a function with no parameters
482
+ * const { data, error } = await client.database
483
+ * .rpc('get_all_active_users');
484
+ *
485
+ * // With options (head, count, get)
486
+ * const { data, count } = await client.database
487
+ * .rpc('search_posts', { query: 'hello' }, { count: 'exact' });
488
+ */
489
+ rpc(fn: string, args?: Record<string, unknown>, options?: {
490
+ head?: boolean;
491
+ get?: boolean;
492
+ count?: 'exact' | 'planned' | 'estimated';
493
+ }): _supabase_postgrest_js.PostgrestFilterBuilder<any, any, any, any, string, null, "RPC">;
494
+ }
495
+
496
+ /**
497
+ * Storage module for InsForge SDK
498
+ * Handles file uploads, downloads, and bucket management
499
+ */
500
+
501
+ interface StorageResponse<T> {
502
+ data: T | null;
503
+ error: InsForgeError | null;
504
+ }
505
+ /**
506
+ * Storage bucket operations
507
+ */
508
+ declare class StorageBucket {
509
+ private bucketName;
510
+ private http;
511
+ constructor(bucketName: string, http: HttpClient);
512
+ /**
513
+ * Upload a file with a specific key
514
+ * Uses the upload strategy from backend (direct or presigned)
515
+ * @param path - The object key/path
516
+ * @param file - File or Blob to upload
517
+ */
518
+ upload(path: string, file: File | Blob): Promise<StorageResponse<StorageFileSchema>>;
519
+ /**
520
+ * Upload a file with auto-generated key
521
+ * Uses the upload strategy from backend (direct or presigned)
522
+ * @param file - File or Blob to upload
523
+ */
524
+ uploadAuto(file: File | Blob): Promise<StorageResponse<StorageFileSchema>>;
525
+ /**
526
+ * Internal method to handle presigned URL uploads
527
+ */
528
+ private uploadWithPresignedUrl;
529
+ /**
530
+ * Download a file
531
+ * Uses the download strategy from backend (direct or presigned)
532
+ * @param path - The object key/path
533
+ * Returns the file as a Blob
534
+ */
535
+ download(path: string): Promise<{
536
+ data: Blob | null;
537
+ error: InsForgeError | null;
538
+ }>;
539
+ /**
540
+ * Get public URL for a file
541
+ * @param path - The object key/path
542
+ */
543
+ getPublicUrl(path: string): string;
544
+ /**
545
+ * List objects in the bucket
546
+ * @param prefix - Filter by key prefix
547
+ * @param search - Search in file names
548
+ * @param limit - Maximum number of results (default: 100, max: 1000)
549
+ * @param offset - Number of results to skip
550
+ */
551
+ list(options?: {
552
+ prefix?: string;
553
+ search?: string;
554
+ limit?: number;
555
+ offset?: number;
556
+ }): Promise<StorageResponse<ListObjectsResponseSchema>>;
557
+ /**
558
+ * Delete a file
559
+ * @param path - The object key/path
560
+ */
561
+ remove(path: string): Promise<StorageResponse<{
562
+ message: string;
563
+ }>>;
564
+ }
565
+ /**
566
+ * Storage module for file operations
567
+ */
568
+ declare class Storage {
569
+ private http;
570
+ constructor(http: HttpClient);
571
+ /**
572
+ * Get a bucket instance for operations
573
+ * @param bucketName - Name of the bucket
574
+ */
575
+ from(bucketName: string): StorageBucket;
576
+ }
577
+
578
+ /**
579
+ * AI Module for Insforge SDK
580
+ * Response format roughly matches OpenAI SDK for compatibility
581
+ *
582
+ * The backend handles all the complexity of different AI providers
583
+ * and returns a unified format. This SDK transforms responses to match OpenAI-like format.
584
+ */
585
+
586
+ declare class AI {
587
+ private http;
588
+ readonly chat: Chat;
589
+ readonly images: Images;
590
+ readonly embeddings: Embeddings;
591
+ constructor(http: HttpClient);
592
+ }
593
+ declare class Chat {
594
+ readonly completions: ChatCompletions;
595
+ constructor(http: HttpClient);
596
+ }
597
+ declare class ChatCompletions {
598
+ private http;
599
+ constructor(http: HttpClient);
600
+ /**
601
+ * Create a chat completion - OpenAI-like response format
602
+ *
603
+ * @example
604
+ * ```typescript
605
+ * // Non-streaming
606
+ * const completion = await client.ai.chat.completions.create({
607
+ * model: 'gpt-4',
608
+ * messages: [{ role: 'user', content: 'Hello!' }]
609
+ * });
610
+ * console.log(completion.choices[0].message.content);
611
+ *
612
+ * // With images (OpenAI-compatible format)
613
+ * const response = await client.ai.chat.completions.create({
614
+ * model: 'gpt-4-vision',
615
+ * messages: [{
616
+ * role: 'user',
617
+ * content: [
618
+ * { type: 'text', text: 'What is in this image?' },
619
+ * { type: 'image_url', image_url: { url: 'https://example.com/image.jpg' } }
620
+ * ]
621
+ * }]
622
+ * });
623
+ *
624
+ * // With PDF files
625
+ * const pdfResponse = await client.ai.chat.completions.create({
626
+ * model: 'anthropic/claude-3.5-sonnet',
627
+ * messages: [{
628
+ * role: 'user',
629
+ * content: [
630
+ * { type: 'text', text: 'Summarize this document' },
631
+ * { type: 'file', file: { filename: 'doc.pdf', file_data: 'https://example.com/doc.pdf' } }
632
+ * ]
633
+ * }],
634
+ * fileParser: { enabled: true, pdf: { engine: 'mistral-ocr' } }
635
+ * });
636
+ *
637
+ * // With web search
638
+ * const searchResponse = await client.ai.chat.completions.create({
639
+ * model: 'openai/gpt-4',
640
+ * messages: [{ role: 'user', content: 'What are the latest news about AI?' }],
641
+ * webSearch: { enabled: true, maxResults: 5 }
642
+ * });
643
+ * // Access citations from response.choices[0].message.annotations
644
+ *
645
+ * // With thinking/reasoning mode (Anthropic models)
646
+ * const thinkingResponse = await client.ai.chat.completions.create({
647
+ * model: 'anthropic/claude-3.5-sonnet',
648
+ * messages: [{ role: 'user', content: 'Solve this complex math problem...' }],
649
+ * thinking: true
650
+ * });
651
+ *
652
+ * // Streaming - returns async iterable
653
+ * const stream = await client.ai.chat.completions.create({
654
+ * model: 'gpt-4',
655
+ * messages: [{ role: 'user', content: 'Tell me a story' }],
656
+ * stream: true
657
+ * });
658
+ *
659
+ * for await (const chunk of stream) {
660
+ * if (chunk.choices[0]?.delta?.content) {
661
+ * process.stdout.write(chunk.choices[0].delta.content);
662
+ * }
663
+ * }
664
+ * ```
665
+ */
666
+ create(params: ChatCompletionRequest): Promise<any>;
667
+ /**
668
+ * Parse SSE stream into async iterable of OpenAI-like chunks
669
+ */
670
+ private parseSSEStream;
671
+ }
672
+ declare class Embeddings {
673
+ private http;
674
+ constructor(http: HttpClient);
675
+ /**
676
+ * Create embeddings for text input - OpenAI-like response format
677
+ *
678
+ * @example
679
+ * ```typescript
680
+ * // Single text input
681
+ * const response = await client.ai.embeddings.create({
682
+ * model: 'openai/text-embedding-3-small',
683
+ * input: 'Hello world'
684
+ * });
685
+ * console.log(response.data[0].embedding); // number[]
686
+ *
687
+ * // Multiple text inputs
688
+ * const response = await client.ai.embeddings.create({
689
+ * model: 'openai/text-embedding-3-small',
690
+ * input: ['Hello world', 'Goodbye world']
691
+ * });
692
+ * response.data.forEach((item, i) => {
693
+ * console.log(`Embedding ${i}:`, item.embedding.slice(0, 5)); // First 5 dimensions
694
+ * });
695
+ *
696
+ * // With custom dimensions (if supported by model)
697
+ * const response = await client.ai.embeddings.create({
698
+ * model: 'openai/text-embedding-3-small',
699
+ * input: 'Hello world',
700
+ * dimensions: 256
701
+ * });
702
+ *
703
+ * // With base64 encoding format
704
+ * const response = await client.ai.embeddings.create({
705
+ * model: 'openai/text-embedding-3-small',
706
+ * input: 'Hello world',
707
+ * encoding_format: 'base64'
708
+ * });
709
+ * ```
710
+ */
711
+ create(params: EmbeddingsRequest): Promise<any>;
712
+ }
713
+ declare class Images {
714
+ private http;
715
+ constructor(http: HttpClient);
716
+ /**
717
+ * Generate images - OpenAI-like response format
718
+ *
719
+ * @example
720
+ * ```typescript
721
+ * // Text-to-image
722
+ * const response = await client.ai.images.generate({
723
+ * model: 'dall-e-3',
724
+ * prompt: 'A sunset over mountains',
725
+ * });
726
+ * console.log(response.images[0].url);
727
+ *
728
+ * // Image-to-image (with input images)
729
+ * const response = await client.ai.images.generate({
730
+ * model: 'stable-diffusion-xl',
731
+ * prompt: 'Transform this into a watercolor painting',
732
+ * images: [
733
+ * { url: 'https://example.com/input.jpg' },
734
+ * // or base64-encoded Data URI:
735
+ * { url: 'data:image/jpeg;base64,/9j/4AAQ...' }
736
+ * ]
737
+ * });
738
+ * ```
739
+ */
740
+ generate(params: ImageGenerationRequest): Promise<any>;
741
+ }
742
+
743
+ interface FunctionInvokeOptions {
744
+ /**
745
+ * The body of the request
746
+ */
747
+ body?: any;
748
+ /**
749
+ * Custom headers to send with the request
750
+ */
751
+ headers?: Record<string, string>;
752
+ /**
753
+ * HTTP method (default: POST)
754
+ */
755
+ method?: 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE';
756
+ }
757
+ /**
758
+ * Edge Functions client for invoking serverless functions
759
+ *
760
+ * @example
761
+ * ```typescript
762
+ * // Invoke a function with JSON body
763
+ * const { data, error } = await client.functions.invoke('hello-world', {
764
+ * body: { name: 'World' }
765
+ * });
766
+ *
767
+ * // GET request
768
+ * const { data, error } = await client.functions.invoke('get-data', {
769
+ * method: 'GET'
770
+ * });
771
+ * ```
772
+ */
773
+ declare class Functions {
774
+ private http;
775
+ private functionsUrl;
776
+ constructor(http: HttpClient, functionsUrl?: string);
777
+ /**
778
+ * Derive the subhosting URL from the base URL.
779
+ * Base URL pattern: https://{appKey}.{region}.insforge.app
780
+ * Functions URL: https://{appKey}.functions.insforge.app
781
+ * Only applies to .insforge.app domains.
782
+ */
783
+ private static deriveSubhostingUrl;
784
+ /**
785
+ * Invokes an Edge Function
786
+ *
787
+ * If functionsUrl is configured, tries direct subhosting first.
788
+ * Falls back to proxy URL if subhosting returns 404.
789
+ *
790
+ * @param slug The function slug to invoke
791
+ * @param options Request options
792
+ */
793
+ invoke<T = any>(slug: string, options?: FunctionInvokeOptions): Promise<{
794
+ data: T | null;
795
+ error: InsForgeError | null;
796
+ }>;
797
+ }
798
+
799
+ type ConnectionState = 'disconnected' | 'connecting' | 'connected';
800
+ type EventCallback<T = unknown> = (payload: T) => void;
801
+ /**
802
+ * Realtime module for subscribing to channels and handling real-time events
803
+ *
804
+ * @example
805
+ * ```typescript
806
+ * const { realtime } = client;
807
+ *
808
+ * // Connect to the realtime server
809
+ * await realtime.connect();
810
+ *
811
+ * // Subscribe to a channel
812
+ * const response = await realtime.subscribe('orders:123');
813
+ * if (!response.ok) {
814
+ * console.error('Failed to subscribe:', response.error);
815
+ * }
816
+ *
817
+ * // Listen for specific events
818
+ * realtime.on('order_updated', (payload) => {
819
+ * console.log('Order updated:', payload);
820
+ * });
821
+ *
822
+ * // Listen for connection events
823
+ * realtime.on('connect', () => console.log('Connected!'));
824
+ * realtime.on('connect_error', (err) => console.error('Connection failed:', err));
825
+ * realtime.on('disconnect', (reason) => console.log('Disconnected:', reason));
826
+ * realtime.on('error', (error) => console.error('Realtime error:', error));
827
+ *
828
+ * // Publish a message to a channel
829
+ * await realtime.publish('orders:123', 'status_changed', { status: 'shipped' });
830
+ *
831
+ * // Unsubscribe and disconnect when done
832
+ * realtime.unsubscribe('orders:123');
833
+ * realtime.disconnect();
834
+ * ```
835
+ */
836
+ declare class Realtime {
837
+ private baseUrl;
838
+ private tokenManager;
839
+ private socket;
840
+ private connectPromise;
841
+ private subscribedChannels;
842
+ private eventListeners;
843
+ private anonKey?;
844
+ constructor(baseUrl: string, tokenManager: TokenManager, anonKey?: string);
845
+ private notifyListeners;
846
+ /**
847
+ * Connect to the realtime server
848
+ * @returns Promise that resolves when connected
849
+ */
850
+ connect(): Promise<void>;
851
+ /**
852
+ * Disconnect from the realtime server
853
+ */
854
+ disconnect(): void;
855
+ /**
856
+ * Handle token changes (e.g., after auth refresh)
857
+ * Updates socket auth so reconnects use the new token
858
+ * If connected, triggers reconnect to apply new token immediately
859
+ */
860
+ private onTokenChange;
861
+ /**
862
+ * Check if connected to the realtime server
863
+ */
864
+ get isConnected(): boolean;
865
+ /**
866
+ * Get the current connection state
867
+ */
868
+ get connectionState(): ConnectionState;
869
+ /**
870
+ * Get the socket ID (if connected)
871
+ */
872
+ get socketId(): string | undefined;
873
+ /**
874
+ * Subscribe to a channel
875
+ *
876
+ * Automatically connects if not already connected.
877
+ *
878
+ * @param channel - Channel name (e.g., 'orders:123', 'broadcast')
879
+ * @returns Promise with the subscription response
880
+ */
881
+ subscribe(channel: string): Promise<SubscribeResponse>;
882
+ /**
883
+ * Unsubscribe from a channel (fire-and-forget)
884
+ *
885
+ * @param channel - Channel name to unsubscribe from
886
+ */
887
+ unsubscribe(channel: string): void;
888
+ /**
889
+ * Publish a message to a channel
890
+ *
891
+ * @param channel - Channel name
892
+ * @param event - Event name
893
+ * @param payload - Message payload
894
+ */
895
+ publish<T = unknown>(channel: string, event: string, payload: T): Promise<void>;
896
+ /**
897
+ * Listen for events
898
+ *
899
+ * Reserved event names:
900
+ * - 'connect' - Fired when connected to the server
901
+ * - 'connect_error' - Fired when connection fails (payload: Error)
902
+ * - 'disconnect' - Fired when disconnected (payload: reason string)
903
+ * - 'error' - Fired when a realtime error occurs (payload: RealtimeErrorPayload)
904
+ *
905
+ * All other events receive a `SocketMessage` payload with metadata.
906
+ *
907
+ * @param event - Event name to listen for
908
+ * @param callback - Callback function when event is received
909
+ */
910
+ on<T = SocketMessage>(event: string, callback: EventCallback<T>): void;
911
+ /**
912
+ * Remove a listener for a specific event
913
+ *
914
+ * @param event - Event name
915
+ * @param callback - The callback function to remove
916
+ */
917
+ off<T = SocketMessage>(event: string, callback: EventCallback<T>): void;
918
+ /**
919
+ * Listen for an event only once, then automatically remove the listener
920
+ *
921
+ * @param event - Event name to listen for
922
+ * @param callback - Callback function when event is received
923
+ */
924
+ once<T = SocketMessage>(event: string, callback: EventCallback<T>): void;
925
+ /**
926
+ * Get all currently subscribed channels
927
+ *
928
+ * @returns Array of channel names
929
+ */
930
+ getSubscribedChannels(): string[];
931
+ }
932
+
933
+ /**
934
+ * Emails client for sending custom emails
935
+ *
936
+ * @example
937
+ * ```typescript
938
+ * // Send a simple email
939
+ * const { data, error } = await client.emails.send({
940
+ * to: 'user@example.com',
941
+ * subject: 'Welcome!',
942
+ * html: '<h1>Welcome to our platform</h1>'
943
+ * });
944
+ *
945
+ * if (error) {
946
+ * console.error('Failed to send:', error.message);
947
+ * return;
948
+ * }
949
+ * // Email sent successfully - data is {} (empty object)
950
+ *
951
+ * // Send to multiple recipients with CC
952
+ * const { data, error } = await client.emails.send({
953
+ * to: ['user1@example.com', 'user2@example.com'],
954
+ * cc: 'manager@example.com',
955
+ * subject: 'Team Update',
956
+ * html: '<p>Here is the latest update...</p>',
957
+ * replyTo: 'support@example.com'
958
+ * });
959
+ * ```
960
+ */
961
+ declare class Emails {
962
+ private http;
963
+ constructor(http: HttpClient);
964
+ /**
965
+ * Send a custom HTML email
966
+ * @param options Email options including recipients, subject, and HTML content
967
+ */
968
+ send(options: SendRawEmailRequest): Promise<{
969
+ data: SendEmailResponse | null;
970
+ error: InsForgeError | null;
971
+ }>;
972
+ }
973
+
974
+ /**
975
+ * Main InsForge SDK Client
976
+ *
977
+ * @example
978
+ * ```typescript
979
+ * import { InsForgeClient } from '@insforge/sdk';
980
+ *
981
+ * const client = new InsForgeClient({
982
+ * baseUrl: 'http://localhost:7130'
983
+ * });
984
+ *
985
+ * // Authentication
986
+ * const { data, error } = await client.auth.signUp({
987
+ * email: 'user@example.com',
988
+ * password: 'password123',
989
+ * name: 'John Doe'
990
+ * });
991
+ *
992
+ * // Database operations
993
+ * const { data, error } = await client.database
994
+ * .from('posts')
995
+ * .select('*')
996
+ * .eq('user_id', session.user.id)
997
+ * .order('created_at', { ascending: false })
998
+ * .limit(10);
999
+ *
1000
+ * // Insert data
1001
+ * const { data: newPost } = await client.database
1002
+ * .from('posts')
1003
+ * .insert({ title: 'Hello', content: 'World' })
1004
+ * .single();
1005
+ *
1006
+ * // Invoke edge functions
1007
+ * const { data, error } = await client.functions.invoke('my-function', {
1008
+ * body: { message: 'Hello from SDK' }
1009
+ * });
1010
+ *
1011
+ * // Enable debug logging
1012
+ * const debugClient = new InsForgeClient({
1013
+ * baseUrl: 'http://localhost:7130',
1014
+ * debug: true
1015
+ * });
1016
+ * ```
1017
+ */
1018
+ declare class InsForgeClient {
1019
+ private http;
1020
+ private tokenManager;
1021
+ readonly auth: Auth;
1022
+ readonly database: Database;
1023
+ readonly storage: Storage;
1024
+ readonly ai: AI;
1025
+ readonly functions: Functions;
1026
+ readonly realtime: Realtime;
1027
+ readonly emails: Emails;
1028
+ constructor(config?: InsForgeConfig);
1029
+ /**
1030
+ * Get the underlying HTTP client for custom requests
1031
+ *
1032
+ * @example
1033
+ * ```typescript
1034
+ * const httpClient = client.getHttpClient();
1035
+ * const customData = await httpClient.get('/api/custom-endpoint');
1036
+ * ```
1037
+ */
1038
+ getHttpClient(): HttpClient;
1039
+ }
1040
+
1041
+ /**
1042
+ * @insforge/sdk - TypeScript SDK for InsForge Backend-as-a-Service
1043
+ *
1044
+ * @packageDocumentation
1045
+ */
1046
+
1047
+ declare function createClient(config: InsForgeConfig): InsForgeClient;
1048
+
1049
+ export { AI, type ApiError, Auth, type AuthSession, type InsForgeConfig as ClientOptions, type ConnectionState, Database, Emails, type EventCallback, type FunctionInvokeOptions, Functions, HttpClient, InsForgeClient, type InsForgeConfig, InsForgeError, Logger, Realtime, Storage, StorageBucket, type StorageResponse, TokenManager, createClient, InsForgeClient as default };