@mitralab.io/platform-sdk 1.0.6 → 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 +115 -66
- package/dist/index.d.mts +27 -508
- package/dist/index.d.ts +27 -508
- package/dist/index.js +147 -184
- package/dist/index.mjs +155 -184
- package/package.json +21 -10
package/README.md
CHANGED
|
@@ -3,126 +3,171 @@
|
|
|
3
3
|
[](https://sonarcloud.io/summary/new_code?id=mitra-platform-sdk)
|
|
4
4
|
[](https://sonarcloud.io/summary/new_code?id=mitra-platform-sdk)
|
|
5
5
|
|
|
6
|
-
|
|
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
|
-
|
|
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
|
-
##
|
|
10
|
+
## O Que a SDK Entrega
|
|
11
11
|
|
|
12
|
-
-
|
|
13
|
-
-
|
|
14
|
-
-
|
|
15
|
-
-
|
|
16
|
-
-
|
|
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
|
-
##
|
|
20
|
+
## Instalação
|
|
19
21
|
|
|
20
22
|
```bash
|
|
21
|
-
npm install
|
|
23
|
+
npm install @mitralab.io/platform-sdk
|
|
22
24
|
```
|
|
23
25
|
|
|
24
26
|
## Quick Start
|
|
25
27
|
|
|
26
28
|
```typescript
|
|
27
|
-
import { createClient } from '
|
|
29
|
+
import { createClient } from '@mitralab.io/platform-sdk';
|
|
28
30
|
|
|
29
|
-
const mitra = createClient({
|
|
30
|
-
appId:
|
|
31
|
-
apiUrl:
|
|
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
|
-
|
|
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
|
-
|
|
42
|
+
## Configuração
|
|
44
43
|
|
|
45
|
-
|
|
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
|
-
|
|
50
|
+
O client deriva os endpoints dos serviços a partir de `apiUrl`: `/iam`, `/data-manager`, `/functions`, `/integration` e `/code-studio`.
|
|
48
51
|
|
|
49
|
-
|
|
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
|
-
|
|
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
|
-
|
|
60
|
-
|
|
82
|
+
const unsubscribe = mitra.auth.onAuthStateChange((currentUser) => {
|
|
83
|
+
console.log(currentUser?.email);
|
|
84
|
+
});
|
|
61
85
|
|
|
62
|
-
|
|
63
|
-
|
|
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
|
-
|
|
66
|
-
|
|
67
|
-
|
|
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
|
-
|
|
71
|
-
mitra.
|
|
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
|
-
|
|
113
|
+
Table names são case-sensitive e precisam bater com o nome da tabela no Data Manager.
|
|
75
114
|
|
|
76
|
-
|
|
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
|
-
|
|
80
|
-
title: 'New task',
|
|
81
|
-
status: 'pending',
|
|
82
|
-
});
|
|
117
|
+
## Functions
|
|
83
118
|
|
|
84
|
-
|
|
119
|
+
```typescript
|
|
120
|
+
const execution = await mitra.functions.execute('function-id', {
|
|
121
|
+
orderId: 'order-123',
|
|
122
|
+
});
|
|
85
123
|
|
|
86
|
-
|
|
124
|
+
console.log(execution.id, execution.status);
|
|
87
125
|
```
|
|
88
126
|
|
|
89
|
-
|
|
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
|
|
93
|
-
|
|
94
|
-
subject: 'Welcome',
|
|
132
|
+
const result = await mitra.queries.execute('query-id', {
|
|
133
|
+
status: 'active',
|
|
95
134
|
});
|
|
96
135
|
|
|
97
|
-
console.log(
|
|
136
|
+
console.log(result.rows, result.affectedRows);
|
|
98
137
|
```
|
|
99
138
|
|
|
100
|
-
|
|
139
|
+
## Integration
|
|
140
|
+
|
|
141
|
+
Resource pré-definido:
|
|
101
142
|
|
|
102
143
|
```typescript
|
|
103
|
-
const result = await mitra.
|
|
104
|
-
|
|
144
|
+
const result = await mitra.integration.executeResource('resource-id', {
|
|
145
|
+
descricao: 'Notebook',
|
|
146
|
+
limit: 10,
|
|
147
|
+
});
|
|
105
148
|
```
|
|
106
149
|
|
|
107
|
-
|
|
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
|
-
##
|
|
162
|
+
## Erros
|
|
118
163
|
|
|
119
|
-
|
|
164
|
+
Erros de API lançam `MitraApiError`:
|
|
120
165
|
|
|
121
166
|
```typescript
|
|
122
|
-
import { MitraApiError } from '
|
|
167
|
+
import { MitraApiError } from '@mitralab.io/platform-sdk';
|
|
123
168
|
|
|
124
169
|
try {
|
|
125
|
-
await mitra.entities.Task.get('
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
199
|
+
Build gera CommonJS, ESM e tipos TypeScript em `dist/`.
|