@resultdev/sdk 0.1.0 → 0.2.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.
@@ -0,0 +1,1057 @@
1
+ import { e as AuthSession, U as UserSchema, a as ResultConfig, G as AuthRefreshResponse, C as ChatCompletionRequest, B as ToolCall, H as Annotation, I as ImageGenerationRequest, j as EmbeddingsRequest, J as EmbeddingObject, h as CreateUserRequest, K as CreateUserResponse, o as ResultError, g as CreateSessionRequest, L as CreateSessionResponse, l as OAuthProvidersSchema, M as RefreshSessionResponse, N as GetProfileResponse, Q as SendVerificationEmailRequest, V as VerifyEmailRequest, W as VerifyEmailResponse, X as SendResetPasswordEmailRequest, Y as ExchangeResetPasswordTokenRequest, Z as ExchangeResetPasswordTokenResponse, _ as ResetPasswordResponse, $ as GetPublicAuthConfigResponse, S as SendRawEmailRequest, q as SendEmailResponse, v as SubscribeResponse, r as SocketMessage, P as PresenceMember, u as StorageFileSchema, a0 as ListObjectsResponseSchema, i as DeleteObjectsResponse, A as Analytics, w as Support } from './types-CbsaMttt.js';
2
+ import * as _supabase_postgrest_js from '@supabase/postgrest-js';
3
+ import { PostgrestClient } from '@supabase/postgrest-js';
4
+
5
+ type LogFunction = (message: string, ...args: any[]) => void;
6
+ /**
7
+ * Debug logger for the Result SDK.
8
+ * Logs HTTP request/response details with automatic redaction of sensitive data.
9
+ *
10
+ * @example
11
+ * ```typescript
12
+ * // Enable via SDK config
13
+ * const client = new ResultClient({ debug: true });
14
+ *
15
+ * // Or with a custom log function
16
+ * const client = new ResultClient({
17
+ * debug: (msg) => myLogger.info(msg)
18
+ * });
19
+ * ```
20
+ */
21
+ declare class Logger {
22
+ /** Whether debug logging is currently enabled */
23
+ enabled: boolean;
24
+ private customLog;
25
+ /**
26
+ * Creates a new Logger instance.
27
+ * @param debug - Set to true to enable console logging, or pass a custom log function
28
+ */
29
+ constructor(debug?: boolean | LogFunction);
30
+ /**
31
+ * Logs a debug message at the info level.
32
+ * @param message - The message to log
33
+ * @param args - Additional arguments to pass to the log function
34
+ */
35
+ log(message: string, ...args: any[]): void;
36
+ /**
37
+ * Logs a debug message at the warning level.
38
+ * @param message - The message to log
39
+ * @param args - Additional arguments to pass to the log function
40
+ */
41
+ warn(message: string, ...args: any[]): void;
42
+ /**
43
+ * Logs a debug message at the error level.
44
+ * @param message - The message to log
45
+ * @param args - Additional arguments to pass to the log function
46
+ */
47
+ error(message: string, ...args: any[]): void;
48
+ /**
49
+ * Logs an outgoing HTTP request with method, URL, headers, and body.
50
+ * Sensitive headers and body fields are automatically redacted.
51
+ * @param method - HTTP method (GET, POST, etc.)
52
+ * @param url - The full request URL
53
+ * @param headers - Request headers (sensitive values will be redacted)
54
+ * @param body - Request body (sensitive fields will be masked)
55
+ */
56
+ logRequest(method: string, url: string, headers?: Record<string, string>, body?: any): void;
57
+ /**
58
+ * Logs an incoming HTTP response with method, URL, status, duration, and body.
59
+ * Error responses (4xx/5xx) are logged at the error level.
60
+ * @param method - HTTP method (GET, POST, etc.)
61
+ * @param url - The full request URL
62
+ * @param status - HTTP response status code
63
+ * @param durationMs - Request duration in milliseconds
64
+ * @param body - Response body (sensitive fields will be masked, large bodies truncated)
65
+ */
66
+ logResponse(method: string, url: string, status: number, durationMs: number, body?: any): void;
67
+ }
68
+
69
+ /**
70
+ * Token Manager for Result SDK
71
+ *
72
+ * Memory-only token storage.
73
+ */
74
+
75
+ declare const AuthChangeEvent: {
76
+ readonly SIGNED_IN: "signedIn";
77
+ readonly SIGNED_OUT: "signedOut";
78
+ readonly TOKEN_REFRESHED: "tokenRefreshed";
79
+ };
80
+ type AuthChangeEvent = (typeof AuthChangeEvent)[keyof typeof AuthChangeEvent];
81
+ type AuthStateChangeCallback = (event: AuthChangeEvent) => void;
82
+ declare class TokenManager {
83
+ private accessToken;
84
+ private user;
85
+ private authStateChangeCallbacks;
86
+ /**
87
+ * Save session in memory
88
+ */
89
+ saveSession(session: AuthSession, event?: AuthChangeEvent): void;
90
+ /**
91
+ * Get current session
92
+ */
93
+ getSession(): AuthSession | null;
94
+ /**
95
+ * Get access token
96
+ */
97
+ getAccessToken(): string | null;
98
+ /**
99
+ * Set access token
100
+ */
101
+ setAccessToken(token: string, event?: AuthChangeEvent): void;
102
+ /**
103
+ * Get user
104
+ */
105
+ getUser(): UserSchema | null;
106
+ /**
107
+ * Set user
108
+ */
109
+ setUser(user: UserSchema): void;
110
+ /**
111
+ * Clear in-memory session
112
+ */
113
+ clearSession(): void;
114
+ onAuthStateChange(callback: AuthStateChangeCallback): () => void;
115
+ private notifyAuthStateChange;
116
+ }
117
+
118
+ type JsonRequestBody = Record<string, unknown> | unknown[] | null;
119
+ interface RequestOptions extends Omit<RequestInit, "body"> {
120
+ params?: Record<string, string>;
121
+ body?: RequestInit["body"] | JsonRequestBody;
122
+ /** Allow retrying non-idempotent requests (POST, PATCH). Off by default to prevent duplicate writes. */
123
+ idempotent?: boolean;
124
+ /** Disable automatic access-token refresh for auth/control-flow requests. */
125
+ skipAuthRefresh?: boolean;
126
+ }
127
+ /**
128
+ * HTTP client with built-in retry, timeout, and exponential backoff support.
129
+ * Handles authentication, request serialization, and error normalization.
130
+ */
131
+ declare class HttpClient {
132
+ readonly baseUrl: string;
133
+ readonly fetch: typeof fetch;
134
+ private readonly config;
135
+ private defaultHeaders;
136
+ private anonKey;
137
+ private userToken;
138
+ private logger;
139
+ private isRefreshing;
140
+ private refreshPromise;
141
+ private tokenManager;
142
+ private refreshToken;
143
+ private timeout;
144
+ private retryCount;
145
+ private retryDelay;
146
+ /**
147
+ * Creates a new HttpClient instance.
148
+ * @param config - SDK configuration including baseUrl, timeout, retry settings, and fetch implementation.
149
+ * @param tokenManager - Token manager for session persistence.
150
+ * @param logger - Optional logger instance for request/response debugging.
151
+ */
152
+ constructor(config: ResultConfig, tokenManager?: TokenManager, logger?: Logger);
153
+ /**
154
+ * Builds a full URL from a path and optional query parameters.
155
+ * Normalizes PostgREST select parameters for proper syntax.
156
+ */
157
+ private buildUrl;
158
+ /** Checks if an HTTP status code is eligible for retry (5xx server errors). */
159
+ private isRetryableStatus;
160
+ /**
161
+ * Computes the delay before the next retry using exponential backoff with jitter.
162
+ * @param attempt - The current retry attempt number (1-based).
163
+ * @returns Delay in milliseconds.
164
+ */
165
+ private computeRetryDelay;
166
+ private shouldRefreshAccessToken;
167
+ private fetchWithRetry;
168
+ /**
169
+ * Performs an HTTP request with automatic retry and timeout handling.
170
+ * Retries on network errors and 5xx server errors with exponential backoff.
171
+ * Client errors (4xx) and timeouts are thrown immediately without retry.
172
+ * @param method - HTTP method (GET, POST, PUT, PATCH, DELETE).
173
+ * @param path - API path relative to the base URL.
174
+ * @param options - Optional request configuration including headers, body, and query params.
175
+ * @returns Parsed response data.
176
+ * @throws {ResultError} On timeout, network failure, or HTTP error responses.
177
+ */
178
+ private handleRequest;
179
+ request<T>(method: string, path: string, options?: RequestOptions): Promise<T>;
180
+ /**
181
+ * Performs an SDK-configured fetch and returns the raw Response.
182
+ * This is used by clients such as postgrest-js that need to own response
183
+ * parsing while still sharing SDK auth and refresh behavior.
184
+ */
185
+ rawFetch(input: RequestInfo | URL, init?: RequestInit, options?: {
186
+ skipAuthRefresh?: boolean;
187
+ }): Promise<Response>;
188
+ /** Performs a GET request. */
189
+ get<T>(path: string, options?: RequestOptions): Promise<T>;
190
+ /** Performs a POST request with an optional JSON body. */
191
+ post<T>(path: string, body?: any, options?: RequestOptions): Promise<T>;
192
+ /** Performs a PUT request with an optional JSON body. */
193
+ put<T>(path: string, body?: any, options?: RequestOptions): Promise<T>;
194
+ /** Performs a PATCH request with an optional JSON body. */
195
+ patch<T>(path: string, body?: any, options?: RequestOptions): Promise<T>;
196
+ /** Performs a DELETE request. */
197
+ delete<T>(path: string, options?: RequestOptions): Promise<T>;
198
+ /** Sets or clears the user authentication token for subsequent requests. */
199
+ setAuthToken(token: string | null): void;
200
+ setRefreshToken(token: string | null): void;
201
+ /** Returns the current default headers including the authorization header if set. */
202
+ getHeaders(): Record<string, string>;
203
+ refreshAccessToken(): Promise<AuthRefreshResponse>;
204
+ /** Returns a token safe to use for a new connection handshake. */
205
+ getValidAccessToken(leewaySeconds?: number): Promise<string | null>;
206
+ private refreshAndSaveSession;
207
+ private clearAuthSession;
208
+ }
209
+
210
+ /**
211
+ * AI Module for Result SDK
212
+ * Response format roughly matches OpenAI SDK for compatibility
213
+ *
214
+ * The backend handles all the complexity of different AI providers
215
+ * and returns a unified format. This SDK transforms responses to match OpenAI-like format.
216
+ */
217
+
218
+ interface ChatCompletionUsage {
219
+ prompt_tokens: number;
220
+ completion_tokens: number;
221
+ total_tokens: number;
222
+ }
223
+ interface ChatCompletionChoice {
224
+ index: number;
225
+ message: {
226
+ role: "assistant";
227
+ content: string;
228
+ tool_calls?: ToolCall[];
229
+ annotations?: Annotation[];
230
+ };
231
+ finish_reason: "stop" | "tool_calls";
232
+ }
233
+ interface ChatCompletion {
234
+ id: string;
235
+ object: "chat.completion";
236
+ created: number;
237
+ model?: string;
238
+ choices: ChatCompletionChoice[];
239
+ usage: ChatCompletionUsage;
240
+ }
241
+ interface ChatCompletionChunk {
242
+ id: string;
243
+ object: "chat.completion.chunk";
244
+ created: number;
245
+ model: string;
246
+ choices: {
247
+ index: number;
248
+ delta: {
249
+ content?: string;
250
+ tool_calls?: ToolCall[];
251
+ };
252
+ finish_reason: "tool_calls" | null;
253
+ }[];
254
+ }
255
+ interface EmbeddingsResult {
256
+ object: "list";
257
+ data: EmbeddingObject[];
258
+ model?: string;
259
+ usage: {
260
+ prompt_tokens: number;
261
+ total_tokens: number;
262
+ };
263
+ }
264
+ interface ImageGenerationResult {
265
+ created: number;
266
+ data: {
267
+ b64_json?: string;
268
+ content?: string;
269
+ }[];
270
+ usage?: {
271
+ total_tokens: number;
272
+ input_tokens: number;
273
+ output_tokens: number;
274
+ };
275
+ }
276
+ declare class AI {
277
+ readonly chat: Chat;
278
+ readonly images: Images;
279
+ readonly embeddings: Embeddings;
280
+ constructor(http: HttpClient);
281
+ }
282
+ declare class Chat {
283
+ readonly completions: ChatCompletions;
284
+ constructor(http: HttpClient);
285
+ }
286
+ declare class ChatCompletions {
287
+ private http;
288
+ constructor(http: HttpClient);
289
+ /**
290
+ * Create a chat completion - OpenAI-like response format
291
+ *
292
+ * @example
293
+ * ```typescript
294
+ * // Non-streaming
295
+ * const completion = await client.ai.chat.completions.create({
296
+ * model: 'gpt-4',
297
+ * messages: [{ role: 'user', content: 'Hello!' }]
298
+ * });
299
+ * console.log(completion.choices[0].message.content);
300
+ *
301
+ * // With images (OpenAI-compatible format)
302
+ * const response = await client.ai.chat.completions.create({
303
+ * model: 'gpt-4-vision',
304
+ * messages: [{
305
+ * role: 'user',
306
+ * content: [
307
+ * { type: 'text', text: 'What is in this image?' },
308
+ * { type: 'image_url', image_url: { url: 'https://example.com/image.jpg' } }
309
+ * ]
310
+ * }]
311
+ * });
312
+ *
313
+ * // With PDF files
314
+ * const pdfResponse = await client.ai.chat.completions.create({
315
+ * model: 'anthropic/claude-3.5-sonnet',
316
+ * messages: [{
317
+ * role: 'user',
318
+ * content: [
319
+ * { type: 'text', text: 'Summarize this document' },
320
+ * { type: 'file', file: { filename: 'doc.pdf', file_data: 'https://example.com/doc.pdf' } }
321
+ * ]
322
+ * }],
323
+ * fileParser: { enabled: true, pdf: { engine: 'mistral-ocr' } }
324
+ * });
325
+ *
326
+ * // With web search
327
+ * const searchResponse = await client.ai.chat.completions.create({
328
+ * model: 'openai/gpt-4',
329
+ * messages: [{ role: 'user', content: 'What are the latest news about AI?' }],
330
+ * webSearch: { enabled: true, maxResults: 5 }
331
+ * });
332
+ * // Access citations from response.choices[0].message.annotations
333
+ *
334
+ * // With thinking/reasoning mode (Anthropic models)
335
+ * const thinkingResponse = await client.ai.chat.completions.create({
336
+ * model: 'anthropic/claude-3.5-sonnet',
337
+ * messages: [{ role: 'user', content: 'Solve this complex math problem...' }],
338
+ * thinking: true
339
+ * });
340
+ *
341
+ * // Streaming - returns async iterable
342
+ * const stream = await client.ai.chat.completions.create({
343
+ * model: 'gpt-4',
344
+ * messages: [{ role: 'user', content: 'Tell me a story' }],
345
+ * stream: true
346
+ * });
347
+ *
348
+ * for await (const chunk of stream) {
349
+ * if (chunk.choices[0]?.delta?.content) {
350
+ * process.stdout.write(chunk.choices[0].delta.content);
351
+ * }
352
+ * }
353
+ * ```
354
+ */
355
+ create(params: ChatCompletionRequest & {
356
+ stream: true;
357
+ }): Promise<AsyncIterableIterator<ChatCompletionChunk>>;
358
+ create(params: ChatCompletionRequest & {
359
+ stream?: false;
360
+ }): Promise<ChatCompletion>;
361
+ create(params: ChatCompletionRequest): Promise<ChatCompletion | AsyncIterableIterator<ChatCompletionChunk>>;
362
+ /**
363
+ * Parse SSE stream into async iterable of OpenAI-like chunks
364
+ */
365
+ private parseSSEStream;
366
+ }
367
+ declare class Embeddings {
368
+ private http;
369
+ constructor(http: HttpClient);
370
+ /**
371
+ * Create embeddings for text input - OpenAI-like response format
372
+ *
373
+ * @example
374
+ * ```typescript
375
+ * // Single text input
376
+ * const response = await client.ai.embeddings.create({
377
+ * model: 'openai/text-embedding-3-small',
378
+ * input: 'Hello world'
379
+ * });
380
+ * console.log(response.data[0].embedding); // number[]
381
+ *
382
+ * // Multiple text inputs
383
+ * const response = await client.ai.embeddings.create({
384
+ * model: 'openai/text-embedding-3-small',
385
+ * input: ['Hello world', 'Goodbye world']
386
+ * });
387
+ * response.data.forEach((item, i) => {
388
+ * console.log(`Embedding ${i}:`, item.embedding.slice(0, 5)); // First 5 dimensions
389
+ * });
390
+ *
391
+ * // With custom dimensions (if supported by model)
392
+ * const response = await client.ai.embeddings.create({
393
+ * model: 'openai/text-embedding-3-small',
394
+ * input: 'Hello world',
395
+ * dimensions: 256
396
+ * });
397
+ *
398
+ * // With base64 encoding format
399
+ * const response = await client.ai.embeddings.create({
400
+ * model: 'openai/text-embedding-3-small',
401
+ * input: 'Hello world',
402
+ * encoding_format: 'base64'
403
+ * });
404
+ * ```
405
+ */
406
+ create(params: EmbeddingsRequest): Promise<EmbeddingsResult>;
407
+ }
408
+ declare class Images {
409
+ private http;
410
+ constructor(http: HttpClient);
411
+ /**
412
+ * Generate images - OpenAI-like response format
413
+ *
414
+ * @example
415
+ * ```typescript
416
+ * // Text-to-image
417
+ * const response = await client.ai.images.generate({
418
+ * model: 'dall-e-3',
419
+ * prompt: 'A sunset over mountains',
420
+ * });
421
+ * console.log(response.data[0].b64_json);
422
+ *
423
+ * // Image-to-image (with input images)
424
+ * const response = await client.ai.images.generate({
425
+ * model: 'stable-diffusion-xl',
426
+ * prompt: 'Transform this into a watercolor painting',
427
+ * images: [
428
+ * { url: 'https://example.com/input.jpg' },
429
+ * // or base64-encoded Data URI:
430
+ * { url: 'data:image/jpeg;base64,/9j/4AAQ...' }
431
+ * ]
432
+ * });
433
+ * ```
434
+ */
435
+ generate(params: ImageGenerationRequest): Promise<ImageGenerationResult>;
436
+ }
437
+
438
+ /**
439
+ * Auth module for Result SDK
440
+ * Handles authentication, sessions, profiles, and email verification
441
+ */
442
+
443
+ interface AuthOptions {
444
+ isServerMode?: boolean;
445
+ detectOAuthCallback?: boolean;
446
+ }
447
+ type OAuthSignInOptions = {
448
+ redirectTo: string;
449
+ additionalParams?: Record<string, string>;
450
+ skipBrowserRedirect?: boolean;
451
+ };
452
+ type OAuthSignInLegacyOptions = OAuthSignInOptions & {
453
+ provider: OAuthProvidersSchema | string;
454
+ };
455
+ declare class Auth {
456
+ private http;
457
+ private tokenManager;
458
+ private options;
459
+ private authCallbackHandled;
460
+ constructor(http: HttpClient, tokenManager: TokenManager, options?: AuthOptions);
461
+ private isServerMode;
462
+ /** Subscribe to SDK authentication state changes. */
463
+ onAuthStateChange(callback: AuthStateChangeCallback): () => void;
464
+ /**
465
+ * Save session from API response
466
+ * Handles token storage, CSRF token, and HTTP auth header
467
+ */
468
+ private saveSessionFromResponse;
469
+ /**
470
+ * Detect and handle OAuth callback parameters in URL
471
+ * Supports the PKCE flow (OAuth callback code in the URL)
472
+ */
473
+ private detectAuthCallback;
474
+ signUp(request: CreateUserRequest): Promise<{
475
+ data: CreateUserResponse | null;
476
+ error: ResultError | null;
477
+ }>;
478
+ signInWithPassword(request: CreateSessionRequest): Promise<{
479
+ data: CreateSessionResponse | null;
480
+ error: ResultError | null;
481
+ }>;
482
+ signOut(): Promise<{
483
+ error: ResultError | null;
484
+ }>;
485
+ /**
486
+ * Sign in with OAuth provider using PKCE flow
487
+ */
488
+ signInWithOAuth(provider: OAuthProvidersSchema | string, options: OAuthSignInOptions): Promise<{
489
+ data: {
490
+ url?: string;
491
+ provider?: string;
492
+ codeVerifier?: string;
493
+ };
494
+ error: ResultError | null;
495
+ }>;
496
+ /**
497
+ * @deprecated Use signInWithOAuth(provider, { redirectTo, additionalParams, skipBrowserRedirect }).
498
+ */
499
+ signInWithOAuth(options: OAuthSignInLegacyOptions): Promise<{
500
+ data: {
501
+ url?: string;
502
+ provider?: string;
503
+ codeVerifier?: string;
504
+ };
505
+ error: ResultError | null;
506
+ }>;
507
+ /**
508
+ * Exchange OAuth authorization code for tokens (PKCE flow)
509
+ * Called automatically on initialization when the OAuth callback code is in the URL
510
+ */
511
+ exchangeOAuthCode(code: string, codeVerifier?: string): Promise<{
512
+ data: CreateSessionResponse | null;
513
+ error: ResultError | null;
514
+ }>;
515
+ /**
516
+ * Sign in with an ID token from a native SDK (Google One Tap, etc.)
517
+ * Use this for native mobile apps or Google One Tap on web.
518
+ *
519
+ * @param credentials.provider - The identity provider (currently only 'google' is supported)
520
+ * @param credentials.token - The ID token from the native SDK
521
+ */
522
+ signInWithIdToken(credentials: {
523
+ provider: "google";
524
+ token: string;
525
+ }): Promise<{
526
+ data: CreateSessionResponse | null;
527
+ error: ResultError | null;
528
+ }>;
529
+ /**
530
+ * Refresh the current auth session.
531
+ *
532
+ * Browser mode:
533
+ * - Uses httpOnly refresh cookie and optional CSRF header.
534
+ *
535
+ * Legacy server mode (`isServerMode: true`):
536
+ * - Uses mobile auth flow and requires `refreshToken` in request body.
537
+ *
538
+ * SSR apps should prefer `createRefreshAuthRouter()` / `refreshAuth()` from
539
+ * `@resultdev/sdk/ssr`.
540
+ */
541
+ refreshSession(options?: {
542
+ refreshToken?: string;
543
+ }): Promise<{
544
+ data: RefreshSessionResponse | null;
545
+ error: ResultError | null;
546
+ }>;
547
+ /**
548
+ * Get current user, automatically waits for pending OAuth callback
549
+ */
550
+ getCurrentUser(): Promise<{
551
+ data: {
552
+ user: UserSchema | null;
553
+ };
554
+ error: ResultError | null;
555
+ }>;
556
+ getProfile(userId: string): Promise<{
557
+ data: GetProfileResponse | null;
558
+ error: ResultError | null;
559
+ }>;
560
+ setProfile(profile: Record<string, unknown>): Promise<{
561
+ data: GetProfileResponse | null;
562
+ error: ResultError | null;
563
+ }>;
564
+ resendVerificationEmail(request: SendVerificationEmailRequest): Promise<{
565
+ data: {
566
+ success: boolean;
567
+ message: string;
568
+ } | null;
569
+ error: ResultError | null;
570
+ }>;
571
+ verifyEmail(request: VerifyEmailRequest): Promise<{
572
+ data: VerifyEmailResponse | null;
573
+ error: ResultError | null;
574
+ }>;
575
+ sendResetPasswordEmail(request: SendResetPasswordEmailRequest): Promise<{
576
+ data: {
577
+ success: boolean;
578
+ message: string;
579
+ } | null;
580
+ error: ResultError | null;
581
+ }>;
582
+ exchangeResetPasswordToken(request: ExchangeResetPasswordTokenRequest): Promise<{
583
+ data: ExchangeResetPasswordTokenResponse | null;
584
+ error: ResultError | null;
585
+ }>;
586
+ resetPassword(request: {
587
+ newPassword: string;
588
+ otp: string;
589
+ }): Promise<{
590
+ data: ResetPasswordResponse | null;
591
+ error: ResultError | null;
592
+ }>;
593
+ getPublicAuthConfig(): Promise<{
594
+ data: GetPublicAuthConfigResponse | null;
595
+ error: ResultError | null;
596
+ }>;
597
+ }
598
+
599
+ /**
600
+ * Database client using postgrest-js
601
+ * Drop-in replacement with FULL PostgREST capabilities
602
+ */
603
+ declare class Database {
604
+ private postgrest;
605
+ constructor(httpClient: HttpClient, defaultSchema?: string);
606
+ /**
607
+ * Select a non-default Postgres schema for the chained query. Maps to
608
+ * PostgREST's `Accept-Profile` (reads) / `Content-Profile` (writes) header.
609
+ * The schema must be exposed by the backend.
610
+ *
611
+ * @example
612
+ * const { data } = await client.database
613
+ * .schema('analytics')
614
+ * .from('events')
615
+ * .select('*');
616
+ *
617
+ * @example
618
+ * await client.database.schema('analytics').rpc('rollup', { day: '2026-01-01' });
619
+ */
620
+ schema(schemaName: string): PostgrestClient<any, any, string, any>;
621
+ /**
622
+ * Create a query builder for a table
623
+ *
624
+ * @example
625
+ * // Basic query
626
+ * const { data, error } = await client.database
627
+ * .from('posts')
628
+ * .select('*')
629
+ * .eq('user_id', userId);
630
+ *
631
+ * // With count (Supabase style!)
632
+ * const { data, error, count } = await client.database
633
+ * .from('posts')
634
+ * .select('*', { count: 'exact' })
635
+ * .range(0, 9);
636
+ *
637
+ * // Just get count, no data
638
+ * const { count } = await client.database
639
+ * .from('posts')
640
+ * .select('*', { count: 'exact', head: true });
641
+ *
642
+ * // Complex queries with OR
643
+ * const { data } = await client.database
644
+ * .from('posts')
645
+ * .select('*, users!inner(*)')
646
+ * .or('status.eq.active,status.eq.pending');
647
+ *
648
+ * // All features work:
649
+ * - Nested selects
650
+ * - Foreign key expansion
651
+ * - OR/AND/NOT conditions
652
+ * - Count with head
653
+ * - Range pagination
654
+ * - Upserts
655
+ */
656
+ from(table: string): _supabase_postgrest_js.PostgrestQueryBuilder<any, any, any, string, unknown>;
657
+ /**
658
+ * Call a PostgreSQL function (RPC)
659
+ *
660
+ * @example
661
+ * // Call a function with parameters
662
+ * const { data, error } = await client.database
663
+ * .rpc('get_user_stats', { user_id: 123 });
664
+ *
665
+ * // Call a function with no parameters
666
+ * const { data, error } = await client.database
667
+ * .rpc('get_all_active_users');
668
+ *
669
+ * // With options (head, count, get)
670
+ * const { data, count } = await client.database
671
+ * .rpc('search_posts', { query: 'hello' }, { count: 'exact' });
672
+ */
673
+ rpc(fn: string, args?: Record<string, unknown>, options?: {
674
+ head?: boolean;
675
+ get?: boolean;
676
+ count?: "exact" | "planned" | "estimated";
677
+ }): _supabase_postgrest_js.PostgrestFilterBuilder<any, any, any, any, string, null, "RPC">;
678
+ }
679
+
680
+ /**
681
+ * Emails client for sending custom emails
682
+ *
683
+ * @example
684
+ * ```typescript
685
+ * // Send a simple email
686
+ * const { data, error } = await client.emails.send({
687
+ * to: 'user@example.com',
688
+ * subject: 'Welcome!',
689
+ * html: '<h1>Welcome to our platform</h1>'
690
+ * });
691
+ *
692
+ * if (error) {
693
+ * console.error('Failed to send:', error.message);
694
+ * return;
695
+ * }
696
+ * // Email sent successfully - data is {} (empty object)
697
+ *
698
+ * // Send to multiple recipients with CC
699
+ * const { data, error } = await client.emails.send({
700
+ * to: ['user1@example.com', 'user2@example.com'],
701
+ * cc: 'manager@example.com',
702
+ * subject: 'Team Update',
703
+ * html: '<p>Here is the latest update...</p>',
704
+ * replyTo: 'support@example.com'
705
+ * });
706
+ * ```
707
+ */
708
+ declare class Emails {
709
+ private http;
710
+ constructor(http: HttpClient);
711
+ /**
712
+ * Send a custom HTML email
713
+ * @param options Email options including recipients, subject, and HTML content
714
+ */
715
+ send(options: SendRawEmailRequest): Promise<{
716
+ data: SendEmailResponse | null;
717
+ error: ResultError | null;
718
+ }>;
719
+ }
720
+
721
+ interface FunctionInvokeOptions {
722
+ /**
723
+ * The body of the request: a JSON-serializable value, or any fetch
724
+ * BodyInit (FormData, Blob, string, ...)
725
+ */
726
+ body?: BodyInit | JsonRequestBody;
727
+ /**
728
+ * Custom headers to send with the request
729
+ */
730
+ headers?: Record<string, string>;
731
+ /**
732
+ * HTTP method (default: POST)
733
+ */
734
+ method?: "GET" | "POST" | "PUT" | "PATCH" | "DELETE";
735
+ }
736
+ /**
737
+ * Edge Functions client for invoking serverless functions.
738
+ *
739
+ * @example
740
+ * ```typescript
741
+ * const { data, error } = await client.functions.invoke('hello-world', {
742
+ * body: { name: 'World' }
743
+ * });
744
+ * ```
745
+ */
746
+ declare class Functions {
747
+ private http;
748
+ private functionsUrl;
749
+ constructor(http: HttpClient, functionsUrl?: string);
750
+ /**
751
+ * Derive the subhosting URL from the base URL.
752
+ * Rewrites the backend base URL to its functions subhosting URL
753
+ * ({appKey}.{region}.<domain> -> {appKey}.functions.<domain>).
754
+ * Only applies to platform-hosted backends.
755
+ */
756
+ private static deriveSubhostingUrl;
757
+ /**
758
+ * Build a Request for in-process dispatch. The host is a non-routable
759
+ * placeholder; the router only reads pathname.
760
+ */
761
+ private buildInProcessRequest;
762
+ /**
763
+ * Invoke an Edge Function.
764
+ *
765
+ * Dispatch order:
766
+ * 1. If the platform's in-process dispatch hook is present, call it directly.
767
+ * This avoids Deno Subhosting's 508 Loop Detected when one bundled
768
+ * function invokes another inside the same deployment.
769
+ * 2. Otherwise, try the configured subhosting URL.
770
+ * 3. On 404 from subhosting, fall back to the proxy path.
771
+ *
772
+ * @param slug The function slug to invoke
773
+ * @param options Request options
774
+ */
775
+ invoke<T = any>(slug: string, options?: FunctionInvokeOptions): Promise<{
776
+ data: T | null;
777
+ error: ResultError | null;
778
+ }>;
779
+ }
780
+
781
+ type ConnectionState = "disconnected" | "connecting" | "connected";
782
+ type EventCallback<T = unknown> = (payload: T) => void;
783
+ /**
784
+ * Socket.IO realtime client. Authentication is evaluated for every handshake,
785
+ * while an established socket remains authenticated until it disconnects.
786
+ */
787
+ declare class Realtime {
788
+ private baseUrl;
789
+ private tokenManager;
790
+ private anonKey?;
791
+ private getValidAccessToken;
792
+ private socket;
793
+ private connectPromise;
794
+ private connectionAttempt;
795
+ private nextConnectionAttemptId;
796
+ private subscriptions;
797
+ private eventListeners;
798
+ constructor(baseUrl: string, tokenManager: TokenManager, anonKey?: string | undefined, getValidAccessToken?: () => Promise<string | null>);
799
+ private notifyListeners;
800
+ private getHandshakeToken;
801
+ connect(): Promise<void>;
802
+ disconnect(): void;
803
+ private reconnectForAuthChange;
804
+ private handleDisconnect;
805
+ private resubscribeChannels;
806
+ private requestSubscription;
807
+ private settleSubscription;
808
+ private applyPresenceEvent;
809
+ get isConnected(): boolean;
810
+ get connectionState(): ConnectionState;
811
+ get socketId(): string | undefined;
812
+ subscribe(channel: string): Promise<SubscribeResponse>;
813
+ unsubscribe(channel: string): void;
814
+ publish<T = unknown>(channel: string, event: string, payload: T): Promise<void>;
815
+ on<T = SocketMessage>(event: string, callback: EventCallback<T>): void;
816
+ off<T = SocketMessage>(event: string, callback: EventCallback<T>): void;
817
+ once<T = SocketMessage>(event: string, callback: EventCallback<T>): void;
818
+ getSubscribedChannels(): string[];
819
+ getPresenceState(channel: string): PresenceMember[];
820
+ }
821
+
822
+ /**
823
+ * Storage module for Result SDK
824
+ * Handles file uploads, downloads, and bucket management
825
+ */
826
+
827
+ interface StorageResponse<T> {
828
+ data: T | null;
829
+ error: ResultError | null;
830
+ }
831
+ /**
832
+ * Storage bucket operations
833
+ */
834
+ declare class StorageBucket {
835
+ private bucketName;
836
+ private http;
837
+ constructor(bucketName: string, http: HttpClient);
838
+ /**
839
+ * Upload a file to a specific key.
840
+ * Uses the upload strategy from the backend (direct or presigned).
841
+ * Standard PUT semantics: uploading to an existing key replaces the
842
+ * current object in place.
843
+ * @param path - The object key/path
844
+ * @param file - File or Blob to upload
845
+ */
846
+ upload(path: string, file: File | Blob): Promise<StorageResponse<StorageFileSchema>>;
847
+ /**
848
+ * Upload a file under an automatically generated, collision-free key.
849
+ * The key is derived client-side from the filename (sanitized base +
850
+ * timestamp + random suffix) and uploaded through the standard
851
+ * {@link upload} path, so repeated uploads of the same file never
852
+ * overwrite each other. Reads the filename structurally to avoid assuming
853
+ * a global `File` (which Node 18 does not expose).
854
+ * @param file - File or Blob to upload
855
+ */
856
+ uploadAuto(file: File | Blob): Promise<StorageResponse<StorageFileSchema>>;
857
+ /**
858
+ * Internal method to handle presigned URL uploads
859
+ */
860
+ private uploadWithPresignedUrl;
861
+ /**
862
+ * Download a file
863
+ * Uses the download strategy from backend (direct or presigned)
864
+ * @param path - The object key/path
865
+ * Returns the file as a Blob
866
+ */
867
+ download(path: string): Promise<{
868
+ data: Blob | null;
869
+ error: ResultError | null;
870
+ }>;
871
+ /**
872
+ * Get the public URL for an object in a public bucket.
873
+ *
874
+ * Pure string construction — no network call, no auth. The URL only resolves
875
+ * if the bucket is public; for private objects use {@link createSignedUrl}.
876
+ *
877
+ * @param path - The object key/path
878
+ * @returns `{ data: { publicUrl }, error }` — matches the external SDK pattern,
879
+ * so `const { data } = getPublicUrl(path)` then `data.publicUrl`.
880
+ */
881
+ getPublicUrl(path: string): StorageResponse<{
882
+ publicUrl: string;
883
+ }>;
884
+ /**
885
+ * Resolve a download strategy (signed or direct URL) for an object with a
886
+ * caller-supplied TTL. Prefers the canonical GET route and falls back to the
887
+ * legacy POST alias so signed-URL creation still works against older backends
888
+ * that predate the GET route (they return 404/405 for it). A genuine
889
+ * "object not found" (STORAGE_NOT_FOUND) is not retried.
890
+ */
891
+ private requestDownloadStrategy;
892
+ /**
893
+ * Create a signed URL for an object.
894
+ *
895
+ * Returns a time-limited, credential-free URL that can be handed directly to
896
+ * a browser (`<img src>`), an email, or a third party — no SDK or session is
897
+ * needed to fetch it. Authorization is enforced when the URL is minted (the
898
+ * caller must be allowed to read the object), so the resulting link is a
899
+ * pre-authorized capability scoped to this one object until it expires.
900
+ *
901
+ * @param path - The object key/path
902
+ * @param expiresIn - Lifetime in seconds (default 3600 = 1h, max 604800 = 7d).
903
+ * Honored for private buckets; public buckets return their long-lived URL.
904
+ */
905
+ createSignedUrl(path: string, expiresIn?: number): Promise<StorageResponse<{
906
+ signedUrl: string;
907
+ expiresAt: string | null;
908
+ }>>;
909
+ /**
910
+ * Create signed URLs for multiple objects in a single call.
911
+ *
912
+ * Each entry resolves independently: a failure on one key (not found / not
913
+ * permitted) is reported on that entry's `error` without failing the rest.
914
+ *
915
+ * @param paths - The object keys/paths
916
+ * @param expiresIn - Lifetime in seconds (default 3600 = 1h, max 604800 = 7d)
917
+ */
918
+ createSignedUrls(paths: string[], expiresIn?: number): Promise<StorageResponse<Array<{
919
+ path: string;
920
+ signedUrl: string | null;
921
+ error: string | null;
922
+ }>>>;
923
+ /**
924
+ * List objects in the bucket
925
+ * @param prefix - Filter by key prefix
926
+ * @param search - Search in file names
927
+ * @param limit - Maximum number of results (default: 100, max: 1000)
928
+ * @param offset - Number of results to skip
929
+ */
930
+ list(options?: {
931
+ prefix?: string;
932
+ search?: string;
933
+ limit?: number;
934
+ offset?: number;
935
+ }): Promise<StorageResponse<ListObjectsResponseSchema>>;
936
+ /** Delete a single file. */
937
+ remove(path: string): Promise<StorageResponse<{
938
+ message: string;
939
+ }>>;
940
+ /** Delete multiple files in a single request. */
941
+ remove(paths: string[]): Promise<StorageResponse<DeleteObjectsResponse>>;
942
+ /** Delete one or more files when the input type is not narrowed. */
943
+ remove(pathOrPaths: string | string[]): Promise<StorageResponse<{
944
+ message: string;
945
+ } | DeleteObjectsResponse>>;
946
+ }
947
+ /**
948
+ * Storage module for file operations
949
+ */
950
+ declare class Storage {
951
+ private http;
952
+ constructor(http: HttpClient);
953
+ /**
954
+ * Get a bucket instance for operations
955
+ * @param bucketName - Name of the bucket
956
+ */
957
+ from(bucketName: string): StorageBucket;
958
+ }
959
+
960
+ type AccessTokenChangeEvent = typeof AuthChangeEvent.SIGNED_IN | typeof AuthChangeEvent.TOKEN_REFRESHED;
961
+ /**
962
+ * Main Result SDK Client
963
+ *
964
+ * @example
965
+ * ```typescript
966
+ * import { ResultClient } from '@resultdev/sdk';
967
+ *
968
+ * const client = new ResultClient({
969
+ * baseUrl: 'http://localhost:7130'
970
+ * });
971
+ *
972
+ * // Authentication
973
+ * const { data, error } = await client.auth.signUp({
974
+ * email: 'user@example.com',
975
+ * password: 'password123',
976
+ * name: 'John Doe'
977
+ * });
978
+ *
979
+ * // Database operations
980
+ * const { data, error } = await client.database
981
+ * .from('posts')
982
+ * .select('*')
983
+ * .eq('user_id', session.user.id)
984
+ * .order('created_at', { ascending: false })
985
+ * .limit(10);
986
+ *
987
+ * // Insert data
988
+ * const { data: newPost } = await client.database
989
+ * .from('posts')
990
+ * .insert({ title: 'Hello', content: 'World' })
991
+ * .single();
992
+ *
993
+ * // Invoke edge functions
994
+ * const { data, error } = await client.functions.invoke('my-function', {
995
+ * body: { message: 'Hello from SDK' }
996
+ * });
997
+ *
998
+ * // Enable debug logging
999
+ * const debugClient = new ResultClient({
1000
+ * baseUrl: 'http://localhost:7130',
1001
+ * debug: true
1002
+ * });
1003
+ * ```
1004
+ */
1005
+ declare class ResultClient {
1006
+ private http;
1007
+ private tokenManager;
1008
+ readonly auth: Auth;
1009
+ readonly database: Database;
1010
+ readonly storage: Storage;
1011
+ readonly ai: AI;
1012
+ readonly functions: Functions;
1013
+ readonly realtime: Realtime;
1014
+ readonly emails: Emails;
1015
+ readonly analytics: Analytics;
1016
+ readonly support: Support;
1017
+ constructor(config?: ResultConfig);
1018
+ /**
1019
+ * Get the underlying HTTP client for custom requests
1020
+ *
1021
+ * @example
1022
+ * ```typescript
1023
+ * const httpClient = client.getHttpClient();
1024
+ * const customData = await httpClient.get('/api/custom-endpoint');
1025
+ * ```
1026
+ */
1027
+ getHttpClient(): HttpClient;
1028
+ /**
1029
+ * Set the access token used by every SDK surface. Updates both the HTTP
1030
+ * client (database / storage / functions / AI / emails) and the realtime
1031
+ * token manager. Pass `null` to sign out. By default a token replacement is
1032
+ * treated as a sign-in boundary and reconnects realtime. Pass
1033
+ * `AuthChangeEvent.TOKEN_REFRESHED` for a same-identity refresh to preserve a live socket; the
1034
+ * refreshed token is then used at the next handshake.
1035
+ *
1036
+ * Use this when an external auth provider (Better Auth, Clerk, Auth0,
1037
+ * WorkOS, Kinde, Stytch, …) issues the JWT and you need to keep the
1038
+ * long-lived Result client in sync. Without this, you'd have to call
1039
+ * `client.getHttpClient().setAuthToken(token)` AND reach into the private
1040
+ * realtime token manager separately.
1041
+ *
1042
+ * @example
1043
+ * ```typescript
1044
+ * import { AuthChangeEvent } from '@resultdev/sdk';
1045
+ *
1046
+ * // Refresh a third-party-issued JWT periodically
1047
+ * const { token } = await fetch('/api/backend-token').then((r) => r.json());
1048
+ * client.setAccessToken(token, AuthChangeEvent.TOKEN_REFRESHED);
1049
+ *
1050
+ * // Sign-out
1051
+ * client.setAccessToken(null);
1052
+ * ```
1053
+ */
1054
+ setAccessToken(token: string | null, event?: AccessTokenChangeEvent): void;
1055
+ }
1056
+
1057
+ export { AI as A, type ChatCompletion as C, Database as D, Emails as E, type FunctionInvokeOptions as F, HttpClient as H, type ImageGenerationResult as I, Logger as L, ResultClient as R, Storage as S, type AccessTokenChangeEvent as a, Auth as b, AuthChangeEvent as c, type AuthStateChangeCallback as d, type ChatCompletionChoice as e, type ChatCompletionChunk as f, type ChatCompletionUsage as g, type ConnectionState as h, type EmbeddingsResult as i, type EventCallback as j, Functions as k, Realtime as l, StorageBucket as m, type StorageResponse as n };