@mitralab.io/platform-sdk 1.0.8 → 1.1.0-beta.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 DELETED
@@ -1,659 +0,0 @@
1
- import { Transport, TransportRequestOptions, QueryParamValue, EntityTable, ProxyResult } from '@mitralab.io/sdk-core';
2
- export { EntityListOptions, EntityTable, ProxyResult } from '@mitralab.io/sdk-core';
3
-
4
- /**
5
- * Configuration options for creating an HttpClient instance.
6
- */
7
- interface HttpClientConfig {
8
- /** Base URL for all HTTP requests (e.g., 'https://api.mitra.io') */
9
- baseUrl: string;
10
- /** Function that returns the current authentication token, or null if not authenticated */
11
- getToken?: () => string | null;
12
- /** Callback invoked on 401 responses. Should attempt token refresh and return true if successful. */
13
- onUnauthorized?: () => Promise<boolean>;
14
- /** Called whenever an API request fails. Useful for global error handling (e.g., toast notifications). */
15
- onError?: (error: MitraApiError) => void;
16
- /** Headers included in every request (e.g., X-App-Id for tracing). */
17
- defaultHeaders?: Record<string, string>;
18
- }
19
- /**
20
- * Options for making HTTP requests.
21
- */
22
- interface RequestOptions extends Omit<TransportRequestOptions, 'method'> {
23
- /** HTTP method (defaults to 'GET') */
24
- method?: 'GET' | 'POST' | 'PUT' | 'DELETE' | 'PATCH';
25
- /** Request body (will be JSON stringified) */
26
- body?: unknown;
27
- /** Additional headers to include in the request */
28
- headers?: Record<string, string>;
29
- /** URL query parameters */
30
- params?: Record<string, QueryParamValue>;
31
- /** @internal Flag to prevent infinite retry loops on 401 */
32
- isRetry?: boolean;
33
- }
34
- /**
35
- * HTTP client for making authenticated API requests.
36
- *
37
- * Handles JSON serialization, authentication headers, and error handling.
38
- * All requests automatically include the Authorization header when a token is available.
39
- *
40
- * @example
41
- * ```typescript
42
- * const client = new HttpClient({
43
- * baseUrl: 'https://api.mitra.io',
44
- * getToken: () => localStorage.getItem('token'),
45
- * });
46
- *
47
- * const users = await client.get<User[]>('/users');
48
- * const user = await client.post<User>('/users', { name: 'John' });
49
- * ```
50
- */
51
- declare class HttpClient implements Transport {
52
- private readonly baseUrl;
53
- private readonly tokenGetter;
54
- private readonly onUnauthorized?;
55
- private readonly onError?;
56
- private readonly defaultHeaders;
57
- constructor(config: HttpClientConfig);
58
- /**
59
- * Returns the current authentication token.
60
- * @returns The JWT token if authenticated, null otherwise
61
- */
62
- getToken(): string | null;
63
- /**
64
- * Makes an HTTP request with automatic JSON handling and authentication.
65
- *
66
- * @param path - API endpoint path (e.g., '/users')
67
- * @param options - Request options including method, body, headers, and params
68
- * @returns Promise resolving to the parsed JSON response
69
- * @throws {MitraApiError} When the API returns an error response
70
- *
71
- * @example
72
- * ```typescript
73
- * const result = await client.request<User>('/users/123', {
74
- * method: 'PUT',
75
- * body: { name: 'Updated Name' },
76
- * });
77
- * ```
78
- */
79
- request<T>(path: string, options?: RequestOptions): Promise<T>;
80
- /**
81
- * Makes a GET request.
82
- *
83
- * @param path - API endpoint path
84
- * @param params - Optional query parameters
85
- * @returns Promise resolving to the parsed JSON response
86
- *
87
- * @example
88
- * ```typescript
89
- * const users = await client.get<User[]>('/users', { limit: 10 });
90
- * ```
91
- */
92
- get<T>(path: string, params?: Record<string, QueryParamValue>): Promise<T>;
93
- /**
94
- * Makes a POST request.
95
- *
96
- * @param path - API endpoint path
97
- * @param body - Request body (will be JSON stringified)
98
- * @returns Promise resolving to the parsed JSON response
99
- *
100
- * @example
101
- * ```typescript
102
- * const user = await client.post<User>('/users', { name: 'John', email: 'john@example.com' });
103
- * ```
104
- */
105
- post<T>(path: string, body?: unknown): Promise<T>;
106
- /**
107
- * Makes a PUT request.
108
- *
109
- * @param path - API endpoint path
110
- * @param body - Request body (will be JSON stringified)
111
- * @returns Promise resolving to the parsed JSON response
112
- *
113
- * @example
114
- * ```typescript
115
- * const user = await client.put<User>('/users/123', { name: 'Updated Name' });
116
- * ```
117
- */
118
- put<T>(path: string, body?: unknown): Promise<T>;
119
- /**
120
- * Makes a DELETE request.
121
- *
122
- * @param path - API endpoint path
123
- * @param params - Optional query parameters
124
- * @returns Promise resolving to the parsed JSON response (or undefined for 204 responses)
125
- *
126
- * @example
127
- * ```typescript
128
- * await client.delete('/users/123');
129
- * ```
130
- */
131
- delete<T>(path: string, params?: Record<string, QueryParamValue>): Promise<T>;
132
- }
133
- /**
134
- * Error thrown when a Mitra API request fails.
135
- *
136
- * Contains detailed information about the error including HTTP status,
137
- * error code, and additional details from the server response.
138
- *
139
- * @example
140
- * ```typescript
141
- * try {
142
- * await mitra.entities.Task.get('invalid-id');
143
- * } catch (error) {
144
- * if (error instanceof MitraApiError) {
145
- * console.log(error.status); // 404
146
- * console.log(error.message); // "Task not found"
147
- * console.log(error.code); // "ENTITY_NOT_FOUND"
148
- * }
149
- * }
150
- * ```
151
- */
152
- declare class MitraApiError extends Error {
153
- /** HTTP status code (e.g., 400, 401, 404, 500) */
154
- readonly status: number;
155
- /** Application-specific error code (e.g., 'ENTITY_NOT_FOUND', 'VALIDATION_ERROR') */
156
- readonly code?: string | undefined;
157
- /** Additional error details from the server response */
158
- readonly details?: unknown | undefined;
159
- constructor(message: string,
160
- /** HTTP status code (e.g., 400, 401, 404, 500) */
161
- status: number,
162
- /** Application-specific error code (e.g., 'ENTITY_NOT_FOUND', 'VALIDATION_ERROR') */
163
- code?: string | undefined,
164
- /** Additional error details from the server response */
165
- details?: unknown | undefined);
166
- }
167
-
168
- /** Authenticated user in the Mitra Platform. */
169
- interface User {
170
- /** Unique identifier. */
171
- id: string;
172
- /** Tenant the user belongs to. */
173
- tenantId: string;
174
- /** Email address. */
175
- email: string;
176
- /** Display name (optional). */
177
- name: string | null;
178
- }
179
- /** Credentials for sign-in. */
180
- interface SignInCredentials {
181
- email: string;
182
- password: string;
183
- }
184
- /** Data for user registration. */
185
- interface SignUpData {
186
- email: string;
187
- password: string;
188
- name?: string;
189
- }
190
- /** Callback for auth state changes. Receives the user on login, null on logout. */
191
- type AuthStateChangeCallback = (user: User | null) => void;
192
-
193
- /**
194
- * Authentication module for managing user sessions.
195
- *
196
- * Handles sign-in, sign-up, sign-out, and automatic token refresh.
197
- * Auth state is persisted to localStorage with key `mitra_auth_{appId}`
198
- * and restored on page reload.
199
- *
200
- * @example
201
- * ```typescript
202
- * await mitra.auth.signIn({ email: 'user@example.com', password: 'password' });
203
- * console.log(mitra.auth.currentUser);
204
- * ```
205
- */
206
- declare class AuthModule {
207
- #private;
208
- private readonly appId;
209
- private _currentUser;
210
- private refreshPromise;
211
- private readonly listeners;
212
- private readonly storageKey;
213
- private readonly publicClient;
214
- private readonly authedClient;
215
- private readonly currentUserApi;
216
- constructor(appId: string, iamBaseUrl: string);
217
- /** The currently authenticated user, or null. */
218
- get currentUser(): User | null;
219
- /** The current JWT access token, or null. */
220
- get accessToken(): string | null;
221
- /** Whether a user is currently authenticated (local check, not server-validated). */
222
- get isAuthenticated(): boolean;
223
- /**
224
- * Signs in a user with email and password.
225
- *
226
- * On success, stores access token, refresh token, and user data.
227
- * Subsequent API requests use the token automatically.
228
- *
229
- * @param credentials - Email and password.
230
- * @returns The authenticated user.
231
- * @throws {MitraApiError} On invalid credentials (401).
232
- *
233
- * @example
234
- * ```typescript
235
- * const user = await mitra.auth.signIn({
236
- * email: 'user@example.com',
237
- * password: 'password123',
238
- * });
239
- * ```
240
- */
241
- signIn(credentials: SignInCredentials): Promise<User>;
242
- /**
243
- * Registers a new user and signs them in automatically.
244
- *
245
- * @param data - Email, password, and optional name.
246
- * @returns The newly created and authenticated user.
247
- * @throws {MitraApiError} On duplicate email (409) or validation error (400).
248
- *
249
- * @example
250
- * ```typescript
251
- * const user = await mitra.auth.signUp({
252
- * email: 'new@example.com',
253
- * password: 'securepassword',
254
- * name: 'Jane Doe',
255
- * });
256
- * ```
257
- */
258
- signUp(data: SignUpData): Promise<User>;
259
- /**
260
- * Signs out the current user, clearing all auth state and localStorage.
261
- *
262
- * @param redirectUrl - Optional URL to navigate to after sign-out.
263
- *
264
- * @example
265
- * ```typescript
266
- * mitra.auth.signOut();
267
- * mitra.auth.signOut('/login');
268
- * ```
269
- */
270
- signOut(redirectUrl?: string): void;
271
- /**
272
- * Refreshes the session using the stored refresh token.
273
- *
274
- * Called automatically by the SDK on 401 responses. Can also be called
275
- * manually. Multiple concurrent calls are deduplicated (only one refresh
276
- * request is made).
277
- *
278
- * @returns `true` if refresh succeeded, `false` otherwise.
279
- *
280
- * @example
281
- * ```typescript
282
- * const ok = await mitra.auth.refreshSession();
283
- * if (!ok) mitra.auth.redirectToLogin();
284
- * ```
285
- */
286
- refreshSession(): Promise<boolean>;
287
- /**
288
- * Fetches the current user from the server and updates local state.
289
- *
290
- * Only clears auth state on 401 (expired/invalid token).
291
- * Transient errors (500, network) return null without clearing the session.
292
- *
293
- * @returns The user if authenticated, `null` otherwise.
294
- *
295
- * @example
296
- * ```typescript
297
- * const user = await mitra.auth.me();
298
- * if (!user) console.log('Not authenticated');
299
- * ```
300
- */
301
- me(): Promise<User | null>;
302
- /**
303
- * Validates the current session with the server.
304
- *
305
- * @returns `true` if the session is valid, `false` otherwise.
306
- *
307
- * @example
308
- * ```typescript
309
- * const valid = await mitra.auth.checkAuth();
310
- * if (!valid) mitra.auth.redirectToLogin();
311
- * ```
312
- */
313
- checkAuth(): Promise<boolean>;
314
- /**
315
- * Sets the access token manually (e.g., from SSO/OAuth callback).
316
- *
317
- * Call `me()` afterwards to fetch the associated user data.
318
- *
319
- * @param token - JWT access token.
320
- * @param saveToStorage - Whether to persist to localStorage (default: true).
321
- *
322
- * @example
323
- * ```typescript
324
- * mitra.auth.setToken(tokenFromCallback);
325
- * await mitra.auth.me();
326
- * ```
327
- */
328
- setToken(token: string, saveToStorage?: boolean): void;
329
- /**
330
- * Redirects to `/login?returnUrl=...` for unauthenticated users.
331
- *
332
- * @param returnUrl - URL to return to after login (default: '/').
333
- *
334
- * @example
335
- * ```typescript
336
- * if (!mitra.auth.isAuthenticated) {
337
- * mitra.auth.redirectToLogin(window.location.pathname);
338
- * }
339
- * ```
340
- */
341
- redirectToLogin(returnUrl?: string): void;
342
- /**
343
- * Registers a callback for auth state changes.
344
- *
345
- * Called immediately with the current state, then on every sign-in/sign-out.
346
- *
347
- * @param callback - Receives the User on login, null on logout.
348
- * @returns Unsubscribe function.
349
- *
350
- * @example
351
- * ```typescript
352
- * useEffect(() => {
353
- * const unsub = mitra.auth.onAuthStateChange((user) => {
354
- * setUser(user);
355
- * setLoading(false);
356
- * });
357
- * return unsub;
358
- * }, []);
359
- * ```
360
- */
361
- onAuthStateChange(callback: AuthStateChangeCallback): () => void;
362
- private doRefresh;
363
- private setAuthState;
364
- private getCurrentUser;
365
- private clearAuthState;
366
- private notifyListeners;
367
- private saveToStorage;
368
- private loadFromStorage;
369
- private removeFromStorage;
370
- }
371
-
372
- /**
373
- * Compatibility facade for the Platform SDK 1.x entity API.
374
- * Shared request behavior lives in `@mitralab.io/sdk-core`.
375
- */
376
- declare class EntitiesModule {
377
- private readonly httpClient;
378
- private core;
379
- constructor(httpClient: HttpClient, dataSourceId: string);
380
- static createProxy(httpClient: HttpClient, dataSourceId: string): EntitiesModule;
381
- /**
382
- * Preserved for Platform SDK 1.x compatibility.
383
- * Records now resolve the app from authenticated context instead of a data source path.
384
- */
385
- setDataSourceId(dataSourceId: string): void;
386
- getTable<T = Record<string, unknown>>(tableName: string): EntityTable<T>;
387
- }
388
- type EntitiesProxy = EntitiesModule & {
389
- [tableName: string]: EntityTable;
390
- };
391
-
392
- /** Result of a serverless function execution. */
393
- interface FunctionExecution {
394
- /** Unique execution ID. */
395
- id: string;
396
- /** ID of the executed function. */
397
- functionId: string;
398
- /** ID of the function version that was executed. */
399
- functionVersionId: string;
400
- /** Execution status returned by the Functions service. */
401
- status: string;
402
- /** Input data passed to the function. */
403
- input: Record<string, unknown>;
404
- /** Output data returned by the function. */
405
- output: Record<string, unknown> | null;
406
- /** Error message if execution failed. */
407
- errorMessage: string | null;
408
- /** Execution logs. */
409
- logs: string | null;
410
- /** Duration in milliseconds. */
411
- durationMs: number | null;
412
- /** When execution started (ISO 8601). */
413
- startedAt: string | null;
414
- /** When execution finished (ISO 8601). */
415
- finishedAt: string | null;
416
- /** When the execution record was created (ISO 8601). */
417
- createdAt: string;
418
- }
419
-
420
- /** Platform SDK 1.x facade over the shared Function contract. */
421
- declare class FunctionsModule {
422
- private readonly core;
423
- constructor(httpClient: HttpClient);
424
- /**
425
- * Executes a Function using the Platform SDK 1.x server-default invocation semantics.
426
- * The runtime SDK uses an explicit invocation header instead.
427
- */
428
- execute(functionId: string, input?: Record<string, unknown>): Promise<FunctionExecution>;
429
- }
430
-
431
- /** Input for a proxied HTTP request through an integration. */
432
- interface ProxyInput {
433
- /** HTTP method (GET, POST, PUT, DELETE, etc.). */
434
- method: string;
435
- /** API endpoint path (appended to the template's baseUrl). */
436
- endpoint: string;
437
- /** Additional headers. */
438
- headers?: Record<string, string>;
439
- /** Request body. */
440
- body?: unknown;
441
- /** Query parameters. */
442
- queryParams?: Record<string, string>;
443
- }
444
-
445
- /** Platform SDK 1.x facade over the shared integration contract. */
446
- declare class IntegrationModule {
447
- private readonly core;
448
- constructor(httpClient: HttpClient);
449
- executeResource(resourceId: string, params?: Record<string, unknown>): Promise<ProxyResult>;
450
- execute(configId: string, request: ProxyInput): Promise<ProxyResult>;
451
- }
452
-
453
- /** Result of executing a custom query. */
454
- interface QueryResult {
455
- /** Array of row objects returned by the query. */
456
- rows: Record<string, unknown>[];
457
- /** Number of affected rows (null for SELECT). */
458
- affectedRows: number | null;
459
- }
460
-
461
- /** Platform SDK 1.x facade over the shared custom query contract. */
462
- declare class QueriesModule {
463
- private dataSourceId;
464
- private readonly core;
465
- constructor(httpClient: HttpClient);
466
- /** Called by `client.init()` to set the app's resolved data source. */
467
- setDataSourceId(dataSourceId: string): void;
468
- execute(id: string, parameters?: Record<string, unknown>): Promise<QueryResult>;
469
- }
470
-
471
- /**
472
- * Configuration options for creating a Mitra client.
473
- */
474
- interface MitraClientConfig {
475
- /**
476
- * Your app's unique identifier.
477
- * Found in the Mitra Code Studio dashboard.
478
- */
479
- appId: string;
480
- /**
481
- * Base URL for the Mitra API (Kong Gateway).
482
- * Injected automatically via `VITE_MITRA_API_URL` environment variable
483
- * during the Code Studio build process.
484
- *
485
- * @example
486
- * ```typescript
487
- * apiUrl: import.meta.env.VITE_MITRA_API_URL
488
- * ```
489
- */
490
- apiUrl: string;
491
- /**
492
- * Global error handler called whenever an API request fails.
493
- * Useful for displaying toast notifications or logging errors.
494
- *
495
- * @example
496
- * ```typescript
497
- * const mitra = createClient({
498
- * appId: 'your-app-id',
499
- * onError: (error) => toast.error(error.message),
500
- * });
501
- * ```
502
- */
503
- onError?: (error: MitraApiError) => void;
504
- }
505
- /**
506
- * The Mitra client instance providing access to all SDK modules.
507
- *
508
- * @example
509
- * ```typescript
510
- * const mitra = createClient({
511
- * appId: 'your-app-id',
512
- * });
513
- *
514
- * // Initialize (resolves app config automatically)
515
- * await mitra.init();
516
- *
517
- * // Authentication
518
- * await mitra.auth.signIn({ email, password });
519
- *
520
- * // Database operations
521
- * const tasks = await mitra.entities.Task.list();
522
- *
523
- * // Serverless functions
524
- * const execution = await mitra.functions.execute('function-id', { orderId });
525
- * ```
526
- */
527
- interface MitraClient {
528
- /**
529
- * Initializes the client by resolving app config from the server.
530
- *
531
- * Must be called before using `auth.signUp()` or `entities`.
532
- * Fetches dataSourceId and allowSignup from the public app info endpoint.
533
- *
534
- * Safe to call multiple times. Subsequent calls are no-ops.
535
- *
536
- * @example
537
- * ```typescript
538
- * const mitra = createClient({ appId: 'your-app-id' });
539
- * await mitra.init();
540
- * ```
541
- */
542
- init(): Promise<void>;
543
- /**
544
- * Authentication module for managing user sessions.
545
- *
546
- * Handles user registration, login, logout, and session persistence.
547
- *
548
- * @example
549
- * ```typescript
550
- * await mitra.auth.signIn({ email: 'user@example.com', password: 'password' });
551
- * console.log(mitra.auth.currentUser);
552
- * ```
553
- */
554
- auth: AuthModule;
555
- /**
556
- * Entities module for database CRUD operations.
557
- *
558
- * Access any table dynamically using `mitra.entities.TableName`.
559
- *
560
- * @example
561
- * ```typescript
562
- * const tasks = await mitra.entities.Task.list('-created_at', 10);
563
- * const task = await mitra.entities.Task.create({ title: 'New task' });
564
- * ```
565
- */
566
- entities: EntitiesProxy;
567
- /**
568
- * Functions module for executing serverless functions.
569
- *
570
- * @example
571
- * ```typescript
572
- * const execution = await mitra.functions.execute('function-id', { orderId });
573
- * console.log(execution.status, execution.output);
574
- * ```
575
- */
576
- functions: FunctionsModule;
577
- /**
578
- * Integration module for proxying HTTP requests to external APIs.
579
- *
580
- * Sends requests through the Mitra server, which handles authentication
581
- * and credential injection automatically based on the template config.
582
- *
583
- * @example
584
- * ```typescript
585
- * const result = await mitra.integration.execute('config-id', {
586
- * method: 'GET',
587
- * endpoint: '/users',
588
- * });
589
- * console.log(result.body);
590
- * ```
591
- */
592
- integration: IntegrationModule;
593
- /**
594
- * Queries module for executing reusable named SELECT queries.
595
- *
596
- * @example
597
- * ```typescript
598
- * const result = await mitra.queries.execute('query-id', { status: 'active' });
599
- * console.log(result.rows);
600
- * ```
601
- */
602
- queries: QueriesModule;
603
- /**
604
- * Whether this app allows public user registration.
605
- * Defaults to `true` before `init()` is called.
606
- */
607
- readonly allowSignup: boolean;
608
- /**
609
- * The configuration used to create this client.
610
- */
611
- config: MitraClientConfig;
612
- }
613
- /**
614
- * Creates a new Mitra client instance.
615
- *
616
- * The client provides access to all Mitra Platform features:
617
- * - **auth**: User authentication and session management
618
- * - **entities**: Database CRUD operations
619
- * - **functions**: Serverless function invocation
620
- * - **integration**: Proxy HTTP requests to external APIs
621
- * - **queries**: Custom query management and execution
622
- *
623
- * After creating the client, call `init()` to resolve the app's config
624
- * (dataSourceId, allowSignup) automatically from the server.
625
- *
626
- * @param config - Configuration options for the client.
627
- * @returns A configured MitraClient instance.
628
- *
629
- * @example
630
- * ```typescript
631
- * import { createClient } from 'mitra-platform-sdk';
632
- *
633
- * const mitra = createClient({
634
- * appId: import.meta.env.VITE_MITRA_APP_ID,
635
- * apiUrl: import.meta.env.VITE_MITRA_API_URL,
636
- * });
637
- *
638
- * await mitra.init();
639
- *
640
- * // Use the client
641
- * await mitra.auth.signIn({ email, password });
642
- * const tasks = await mitra.entities.Task.list();
643
- * ```
644
- *
645
- * @example
646
- * ```typescript
647
- * // Export as singleton for use throughout your app
648
- * // src/api/mitraClient.ts
649
- * import { createClient } from 'mitra-platform-sdk';
650
- *
651
- * export const mitra = createClient({
652
- * appId: import.meta.env.VITE_MITRA_APP_ID,
653
- * apiUrl: import.meta.env.VITE_MITRA_API_URL,
654
- * });
655
- * ```
656
- */
657
- declare function createClient(config: MitraClientConfig): MitraClient;
658
-
659
- export { type FunctionExecution, MitraApiError, type MitraClient, type MitraClientConfig, type ProxyInput, type QueryResult, type SignInCredentials, type SignUpData, type User, createClient };