@mitralab.io/platform-sdk 1.0.7 → 1.0.8

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,5 +1,6 @@
1
- /** Allowed query parameter value types. */
2
- type QueryParamValue = string | number | boolean | undefined;
1
+ import { Transport, TransportRequestOptions, QueryParamValue, EntityTable, ProxyResult } from '@mitralab.io/sdk-core';
2
+ export { EntityListOptions, EntityTable, ProxyResult } from '@mitralab.io/sdk-core';
3
+
3
4
  /**
4
5
  * Configuration options for creating an HttpClient instance.
5
6
  */
@@ -18,7 +19,7 @@ interface HttpClientConfig {
18
19
  /**
19
20
  * Options for making HTTP requests.
20
21
  */
21
- interface RequestOptions {
22
+ interface RequestOptions extends Omit<TransportRequestOptions, 'method'> {
22
23
  /** HTTP method (defaults to 'GET') */
23
24
  method?: 'GET' | 'POST' | 'PUT' | 'DELETE' | 'PATCH';
24
25
  /** Request body (will be JSON stringified) */
@@ -47,7 +48,7 @@ interface RequestOptions {
47
48
  * const user = await client.post<User>('/users', { name: 'John' });
48
49
  * ```
49
50
  */
50
- declare class HttpClient {
51
+ declare class HttpClient implements Transport {
51
52
  private readonly baseUrl;
52
53
  private readonly tokenGetter;
53
54
  private readonly onUnauthorized?;
@@ -203,15 +204,15 @@ type AuthStateChangeCallback = (user: User | null) => void;
203
204
  * ```
204
205
  */
205
206
  declare class AuthModule {
207
+ #private;
206
208
  private readonly appId;
207
209
  private _currentUser;
208
- private _accessToken;
209
- private _refreshToken;
210
210
  private refreshPromise;
211
211
  private readonly listeners;
212
212
  private readonly storageKey;
213
213
  private readonly publicClient;
214
214
  private readonly authedClient;
215
+ private readonly currentUserApi;
215
216
  constructor(appId: string, iamBaseUrl: string);
216
217
  /** The currently authenticated user, or null. */
217
218
  get currentUser(): User | null;
@@ -360,6 +361,7 @@ declare class AuthModule {
360
361
  onAuthStateChange(callback: AuthStateChangeCallback): () => void;
361
362
  private doRefresh;
362
363
  private setAuthState;
364
+ private getCurrentUser;
363
365
  private clearAuthState;
364
366
  private notifyListeners;
365
367
  private saveToStorage;
@@ -368,401 +370,20 @@ declare class AuthModule {
368
370
  }
369
371
 
370
372
  /**
371
- * Options for listing entities with sorting and pagination.
372
- */
373
- interface EntityListOptions {
374
- /**
375
- * Field to sort by. Prefix with '-' for descending order.
376
- *
377
- * @example
378
- * ```typescript
379
- * // Sort by created_at descending (newest first)
380
- * { sort: '-created_at' }
381
- *
382
- * // Sort by name ascending (A-Z)
383
- * { sort: 'name' }
384
- * ```
385
- */
386
- sort?: string;
387
- /**
388
- * Maximum number of records to return.
389
- * Defaults to 100. Maximum allowed is 1000.
390
- */
391
- limit?: number;
392
- /**
393
- * Number of records to skip for pagination.
394
- * Use with `limit` to implement pagination.
395
- *
396
- * @example
397
- * ```typescript
398
- * // Get page 2 (records 11-20)
399
- * { limit: 10, skip: 10 }
400
- * ```
401
- */
402
- skip?: number;
403
- /**
404
- * Array of field names to include in the response.
405
- * If not specified, all fields are returned.
406
- *
407
- * @example
408
- * ```typescript
409
- * // Only return id, title, and status
410
- * { fields: ['id', 'title', 'status'] }
411
- * ```
412
- */
413
- fields?: string[];
414
- }
415
- /**
416
- * Entity handler providing CRUD operations for a specific entity type.
417
- *
418
- * Each table in the database gets a handler with these methods for managing data.
419
- * Access tables dynamically using `mitra.entities.TableName`.
420
- *
421
- * @typeParam T - The shape of records in this table. Defaults to `Record<string, unknown>`.
422
- *
423
- * @example
424
- * ```typescript
425
- * // Dynamic access (no type safety)
426
- * const tasks = await mitra.entities.Task.list();
427
- *
428
- * // Typed access
429
- * interface Task {
430
- * id: string;
431
- * title: string;
432
- * status: 'pending' | 'done';
433
- * }
434
- * const tasks = mitra.entities.getTable<Task>('Task');
435
- * const pending = await tasks.filter({ status: 'pending' });
436
- * ```
437
- */
438
- interface EntityTable<T = Record<string, unknown>> {
439
- /**
440
- * Lists records with optional pagination and sorting.
441
- *
442
- * Retrieves all records from the table with support for sorting,
443
- * pagination, and field selection. Supports both positional parameters
444
- * (for quick usage) and options object (for clarity).
445
- *
446
- * @param sortOrOptions - Sort field (e.g., '-created_at') or options object.
447
- * @param limit - Maximum number of results to return. Defaults to 100.
448
- * @param skip - Number of results to skip for pagination. Defaults to 0.
449
- * @param fields - Array of field names to include in the response.
450
- * @returns Promise resolving to an array of records.
451
- *
452
- * @example
453
- * ```typescript
454
- * // Get all records
455
- * const tasks = await mitra.entities.Task.list();
456
- * ```
457
- *
458
- * @example
459
- * ```typescript
460
- * // Get first 10 records sorted by date (newest first)
461
- * const tasks = await mitra.entities.Task.list('-created_at', 10);
462
- * ```
463
- *
464
- * @example
465
- * ```typescript
466
- * // Get paginated results (page 3, 10 items per page)
467
- * const tasks = await mitra.entities.Task.list('-created_at', 10, 20);
468
- * ```
469
- *
470
- * @example
471
- * ```typescript
472
- * // Using options object
473
- * const tasks = await mitra.entities.Task.list({
474
- * sort: '-created_at',
475
- * limit: 10,
476
- * skip: 0,
477
- * fields: ['id', 'title', 'status'],
478
- * });
479
- * ```
480
- */
481
- list(sortOrOptions?: string | EntityListOptions, limit?: number, skip?: number, fields?: string[]): Promise<T[]>;
482
- /**
483
- * Filters records based on a query.
484
- *
485
- * Retrieves records that match specific criteria with support for
486
- * sorting, pagination, and field selection. All query conditions
487
- * are combined with AND logic.
488
- *
489
- * @param query - Query object with field-value pairs. Records matching
490
- * all specified criteria are returned. Field names are case-sensitive.
491
- * @param sort - Sort field (prefix '-' for descending). Defaults to '-created_at'.
492
- * @param limit - Maximum number of results to return. Defaults to 100.
493
- * @param skip - Number of results to skip for pagination. Defaults to 0.
494
- * @param fields - Array of field names to include in the response.
495
- * @returns Promise resolving to an array of matching records.
496
- *
497
- * @example
498
- * ```typescript
499
- * // Filter by single field
500
- * const doneTasks = await mitra.entities.Task.filter({ status: 'done' });
501
- * ```
502
- *
503
- * @example
504
- * ```typescript
505
- * // Filter by multiple fields (AND logic)
506
- * const urgentTasks = await mitra.entities.Task.filter({
507
- * status: 'pending',
508
- * priority: 'high',
509
- * });
510
- * ```
511
- *
512
- * @example
513
- * ```typescript
514
- * // Filter with sorting and pagination
515
- * const tasks = await mitra.entities.Task.filter(
516
- * { status: 'pending' },
517
- * '-priority', // sort by priority descending
518
- * 10, // limit
519
- * 0 // skip
520
- * );
521
- * ```
522
- *
523
- * @example
524
- * ```typescript
525
- * // Filter with specific fields
526
- * const tasks = await mitra.entities.Task.filter(
527
- * { assignee: 'user-123' },
528
- * '-created_at',
529
- * 20,
530
- * 0,
531
- * ['id', 'title', 'status']
532
- * );
533
- * ```
534
- *
535
- * @example
536
- * ```typescript
537
- * // Comparison operators: $gt, $gte, $lt, $lte, $ne
538
- * const expensive = await mitra.entities.Product.filter({ price: { $gt: 100 } });
539
- * const recent = await mitra.entities.Order.filter({ created_at: { $gte: '2025-01-01' } });
540
- * const notDone = await mitra.entities.Task.filter({ status: { $ne: 'done' } });
541
- * ```
542
- *
543
- * @example
544
- * ```typescript
545
- * // Range query (combines with AND)
546
- * const midRange = await mitra.entities.Product.filter({
547
- * price: { $gte: 50, $lte: 200 },
548
- * });
549
- * ```
550
- *
551
- * @example
552
- * ```typescript
553
- * // Mix equality and operators
554
- * const results = await mitra.entities.Order.filter({
555
- * status: 'shipped',
556
- * total: { $gt: 1000 },
557
- * });
558
- * ```
559
- */
560
- filter(query: Record<string, unknown>, sort?: string, limit?: number, skip?: number, fields?: string[]): Promise<T[]>;
561
- /**
562
- * Gets a single record by ID.
563
- *
564
- * Retrieves a specific record using its unique identifier.
565
- *
566
- * @param id - The unique identifier of the record.
567
- * @returns Promise resolving to the record.
568
- * @throws {MitraApiError} When record is not found (404).
569
- *
570
- * @example
571
- * ```typescript
572
- * const task = await mitra.entities.Task.get('task-123');
573
- * console.log(task.title);
574
- * ```
575
- *
576
- * @example
577
- * ```typescript
578
- * // With error handling
579
- * try {
580
- * const task = await mitra.entities.Task.get(taskId);
581
- * setTask(task);
582
- * } catch (error) {
583
- * if (error.status === 404) {
584
- * console.error('Task not found');
585
- * }
586
- * }
587
- * ```
588
- */
589
- get(id: string | number): Promise<T>;
590
- /**
591
- * Creates a new record.
592
- *
593
- * Creates a new record in the table with the provided data.
594
- * The server will generate an `id` and timestamps automatically.
595
- *
596
- * @param data - Object containing the record data.
597
- * @returns Promise resolving to the created record (including generated id).
598
- * @throws {MitraApiError} When validation fails (400).
599
- *
600
- * @example
601
- * ```typescript
602
- * const task = await mitra.entities.Task.create({
603
- * title: 'Complete documentation',
604
- * status: 'pending',
605
- * priority: 'high',
606
- * });
607
- * console.log('Created task:', task.id);
608
- * ```
609
- *
610
- * @example
611
- * ```typescript
612
- * // With error handling
613
- * try {
614
- * const task = await mitra.entities.Task.create(formData);
615
- * toast.success('Task created!');
616
- * navigate(`/tasks/${task.id}`);
617
- * } catch (error) {
618
- * toast.error(error.message);
619
- * }
620
- * ```
621
- */
622
- create(data: Partial<T>): Promise<T>;
623
- /**
624
- * Updates an existing record.
625
- *
626
- * Updates a record by ID with the provided data. Only the fields
627
- * included in the data object will be updated; other fields remain
628
- * unchanged (partial update).
629
- *
630
- * @param id - The unique identifier of the record to update.
631
- * @param data - Object containing the fields to update.
632
- * @returns Promise resolving to the updated record.
633
- * @throws {MitraApiError} When record is not found (404).
634
- *
635
- * @example
636
- * ```typescript
637
- * // Update single field
638
- * const updated = await mitra.entities.Task.update('task-123', {
639
- * status: 'completed',
640
- * });
641
- * ```
642
- *
643
- * @example
644
- * ```typescript
645
- * // Update multiple fields
646
- * const updated = await mitra.entities.Task.update('task-123', {
647
- * status: 'done',
648
- * completedAt: new Date().toISOString(),
649
- * completedBy: currentUser.id,
650
- * });
651
- * ```
652
- */
653
- update(id: string | number, data: Partial<T>): Promise<T>;
654
- /**
655
- * Deletes a single record by ID.
656
- *
657
- * Permanently removes a record from the database. This action cannot
658
- * be undone.
659
- *
660
- * @param id - The unique identifier of the record to delete.
661
- * @returns Promise resolving when deletion is complete.
662
- * @throws {MitraApiError} When record is not found (404).
663
- *
664
- * @example
665
- * ```typescript
666
- * await mitra.entities.Task.delete('task-123');
667
- * console.log('Task deleted');
668
- * ```
669
- *
670
- * @example
671
- * ```typescript
672
- * // With confirmation
673
- * if (confirm('Delete this task?')) {
674
- * await mitra.entities.Task.delete(task.id);
675
- * toast.success('Task deleted');
676
- * navigate('/tasks');
677
- * }
678
- * ```
679
- */
680
- delete(id: string | number): Promise<void>;
681
- /**
682
- * Deletes multiple records matching a query.
683
- *
684
- * Permanently removes all records that match the provided query.
685
- * Use with caution as this action cannot be undone.
686
- *
687
- * @param query - Query object with field-value pairs. Records matching
688
- * all specified criteria will be deleted.
689
- * @returns Promise resolving to object with count of deleted records.
690
- *
691
- * @example
692
- * ```typescript
693
- * // Delete all completed tasks
694
- * const result = await mitra.entities.Task.deleteMany({ status: 'done' });
695
- * console.log(`Deleted ${result.deleted} tasks`);
696
- * ```
697
- *
698
- * @example
699
- * ```typescript
700
- * // Delete by multiple criteria
701
- * const result = await mitra.entities.Task.deleteMany({
702
- * status: 'archived',
703
- * createdAt: { $lt: '2024-01-01' },
704
- * });
705
- * ```
706
- */
707
- deleteMany(query: Record<string, unknown>): Promise<{
708
- deleted: number;
709
- }>;
710
- /**
711
- * Creates multiple records in a single request.
712
- *
713
- * Efficiently creates multiple records at once. This is faster than
714
- * calling `create()` multiple times as it uses a single API request.
715
- *
716
- * @param data - Array of record data objects.
717
- * @returns Promise resolving to an array of created records.
718
- *
719
- * @example
720
- * ```typescript
721
- * const tasks = await mitra.entities.Task.bulkCreate([
722
- * { title: 'Task 1', status: 'pending' },
723
- * { title: 'Task 2', status: 'pending' },
724
- * { title: 'Task 3', status: 'pending' },
725
- * ]);
726
- * console.log(`Created ${tasks.length} tasks`);
727
- * ```
728
- *
729
- * @example
730
- * ```typescript
731
- * // Import from external source
732
- * const importedData = parseCSV(csvContent);
733
- * const records = await mitra.entities.Product.bulkCreate(importedData);
734
- * toast.success(`Imported ${records.length} products`);
735
- * ```
736
- */
737
- bulkCreate(data: Partial<T>[]): Promise<T[]>;
738
- }
739
-
740
- /**
741
- * Module for database CRUD operations.
742
- *
743
- * Access any table dynamically: `mitra.entities.TableName.method()`.
744
- * Table names are case-sensitive and must match the Data Manager config.
745
- *
746
- * @example
747
- * ```typescript
748
- * // Dynamic access
749
- * const tasks = await mitra.entities.Task.list('-created_at', 10);
750
- * const task = await mitra.entities.Task.create({ title: 'New task' });
751
- *
752
- * // Typed access
753
- * const typed = mitra.entities.getTable<Task>('Task');
754
- * const pending = await typed.filter({ status: 'pending' });
755
- * ```
373
+ * Compatibility facade for the Platform SDK 1.x entity API.
374
+ * Shared request behavior lives in `@mitralab.io/sdk-core`.
756
375
  */
757
376
  declare class EntitiesModule {
758
377
  private readonly httpClient;
759
- private dataSourceId;
760
- private readonly tableProxies;
378
+ private core;
761
379
  constructor(httpClient: HttpClient, dataSourceId: string);
762
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
+ */
763
385
  setDataSourceId(dataSourceId: string): void;
764
386
  getTable<T = Record<string, unknown>>(tableName: string): EntityTable<T>;
765
- private createTableAccessor;
766
387
  }
767
388
  type EntitiesProxy = EntitiesModule & {
768
389
  [tableName: string]: EntityTable;
@@ -776,7 +397,7 @@ interface FunctionExecution {
776
397
  functionId: string;
777
398
  /** ID of the function version that was executed. */
778
399
  functionVersionId: string;
779
- /** Execution status: PENDING, RUNNING, COMPLETED, or FAILED. */
400
+ /** Execution status returned by the Functions service. */
780
401
  status: string;
781
402
  /** Input data passed to the function. */
782
403
  input: Record<string, unknown>;
@@ -796,35 +417,13 @@ interface FunctionExecution {
796
417
  createdAt: string;
797
418
  }
798
419
 
799
- /**
800
- * Module for executing serverless functions.
801
- *
802
- * @example
803
- * ```typescript
804
- * const result = await mitra.functions.execute('function-id', { orderId: '123' });
805
- * if (result.status === 'COMPLETED') {
806
- * console.log(result.output);
807
- * }
808
- * ```
809
- */
420
+ /** Platform SDK 1.x facade over the shared Function contract. */
810
421
  declare class FunctionsModule {
811
- private readonly httpClient;
422
+ private readonly core;
812
423
  constructor(httpClient: HttpClient);
813
424
  /**
814
- * Executes a serverless function by ID.
815
- *
816
- * Triggers the function's current published version with the provided input.
817
- *
818
- * @param functionId - UUID of the function to execute.
819
- * @param input - Input data to pass to the function.
820
- * @returns The execution result with status, output, and metadata.
821
- * @throws {MitraApiError} On function not found (404) or unauthorized (401).
822
- *
823
- * @example
824
- * ```typescript
825
- * const execution = await mitra.functions.execute('fn-id', { key: 'value' });
826
- * console.log(execution.status, execution.output);
827
- * ```
425
+ * Executes a Function using the Platform SDK 1.x server-default invocation semantics.
426
+ * The runtime SDK uses an explicit invocation header instead.
828
427
  */
829
428
  execute(functionId: string, input?: Record<string, unknown>): Promise<FunctionExecution>;
830
429
  }
@@ -842,70 +441,12 @@ interface ProxyInput {
842
441
  /** Query parameters. */
843
442
  queryParams?: Record<string, string>;
844
443
  }
845
- /** Result of a proxied HTTP request. */
846
- interface ProxyResult {
847
- /** HTTP status code from the external API. */
848
- status: number;
849
- /** Response headers. */
850
- headers: Record<string, string>;
851
- /** Response body. */
852
- body: unknown;
853
- /** Execution time in milliseconds. */
854
- durationMs: number;
855
- /** Unique execution record ID. */
856
- executionId: string;
857
- }
858
444
 
859
- /**
860
- * Module for proxying HTTP requests to external APIs.
861
- *
862
- * Sends requests through the Mitra server, which handles authentication
863
- * and credential injection based on the integration config.
864
- *
865
- * @example
866
- * ```typescript
867
- * const result = await mitra.integration.executeResource('resource-id', {
868
- * descricao: 'Notebook',
869
- * limit: 10,
870
- * });
871
- * console.log(result.body);
872
- * ```
873
- */
445
+ /** Platform SDK 1.x facade over the shared integration contract. */
874
446
  declare class IntegrationModule {
875
- private readonly httpClient;
447
+ private readonly core;
876
448
  constructor(httpClient: HttpClient);
877
- /**
878
- * Executes a pre-defined integration resource by ID.
879
- *
880
- * The resource's endpoint, method, and body are resolved server-side
881
- * using the provided parameters. Only declared parameters can be passed.
882
- *
883
- * @param resourceId - UUID of the integration resource.
884
- * @param params - Named parameters declared in the resource's params schema.
885
- * @returns Proxy result with status, headers, body, and execution metadata.
886
- * @throws {MitraApiError} On resource not found (404) or external API failure.
887
- *
888
- * @example
889
- * ```typescript
890
- * const result = await mitra.integration.executeResource('resource-id', {
891
- * descricao: 'Notebook',
892
- * limit: 10,
893
- * });
894
- * console.log(result.body);
895
- * ```
896
- */
897
449
  executeResource(resourceId: string, params?: Record<string, unknown>): Promise<ProxyResult>;
898
- /**
899
- * Executes a proxied HTTP request through an integration config.
900
- *
901
- * The Mitra server handles authentication and injects credentials automatically.
902
- * Note: integrations configured with RESOURCE_ONLY mode will block direct proxy access.
903
- *
904
- * @param configId - UUID of the integration config.
905
- * @param request - The HTTP request to proxy (method, endpoint, body, etc.).
906
- * @returns Proxy result with status, headers, body, and execution metadata.
907
- * @throws {MitraApiError} On config not found (404) or external API failure.
908
- */
909
450
  execute(configId: string, request: ProxyInput): Promise<ProxyResult>;
910
451
  }
911
452
 
@@ -917,35 +458,13 @@ interface QueryResult {
917
458
  affectedRows: number | null;
918
459
  }
919
460
 
920
- /**
921
- * Module for executing reusable named queries.
922
- *
923
- * @example
924
- * ```typescript
925
- * const result = await mitra.queries.execute('query-id', { status: 'active' });
926
- * console.log(result.rows);
927
- * ```
928
- */
461
+ /** Platform SDK 1.x facade over the shared custom query contract. */
929
462
  declare class QueriesModule {
930
- private readonly httpClient;
931
463
  private dataSourceId;
464
+ private readonly core;
932
465
  constructor(httpClient: HttpClient);
933
- /** @internal Called by client.init() to set the resolved data source. */
466
+ /** Called by `client.init()` to set the app's resolved data source. */
934
467
  setDataSourceId(dataSourceId: string): void;
935
- /**
936
- * Executes a named query.
937
- *
938
- * @param id - UUID of the custom query.
939
- * @param parameters - Named parameters for the prepared statement.
940
- * @returns Query result with rows and affected row count.
941
- * @throws {MitraApiError} On query not found (404).
942
- *
943
- * @example
944
- * ```typescript
945
- * const result = await mitra.queries.execute('query-id', { status: 'active' });
946
- * console.log(`Found ${result.rows.length} rows`);
947
- * ```
948
- */
949
468
  execute(id: string, parameters?: Record<string, unknown>): Promise<QueryResult>;
950
469
  }
951
470
 
@@ -1012,7 +531,7 @@ interface MitraClient {
1012
531
  * Must be called before using `auth.signUp()` or `entities`.
1013
532
  * Fetches dataSourceId and allowSignup from the public app info endpoint.
1014
533
  *
1015
- * Safe to call multiple times subsequent calls are no-ops.
534
+ * Safe to call multiple times. Subsequent calls are no-ops.
1016
535
  *
1017
536
  * @example
1018
537
  * ```typescript
@@ -1137,4 +656,4 @@ interface MitraClient {
1137
656
  */
1138
657
  declare function createClient(config: MitraClientConfig): MitraClient;
1139
658
 
1140
- export { type EntityListOptions, type EntityTable, type FunctionExecution, MitraApiError, type MitraClient, type MitraClientConfig, type ProxyInput, type ProxyResult, type QueryResult, type SignInCredentials, type SignUpData, type User, createClient };
659
+ export { type FunctionExecution, MitraApiError, type MitraClient, type MitraClientConfig, type ProxyInput, type QueryResult, type SignInCredentials, type SignUpData, type User, createClient };