@mundogamernetwork/shared-ui 1.18.1 → 1.18.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/README.md CHANGED
@@ -51,6 +51,7 @@ Todas filtram por `systemId` (platform_id) e compartilham a mesma estrutura visu
51
51
  ### Plugins
52
52
  - **echo.client** - Laravel Echo / Pusher com auto-reconnect
53
53
  - **auth.client** - Auto-fetch do usuário ao montar o app
54
+ - **presence.client** - Heartbeat de presença (desligado por padrão, ver "Presença")
54
55
 
55
56
  ### Middleware
56
57
  - **auth.global** - Proteção de rotas configurável via `protectedRoutes`
@@ -198,6 +199,30 @@ Também pode ser usado direto: `<MgWhatsNewModal :suppress="meuModalAberto" :blo
198
199
  - Preview do admin: rota `/whats-new-preview` (noindex). O pai (iframe) envia `postMessage({ type: "mg-whats-new-preview", payload, theme?, lang? })` e recebe `{ type: "mg-whats-new-preview-ready" }`. Para QA: `/whats-new-preview?demo=image|video|embed|text&lang=pt-BR&theme=dark`.
199
200
  - Testes: `yarn test` (vitest via npx) cobre markup seguro, rotas bloqueadas, elegibilidade, embeds e idiomas.
200
201
 
202
+ ### Presença (quem está online / quem sumiu)
203
+
204
+ O plugin `presence.client` avisa a API, a cada ~2 minutos e só com a aba visível, que o usuário logado está ativo na plataforma. O network-admin usa isso para mostrar "Online" e "Última atividade" na lista de usuários e para os fluxos de reativação.
205
+
206
+ **Desligado por padrão.** Ligue por front, só depois que a API desse front estiver rodando a versão do api-main que guarda o heartbeat no Redis (antes disso cada ping vira uma escrita no Postgres):
207
+
208
+ ```ts
209
+ // nuxt.config.ts do app
210
+ runtimeConfig: {
211
+ public: {
212
+ mgSharedUi: {
213
+ systemId: '1', // id da plataforma em mg_network_systems (VITE_SYSTEM_ID)
214
+ presence: { enabled: true, intervalSeconds: 120 } // nunca abaixo de 60
215
+ }
216
+ }
217
+ }
218
+ ```
219
+
220
+ ou por ambiente, sem mexer no código: `NUXT_PUBLIC_MG_SHARED_UI_PRESENCE_ENABLED=true`.
221
+
222
+ - Chama `POST /public/user-status/heartbeat` com `{ platform_id }`. Sem `systemId` numérico, o plugin não faz nada.
223
+ - Acompanha o login pelo store `auth-store`, então funciona também nos apps que têm cópia própria do store (academy, agency) com o mesmo id.
224
+ - Para ao receber 401/403 e volta no próximo login; falhas de rede ou 5xx são ignoradas.
225
+
201
226
  ## Sobrescrita (Override)
202
227
 
203
228
  Por ser um Nuxt Layer, qualquer arquivo pode ser sobrescrito no app consumidor. Basta criar o arquivo com o mesmo caminho:
package/nuxt.config.ts CHANGED
@@ -157,6 +157,13 @@ export default defineNuxtConfig({
157
157
  // with no gamification data for its users can set this to false.
158
158
  gamification: true,
159
159
  },
160
+ // Presence: pings the API every couple of minutes while a signed-in user has a tab open, so the admin can
161
+ // show who is online and who stopped coming back. Off until a front opts in (the front's API must run the
162
+ // api-main version that buffers the heartbeat). Env: NUXT_PUBLIC_MG_SHARED_UI_PRESENCE_ENABLED=true.
163
+ presence: {
164
+ enabled: false,
165
+ intervalSeconds: 120, // never below 60
166
+ },
160
167
  // "Novidades da Rede" modal, mounted by <MgBanners />. Routes are path
161
168
  // prefixes (locale prefix ignored); allowedRoutes empty = any logged-in
162
169
  // route that is not blocked. blockedRoutes add to the built-in list
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mundogamernetwork/shared-ui",
3
- "version": "1.18.1",
3
+ "version": "1.18.2",
4
4
  "description": "Mundo Gamer Network - Shared UI Layer (Nuxt 3)",
5
5
  "type": "module",
6
6
  "main": "./nuxt.config.ts",
@@ -0,0 +1,50 @@
1
+ import { createPresenceHeartbeat } from "../utils/presenceHeartbeat";
2
+ import httpService from "../services/httpService";
3
+
4
+ /**
5
+ * Presence: tells the API this user is active on this platform, so the admin can see who is online and who stopped coming
6
+ * back (api-main: POST /public/user-status/heartbeat, buffered in Redis and flushed to Postgres in batches).
7
+ *
8
+ * Off by default. Turn it on per front with `runtimeConfig.public.mgSharedUi.presence.enabled`, or the env var
9
+ * NUXT_PUBLIC_MG_SHARED_UI_PRESENCE_ENABLED=true, once that front's API runs the version of api-main that buffers the
10
+ * heartbeat. The platform is mgSharedUi.systemId (VITE_SYSTEM_ID), the same id the user-status toggle already uses.
11
+ *
12
+ * It follows the persisted auth store by its id ("auth-store") instead of importing the store: a few fronts (academy, agency)
13
+ * keep their own copy of the store, with the same id, and this works with either.
14
+ */
15
+ export default defineNuxtPlugin({
16
+ name: "shared-ui-presence",
17
+ setup(nuxtApp) {
18
+ try {
19
+ const config = (useRuntimeConfig().public as any).mgSharedUi ?? {};
20
+ const presence = config.presence ?? {};
21
+ if (!presence.enabled) return;
22
+
23
+ const platformId = Number(config.systemId || import.meta.env.VITE_SYSTEM_ID);
24
+ if (!Number.isInteger(platformId) || platformId <= 0) return;
25
+
26
+ const pinia = (nuxtApp as any).$pinia;
27
+ if (!pinia) return;
28
+
29
+ // Never faster than once a minute, whatever a front configures: the API treats ~5 minutes as online.
30
+ const intervalMs = Math.max(60, Number(presence.intervalSeconds) || 120) * 1000;
31
+
32
+ const heartbeat = createPresenceHeartbeat({
33
+ intervalMs,
34
+ isVisible: () => document.visibilityState === "visible",
35
+ send: () => httpService.post("/public/user-status/heartbeat", { platform_id: platformId }),
36
+ });
37
+
38
+ watch(
39
+ () => pinia.state.value["auth-store"]?.signedIn,
40
+ (signedIn) => (signedIn ? heartbeat.start() : heartbeat.stop()),
41
+ { immediate: true },
42
+ );
43
+
44
+ document.addEventListener("visibilitychange", () => heartbeat.onVisible());
45
+ } catch (e) {
46
+ // Presence must never break a page.
47
+ console.warn("[shared-ui Presence] disabled:", e);
48
+ }
49
+ },
50
+ });
@@ -0,0 +1,81 @@
1
+ /**
2
+ * Keeps a signed-in user "present" on a platform by pinging the API about every couple of minutes.
3
+ *
4
+ * The scheduling is kept free of Nuxt and the DOM so it can be tested: the plugin hands it a `send` function and a
5
+ * visibility probe. Rules:
6
+ * - ping right away on start, then every `intervalMs` with a little jitter so a few thousand tabs do not all hit the API on
7
+ * the same second;
8
+ * - never ping a hidden tab; when it becomes visible again, ping at once if the last ping is already stale;
9
+ * - never overlap two pings;
10
+ * - a 401/403 means the session is gone: stop, and let the next sign-in start it again;
11
+ * - any other failure is ignored, presence is a convenience and must never surface an error to the user.
12
+ */
13
+ export interface PresenceHeartbeatOptions {
14
+ intervalMs: number;
15
+ send: () => Promise<unknown>;
16
+ isVisible: () => boolean;
17
+ /** Random in [0, 1); injectable for tests. */
18
+ random?: () => number;
19
+ now?: () => number;
20
+ }
21
+
22
+ /** +/- this fraction of the interval is added to every wait. */
23
+ const JITTER = 0.15;
24
+
25
+ export function createPresenceHeartbeat(options: PresenceHeartbeatOptions) {
26
+ const random = options.random ?? Math.random;
27
+ const now = options.now ?? Date.now;
28
+
29
+ let timer: ReturnType<typeof setTimeout> | null = null;
30
+ let running = false;
31
+ let inFlight = false;
32
+ let lastSentAt = 0;
33
+
34
+ const nextDelay = () => Math.round(options.intervalMs * (1 - JITTER + random() * 2 * JITTER));
35
+
36
+ const schedule = () => {
37
+ if (!running) return;
38
+ if (timer) clearTimeout(timer);
39
+ timer = setTimeout(tick, nextDelay());
40
+ };
41
+
42
+ const ping = async () => {
43
+ if (inFlight) return;
44
+ inFlight = true;
45
+ lastSentAt = now();
46
+ try {
47
+ await options.send();
48
+ } catch (error: any) {
49
+ const status = error?.response?.status;
50
+ if (status === 401 || status === 403) stop();
51
+ } finally {
52
+ inFlight = false;
53
+ }
54
+ };
55
+
56
+ async function tick() {
57
+ if (!running) return;
58
+ if (options.isVisible()) await ping();
59
+ schedule();
60
+ }
61
+
62
+ function start() {
63
+ if (running) return;
64
+ running = true;
65
+ if (options.isVisible()) void ping();
66
+ schedule();
67
+ }
68
+
69
+ function stop() {
70
+ running = false;
71
+ if (timer) clearTimeout(timer);
72
+ timer = null;
73
+ }
74
+
75
+ /** Call when the tab becomes visible: a tab hidden for a while should not wait out the rest of its timer. */
76
+ function onVisible() {
77
+ if (running && options.isVisible() && now() - lastSentAt >= options.intervalMs / 2) void ping();
78
+ }
79
+
80
+ return { start, stop, onVisible, isRunning: () => running };
81
+ }