@allanfsouza/aether-sdk 2.4.10 → 2.5.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/README.md CHANGED
@@ -1,9 +1,299 @@
1
- # Plataforma SDK (Cliente JS/TS)
1
+ # 🚀 Aether SDK
2
2
 
3
- Este é o SDK oficial para interagir com a sua "Plataforma BaaS" (clone do Firebase). Ele gerencia autenticação, banco de dados genérico (com tempo real) e storage.
3
+ SDK oficial JavaScript/TypeScript para a plataforma **Aether BaaS**.
4
+
5
+ [![npm version](https://badge.fury.io/js/%40allanfsouza%2Faether-sdk.svg)](https://www.npmjs.com/package/@allanfsouza/aether-sdk)
4
6
 
5
7
  ## Instalação
6
8
 
7
9
  ```bash
8
- npm install @seu-username/plataforma-sdk
10
+ npm install @allanfsouza/aether-sdk
11
+ ```
12
+
13
+ ## Inicialização
14
+
15
+ ```typescript
16
+ import { PlataformaClient } from '@allanfsouza/aether-sdk';
17
+
18
+ const aether = new PlataformaClient({
19
+ baseUrl: 'https://sua-api.aether.com',
20
+ apiKey: 'seu-project-id',
21
+ persistSession: true // Salva sessão no localStorage (padrão: true)
22
+ });
23
+ ```
24
+
25
+ ---
26
+
27
+ ## 📦 Database
28
+
29
+ ```typescript
30
+ const users = aether.db.collection('users');
31
+
32
+ // Listar
33
+ const list = await users.list({ limit: 10 });
34
+
35
+ // Buscar por ID
36
+ const user = await users.get('user-id');
37
+
38
+ // Criar
39
+ const newUser = await users.create({ name: 'João', email: 'joao@email.com' });
40
+
41
+ // Atualizar
42
+ await users.update('user-id', { name: 'Novo Nome' });
43
+
44
+ // Deletar
45
+ await users.delete('user-id');
46
+ ```
47
+
48
+ ### Query Builder
49
+
50
+ ```typescript
51
+ const adults = await aether.db.collection('users')
52
+ .query()
53
+ .eq('status', 'active')
54
+ .gt('age', 18)
55
+ .order('name', 'ASC')
56
+ .limit(50)
57
+ .get();
58
+ ```
59
+
60
+ ---
61
+
62
+ ## 🔐 Autenticação
63
+
64
+ ```typescript
65
+ // Login
66
+ const { accessToken, user } = await aether.auth.login('email@test.com', 'senha');
67
+
68
+ // Registro
69
+ await aether.auth.register({ name: 'João', email: 'joao@email.com', password: 'senha' });
70
+
71
+ // Logout
72
+ await aether.auth.logout();
73
+
74
+ // Sessão
75
+ const user = aether.auth.getCurrentUser();
76
+ ```
77
+
78
+ ---
79
+
80
+ ## 📁 Storage
81
+
82
+ ```typescript
83
+ // Upload
84
+ const { data } = await aether.storage.upload(file, 'avatar.png', 'image/png');
85
+ console.log(data.downloadUrl);
86
+
87
+ // Listar
88
+ const files = await aether.storage.list('folder');
89
+
90
+ // Deletar
91
+ await aether.storage.delete('file-id');
92
+ ```
93
+
94
+ ---
95
+
96
+ ## ⚡ Functions
97
+
98
+ ```typescript
99
+ // Invocar função
100
+ const result = await aether.functions.invoke('send-email', {
101
+ to: 'user@email.com',
102
+ subject: 'Olá!',
103
+ body: 'Bem-vindo!'
104
+ });
9
105
  ```
106
+
107
+ ---
108
+
109
+ ## 📱 Push Notifications
110
+
111
+ ```typescript
112
+ // Registrar dispositivo
113
+ await aether.push.registerDevice({
114
+ token: 'fcm-token',
115
+ platform: 'android',
116
+ environment: 'prod'
117
+ });
118
+
119
+ // Enviar para usuário
120
+ await aether.push.sendToUser({
121
+ userId: 'user-id',
122
+ title: 'Olá!',
123
+ body: 'Nova mensagem'
124
+ });
125
+ ```
126
+
127
+ ---
128
+
129
+ ## 🤖 AI (Inteligência Artificial)
130
+
131
+ O módulo de IA permite adicionar capacidades de linguagem natural aos seus apps.
132
+
133
+ ### Chat Simples
134
+
135
+ ```typescript
136
+ // Pergunta simples (aguarda resposta completa)
137
+ const { text, conversationId } = await aether.ai.ask("Quais produtos estão em promoção?");
138
+ console.log(text);
139
+ ```
140
+
141
+ ### Chat com Streaming
142
+
143
+ ```typescript
144
+ // Resposta em tempo real (chunk por chunk)
145
+ await aether.ai.chat("Explique como funciona o sistema de pagamentos", {
146
+ conversationId: 'conv-id-opcional', // Mantém contexto
147
+ onChunk: (chunk) => {
148
+ // Atualiza UI em tempo real
149
+ setResponse(prev => prev + chunk);
150
+ },
151
+ onComplete: (fullResponse, meta) => {
152
+ console.log("Conversa:", meta.conversationId);
153
+ },
154
+ onError: (error) => {
155
+ console.error(error);
156
+ }
157
+ });
158
+ ```
159
+
160
+ ### Busca Semântica
161
+
162
+ ```typescript
163
+ // Encontra documentos similares usando embeddings
164
+ const results = await aether.ai.search("tênis confortável para corrida", {
165
+ collection: "products", // Opcional: filtrar por collection
166
+ limit: 10,
167
+ minScore: 0.7
168
+ });
169
+
170
+ results.forEach(r => console.log(r.content, r.similarity));
171
+ ```
172
+
173
+ ### Geração de Conteúdo
174
+
175
+ ```typescript
176
+ // Gera texto baseado em dados e prompt
177
+ const descricao = await aether.ai.generate(
178
+ "Escreva uma descrição para o produto",
179
+ { name: "iPhone 15", price: 5999, features: ["5G", "48MP"] },
180
+ { tone: 'friendly', length: 'medium', language: 'pt-BR' }
181
+ );
182
+ ```
183
+
184
+ ### Análise de Dados
185
+
186
+ ```typescript
187
+ // Analisa dados e retorna insights em linguagem natural
188
+ const { insights, data } = await aether.ai.analyze("orders", {
189
+ question: "Como foram as vendas essa semana?",
190
+ period: "7d"
191
+ });
192
+ console.log(insights);
193
+ ```
194
+
195
+ ### Conversão de Linguagem Natural para Query
196
+
197
+ ```typescript
198
+ // Converte texto em filtros estruturados
199
+ const query = await aether.ai.parseQuery(
200
+ "produtos vermelhos acima de 100 reais ordenados por preço"
201
+ );
202
+ // Retorna: { filter: { color: 'vermelho', price: { $gt: 100 } }, sort: { price: 'ASC' } }
203
+ ```
204
+
205
+ ### Gerenciar Conversas
206
+
207
+ ```typescript
208
+ // Listar conversas
209
+ const conversas = await aether.ai.conversations.list();
210
+
211
+ // Histórico de mensagens
212
+ const mensagens = await aether.ai.conversations.getMessages(conversationId);
213
+
214
+ // Renomear conversa
215
+ await aether.ai.conversations.rename(conversationId, "Suporte Técnico");
216
+
217
+ // Deletar conversa
218
+ await aether.ai.conversations.delete(conversationId);
219
+ ```
220
+
221
+ ### Feedback
222
+
223
+ ```typescript
224
+ // Enviar feedback sobre resposta
225
+ await aether.ai.feedback(messageId, 'thumbs_up');
226
+ await aether.ai.feedback(messageId, 'thumbs_down', 'Resposta incorreta');
227
+ ```
228
+
229
+ ### Funções Administrativas
230
+
231
+ ```typescript
232
+ // Reindexar dados para RAG
233
+ await aether.ai.admin.reindex();
234
+
235
+ // Estatísticas de uso
236
+ const stats = await aether.ai.admin.stats();
237
+ console.log(stats.totalConversations, stats.totalMessages);
238
+
239
+ // Configurar collections indexadas
240
+ await aether.ai.admin.setIndexedCollections(['products', 'articles', 'faq']);
241
+
242
+ // Limpar embeddings (CUIDADO!)
243
+ await aether.ai.admin.clear();
244
+ ```
245
+
246
+ ---
247
+
248
+ ## 👥 Tenant Auth
249
+
250
+ Para apps que precisam de sistema de login para usuários finais:
251
+
252
+ ```typescript
253
+ // Registro de usuário no projeto
254
+ const { user } = await aether.tenantAuth.signUp('project-id', {
255
+ email: 'usuario@app.com',
256
+ password: 'senha123',
257
+ name: 'Nome'
258
+ });
259
+
260
+ // Login
261
+ const { accessToken, user } = await aether.tenantAuth.signIn('project-id', {
262
+ email: 'usuario@app.com',
263
+ password: 'senha123'
264
+ });
265
+
266
+ // Perfil
267
+ const profile = await aether.tenantAuth.getProfile();
268
+
269
+ // Logout
270
+ aether.tenantAuth.signOut();
271
+ ```
272
+
273
+ ---
274
+
275
+ ## 📖 Tipos Exportados
276
+
277
+ ```typescript
278
+ import type {
279
+ // Auth
280
+ LoginResponse, Session, User,
281
+ // Database
282
+ ListOptions,
283
+ // Push
284
+ PushDevice, PushStatus, PushStats,
285
+ // Tenant
286
+ TenantUser, TenantLoginResponse,
287
+ // AI
288
+ ChatOptions, ChatMetadata, AskResponse,
289
+ Conversation, Message, FeedbackType,
290
+ SemanticSearchOptions, SemanticSearchResult,
291
+ GenerateOptions, RetrievedSource
292
+ } from '@allanfsouza/aether-sdk';
293
+ ```
294
+
295
+ ---
296
+
297
+ ## 📝 Licença
298
+
299
+ MIT © Allan Felipe de Souza
package/dist/ai.d.ts ADDED
@@ -0,0 +1,300 @@
1
+ import type { AxiosInstance } from "axios";
2
+ import type { PlataformaClient } from "./index.js";
3
+ /**
4
+ * Opções para o método chat()
5
+ */
6
+ export interface ChatOptions {
7
+ /** ID da conversa para manter contexto entre mensagens */
8
+ conversationId?: string;
9
+ /** Contexto adicional (ex: "vendas", "suporte", "produtos") */
10
+ context?: string;
11
+ /** Callback chamado a cada chunk de texto recebido (streaming) */
12
+ onChunk?: (chunk: string) => void;
13
+ /** Callback chamado quando a resposta completa é recebida */
14
+ onComplete?: (fullResponse: string, metadata: ChatMetadata) => void;
15
+ /** Callback chamado em caso de erro */
16
+ onError?: (error: Error) => void;
17
+ /** Timeout em ms (padrão: 30000) */
18
+ timeout?: number;
19
+ }
20
+ /**
21
+ * Metadados retornados após uma resposta completa
22
+ */
23
+ export interface ChatMetadata {
24
+ conversationId: string;
25
+ messageId?: string;
26
+ tokensUsed?: number;
27
+ sources?: RetrievedSource[];
28
+ }
29
+ /**
30
+ * Fonte de dados usada pelo RAG
31
+ */
32
+ export interface RetrievedSource {
33
+ type: string;
34
+ content: string;
35
+ similarity: number;
36
+ }
37
+ /**
38
+ * Resposta do método ask()
39
+ */
40
+ export interface AskResponse {
41
+ text: string;
42
+ conversationId: string;
43
+ sources?: RetrievedSource[];
44
+ }
45
+ /**
46
+ * Conversa persistida
47
+ */
48
+ export interface Conversation {
49
+ id: string;
50
+ title: string;
51
+ context: string;
52
+ createdAt: string;
53
+ updatedAt: string;
54
+ messageCount?: number;
55
+ }
56
+ /**
57
+ * Mensagem de uma conversa
58
+ */
59
+ export interface Message {
60
+ id: string;
61
+ conversationId: string;
62
+ role: 'user' | 'assistant';
63
+ content: string;
64
+ metadata?: Record<string, any>;
65
+ createdAt: string;
66
+ }
67
+ /**
68
+ * Tipo de feedback
69
+ */
70
+ export type FeedbackType = 'thumbs_up' | 'thumbs_down';
71
+ /**
72
+ * Opções para busca semântica
73
+ */
74
+ export interface SemanticSearchOptions {
75
+ /** Número máximo de resultados (padrão: 10) */
76
+ limit?: number;
77
+ /** Score mínimo de similaridade 0-1 (padrão: 0.5) */
78
+ minScore?: number;
79
+ /** Filtrar por collection específica */
80
+ collection?: string;
81
+ }
82
+ /**
83
+ * Resultado de busca semântica
84
+ */
85
+ export interface SemanticSearchResult {
86
+ id: string;
87
+ content: string;
88
+ collection: string;
89
+ similarity: number;
90
+ metadata?: Record<string, any>;
91
+ }
92
+ /**
93
+ * Opções para geração de conteúdo
94
+ */
95
+ export interface GenerateOptions {
96
+ /** Tom do texto (formal, casual, técnico, etc) */
97
+ tone?: 'formal' | 'casual' | 'technical' | 'friendly';
98
+ /** Tamanho aproximado (short, medium, long) */
99
+ length?: 'short' | 'medium' | 'long';
100
+ /** Idioma (padrão: pt-BR) */
101
+ language?: string;
102
+ /** Contexto adicional para a geração */
103
+ context?: string;
104
+ }
105
+ export declare class AIModule {
106
+ private client;
107
+ private http;
108
+ /** Sub-módulo para gerenciar conversas */
109
+ conversations: ConversationsAPI;
110
+ /** Sub-módulo para funções administrativas */
111
+ admin: AIAdminAPI;
112
+ constructor(client: PlataformaClient, http: AxiosInstance);
113
+ /**
114
+ * Faz uma pergunta simples e aguarda a resposta completa.
115
+ * Ideal para quando não precisa de streaming.
116
+ *
117
+ * @example
118
+ * const { text } = await aether.ai.ask("Quais produtos estão em promoção?");
119
+ * console.log(text);
120
+ */
121
+ ask(message: string, conversationId?: string): Promise<AskResponse>;
122
+ /**
123
+ * Inicia um chat com streaming de resposta.
124
+ * A resposta chega em chunks conforme a IA gera.
125
+ *
126
+ * @example
127
+ * await aether.ai.chat("Explique como funciona o sistema de pagamentos", {
128
+ * onChunk: (chunk) => {
129
+ * // Atualiza UI em tempo real
130
+ * setResponse(prev => prev + chunk);
131
+ * },
132
+ * onComplete: (full, meta) => {
133
+ * console.log("Conversa ID:", meta.conversationId);
134
+ * }
135
+ * });
136
+ */
137
+ chat(message: string, options?: ChatOptions): Promise<void>;
138
+ /**
139
+ * Envia feedback sobre uma resposta da IA.
140
+ * Ajuda a melhorar as respostas futuras.
141
+ *
142
+ * @example
143
+ * await aether.ai.feedback(messageId, 'thumbs_up');
144
+ * await aether.ai.feedback(messageId, 'thumbs_down', 'Resposta incorreta');
145
+ */
146
+ feedback(messageId: string, type: FeedbackType, comment?: string): Promise<{
147
+ success: boolean;
148
+ }>;
149
+ /**
150
+ * Busca semântica nos dados do projeto.
151
+ * Encontra documentos similares usando embeddings.
152
+ *
153
+ * @example
154
+ * // Busca produtos similares a uma descrição
155
+ * const results = await aether.ai.search("tênis confortável para corrida");
156
+ *
157
+ * // Com filtros
158
+ * const results = await aether.ai.search("problema no login", {
159
+ * collection: "support_tickets",
160
+ * limit: 5,
161
+ * minScore: 0.7
162
+ * });
163
+ */
164
+ search(query: string, options?: SemanticSearchOptions): Promise<SemanticSearchResult[]>;
165
+ /**
166
+ * Gera texto baseado em um prompt e contexto.
167
+ * Útil para descrições de produtos, resumos, etc.
168
+ *
169
+ * @example
170
+ * // Gerar descrição de produto
171
+ * const descricao = await aether.ai.generate(
172
+ * "Escreva uma descrição para o produto",
173
+ * { productName: "iPhone 15", price: 5999, features: ["5G", "48MP"] },
174
+ * { tone: 'friendly', length: 'medium' }
175
+ * );
176
+ */
177
+ generate(prompt: string, data: Record<string, any>, options?: GenerateOptions): Promise<string>;
178
+ /**
179
+ * Analisa dados e retorna insights em linguagem natural.
180
+ *
181
+ * @example
182
+ * const insights = await aether.ai.analyze("orders", {
183
+ * question: "Como foram as vendas essa semana?",
184
+ * period: "7d"
185
+ * });
186
+ */
187
+ analyze(collection: string, options: {
188
+ question: string;
189
+ period?: string;
190
+ }): Promise<{
191
+ insights: string;
192
+ data?: any;
193
+ }>;
194
+ /**
195
+ * Processa linguagem natural e converte em query estruturada.
196
+ * Útil para criar filtros de busca baseados em texto do usuário.
197
+ *
198
+ * @example
199
+ * const query = await aether.ai.parseQuery(
200
+ * "produtos vermelhos acima de 100 reais ordenados por preço"
201
+ * );
202
+ * // Retorna: { filter: { color: 'vermelho', price: { $gt: 100 } }, sort: { price: 'ASC' } }
203
+ */
204
+ parseQuery(naturalLanguage: string, collection?: string): Promise<{
205
+ filter?: Record<string, any>;
206
+ sort?: Record<string, any>;
207
+ }>;
208
+ }
209
+ declare class ConversationsAPI {
210
+ private client;
211
+ private http;
212
+ constructor(client: PlataformaClient, http: AxiosInstance);
213
+ /**
214
+ * Lista todas as conversas do usuário no projeto.
215
+ *
216
+ * @example
217
+ * const conversas = await aether.ai.conversations.list();
218
+ */
219
+ list(): Promise<Conversation[]>;
220
+ /**
221
+ * Busca o histórico de mensagens de uma conversa.
222
+ *
223
+ * @example
224
+ * const mensagens = await aether.ai.conversations.getMessages(conversationId);
225
+ */
226
+ getMessages(conversationId: string): Promise<Message[]>;
227
+ /**
228
+ * Deleta uma conversa e todo seu histórico.
229
+ *
230
+ * @example
231
+ * await aether.ai.conversations.delete(conversationId);
232
+ */
233
+ delete(conversationId: string): Promise<{
234
+ success: boolean;
235
+ }>;
236
+ /**
237
+ * Renomeia uma conversa.
238
+ *
239
+ * @example
240
+ * await aether.ai.conversations.rename(conversationId, "Suporte Técnico");
241
+ */
242
+ rename(conversationId: string, title: string): Promise<Conversation>;
243
+ }
244
+ declare class AIAdminAPI {
245
+ private client;
246
+ private http;
247
+ constructor(client: PlataformaClient, http: AxiosInstance);
248
+ /**
249
+ * Reindexa todos os dados do projeto para RAG.
250
+ * Use após adicionar/modificar grandes volumes de dados.
251
+ * Executa em background.
252
+ *
253
+ * @example
254
+ * await aether.ai.admin.reindex();
255
+ */
256
+ reindex(): Promise<{
257
+ message: string;
258
+ }>;
259
+ /**
260
+ * Limpa todos os embeddings do projeto.
261
+ * CUIDADO: A IA "esquece" todo o contexto aprendido.
262
+ *
263
+ * @example
264
+ * const { deletedCount } = await aether.ai.admin.clear();
265
+ */
266
+ clear(): Promise<{
267
+ deletedCount: number;
268
+ }>;
269
+ /**
270
+ * Retorna estatísticas de uso da IA.
271
+ *
272
+ * @example
273
+ * const stats = await aether.ai.admin.stats();
274
+ * console.log(stats.totalConversations, stats.totalMessages);
275
+ */
276
+ stats(): Promise<{
277
+ totalConversations: number;
278
+ totalMessages: number;
279
+ totalEmbeddings: number;
280
+ storageUsedMB: number;
281
+ }>;
282
+ /**
283
+ * Configura quais collections são indexadas automaticamente.
284
+ *
285
+ * @example
286
+ * await aether.ai.admin.setIndexedCollections(['products', 'articles', 'faq']);
287
+ */
288
+ setIndexedCollections(collections: string[]): Promise<{
289
+ success: boolean;
290
+ }>;
291
+ /**
292
+ * Busca configurações atuais de IA do projeto.
293
+ */
294
+ getConfig(): Promise<{
295
+ indexedCollections: string[];
296
+ autoIndex: boolean;
297
+ embeddingModel: string;
298
+ }>;
299
+ }
300
+ export {};