@insforge/sdk 1.2.9 → 1.3.0-ssr.0

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