@snackbase/sdk 0.1.1 → 0.3.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.mts CHANGED
@@ -1,2 +1,2447 @@
1
- import { $ as AuditLogFilters, A as EmailTemplateRenderResponse, At as OAuthCallbackParams, B as SystemHealth, Bt as SAMLUrlResponse, C as FileUploadOptions, Ct as FieldDefinition, D as EmailTemplate, Dt as AuthResponse, E as EmailLogListResponse, Et as AuthEvents, F as ConfigurationStats, Ft as PasswordResetRequest, G as RoleCreate, Gt as UserUpdate, H as CollectionRuleUpdate, Ht as UserCreate, I as ConnectionTestResult, It as RegisterData, J as RuleTestResult, Jt as LogLevel, K as RoleListResponse, Kt as Account, L as ProviderDefinition, Lt as SAMLCallbackParams, M as EmailTemplateUpdate, Mt as OAuthResponse, N as Configuration, Nt as OAuthUrlResponse, O as EmailTemplateFilters, Ot as AuthState, P as ConfigurationCreate, Pt as PasswordResetConfirm, Q as AuditLogExportFormat, R as RecentConfiguration, Rt as SAMLProvider, S as FileMetadata, St as CollectionUpdate, T as EmailLogFilters, Tt as AuthEvent, U as Permission, Ut as UserListParams, V as CollectionRule, Vt as User, W as Role, Wt as UserListResponse, X as RuleValidationResult, Xt as StorageBackend, Y as RuleValidationParams, Yt as SnackBaseConfig, Z as AuditLog, _ as RealTimeState, _t as BaseRecord, a as InferSchema, at as InvitationListParams, b as WebSocketAction, bt as Collection, c as CurrentRevisionResponse, ct as GroupListParams, d as MigrationListResponse, dt as QueryBuilder, et as AuditLogListResponse, f as MigrationRevision, ft as FilterExpression, g as RealTimeEvents, gt as SortExpression, h as RealTimeEventHandler, ht as SortDirection, i as Filter, it as InvitationCreate, j as EmailTemplateType, jt as OAuthProvider, k as EmailTemplateRenderRequest, kt as LoginCredentials, l as MigrationHistoryItem, lt as GroupListResponse, m as RealTimeEvent, mt as QueryParams, n as CollectionRecord, nt as ApiKeyCreate, o as ListResponse, ot as Group, p as RealTimeConfig, pt as FilterOperator, q as RoleUpdate, qt as DEFAULT_CONFIG, r as FieldTypeToTs, rt as Invitation, s as SnackBaseClient, st as GroupCreate, t as getAutoDetectedStorage, tt as ApiKey, u as MigrationHistoryResponse, ut as GroupUpdate, v as RealtimeEvent, vt as RecordListParams, w as EmailLog, wt as FieldType, x as WebSocketMessage, xt as CollectionCreate, y as ServerMessage, yt as RecordListResponse, z as DashboardStats, zt as SAMLResponse } from "./index-Dr6K4PMl.mjs";
2
- export { Account, ApiKey, ApiKeyCreate, AuditLog, AuditLogExportFormat, AuditLogFilters, AuditLogListResponse, AuthEvent, AuthEvents, AuthResponse, AuthState, BaseRecord, Collection, CollectionCreate, CollectionRecord, CollectionRule, CollectionRuleUpdate, CollectionUpdate, Configuration, ConfigurationCreate, ConfigurationStats, ConnectionTestResult, CurrentRevisionResponse, DEFAULT_CONFIG, DashboardStats, EmailLog, EmailLogFilters, EmailLogListResponse, EmailTemplate, EmailTemplateFilters, EmailTemplateRenderRequest, EmailTemplateRenderResponse, EmailTemplateType, EmailTemplateUpdate, FieldDefinition, FieldType, FieldTypeToTs, FileMetadata, FileUploadOptions, Filter, FilterExpression, FilterOperator, Group, GroupCreate, GroupListParams, GroupListResponse, GroupUpdate, InferSchema, Invitation, InvitationCreate, InvitationListParams, ListResponse, LogLevel, LoginCredentials, MigrationHistoryItem, MigrationHistoryResponse, MigrationListResponse, MigrationRevision, OAuthCallbackParams, OAuthProvider, OAuthResponse, OAuthUrlResponse, PasswordResetConfirm, PasswordResetRequest, Permission, ProviderDefinition, QueryBuilder, QueryParams, RealTimeConfig, RealTimeEvent, RealTimeEventHandler, RealTimeEvents, RealTimeState, RealtimeEvent, RecentConfiguration, RecordListParams, RecordListResponse, RegisterData, Role, RoleCreate, RoleListResponse, RoleUpdate, RuleTestResult, RuleValidationParams, RuleValidationResult, SAMLCallbackParams, SAMLProvider, SAMLResponse, SAMLUrlResponse, ServerMessage, SnackBaseClient as SnackBase, SnackBaseClient, SnackBaseConfig, SortDirection, SortExpression, StorageBackend, SystemHealth, User, UserCreate, UserListParams, UserListResponse, UserUpdate, WebSocketAction, WebSocketMessage, getAutoDetectedStorage };
1
+ //#region src/types/config.d.ts
2
+ type LogLevel = 'debug' | 'info' | 'warn' | 'error';
3
+ type StorageBackend = 'localStorage' | 'sessionStorage' | 'memory' | 'asyncStorage';
4
+ interface SnackBaseConfig {
5
+ /**
6
+ * API base URL (required)
7
+ */
8
+ baseUrl: string;
9
+ /**
10
+ * Request timeout in milliseconds (default: 30000)
11
+ */
12
+ timeout?: number;
13
+ /**
14
+ * Optional API key for service authentication
15
+ */
16
+ apiKey?: string;
17
+ /**
18
+ * Optional override for system account detection
19
+ * (useful for testing/custom deployments)
20
+ */
21
+ systemAccountId?: string;
22
+ /**
23
+ * Enable automatic token refresh (default: true)
24
+ */
25
+ enableAutoRefresh?: boolean;
26
+ /**
27
+ * Refresh tokens N seconds before expiry (default: 300)
28
+ */
29
+ refreshBeforeExpiry?: number;
30
+ /**
31
+ * Maximum retry attempts for failed requests (default: 3)
32
+ */
33
+ maxRetries?: number;
34
+ /**
35
+ * Delay between retries in milliseconds (default: 1000)
36
+ */
37
+ retryDelay?: number;
38
+ /**
39
+ * Token storage backend.
40
+ * 'localStorage' or 'sessionStorage' for web,
41
+ * 'asyncStorage' for React Native.
42
+ * Default: auto-detect based on platform.
43
+ */
44
+ storageBackend?: StorageBackend;
45
+ /**
46
+ * Enable request/response logging (default: false in production)
47
+ */
48
+ enableLogging?: boolean;
49
+ /**
50
+ * Logging level (default: 'error')
51
+ */
52
+ logLevel?: LogLevel;
53
+ /**
54
+ * Callback for 401 authentication errors
55
+ */
56
+ onAuthError?: (error: any) => void;
57
+ /**
58
+ * Callback for network failures
59
+ */
60
+ onNetworkError?: (error: any) => void;
61
+ /**
62
+ * Callback for 429 rate limit errors
63
+ */
64
+ onRateLimitError?: (error: any) => void;
65
+ /**
66
+ * Default account slug/ID for single-tenant mode (optional)
67
+ */
68
+ defaultAccount?: string;
69
+ /**
70
+ * Maximum reconnection attempts for real-time (default: 10)
71
+ */
72
+ maxRealTimeRetries?: number;
73
+ /**
74
+ * Initial delay for real-time reconnection in milliseconds (default: 1000)
75
+ */
76
+ realTimeReconnectionDelay?: number;
77
+ }
78
+ declare const DEFAULT_CONFIG: Partial<SnackBaseConfig>;
79
+ //#endregion
80
+ //#region src/core/logger.d.ts
81
+ declare enum LogLevel$1 {
82
+ NONE = 0,
83
+ ERROR = 1,
84
+ WARN = 2,
85
+ INFO = 3,
86
+ DEBUG = 4
87
+ }
88
+ interface LogEntry {
89
+ timestamp: string;
90
+ level: LogLevel$1;
91
+ message: string;
92
+ data?: any;
93
+ }
94
+ declare class Logger {
95
+ private level;
96
+ private handlers;
97
+ private logs;
98
+ private maxLogs;
99
+ constructor(level?: LogLevel$1);
100
+ setLevel(level: LogLevel$1): void;
101
+ getLogs(): LogEntry[];
102
+ clearLogs(): void;
103
+ private log;
104
+ error(message: string, data?: any): void;
105
+ warn(message: string, data?: any): void;
106
+ info(message: string, data?: any): void;
107
+ debug(message: string, data?: any): void;
108
+ }
109
+ //#endregion
110
+ //#region src/core/http-client.d.ts
111
+ type HttpMethod = 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE';
112
+ interface HttpRequest {
113
+ url: string;
114
+ method: HttpMethod;
115
+ headers: Record<string, string>;
116
+ body?: any;
117
+ params?: Record<string, string | number | boolean | undefined>;
118
+ timeout?: number;
119
+ signal?: AbortSignal;
120
+ }
121
+ interface HttpResponse<T = any> {
122
+ data: T;
123
+ status: number;
124
+ headers: Headers;
125
+ request: HttpRequest;
126
+ }
127
+ type RequestInterceptor = (request: HttpRequest) => HttpRequest | Promise<HttpRequest>;
128
+ type ResponseInterceptor = (response: HttpResponse) => HttpResponse | Promise<HttpResponse>;
129
+ type ErrorInterceptor = (error: any) => any | Promise<any>;
130
+ interface HttpClientConfig {
131
+ baseUrl: string;
132
+ timeout?: number;
133
+ maxRetries?: number;
134
+ retryDelay?: number;
135
+ logger?: Logger;
136
+ }
137
+ /**
138
+ * Robust HTTP client wrapping the fetch API.
139
+ */
140
+ declare class HttpClient {
141
+ private config;
142
+ private requestInterceptors;
143
+ private responseInterceptors;
144
+ private errorInterceptors;
145
+ constructor(config: HttpClientConfig);
146
+ addRequestInterceptor(interceptor: RequestInterceptor): void;
147
+ addResponseInterceptor(interceptor: ResponseInterceptor): void;
148
+ addErrorInterceptor(interceptor: ErrorInterceptor): void;
149
+ request<T = any>(req: Partial<HttpRequest>): Promise<HttpResponse<T>>;
150
+ get<T = any>(url: string, config?: Partial<HttpRequest>): Promise<HttpResponse<T>>;
151
+ post<T = any>(url: string, body?: any, config?: Partial<HttpRequest>): Promise<HttpResponse<T>>;
152
+ put<T = any>(url: string, body?: any, config?: Partial<HttpRequest>): Promise<HttpResponse<T>>;
153
+ patch<T = any>(url: string, body?: any, config?: Partial<HttpRequest>): Promise<HttpResponse<T>>;
154
+ delete<T = any>(url: string, config?: Partial<HttpRequest>): Promise<HttpResponse<T>>;
155
+ private resolveUrl;
156
+ private shouldRetry;
157
+ private calculateRetryDelay;
158
+ }
159
+ //#endregion
160
+ //#region src/types/account.d.ts
161
+ interface Account {
162
+ id: string;
163
+ slug: string;
164
+ name: string;
165
+ created_at: string;
166
+ }
167
+ interface AccountCreate {
168
+ name: string;
169
+ slug?: string;
170
+ }
171
+ interface AccountUpdate {
172
+ name: string;
173
+ }
174
+ interface AccountListParams {
175
+ page?: number;
176
+ page_size?: number;
177
+ search?: string;
178
+ is_active?: boolean;
179
+ sort_by?: string;
180
+ sort_order?: 'asc' | 'desc';
181
+ [key: string]: string | number | boolean | undefined;
182
+ }
183
+ interface AccountListResponse {
184
+ items: Account[];
185
+ total: number;
186
+ }
187
+ interface AccountUserListParams {
188
+ page?: number;
189
+ page_size?: number;
190
+ [key: string]: string | number | boolean | undefined;
191
+ }
192
+ //#endregion
193
+ //#region src/types/user.d.ts
194
+ interface User {
195
+ id: string;
196
+ email: string;
197
+ role: string;
198
+ account_id: string;
199
+ groups: string[];
200
+ is_active: boolean;
201
+ created_at: string;
202
+ last_login: string | null;
203
+ token_type: TokenType;
204
+ }
205
+ interface UserCreate {
206
+ email: string;
207
+ password?: string;
208
+ account_id: string;
209
+ role?: string;
210
+ }
211
+ interface UserUpdate {
212
+ email?: string;
213
+ role?: string;
214
+ is_active?: boolean;
215
+ }
216
+ interface UserListParams {
217
+ page?: number;
218
+ page_size?: number;
219
+ account_id?: string;
220
+ role_id?: string;
221
+ is_active?: boolean;
222
+ search?: string;
223
+ sort_by?: string;
224
+ sort_order?: 'asc' | 'desc';
225
+ [key: string]: string | number | boolean | undefined;
226
+ }
227
+ interface UserListResponse {
228
+ items: User[];
229
+ total: number;
230
+ }
231
+ //#endregion
232
+ //#region src/types/auth.d.ts
233
+ /**
234
+ * Token type enum matching backend TokenType
235
+ */
236
+ declare enum TokenType {
237
+ JWT = "jwt",
238
+ API_KEY = "api_key",
239
+ PERSONAL_TOKEN = "personal_token",
240
+ OAUTH = "oauth"
241
+ }
242
+ interface AuthState {
243
+ user: User | null;
244
+ account: Account | null;
245
+ token: string | null;
246
+ refreshToken: string | null;
247
+ isAuthenticated: boolean;
248
+ expiresAt: string | null;
249
+ tokenType: TokenType;
250
+ }
251
+ type AuthEvent = 'auth:login' | 'auth:logout' | 'auth:refresh' | 'auth:error';
252
+ interface AuthEvents {
253
+ 'auth:login': (state: AuthState) => void;
254
+ 'auth:logout': () => void;
255
+ 'auth:refresh': (state: AuthState) => void;
256
+ 'auth:error': (error: Error) => void;
257
+ }
258
+ interface LoginCredentials {
259
+ account?: string;
260
+ email: string;
261
+ password: string;
262
+ }
263
+ interface RegisterData {
264
+ email: string;
265
+ password: string;
266
+ account_name?: string;
267
+ account_slug?: string;
268
+ }
269
+ interface AuthResponse {
270
+ user?: User;
271
+ account?: Account;
272
+ token?: string;
273
+ refresh_token?: string;
274
+ refreshToken?: string;
275
+ expires_in?: number;
276
+ expiresAt?: string;
277
+ user_id?: string;
278
+ account_id?: string;
279
+ email?: string;
280
+ role?: string;
281
+ }
282
+ interface PasswordResetRequest {
283
+ account?: string;
284
+ email: string;
285
+ }
286
+ interface PasswordResetConfirm {
287
+ token: string;
288
+ newPassword: string;
289
+ }
290
+ type OAuthProvider = 'google' | 'github' | 'microsoft' | 'apple';
291
+ interface OAuthUrlResponse {
292
+ url: string;
293
+ state: string;
294
+ }
295
+ interface OAuthCallbackParams {
296
+ provider: OAuthProvider;
297
+ code: string;
298
+ redirectUri: string;
299
+ state: string;
300
+ }
301
+ interface OAuthResponse extends AuthResponse {
302
+ isNewUser: boolean;
303
+ isNewAccount: boolean;
304
+ }
305
+ type SAMLProvider = 'okta' | 'azure_ad' | 'generic_saml';
306
+ interface SAMLUrlResponse {
307
+ url: string;
308
+ }
309
+ interface SAMLCallbackParams {
310
+ SAMLResponse: string;
311
+ relayState?: string;
312
+ }
313
+ interface SAMLResponse extends AuthResponse {
314
+ isNewUser: boolean;
315
+ isNewAccount: boolean;
316
+ }
317
+ //#endregion
318
+ //#region src/core/storage.d.ts
319
+ interface AuthStorage {
320
+ getItem(key: string): string | null | Promise<string | null>;
321
+ setItem(key: string, value: string): void | Promise<void>;
322
+ removeItem(key: string): void | Promise<void>;
323
+ }
324
+ //#endregion
325
+ //#region src/core/auth.d.ts
326
+ interface AuthManagerOptions {
327
+ storage: AuthStorage;
328
+ storageKey?: string;
329
+ }
330
+ declare class AuthManager {
331
+ private state;
332
+ private storage;
333
+ private storageKey;
334
+ private events;
335
+ constructor(options: AuthManagerOptions);
336
+ initialize(): Promise<void>;
337
+ getState(): AuthState;
338
+ get user(): User | null;
339
+ get account(): Account | null;
340
+ get token(): string | null;
341
+ get refreshToken(): string | null;
342
+ get isAuthenticated(): boolean;
343
+ get tokenType(): TokenType;
344
+ /**
345
+ * Update auth state (enhanced to extract token_type)
346
+ */
347
+ updateState(data: AuthResponse): Promise<void>;
348
+ /**
349
+ * Check if current user is superadmin
350
+ */
351
+ isSuperadmin(): boolean;
352
+ /**
353
+ * Check if current session uses API key authentication
354
+ */
355
+ isApiKeySession(): boolean;
356
+ /**
357
+ * Check if current session uses personal token authentication
358
+ */
359
+ isPersonalTokenSession(): boolean;
360
+ /**
361
+ * Check if current session uses OAuth authentication
362
+ */
363
+ isOAuthSession(): boolean;
364
+ private calculateExpiry;
365
+ setState(newState: Partial<AuthState>): Promise<void>;
366
+ clear(): Promise<void>;
367
+ on<K extends keyof AuthEvents>(event: K, listener: AuthEvents[K]): () => void;
368
+ private hydrate;
369
+ private persist;
370
+ private validateSession;
371
+ }
372
+ //#endregion
373
+ //#region src/core/auth-service.d.ts
374
+ /**
375
+ * Service for handling authentication operations.
376
+ */
377
+ declare class AuthService {
378
+ private http;
379
+ private auth;
380
+ private apiKey?;
381
+ private defaultAccount?;
382
+ private oauthStates;
383
+ private readonly STATE_EXPIRY_MS;
384
+ constructor(http: HttpClient, auth: AuthManager, apiKey?: string | undefined, defaultAccount?: string | undefined);
385
+ /**
386
+ * Helper to ensure API key is not used for user-specific operations.
387
+ */
388
+ private checkApiKeyRestriction;
389
+ /**
390
+ * Authenticate a user with email and password.
391
+ */
392
+ login(credentials: LoginCredentials): Promise<AuthResponse>;
393
+ /**
394
+ * Register a new user and account.
395
+ */
396
+ register(data: RegisterData): Promise<AuthResponse>;
397
+ /**
398
+ * Refresh the access token using the refresh token.
399
+ */
400
+ refreshToken(): Promise<AuthResponse>;
401
+ /**
402
+ * Log out the current user.
403
+ */
404
+ logout(): Promise<{
405
+ success: boolean;
406
+ }>;
407
+ /**
408
+ * Get the current authenticated user profile.
409
+ */
410
+ getCurrentUser(): Promise<AuthResponse>;
411
+ /**
412
+ * Initiate password reset flow.
413
+ */
414
+ forgotPassword(data: PasswordResetRequest): Promise<{
415
+ message: string;
416
+ }>;
417
+ /**
418
+ * Reset password using a token.
419
+ */
420
+ resetPassword(data: PasswordResetConfirm): Promise<{
421
+ message: string;
422
+ }>;
423
+ /**
424
+ * Verify email using a token.
425
+ */
426
+ verifyEmail(token: string): Promise<{
427
+ message: string;
428
+ }>;
429
+ /**
430
+ * Resend the verification email to the current user.
431
+ */
432
+ resendVerificationEmail(): Promise<{
433
+ message: string;
434
+ }>;
435
+ /**
436
+ * Send a verification email to a specific email address.
437
+ * This can be used by admins to send verification emails to users.
438
+ */
439
+ sendVerification(email: string): Promise<{
440
+ message: string;
441
+ }>;
442
+ /**
443
+ * Verify a password reset token is valid.
444
+ * Returns the email associated with the token if valid.
445
+ */
446
+ verifyResetToken(token: string): Promise<{
447
+ email: string;
448
+ }>;
449
+ /**
450
+ * Generate OAuth authorization URL for the specified provider.
451
+ */
452
+ getOAuthUrl(provider: OAuthProvider, redirectUri: string, state?: string): Promise<OAuthUrlResponse>;
453
+ /**
454
+ * Handle OAuth callback and authenticate user.
455
+ */
456
+ handleOAuthCallback(params: OAuthCallbackParams): Promise<OAuthResponse>;
457
+ /**
458
+ * Generate SAML SSO authorization URL for the specified provider and account.
459
+ */
460
+ getSAMLUrl(provider: SAMLProvider, account: string, relayState?: string): Promise<SAMLUrlResponse>;
461
+ /**
462
+ * Handle SAML callback (ACS) and authenticate user.
463
+ */
464
+ handleSAMLCallback(params: SAMLCallbackParams): Promise<SAMLResponse>;
465
+ /**
466
+ * Get SAML metadata for the specified provider and account.
467
+ */
468
+ getSAMLMetadata(provider: SAMLProvider, account: string): Promise<string>;
469
+ /**
470
+ * Cleanup expired state tokens.
471
+ */
472
+ private cleanupExpiredStates;
473
+ }
474
+ //#endregion
475
+ //#region src/core/account-service.d.ts
476
+ /**
477
+ * Service for managing accounts and their users.
478
+ * Requires superadmin authentication.
479
+ */
480
+ declare class AccountService {
481
+ private http;
482
+ constructor(http: HttpClient);
483
+ /**
484
+ * List all accounts with pagination, filtering, and sorting.
485
+ */
486
+ list(params?: AccountListParams): Promise<AccountListResponse>;
487
+ /**
488
+ * Get details for a specific account.
489
+ */
490
+ get(accountId: string): Promise<Account>;
491
+ /**
492
+ * Create a new account.
493
+ */
494
+ create(data: AccountCreate): Promise<Account>;
495
+ /**
496
+ * Update an existing account.
497
+ */
498
+ update(accountId: string, data: AccountUpdate): Promise<Account>;
499
+ /**
500
+ * Delete an account and all its associated data.
501
+ */
502
+ delete(accountId: string): Promise<{
503
+ success: boolean;
504
+ }>;
505
+ /**
506
+ * Get all users belonging to a specific account.
507
+ */
508
+ getUsers(accountId: string, params?: AccountUserListParams): Promise<UserListResponse>;
509
+ }
510
+ //#endregion
511
+ //#region src/core/user-service.d.ts
512
+ /**
513
+ * Service for managing users.
514
+ * Requires superadmin authentication for most operations.
515
+ */
516
+ declare class UserService {
517
+ private http;
518
+ constructor(http: HttpClient);
519
+ /**
520
+ * List all users with pagination, filtering, and sorting.
521
+ */
522
+ list(params?: UserListParams): Promise<UserListResponse>;
523
+ /**
524
+ * Get details for a specific user.
525
+ */
526
+ get(userId: string): Promise<User>;
527
+ /**
528
+ * Create a new user in a specific account.
529
+ */
530
+ create(data: UserCreate): Promise<User>;
531
+ /**
532
+ * Update an existing user.
533
+ */
534
+ update(userId: string, data: UserUpdate): Promise<User>;
535
+ /**
536
+ * Soft delete (deactivate) a user.
537
+ */
538
+ delete(userId: string): Promise<{
539
+ success: boolean;
540
+ }>;
541
+ /**
542
+ * Manually set a new password for a user.
543
+ */
544
+ setPassword(userId: string, password: string): Promise<{
545
+ success: boolean;
546
+ }>;
547
+ /**
548
+ * Manually verify a user's email address.
549
+ */
550
+ verifyEmail(userId: string): Promise<{
551
+ success: boolean;
552
+ }>;
553
+ /**
554
+ * Resend the verification email to a user.
555
+ */
556
+ resendVerification(userId: string): Promise<{
557
+ success: boolean;
558
+ }>;
559
+ }
560
+ //#endregion
561
+ //#region src/types/collection.d.ts
562
+ type FieldType = 'text' | 'number' | 'boolean' | 'date' | 'datetime' | 'email' | 'url' | 'phone' | 'select' | 'multi_select' | 'relation' | 'json';
563
+ interface FieldDefinition {
564
+ name: string;
565
+ type: FieldType;
566
+ required?: boolean;
567
+ default?: any;
568
+ unique?: boolean;
569
+ options?: string[];
570
+ collection?: string;
571
+ }
572
+ interface Collection {
573
+ id: string;
574
+ name: string;
575
+ fields: FieldDefinition[];
576
+ record_count: number;
577
+ field_count: number;
578
+ created_at: string;
579
+ updated_at: string;
580
+ }
581
+ interface CollectionCreate {
582
+ name: string;
583
+ fields: FieldDefinition[];
584
+ list_rule?: string | null;
585
+ view_rule?: string | null;
586
+ create_rule?: string | null;
587
+ update_rule?: string | null;
588
+ delete_rule?: string | null;
589
+ }
590
+ interface CollectionUpdate {
591
+ name?: string;
592
+ fields?: FieldDefinition[];
593
+ list_rule?: string | null;
594
+ view_rule?: string | null;
595
+ create_rule?: string | null;
596
+ update_rule?: string | null;
597
+ delete_rule?: string | null;
598
+ }
599
+ /**
600
+ * Comprehensive field definition for export including all metadata
601
+ */
602
+ interface CollectionExportFieldDefinition {
603
+ name: string;
604
+ type: FieldType;
605
+ required?: boolean;
606
+ default?: any;
607
+ unique?: boolean;
608
+ options?: Record<string, any> | null;
609
+ collection?: string | null;
610
+ on_delete?: string | null;
611
+ pii?: boolean;
612
+ mask_type?: string | null;
613
+ }
614
+ /**
615
+ * Access control rules structure for Permission System V2
616
+ * Rule values:
617
+ * - null = locked (access denied)
618
+ * - "" (empty string) = public (all users can access)
619
+ * - Expression string = conditional access (RLS rule)
620
+ */
621
+ interface CollectionExportRules {
622
+ list_rule: string | null;
623
+ view_rule: string | null;
624
+ create_rule: string | null;
625
+ update_rule: string | null;
626
+ delete_rule: string | null;
627
+ list_fields: string;
628
+ view_fields: string;
629
+ create_fields: string;
630
+ update_fields: string;
631
+ }
632
+ /**
633
+ * Single collection in export bundle
634
+ */
635
+ interface CollectionExportItem {
636
+ name: string;
637
+ schema: CollectionExportFieldDefinition[];
638
+ rules: CollectionExportRules;
639
+ }
640
+ /**
641
+ * Complete export file structure
642
+ */
643
+ interface CollectionExportData {
644
+ version: string;
645
+ exported_at: string;
646
+ exported_by: string;
647
+ collections: CollectionExportItem[];
648
+ }
649
+ /**
650
+ * Import conflict handling strategies
651
+ */
652
+ type ImportStrategy = 'error' | 'skip' | 'update';
653
+ /**
654
+ * Import request payload
655
+ */
656
+ interface CollectionImportRequest {
657
+ data: CollectionExportData;
658
+ strategy?: ImportStrategy;
659
+ }
660
+ /**
661
+ * Import result for a single collection
662
+ */
663
+ interface CollectionImportItemResult {
664
+ name: string;
665
+ status: 'imported' | 'skipped' | 'updated' | 'error';
666
+ message: string;
667
+ }
668
+ /**
669
+ * Complete import operation result
670
+ */
671
+ interface CollectionImportResult {
672
+ success: boolean;
673
+ imported_count: number;
674
+ skipped_count: number;
675
+ updated_count: number;
676
+ failed_count: number;
677
+ collections: CollectionImportItemResult[];
678
+ migrations_created: string[];
679
+ }
680
+ /**
681
+ * Export query parameters
682
+ */
683
+ interface CollectionExportParams {
684
+ collection_ids?: string[];
685
+ }
686
+ //#endregion
687
+ //#region src/core/collection-service.d.ts
688
+ /**
689
+ * Service for managing collections and their schemas.
690
+ * Requires superadmin authentication.
691
+ */
692
+ declare class CollectionService {
693
+ private http;
694
+ constructor(http: HttpClient);
695
+ /**
696
+ * List all collections.
697
+ */
698
+ list(): Promise<Collection[]>;
699
+ /**
700
+ * List collection names only.
701
+ */
702
+ listNames(): Promise<string[]>;
703
+ /**
704
+ * Get schema details for a specific collection.
705
+ */
706
+ get(collectionId: string): Promise<Collection>;
707
+ /**
708
+ * Create a new collection and its physical table.
709
+ */
710
+ create(data: CollectionCreate): Promise<Collection>;
711
+ /**
712
+ * Update an existing collection schema.
713
+ * Note: Field types cannot be changed for data safety.
714
+ */
715
+ update(collectionId: string, data: CollectionUpdate): Promise<Collection>;
716
+ /**
717
+ * Delete a collection and drop its physical table.
718
+ */
719
+ delete(collectionId: string): Promise<{
720
+ success: boolean;
721
+ }>;
722
+ /**
723
+ * Export collections to JSON format.
724
+ * Returns collection schemas and rules for backup or migration.
725
+ *
726
+ * @param params Optional filter by collection IDs
727
+ * @returns Complete export data structure with collections, schemas, and rules
728
+ * @throws {AuthorizationError} If user is not a superadmin
729
+ *
730
+ * @example
731
+ * // Export all collections
732
+ * const exportData = await client.collections.export();
733
+ *
734
+ * @example
735
+ * // Export specific collections
736
+ * const exportData = await client.collections.export({
737
+ * collection_ids: ['col-123', 'col-456']
738
+ * });
739
+ */
740
+ export(params?: CollectionExportParams): Promise<CollectionExportData>;
741
+ /**
742
+ * Import collections from JSON export.
743
+ *
744
+ * @param request Import request with data and conflict strategy
745
+ * @returns Import result with per-collection status and migration IDs
746
+ * @throws {ValidationError} If import data is invalid
747
+ * @throws {ConflictError} If collection exists and strategy is 'error'
748
+ * @throws {AuthorizationError} If user is not a superadmin
749
+ *
750
+ * @example
751
+ * // Import with error strategy (fail on conflicts)
752
+ * const result = await client.collections.import({
753
+ * data: exportData,
754
+ * strategy: 'error'
755
+ * });
756
+ *
757
+ * @example
758
+ * // Import with skip strategy (skip existing collections)
759
+ * const result = await client.collections.import({
760
+ * data: exportData,
761
+ * strategy: 'skip'
762
+ * });
763
+ *
764
+ * @example
765
+ * // Import with update strategy (update existing collections)
766
+ * const result = await client.collections.import({
767
+ * data: exportData,
768
+ * strategy: 'update'
769
+ * });
770
+ */
771
+ import(request: CollectionImportRequest): Promise<CollectionImportResult>;
772
+ }
773
+ //#endregion
774
+ //#region src/types/record.d.ts
775
+ /**
776
+ * Base record fields managed by the system.
777
+ */
778
+ interface BaseRecord {
779
+ id: string;
780
+ account_id: string;
781
+ created_at: string;
782
+ updated_at: string;
783
+ created_by?: string;
784
+ updated_by?: string;
785
+ [key: string]: any;
786
+ }
787
+ /**
788
+ * Parameters for listing records.
789
+ */
790
+ interface RecordListParams {
791
+ /**
792
+ * Number of records to skip.
793
+ */
794
+ skip?: number;
795
+ /**
796
+ * Maximum number of records to return.
797
+ */
798
+ limit?: number;
799
+ /**
800
+ * Sort expression (e.g., 'created_at' or '-created_at' for descending).
801
+ */
802
+ sort?: string;
803
+ /**
804
+ * Fields to include in the response.
805
+ */
806
+ fields?: string[] | string;
807
+ /**
808
+ * Filter parameters.
809
+ */
810
+ filter?: any;
811
+ /**
812
+ * Related collections to expand.
813
+ */
814
+ expand?: string[] | string;
815
+ }
816
+ /**
817
+ * Paginated response for records.
818
+ */
819
+ interface RecordListResponse<T> {
820
+ items: (T & BaseRecord)[];
821
+ total: number;
822
+ skip: number;
823
+ limit: number;
824
+ }
825
+ //#endregion
826
+ //#region src/types/query.d.ts
827
+ /**
828
+ * Supported filter operators.
829
+ */
830
+ type FilterOperator = '=' | '!=' | '>' | '>=' | '<' | '<=' | '~' | '!~' | '?=' | '?!=';
831
+ /**
832
+ * Filter expression object.
833
+ */
834
+ interface FilterExpression {
835
+ field: string;
836
+ operator: FilterOperator;
837
+ value?: any;
838
+ }
839
+ /**
840
+ * Sort direction.
841
+ */
842
+ type SortDirection = 'asc' | 'desc';
843
+ /**
844
+ * Sort expression object.
845
+ */
846
+ interface SortExpression {
847
+ field: string;
848
+ direction: SortDirection;
849
+ }
850
+ /**
851
+ * Query parameters interface matching the backend expectations.
852
+ * This is similar to RecordListParams but used internally by the builder.
853
+ */
854
+ interface QueryParams {
855
+ page?: number;
856
+ perPage?: number;
857
+ sort?: string;
858
+ filter?: string;
859
+ expand?: string;
860
+ fields?: string;
861
+ skip?: number;
862
+ limit?: number;
863
+ }
864
+ //#endregion
865
+ //#region src/core/query-builder.d.ts
866
+ /**
867
+ * Fluent interface for building complex queries.
868
+ */
869
+ declare class QueryBuilder<T = any> {
870
+ private service;
871
+ private collection;
872
+ private _fields;
873
+ private _expand;
874
+ private _filterParts;
875
+ private _sortParts;
876
+ private _page;
877
+ private _perPage;
878
+ private _skip;
879
+ private _limit;
880
+ private _useLegacyPagination;
881
+ constructor(service: RecordService, collection: string);
882
+ /**
883
+ * Specify fields to return.
884
+ * @param fields Array of field names or comma-separated string
885
+ */
886
+ select(fields: string | string[]): this;
887
+ /**
888
+ * Expand related records.
889
+ * @param relations Array of relation names or comma-separated string
890
+ */
891
+ expand(relations: string | string[]): this;
892
+ /**
893
+ * Add a filter condition.
894
+ * @param field Field name
895
+ * @param operator Filter operator
896
+ * @param value Value to compare against
897
+ */
898
+ filter(field: string, operator: FilterOperator, value?: any): this;
899
+ /**
900
+ * Add a raw filter string.
901
+ * @param filterString Raw filter string (e.g., "age > 21")
902
+ */
903
+ filter(filterString: string): this;
904
+ /**
905
+ * Add sorting.
906
+ * @param field Field name
907
+ * @param direction 'asc' or 'desc' (default: 'asc')
908
+ */
909
+ sort(field: string, direction?: SortDirection): this;
910
+ /**
911
+ * Set limit (and optionally skip).
912
+ * Note: Using limit/skip switches to manual offset pagination.
913
+ * @param limit Max records
914
+ * @param skip Records to skip
915
+ */
916
+ limit(limit: number): this;
917
+ /**
918
+ * Set skip.
919
+ * Note: Using limit/skip switches to manual offset pagination.
920
+ * @param skip Records to skip
921
+ */
922
+ skip(skip: number): this;
923
+ /**
924
+ * Set page number and page size.
925
+ * @param page Page number (1-based)
926
+ * @param perPage Records per page
927
+ */
928
+ page(page: number, perPage?: number): this;
929
+ /**
930
+ * Execute query and get list of records.
931
+ */
932
+ get(): Promise<RecordListResponse<T>>;
933
+ /**
934
+ * Execute query and get the first matching record.
935
+ */
936
+ first(): Promise<(T & BaseRecord) | null>;
937
+ private formatValue;
938
+ }
939
+ //#endregion
940
+ //#region src/core/record-service.d.ts
941
+ /**
942
+ * Service for performing CRUD operations on dynamic collections.
943
+ */
944
+ declare class RecordService {
945
+ private http;
946
+ constructor(http: HttpClient);
947
+ /**
948
+ * List records from a collection with pagination, filtering, and sorting.
949
+ * @template T The record type
950
+ * @param collection Collection name
951
+ * @param params Query parameters
952
+ */
953
+ list<T = any>(collection: string, params?: RecordListParams): Promise<RecordListResponse<T>>;
954
+ /**
955
+ * Create a query builder for the collection.
956
+ * @template T The record type
957
+ * @param collection Collection name
958
+ */
959
+ query<T = any>(collection: string): QueryBuilder<T>;
960
+ /**
961
+ * Get a single record by ID.
962
+ * @template T The record type
963
+ * @param collection Collection name
964
+ * @param recordId Record ID
965
+ * @param params Optional query parameters (e.g., fields)
966
+ */
967
+ get<T = any>(collection: string, recordId: string, params?: {
968
+ fields?: string[] | string;
969
+ expand?: string[] | string;
970
+ }): Promise<T & BaseRecord>;
971
+ /**
972
+ * Create a new record in a collection.
973
+ * @template T The record type
974
+ * @param collection Collection name
975
+ * @param data Record data
976
+ */
977
+ create<T = any>(collection: string, data: Partial<T>): Promise<T & BaseRecord>;
978
+ /**
979
+ * Full update of an existing record (PUT).
980
+ * @template T The record type
981
+ * @param collection Collection name
982
+ * @param recordId Record ID
983
+ * @param data Record data
984
+ */
985
+ update<T = any>(collection: string, recordId: string, data: Partial<T>): Promise<T & BaseRecord>;
986
+ /**
987
+ * Partial update of an existing record (PATCH).
988
+ * @template T The record type
989
+ * @param collection Collection name
990
+ * @param recordId Record ID
991
+ * @param data Partial record data
992
+ */
993
+ patch<T = any>(collection: string, recordId: string, data: Partial<T>): Promise<T & BaseRecord>;
994
+ /**
995
+ * Delete a record from a collection.
996
+ * @param collection Collection name
997
+ * @param recordId Record ID
998
+ */
999
+ delete(collection: string, recordId: string): Promise<{
1000
+ success: boolean;
1001
+ }>;
1002
+ }
1003
+ //#endregion
1004
+ //#region src/types/group.d.ts
1005
+ interface Group {
1006
+ id: string;
1007
+ account_id: string;
1008
+ name: string;
1009
+ description?: string;
1010
+ is_system: boolean;
1011
+ created_at: string;
1012
+ updated_at: string;
1013
+ }
1014
+ interface GroupCreate {
1015
+ name: string;
1016
+ description?: string;
1017
+ }
1018
+ interface GroupUpdate {
1019
+ name?: string;
1020
+ description?: string;
1021
+ }
1022
+ interface GroupListParams {
1023
+ page?: number;
1024
+ page_size?: number;
1025
+ search?: string;
1026
+ [key: string]: string | number | boolean | undefined;
1027
+ }
1028
+ interface GroupListResponse {
1029
+ items: Group[];
1030
+ total: number;
1031
+ page: number;
1032
+ page_size: number;
1033
+ }
1034
+ //#endregion
1035
+ //#region src/core/group-service.d.ts
1036
+ /**
1037
+ * Service for managing groups.
1038
+ */
1039
+ declare class GroupsService {
1040
+ private http;
1041
+ constructor(http: HttpClient);
1042
+ /**
1043
+ * List all groups in the current account.
1044
+ */
1045
+ list(params?: GroupListParams): Promise<GroupListResponse>;
1046
+ /**
1047
+ * Get details for a specific group.
1048
+ */
1049
+ get(groupId: string): Promise<Group>;
1050
+ /**
1051
+ * Create a new group in the current account.
1052
+ */
1053
+ create(data: GroupCreate): Promise<Group>;
1054
+ /**
1055
+ * Update a group's name or description.
1056
+ */
1057
+ update(groupId: string, data: GroupUpdate): Promise<Group>;
1058
+ /**
1059
+ * Delete a group.
1060
+ */
1061
+ delete(groupId: string): Promise<{
1062
+ success: boolean;
1063
+ }>;
1064
+ /**
1065
+ * Add a user to a group.
1066
+ */
1067
+ addMember(groupId: string, userId: string): Promise<{
1068
+ success: boolean;
1069
+ }>;
1070
+ /**
1071
+ * Remove a user from a group.
1072
+ */
1073
+ removeMember(groupId: string, userId: string): Promise<{
1074
+ success: boolean;
1075
+ }>;
1076
+ }
1077
+ //#endregion
1078
+ //#region src/types/invitation.d.ts
1079
+ interface Invitation {
1080
+ id: string;
1081
+ email: string;
1082
+ account_id: string;
1083
+ role_id?: string;
1084
+ status: 'pending' | 'accepted' | 'expired' | 'cancelled';
1085
+ token?: string;
1086
+ expires_at: string;
1087
+ created_at: string;
1088
+ updated_at: string;
1089
+ }
1090
+ interface InvitationCreate {
1091
+ email: string;
1092
+ role_id?: string;
1093
+ }
1094
+ interface InvitationListParams {
1095
+ status?: 'pending' | 'accepted' | 'expired' | 'cancelled';
1096
+ page?: number;
1097
+ page_size?: number;
1098
+ [key: string]: string | number | boolean | undefined;
1099
+ }
1100
+ //#endregion
1101
+ //#region src/core/invitation-service.d.ts
1102
+ /**
1103
+ * Service for managing user invitations.
1104
+ * Allows admins to invite users and tracks invitation status.
1105
+ */
1106
+ declare class InvitationService {
1107
+ private http;
1108
+ constructor(http: HttpClient);
1109
+ /**
1110
+ * List all invitations in the current account.
1111
+ */
1112
+ list(params?: InvitationListParams): Promise<Invitation[]>;
1113
+ /**
1114
+ * Create a new invitation for a user.
1115
+ */
1116
+ create(data: InvitationCreate): Promise<Invitation>;
1117
+ /**
1118
+ * Resend an invitation email.
1119
+ */
1120
+ resend(invitationId: string): Promise<{
1121
+ success: boolean;
1122
+ }>;
1123
+ /**
1124
+ * Get public details of an invitation using a token.
1125
+ * No authentication required.
1126
+ */
1127
+ getPublic(token: string): Promise<Invitation>;
1128
+ /**
1129
+ * Accept an invitation using a token and password.
1130
+ * Creates the user account and returns authentication tokens.
1131
+ */
1132
+ accept(token: string, password: string): Promise<AuthResponse>;
1133
+ /**
1134
+ * Cancel a pending invitation.
1135
+ */
1136
+ cancel(invitationId: string): Promise<{
1137
+ success: boolean;
1138
+ }>;
1139
+ }
1140
+ //#endregion
1141
+ //#region src/types/api-key.d.ts
1142
+ interface ApiKey {
1143
+ id: string;
1144
+ name: string;
1145
+ /**
1146
+ * The full API key. Only returned once during creation.
1147
+ * Format: sb_ak.<payload>.<signature>
1148
+ */
1149
+ key?: string;
1150
+ /**
1151
+ * The masked version of the key (e.g., "sb_ak....SIGN").
1152
+ */
1153
+ masked_key: string;
1154
+ /**
1155
+ * The last 4 characters of the key.
1156
+ */
1157
+ last_4: string;
1158
+ expires_at: string | null;
1159
+ created_at: string;
1160
+ updated_at: string;
1161
+ revoked_at: string | null;
1162
+ }
1163
+ interface ApiKeyCreate {
1164
+ name: string;
1165
+ expires_at?: string;
1166
+ }
1167
+ interface ApiKeyListParams {
1168
+ limit?: number;
1169
+ offset?: number;
1170
+ [key: string]: string | number | boolean | undefined;
1171
+ }
1172
+ type ApiKeyListResponse = ApiKey[];
1173
+ //#endregion
1174
+ //#region src/core/api-key-service.d.ts
1175
+ /**
1176
+ * Service for managing API keys.
1177
+ * API keys are used for service-to-service communication.
1178
+ */
1179
+ declare class ApiKeyService {
1180
+ private http;
1181
+ constructor(http: HttpClient);
1182
+ /**
1183
+ * List all API keys
1184
+ * GET /api/v1/admin/api-keys
1185
+ */
1186
+ list(params?: ApiKeyListParams): Promise<ApiKeyListResponse>;
1187
+ /**
1188
+ * Get specific API key
1189
+ * GET /api/v1/admin/api-keys/{id}
1190
+ */
1191
+ get(keyId: string): Promise<ApiKey>;
1192
+ /**
1193
+ * Create a new API key
1194
+ * POST /api/v1/admin/api-keys
1195
+ */
1196
+ create(data: ApiKeyCreate): Promise<ApiKey>;
1197
+ /**
1198
+ * Revoke an API key
1199
+ * DELETE /api/v1/admin/api-keys/{id}
1200
+ */
1201
+ revoke(keyId: string): Promise<{
1202
+ success: boolean;
1203
+ }>;
1204
+ }
1205
+ //#endregion
1206
+ //#region src/types/audit-log.d.ts
1207
+ /**
1208
+ * Audit log extra metadata
1209
+ */
1210
+ interface AuditLogExtraMetadata {
1211
+ auth_method?: 'jwt' | 'api_key' | 'personal_token' | 'oauth' | 'unknown';
1212
+ [key: string]: any;
1213
+ }
1214
+ interface AuditLog {
1215
+ id: string;
1216
+ account_id: string;
1217
+ table_name: string;
1218
+ record_id: string;
1219
+ user_id: string;
1220
+ operation: 'create' | 'update' | 'delete' | 'login' | 'logout' | string;
1221
+ before: Record<string, any> | null;
1222
+ after: Record<string, any> | null;
1223
+ created_at: string;
1224
+ extra_metadata?: AuditLogExtraMetadata;
1225
+ }
1226
+ interface AuditLogFilters {
1227
+ account_id?: string;
1228
+ table_name?: string;
1229
+ record_id?: string;
1230
+ user_id?: string;
1231
+ operation?: string;
1232
+ from_date?: string;
1233
+ to_date?: string;
1234
+ page?: number;
1235
+ skip?: number;
1236
+ limit?: number;
1237
+ sort?: string;
1238
+ }
1239
+ type AuditLogExportFormat = 'csv' | 'json' | 'pdf';
1240
+ interface AuditLogListResponse {
1241
+ items: AuditLog[];
1242
+ total: number;
1243
+ page: number;
1244
+ limit: number;
1245
+ audit_logging_enabled: boolean;
1246
+ }
1247
+ //#endregion
1248
+ //#region src/core/audit-log-service.d.ts
1249
+ declare class AuditLogService {
1250
+ private httpClient;
1251
+ constructor(httpClient: HttpClient);
1252
+ /**
1253
+ * Lists audit logs with optional filtering, pagination, and sorting.
1254
+ */
1255
+ list(params?: AuditLogFilters): Promise<AuditLogListResponse>;
1256
+ /**
1257
+ * Retrieves a single audit log entry by ID.
1258
+ */
1259
+ get(logId: string): Promise<AuditLog>;
1260
+ /**
1261
+ * Exports audit logs in the specified format (JSON, CSV, or PDF).
1262
+ *
1263
+ * @param params Optional filters (account_id, table_name, operation, date range, etc.)
1264
+ * @param format Export format: 'json', 'csv', or 'pdf' (default: 'json')
1265
+ * @returns Exported data as string (base64-encoded for PDF format)
1266
+ * @throws {AuthorizationError} If user is not a superadmin
1267
+ *
1268
+ * @example
1269
+ * // Export as JSON
1270
+ * const jsonData = await client.auditLogs.export({ table_name: 'users' }, 'json');
1271
+ *
1272
+ * @example
1273
+ * // Export as CSV
1274
+ * const csvData = await client.auditLogs.export({ table_name: 'users' }, 'csv');
1275
+ *
1276
+ * @example
1277
+ * // Export as PDF
1278
+ * const pdfBase64 = await client.auditLogs.export({ table_name: 'users' }, 'pdf');
1279
+ * // pdfBase64 is a base64-encoded PDF string
1280
+ */
1281
+ export(params?: AuditLogFilters, format?: AuditLogExportFormat): Promise<string>;
1282
+ }
1283
+ //#endregion
1284
+ //#region src/types/role.d.ts
1285
+ interface Role {
1286
+ id: string;
1287
+ name: string;
1288
+ description: string;
1289
+ created_at: string;
1290
+ updated_at: string;
1291
+ }
1292
+ interface RoleCreate {
1293
+ name: string;
1294
+ description?: string;
1295
+ }
1296
+ interface RoleUpdate {
1297
+ name?: string;
1298
+ description?: string;
1299
+ }
1300
+ interface RoleListResponse {
1301
+ items: Role[];
1302
+ total: number;
1303
+ }
1304
+ interface CollectionRule {
1305
+ list_rule: string | null;
1306
+ view_rule: string | null;
1307
+ create_rule: string | null;
1308
+ update_rule: string | null;
1309
+ delete_rule: string | null;
1310
+ list_fields: string;
1311
+ view_fields: string;
1312
+ create_fields: string;
1313
+ update_fields: string;
1314
+ }
1315
+ interface CollectionRuleUpdate {
1316
+ list_rule?: string | null;
1317
+ view_rule?: string | null;
1318
+ create_rule?: string | null;
1319
+ update_rule?: string | null;
1320
+ delete_rule?: string | null;
1321
+ list_fields?: string;
1322
+ view_fields?: string;
1323
+ create_fields?: string;
1324
+ update_fields?: string;
1325
+ }
1326
+ interface RuleValidationResult {
1327
+ valid: boolean;
1328
+ errors?: string[];
1329
+ }
1330
+ interface RuleTestResult {
1331
+ result: boolean;
1332
+ }
1333
+ interface RuleValidationParams {
1334
+ rule: string;
1335
+ operation: 'list' | 'view' | 'create' | 'update' | 'delete';
1336
+ collectionFields: string[];
1337
+ }
1338
+ /**
1339
+ * Permission type alias for CollectionRule (Permission System V2).
1340
+ */
1341
+ type Permission = CollectionRule;
1342
+ //#endregion
1343
+ //#region src/core/role-service.d.ts
1344
+ /**
1345
+ * Service for managing roles.
1346
+ * Requires superadmin authentication.
1347
+ */
1348
+ declare class RoleService {
1349
+ private http;
1350
+ constructor(http: HttpClient);
1351
+ /**
1352
+ * List all roles with pagination.
1353
+ */
1354
+ list(): Promise<RoleListResponse>;
1355
+ /**
1356
+ * Get details for a specific role.
1357
+ */
1358
+ get(roleId: string): Promise<Role>;
1359
+ /**
1360
+ * Create a new role.
1361
+ */
1362
+ create(data: RoleCreate): Promise<Role>;
1363
+ /**
1364
+ * Update an existing role.
1365
+ */
1366
+ update(roleId: string, data: RoleUpdate): Promise<Role>;
1367
+ /**
1368
+ * Delete a role.
1369
+ * Fails if the role is currently in use.
1370
+ */
1371
+ delete(roleId: string): Promise<{
1372
+ success: boolean;
1373
+ }>;
1374
+ }
1375
+ //#endregion
1376
+ //#region src/core/collection-rule-service.d.ts
1377
+ /**
1378
+ * Service for managing collection-level access rules and field permissions.
1379
+ * Requires superadmin authentication.
1380
+ */
1381
+ declare class CollectionRuleService {
1382
+ private http;
1383
+ constructor(http: HttpClient);
1384
+ /**
1385
+ * Get access rules and field permissions for a specific collection.
1386
+ */
1387
+ get(collectionName: string): Promise<CollectionRule>;
1388
+ /**
1389
+ * Update access rules and field permissions for a specific collection.
1390
+ */
1391
+ update(collectionName: string, data: CollectionRuleUpdate): Promise<CollectionRule>;
1392
+ /**
1393
+ * Validate a rule expression against a collection schema.
1394
+ */
1395
+ validateRule(rule: string, operation: 'list' | 'view' | 'create' | 'update' | 'delete', collectionFields: string[]): Promise<RuleValidationResult>;
1396
+ /**
1397
+ * Test a rule evaluation with a sample context.
1398
+ */
1399
+ testRule(rule: string, context: any): Promise<RuleTestResult>;
1400
+ }
1401
+ //#endregion
1402
+ //#region src/types/macro.d.ts
1403
+ interface Macro {
1404
+ id: string;
1405
+ name: string;
1406
+ description: string;
1407
+ sql_query: string;
1408
+ parameters: string[];
1409
+ is_builtin: boolean;
1410
+ created_at: string;
1411
+ updated_at: string;
1412
+ }
1413
+ interface MacroCreate {
1414
+ name: string;
1415
+ description: string;
1416
+ sql_query: string;
1417
+ parameters: string[];
1418
+ }
1419
+ interface MacroUpdate {
1420
+ name?: string;
1421
+ description?: string;
1422
+ sql_query?: string;
1423
+ parameters?: string[];
1424
+ }
1425
+ interface MacroTestResult {
1426
+ success: boolean;
1427
+ result: any;
1428
+ }
1429
+ interface MacroListResponse {
1430
+ items: Macro[];
1431
+ total: number;
1432
+ }
1433
+ //#endregion
1434
+ //#region src/core/macro-service.d.ts
1435
+ /**
1436
+ * Service for managing SQL macros.
1437
+ * Macros can be used in permission rules.
1438
+ * Requires superadmin authentication for most operations.
1439
+ */
1440
+ declare class MacroService {
1441
+ private http;
1442
+ constructor(http: HttpClient);
1443
+ /**
1444
+ * List all macros, including built-in ones.
1445
+ */
1446
+ list(): Promise<MacroListResponse>;
1447
+ /**
1448
+ * Get details for a specific macro.
1449
+ */
1450
+ get(macroId: string): Promise<Macro>;
1451
+ /**
1452
+ * Create a new custom macro.
1453
+ */
1454
+ create(data: MacroCreate): Promise<Macro>;
1455
+ /**
1456
+ * Update an existing custom macro.
1457
+ * Built-in macros cannot be updated.
1458
+ */
1459
+ update(macroId: string, data: MacroUpdate): Promise<Macro>;
1460
+ /**
1461
+ * Delete a macro.
1462
+ * Fails if the macro is built-in or currently in use.
1463
+ */
1464
+ delete(macroId: string): Promise<{
1465
+ success: boolean;
1466
+ }>;
1467
+ /**
1468
+ * Test a macro with parameters.
1469
+ */
1470
+ test(macroId: string, params: Record<string, any>): Promise<MacroTestResult>;
1471
+ }
1472
+ //#endregion
1473
+ //#region src/types/dashboard.d.ts
1474
+ /**
1475
+ * Dashboard statistics and metrics for superadmins.
1476
+ */
1477
+ interface DashboardStats {
1478
+ /** Total number of accounts in the system */
1479
+ total_accounts: number;
1480
+ /** Total number of users across all accounts */
1481
+ total_users: number;
1482
+ /** Total number of collections defined */
1483
+ total_collections: number;
1484
+ /** Total number of records across all collections */
1485
+ total_records: number;
1486
+ /** Number of new accounts created in the last 7 days */
1487
+ new_accounts_7d: number;
1488
+ /** Number of new users registered in the last 7 days */
1489
+ new_users_7d: number;
1490
+ /** List of the most recent user registrations */
1491
+ recent_registrations: User[];
1492
+ /** Overview of current system health and status */
1493
+ system_health: SystemHealth;
1494
+ /** Number of currently active user sessions */
1495
+ active_sessions: number;
1496
+ /** List of the most recent audit log entries */
1497
+ recent_audit_logs: AuditLog[];
1498
+ }
1499
+ /**
1500
+ * System health information.
1501
+ */
1502
+ interface SystemHealth {
1503
+ /** overall status of the system */
1504
+ status: 'healthy' | 'degraded' | 'unhealthy' | string;
1505
+ /** System uptime (e.g., "7 days, 4 hours") */
1506
+ uptime?: string;
1507
+ /** Current version of the SnackBase server */
1508
+ version?: string;
1509
+ /** Additional health metrics */
1510
+ [key: string]: any;
1511
+ }
1512
+ //#endregion
1513
+ //#region src/core/dashboard-service.d.ts
1514
+ /**
1515
+ * Service for interacting with the Dashboard API.
1516
+ * Provides statistics and metrics for system monitoring.
1517
+ */
1518
+ declare class DashboardService {
1519
+ private httpClient;
1520
+ constructor(httpClient: HttpClient);
1521
+ /**
1522
+ * Retrieves dashboard statistics including counts for accounts, users,
1523
+ * collections, and records, as well as recent activity and health metrics.
1524
+ *
1525
+ * @returns {Promise<DashboardStats>} A promise that resolves to dashboard statistics.
1526
+ * @throws {AuthenticationError} If not authenticated.
1527
+ * @throws {AuthorizationError} If the user is not a superadmin.
1528
+ */
1529
+ getStats(): Promise<DashboardStats>;
1530
+ }
1531
+ //#endregion
1532
+ //#region src/types/admin.d.ts
1533
+ /**
1534
+ * Configuration record representing a system or account level setting.
1535
+ */
1536
+ interface Configuration {
1537
+ id: string;
1538
+ name: string;
1539
+ category: string;
1540
+ provider_name: string;
1541
+ is_system: boolean;
1542
+ account_id?: string;
1543
+ enabled: boolean;
1544
+ created_at: string;
1545
+ updated_at: string;
1546
+ }
1547
+ /**
1548
+ * Statistics for configurations by category.
1549
+ */
1550
+ interface ConfigurationStats {
1551
+ system_count: number;
1552
+ account_count: number;
1553
+ by_category: Record<string, {
1554
+ system: number;
1555
+ account: number;
1556
+ }>;
1557
+ }
1558
+ /**
1559
+ * Available provider definition.
1560
+ */
1561
+ interface ProviderDefinition {
1562
+ name: string;
1563
+ display_name: string;
1564
+ category: string;
1565
+ description?: string;
1566
+ is_built_in: boolean;
1567
+ icon?: string;
1568
+ }
1569
+ /**
1570
+ * Connection test result.
1571
+ */
1572
+ interface ConnectionTestResult {
1573
+ success: boolean;
1574
+ message: string;
1575
+ details?: Record<string, any>;
1576
+ }
1577
+ /**
1578
+ * Request data for creating a configuration.
1579
+ */
1580
+ interface ConfigurationCreate {
1581
+ name: string;
1582
+ category: string;
1583
+ provider_name: string;
1584
+ values: Record<string, any>;
1585
+ is_system?: boolean;
1586
+ account_id?: string;
1587
+ enabled?: boolean;
1588
+ }
1589
+ /**
1590
+ * Recent configuration summary.
1591
+ */
1592
+ interface RecentConfiguration extends Configuration {
1593
+ last_modified_by?: {
1594
+ id: string;
1595
+ email: string;
1596
+ };
1597
+ }
1598
+ //#endregion
1599
+ //#region src/core/admin-service.d.ts
1600
+ /**
1601
+ * Service for superadmin operations and system configuration management.
1602
+ */
1603
+ declare class AdminService {
1604
+ private http;
1605
+ constructor(http: HttpClient);
1606
+ /**
1607
+ * Returns configuration statistics by category.
1608
+ */
1609
+ getConfigurationStats(): Promise<ConfigurationStats>;
1610
+ /**
1611
+ * Returns recently modified configurations.
1612
+ * @param limit Number of configurations to return
1613
+ */
1614
+ getRecentConfigurations(limit?: number): Promise<RecentConfiguration[]>;
1615
+ /**
1616
+ * Returns all system-level configurations.
1617
+ * @param category Optional category filter
1618
+ */
1619
+ listSystemConfigurations(category?: string): Promise<Configuration[]>;
1620
+ /**
1621
+ * Returns configurations for specific account.
1622
+ * @param accountId Account ID
1623
+ * @param category Optional category filter
1624
+ */
1625
+ listAccountConfigurations(accountId: string, category?: string): Promise<Configuration[]>;
1626
+ /**
1627
+ * Returns decrypted configuration values with secrets masked.
1628
+ * @param configId Configuration ID
1629
+ */
1630
+ getConfigurationValues(configId: string): Promise<Record<string, any>>;
1631
+ /**
1632
+ * Updates configuration values.
1633
+ * @param configId Configuration ID
1634
+ * @param values New configuration values
1635
+ */
1636
+ updateConfigurationValues(configId: string, values: Record<string, any>): Promise<Record<string, any>>;
1637
+ /**
1638
+ * Enables or disables configuration.
1639
+ * @param configId Configuration ID
1640
+ * @param enabled Enabled status
1641
+ */
1642
+ updateConfigurationStatus(configId: string, enabled: boolean): Promise<Configuration>;
1643
+ /**
1644
+ * Creates new configuration record.
1645
+ * @param data Configuration data
1646
+ */
1647
+ createConfiguration(data: ConfigurationCreate): Promise<Configuration>;
1648
+ /**
1649
+ * Deletes configuration.
1650
+ * @param configId Configuration ID
1651
+ */
1652
+ deleteConfiguration(configId: string): Promise<{
1653
+ success: boolean;
1654
+ }>;
1655
+ /**
1656
+ * Lists all available provider definitions.
1657
+ * @param category Optional category filter
1658
+ */
1659
+ listProviders(category?: string): Promise<ProviderDefinition[]>;
1660
+ /**
1661
+ * Returns JSON schema for provider configuration.
1662
+ * @param category Provider category
1663
+ * @param providerName Provider name
1664
+ */
1665
+ getProviderSchema(category: string, providerName: string): Promise<Record<string, any>>;
1666
+ /**
1667
+ * Tests provider connection.
1668
+ * @param category Provider category
1669
+ * @param providerName Provider name
1670
+ * @param config Configuration values to test
1671
+ */
1672
+ testConnection(category: string, providerName: string, config: Record<string, any>): Promise<ConnectionTestResult>;
1673
+ }
1674
+ //#endregion
1675
+ //#region src/types/email-template.d.ts
1676
+ /**
1677
+ * Email template type.
1678
+ */
1679
+ type EmailTemplateType = 'verification' | 'reset_password' | 'invitation' | string;
1680
+ /**
1681
+ * Email template interface.
1682
+ */
1683
+ interface EmailTemplate {
1684
+ id: string;
1685
+ template_type: EmailTemplateType;
1686
+ locale: string;
1687
+ subject: string;
1688
+ html_body: string;
1689
+ text_body: string;
1690
+ enabled: boolean;
1691
+ account_id?: string;
1692
+ created_at: string;
1693
+ updated_at: string;
1694
+ }
1695
+ /**
1696
+ * Data for updating an email template.
1697
+ */
1698
+ interface EmailTemplateUpdate {
1699
+ subject?: string;
1700
+ html_body?: string;
1701
+ text_body?: string;
1702
+ enabled?: boolean;
1703
+ }
1704
+ /**
1705
+ * Filters for listing email templates.
1706
+ */
1707
+ interface EmailTemplateFilters {
1708
+ [key: string]: string | number | boolean | undefined;
1709
+ template_type?: EmailTemplateType;
1710
+ locale?: string;
1711
+ account_id?: string;
1712
+ enabled?: boolean;
1713
+ }
1714
+ /**
1715
+ * Request for rendering an email template.
1716
+ */
1717
+ interface EmailTemplateRenderRequest {
1718
+ template_type: EmailTemplateType;
1719
+ locale: string;
1720
+ variables: Record<string, any>;
1721
+ subject_override?: string;
1722
+ html_body_override?: string;
1723
+ text_body_override?: string;
1724
+ }
1725
+ /**
1726
+ * Response from rendering an email template.
1727
+ */
1728
+ interface EmailTemplateRenderResponse {
1729
+ subject: string;
1730
+ html_body: string;
1731
+ text_body: string;
1732
+ }
1733
+ /**
1734
+ * Email log interface.
1735
+ */
1736
+ interface EmailLog {
1737
+ id: string;
1738
+ account_id: string;
1739
+ template_type: EmailTemplateType;
1740
+ recipient: string;
1741
+ subject: string;
1742
+ status: 'sent' | 'failed' | 'pending';
1743
+ provider: string;
1744
+ error?: string;
1745
+ sent_at: string;
1746
+ metadata?: Record<string, any>;
1747
+ }
1748
+ /**
1749
+ * Filters for listing email logs.
1750
+ */
1751
+ interface EmailLogFilters {
1752
+ [key: string]: string | number | boolean | undefined;
1753
+ status?: string;
1754
+ template_type?: EmailTemplateType;
1755
+ start_date?: string;
1756
+ end_date?: string;
1757
+ page?: number;
1758
+ limit?: number;
1759
+ }
1760
+ /**
1761
+ * Paginated response for email logs.
1762
+ */
1763
+ interface EmailLogListResponse {
1764
+ data: EmailLog[];
1765
+ total: number;
1766
+ page: number;
1767
+ limit: number;
1768
+ last_page: number;
1769
+ }
1770
+ //#endregion
1771
+ //#region src/core/email-template-service.d.ts
1772
+ /**
1773
+ * Service for managing email templates and logs.
1774
+ */
1775
+ declare class EmailTemplateService {
1776
+ private http;
1777
+ constructor(http: HttpClient);
1778
+ /**
1779
+ * Returns a list of email templates.
1780
+ * @param filters Optional filters for listing templates
1781
+ */
1782
+ list(filters?: EmailTemplateFilters): Promise<EmailTemplate[]>;
1783
+ /**
1784
+ * Returns email template details.
1785
+ * @param templateId Template ID
1786
+ */
1787
+ get(templateId: string): Promise<EmailTemplate>;
1788
+ /**
1789
+ * Updates an email template.
1790
+ * @param templateId Template ID
1791
+ * @param data Update data
1792
+ */
1793
+ update(templateId: string, data: EmailTemplateUpdate): Promise<EmailTemplate>;
1794
+ /**
1795
+ * Renders an email template with provided variables.
1796
+ * @param request Render request data
1797
+ */
1798
+ render(request: EmailTemplateRenderRequest): Promise<EmailTemplateRenderResponse>;
1799
+ /**
1800
+ * Sends a test email using the specified template.
1801
+ * @param templateId Template ID
1802
+ * @param recipientEmail Recipient email address
1803
+ * @param variables Template variables
1804
+ * @param provider Optional provider override
1805
+ */
1806
+ sendTest(templateId: string, recipientEmail: string, variables?: Record<string, any>, provider?: string): Promise<{
1807
+ success: boolean;
1808
+ }>;
1809
+ /**
1810
+ * Returns a paginated list of email logs.
1811
+ * @param filters Optional filters for listing logs
1812
+ */
1813
+ listLogs(filters?: EmailLogFilters): Promise<EmailLogListResponse>;
1814
+ /**
1815
+ * Returns single email log details.
1816
+ * @param logId Log ID
1817
+ */
1818
+ getLog(logId: string): Promise<EmailLog>;
1819
+ }
1820
+ //#endregion
1821
+ //#region src/types/file.d.ts
1822
+ /**
1823
+ * Metadata for a file.
1824
+ */
1825
+ interface FileMetadata {
1826
+ /**
1827
+ * Safe filename.
1828
+ */
1829
+ filename: string;
1830
+ /**
1831
+ * MIME type of the file.
1832
+ */
1833
+ contentType: string;
1834
+ /**
1835
+ * File size in bytes.
1836
+ */
1837
+ size: number;
1838
+ /**
1839
+ * Server path to the file.
1840
+ */
1841
+ path: string;
1842
+ /**
1843
+ * Upload timestamp.
1844
+ */
1845
+ created_at: string;
1846
+ }
1847
+ /**
1848
+ * Options for file upload.
1849
+ */
1850
+ interface FileUploadOptions {
1851
+ /**
1852
+ * Custom filename for the upload.
1853
+ */
1854
+ filename?: string;
1855
+ /**
1856
+ * Custom content type for the upload.
1857
+ */
1858
+ contentType?: string;
1859
+ }
1860
+ //#endregion
1861
+ //#region src/core/file-service.d.ts
1862
+ /**
1863
+ * Service for working with files (upload, download, delete).
1864
+ */
1865
+ declare class FileService {
1866
+ private http;
1867
+ private getBaseUrl;
1868
+ private getToken;
1869
+ constructor(http: HttpClient, getBaseUrl: () => string, getToken: () => string | null);
1870
+ /**
1871
+ * Upload a file to the server.
1872
+ * @param file The file or blob to upload
1873
+ * @param options Optional upload options (filename, contentType)
1874
+ */
1875
+ upload(file: File | Blob, options?: FileUploadOptions): Promise<FileMetadata>;
1876
+ /**
1877
+ * Get the download URL for a file.
1878
+ * @param path The server path to the file
1879
+ */
1880
+ getDownloadUrl(path: string): string;
1881
+ /**
1882
+ * Delete a file from the server.
1883
+ * @param path The server path to the file
1884
+ */
1885
+ delete(path: string): Promise<{
1886
+ success: boolean;
1887
+ }>;
1888
+ }
1889
+ //#endregion
1890
+ //#region src/types/realtime.d.ts
1891
+ type RealTimeState = 'disconnected' | 'connecting' | 'connected' | 'error';
1892
+ type RealTimeEvent = 'connecting' | 'connected' | 'disconnected' | 'error' | 'message';
1893
+ type WebSocketAction = 'subscribe' | 'unsubscribe' | 'ping';
1894
+ interface WebSocketMessage {
1895
+ action: WebSocketAction;
1896
+ collection?: string;
1897
+ operations?: string[];
1898
+ }
1899
+ interface ServerMessage {
1900
+ type: string | 'heartbeat' | 'pong' | 'subscribed' | 'unsubscribed';
1901
+ timestamp: string;
1902
+ data?: any;
1903
+ collection?: string;
1904
+ }
1905
+ /**
1906
+ * Real-time event object structure
1907
+ * @template T - Type of the event data
1908
+ */
1909
+ interface RealtimeEvent<T = any> {
1910
+ /** Event type in format: {collection}.{operation} (e.g., "posts.create") */
1911
+ type: string;
1912
+ /** ISO 8601 timestamp */
1913
+ timestamp: string;
1914
+ /** Event data - full record for create/update, ID only for delete */
1915
+ data: T;
1916
+ }
1917
+ interface RealTimeConfig {
1918
+ maxReconnectionAttempts?: number;
1919
+ heartbeatInterval?: number;
1920
+ reconnectionDelay?: (attempt: number) => number;
1921
+ }
1922
+ type RealTimeEventHandler = (data?: any) => void;
1923
+ /**
1924
+ * Real-time event handlers
1925
+ *
1926
+ * Event type formats:
1927
+ * - Connection events: 'connecting', 'connected', 'disconnected', 'error'
1928
+ * - Message event: 'message' - receives full ServerMessage
1929
+ * - Specific events: '{collection}.{operation}' (e.g., 'posts.create')
1930
+ * - Collection wildcard: '{collection}.*' (e.g., 'posts.*') - all events for a collection
1931
+ * - Global wildcard: '*' - all events
1932
+ */
1933
+ interface RealTimeEvents {
1934
+ connecting: () => void;
1935
+ connected: () => void;
1936
+ disconnected: () => void;
1937
+ error: (error: Error) => void;
1938
+ auth_error: (error: Error) => void;
1939
+ message: (data: ServerMessage) => void;
1940
+ [key: string]: RealTimeEventHandler;
1941
+ }
1942
+ //#endregion
1943
+ //#region src/core/realtime-service.d.ts
1944
+ interface RealTimeOptions {
1945
+ baseUrl: string;
1946
+ getToken: () => string | null;
1947
+ authManager?: AuthManager;
1948
+ maxRetries?: number;
1949
+ reconnectionDelay?: number;
1950
+ logger?: Logger;
1951
+ }
1952
+ declare class RealTimeService {
1953
+ private options;
1954
+ private state;
1955
+ private socket;
1956
+ private sse;
1957
+ private listeners;
1958
+ private retryCount;
1959
+ private reconnectTimer;
1960
+ private heartbeatTimer;
1961
+ private subscriptions;
1962
+ private subscriptionRequests;
1963
+ private pendingSubscriptions;
1964
+ private authUnsubscribe?;
1965
+ private isReconnectingForAuth;
1966
+ constructor(options: RealTimeOptions);
1967
+ connect(): Promise<void>;
1968
+ disconnect(): void;
1969
+ getState(): RealTimeState;
1970
+ on<K extends keyof RealTimeEvents>(event: K, handler: RealTimeEvents[K]): () => void;
1971
+ off<K extends keyof RealTimeEvents>(event: K, handler: RealTimeEvents[K]): void;
1972
+ subscribe(collection: string, operations?: string[]): Promise<void>;
1973
+ unsubscribe(collection: string): Promise<void>;
1974
+ getSubscriptions(): string[];
1975
+ private doConnect;
1976
+ private connectWebSocket;
1977
+ private connectSSE;
1978
+ private handleMessage;
1979
+ private handleReconnect;
1980
+ private handleError;
1981
+ private setState;
1982
+ private emit;
1983
+ private send;
1984
+ private startHeartbeat;
1985
+ private resubscribe;
1986
+ private clearTimers;
1987
+ private closeConnections;
1988
+ /**
1989
+ * Handle token refresh by reconnecting with new token
1990
+ */
1991
+ private handleTokenRefresh;
1992
+ }
1993
+ //#endregion
1994
+ //#region src/types/migration.d.ts
1995
+ /**
1996
+ * Migration-related type definitions.
1997
+ */
1998
+ /**
1999
+ * Represents a single migration revision.
2000
+ */
2001
+ interface MigrationRevision {
2002
+ /** The revision identifier (e.g., "001_abc123") */
2003
+ revision: string;
2004
+ /** Human-readable description of the migration */
2005
+ description: string;
2006
+ /** Whether this revision has been applied to the database */
2007
+ isApplied: boolean;
2008
+ /** Whether this is a dynamic collection migration */
2009
+ isDynamic: boolean;
2010
+ }
2011
+ /**
2012
+ * Response from listing all migrations.
2013
+ */
2014
+ interface MigrationListResponse {
2015
+ /** All available migration revisions */
2016
+ revisions: MigrationRevision[];
2017
+ /** Total number of revisions */
2018
+ total: number;
2019
+ /** The currently applied revision (if any) */
2020
+ currentRevision: string | null;
2021
+ }
2022
+ /**
2023
+ * Response from getting the current migration.
2024
+ */
2025
+ interface CurrentRevisionResponse {
2026
+ /** The current revision identifier */
2027
+ revision: string;
2028
+ /** Human-readable description of the migration */
2029
+ description: string;
2030
+ /** Timestamp when this revision was applied */
2031
+ appliedAt: string;
2032
+ /** Whether this is a dynamic collection migration */
2033
+ isDynamic: boolean;
2034
+ }
2035
+ /**
2036
+ * A single item in the migration history.
2037
+ */
2038
+ interface MigrationHistoryItem {
2039
+ /** The revision identifier */
2040
+ revision: string;
2041
+ /** Human-readable description of the migration */
2042
+ description: string;
2043
+ /** Whether this is a dynamic collection migration */
2044
+ isDynamic: boolean;
2045
+ /** Timestamp when this revision was applied */
2046
+ createdAt: string;
2047
+ }
2048
+ /**
2049
+ * Response from getting migration history.
2050
+ */
2051
+ interface MigrationHistoryResponse {
2052
+ /** Applied migrations in chronological order */
2053
+ history: MigrationHistoryItem[];
2054
+ /** Total number of applied migrations */
2055
+ total: number;
2056
+ }
2057
+ //#endregion
2058
+ //#region src/core/migration-service.d.ts
2059
+ /**
2060
+ * Service for viewing migration status and history.
2061
+ * Requires superadmin authentication.
2062
+ */
2063
+ declare class MigrationService {
2064
+ private http;
2065
+ constructor(http: HttpClient);
2066
+ /**
2067
+ * List all Alembic migration revisions.
2068
+ * Returns all migrations with their application status.
2069
+ */
2070
+ list(): Promise<MigrationListResponse>;
2071
+ /**
2072
+ * Get the current database revision.
2073
+ * Returns the currently applied migration.
2074
+ */
2075
+ getCurrent(): Promise<CurrentRevisionResponse | null>;
2076
+ /**
2077
+ * Get full migration history.
2078
+ * Returns all applied migrations in chronological order.
2079
+ */
2080
+ getHistory(): Promise<MigrationHistoryResponse>;
2081
+ }
2082
+ //#endregion
2083
+ //#region src/core/client.d.ts
2084
+ /**
2085
+ * Main SDK client for interacting with SnackBase API.
2086
+ */
2087
+ declare class SnackBaseClient {
2088
+ private config;
2089
+ private http;
2090
+ private logger;
2091
+ private authManager;
2092
+ private authService;
2093
+ private accountService;
2094
+ private userService;
2095
+ private collectionService;
2096
+ private recordService;
2097
+ private groupsService;
2098
+ private invitationService;
2099
+ private apiKeyService;
2100
+ private auditLogService;
2101
+ private roleService;
2102
+ private collectionRuleService;
2103
+ private macroService;
2104
+ private dashboardService;
2105
+ private adminService;
2106
+ private emailTemplateService;
2107
+ private fileService;
2108
+ private realtimeService;
2109
+ private migrationService;
2110
+ /**
2111
+ * Initialize a new SnackBaseClient instance.
2112
+ * @param config Configuration options
2113
+ */
2114
+ constructor(config: SnackBaseConfig);
2115
+ /**
2116
+ * Returns the current client configuration.
2117
+ */
2118
+ getConfig(): Required<SnackBaseConfig>;
2119
+ /**
2120
+ * Internal helper to access the HTTP client.
2121
+ * @internal
2122
+ */
2123
+ get httpClient(): HttpClient;
2124
+ /**
2125
+ * Sets up the default interceptors for the HTTP client.
2126
+ */
2127
+ private setupInterceptors;
2128
+ /**
2129
+ * Returns the current authenticated user.
2130
+ */
2131
+ get user(): User | null;
2132
+ /**
2133
+ * Returns the current account.
2134
+ */
2135
+ get account(): Account | null;
2136
+ /**
2137
+ * Returns whether the client is currently authenticated.
2138
+ */
2139
+ get isAuthenticated(): boolean;
2140
+ /**
2141
+ * Check if current user is superadmin.
2142
+ */
2143
+ get isSuperadmin(): boolean;
2144
+ /**
2145
+ * Check if current session uses API key authentication.
2146
+ */
2147
+ get isApiKeySession(): boolean;
2148
+ /**
2149
+ * Check if current session uses personal token authentication.
2150
+ */
2151
+ get isPersonalTokenSession(): boolean;
2152
+ /**
2153
+ * Check if current session uses OAuth authentication.
2154
+ */
2155
+ get isOAuthSession(): boolean;
2156
+ /**
2157
+ * Returns the current token type.
2158
+ */
2159
+ get tokenType(): TokenType;
2160
+ /**
2161
+ * Access to authentication methods.
2162
+ */
2163
+ get auth(): AuthService;
2164
+ /**
2165
+ * Access to account management methods.
2166
+ */
2167
+ get accounts(): AccountService;
2168
+ /**
2169
+ * Access to user management methods.
2170
+ */
2171
+ get users(): UserService;
2172
+ /**
2173
+ * Access to collection management methods.
2174
+ */
2175
+ get collections(): CollectionService;
2176
+ /**
2177
+ * Access to record management methods (CRUD on dynamic collections).
2178
+ */
2179
+ get records(): RecordService;
2180
+ /**
2181
+ * Access to group management methods.
2182
+ */
2183
+ get groups(): GroupsService;
2184
+ /**
2185
+ * Access to invitation management methods.
2186
+ */
2187
+ get invitations(): InvitationService;
2188
+ /**
2189
+ * Access to API key management methods.
2190
+ */
2191
+ get apiKeys(): ApiKeyService;
2192
+ /**
2193
+ * Access to audit log management methods.
2194
+ */
2195
+ get auditLogs(): AuditLogService;
2196
+ /**
2197
+ * Access to role management methods.
2198
+ */
2199
+ get roles(): RoleService;
2200
+ /**
2201
+ * Access to collection rule management methods.
2202
+ */
2203
+ get collectionRules(): CollectionRuleService;
2204
+ /**
2205
+ * Access to macro management methods.
2206
+ */
2207
+ get macros(): MacroService;
2208
+ /**
2209
+ * Access to dashboard statistics and monitoring.
2210
+ */
2211
+ get dashboard(): DashboardService;
2212
+ /**
2213
+ * Access to system administration and configuration methods.
2214
+ */
2215
+ get admin(): AdminService;
2216
+ /**
2217
+ * Access to email template management methods.
2218
+ */
2219
+ get emailTemplates(): EmailTemplateService;
2220
+ /**
2221
+ * Access to file management methods.
2222
+ */
2223
+ get files(): FileService;
2224
+ /**
2225
+ * Access to real-time features and subscriptions.
2226
+ */
2227
+ get realtime(): RealTimeService;
2228
+ /**
2229
+ * Access to migration status and history.
2230
+ */
2231
+ get migrations(): MigrationService;
2232
+ /**
2233
+ * Subscribe to authentication events.
2234
+ * @param event Event name
2235
+ * @param listener Callback function
2236
+ */
2237
+ on<K extends keyof AuthEvents>(event: K, listener: AuthEvents[K]): () => void;
2238
+ /**
2239
+ * Authenticate a user with email and password.
2240
+ */
2241
+ login(credentials: LoginCredentials): Promise<AuthResponse>;
2242
+ /**
2243
+ * Log out the current user.
2244
+ */
2245
+ logout(): Promise<{
2246
+ success: boolean;
2247
+ }>;
2248
+ /**
2249
+ * Register a new user and account.
2250
+ */
2251
+ register(data: RegisterData): Promise<AuthResponse>;
2252
+ /**
2253
+ * Refresh the access token using the refresh token.
2254
+ */
2255
+ refreshToken(): Promise<AuthResponse>;
2256
+ /**
2257
+ * Get the current authenticated user profile.
2258
+ */
2259
+ getCurrentUser(): Promise<AuthResponse>;
2260
+ /**
2261
+ * Initiate password reset flow.
2262
+ */
2263
+ forgotPassword(data: PasswordResetRequest): Promise<{
2264
+ message: string;
2265
+ }>;
2266
+ /**
2267
+ * Reset password using a token.
2268
+ */
2269
+ resetPassword(data: PasswordResetConfirm): Promise<{
2270
+ message: string;
2271
+ }>;
2272
+ /**
2273
+ * Verify email using a token.
2274
+ */
2275
+ verifyEmail(token: string): Promise<{
2276
+ message: string;
2277
+ }>;
2278
+ /**
2279
+ * Resend the verification email to the current user.
2280
+ */
2281
+ resendVerificationEmail(): Promise<{
2282
+ message: string;
2283
+ }>;
2284
+ /**
2285
+ * Generate SAML SSO authorization URL.
2286
+ */
2287
+ getSAMLUrl(provider: SAMLProvider, account: string, relayState?: string): Promise<SAMLUrlResponse>;
2288
+ /**
2289
+ * Handle SAML callback.
2290
+ */
2291
+ handleSAMLCallback(params: SAMLCallbackParams): Promise<SAMLResponse>;
2292
+ /**
2293
+ * Get SAML metadata.
2294
+ */
2295
+ getSAMLMetadata(provider: SAMLProvider, account: string): Promise<string>;
2296
+ /**
2297
+ * Internal access to AuthManager.
2298
+ * @internal
2299
+ */
2300
+ get internalAuthManager(): AuthManager;
2301
+ /**
2302
+ * Validates the configuration object.
2303
+ * Throws descriptive errors for invalid options.
2304
+ */
2305
+ private validateConfig;
2306
+ }
2307
+ //#endregion
2308
+ //#region src/core/errors.d.ts
2309
+ /**
2310
+ * Base error class for all SnackBase SDK errors.
2311
+ */
2312
+ declare class SnackBaseError extends Error {
2313
+ redirectUrl?: string | undefined;
2314
+ authProvider?: string | undefined;
2315
+ providerName?: string | undefined;
2316
+ readonly code: string;
2317
+ readonly status?: number;
2318
+ readonly details?: any;
2319
+ readonly field?: string;
2320
+ readonly retryable: boolean;
2321
+ constructor(message: string, code: string, status?: number, details?: any, retryable?: boolean, field?: string, redirectUrl?: string | undefined, authProvider?: string | undefined, providerName?: string | undefined);
2322
+ }
2323
+ /**
2324
+ * Thrown when authentication fails (401).
2325
+ */
2326
+ declare class AuthenticationError extends SnackBaseError {
2327
+ constructor(message?: string, details?: any);
2328
+ }
2329
+ /**
2330
+ * Thrown when the user is not authorized to perform an action (403).
2331
+ */
2332
+ declare class AuthorizationError extends SnackBaseError {
2333
+ constructor(message?: string, details?: any);
2334
+ }
2335
+ /**
2336
+ * Thrown when an API key is restricted to superadmin users (403).
2337
+ */
2338
+ declare class ApiKeyRestrictedError extends SnackBaseError {
2339
+ constructor(message?: string, details?: any);
2340
+ }
2341
+ /**
2342
+ * Thrown when email verification is required (401).
2343
+ */
2344
+ declare class EmailVerificationRequiredError extends SnackBaseError {
2345
+ constructor(message?: string, details?: any);
2346
+ }
2347
+ /**
2348
+ * Thrown when a resource is not found (404).
2349
+ */
2350
+ declare class NotFoundError extends SnackBaseError {
2351
+ constructor(message?: string, details?: any);
2352
+ }
2353
+ /**
2354
+ * Thrown when a conflict occurs (409).
2355
+ */
2356
+ declare class ConflictError extends SnackBaseError {
2357
+ constructor(message?: string, details?: any);
2358
+ }
2359
+ /**
2360
+ * Thrown when validation fails (422).
2361
+ */
2362
+ declare class ValidationError extends SnackBaseError {
2363
+ readonly fields?: Record<string, string[]>;
2364
+ constructor(message?: string, details?: any);
2365
+ }
2366
+ /**
2367
+ * Thrown when rate limit is exceeded (429).
2368
+ */
2369
+ declare class RateLimitError extends SnackBaseError {
2370
+ readonly retryAfter?: number;
2371
+ constructor(message?: string, details?: any, retryAfter?: number);
2372
+ }
2373
+ /**
2374
+ * Thrown when a network failure occurs.
2375
+ */
2376
+ declare class NetworkError extends SnackBaseError {
2377
+ constructor(message?: string, details?: any);
2378
+ }
2379
+ /**
2380
+ * Thrown when a request times out.
2381
+ */
2382
+ declare class TimeoutError extends SnackBaseError {
2383
+ constructor(message?: string, details?: any);
2384
+ }
2385
+ /**
2386
+ * Thrown when a server error occurs (500+).
2387
+ */
2388
+ declare class ServerError extends SnackBaseError {
2389
+ constructor(message?: string, status?: number, details?: any);
2390
+ }
2391
+ //#endregion
2392
+ //#region src/types/utils.d.ts
2393
+ /**
2394
+ * Generic record type with system fields.
2395
+ * Use this to define your record interfaces.
2396
+ *
2397
+ * @example
2398
+ * interface Post {
2399
+ * title: string;
2400
+ * content: string;
2401
+ * views: number;
2402
+ * }
2403
+ * type PostRecord = CollectionRecord<Post>;
2404
+ */
2405
+ type CollectionRecord<T> = T & BaseRecord;
2406
+ /**
2407
+ * Paginated list response type alias.
2408
+ */
2409
+ type ListResponse<T> = RecordListResponse<T>;
2410
+ /**
2411
+ * Filter object type for a collection.
2412
+ * Allows filtering by fields of T.
2413
+ *
2414
+ * This is a basic typed filter. For complex MongoDB-style queries,
2415
+ * you might need more flexible types.
2416
+ */
2417
+ type Filter<T> = { [P in keyof T]?: any } & {
2418
+ [key: string]: any;
2419
+ };
2420
+ /**
2421
+ * Helper to map FieldType strings to TypeScript types.
2422
+ */
2423
+ type FieldTypeToTs<T extends string> = T extends 'text' ? string : T extends 'number' ? number : T extends 'boolean' ? boolean : T extends 'date' ? string : T extends 'datetime' ? string : T extends 'email' ? string : T extends 'url' ? string : T extends 'phone' ? string : T extends 'select' ? string : T extends 'multi_select' ? string[] : T extends 'relation' ? string | string[] : T extends 'json' ? any : any;
2424
+ /**
2425
+ * Infers a record type from a schema definition (array of FieldDefinition).
2426
+ * Note: The schema array must be defined `as const` to work correctly.
2427
+ *
2428
+ * @example
2429
+ * const postSchema = [
2430
+ * { name: 'title', type: 'text' },
2431
+ * { name: 'views', type: 'number' }
2432
+ * ] as const;
2433
+ *
2434
+ * type Post = InferSchema<typeof postSchema>;
2435
+ * // Result: { title: string; views: number }
2436
+ */
2437
+ type InferSchema<T extends readonly FieldDefinition[]> = { [K in T[number] as K['name']]: FieldTypeToTs<K['type']> | (K['required'] extends true ? never : undefined | null) };
2438
+ //#endregion
2439
+ //#region src/utils/platform.d.ts
2440
+ /**
2441
+ * Detects the platform and returns the recommended storage backend.
2442
+ * - Web: localStorage
2443
+ * - React Native: asyncStorage
2444
+ */
2445
+ declare function getAutoDetectedStorage(): StorageBackend;
2446
+ //#endregion
2447
+ export { type Account, ApiKey, ApiKeyCreate, ApiKeyListParams, ApiKeyListResponse, ApiKeyRestrictedError, AuditLog, AuditLogExportFormat, AuditLogExtraMetadata, AuditLogFilters, AuditLogListResponse, AuthEvent, AuthEvents, AuthResponse, AuthState, AuthenticationError, AuthorizationError, BaseRecord, Collection, CollectionCreate, CollectionExportData, CollectionExportFieldDefinition, CollectionExportItem, CollectionExportParams, CollectionExportRules, CollectionImportItemResult, CollectionImportRequest, CollectionImportResult, CollectionRecord, CollectionRule, CollectionRuleUpdate, CollectionUpdate, Configuration, ConfigurationCreate, ConfigurationStats, ConflictError, ConnectionTestResult, CurrentRevisionResponse, DEFAULT_CONFIG, DashboardStats, EmailLog, EmailLogFilters, EmailLogListResponse, EmailTemplate, EmailTemplateFilters, EmailTemplateRenderRequest, EmailTemplateRenderResponse, EmailTemplateType, EmailTemplateUpdate, EmailVerificationRequiredError, FieldDefinition, FieldType, FieldTypeToTs, FileMetadata, FileUploadOptions, Filter, FilterExpression, FilterOperator, Group, GroupCreate, GroupListParams, GroupListResponse, GroupUpdate, ImportStrategy, InferSchema, Invitation, InvitationCreate, InvitationListParams, ListResponse, LogLevel, LoginCredentials, MigrationHistoryItem, MigrationHistoryResponse, MigrationListResponse, MigrationRevision, NetworkError, NotFoundError, OAuthCallbackParams, OAuthProvider, OAuthResponse, OAuthUrlResponse, PasswordResetConfirm, PasswordResetRequest, Permission, ProviderDefinition, QueryBuilder, QueryParams, RateLimitError, RealTimeConfig, RealTimeEvent, RealTimeEventHandler, RealTimeEvents, RealTimeState, RealtimeEvent, RecentConfiguration, RecordListParams, RecordListResponse, RegisterData, Role, RoleCreate, RoleListResponse, RoleUpdate, RuleTestResult, RuleValidationParams, RuleValidationResult, SAMLCallbackParams, SAMLProvider, SAMLResponse, SAMLUrlResponse, ServerError, ServerMessage, type SnackBaseClient as SnackBase, SnackBaseClient, SnackBaseConfig, SnackBaseError, SortDirection, SortExpression, StorageBackend, SystemHealth, TimeoutError, TokenType, type User, UserCreate, UserListParams, type UserListResponse, UserUpdate, ValidationError, WebSocketAction, WebSocketMessage, getAutoDetectedStorage };