@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/README.md CHANGED
@@ -3,126 +3,171 @@
3
3
  [![Quality Gate Status](https://sonarcloud.io/api/project_badges/measure?project=mitra-platform-sdk&metric=alert_status&token=28d7be14b66d6f88d706347e2418af5ea39ab3e9)](https://sonarcloud.io/summary/new_code?id=mitra-platform-sdk)
4
4
  [![Coverage](https://sonarcloud.io/api/project_badges/measure?project=mitra-platform-sdk&metric=coverage&token=28d7be14b66d6f88d706347e2418af5ea39ab3e9)](https://sonarcloud.io/summary/new_code?id=mitra-platform-sdk)
5
5
 
6
- The Mitra Platform SDK provides a JavaScript/TypeScript interface for building apps on the Mitra Platform. When Mitra generates your app, the generated code uses this SDK to authenticate users, manage your app's data, execute serverless functions, and more. You can use the same SDK to modify and extend your app.
6
+ SDK JavaScript/TypeScript para apps criados na plataforma Mitra. O código gerado pelo Code Studio usa este pacote para autenticar usuários, acessar entidades do Data Manager, executar server functions, rodar custom queries e chamar integrações.
7
7
 
8
- **Zero runtime dependencies.** Uses only standard Web APIs (`fetch`, `localStorage`, `URL`, `Proxy`).
8
+ O transporte de browser usa apenas Web APIs padrão (`fetch`, `localStorage`, `URL`, `Proxy`). Os contratos e módulos comuns vêm de `@mitralab.io/sdk-core`, sem trazer autenticação de browser para o core.
9
9
 
10
- ## Modules
10
+ ## O Que a SDK Entrega
11
11
 
12
- - **`auth`**: User authentication, registration, and session handling.
13
- - **`entities`**: Database CRUD operations.
14
- - **`functions`**: Serverless function execution.
15
- - **`integration`**: Proxy HTTP requests to external APIs with automatic credential injection.
16
- - **`queries`**: Execute reusable named queries.
12
+ - Client único criado por `createClient`.
13
+ - Auth com login, cadastro, refresh token, logout e estado em `localStorage`.
14
+ - CRUD dinâmico em tabelas via `mitra.entities.<TableName>`.
15
+ - Execução de server functions publicadas.
16
+ - Execução de custom queries.
17
+ - Proxy de integrações e resources com credential injection no servidor.
18
+ - Tipos TypeScript exportados para os contratos principais.
17
19
 
18
- ## Installation
20
+ ## Instalação
19
21
 
20
22
  ```bash
21
- npm install mitra-platform-sdk
23
+ npm install @mitralab.io/platform-sdk
22
24
  ```
23
25
 
24
26
  ## Quick Start
25
27
 
26
28
  ```typescript
27
- import { createClient } from 'mitra-platform-sdk';
29
+ import { createClient } from '@mitralab.io/platform-sdk';
28
30
 
29
- const mitra = createClient({
30
- appId: 'your-app-id',
31
- apiUrl: 'https://api.mitra.io',
31
+ export const mitra = createClient({
32
+ appId: import.meta.env.VITE_MITRA_APP_ID,
33
+ apiUrl: import.meta.env.VITE_MITRA_API_URL,
34
+ onError: (error) => console.error(error.status, error.code, error.message),
32
35
  });
33
36
 
34
37
  await mitra.init();
35
38
  ```
36
39
 
37
- | Parameter | Type | Required | Description |
38
- |-----------|------|----------|-------------|
39
- | `appId` | `string` | Yes | Your app's unique identifier |
40
- | `apiUrl` | `string` | Yes | Base URL of the Mitra API |
41
- | `onError` | `(error) => void` | No | Global error handler for all API requests |
40
+ `init()` resolve a configuração pública do app no Code Studio, incluindo `dataSourceId` e `allowSignup`. Chame no boot da aplicação antes de usar `entities`, `queries` ou fluxo de cadastro.
42
41
 
43
- `init()` must be called before using the client. Safe to call multiple times.
42
+ ## Configuração
44
43
 
45
- ## Usage
44
+ | Campo | Obrigatório | Uso |
45
+ | --------- | ----------- | ---------------------------------- |
46
+ | `appId` | sim | ID do app publicado no Code Studio |
47
+ | `apiUrl` | sim | URL base do Kong/API da plataforma |
48
+ | `onError` | não | callback global para erros de API |
46
49
 
47
- All modules and methods are fully typed explore the full API through your editor's autocomplete or read the JSDoc in the source code.
50
+ O client deriva os endpoints dos serviços a partir de `apiUrl`: `/iam`, `/data-manager`, `/functions`, `/integration` e `/code-studio`.
48
51
 
49
- ### Authentication
52
+ ## Estrutura de Arquivos
53
+
54
+ ```text
55
+ src/
56
+ ├── client.ts # createClient, composição dos módulos e init
57
+ ├── modules/ # auth de browser e fachadas compatíveis com a API 1.x
58
+ ├── utils/http-client # fetch wrapper, auth header, retry 401 e MitraApiError
59
+ └── index.ts # exports públicos
60
+ ```
61
+
62
+ `@mitralab.io/sdk-core` concentra entities, queries, Functions, integration, `auth.me`, paths seguros e validação estrutural de respostas. A Platform SDK continua responsável por login, cadastro, refresh, `localStorage`, listeners e o retry único após refresh em resposta `401`.
63
+
64
+ ## Módulos
65
+
66
+ | Módulo | Uso |
67
+ | ------------- | --------------------------------------------------------------------------------------- |
68
+ | `auth` | `signIn`, `signUp`, `signOut`, `refreshSession`, `me`, `checkAuth`, `onAuthStateChange` |
69
+ | `entities` | CRUD dinâmico por tabela, filtro, paginação, bulk create e deleteMany |
70
+ | `functions` | disparo de server function por ID com a semântica assíncrona da API 1.x |
71
+ | `queries` | execução de custom query por ID com parâmetros |
72
+ | `integration` | execução de integration resource ou proxy direto por config |
73
+
74
+ ## Auth
50
75
 
51
76
  ```typescript
52
- // Sign up (auto-signs in after registration)
53
- const user = await mitra.auth.signUp({
77
+ const user = await mitra.auth.signIn({
54
78
  email: 'user@example.com',
55
79
  password: 'password123',
56
- name: 'Jane Doe',
57
80
  });
58
81
 
59
- // Sign in
60
- await mitra.auth.signIn({ email: 'user@example.com', password: 'password123' });
82
+ const unsubscribe = mitra.auth.onAuthStateChange((currentUser) => {
83
+ console.log(currentUser?.email);
84
+ });
61
85
 
62
- // Check state
63
- console.log(mitra.auth.isAuthenticated, mitra.auth.currentUser);
86
+ mitra.auth.signOut('/login');
87
+ unsubscribe();
88
+ ```
89
+
90
+ Estado de auth é persistido no `localStorage` com chave `mitra_auth_{appId}`. Em resposta `401`, o SDK tenta `refreshSession()` uma vez e repete a request.
91
+
92
+ ## Entities
64
93
 
65
- // Listen for auth changes (fires immediately with current state)
66
- const unsubscribe = mitra.auth.onAuthStateChange((user) => {
67
- console.log(user ? 'Logged in' : 'Logged out');
94
+ ```typescript
95
+ type Task = {
96
+ id: string;
97
+ title: string;
98
+ status: 'pending' | 'done';
99
+ };
100
+
101
+ const tasks = await mitra.entities.getTable<Task>('Task').list({
102
+ sort: '-created_at',
103
+ limit: 10,
104
+ fields: ['id', 'title', 'status'],
68
105
  });
69
106
 
70
- // Sign out
71
- mitra.auth.signOut();
107
+ const pending = await mitra.entities.Task.filter({ status: 'pending' });
108
+ const created = await mitra.entities.Task.create({ title: 'New task' });
109
+ await mitra.entities.Task.update(created.id, { status: 'done' });
110
+ await mitra.entities.Task.delete(created.id);
72
111
  ```
73
112
 
74
- ### Entities
113
+ Table names são case-sensitive e precisam bater com o nome da tabela no Data Manager.
75
114
 
76
- ```typescript
77
- const tasks = await mitra.entities.Task.list('-created_at', 10);
115
+ Records usam `/api/v1/tables/{table}/records`. O app e o tenant vêm do contexto autenticado, não do `dataSourceId` no path.
78
116
 
79
- const task = await mitra.entities.Task.create({
80
- title: 'New task',
81
- status: 'pending',
82
- });
117
+ ## Functions
83
118
 
84
- await mitra.entities.Task.update(task.id, { status: 'done' });
119
+ ```typescript
120
+ const execution = await mitra.functions.execute('function-id', {
121
+ orderId: 'order-123',
122
+ });
85
123
 
86
- await mitra.entities.Task.delete(task.id);
124
+ console.log(execution.id, execution.status);
87
125
  ```
88
126
 
89
- ### Functions
127
+ Na API 1.x, `execute` não envia `X-Invocation-Type`. O serviço usa o default assíncrono e devolve a execução criada, normalmente com status `PENDING`; a chamada não espera a Function terminar.
128
+
129
+ ## Queries
90
130
 
91
131
  ```typescript
92
- const execution = await mitra.functions.execute('function-id', {
93
- to: 'user@example.com',
94
- subject: 'Welcome',
132
+ const result = await mitra.queries.execute('query-id', {
133
+ status: 'active',
95
134
  });
96
135
 
97
- console.log(execution.status, execution.output);
136
+ console.log(result.rows, result.affectedRows);
98
137
  ```
99
138
 
100
- ### Queries
139
+ ## Integration
140
+
141
+ Resource pré-definido:
101
142
 
102
143
  ```typescript
103
- const result = await mitra.queries.execute('query-id', { status: 'active' });
104
- console.log(result.rows);
144
+ const result = await mitra.integration.executeResource('resource-id', {
145
+ descricao: 'Notebook',
146
+ limit: 10,
147
+ });
105
148
  ```
106
149
 
107
- ### Integration
150
+ Proxy direto por config:
108
151
 
109
152
  ```typescript
110
153
  const result = await mitra.integration.execute('config-id', {
111
154
  method: 'GET',
112
155
  endpoint: '/users',
156
+ queryParams: { limit: '10' },
113
157
  });
158
+
114
159
  console.log(result.status, result.body);
115
160
  ```
116
161
 
117
- ## Error Handling
162
+ ## Erros
118
163
 
119
- All API errors throw `MitraApiError`:
164
+ Erros de API lançam `MitraApiError`:
120
165
 
121
166
  ```typescript
122
- import { MitraApiError } from 'mitra-platform-sdk';
167
+ import { MitraApiError } from '@mitralab.io/platform-sdk';
123
168
 
124
169
  try {
125
- await mitra.entities.Task.get('non-existent-id');
170
+ await mitra.entities.Task.get('missing-id');
126
171
  } catch (error) {
127
172
  if (error instanceof MitraApiError) {
128
173
  console.error(error.status, error.code, error.message);
@@ -130,21 +175,25 @@ try {
130
175
  }
131
176
  ```
132
177
 
133
- ## Development
178
+ O transporte não segue redirects HTTP. Respostas 307, 308 ou respostas já
179
+ marcadas como redirecionadas falham sem replay. A única repetição automática é
180
+ a tentativa única após refresh bem-sucedido em resposta 401.
181
+
182
+ Antes de construir `MitraApiError`, a SDK remove o token usado na tentativa e
183
+ qualquer credencial no formato `Bearer` de `message`, `code` e `details`,
184
+ percorrendo recursivamente valores, arrays e chaves de objetos.
134
185
 
135
- ### Build the SDK
186
+ ## Desenvolvimento
136
187
 
137
188
  ```bash
138
189
  npm install
139
190
  npm run build
140
- ```
141
-
142
- ### Run tests
143
-
144
- ```bash
191
+ npm run lint
145
192
  npm test
146
193
  ```
147
194
 
148
- ## License
195
+ `@mitralab.io/sdk-core@0.1.0` é resolvido pelo registry público do npm e fica
196
+ travado por integridade no `package-lock.json`. Não substitua a dependência por
197
+ `file:` ou tarball local.
149
198
 
150
- MIT
199
+ Build gera CommonJS, ESM e tipos TypeScript em `dist/`.