@menuia/core 1.5.2 → 1.7.1

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 ADDED
@@ -0,0 +1,148 @@
1
+ # @menuia/core
2
+
3
+ SDK do chat da MenuIA para colocar o atendimento (IA + equipe) dentro do seu site ou app.
4
+
5
+ ```bash
6
+ npm install @menuia/core
7
+ ```
8
+
9
+ ```ts
10
+ import { MenuIAClient } from '@menuia/core';
11
+
12
+ const chat = new MenuIAClient({
13
+ widgetId: 'SEU_WIDGET_ID', // painel › Canais › Widget
14
+ onMessage: (msg) => console.log(msg.role, msg.content),
15
+ });
16
+
17
+ await chat.sendMessage({ content: 'Olá!' });
18
+ chat.startPolling(); // respostas da equipe chegam por aqui
19
+ ```
20
+
21
+ ## Widget privado (cliente logado)
22
+
23
+ No widget **privado**, quem diz quem é o cliente é o **seu servidor**:
24
+
25
+ 1. Seu backend chama `POST https://api-ia.menuia.com/api/v1/widget/<widgetId>/auth` com
26
+ `Authorization: Bearer wsec_...` (segredo do painel; nunca vai para o navegador) e o corpo
27
+ `{ externalUserId, name, email, phone }` de quem está logado.
28
+ 2. A resposta traz `sessionToken` (vale ~10 min). Só ele vai para o front:
29
+
30
+ ```ts
31
+ const chat = new MenuIAClient({ widgetId, sessionToken, metadata: { widgetSession: sessionToken } });
32
+ ```
33
+
34
+ ## Notificação quando a equipe ou a IA responde
35
+
36
+ Há dois jeitos, e eles se completam:
37
+
38
+ | | Quando funciona | O que você precisa |
39
+ |---|---|---|
40
+ | **Push de aplicativo** (`registrarPush`) | com o app **fechado** ou em segundo plano | app com FCM ou Expo + credencial cadastrada no painel |
41
+ | **Aviso do navegador** (`ativarNotificacaoNoNavegador`) | com a página aberta em **outra aba** ou minimizada | só o navegador (nenhuma credencial) |
42
+
43
+ ### 1. Push de aplicativo
44
+
45
+ **a) Cadastre a credencial de envio (uma vez, dono ou admin da conta).**
46
+ Ela fica no servidor da MenuIA. Nunca vai no app e nunca é devolvida em leitura.
47
+
48
+ - **FCM** (Android, iOS ou web com o SDK do Firebase): no console do Firebase, abra Configurações
49
+ do projeto › Contas de serviço › **Gerar nova chave privada** e envie o JSON:
50
+
51
+ ```bash
52
+ curl -X PUT https://api-ia.menuia.com/api/v1/push-credentials/fcm \
53
+ -H "Authorization: Bearer <token do painel>" -H "Content-Type: application/json" \
54
+ -d '{"serviceAccount": <conteúdo do JSON>, "titulo": "Minha Loja"}'
55
+ ```
56
+
57
+ A chave é conferida com o Google na hora: chave revogada ou incompleta é recusada.
58
+
59
+ - **Expo** (React Native / expo-notifications): não precisa de credencial. O token de acesso só é
60
+ necessário com "push security" ligado no Expo.
61
+
62
+ ```bash
63
+ curl -X PUT https://api-ia.menuia.com/api/v1/push-credentials/expo \
64
+ -H "Authorization: Bearer <token do painel>" -H "Content-Type: application/json" \
65
+ -d '{"titulo": "Minha Loja"}'
66
+ ```
67
+
68
+ **Opções** (as duas valem por credencial):
69
+
70
+ - `titulo`: título da notificação. Padrão: o nome da conta.
71
+ - `previa: false`: manda "Você tem uma mensagem nova no chat" em vez do começo da mensagem.
72
+
73
+ **Ver e remover:**
74
+
75
+ - `GET /push-credentials` mostra só o que está configurado, uma dica e quantos aparelhos.
76
+ - `DELETE /push-credentials/<fcm|expo>` remove.
77
+
78
+ **b) No app, registre o aparelho:**
79
+
80
+ ```ts
81
+ // Android/iOS com Firebase
82
+ const token = await messaging().getToken();
83
+ await chat.registrarPush({ tipo: 'fcm', token, plataforma: 'android' });
84
+
85
+ // Expo
86
+ const { data: token } = await Notifications.getExpoPushTokenAsync();
87
+ await chat.registrarPush({ tipo: 'expo', token });
88
+ ```
89
+
90
+ **Quem recebe:**
91
+
92
+ - **Widget privado:** o aparelho fica ligado à PESSOA (`externalUserId` do token de sessão) e recebe
93
+ as respostas de todas as conversas dela.
94
+ - **Widget público:** o aparelho fica ligado à conversa deste aparelho.
95
+ - Antes da primeira mensagem ainda não existe conversa. Nesse caso `registrarPush` devolve
96
+ `{ ok: true, pendente: true }` e o registro sai sozinho logo depois da primeira mensagem.
97
+ - **O mesmo token registrado de novo muda de dono:** num aparelho compartilhado, só quem entrou por
98
+ último recebe.
99
+ - **Ao sair da conta,** desligue: `await chat.removerPush(token)`.
100
+
101
+ **O que chega no aparelho:**
102
+
103
+ - **Título:** o configurado (ou o nome da conta). Com várias respostas antes de a pessoa voltar,
104
+ vira `Minha Loja — 3 mensagens novas`, numa notificação só: a nova substitui a anterior.
105
+ - **Texto:** o começo da mensagem (até 90 caracteres), sem marcação. Link vira "link" e mídia vira
106
+ "Imagem", "Áudio", "Vídeo" ou "Arquivo".
107
+ - **Não notifica:** mensagem do próprio visitante, nota interna da equipe e avisos do sistema.
108
+ - **`data`:** `{ menuia: 'chat', conversationId, widgetId }`. Use para abrir a tela do chat no
109
+ toque.
110
+ - **App aberto na tela:** o FCM entrega em `onMessageReceived`/`onMessage` e o sistema não mostra
111
+ nada. Decida no app se quer mostrar.
112
+
113
+ **A contagem é do que a pessoa ainda não viu.** Zera quando ela escreve e quando está com o chat
114
+ na tela. Com `startPolling()` e a página visível, o SDK avisa a presença sozinho. Em app nativo,
115
+ chame `chat.marcarPresenca()` a cada ~20 s enquanto a tela do chat estiver aberta.
116
+
117
+ ### 2. Aviso do navegador
118
+
119
+ ```ts
120
+ botao.onclick = async () => {
121
+ // ⚠️ dentro de um clique: o navegador só pede permissão em resposta a um gesto da pessoa
122
+ const permissao = await chat.ativarNotificacaoNoNavegador({ titulo: 'Minha Loja', icone: '/logo.png' });
123
+ // 'granted' | 'denied' | 'default' | 'indisponivel'
124
+ };
125
+ chat.startPolling();
126
+ ```
127
+
128
+ - Com a aba **escondida**, cada resposta vira um aviso. O aviso seguinte substitui o anterior e
129
+ mostra a contagem.
130
+ - Ao voltar para a aba, o aviso fecha e a contagem zera.
131
+ - **Com a aba visível, nada aparece:** a pessoa já está vendo.
132
+ - **Com a página fechada, não há aviso.** Use o push de aplicativo.
133
+ - Para desligar: `chat.desativarNotificacaoNoNavegador()`.
134
+
135
+ > **Web Push (service worker, aviso com o site fechado) ainda não está disponível.** Por isso
136
+ > `registrarPush({ tipo: 'webpush' })` responde 400 explicando. Se o seu site já usa o Firebase
137
+ > Messaging no navegador, o token dele é do tipo `fcm` e funciona normalmente.
138
+
139
+ ### Sem o SDK (chamadas diretas)
140
+
141
+ `POST /api/v1/widget/<widgetId>/push` com
142
+ `{ tipo: 'fcm' | 'expo', token, plataforma? }` e uma das provas abaixo:
143
+
144
+ - **widget privado:** header `x-widget-session: <sessionToken>`;
145
+ - **widget público:** `sessionId` da conversa no corpo, ou o `widgetToken` que `/widget/<id>/session`
146
+ devolveu.
147
+
148
+ Para desligar: `POST /api/v1/widget/<widgetId>/push/remove` com `{ token }` e a mesma prova.
package/dist/index.d.mts CHANGED
@@ -26,6 +26,11 @@ interface MenuIAConfig {
26
26
  * ignorado pelo servidor, de proposito: quem garante a identidade e o seu backend.
27
27
  */
28
28
  sessionToken?: string;
29
+ /**
30
+ * Widget privado: o servidor recusou o token de sessao (vencido ou invalido). Busque um token
31
+ * novo no SEU servidor e chame `setSessionToken(novo)` — a conversa continua a mesma.
32
+ */
33
+ onSessionTokenExpired?: () => void;
29
34
  onMessage?: (message: ChatMessage) => void;
30
35
  onStatusChange?: (status: ConnectionStatus) => void;
31
36
  onTicketCreated?: (ticketId: string) => void;
@@ -44,7 +49,71 @@ interface ChatMessage {
44
49
  toolCalls?: string;
45
50
  toolResults?: string;
46
51
  authorName?: string;
52
+ /**
53
+ * Botoes / lista / carrossel desta mensagem (ver `InteractivePayload`).
54
+ * Quando vem preenchido, `content` traz o MESMO conteudo em texto: mostre um OU outro.
55
+ */
56
+ interactive?: InteractivePayload;
57
+ /**
58
+ * O envio desta mensagem FALHOU e ela nao chegou ao servidor.
59
+ *
60
+ * ⚠️ Sem este campo a bolha do usuario ficava na tela identica a uma enviada com sucesso
61
+ * quando o envio falhava — o hook so chamava `setError`, e quem olhava o chat nao tinha como
62
+ * saber que aquela mensagem nunca saiu. O widget proprio desta casa sempre teve `failed` +
63
+ * botao de reenviar; o SDK nao tinha recebido a paridade.
64
+ *
65
+ * Desenhe a bolha com um aviso e um botao que chame `retryMessage(msg)`.
66
+ */
67
+ failed?: boolean;
47
68
  }
69
+ /** Botao de mensagem interativa: com `url` abre um link; sem, e resposta rapida. */
70
+ interface InteractiveButton {
71
+ text: string;
72
+ url?: string;
73
+ id?: string;
74
+ }
75
+ /**
76
+ * Mensagem interativa enviada pela IA: botoes, lista/menu ou carrossel.
77
+ *
78
+ * Como desenhar: botao com `url` abre o link em outra aba; botao sem `url` e item de lista sao
79
+ * RESPOSTA — ao tocar, envie o rotulo (`text` / `title`) como a proxima mensagem do usuario.
80
+ * Quem nao desenha pode mostrar so o `content` da mensagem, que traz as mesmas opcoes em texto.
81
+ *
82
+ * ⚠️ O conteudo vem da IA: so abra `url` e `imageUrl` que comecem com http:// ou https://.
83
+ */
84
+ type InteractivePayload = {
85
+ kind: 'buttons';
86
+ text?: string;
87
+ header?: string;
88
+ footer?: string;
89
+ buttons: InteractiveButton[];
90
+ } | {
91
+ kind: 'list';
92
+ text?: string;
93
+ header?: string;
94
+ list: {
95
+ title?: string;
96
+ footer?: string;
97
+ sections: Array<{
98
+ title?: string;
99
+ rows: Array<{
100
+ title: string;
101
+ description?: string;
102
+ id?: string;
103
+ }>;
104
+ }>;
105
+ };
106
+ } | {
107
+ kind: 'carousel';
108
+ text?: string;
109
+ footer?: string;
110
+ cards: Array<{
111
+ imageUrl?: string;
112
+ body?: string;
113
+ footer?: string;
114
+ buttons?: InteractiveButton[];
115
+ }>;
116
+ };
48
117
  interface SendMessageOptions {
49
118
  content: string;
50
119
  attachments?: MessageAttachment[];
@@ -72,13 +141,51 @@ interface ChatResponse {
72
141
  aiPaused?: boolean;
73
142
  /** Enquanto a IA consulta a equipe: ate quando esperar por uma resposta. */
74
143
  aiCheckingUntil?: string;
144
+ /**
145
+ * Mensagens interativas (botoes / lista / carrossel) que a IA mostrou NESTE turno, em ordem e
146
+ * com o id real. Na tela vem ANTES de `message`. As mesmas voltam no historico (`loadHistory`).
147
+ */
148
+ interactiveMessages?: ChatMessage[];
75
149
  };
76
150
  }
77
151
  interface StreamEvent {
78
152
  type: 'token' | 'thinking' | 'tool_start' | 'tool_done' | 'tool_end' | 'done' | 'error' | 'response';
79
153
  data: unknown;
80
154
  }
155
+ /**
156
+ * Aparelho que recebe notificacao quando a equipe ou a IA responde (`client.registrarPush`).
157
+ *
158
+ * - `fcm`: token do Firebase Cloud Messaging (Android/iOS nativo, ou web com o SDK do Firebase).
159
+ * - `expo`: `ExponentPushToken[...]` do expo-notifications (React Native/Expo).
160
+ *
161
+ * A credencial de envio (conta de servico do Firebase / token do Expo) e do DONO do widget,
162
+ * cadastrada no painel — nunca vai no app.
163
+ */
164
+ interface RegistrarPushOptions {
165
+ tipo: 'fcm' | 'expo';
166
+ token: string;
167
+ /** Opcional, so para o painel saber de onde veio (ex.: 'android', 'ios', 'web'). */
168
+ plataforma?: string;
169
+ }
170
+ interface RegistrarPushResult {
171
+ ok: boolean;
172
+ /**
173
+ * Widget publico sem conversa ainda: o registro fica guardado e sai sozinho logo depois da
174
+ * primeira mensagem (antes disso nao ha resposta para avisar).
175
+ */
176
+ pendente?: boolean;
177
+ erro?: string;
178
+ }
179
+ /** Aviso do NAVEGADOR (Notification API) quando chega resposta com a aba escondida. */
180
+ interface NotificacaoNavegadorOptions {
181
+ /** Titulo do aviso. Padrao: 'Nova mensagem'. */
182
+ titulo?: string;
183
+ /** URL do icone. */
184
+ icone?: string;
185
+ }
81
186
  interface WidgetSession {
187
+ /** Registro de push guardado ate existir conversa (widget publico). */
188
+ pushPendente?: RegistrarPushOptions;
82
189
  sessionId: string;
83
190
  conversationId?: string;
84
191
  ticketId?: string;
@@ -100,6 +207,12 @@ declare class MenuIAClient {
100
207
  private pollInterval;
101
208
  private lastMessageCount;
102
209
  private resolvedAgentId;
210
+ /** Aviso do navegador ligado (ativarNotificacaoNoNavegador) e quantas chegaram com a aba escondida. */
211
+ private notifNavegador;
212
+ private naoVistasNavegador;
213
+ private avisoNavegador;
214
+ private ultimaPresenca;
215
+ private ouvindoVisibilidade;
103
216
  constructor(config: MenuIAConfig);
104
217
  /** Get the effective ID (widgetId preferred, falls back to agentId) */
105
218
  private getWidgetId;
@@ -113,12 +226,52 @@ declare class MenuIAClient {
113
226
  private ensureSession;
114
227
  /** Send a message to the AI agent */
115
228
  sendMessage(options: SendMessageOptions): Promise<ChatResponse>;
229
+ /**
230
+ * Troca o token de sessão do widget privado (o servidor do site emite um novo antes de o anterior
231
+ * vencer). Vale para as próximas chamadas; a conversa continua a mesma.
232
+ */
233
+ setSessionToken(token: string): void;
116
234
  /** Send a message and receive streaming response */
117
235
  sendMessageStream(options: SendMessageOptions, onToken: (token: string, fullText: string) => void): Promise<ChatResponse | null>;
118
236
  /** Load conversation history from server */
119
237
  loadHistory(): Promise<ChatMessage[]>;
120
238
  /** Start polling for new messages (human agent replies) */
121
239
  startPolling(intervalMs?: number): void;
240
+ /**
241
+ * Registra este aparelho para receber notificacao quando a equipe ou a IA responder no chat,
242
+ * mesmo com o app fechado. O envio usa a credencial do DONO do widget (painel > Notificacoes do
243
+ * chat); o app so entrega o token do aparelho.
244
+ *
245
+ * - Widget PRIVADO: vale para a PESSOA (identidade do token de sessao) em todas as conversas dela.
246
+ * - Widget publico: vale para a conversa deste aparelho. Sem conversa ainda, fica guardado e sai
247
+ * sozinho depois da primeira mensagem (`pendente: true`).
248
+ *
249
+ * O mesmo token registrado de novo muda de dono: num aparelho compartilhado, so quem entrou por
250
+ * ultimo recebe. Ao sair da conta, chame `removerPush(token)`.
251
+ */
252
+ registrarPush(opcoes: RegistrarPushOptions): Promise<RegistrarPushResult>;
253
+ /** Desliga a notificacao neste aparelho (ex.: ao sair da conta no app). */
254
+ removerPush(token: string): Promise<RegistrarPushResult>;
255
+ /**
256
+ * Aviso do NAVEGADOR quando chega resposta com a aba escondida (Notification API).
257
+ *
258
+ * Chame dentro de um clique (ex.: botao "Avisar quando responderem"): o navegador so mostra o
259
+ * pedido de permissao em resposta a um gesto da pessoa. Funciona enquanto a pagina estiver aberta
260
+ * (em outra aba ou minimizada) e com `startPolling()` ligado; com a pagina FECHADA so o push de
261
+ * aplicativo (`registrarPush`) alcanca a pessoa.
262
+ *
263
+ * Devolve a permissao: 'granted' liga o aviso; 'denied'/'default' nao; 'indisponivel' quando o
264
+ * ambiente nao tem a API (app nativo, navegador antigo, iframe sem permissao).
265
+ */
266
+ ativarNotificacaoNoNavegador(opcoes?: NotificacaoNavegadorOptions): Promise<NotificationPermission | 'indisponivel'>;
267
+ /** Desliga o aviso do navegador. */
268
+ desativarNotificacaoNoNavegador(): void;
269
+ /**
270
+ * Avisa que a pessoa esta com o chat na tela (o inbox mostra "online", e a notificacao no celular
271
+ * nao conta como nova o que ela ja viu). O `startPolling()` ja chama sozinho com a pagina
272
+ * visivel; em app nativo, chame enquanto a tela do chat estiver aberta (a cada ~20 s).
273
+ */
274
+ marcarPresenca(): Promise<void>;
122
275
  /** Stop polling */
123
276
  stopPolling(): void;
124
277
  /** Get current messages */
@@ -150,6 +303,16 @@ declare class MenuIAClient {
150
303
  clearSession(): void;
151
304
  /** Cleanup - call when component unmounts */
152
305
  destroy(): void;
306
+ /** Registro guardado ate a 1a mensagem (widget publico). Falhou: fica para a proxima. */
307
+ private registrarPushPendente;
308
+ private enviarRegistroPush;
309
+ private paginaVisivel;
310
+ /** Resposta chegou pelo poll: com a aba escondida e o aviso ligado, mostra uma notificacao. */
311
+ private avisarNoNavegador;
312
+ private fecharAvisoNavegador;
313
+ private ouvirVisibilidade;
314
+ /** Voltou para a aba: o que estava avisado foi visto. */
315
+ private aoMudarVisibilidade;
153
316
  private setStatus;
154
317
  private getSessionKey;
155
318
  private loadSession;
@@ -157,4 +320,4 @@ declare class MenuIAClient {
157
320
  private saveSession;
158
321
  }
159
322
 
160
- export { type ChatMessage, type ChatResponse, type ConnectionStatus, MenuIAClient, type MenuIAConfig, type MessageAttachment, type SendMessageOptions, type StreamEvent, type WidgetSession };
323
+ export { type ChatMessage, type ChatResponse, type ConnectionStatus, type InteractiveButton, type InteractivePayload, MenuIAClient, type MenuIAConfig, type MessageAttachment, type NotificacaoNavegadorOptions, type RegistrarPushOptions, type RegistrarPushResult, type SendMessageOptions, type StreamEvent, type WidgetSession };
package/dist/index.d.ts CHANGED
@@ -26,6 +26,11 @@ interface MenuIAConfig {
26
26
  * ignorado pelo servidor, de proposito: quem garante a identidade e o seu backend.
27
27
  */
28
28
  sessionToken?: string;
29
+ /**
30
+ * Widget privado: o servidor recusou o token de sessao (vencido ou invalido). Busque um token
31
+ * novo no SEU servidor e chame `setSessionToken(novo)` — a conversa continua a mesma.
32
+ */
33
+ onSessionTokenExpired?: () => void;
29
34
  onMessage?: (message: ChatMessage) => void;
30
35
  onStatusChange?: (status: ConnectionStatus) => void;
31
36
  onTicketCreated?: (ticketId: string) => void;
@@ -44,7 +49,71 @@ interface ChatMessage {
44
49
  toolCalls?: string;
45
50
  toolResults?: string;
46
51
  authorName?: string;
52
+ /**
53
+ * Botoes / lista / carrossel desta mensagem (ver `InteractivePayload`).
54
+ * Quando vem preenchido, `content` traz o MESMO conteudo em texto: mostre um OU outro.
55
+ */
56
+ interactive?: InteractivePayload;
57
+ /**
58
+ * O envio desta mensagem FALHOU e ela nao chegou ao servidor.
59
+ *
60
+ * ⚠️ Sem este campo a bolha do usuario ficava na tela identica a uma enviada com sucesso
61
+ * quando o envio falhava — o hook so chamava `setError`, e quem olhava o chat nao tinha como
62
+ * saber que aquela mensagem nunca saiu. O widget proprio desta casa sempre teve `failed` +
63
+ * botao de reenviar; o SDK nao tinha recebido a paridade.
64
+ *
65
+ * Desenhe a bolha com um aviso e um botao que chame `retryMessage(msg)`.
66
+ */
67
+ failed?: boolean;
47
68
  }
69
+ /** Botao de mensagem interativa: com `url` abre um link; sem, e resposta rapida. */
70
+ interface InteractiveButton {
71
+ text: string;
72
+ url?: string;
73
+ id?: string;
74
+ }
75
+ /**
76
+ * Mensagem interativa enviada pela IA: botoes, lista/menu ou carrossel.
77
+ *
78
+ * Como desenhar: botao com `url` abre o link em outra aba; botao sem `url` e item de lista sao
79
+ * RESPOSTA — ao tocar, envie o rotulo (`text` / `title`) como a proxima mensagem do usuario.
80
+ * Quem nao desenha pode mostrar so o `content` da mensagem, que traz as mesmas opcoes em texto.
81
+ *
82
+ * ⚠️ O conteudo vem da IA: so abra `url` e `imageUrl` que comecem com http:// ou https://.
83
+ */
84
+ type InteractivePayload = {
85
+ kind: 'buttons';
86
+ text?: string;
87
+ header?: string;
88
+ footer?: string;
89
+ buttons: InteractiveButton[];
90
+ } | {
91
+ kind: 'list';
92
+ text?: string;
93
+ header?: string;
94
+ list: {
95
+ title?: string;
96
+ footer?: string;
97
+ sections: Array<{
98
+ title?: string;
99
+ rows: Array<{
100
+ title: string;
101
+ description?: string;
102
+ id?: string;
103
+ }>;
104
+ }>;
105
+ };
106
+ } | {
107
+ kind: 'carousel';
108
+ text?: string;
109
+ footer?: string;
110
+ cards: Array<{
111
+ imageUrl?: string;
112
+ body?: string;
113
+ footer?: string;
114
+ buttons?: InteractiveButton[];
115
+ }>;
116
+ };
48
117
  interface SendMessageOptions {
49
118
  content: string;
50
119
  attachments?: MessageAttachment[];
@@ -72,13 +141,51 @@ interface ChatResponse {
72
141
  aiPaused?: boolean;
73
142
  /** Enquanto a IA consulta a equipe: ate quando esperar por uma resposta. */
74
143
  aiCheckingUntil?: string;
144
+ /**
145
+ * Mensagens interativas (botoes / lista / carrossel) que a IA mostrou NESTE turno, em ordem e
146
+ * com o id real. Na tela vem ANTES de `message`. As mesmas voltam no historico (`loadHistory`).
147
+ */
148
+ interactiveMessages?: ChatMessage[];
75
149
  };
76
150
  }
77
151
  interface StreamEvent {
78
152
  type: 'token' | 'thinking' | 'tool_start' | 'tool_done' | 'tool_end' | 'done' | 'error' | 'response';
79
153
  data: unknown;
80
154
  }
155
+ /**
156
+ * Aparelho que recebe notificacao quando a equipe ou a IA responde (`client.registrarPush`).
157
+ *
158
+ * - `fcm`: token do Firebase Cloud Messaging (Android/iOS nativo, ou web com o SDK do Firebase).
159
+ * - `expo`: `ExponentPushToken[...]` do expo-notifications (React Native/Expo).
160
+ *
161
+ * A credencial de envio (conta de servico do Firebase / token do Expo) e do DONO do widget,
162
+ * cadastrada no painel — nunca vai no app.
163
+ */
164
+ interface RegistrarPushOptions {
165
+ tipo: 'fcm' | 'expo';
166
+ token: string;
167
+ /** Opcional, so para o painel saber de onde veio (ex.: 'android', 'ios', 'web'). */
168
+ plataforma?: string;
169
+ }
170
+ interface RegistrarPushResult {
171
+ ok: boolean;
172
+ /**
173
+ * Widget publico sem conversa ainda: o registro fica guardado e sai sozinho logo depois da
174
+ * primeira mensagem (antes disso nao ha resposta para avisar).
175
+ */
176
+ pendente?: boolean;
177
+ erro?: string;
178
+ }
179
+ /** Aviso do NAVEGADOR (Notification API) quando chega resposta com a aba escondida. */
180
+ interface NotificacaoNavegadorOptions {
181
+ /** Titulo do aviso. Padrao: 'Nova mensagem'. */
182
+ titulo?: string;
183
+ /** URL do icone. */
184
+ icone?: string;
185
+ }
81
186
  interface WidgetSession {
187
+ /** Registro de push guardado ate existir conversa (widget publico). */
188
+ pushPendente?: RegistrarPushOptions;
82
189
  sessionId: string;
83
190
  conversationId?: string;
84
191
  ticketId?: string;
@@ -100,6 +207,12 @@ declare class MenuIAClient {
100
207
  private pollInterval;
101
208
  private lastMessageCount;
102
209
  private resolvedAgentId;
210
+ /** Aviso do navegador ligado (ativarNotificacaoNoNavegador) e quantas chegaram com a aba escondida. */
211
+ private notifNavegador;
212
+ private naoVistasNavegador;
213
+ private avisoNavegador;
214
+ private ultimaPresenca;
215
+ private ouvindoVisibilidade;
103
216
  constructor(config: MenuIAConfig);
104
217
  /** Get the effective ID (widgetId preferred, falls back to agentId) */
105
218
  private getWidgetId;
@@ -113,12 +226,52 @@ declare class MenuIAClient {
113
226
  private ensureSession;
114
227
  /** Send a message to the AI agent */
115
228
  sendMessage(options: SendMessageOptions): Promise<ChatResponse>;
229
+ /**
230
+ * Troca o token de sessão do widget privado (o servidor do site emite um novo antes de o anterior
231
+ * vencer). Vale para as próximas chamadas; a conversa continua a mesma.
232
+ */
233
+ setSessionToken(token: string): void;
116
234
  /** Send a message and receive streaming response */
117
235
  sendMessageStream(options: SendMessageOptions, onToken: (token: string, fullText: string) => void): Promise<ChatResponse | null>;
118
236
  /** Load conversation history from server */
119
237
  loadHistory(): Promise<ChatMessage[]>;
120
238
  /** Start polling for new messages (human agent replies) */
121
239
  startPolling(intervalMs?: number): void;
240
+ /**
241
+ * Registra este aparelho para receber notificacao quando a equipe ou a IA responder no chat,
242
+ * mesmo com o app fechado. O envio usa a credencial do DONO do widget (painel > Notificacoes do
243
+ * chat); o app so entrega o token do aparelho.
244
+ *
245
+ * - Widget PRIVADO: vale para a PESSOA (identidade do token de sessao) em todas as conversas dela.
246
+ * - Widget publico: vale para a conversa deste aparelho. Sem conversa ainda, fica guardado e sai
247
+ * sozinho depois da primeira mensagem (`pendente: true`).
248
+ *
249
+ * O mesmo token registrado de novo muda de dono: num aparelho compartilhado, so quem entrou por
250
+ * ultimo recebe. Ao sair da conta, chame `removerPush(token)`.
251
+ */
252
+ registrarPush(opcoes: RegistrarPushOptions): Promise<RegistrarPushResult>;
253
+ /** Desliga a notificacao neste aparelho (ex.: ao sair da conta no app). */
254
+ removerPush(token: string): Promise<RegistrarPushResult>;
255
+ /**
256
+ * Aviso do NAVEGADOR quando chega resposta com a aba escondida (Notification API).
257
+ *
258
+ * Chame dentro de um clique (ex.: botao "Avisar quando responderem"): o navegador so mostra o
259
+ * pedido de permissao em resposta a um gesto da pessoa. Funciona enquanto a pagina estiver aberta
260
+ * (em outra aba ou minimizada) e com `startPolling()` ligado; com a pagina FECHADA so o push de
261
+ * aplicativo (`registrarPush`) alcanca a pessoa.
262
+ *
263
+ * Devolve a permissao: 'granted' liga o aviso; 'denied'/'default' nao; 'indisponivel' quando o
264
+ * ambiente nao tem a API (app nativo, navegador antigo, iframe sem permissao).
265
+ */
266
+ ativarNotificacaoNoNavegador(opcoes?: NotificacaoNavegadorOptions): Promise<NotificationPermission | 'indisponivel'>;
267
+ /** Desliga o aviso do navegador. */
268
+ desativarNotificacaoNoNavegador(): void;
269
+ /**
270
+ * Avisa que a pessoa esta com o chat na tela (o inbox mostra "online", e a notificacao no celular
271
+ * nao conta como nova o que ela ja viu). O `startPolling()` ja chama sozinho com a pagina
272
+ * visivel; em app nativo, chame enquanto a tela do chat estiver aberta (a cada ~20 s).
273
+ */
274
+ marcarPresenca(): Promise<void>;
122
275
  /** Stop polling */
123
276
  stopPolling(): void;
124
277
  /** Get current messages */
@@ -150,6 +303,16 @@ declare class MenuIAClient {
150
303
  clearSession(): void;
151
304
  /** Cleanup - call when component unmounts */
152
305
  destroy(): void;
306
+ /** Registro guardado ate a 1a mensagem (widget publico). Falhou: fica para a proxima. */
307
+ private registrarPushPendente;
308
+ private enviarRegistroPush;
309
+ private paginaVisivel;
310
+ /** Resposta chegou pelo poll: com a aba escondida e o aviso ligado, mostra uma notificacao. */
311
+ private avisarNoNavegador;
312
+ private fecharAvisoNavegador;
313
+ private ouvirVisibilidade;
314
+ /** Voltou para a aba: o que estava avisado foi visto. */
315
+ private aoMudarVisibilidade;
153
316
  private setStatus;
154
317
  private getSessionKey;
155
318
  private loadSession;
@@ -157,4 +320,4 @@ declare class MenuIAClient {
157
320
  private saveSession;
158
321
  }
159
322
 
160
- export { type ChatMessage, type ChatResponse, type ConnectionStatus, MenuIAClient, type MenuIAConfig, type MessageAttachment, type SendMessageOptions, type StreamEvent, type WidgetSession };
323
+ export { type ChatMessage, type ChatResponse, type ConnectionStatus, type InteractiveButton, type InteractivePayload, MenuIAClient, type MenuIAConfig, type MessageAttachment, type NotificacaoNavegadorOptions, type RegistrarPushOptions, type RegistrarPushResult, type SendMessageOptions, type StreamEvent, type WidgetSession };
package/dist/index.js CHANGED
@@ -33,7 +33,20 @@ var MenuIAClient = class {
33
33
  this.pollInterval = null;
34
34
  this.lastMessageCount = 0;
35
35
  this.resolvedAgentId = null;
36
+ /** Aviso do navegador ligado (ativarNotificacaoNoNavegador) e quantas chegaram com a aba escondida. */
37
+ this.notifNavegador = null;
38
+ this.naoVistasNavegador = 0;
39
+ this.avisoNavegador = null;
40
+ this.ultimaPresenca = 0;
41
+ this.ouvindoVisibilidade = false;
36
42
  this._proactivePollInterval = null;
43
+ /** Voltou para a aba: o que estava avisado foi visto. */
44
+ this.aoMudarVisibilidade = () => {
45
+ if (document.visibilityState !== "visible") return;
46
+ this.naoVistasNavegador = 0;
47
+ this.fecharAvisoNavegador();
48
+ void this.marcarPresenca();
49
+ };
37
50
  if (!config.widgetId && !config.agentId) {
38
51
  throw new Error("[MenuIA] widgetId ou agentId e obrigatorio");
39
52
  }
@@ -96,7 +109,9 @@ var MenuIAClient = class {
96
109
  createdAt: m.createdAt,
97
110
  mediaUrl: m.mediaUrl,
98
111
  mediaType: m.mediaType,
99
- authorName: m.authorName
112
+ authorName: m.authorName,
113
+ // Botoes / lista / carrossel: sem repassar, o app so teria a versao em texto (`content`).
114
+ interactive: m.interactive
100
115
  }));
101
116
  this.lastMessageCount = this.session.messages.length;
102
117
  }
@@ -106,6 +121,12 @@ var MenuIAClient = class {
106
121
  } catch {
107
122
  }
108
123
  if (sessaoRecusada) {
124
+ if (sessaoRecusada === 401 && this.config.sessionToken) {
125
+ try {
126
+ this.config.onSessionTokenExpired?.();
127
+ } catch {
128
+ }
129
+ }
109
130
  this.config.onError?.(new Error(
110
131
  sessaoRecusada === 401 ? "Este chat exige autenticacao e o token de sessao nao foi aceito. Peca um token novo ao seu servidor." : `Nao foi possivel abrir a sessao do chat (HTTP ${sessaoRecusada}).`
111
132
  ));
@@ -128,6 +149,9 @@ var MenuIAClient = class {
128
149
  channel: this.config.channel,
129
150
  sessionId: this.session.sessionId,
130
151
  metadata: {
152
+ // Widget PRIVADO: o token prova QUEM escreve em cada mensagem (as ferramentas de conta do
153
+ // cliente dependem disso). Quem já manda o próprio `metadata.widgetSession` continua mandando.
154
+ ...this.config.sessionToken ? { widgetSession: this.config.sessionToken } : {},
131
155
  ...this.config.metadata,
132
156
  widgetId: this.getWidgetId(),
133
157
  customData: this.config.customFields
@@ -172,6 +196,7 @@ var MenuIAClient = class {
172
196
  this.saveSession();
173
197
  this.setStatus("connected");
174
198
  this.config.onMessage?.(assistantMsg);
199
+ void this.registrarPushPendente();
175
200
  return data;
176
201
  } catch (error) {
177
202
  this.setStatus("error");
@@ -180,6 +205,13 @@ var MenuIAClient = class {
180
205
  throw err;
181
206
  }
182
207
  }
208
+ /**
209
+ * Troca o token de sessão do widget privado (o servidor do site emite um novo antes de o anterior
210
+ * vencer). Vale para as próximas chamadas; a conversa continua a mesma.
211
+ */
212
+ setSessionToken(token) {
213
+ if (typeof token === "string" && token.length > 20 && token.length < 4096) this.config.sessionToken = token;
214
+ }
183
215
  /** Send a message and receive streaming response */
184
216
  async sendMessageStream(options, onToken) {
185
217
  this.setStatus("connecting");
@@ -191,6 +223,9 @@ var MenuIAClient = class {
191
223
  channel: this.config.channel,
192
224
  sessionId: this.session.sessionId,
193
225
  metadata: {
226
+ // Widget PRIVADO: o token prova QUEM escreve em cada mensagem (as ferramentas de conta do
227
+ // cliente dependem disso). Quem já manda o próprio `metadata.widgetSession` continua mandando.
228
+ ...this.config.sessionToken ? { widgetSession: this.config.sessionToken } : {},
194
229
  ...this.config.metadata,
195
230
  widgetId: this.getWidgetId(),
196
231
  customData: this.config.customFields
@@ -268,6 +303,7 @@ var MenuIAClient = class {
268
303
  this.session.messages.push(assistantMsg);
269
304
  this.saveSession();
270
305
  this.config.onMessage?.(assistantMsg);
306
+ void this.registrarPushPendente();
271
307
  return responseData;
272
308
  } catch (error) {
273
309
  this.setStatus("error");
@@ -299,7 +335,8 @@ var MenuIAClient = class {
299
335
  // ⚠️ O endpoint devolve `mediaName` e o mapeamento o descartava: anexo recarregado do
300
336
  // historico aparecia sem o nome do arquivo, mesmo com o nome gravado no banco.
301
337
  mediaName: m.mediaName,
302
- authorName: m.authorName
338
+ authorName: m.authorName,
339
+ interactive: m.interactive
303
340
  }));
304
341
  if (messages.length) {
305
342
  this.session.messages = messages;
@@ -322,12 +359,104 @@ var MenuIAClient = class {
322
359
  for (const msg of newMessages) {
323
360
  if (msg.role === "assistant") {
324
361
  this.config.onMessage?.(msg);
362
+ this.avisarNoNavegador(msg);
325
363
  }
326
364
  }
327
365
  this.lastMessageCount = messages.length;
328
366
  }
367
+ if (this.paginaVisivel()) void this.marcarPresenca();
329
368
  }, intervalMs);
330
369
  }
370
+ // =====================
371
+ // NOTIFICACOES
372
+ // =====================
373
+ /**
374
+ * Registra este aparelho para receber notificacao quando a equipe ou a IA responder no chat,
375
+ * mesmo com o app fechado. O envio usa a credencial do DONO do widget (painel > Notificacoes do
376
+ * chat); o app so entrega o token do aparelho.
377
+ *
378
+ * - Widget PRIVADO: vale para a PESSOA (identidade do token de sessao) em todas as conversas dela.
379
+ * - Widget publico: vale para a conversa deste aparelho. Sem conversa ainda, fica guardado e sai
380
+ * sozinho depois da primeira mensagem (`pendente: true`).
381
+ *
382
+ * O mesmo token registrado de novo muda de dono: num aparelho compartilhado, so quem entrou por
383
+ * ultimo recebe. Ao sair da conta, chame `removerPush(token)`.
384
+ */
385
+ async registrarPush(opcoes) {
386
+ if (!this.config.widgetId) throw new Error("[MenuIA] registrarPush exige widgetId");
387
+ const tipo = String(opcoes?.tipo || "").toLowerCase();
388
+ const token = String(opcoes?.token || "").trim();
389
+ if (!token) throw new Error("[MenuIA] registrarPush: informe o token do aparelho");
390
+ if (tipo !== "fcm" && tipo !== "expo") throw new Error("[MenuIA] registrarPush: tipo deve ser 'fcm' ou 'expo'");
391
+ const pedido = { tipo, token, ...opcoes.plataforma ? { plataforma: opcoes.plataforma } : {} };
392
+ await this.ensureSession();
393
+ if (!this.config.sessionToken && !this.session.conversationId) {
394
+ this.session.pushPendente = pedido;
395
+ this.saveSession();
396
+ return { ok: true, pendente: true };
397
+ }
398
+ return this.enviarRegistroPush("push", pedido);
399
+ }
400
+ /** Desliga a notificacao neste aparelho (ex.: ao sair da conta no app). */
401
+ async removerPush(token) {
402
+ if (!this.config.widgetId) throw new Error("[MenuIA] removerPush exige widgetId");
403
+ if (this.session.pushPendente?.token === token) {
404
+ delete this.session.pushPendente;
405
+ this.saveSession();
406
+ }
407
+ if (!this.config.sessionToken && !this.session.conversationId) return { ok: true };
408
+ return this.enviarRegistroPush("push/remove", { token });
409
+ }
410
+ /**
411
+ * Aviso do NAVEGADOR quando chega resposta com a aba escondida (Notification API).
412
+ *
413
+ * Chame dentro de um clique (ex.: botao "Avisar quando responderem"): o navegador so mostra o
414
+ * pedido de permissao em resposta a um gesto da pessoa. Funciona enquanto a pagina estiver aberta
415
+ * (em outra aba ou minimizada) e com `startPolling()` ligado; com a pagina FECHADA so o push de
416
+ * aplicativo (`registrarPush`) alcanca a pessoa.
417
+ *
418
+ * Devolve a permissao: 'granted' liga o aviso; 'denied'/'default' nao; 'indisponivel' quando o
419
+ * ambiente nao tem a API (app nativo, navegador antigo, iframe sem permissao).
420
+ */
421
+ async ativarNotificacaoNoNavegador(opcoes = {}) {
422
+ const N = globalThis.Notification;
423
+ if (typeof window === "undefined" || !N) return "indisponivel";
424
+ let permissao = N.permission;
425
+ if (permissao === "default") {
426
+ try {
427
+ permissao = await N.requestPermission();
428
+ } catch {
429
+ return "indisponivel";
430
+ }
431
+ }
432
+ this.notifNavegador = permissao === "granted" ? { ...opcoes } : null;
433
+ if (this.notifNavegador) this.ouvirVisibilidade();
434
+ return permissao;
435
+ }
436
+ /** Desliga o aviso do navegador. */
437
+ desativarNotificacaoNoNavegador() {
438
+ this.notifNavegador = null;
439
+ this.fecharAvisoNavegador();
440
+ }
441
+ /**
442
+ * Avisa que a pessoa esta com o chat na tela (o inbox mostra "online", e a notificacao no celular
443
+ * nao conta como nova o que ela ja viu). O `startPolling()` ja chama sozinho com a pagina
444
+ * visivel; em app nativo, chame enquanto a tela do chat estiver aberta (a cada ~20 s).
445
+ */
446
+ async marcarPresenca() {
447
+ const conversationId = this.session.conversationId;
448
+ if (!conversationId) return;
449
+ if (Date.now() - this.ultimaPresenca < 15e3) return;
450
+ this.ultimaPresenca = Date.now();
451
+ try {
452
+ await fetch(`${this.config.apiUrl}/widget/heartbeat`, {
453
+ method: "POST",
454
+ headers: { "Content-Type": "application/json" },
455
+ body: JSON.stringify({ conversationId })
456
+ });
457
+ } catch {
458
+ }
459
+ }
331
460
  /** Stop polling */
332
461
  stopPolling() {
333
462
  if (this.pollInterval) {
@@ -376,7 +505,8 @@ var MenuIAClient = class {
376
505
  createdAt: m.createdAt,
377
506
  authorName: m.authorName,
378
507
  mediaType: m.mediaType,
379
- mediaUrl: m.mediaUrl
508
+ mediaUrl: m.mediaUrl,
509
+ interactive: m.interactive
380
510
  }));
381
511
  this.lastMessageCount = this.session.messages.length;
382
512
  this.saveSession();
@@ -421,10 +551,88 @@ var MenuIAClient = class {
421
551
  destroy() {
422
552
  this.stopPolling();
423
553
  this.stopProactivePolling();
554
+ this.fecharAvisoNavegador();
555
+ if (this.ouvindoVisibilidade && typeof document !== "undefined") {
556
+ document.removeEventListener("visibilitychange", this.aoMudarVisibilidade);
557
+ this.ouvindoVisibilidade = false;
558
+ }
424
559
  }
425
560
  // =====================
426
561
  // PRIVATE
427
562
  // =====================
563
+ /** Registro guardado ate a 1a mensagem (widget publico). Falhou: fica para a proxima. */
564
+ async registrarPushPendente() {
565
+ const p = this.session.pushPendente;
566
+ if (!p || !this.session.conversationId) return;
567
+ const r = await this.enviarRegistroPush("push", p);
568
+ if (r.ok) {
569
+ delete this.session.pushPendente;
570
+ this.saveSession();
571
+ }
572
+ }
573
+ async enviarRegistroPush(rota, pedido) {
574
+ try {
575
+ const response = await fetch(`${this.config.apiUrl}/widget/${this.config.widgetId}/${rota}`, {
576
+ method: "POST",
577
+ headers: {
578
+ "Content-Type": "application/json",
579
+ // Widget privado: quem diz QUEM e o token assinado pelo servidor do site, no header.
580
+ ...this.config.sessionToken ? { "x-widget-session": this.config.sessionToken } : {}
581
+ },
582
+ // Widget publico: a prova e a da propria conversa (sessionId e o token que a sessao devolveu).
583
+ body: JSON.stringify({
584
+ ...pedido,
585
+ sessionId: this.session.sessionId,
586
+ ...this.session.widgetToken ? { widgetToken: this.session.widgetToken } : {}
587
+ })
588
+ });
589
+ if (response.ok) return { ok: true };
590
+ const err = await response.json().catch(() => ({}));
591
+ const erro = String(err?.message || `HTTP ${response.status}`);
592
+ this.config.onError?.(new Error(`[MenuIA] notificacao: ${erro}`));
593
+ return { ok: false, erro };
594
+ } catch (e) {
595
+ return { ok: false, erro: e instanceof Error ? e.message : String(e) };
596
+ }
597
+ }
598
+ paginaVisivel() {
599
+ return typeof document !== "undefined" && document.visibilityState === "visible";
600
+ }
601
+ /** Resposta chegou pelo poll: com a aba escondida e o aviso ligado, mostra uma notificacao. */
602
+ avisarNoNavegador(msg) {
603
+ const N = globalThis.Notification;
604
+ if (!this.notifNavegador || !N || N.permission !== "granted") return;
605
+ if (typeof document === "undefined" || document.visibilityState !== "hidden") return;
606
+ this.naoVistasNavegador += 1;
607
+ const n = this.naoVistasNavegador;
608
+ const base = this.notifNavegador.titulo || "Nova mensagem";
609
+ const titulo = n > 1 ? `${base} \u2014 ${n} mensagens novas` : base;
610
+ try {
611
+ this.fecharAvisoNavegador();
612
+ const aviso = new N(titulo, { body: previaDaMensagem(msg), tag: `menuia-chat-${this.getWidgetId()}`, icon: this.notifNavegador.icone });
613
+ aviso.onclick = () => {
614
+ try {
615
+ window.focus();
616
+ } catch {
617
+ }
618
+ aviso.close();
619
+ };
620
+ this.avisoNavegador = aviso;
621
+ } catch {
622
+ }
623
+ }
624
+ fecharAvisoNavegador() {
625
+ try {
626
+ this.avisoNavegador?.close();
627
+ } catch {
628
+ }
629
+ this.avisoNavegador = null;
630
+ }
631
+ ouvirVisibilidade() {
632
+ if (this.ouvindoVisibilidade || typeof document === "undefined") return;
633
+ document.addEventListener("visibilitychange", this.aoMudarVisibilidade);
634
+ this.ouvindoVisibilidade = true;
635
+ }
428
636
  setStatus(status) {
429
637
  if (this.status !== status) {
430
638
  this.status = status;
@@ -473,6 +681,19 @@ var MenuIAClient = class {
473
681
  }
474
682
  }
475
683
  };
684
+ function previaDaMensagem(msg) {
685
+ let t = String(msg.content || "").trim();
686
+ if (!t) {
687
+ const tipo = String(msg.mediaType || "").toLowerCase();
688
+ if (tipo.includes("image")) return "Imagem";
689
+ if (tipo.includes("audio")) return "Audio";
690
+ if (tipo.includes("video")) return "Video";
691
+ return msg.mediaUrl ? "Arquivo" : "Mensagem nova";
692
+ }
693
+ if (t.startsWith("[INTERACTIVE]")) return "Opcoes para escolher no chat";
694
+ t = t.replace(/\[(?:BUTTON|BOTAO|BTN):([^:\]]+):[^\]]*\]/gi, "$1").replace(/[*_~`]+/g, "").replace(/https?:\/\/\S+/g, "link").replace(/\s+/g, " ").trim();
695
+ return t.length > 120 ? `${t.slice(0, 119).trimEnd()}\u2026` : t || "Mensagem nova";
696
+ }
476
697
  // Annotate the CommonJS export names for ESM import in node:
477
698
  0 && (module.exports = {
478
699
  MenuIAClient
package/dist/index.mjs CHANGED
@@ -7,7 +7,20 @@ var MenuIAClient = class {
7
7
  this.pollInterval = null;
8
8
  this.lastMessageCount = 0;
9
9
  this.resolvedAgentId = null;
10
+ /** Aviso do navegador ligado (ativarNotificacaoNoNavegador) e quantas chegaram com a aba escondida. */
11
+ this.notifNavegador = null;
12
+ this.naoVistasNavegador = 0;
13
+ this.avisoNavegador = null;
14
+ this.ultimaPresenca = 0;
15
+ this.ouvindoVisibilidade = false;
10
16
  this._proactivePollInterval = null;
17
+ /** Voltou para a aba: o que estava avisado foi visto. */
18
+ this.aoMudarVisibilidade = () => {
19
+ if (document.visibilityState !== "visible") return;
20
+ this.naoVistasNavegador = 0;
21
+ this.fecharAvisoNavegador();
22
+ void this.marcarPresenca();
23
+ };
11
24
  if (!config.widgetId && !config.agentId) {
12
25
  throw new Error("[MenuIA] widgetId ou agentId e obrigatorio");
13
26
  }
@@ -70,7 +83,9 @@ var MenuIAClient = class {
70
83
  createdAt: m.createdAt,
71
84
  mediaUrl: m.mediaUrl,
72
85
  mediaType: m.mediaType,
73
- authorName: m.authorName
86
+ authorName: m.authorName,
87
+ // Botoes / lista / carrossel: sem repassar, o app so teria a versao em texto (`content`).
88
+ interactive: m.interactive
74
89
  }));
75
90
  this.lastMessageCount = this.session.messages.length;
76
91
  }
@@ -80,6 +95,12 @@ var MenuIAClient = class {
80
95
  } catch {
81
96
  }
82
97
  if (sessaoRecusada) {
98
+ if (sessaoRecusada === 401 && this.config.sessionToken) {
99
+ try {
100
+ this.config.onSessionTokenExpired?.();
101
+ } catch {
102
+ }
103
+ }
83
104
  this.config.onError?.(new Error(
84
105
  sessaoRecusada === 401 ? "Este chat exige autenticacao e o token de sessao nao foi aceito. Peca um token novo ao seu servidor." : `Nao foi possivel abrir a sessao do chat (HTTP ${sessaoRecusada}).`
85
106
  ));
@@ -102,6 +123,9 @@ var MenuIAClient = class {
102
123
  channel: this.config.channel,
103
124
  sessionId: this.session.sessionId,
104
125
  metadata: {
126
+ // Widget PRIVADO: o token prova QUEM escreve em cada mensagem (as ferramentas de conta do
127
+ // cliente dependem disso). Quem já manda o próprio `metadata.widgetSession` continua mandando.
128
+ ...this.config.sessionToken ? { widgetSession: this.config.sessionToken } : {},
105
129
  ...this.config.metadata,
106
130
  widgetId: this.getWidgetId(),
107
131
  customData: this.config.customFields
@@ -146,6 +170,7 @@ var MenuIAClient = class {
146
170
  this.saveSession();
147
171
  this.setStatus("connected");
148
172
  this.config.onMessage?.(assistantMsg);
173
+ void this.registrarPushPendente();
149
174
  return data;
150
175
  } catch (error) {
151
176
  this.setStatus("error");
@@ -154,6 +179,13 @@ var MenuIAClient = class {
154
179
  throw err;
155
180
  }
156
181
  }
182
+ /**
183
+ * Troca o token de sessão do widget privado (o servidor do site emite um novo antes de o anterior
184
+ * vencer). Vale para as próximas chamadas; a conversa continua a mesma.
185
+ */
186
+ setSessionToken(token) {
187
+ if (typeof token === "string" && token.length > 20 && token.length < 4096) this.config.sessionToken = token;
188
+ }
157
189
  /** Send a message and receive streaming response */
158
190
  async sendMessageStream(options, onToken) {
159
191
  this.setStatus("connecting");
@@ -165,6 +197,9 @@ var MenuIAClient = class {
165
197
  channel: this.config.channel,
166
198
  sessionId: this.session.sessionId,
167
199
  metadata: {
200
+ // Widget PRIVADO: o token prova QUEM escreve em cada mensagem (as ferramentas de conta do
201
+ // cliente dependem disso). Quem já manda o próprio `metadata.widgetSession` continua mandando.
202
+ ...this.config.sessionToken ? { widgetSession: this.config.sessionToken } : {},
168
203
  ...this.config.metadata,
169
204
  widgetId: this.getWidgetId(),
170
205
  customData: this.config.customFields
@@ -242,6 +277,7 @@ var MenuIAClient = class {
242
277
  this.session.messages.push(assistantMsg);
243
278
  this.saveSession();
244
279
  this.config.onMessage?.(assistantMsg);
280
+ void this.registrarPushPendente();
245
281
  return responseData;
246
282
  } catch (error) {
247
283
  this.setStatus("error");
@@ -273,7 +309,8 @@ var MenuIAClient = class {
273
309
  // ⚠️ O endpoint devolve `mediaName` e o mapeamento o descartava: anexo recarregado do
274
310
  // historico aparecia sem o nome do arquivo, mesmo com o nome gravado no banco.
275
311
  mediaName: m.mediaName,
276
- authorName: m.authorName
312
+ authorName: m.authorName,
313
+ interactive: m.interactive
277
314
  }));
278
315
  if (messages.length) {
279
316
  this.session.messages = messages;
@@ -296,12 +333,104 @@ var MenuIAClient = class {
296
333
  for (const msg of newMessages) {
297
334
  if (msg.role === "assistant") {
298
335
  this.config.onMessage?.(msg);
336
+ this.avisarNoNavegador(msg);
299
337
  }
300
338
  }
301
339
  this.lastMessageCount = messages.length;
302
340
  }
341
+ if (this.paginaVisivel()) void this.marcarPresenca();
303
342
  }, intervalMs);
304
343
  }
344
+ // =====================
345
+ // NOTIFICACOES
346
+ // =====================
347
+ /**
348
+ * Registra este aparelho para receber notificacao quando a equipe ou a IA responder no chat,
349
+ * mesmo com o app fechado. O envio usa a credencial do DONO do widget (painel > Notificacoes do
350
+ * chat); o app so entrega o token do aparelho.
351
+ *
352
+ * - Widget PRIVADO: vale para a PESSOA (identidade do token de sessao) em todas as conversas dela.
353
+ * - Widget publico: vale para a conversa deste aparelho. Sem conversa ainda, fica guardado e sai
354
+ * sozinho depois da primeira mensagem (`pendente: true`).
355
+ *
356
+ * O mesmo token registrado de novo muda de dono: num aparelho compartilhado, so quem entrou por
357
+ * ultimo recebe. Ao sair da conta, chame `removerPush(token)`.
358
+ */
359
+ async registrarPush(opcoes) {
360
+ if (!this.config.widgetId) throw new Error("[MenuIA] registrarPush exige widgetId");
361
+ const tipo = String(opcoes?.tipo || "").toLowerCase();
362
+ const token = String(opcoes?.token || "").trim();
363
+ if (!token) throw new Error("[MenuIA] registrarPush: informe o token do aparelho");
364
+ if (tipo !== "fcm" && tipo !== "expo") throw new Error("[MenuIA] registrarPush: tipo deve ser 'fcm' ou 'expo'");
365
+ const pedido = { tipo, token, ...opcoes.plataforma ? { plataforma: opcoes.plataforma } : {} };
366
+ await this.ensureSession();
367
+ if (!this.config.sessionToken && !this.session.conversationId) {
368
+ this.session.pushPendente = pedido;
369
+ this.saveSession();
370
+ return { ok: true, pendente: true };
371
+ }
372
+ return this.enviarRegistroPush("push", pedido);
373
+ }
374
+ /** Desliga a notificacao neste aparelho (ex.: ao sair da conta no app). */
375
+ async removerPush(token) {
376
+ if (!this.config.widgetId) throw new Error("[MenuIA] removerPush exige widgetId");
377
+ if (this.session.pushPendente?.token === token) {
378
+ delete this.session.pushPendente;
379
+ this.saveSession();
380
+ }
381
+ if (!this.config.sessionToken && !this.session.conversationId) return { ok: true };
382
+ return this.enviarRegistroPush("push/remove", { token });
383
+ }
384
+ /**
385
+ * Aviso do NAVEGADOR quando chega resposta com a aba escondida (Notification API).
386
+ *
387
+ * Chame dentro de um clique (ex.: botao "Avisar quando responderem"): o navegador so mostra o
388
+ * pedido de permissao em resposta a um gesto da pessoa. Funciona enquanto a pagina estiver aberta
389
+ * (em outra aba ou minimizada) e com `startPolling()` ligado; com a pagina FECHADA so o push de
390
+ * aplicativo (`registrarPush`) alcanca a pessoa.
391
+ *
392
+ * Devolve a permissao: 'granted' liga o aviso; 'denied'/'default' nao; 'indisponivel' quando o
393
+ * ambiente nao tem a API (app nativo, navegador antigo, iframe sem permissao).
394
+ */
395
+ async ativarNotificacaoNoNavegador(opcoes = {}) {
396
+ const N = globalThis.Notification;
397
+ if (typeof window === "undefined" || !N) return "indisponivel";
398
+ let permissao = N.permission;
399
+ if (permissao === "default") {
400
+ try {
401
+ permissao = await N.requestPermission();
402
+ } catch {
403
+ return "indisponivel";
404
+ }
405
+ }
406
+ this.notifNavegador = permissao === "granted" ? { ...opcoes } : null;
407
+ if (this.notifNavegador) this.ouvirVisibilidade();
408
+ return permissao;
409
+ }
410
+ /** Desliga o aviso do navegador. */
411
+ desativarNotificacaoNoNavegador() {
412
+ this.notifNavegador = null;
413
+ this.fecharAvisoNavegador();
414
+ }
415
+ /**
416
+ * Avisa que a pessoa esta com o chat na tela (o inbox mostra "online", e a notificacao no celular
417
+ * nao conta como nova o que ela ja viu). O `startPolling()` ja chama sozinho com a pagina
418
+ * visivel; em app nativo, chame enquanto a tela do chat estiver aberta (a cada ~20 s).
419
+ */
420
+ async marcarPresenca() {
421
+ const conversationId = this.session.conversationId;
422
+ if (!conversationId) return;
423
+ if (Date.now() - this.ultimaPresenca < 15e3) return;
424
+ this.ultimaPresenca = Date.now();
425
+ try {
426
+ await fetch(`${this.config.apiUrl}/widget/heartbeat`, {
427
+ method: "POST",
428
+ headers: { "Content-Type": "application/json" },
429
+ body: JSON.stringify({ conversationId })
430
+ });
431
+ } catch {
432
+ }
433
+ }
305
434
  /** Stop polling */
306
435
  stopPolling() {
307
436
  if (this.pollInterval) {
@@ -350,7 +479,8 @@ var MenuIAClient = class {
350
479
  createdAt: m.createdAt,
351
480
  authorName: m.authorName,
352
481
  mediaType: m.mediaType,
353
- mediaUrl: m.mediaUrl
482
+ mediaUrl: m.mediaUrl,
483
+ interactive: m.interactive
354
484
  }));
355
485
  this.lastMessageCount = this.session.messages.length;
356
486
  this.saveSession();
@@ -395,10 +525,88 @@ var MenuIAClient = class {
395
525
  destroy() {
396
526
  this.stopPolling();
397
527
  this.stopProactivePolling();
528
+ this.fecharAvisoNavegador();
529
+ if (this.ouvindoVisibilidade && typeof document !== "undefined") {
530
+ document.removeEventListener("visibilitychange", this.aoMudarVisibilidade);
531
+ this.ouvindoVisibilidade = false;
532
+ }
398
533
  }
399
534
  // =====================
400
535
  // PRIVATE
401
536
  // =====================
537
+ /** Registro guardado ate a 1a mensagem (widget publico). Falhou: fica para a proxima. */
538
+ async registrarPushPendente() {
539
+ const p = this.session.pushPendente;
540
+ if (!p || !this.session.conversationId) return;
541
+ const r = await this.enviarRegistroPush("push", p);
542
+ if (r.ok) {
543
+ delete this.session.pushPendente;
544
+ this.saveSession();
545
+ }
546
+ }
547
+ async enviarRegistroPush(rota, pedido) {
548
+ try {
549
+ const response = await fetch(`${this.config.apiUrl}/widget/${this.config.widgetId}/${rota}`, {
550
+ method: "POST",
551
+ headers: {
552
+ "Content-Type": "application/json",
553
+ // Widget privado: quem diz QUEM e o token assinado pelo servidor do site, no header.
554
+ ...this.config.sessionToken ? { "x-widget-session": this.config.sessionToken } : {}
555
+ },
556
+ // Widget publico: a prova e a da propria conversa (sessionId e o token que a sessao devolveu).
557
+ body: JSON.stringify({
558
+ ...pedido,
559
+ sessionId: this.session.sessionId,
560
+ ...this.session.widgetToken ? { widgetToken: this.session.widgetToken } : {}
561
+ })
562
+ });
563
+ if (response.ok) return { ok: true };
564
+ const err = await response.json().catch(() => ({}));
565
+ const erro = String(err?.message || `HTTP ${response.status}`);
566
+ this.config.onError?.(new Error(`[MenuIA] notificacao: ${erro}`));
567
+ return { ok: false, erro };
568
+ } catch (e) {
569
+ return { ok: false, erro: e instanceof Error ? e.message : String(e) };
570
+ }
571
+ }
572
+ paginaVisivel() {
573
+ return typeof document !== "undefined" && document.visibilityState === "visible";
574
+ }
575
+ /** Resposta chegou pelo poll: com a aba escondida e o aviso ligado, mostra uma notificacao. */
576
+ avisarNoNavegador(msg) {
577
+ const N = globalThis.Notification;
578
+ if (!this.notifNavegador || !N || N.permission !== "granted") return;
579
+ if (typeof document === "undefined" || document.visibilityState !== "hidden") return;
580
+ this.naoVistasNavegador += 1;
581
+ const n = this.naoVistasNavegador;
582
+ const base = this.notifNavegador.titulo || "Nova mensagem";
583
+ const titulo = n > 1 ? `${base} \u2014 ${n} mensagens novas` : base;
584
+ try {
585
+ this.fecharAvisoNavegador();
586
+ const aviso = new N(titulo, { body: previaDaMensagem(msg), tag: `menuia-chat-${this.getWidgetId()}`, icon: this.notifNavegador.icone });
587
+ aviso.onclick = () => {
588
+ try {
589
+ window.focus();
590
+ } catch {
591
+ }
592
+ aviso.close();
593
+ };
594
+ this.avisoNavegador = aviso;
595
+ } catch {
596
+ }
597
+ }
598
+ fecharAvisoNavegador() {
599
+ try {
600
+ this.avisoNavegador?.close();
601
+ } catch {
602
+ }
603
+ this.avisoNavegador = null;
604
+ }
605
+ ouvirVisibilidade() {
606
+ if (this.ouvindoVisibilidade || typeof document === "undefined") return;
607
+ document.addEventListener("visibilitychange", this.aoMudarVisibilidade);
608
+ this.ouvindoVisibilidade = true;
609
+ }
402
610
  setStatus(status) {
403
611
  if (this.status !== status) {
404
612
  this.status = status;
@@ -447,6 +655,19 @@ var MenuIAClient = class {
447
655
  }
448
656
  }
449
657
  };
658
+ function previaDaMensagem(msg) {
659
+ let t = String(msg.content || "").trim();
660
+ if (!t) {
661
+ const tipo = String(msg.mediaType || "").toLowerCase();
662
+ if (tipo.includes("image")) return "Imagem";
663
+ if (tipo.includes("audio")) return "Audio";
664
+ if (tipo.includes("video")) return "Video";
665
+ return msg.mediaUrl ? "Arquivo" : "Mensagem nova";
666
+ }
667
+ if (t.startsWith("[INTERACTIVE]")) return "Opcoes para escolher no chat";
668
+ t = t.replace(/\[(?:BUTTON|BOTAO|BTN):([^:\]]+):[^\]]*\]/gi, "$1").replace(/[*_~`]+/g, "").replace(/https?:\/\/\S+/g, "link").replace(/\s+/g, " ").trim();
669
+ return t.length > 120 ? `${t.slice(0, 119).trimEnd()}\u2026` : t || "Mensagem nova";
670
+ }
450
671
  export {
451
672
  MenuIAClient
452
673
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@menuia/core",
3
- "version": "1.5.2",
3
+ "version": "1.7.1",
4
4
  "description": "MenuIA Chat SDK - Core",
5
5
  "main": "dist/index.js",
6
6
  "module": "dist/index.mjs",