@mitralab.io/platform-sdk 1.8.7 → 1.9.0-beta.2
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/CHANGELOG.md +113 -0
- package/README.md +105 -5
- package/dist/index.cjs +665 -53
- package/dist/index.d.cts +163 -7
- package/dist/index.d.ts +163 -7
- package/dist/index.js +665 -53
- package/package.json +2 -2
package/CHANGELOG.md
CHANGED
|
@@ -2,6 +2,119 @@
|
|
|
2
2
|
|
|
3
3
|
All notable changes to this project are documented in this file.
|
|
4
4
|
|
|
5
|
+
## 1.9.0-beta.2
|
|
6
|
+
|
|
7
|
+
App files through `client.files`, and a single sign-in screen with every method the app has.
|
|
8
|
+
|
|
9
|
+
- Depend on `@mitralab.io/sdk-core@0.3.10` for its `files` module, exposed as `client.files`: app
|
|
10
|
+
files kept by the Data Manager under `/data-manager/api/v1/files`. `upload(fileOrBlob, options)`
|
|
11
|
+
requests the upload, sends the bytes to the signed link and confirms, resolving only with the
|
|
12
|
+
`READY` file; `requestUpload` and `confirmUpload` are the steps on their own. `get`, `getUrl`,
|
|
13
|
+
`getUrls` (1 to 100 ids), `download` and `delete` complete the module.
|
|
14
|
+
- The API calls go through the Data Manager client of this SDK, with the session token,
|
|
15
|
+
`X-App-Id`, the renewal before the request and the global `onError`. The bytes go to the signed
|
|
16
|
+
link through the global `fetch`, without `Authorization`, `X-App-Id` or any other header this SDK
|
|
17
|
+
adds: the link is the credential, and storage gets only the headers the API signed it with.
|
|
18
|
+
- An API refusal rejects with `MitraApiError`. A failure after the upload request rejects with the
|
|
19
|
+
Core `FileTransferError` (`step` `send`, `confirm` or `download`), now exported by this package,
|
|
20
|
+
and never carries the link; a failed send deletes the pending file first. A `signal` stops the
|
|
21
|
+
transfer with storage and the call rejects with `signal.reason` (`AbortError`, or `TimeoutError`
|
|
22
|
+
from `AbortSignal.timeout`). The transfer with storage does not reach `onError`.
|
|
23
|
+
- New exported types: `FilesModule`, `FileUploadOptions`, `FileDownloadOptions`, `FileMetadata`,
|
|
24
|
+
`FileKind`, `FileVisibility`, `FileStatus`, `FileCreator`, `FileUpload`, `FileUploadInput`,
|
|
25
|
+
`FileReadUrl`, `FileReadUrlItem`, `FileReadUrlOptions`, `FileReadUrls` and `FileTransferStep`.
|
|
26
|
+
- `auth.signInWithAuthPage({ mode? })` opens the Mitra sign-in page, in a popup or by redirect, on
|
|
27
|
+
a choice screen with the methods the app has: Google and Microsoft always, password and e-mail
|
|
28
|
+
code when the app has them on. The person chooses there, and the SDK exchanges the code through
|
|
29
|
+
the route of the chosen method. It is optional: an app that does not call it stays the same. In
|
|
30
|
+
`redirect` mode, and for the tab opened by the e-mail link, call
|
|
31
|
+
`auth.completeAuthPageSignInRedirect()` at startup; it returns `null` when the URL is not its
|
|
32
|
+
own. The pending request stays in `localStorage` for 10 minutes under
|
|
33
|
+
`mitra_all_redirect_{appId}`: the single-use state and the page address, never a token. An answer
|
|
34
|
+
from the page without the chosen method is refused, and the code is not exchanged.
|
|
35
|
+
|
|
36
|
+
## 1.9.0-beta.1
|
|
37
|
+
|
|
38
|
+
Sign-in through an identity connection by redirect, for an app opened directly in the browser,
|
|
39
|
+
outside a host system iframe (a "Sign in with Sankhya Pass" button).
|
|
40
|
+
|
|
41
|
+
- `auth.signInWithIdentityConnection(slug, { mode: 'redirect', redirectUri?, language? })` reads
|
|
42
|
+
the connection (`GET /api/v1/auth/identity-connections/{slug}`), which now carries
|
|
43
|
+
`authorizationEndpoint`, `tokenEndpoint` and `clientId`, and sends the page to the provider with
|
|
44
|
+
Authorization Code and PKCE (S256). A connection without those fields is refused before anything
|
|
45
|
+
is stored. The pending request (`state` prefixed `connection.{slug}.`, `code_verifier`, redirect
|
|
46
|
+
URI, token endpoint) is kept in `sessionStorage` under `mitra_identity_connection_redirect_{appId}`.
|
|
47
|
+
The redirect URI defaults to the current origin and path, without query or fragment; a
|
|
48
|
+
`redirectUri` outside the app origin, not http(s), or with a query or a fragment is refused
|
|
49
|
+
before any request (RFC 6749 3.1.2).
|
|
50
|
+
- `auth.completeIdentityConnectionRedirect()` reads `code` and `state` from the query, not the
|
|
51
|
+
fragment, so it never collides with the bridge completion. It returns `null`, without a request
|
|
52
|
+
and without touching the URL, when `state` does not start with `connection.`. From there on the
|
|
53
|
+
pending request is spent, the callback parameters leave the URL before anything can fail, and a
|
|
54
|
+
state that matches no pending request in the tab is refused without a request. The code is
|
|
55
|
+
redeemed at the provider's token endpoint saved at start, the provider's access token is sent to
|
|
56
|
+
`POST /api/v1/auth/identity-connections/{slug}/login` and the returned exchange code is redeemed
|
|
57
|
+
at `/exchange`, as the bridge flow does. The token endpoint call gives up after 15 seconds, and
|
|
58
|
+
its error message masks the code and the verifier. The provider's id token and refresh token are never kept.
|
|
59
|
+
The session is tab-scoped, like the bridge one, and a failure with a sign-in pending in the tab
|
|
60
|
+
drops the in-memory session while keeping it stored; a callback with nothing pending, such as a
|
|
61
|
+
forged link, is refused and leaves the session alone.
|
|
62
|
+
- `init()` calls it in a browser right after the bridge completion; a failure rejects `init()`.
|
|
63
|
+
- New exported type: `IdentityConnectionSignInOptions`.
|
|
64
|
+
|
|
65
|
+
## 1.9.0-beta.0
|
|
66
|
+
|
|
67
|
+
Sign-in through an identity connection, starting with Sankhya Pass, for an app opened inside the
|
|
68
|
+
host system's iframe.
|
|
69
|
+
|
|
70
|
+
- `auth.completeIdentityConnectionSignInRedirect()` reads `codeMitra`, `stateMitra` and
|
|
71
|
+
`connectionMitra` from the fragment the platform bridge page (`sankhya-auth.html`) leaves on the
|
|
72
|
+
app's origin, and redeems the single-use code at
|
|
73
|
+
`POST /api/v1/auth/identity-connections/{slug}/exchange` with `{ appId, code }`. The response is
|
|
74
|
+
read like every other exchange, `allTokens` included. Tokens never travel in the URL or by
|
|
75
|
+
`postMessage`.
|
|
76
|
+
- It returns `null`, without a request and without touching the URL, when the fragment has no
|
|
77
|
+
`connectionMitra` or its `stateMitra` does not start with `connection.`, so the other completions
|
|
78
|
+
still read their own fragment. From there on the fragment belongs to this flow and is removed
|
|
79
|
+
before anything can fail. It rejects in a top-level tab (the bridge only runs in an iframe), for
|
|
80
|
+
a connection slug outside `[a-z0-9-]{1,64}`, for an `errorMitra` (with a fixed message that names
|
|
81
|
+
the error only when it matches `[a-z_]{1,64}`, since any embedding page can write it), for a
|
|
82
|
+
missing code and when IAM refuses the code (`401 INVALID_EXCHANGE_CODE`). It also reads the
|
|
83
|
+
connection (`GET /api/v1/auth/identity-connections/{slug}`) and rejects, without redeeming the
|
|
84
|
+
code, unless every page in the chain embedding the app (`location.ancestorOrigins`) is one of its
|
|
85
|
+
`allowedOrigins`; a page of someone else could otherwise embed the app, directly or around an
|
|
86
|
+
allowed host, with a code of another account and sign the visitor in as it. A browser that does
|
|
87
|
+
not expose `ancestorOrigins` is refused the same way: the requirement is the API, which Chromium
|
|
88
|
+
and WebKit expose and Firefox exposes from version 148.
|
|
89
|
+
- `init()` calls it in a browser after reading the app info, so an app that already calls
|
|
90
|
+
`await mitra.init()` opens signed in with no change. A refused code rejects `init()`; the
|
|
91
|
+
fragment is already gone, so a reload does not repeat the failure. Without the fragment `init()`
|
|
92
|
+
makes no extra request. A call to `init()` while another one runs now waits for it instead of
|
|
93
|
+
reading the app info a second time, so a double boot (React `StrictMode`) redeems the code once.
|
|
94
|
+
- A session from an identity connection is kept in `sessionStorage` under `mitra_auth_{appId}`
|
|
95
|
+
instead of `localStorage`, and lives only as long as its tab: two accounts of the host system
|
|
96
|
+
(two Sankhya demo bases) open in one browser no longer hand each other's session to the next
|
|
97
|
+
reload. On startup the tab's session wins over the shared one, which is left in place for the
|
|
98
|
+
other tabs of the app; a broken tab session is dropped alone and the shared one is restored.
|
|
99
|
+
`signOut()` in that tab ends only the tab session. Another sign-in or `setSession()` in the same
|
|
100
|
+
tab goes back to `localStorage` and removes the tab copy; after `setToken()` the session always
|
|
101
|
+
goes to `localStorage`, and the tab copy is removed even with `setToken(token, false)`. The
|
|
102
|
+
refresh token of the tab session is dropped by `setToken()` as well, so it never reaches the
|
|
103
|
+
shared storage or the legacy SDK with the hand-set token. A renewal keeps the session where it
|
|
104
|
+
is.
|
|
105
|
+
- When the identity connection sign-in fails, the session the client restored at startup is
|
|
106
|
+
dropped from memory and stays stored where it was (`localStorage`, or `sessionStorage` for a tab
|
|
107
|
+
session), so the iframe does not stay signed in as someone else after a refused Sankhya Pass
|
|
108
|
+
login. `init()` still rejects. An exchange that returns a token of another app leaves the shared
|
|
109
|
+
session stored as well.
|
|
110
|
+
- The deprecated `mitra-interactions-sdk` exports get only the access token of a tab session.
|
|
111
|
+
Its refresh token is not handed over, because the legacy SDK writes every refresh token it
|
|
112
|
+
receives to `localStorage` (`mitra-session`), where it would outlive the tab. So in a tab session
|
|
113
|
+
the legacy exports do not renew on their own, and this SDK renews only before one of its own
|
|
114
|
+
requests, in `ensureFreshSession()` or in `refreshSession()`, with no timer. An app that uses
|
|
115
|
+
only the legacy exports gets `401` once the access token expires, unless it makes a call through
|
|
116
|
+
this SDK or calls `refreshSession()`; the renewed token then reaches the legacy SDK at once.
|
|
117
|
+
|
|
5
118
|
## 1.8.7
|
|
6
119
|
|
|
7
120
|
- Depend on `@mitralab.io/sdk-core@0.3.9`: a history reread while a turn runs no longer drops the
|
package/README.md
CHANGED
|
@@ -36,7 +36,7 @@ No app gerado pelo Code Studio, `VITE_MITRA_APP_ID` e `VITE_MITRA_API_URL` já v
|
|
|
36
36
|
|
|
37
37
|
## O que dá para fazer
|
|
38
38
|
|
|
39
|
-
- `auth`: login com Google (`signInWithGoogle`), Microsoft (`signInWithMicrosoft`), código por e-mail ou e-mail e senha (`signInWithPassword` no popup da Mitra, ou `signInWithPasswordForm` no formulário do próprio app), mais `currentUser`, `onAuthStateChange` e `signOut`.
|
|
39
|
+
- `auth`: login com Google (`signInWithGoogle`), Microsoft (`signInWithMicrosoft`), código por e-mail ou e-mail e senha (`signInWithPassword` no popup da Mitra, ou `signInWithPasswordForm` no formulário do próprio app), ou todos numa tela só (`signInWithAuthPage`), mais `currentUser`, `onAuthStateChange` e `signOut`.
|
|
40
40
|
- `entities.<Tabela>`: `list`, `filter`, `get`, `create`, `bulkCreate`, `update`, `delete` e `deleteMany` nas tabelas do app.
|
|
41
41
|
- `queries.execute(id, params)`: roda uma query salva no app.
|
|
42
42
|
- `functions`: `execute` espera o resultado da Server Function; `executeAsync` devolve a execução para acompanhar com `getExecution` ou parar com `cancelExecution`. `publicFunctions` chama as Functions publicadas como públicas, sem login.
|
|
@@ -46,6 +46,7 @@ No app gerado pelo Code Studio, `VITE_MITRA_APP_ID` e `VITE_MITRA_API_URL` já v
|
|
|
46
46
|
`loadOlder()` traz a página anterior do histórico e põe antes de `history`; `hasOlder` diz se ainda há mais antiga.
|
|
47
47
|
- `agentCredentials`: credenciais de provedor de IA e modelos disponíveis. `providers(agentId?)` devolve numa chamada só os provedores em que o próximo turno pode rodar, cada um com os modelos e a última leitura da assinatura.
|
|
48
48
|
- `aiProviders.get()`: consulta tipada de `GET /copilot/api/v1/ai-providers`, com o token da sessão e o `X-App-Id` do cliente. Retorna engine ativa, quota pessoal, provedores personalizados, conexão OpenCode e `managedAiProfile`. O módulo oferece somente leitura: não altera preferências, cria tarefas ou conecta provedores.
|
|
49
|
+
- `files`: arquivos do app, com `upload`, `get`, `getUrl`, `getUrls`, `download` e `delete`, mais os passos `requestUpload` e `confirmUpload` (ver [Arquivos do app](#arquivos-do-app)).
|
|
49
50
|
|
|
50
51
|
`managedAiProfile` é `null` quando inelegível e pode estar ausente em backends anteriores. Quando o Copilot oferece Immersion, o perfil traz `profile: "IMMERSION"`, `agentType: "IMMERSION"`, `selectionMode: "FORCED"`, `model: "immersion"` e `requiredScope: "ACCOUNT"`. A leitura preserva a engine ativa e a quota pessoal; não calcula elegibilidade com base nelas. Falhas, inclusive `404` de backend sem a rota, chegam como `MitraApiError`.
|
|
51
52
|
|
|
@@ -58,6 +59,22 @@ const { receipt } = await mitra.auth.requestEmailCode({ email })
|
|
|
58
59
|
const user = await mitra.auth.verifyEmailCode({ receipt, code })
|
|
59
60
|
```
|
|
60
61
|
|
|
62
|
+
### Tela única de login
|
|
63
|
+
|
|
64
|
+
`signInWithAuthPage()` abre a página de login da Mitra numa tela de escolha, com os métodos que o app tem: Google e Microsoft sempre, e senha e código por e-mail quando estão ligados no app. A pessoa escolhe lá, e o SDK troca o código pela rota do método escolhido, como o método sozinho faria. É opcional: o app que não chama esse método continua igual. Chame direto do clique, antes de qualquer `await`, para o browser não bloquear o popup:
|
|
65
|
+
|
|
66
|
+
```typescript
|
|
67
|
+
const user = await mitra.auth.signInWithAuthPage() // popup
|
|
68
|
+
await mitra.auth.signInWithAuthPage({ mode: "redirect" })
|
|
69
|
+
|
|
70
|
+
// no startup, para o modo redirect e para a aba aberta pelo link do e-mail
|
|
71
|
+
const redirectedUser = await mitra.auth.completeAuthPageSignInRedirect()
|
|
72
|
+
```
|
|
73
|
+
|
|
74
|
+
- Como a pessoa pode escolher o código por e-mail, o pedido pendente fica no `localStorage` por 10 minutos, na chave `mitra_all_redirect_{appId}`, como no `signInWithEmail()`: o state de uso único e o endereço da página, nunca um token. O popup também espera até 10 minutos.
|
|
75
|
+
- Se a pessoa terminar pelo link do e-mail em outra aba, o popup não recebe o resultado e a chamada termina por tempo esgotado; trate como popup cancelado.
|
|
76
|
+
- Uma resposta da página sem o método escolhido é recusada, e o código não é trocado.
|
|
77
|
+
|
|
61
78
|
### Login por e-mail e senha
|
|
62
79
|
|
|
63
80
|
Só em app com contas próprias (modo exclusivo) e quando `mitra.passwordLoginEnabled` for `true`. O dono do app escolhe um de dois modos, app a app.
|
|
@@ -98,6 +115,39 @@ if (token) await mitra.auth.confirmPasswordReset({ token, newPassword })
|
|
|
98
115
|
|
|
99
116
|
A troca e o reset encerram todas as sessões da conta. Depois do reset, a pessoa entra de novo com a senha nova.
|
|
100
117
|
|
|
118
|
+
### Login por conexão de identidade (Sankhya Pass)
|
|
119
|
+
|
|
120
|
+
Para app aberto dentro do iframe de outro sistema, como o SKW da Sankhya. O sistema hospedeiro abre a página de ponte da Mitra (`sankhya-auth.html`), que faz o login no IAM com o token dele e manda o iframe para a origem do app com um código de uso único no fragmento (`#codeMitra=...&stateMitra=connection.*&connectionMitra=sankhya-pass`). Nenhum token passa pela URL ou por `postMessage`.
|
|
121
|
+
|
|
122
|
+
O `await mitra.init()` troca esse código pela sessão sozinho, então o app abre logado sem código novo. Se a troca falhar, o `init()` rejeita; o fragmento já saiu da URL, e um reload não repete o erro. Fora desse fluxo, o `init()` não faz requisição a mais. Quem não chama `init()` usa `completeIdentityConnectionSignInRedirect()` no startup, que devolve `null` quando a URL não é dele.
|
|
123
|
+
|
|
124
|
+
O código só é aceito dentro de iframe e sob um sistema hospedeiro permitido: o SDK lê `location.ancestorOrigins` e confere toda a cadeia de páginas que embute o app contra os `allowedOrigins` da conexão (`GET /api/v1/auth/identity-connections/{slug}`). Aba de topo, qualquer origem da cadeia fora da lista ou browser que não expõe `ancestorOrigins` recusam o código sem trocá-lo. O requisito é a API, não a família do browser: Chromium e WebKit a expõem há anos, e o Firefox a partir da versão 148.
|
|
125
|
+
|
|
126
|
+
A sessão desse login fica no `sessionStorage`, na mesma chave `mitra_auth_{appId}`, e dura só enquanto a aba existe. É assim porque o sistema hospedeiro abre o app com a conta de cada base, e duas bases demo da Sankhya abertas no mesmo browser, dividindo o `localStorage`, trocavam a sessão e o alias uma da outra no reload, como já acontecia no legado.
|
|
127
|
+
|
|
128
|
+
- No startup, a sessão da aba vale antes da sessão compartilhada do `localStorage`. A sessão compartilhada não é apagada: ela é das outras abas do app, logadas do jeito normal. Se a aba não tem sessão própria, ela usa a compartilhada.
|
|
129
|
+
- `signOut()` numa aba assim encerra só a sessão da aba.
|
|
130
|
+
- Um login por outro método ou `setSession()` na mesma aba volta a gravar no `localStorage` e apaga a cópia da aba. Depois de `setToken()` o destino é sempre o `localStorage`, e a cópia da aba é apagada mesmo com `setToken(token, false)`.
|
|
131
|
+
- Se o login pela conexão for recusado, o `init()` rejeita e a sessão que o app tinha restaurado no startup deixa de valer naquela página, para o iframe não seguir logado com outra pessoa. Ela continua guardada onde estava: no `localStorage`, ou no `sessionStorage` se era uma sessão por aba.
|
|
132
|
+
- Os exports legados do `mitra-interactions-sdk` recebem dessa sessão só o access token. O refresh token não vai para eles, porque o SDK legado grava o refresh token no `localStorage` (`mitra-session`), onde ele sobreviveria à aba. Por isso, numa sessão por aba, os exports legados não renovam sozinhos, e o SDK novo também não renova em segundo plano: ele renova antes de uma requisição dele mesmo, em `ensureFreshSession()` ou em `refreshSession()`. Um app que só usa os exports legados recebe `401` quando o access token vence, a menos que faça uma chamada pelo SDK novo ou chame `refreshSession()`; o token renovado chega ao legado na hora.
|
|
133
|
+
|
|
134
|
+
#### Modo redirect, fora do iframe
|
|
135
|
+
|
|
136
|
+
Para um botão "Entrar com Sankhya Pass" num app aberto direto no browser, sem sistema hospedeiro. O SDK manda a página para o provedor de identidade da conexão (o Keycloak do Sankhya Pass), com Authorization Code e PKCE (Proof Key for Code Exchange, a prova que amarra o código a quem pediu), e o provedor devolve a pessoa ao app com um código na query.
|
|
137
|
+
|
|
138
|
+
```typescript
|
|
139
|
+
await mitra.auth.signInWithIdentityConnection("sankhya-pass", { mode: "redirect" })
|
|
140
|
+
```
|
|
141
|
+
|
|
142
|
+
- No retorno, o `await mitra.init()` completa o login sozinho. Quem não chama `init()` usa `completeIdentityConnectionRedirect()` no startup, que devolve `null` quando a query não é dele. Se o login falhar, o `init()` rejeita; a query já saiu da URL, e um reload não repete o erro.
|
|
143
|
+
- O app volta para a origem e o caminho atuais, sem query e sem fragmento, ou para o `redirectUri` passado nas opções, que precisa ser http ou https, estar na origem do app e não ter query nem fragmento (o SDK recusa antes de sair da página).
|
|
144
|
+
- O client público da conexão no provedor precisa de duas liberações para a origem do app: o redirect URI, para o provedor devolver a pessoa, e a origem em Web Origins (CORS, a regra que deixa o browser ler a resposta de outro domínio), porque o SDK troca o código no token endpoint direto do browser. Sem a segunda, essa troca falha com `TypeError` de rede. Peça à Mitra para liberar as duas.
|
|
145
|
+
- O pedido pendente (`state` e `code_verifier`) fica no `sessionStorage` da aba e vale uma vez. Retorno sem pedido pendente na aba, ou com `state` diferente, é recusado sem requisição. Sem pedido pendente, como num link forjado, a sessão que a página já tinha continua valendo.
|
|
146
|
+
- A troca no token endpoint espera até 15 segundos; passado isso, o login rejeita.
|
|
147
|
+
- O token do provedor serve só para o IAM validar quem é a pessoa e é descartado em seguida. O `id_token` e o `refresh_token` do provedor não são guardados.
|
|
148
|
+
- A sessão fica no `sessionStorage`, como no login pelo iframe, com as mesmas regras de sessão por aba descritas acima.
|
|
149
|
+
- Como não há iframe, não há requisito de `ancestorOrigins`: funciona em Chromium, WebKit e Firefox.
|
|
150
|
+
|
|
101
151
|
Chat com agente:
|
|
102
152
|
|
|
103
153
|
```typescript
|
|
@@ -109,13 +159,63 @@ const { content } = await chat.sendAndWait("Resuma os pedidos de hoje")
|
|
|
109
159
|
chat.close()
|
|
110
160
|
```
|
|
111
161
|
|
|
162
|
+
### Arquivos do app
|
|
163
|
+
|
|
164
|
+
Os arquivos que a pessoa envia pelo app ficam no storage da Mitra, registrados pelo Data Manager. Os bytes não passam pela API: o browser manda e lê direto do storage por um link assinado, que vale poucos minutos, e a API só autoriza e registra. As chamadas à API levam o token da sessão e o `X-App-Id`; o envio e o download saem pelo `fetch` do browser sem eles, porque o link já é a credencial.
|
|
165
|
+
|
|
166
|
+
Envio a partir de um `<input type="file">`:
|
|
167
|
+
|
|
168
|
+
```typescript
|
|
169
|
+
// <input type="file" id="attachment"> e <button id="cancel">
|
|
170
|
+
const input = document.querySelector<HTMLInputElement>("#attachment")!
|
|
171
|
+
const cancel = document.querySelector<HTMLButtonElement>("#cancel")!
|
|
172
|
+
|
|
173
|
+
input.addEventListener("change", async () => {
|
|
174
|
+
const picked = input.files?.[0]
|
|
175
|
+
if (!picked) return
|
|
176
|
+
|
|
177
|
+
const sending = new AbortController()
|
|
178
|
+
cancel.onclick = () => sending.abort()
|
|
179
|
+
try {
|
|
180
|
+
const file = await mitra.files.upload(picked, {
|
|
181
|
+
kind: "PERMANENT",
|
|
182
|
+
visibility: "PRIVATE",
|
|
183
|
+
signal: sending.signal,
|
|
184
|
+
})
|
|
185
|
+
await mitra.entities.Attachment.create({ fileId: file.id, name: file.name })
|
|
186
|
+
} catch (error) {
|
|
187
|
+
if (error instanceof DOMException && error.name === "AbortError") return
|
|
188
|
+
throw error
|
|
189
|
+
}
|
|
190
|
+
})
|
|
191
|
+
```
|
|
192
|
+
|
|
193
|
+
Quem lê o arquivo depende da visibilidade, não de quem tem o `fileId`: `PRIVATE` só quem enviou, `APP` qualquer pessoa do app, `RESTRICTED` quem enviou e quem a regra do app liberar, por uma Server Function que roda em nome de um usuário; a execução pública de uma Server Function não recebe o link.
|
|
194
|
+
|
|
195
|
+
Exibição pelo link de leitura:
|
|
196
|
+
|
|
197
|
+
```typescript
|
|
198
|
+
// <img id="preview">
|
|
199
|
+
const { url } = await mitra.files.getUrl(attachment.fileId)
|
|
200
|
+
document.querySelector<HTMLImageElement>("#preview")!.src = url
|
|
201
|
+
```
|
|
202
|
+
|
|
203
|
+
- `upload` pede o envio com o nome, o tipo e o tamanho do `File`, manda os bytes ao link com os headers que a API devolveu e confirma; só resolve com o arquivo `READY`. Um `Blob` que não é `File` precisa de `name` nas opções.
|
|
204
|
+
- `kind`: `TEMPORARY` vence 7 dias depois do pedido de envio, `PERMANENT` fica até ser apagado.
|
|
205
|
+
- Guarde o `id`, nunca o link: ele vence e autoriza sozinho quem o tiver. O link de `PRIVATE` e `RESTRICTED` vale 5 minutos e não se estende; o de `APP` aceita `expiresInSeconds` até 1 hora. Peça o link na hora de exibir, e peça outro quando uma imagem voltar a montar depois do prazo, pelo `expiresAt` ou no `onerror` do `<img>`. Para várias imagens, `getUrls(ids)` traz até 100 numa chamada. Aberto direto numa aba, o link baixa o arquivo com o nome original. `download(fileId)` devolve o conteúdo como `Blob`.
|
|
206
|
+
- Recusa da API chega como `MitraApiError`, como nas outras chamadas: `FILE_TOO_LARGE`, `FILE_QUOTA_REACHED` e `FILE_PENDING_LIMIT_REACHED` no pedido de envio, `NOT_FOUND` para arquivo que a pessoa não pode ler.
|
|
207
|
+
- Falha depois do pedido de envio chega como `FileTransferError`, com `step` (`send`, `confirm` ou `download`) e `fileId`, e nunca carrega o link. No `send`, o `upload` já apagou o arquivo pendente quando `cleanedUp` é `true`; com `false`, apague com `files.delete(fileId)`. No `confirm`, os bytes já estão no storage: confirme de novo com `files.confirmUpload(fileId)` ou apague. A exclusão que limpa um envio que falhou é uma chamada à plataforma como as outras, então a falha dela passa pelo `onError`; o erro do envio já traz `cleanedUp: false`.
|
|
208
|
+
- O `signal` interrompe só a transferência dos bytes, e a chamada rejeita com o `signal.reason`, como o `fetch`: `AbortError` no `abort()` do exemplo. Um envio cancelado no meio já tentou apagar o arquivo pendente, que vence sozinho em 24 horas se a exclusão falhar. Sem `signal`, o browser não dá prazo à transferência. Um prazo por `AbortSignal.timeout(ms)` rejeita com `TimeoutError`, mas conta desde a criação do sinal, pedido de envio incluído, e corta um envio legítimo de 25 MiB numa rede lenta: dimensione pelo tamanho do arquivo.
|
|
209
|
+
|
|
210
|
+
O comportamento completo, com as garantias sobre o link e os erros, está no [README do Core](https://github.com/mitralab-dev/mitra-core-sdk#arquivos-de-app), que este módulo usa sem mudar.
|
|
211
|
+
|
|
112
212
|
## Configuração
|
|
113
213
|
|
|
114
214
|
| Campo | Obrigatório | Uso |
|
|
115
215
|
|---|---|---|
|
|
116
216
|
| `appId` | sim | ID do app no Code Studio |
|
|
117
217
|
| `apiUrl` | sim | URL do API gateway da Mitra |
|
|
118
|
-
| `onError` | não | callback com o `MitraApiError` das falhas de `entities`, `queries`, `functions`, `integration`, `agentTasks`, `agentCredentials` e `
|
|
218
|
+
| `onError` | não | callback com o `MitraApiError` das falhas de `entities`, `queries`, `functions`, `integration`, `agentTasks`, `agentCredentials`, `aiProviders` e das chamadas de `files` à API, inclusive a exclusão que limpa um envio que falhou; `init()`, login, `publicFunctions`, a transferência de `files` com o storage e falha de rede não passam por ele e são tratados no `catch` de cada chamada |
|
|
119
219
|
| `authPageUrl` | não | URL da página de login da Mitra; sem ela, o SDK descobre sozinho |
|
|
120
220
|
| `apiKey` | não | chave padrão de `auth.signInWithApiKey()`; só em código de servidor, nunca no bundle do browser |
|
|
121
221
|
|
|
@@ -149,9 +249,9 @@ Falha de rede chega como o erro do próprio `fetch` (`TypeError`), sem passar po
|
|
|
149
249
|
## Boas práticas
|
|
150
250
|
|
|
151
251
|
- Chame `await mitra.init()` no startup, antes de montar a tela de login: `allowSignup`, `emailLoginEnabled`, `passwordLoginEnabled` e o login por e-mail dependem dele.
|
|
152
|
-
- Com `mode: "redirect"`, chame no startup o `completeGoogleSignInRedirect()`, `completeMicrosoftSignInRedirect()` ou `
|
|
153
|
-
- A sessão fica no `localStorage` do domínio do app, na chave `mitra_auth_{appId}`, e é renovada sozinha antes de vencer. `signOut()` limpa e, em app com contas próprias, encerra a sessão no servidor: o refresh token deixa de renovar, e o access token já emitido vale até vencer.
|
|
154
|
-
- Alguns apps recebem tokens extras junto da sessão, em `auth.allTokens`, liberados app por app pela Mitra. O de backoffice é o mais sensível: ele carrega os acessos que a pessoa tem no backoffice da Mitra, vale uma hora e fica no mesmo
|
|
252
|
+
- Com `mode: "redirect"`, chame no startup o `completeGoogleSignInRedirect()`, `completeMicrosoftSignInRedirect()`, `completeEmailSignInRedirect()` ou `completeAuthPageSignInRedirect()` do método que você usa. Cada um devolve `null` quando a URL não é dele. O link do e-mail completa o login no mesmo browser que pediu o código; em outro aparelho, a pessoa digita o código. O login por conexão de identidade (Sankhya Pass), pelo iframe ou por redirect, dispensa essa chamada: o `init()` já completa.
|
|
253
|
+
- A sessão fica no `localStorage` do domínio do app, na chave `mitra_auth_{appId}`, e é renovada sozinha antes de vencer. A do login por conexão de identidade fica no `sessionStorage` da aba, na mesma chave. `signOut()` limpa a sessão e, em app com contas próprias, encerra a sessão no servidor: o refresh token deixa de renovar, e o access token já emitido vale até vencer.
|
|
254
|
+
- Alguns apps recebem tokens extras junto da sessão, em `auth.allTokens`, liberados app por app pela Mitra. O de backoffice é o mais sensível: ele carrega os acessos que a pessoa tem no backoffice da Mitra, vale uma hora e fica no mesmo storage da sessão, onde qualquer script do domínio do app consegue ler. Leia ele por `auth.ensureFreshBackofficeToken()`, que renova o token quando está perto de vencer e devolve `null` quando o app ou a pessoa não têm esse acesso. Use só contra o backoffice e não repasse para outro serviço.
|
|
155
255
|
- O SDK só repete uma requisição depois de renovar o token num `401`. Fora isso, quem decide repetir é o app.
|
|
156
256
|
- Nunca coloque API key em código que vai para o browser, nem passe uma em `createClient({ apiKey })` num app de browser: o bundle entrega a chave a quem abrir o app. O `signInWithApiKey()` recusa rodar no browser, mas isso não tira do bundle uma chave escrita nele. Para processo sem pessoa, como cron ou coletor, use `@mitralab.io/functions-sdk` com `createClientFromApiKey`.
|
|
157
257
|
|