UNPKG

@e-techsolutions/e-baas-sdk

Version:

Official E-BaaS TypeScript SDK - Backend as a Service client library

893 lines (871 loc) 26.9 kB
import { AxiosRequestConfig } from 'axios'; interface HttpClientConfig { url: string; apiKey: string; timeout?: number; headers?: Record<string, string>; } interface ApiResponse<T = any> { data: T; status: number; statusText: string; headers: any; } declare class HttpClient { private client; private baseURL; private apiKey; constructor(config: HttpClientConfig); private setupInterceptors; get<T = any>(url: string, config?: AxiosRequestConfig): Promise<ApiResponse<T>>; post<T = any>(url: string, data?: any, config?: AxiosRequestConfig): Promise<ApiResponse<T>>; put<T = any>(url: string, data?: any, config?: AxiosRequestConfig): Promise<ApiResponse<T>>; patch<T = any>(url: string, data?: any, config?: AxiosRequestConfig): Promise<ApiResponse<T>>; delete<T = any>(url: string, config?: AxiosRequestConfig): Promise<ApiResponse<T>>; getBaseUrl(): string; setAuthToken(token: string): void; removeAuthToken(): void; private handleError; } declare class EBaaSError extends Error { readonly status: number; readonly details?: any; constructor(message: string, status?: number, details?: any); toJSON(): { name: string; message: string; status: number; details: any; stack: string | undefined; }; toString(): string; } interface CustomDatabaseCredentials { host: string; port: number; database: string; username: string; password: string; schema?: string; sslEnabled?: boolean; } interface EBaaSClientOptions { supabaseUrl: string; supabaseKey: string; options?: { auth?: { autoRefreshToken?: boolean; persistSession?: boolean; detectSessionInUrl?: boolean; }; realtime?: { params?: Record<string, string>; }; global?: { headers?: Record<string, string>; }; database?: { customCredentials?: CustomDatabaseCredentials; autoDetectCustomDatabase?: boolean; workspaceId?: string; }; functions?: { defaultUnwrap?: boolean; }; rest?: { url?: string; }; }; } interface DatabaseFilters { eq?: any; neq?: any; gt?: any; gte?: any; lt?: any; lte?: any; like?: string; ilike?: string; is?: any; in?: any[]; contains?: any; contained_by?: any; range_gt?: any; range_gte?: any; range_lt?: any; range_lte?: any; range_adjacent?: any; overlaps?: any; text_search?: string; match?: Record<string, any>; } interface QueryOptions { count?: 'exact' | 'planned' | 'estimated'; head?: boolean; } interface SelectOptions extends QueryOptions { columns?: string; } interface InsertOptions extends QueryOptions { returning?: 'minimal' | 'representation'; upsert?: boolean; onConflict?: string; } interface UpdateOptions extends QueryOptions { returning?: 'minimal' | 'representation'; } interface DeleteOptions extends QueryOptions { returning?: 'minimal' | 'representation'; } interface AuthUser { id: string; email: string; phone?: string; name?: string; avatar_url?: string; created_at: string; updated_at: string; email_verified: boolean; phone_verified: boolean; app_metadata?: Record<string, any>; user_metadata?: Record<string, any>; } interface AuthSession { access_token: string; refresh_token: string; expires_in: number; expires_at: number; token_type: string; user: AuthUser; created_at?: number; client_fingerprint?: string; } interface AuthResponse { user?: AuthUser; session?: AuthSession; error?: string; } interface SignUpData { email: string; password: string; name?: string; phone?: string; metadata?: Record<string, any>; firstName?: string; lastName?: string; workspaceId?: string; autoSignIn?: boolean; } interface SignInData { email: string; password: string; } interface OAuthProvider { provider: 'google' | 'github' | 'facebook'; redirectTo?: string; scopes?: string; } declare class AuthClient { private httpClient; private currentSession; private workspaceId?; constructor(httpClient: HttpClient, workspaceId?: string); signUp(data: SignUpData): Promise<AuthResponse>; signIn(data: SignInData): Promise<AuthResponse>; signOut(): Promise<void>; getUser(): Promise<AuthUser | null>; refreshSession(): Promise<AuthSession | null>; resetPassword(email: string): Promise<void>; updateUser(data: Partial<AuthUser>): Promise<AuthUser>; getSession(): AuthSession | null; setSession(session: AuthSession): void; onAuthStateChange(callback: (event: string, session: AuthSession | null) => void): () => void; /** * Atualiza o workspace ID (útil quando o usuário troca de workspace) */ setWorkspaceId(workspaceId: string): void; private buildSignUpPayload; private resolveNamesFromMetadata; private getStringValue; private setSessionInternal; private clearSession; private loadSession; private handleAuthError; } /** * Returns session expiration as milliseconds timestamp. * Handles both seconds and milliseconds formats from the API. */ declare function getExpiresAtMs(session: AuthSession): number; interface CustomDatabaseConfig { id: string; postgresHost: string; postgresPort: number; postgresDatabase: string; postgresUsername: string; postgresSchema: string; sslEnabled: boolean; lastConnectionTest: string; isActive: boolean; } interface CustomDatabaseDetectionResult { hasCustomDatabase: boolean; config?: CustomDatabaseConfig; credentials?: CustomDatabaseCredentials; } declare class CustomDatabaseManager { private httpClient; private workspaceId?; private detectedConfig?; constructor(httpClient: HttpClient, workspaceId?: string); /** * Detecta automaticamente se o workspace usa banco customizado */ detectCustomDatabase(): Promise<CustomDatabaseDetectionResult>; /** * Testa conexão com banco customizado */ testConnection(credentials: CustomDatabaseCredentials): Promise<{ success: boolean; message: string; }>; /** * Configura credenciais customizadas para o workspace */ configureCustomDatabase(credentials: CustomDatabaseCredentials): Promise<CustomDatabaseConfig>; /** * Remove configuração de banco customizado */ removeCustomDatabase(): Promise<void>; /** * Retorna a configuração detectada em cache */ getDetectedConfig(): CustomDatabaseDetectionResult | undefined; /** * Verifica se tem configuração customizada em cache */ hasCustomDatabase(): boolean; /** * Retorna as credenciais customizadas se disponíveis */ getCustomCredentials(): CustomDatabaseCredentials | undefined; /** * Atualiza o workspace ID */ setWorkspaceId(workspaceId: string): void; /** * Retorna o workspace ID atual */ getWorkspaceId(): string | undefined; /** * Retorna informações sobre o status do banco customizado */ getStatus(): { workspaceId?: string; hasConfig: boolean; lastDetection?: Date; configDetails?: { host: string; port: number; database: string; schema: string; sslEnabled: boolean; }; }; } declare class QueryBuilder<T = any> { private httpClient; private table; private schema?; private workspaceId?; private restUrl; private query; constructor(httpClient: HttpClient, table: string, schema?: string, workspaceId?: string, restUrl?: string); select(columns?: string, options?: SelectOptions): this; insert(data: Partial<T> | Partial<T>[], options?: InsertOptions): this; update(data: Partial<T>, options?: UpdateOptions): this; upsert(data: Partial<T> | Partial<T>[], options?: InsertOptions): Promise<{ data: T[] | null; error: EBaaSError | null; }>; delete(options?: DeleteOptions): this; eq(column: string, value: any): this; neq(column: string, value: any): this; gt(column: string, value: any): this; gte(column: string, value: any): this; lt(column: string, value: any): this; lte(column: string, value: any): this; like(column: string, pattern: string): this; ilike(column: string, pattern: string): this; is(column: string, value: any): this; in(column: string, values: any[]): this; contains(column: string, value: any): this; match(query: Record<string, any>): this; order(column: string, options?: { ascending?: boolean; }): this; limit(count: number): this; range(from: number, to: number): this; execute(): Promise<{ data: T[] | null; error: EBaaSError | null; count?: number; }>; then<TResult1 = { data: T[] | null; error: EBaaSError | null; count?: number; }, TResult2 = never>(onfulfilled?: ((value: { data: T[] | null; error: EBaaSError | null; count?: number; }) => TResult1 | PromiseLike<TResult1>) | null, onrejected?: ((reason: any) => TResult2 | PromiseLike<TResult2>) | null): Promise<TResult1 | TResult2>; single(): Promise<{ data: T | null; error: EBaaSError | null; }>; private executeQuery; } declare class DatabaseClient { private httpClient; private customDatabaseManager; private currentSchema?; private restUrl; constructor(httpClient: HttpClient, workspaceId?: string, restUrl?: string); from(table: string): QueryBuilder; rpc(fn: string, args?: Record<string, any>): Promise<any>; schema(schema: string): DatabaseClient; /** * Detecta automaticamente se o workspace usa banco customizado */ detectCustomDatabase(): Promise<CustomDatabaseDetectionResult>; /** * Testa conexão com credenciais customizadas */ testCustomConnection(credentials: CustomDatabaseCredentials): Promise<{ success: boolean; message: string; }>; /** * Configura banco customizado para o workspace */ configureCustomDatabase(credentials: CustomDatabaseCredentials): Promise<CustomDatabaseConfig>; /** * Remove configuração de banco customizado */ removeCustomDatabase(): Promise<void>; /** * Verifica se o workspace está usando banco customizado */ isUsingCustomDatabase(): boolean; /** * Retorna informações sobre o banco customizado */ getCustomDatabaseStatus(): { workspaceId?: string; hasConfig: boolean; lastDetection?: Date; configDetails?: { host: string; port: number; database: string; schema: string; sslEnabled: boolean; }; }; /** * Atualiza o workspace ID (útil quando o usuário troca de workspace) */ setWorkspaceId(workspaceId: string): void; /** * Inicializa a detecção automática do banco customizado * Deve ser chamado após a autenticação se autoDetectCustomDatabase estiver habilitado */ initialize(): Promise<void>; } interface StorageFile { id: string; name: string; path: string; bucket: string; size: number; mimeType: string; etag: string; createdAt: string; updatedAt: string; metadata?: Record<string, any>; version?: string; cacheControl?: string; owner?: string; isPublic?: boolean; lastAccessed?: string; accessCount?: number; humanSize?: string; extension?: string; isImage?: boolean; isVideo?: boolean; isAudio?: boolean; isDocument?: boolean; } interface Bucket { id: string; name: string; workspaceId: string; visibility: 'public' | 'private'; description?: string; allowedMimeTypes?: string[]; maxFileSize?: number; enableVersioning: boolean; enableCors: boolean; corsOrigins?: string[]; filesCount: number; totalSize: number; createdBy?: string; isActive: boolean; createdAt: string; updatedAt: string; storageUsed?: number; fileCount?: number; } interface BucketOptions { visibility?: 'public' | 'private'; public?: boolean; description?: string; allowedMimeTypes?: string[]; maxFileSize?: number; fileSizeLimit?: number; enableVersioning?: boolean; versioningEnabled?: boolean; enableCors?: boolean; corsOrigins?: string[]; } interface StorageUploadOptions { cacheControl?: string; contentType?: string; upsert?: boolean; metadata?: Record<string, any>; expiresIn?: number; duplex?: 'half'; } interface StorageDownloadOptions { transform?: { width?: number; height?: number; resize?: 'cover' | 'contain' | 'fill' | 'inside' | 'outside'; format?: 'jpeg' | 'png' | 'webp' | 'avif'; quality?: number; }; } interface StorageListOptions { limit?: number; offset?: string; sortBy?: Array<{ column: string; order?: 'asc' | 'desc'; }>; search?: string; } interface StorageSignedUrlOptions { operation?: 'upload' | 'download' | 'delete' | 'update'; expiresIn?: number; } interface FileUploadResponse { id: string; path: string; fullPath: string; metadata: StorageFile; signedUrl?: string; } interface FileListResponse { files: StorageFile[]; hasMore: boolean; nextOffset?: string; totalCount?: number; } interface SignedUrlResponse { signedUrl: string; token: string; expiresAt: string; operation: 'upload' | 'download' | 'delete' | 'update'; } interface PublicUrlResponse { data: { publicUrl: string; }; } interface StorageUsage { workspaceId: string; totalBuckets: number; totalFiles: number; totalSize: number; buckets: Array<{ name: string; filesCount: number; size: number; }>; } declare class StorageBucket { private httpClient; private bucketId; private workspaceId?; constructor(httpClient: HttpClient, bucketId: string, workspaceId?: string); setWorkspaceId(workspaceId: string): void; private getWorkspaceHeaders; private normalizePath; private encodePath; private extractPathParts; private serializeTransform; private appendFileToFormData; upload(path: string, file: File | Blob | ArrayBuffer | string, options?: StorageUploadOptions): Promise<{ data: FileUploadResponse | null; error: EBaaSError | null; }>; download(path: string, options?: StorageDownloadOptions): Promise<{ data: Blob | null; error: EBaaSError | null; }>; list(prefix?: string, options?: StorageListOptions): Promise<{ data: FileListResponse | null; error: EBaaSError | null; }>; remove(paths: string[]): Promise<{ data: { message: string; } | null; error: EBaaSError | null; }>; move(_fromPath: string, _toPath: string): Promise<{ data: { message: string; } | null; error: EBaaSError | null; }>; copy(_fromPath: string, _toPath: string): Promise<{ data: { message: string; } | null; error: EBaaSError | null; }>; createSignedUrl(path: string, expiresIn: number, options?: StorageSignedUrlOptions): Promise<{ data: SignedUrlResponse | null; error: EBaaSError | null; }>; getPublicUrl(path: string, options?: { transform?: Record<string, any>; }): PublicUrlResponse; getFileInfo(_path: string): Promise<{ data: StorageFile | null; error: EBaaSError | null; }>; updateFileMetadata(_path: string, _metadata: Record<string, any>): Promise<{ data: StorageFile | null; error: EBaaSError | null; }>; } declare class StorageClient { private httpClient; private workspaceId?; constructor(httpClient: HttpClient, workspaceId?: string); from(bucketId: string): StorageBucket; setWorkspaceId(workspaceId: string): void; private getWorkspaceHeaders; private mapBucketOptions; createBucket(id: string, options?: BucketOptions): Promise<{ data: Bucket | null; error: EBaaSError | null; }>; getBucket(id: string): Promise<{ data: Bucket | null; error: EBaaSError | null; }>; listBuckets(): Promise<{ data: Bucket[] | null; error: EBaaSError | null; }>; updateBucket(id: string, options: Partial<BucketOptions>): Promise<{ data: Bucket | null; error: EBaaSError | null; }>; deleteBucket(id: string): Promise<{ data: { message: string; } | null; error: EBaaSError | null; }>; getUsage(): Promise<{ data: StorageUsage | null; error: EBaaSError | null; }>; } type EventCallback = (...args: any[]) => void; declare class EventManager { private events; on(event: string, callback: EventCallback): void; off(event: string, callback?: EventCallback): void; emit(event: string, ...args: any[]): boolean; removeAllListeners(event?: string): void; listenerCount(event: string): number; eventNames(): string[]; listeners(event: string): EventCallback[]; addListener(event: string, callback: EventCallback): void; removeListener(event: string, callback: EventCallback): void; once(event: string, callback: EventCallback): void; prependListener(event: string, callback: EventCallback): void; prependOnceListener(event: string, callback: EventCallback): void; private maxListeners; setMaxListeners(max: number): this; getMaxListeners(): number; rawListeners(event: string): EventCallback[]; } interface RealtimeEvent { schema: string; table: string; commit_timestamp: string; eventType: 'INSERT' | 'UPDATE' | 'DELETE'; new?: Record<string, any>; old?: Record<string, any>; errors?: string[]; } interface ChannelSubscription { unsubscribe: () => void; } interface PresenceState { [key: string]: { metas: Array<{ [key: string]: any; phx_ref: string; phx_ref_prev?: string; }>; }; } interface PostgresChangesFilter { event: '*' | 'INSERT' | 'UPDATE' | 'DELETE'; schema: string; table?: string; filter?: string; } interface BroadcastFilter { event: string; } interface PresenceFilter { event: 'sync' | 'join' | 'leave'; } type ChannelState = 'closed' | 'errored' | 'joined' | 'joining' | 'leaving'; type RealtimeConnectionState = 'connecting' | 'connected' | 'disconnected' | 'error'; interface RealtimeClientOptions { heartbeatInterval?: number; reconnectInterval?: number; maxReconnectAttempts?: number; socketOptions?: { [key: string]: any; }; } declare class RealtimeChannel extends EventManager { topic: string; private socket; private joinedOnce; private state; private subscriptions; constructor(topic: string, socket: any); subscribe(callback?: (status: 'SUBSCRIBED' | 'CHANNEL_ERROR' | 'TIMED_OUT' | 'CLOSED') => void): RealtimeChannel; onPostgresChanges(filter: PostgresChangesFilter, callback: (payload: RealtimeEvent) => void): ChannelSubscription; onBroadcast(filter: BroadcastFilter, callback: (payload: any) => void): ChannelSubscription; onPresence(filter: PresenceFilter, callback: (payload: PresenceState) => void): ChannelSubscription; send(payload: { type: 'broadcast'; event: string; [key: string]: any; }): Promise<'ok' | 'error' | 'timeout'>; track(payload: Record<string, any>): Promise<'ok' | 'error' | 'timeout'>; untrack(): Promise<'ok' | 'error' | 'timeout'>; unsubscribe(): Promise<'ok' | 'error' | 'timeout'>; _join(): void; _rejoin(): void; _trigger(event: string, payload: any): void; _setState(state: ChannelState): void; private makeRef; getState(): ChannelState; } declare class RealtimeClient { private socketAdapter; private socket; private url; private apiKey; private options; private channels; private connectionState; private reconnectAttempts; private maxReconnectAttempts; constructor(url: string, apiKey: string, options?: RealtimeClientOptions); connect(): Promise<void>; disconnect(): void; channel(topic: string): RealtimeChannel; removeChannel(channel: RealtimeChannel): void; removeAllChannels(): void; getChannels(): RealtimeChannel[]; isConnected(): boolean; getConnectionState(): RealtimeConnectionState; onConnectionStateChange(callback: (state: RealtimeConnectionState) => void): () => void; private setupHeartbeat; _getSocket(): any; } interface FunctionInvokeOptions { method?: 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE'; headers?: Record<string, string>; body?: any; region?: string; unwrap?: boolean; } interface FunctionResponse<T = any> { data: T; error?: string; } interface EdgeFunction { id: string; name: string; slug: string; status: 'active' | 'inactive' | 'deploying' | 'failed'; version: number; created_at: string; updated_at: string; entrypoint?: string; env?: Record<string, string>; import_map?: Record<string, any>; verify_jwt?: boolean; execution_stats?: { total_executions: number; total_errors: number; avg_execution_time: number; last_execution: string; }; } interface FunctionListResponse { functions: EdgeFunction[]; count: number; } interface FunctionDeployOptions { code: string | File; entrypoint?: string; env?: Record<string, string>; importMap?: Record<string, any>; verify?: boolean; } interface FunctionDeployResponse { id: string; name: string; version: number; status: 'deploying' | 'active' | 'failed'; deployment_id: string; created_at: string; } declare class FunctionsClient { private httpClient; private workspaceId?; private defaultUnwrap; constructor(httpClient: HttpClient, workspaceId?: string, defaultUnwrap?: boolean); setWorkspaceId(workspaceId: string): void; invoke<T = any>(functionName: string, options?: FunctionInvokeOptions): Promise<{ data: T | null; error: EBaaSError | null; }>; invokeExternal<T = any>(functionName: string, options: { workspaceId: string; apiKey: string; body?: any; method?: string; unwrap?: boolean; }): Promise<{ data: T | null; error: EBaaSError | null; }>; list(): Promise<{ data: FunctionListResponse | null; error: EBaaSError | null; }>; get(functionName: string): Promise<{ data: EdgeFunction | null; error: EBaaSError | null; }>; deploy(functionName: string, options: FunctionDeployOptions): Promise<{ data: FunctionDeployResponse | null; error: EBaaSError | null; }>; delete(functionName: string): Promise<{ data: { message: string; } | null; error: EBaaSError | null; }>; updateEnv(functionName: string, env: Record<string, string>): Promise<{ data: EdgeFunction | null; error: EBaaSError | null; }>; getLogs(functionName: string, options?: { limit?: number; offset?: number; level?: 'info' | 'warn' | 'error' | 'debug'; }): Promise<{ data: any[] | null; error: EBaaSError | null; }>; getMetrics(functionName: string, options?: { period?: '1h' | '24h' | '7d' | '30d'; }): Promise<{ data: any | null; error: EBaaSError | null; }>; } declare class EBaaSClient { readonly auth: AuthClient; readonly database: DatabaseClient; readonly storage: StorageClient; readonly realtime: RealtimeClient; readonly functions: FunctionsClient; private httpClient; private options?; constructor(supabaseUrl: string, supabaseKey: string, options?: EBaaSClientOptions['options']); from(table: string): QueryBuilder<any>; rpc(fn: string, args?: Record<string, any>): Promise<any>; bucket(id: string): StorageBucket; channel(name: string): RealtimeChannel; invoke(functionName: string, options?: any): Promise<{ data: any; error: EBaaSError | null; }>; /** * Creates a new EBaaSClient instance configured for a different workspace. * Reuses the same base URL. */ forWorkspace(workspaceId: string, apiKey: string): EBaaSClient; /** * Inicializa a detecção automática de banco customizado */ private initializeCustomDatabase; /** * Atualiza o workspace ID para todos os módulos que precisam */ setWorkspaceId(workspaceId: string): Promise<void>; /** * Configura credenciais customizadas diretamente */ configureCustomDatabase(credentials: CustomDatabaseCredentials): Promise<void>; /** * Retorna informações sobre o banco customizado */ getCustomDatabaseStatus(): { workspaceId?: string; hasConfig: boolean; lastDetection?: Date; configDetails?: { host: string; port: number; database: string; schema: string; sslEnabled: boolean; }; }; } declare function createClient(supabaseUrl: string, supabaseKey: string, options?: EBaaSClientOptions['options']): EBaaSClient; declare const version = "1.3.0"; export { AuthClient, CustomDatabaseManager, DatabaseClient, EBaaSClient, EBaaSError, FunctionsClient, HttpClient, QueryBuilder, RealtimeChannel, RealtimeClient, StorageBucket, StorageClient, createClient, getExpiresAtMs, version }; export type { AuthResponse, AuthSession, AuthUser, BroadcastFilter, Bucket, BucketOptions, ChannelSubscription, CustomDatabaseConfig, CustomDatabaseCredentials, CustomDatabaseDetectionResult, DatabaseFilters, DeleteOptions, EBaaSClientOptions, EdgeFunction, FunctionDeployOptions, FunctionInvokeOptions, FunctionListResponse, FunctionResponse, InsertOptions, OAuthProvider, PostgresChangesFilter, PresenceFilter, PresenceState, QueryOptions, RealtimeClientOptions, RealtimeEvent, SelectOptions, SignInData, SignUpData, StorageDownloadOptions, StorageFile, StorageListOptions, StorageUploadOptions, StorageUsage, UpdateOptions };