@victor-studio/monitor 0.1.0 → 0.2.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/dist/index.d.ts CHANGED
@@ -1,42 +1,112 @@
1
- interface MonitorEvent {
2
- type: 'heartbeat' | 'request' | 'vital';
3
- data: Record<string, unknown>;
4
- timestamp: string;
1
+ interface HeartbeatData {
2
+ status: 'online' | 'offline';
3
+ latencyMs: number;
5
4
  }
6
- interface TransportConfig {
7
- endpoint: string;
8
- apiKey: string;
5
+ interface RequestData {
6
+ method: string;
7
+ route: string;
8
+ statusCode: number;
9
+ responseTimeMs: number;
10
+ userAgent?: string;
11
+ region?: string;
9
12
  }
10
-
11
- declare class Collector {
12
- private buffer;
13
- private timer;
14
- private config;
15
- private flushInterval;
16
- constructor(config: TransportConfig, flushInterval?: number);
17
- start(): void;
18
- stop(): void;
19
- push(event: Omit<MonitorEvent, 'timestamp'>): void;
20
- private flush;
13
+ interface VitalData {
14
+ name: 'LCP' | 'INP' | 'CLS' | 'FCP' | 'TTFB';
15
+ value: number;
16
+ rating: 'good' | 'needs-improvement' | 'poor';
17
+ page?: string;
18
+ deviceType?: string;
19
+ browser?: string;
20
+ }
21
+ interface ErrorData {
22
+ type: 'unhandled' | 'caught' | 'promise';
23
+ message: string;
24
+ stack?: string;
25
+ groupingKey: string;
26
+ route?: string;
27
+ method?: string;
28
+ statusCode?: number;
29
+ environment?: string;
30
+ commitHash?: string;
31
+ extra?: Record<string, string>;
32
+ }
33
+ interface DeployData {
34
+ commitHash: string;
35
+ branch?: string;
36
+ author?: string;
37
+ status: 'started' | 'succeeded' | 'failed';
38
+ buildDurationMs?: number;
39
+ url?: string;
40
+ environment?: string;
41
+ provider?: string;
21
42
  }
43
+ interface AdapterData {
44
+ adapter: string;
45
+ operation: string;
46
+ durationMs: number;
47
+ success: boolean;
48
+ error?: string;
49
+ meta?: Record<string, string>;
50
+ }
51
+ type MonitorEvent = {
52
+ type: 'heartbeat';
53
+ data: HeartbeatData;
54
+ timestamp: string;
55
+ } | {
56
+ type: 'request';
57
+ data: RequestData;
58
+ timestamp: string;
59
+ } | {
60
+ type: 'vital';
61
+ data: VitalData;
62
+ timestamp: string;
63
+ } | {
64
+ type: 'error';
65
+ data: ErrorData;
66
+ timestamp: string;
67
+ } | {
68
+ type: 'deploy';
69
+ data: DeployData;
70
+ timestamp: string;
71
+ } | {
72
+ type: 'adapter';
73
+ data: AdapterData;
74
+ timestamp: string;
75
+ };
76
+ type MonitorEventType = MonitorEvent['type'];
77
+ /** Evento sem timestamp — usado pelo collector ao receber do client */
78
+ type MonitorEventInput = Omit<MonitorEvent, 'timestamp'>;
79
+ /** Hook para filtrar/modificar eventos antes do envio */
80
+ type BeforeSendHook = (event: MonitorEvent) => MonitorEvent | null;
22
81
 
23
82
  interface MonitorConfig {
24
83
  /** ID do projeto no Nuvio */
25
84
  projectId: string;
26
85
  /** API key gerada no Nuvio */
27
86
  apiKey: string;
28
- /** URL do endpoint de ingest (ex: https://app.nuvio.com/api/monitor/ingest) */
87
+ /** URL do endpoint de ingest */
29
88
  endpoint: string;
30
89
  /** Intervalo do heartbeat em ms (default: 60000) */
31
90
  heartbeatInterval?: number;
32
91
  /** Intervalo do flush do buffer em ms (default: 30000) */
33
92
  flushInterval?: number;
93
+ /** Timeout do fetch em ms (default: 10000) */
94
+ timeout?: number;
95
+ /** Max tentativas de retry (default: 3) */
96
+ maxRetries?: number;
34
97
  /** Desabilitar em desenvolvimento (default: true) */
35
98
  disableInDev?: boolean;
99
+ /** Taxa de amostragem 0.0-1.0 (default: 1.0). Heartbeats nunca são amostrados */
100
+ sampleRate?: number;
101
+ /** Hook chamado antes de enfileirar cada evento. Retorna null para dropar */
102
+ beforeSend?: BeforeSendHook;
103
+ /** Habilitar logs de debug no console (default: false) */
104
+ debug?: boolean;
36
105
  }
37
106
  declare class MonitorClient {
38
107
  readonly config: MonitorConfig;
39
- readonly collector: Collector;
108
+ private readonly collector;
109
+ private readonly logger;
40
110
  private heartbeatTimer;
41
111
  private active;
42
112
  constructor(config: MonitorConfig);
@@ -44,27 +114,22 @@ declare class MonitorClient {
44
114
  start(): void;
45
115
  /** Para o monitoring */
46
116
  stop(): void;
117
+ /** Força um flush imediato do buffer */
118
+ flush(): void;
119
+ /** Verifica se o monitoring está ativo */
120
+ get isActive(): boolean;
47
121
  /** Registra um evento de request HTTP (usado pelo middleware) */
48
- trackRequest(data: {
49
- method: string;
50
- route: string;
51
- statusCode: number;
52
- responseTimeMs: number;
53
- userAgent?: string;
54
- region?: string;
55
- }): void;
122
+ trackRequest(data: RequestData): void;
56
123
  /** Registra um Web Vital (usado pelo MonitorScript) */
57
- trackVital(data: {
58
- name: 'LCP' | 'INP' | 'CLS' | 'FCP' | 'TTFB';
59
- value: number;
60
- rating: 'good' | 'needs-improvement' | 'poor';
61
- page?: string;
62
- deviceType?: string;
63
- browser?: string;
64
- }): void;
124
+ trackVital(data: VitalData): void;
125
+ /** Registra um evento de adapter (DB, cache, AI, queue, email) */
126
+ trackAdapter(data: AdapterData): void;
127
+ /** Registra um erro capturado */
128
+ captureError(data: ErrorData): void;
129
+ /** Registra um evento de deploy */
130
+ trackDeploy(data: DeployData): void;
65
131
  private startHeartbeat;
66
132
  private sendHeartbeat;
67
- private isDev;
68
133
  }
69
134
 
70
135
  /**
@@ -77,10 +142,10 @@ declare class MonitorClient {
77
142
  * export const monitor = createMonitor({
78
143
  * projectId: 'uuid-do-projeto',
79
144
  * apiKey: 'nuvio_mon_xxxxxxxx',
80
- * endpoint: 'https://app.nuvio.com/api/monitor/ingest',
145
+ * endpoint: 'https://nuvio.app/api/monitor/ingest',
81
146
  * })
82
147
  * ```
83
148
  */
84
149
  declare function createMonitor(config: MonitorConfig): MonitorClient;
85
150
 
86
- export { MonitorClient, type MonitorConfig, createMonitor };
151
+ export { type AdapterData, type BeforeSendHook, type DeployData, type ErrorData, type HeartbeatData, MonitorClient, type MonitorConfig, type MonitorEvent, type MonitorEventInput, type MonitorEventType, type RequestData, type VitalData, createMonitor };
package/dist/index.js CHANGED
@@ -1,21 +1,71 @@
1
1
  // src/core/transport.ts
2
- async function sendBatch(config, events) {
2
+ var DEFAULT_TIMEOUT = 1e4;
3
+ var DEFAULT_MAX_RETRIES = 3;
4
+ var MAX_PAYLOAD_BYTES = 6e4;
5
+ async function sendBatch(config, events, logger, options) {
3
6
  if (events.length === 0) return true;
4
- try {
5
- const response = await fetch(config.endpoint, {
6
- method: "POST",
7
- headers: { "Content-Type": "application/json" },
8
- body: JSON.stringify({
9
- apiKey: config.apiKey,
10
- events
11
- }),
12
- // Usar keepalive pra garantir envio mesmo quando a página fecha
13
- keepalive: true
14
- });
15
- return response.ok;
16
- } catch {
17
- return false;
7
+ const payload = JSON.stringify({ events });
8
+ if (options?.useBeacon && typeof navigator !== "undefined" && navigator.sendBeacon) {
9
+ const beaconPayload = JSON.stringify({ apiKey: config.apiKey, events });
10
+ const beaconBlob = new Blob([beaconPayload], { type: "application/json" });
11
+ const sent = navigator.sendBeacon(config.endpoint, beaconBlob);
12
+ logger.debug("sendBeacon", sent ? "queued" : "failed", `${events.length} events`);
13
+ return sent;
14
+ }
15
+ const payloadSize = new Blob([payload]).size;
16
+ if (payloadSize > MAX_PAYLOAD_BYTES && events.length > 1) {
17
+ const mid = Math.floor(events.length / 2);
18
+ const [first, second] = await Promise.all([
19
+ sendBatch(config, events.slice(0, mid), logger),
20
+ sendBatch(config, events.slice(mid), logger)
21
+ ]);
22
+ return first && second;
23
+ }
24
+ return sendWithRetry(config, payload, logger);
25
+ }
26
+ async function sendWithRetry(config, payload, logger) {
27
+ const maxRetries = config.maxRetries ?? DEFAULT_MAX_RETRIES;
28
+ const timeout = config.timeout ?? DEFAULT_TIMEOUT;
29
+ for (let attempt = 0; attempt <= maxRetries; attempt++) {
30
+ try {
31
+ const controller = new AbortController();
32
+ const timer = setTimeout(() => controller.abort(), timeout);
33
+ const response = await fetch(config.endpoint, {
34
+ method: "POST",
35
+ headers: {
36
+ "Content-Type": "application/json",
37
+ "Authorization": `Bearer ${config.apiKey}`
38
+ },
39
+ body: payload,
40
+ signal: controller.signal,
41
+ keepalive: attempt === 0
42
+ // keepalive só na primeira tentativa
43
+ });
44
+ clearTimeout(timer);
45
+ if (response.ok) {
46
+ logger.debug("sent", `attempt ${attempt + 1}`, response.status);
47
+ return true;
48
+ }
49
+ if (response.status >= 400 && response.status < 500) {
50
+ logger.warn("client error", response.status, "\u2014 no retry");
51
+ return false;
52
+ }
53
+ logger.warn("server error", response.status, `attempt ${attempt + 1}/${maxRetries + 1}`);
54
+ } catch (err) {
55
+ const message = err instanceof Error ? err.message : "unknown error";
56
+ logger.warn("network error", message, `attempt ${attempt + 1}/${maxRetries + 1}`);
57
+ }
58
+ if (attempt < maxRetries) {
59
+ const delay = Math.min(1e3 * Math.pow(2, attempt), 16e3);
60
+ const jitter = Math.random() * 1e3;
61
+ await sleep(delay + jitter);
62
+ }
18
63
  }
64
+ logger.error("all retries exhausted, dropping batch");
65
+ return false;
66
+ }
67
+ function sleep(ms) {
68
+ return new Promise((resolve) => setTimeout(resolve, ms));
19
69
  }
20
70
 
21
71
  // src/core/collector.ts
@@ -26,9 +76,16 @@ var Collector = class {
26
76
  timer = null;
27
77
  config;
28
78
  flushInterval;
29
- constructor(config, flushInterval = DEFAULT_FLUSH_INTERVAL) {
79
+ logger;
80
+ beforeSend;
81
+ sampleRate;
82
+ visibilityHandler = null;
83
+ constructor(config, logger, options) {
30
84
  this.config = config;
31
- this.flushInterval = flushInterval;
85
+ this.logger = logger;
86
+ this.flushInterval = options?.flushInterval ?? DEFAULT_FLUSH_INTERVAL;
87
+ this.beforeSend = options?.beforeSend;
88
+ this.sampleRate = options?.sampleRate ?? 1;
32
89
  }
33
90
  start() {
34
91
  if (this.timer) return;
@@ -36,11 +93,12 @@ var Collector = class {
36
93
  this.flush();
37
94
  }, this.flushInterval);
38
95
  if (typeof window !== "undefined") {
39
- window.addEventListener("visibilitychange", () => {
96
+ this.visibilityHandler = () => {
40
97
  if (document.visibilityState === "hidden") {
41
- this.flush();
98
+ this.flush(true);
42
99
  }
43
- });
100
+ };
101
+ window.addEventListener("visibilitychange", this.visibilityHandler);
44
102
  }
45
103
  }
46
104
  stop() {
@@ -48,55 +106,132 @@ var Collector = class {
48
106
  clearInterval(this.timer);
49
107
  this.timer = null;
50
108
  }
109
+ if (this.visibilityHandler && typeof window !== "undefined") {
110
+ window.removeEventListener("visibilitychange", this.visibilityHandler);
111
+ this.visibilityHandler = null;
112
+ }
51
113
  this.flush();
52
114
  }
53
- push(event) {
54
- this.buffer.push({
55
- ...event,
115
+ push(input) {
116
+ if (input.type !== "heartbeat" && this.sampleRate < 1) {
117
+ if (Math.random() >= this.sampleRate) {
118
+ this.logger.debug("sampled out", input.type);
119
+ return;
120
+ }
121
+ }
122
+ const event = {
123
+ ...input,
56
124
  timestamp: (/* @__PURE__ */ new Date()).toISOString()
57
- });
125
+ };
126
+ if (this.beforeSend) {
127
+ const result = this.beforeSend(event);
128
+ if (result === null) {
129
+ this.logger.debug("dropped by beforeSend", event.type);
130
+ return;
131
+ }
132
+ this.buffer.push(result);
133
+ } else {
134
+ this.buffer.push(event);
135
+ }
136
+ this.logger.debug("buffered", event.type, `(${this.buffer.length}/${MAX_BUFFER_SIZE})`);
58
137
  if (this.buffer.length >= MAX_BUFFER_SIZE) {
59
138
  this.flush();
60
139
  }
61
140
  }
62
- flush() {
141
+ /** Flush manual — exposto via MonitorClient.flush() */
142
+ flush(useBeacon = false) {
63
143
  if (this.buffer.length === 0) return;
64
144
  const events = [...this.buffer];
65
145
  this.buffer = [];
66
- sendBatch(this.config, events).catch(() => {
146
+ this.logger.debug("flushing", events.length, "events", useBeacon ? "(beacon)" : "");
147
+ sendBatch(this.config, events, this.logger, { useBeacon }).catch(() => {
67
148
  });
68
149
  }
150
+ /** Número de eventos no buffer (para debug/testes) */
151
+ get pending() {
152
+ return this.buffer.length;
153
+ }
69
154
  };
70
155
 
156
+ // src/core/env.ts
157
+ var LOCAL_HOSTNAMES = /* @__PURE__ */ new Set(["localhost", "127.0.0.1", "0.0.0.0", "[::1]"]);
158
+ function isDev() {
159
+ if (typeof process !== "undefined" && process.env?.NODE_ENV === "development") return true;
160
+ if (typeof process !== "undefined" && process.env?.NODE_ENV === "test") return true;
161
+ if (typeof window !== "undefined" && LOCAL_HOSTNAMES.has(window.location?.hostname)) return true;
162
+ return false;
163
+ }
164
+
165
+ // src/core/logger.ts
166
+ var PREFIX = "[monitor]";
167
+ function createLogger(debug) {
168
+ if (!debug) {
169
+ return { debug: noop, warn: noop, error: noop };
170
+ }
171
+ return {
172
+ debug: (...args) => console.debug(PREFIX, ...args),
173
+ warn: (...args) => console.warn(PREFIX, ...args),
174
+ error: (...args) => console.error(PREFIX, ...args)
175
+ };
176
+ }
177
+ function noop() {
178
+ }
179
+
71
180
  // src/core/client.ts
72
181
  var MonitorClient = class {
73
182
  config;
74
183
  collector;
184
+ logger;
75
185
  heartbeatTimer = null;
76
186
  active = false;
77
187
  constructor(config) {
78
188
  this.config = config;
189
+ this.logger = createLogger(config.debug ?? false);
79
190
  this.collector = new Collector(
80
- { endpoint: config.endpoint, apiKey: config.apiKey },
81
- config.flushInterval
191
+ {
192
+ endpoint: config.endpoint,
193
+ apiKey: config.apiKey,
194
+ timeout: config.timeout,
195
+ maxRetries: config.maxRetries
196
+ },
197
+ this.logger,
198
+ {
199
+ flushInterval: config.flushInterval,
200
+ beforeSend: config.beforeSend,
201
+ sampleRate: config.sampleRate
202
+ }
82
203
  );
83
204
  }
84
205
  /** Inicia o monitoring (heartbeat + collector) */
85
206
  start() {
86
- if (this.config.disableInDev !== false && this.isDev()) return;
207
+ if (this.config.disableInDev !== false && isDev()) {
208
+ this.logger.debug("disabled in dev \u2014 call start() with disableInDev: false to override");
209
+ return;
210
+ }
87
211
  if (this.active) return;
88
212
  this.active = true;
89
213
  this.collector.start();
90
214
  this.startHeartbeat();
215
+ this.logger.debug("started", `endpoint=${this.config.endpoint}`);
91
216
  }
92
217
  /** Para o monitoring */
93
218
  stop() {
219
+ if (!this.active) return;
94
220
  this.active = false;
95
221
  this.collector.stop();
96
222
  if (this.heartbeatTimer) {
97
223
  clearInterval(this.heartbeatTimer);
98
224
  this.heartbeatTimer = null;
99
225
  }
226
+ this.logger.debug("stopped");
227
+ }
228
+ /** Força um flush imediato do buffer */
229
+ flush() {
230
+ this.collector.flush();
231
+ }
232
+ /** Verifica se o monitoring está ativo */
233
+ get isActive() {
234
+ return this.active;
100
235
  }
101
236
  /** Registra um evento de request HTTP (usado pelo middleware) */
102
237
  trackRequest(data) {
@@ -108,6 +243,22 @@ var MonitorClient = class {
108
243
  if (!this.active) return;
109
244
  this.collector.push({ type: "vital", data });
110
245
  }
246
+ /** Registra um evento de adapter (DB, cache, AI, queue, email) */
247
+ trackAdapter(data) {
248
+ if (!this.active) return;
249
+ this.collector.push({ type: "adapter", data });
250
+ }
251
+ /** Registra um erro capturado */
252
+ captureError(data) {
253
+ if (!this.active) return;
254
+ this.collector.push({ type: "error", data });
255
+ }
256
+ /** Registra um evento de deploy */
257
+ trackDeploy(data) {
258
+ if (!this.active) return;
259
+ this.collector.push({ type: "deploy", data });
260
+ }
261
+ // ─── Private ────────────────────────────────────────
111
262
  startHeartbeat() {
112
263
  const interval = this.config.heartbeatInterval ?? 6e4;
113
264
  this.sendHeartbeat();
@@ -134,18 +285,12 @@ var MonitorClient = class {
134
285
  this.collector.push({
135
286
  type: "heartbeat",
136
287
  data: {
137
- status: "online",
138
- // O app está rodando, mesmo que o endpoint falhe
288
+ status: "offline",
139
289
  latencyMs: Math.round(performance.now() - start)
140
290
  }
141
291
  });
142
292
  }
143
293
  }
144
- isDev() {
145
- if (typeof process !== "undefined" && process.env?.NODE_ENV === "development") return true;
146
- if (typeof window !== "undefined" && window.location?.hostname === "localhost") return true;
147
- return false;
148
- }
149
294
  };
150
295
 
151
296
  // src/index.ts
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/core/transport.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EAAM;AACb,EAAA,OAAO,MAAA;AACT","file":"index.js","sourcesContent":["// Transport — envia batch de eventos pro backend Nuvio\n\nexport interface MonitorEvent {\n type: 'heartbeat' | 'request' | 'vital'\n data: Record<string, unknown>\n timestamp: string\n}\n\nexport interface TransportConfig {\n endpoint: string\n apiKey: string\n}\n\nexport async function sendBatch(\n config: TransportConfig,\n events: MonitorEvent[],\n): Promise<boolean> {\n if (events.length === 0) return true\n\n try {\n const response = await fetch(config.endpoint, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({\n apiKey: config.apiKey,\n events,\n }),\n // Usar keepalive pra garantir envio mesmo quando a página fecha\n keepalive: true,\n })\n\n return response.ok\n } catch {\n // Falha silenciosa — monitoring não pode quebrar o app do cliente\n return false\n }\n}\n","// Collector — acumula eventos em buffer e envia em batch\n\nimport { sendBatch, type MonitorEvent, type TransportConfig } from './transport'\n\nconst DEFAULT_FLUSH_INTERVAL = 30_000 // 30 segundos\nconst MAX_BUFFER_SIZE = 50\n\nexport class Collector {\n private buffer: MonitorEvent[] = []\n private timer: ReturnType<typeof setInterval> | null = null\n private config: TransportConfig\n private flushInterval: number\n\n constructor(config: TransportConfig, flushInterval = DEFAULT_FLUSH_INTERVAL) {\n this.config = config\n this.flushInterval = flushInterval\n }\n\n start() {\n if (this.timer) return\n\n this.timer = setInterval(() => {\n this.flush()\n }, this.flushInterval)\n\n // Flush quando a página for fechada (browser)\n if (typeof window !== 'undefined') {\n window.addEventListener('visibilitychange', () => {\n if (document.visibilityState === 'hidden') {\n this.flush()\n }\n })\n }\n }\n\n stop() {\n if (this.timer) {\n clearInterval(this.timer)\n this.timer = null\n }\n // Flush final\n this.flush()\n }\n\n push(event: Omit<MonitorEvent, 'timestamp'>) {\n this.buffer.push({\n ...event,\n timestamp: new Date().toISOString(),\n })\n\n // Se buffer cheio, flush imediato\n if (this.buffer.length >= MAX_BUFFER_SIZE) {\n this.flush()\n }\n }\n\n private flush() {\n if (this.buffer.length === 0) return\n\n const events = [...this.buffer]\n this.buffer = []\n\n // Fire-and-forget — não bloqueia o app\n sendBatch(this.config, events).catch(() => {\n // Silencioso — eventos perdidos são aceitáveis\n })\n }\n}\n","// MonitorClient — instância principal do SDK\n\nimport { Collector } from './collector'\n\nexport interface MonitorConfig {\n /** ID do projeto no Nuvio */\n projectId: string\n /** API key gerada no Nuvio */\n apiKey: string\n /** URL do endpoint de ingest (ex: https://app.nuvio.com/api/monitor/ingest) */\n endpoint: string\n /** Intervalo do heartbeat em ms (default: 60000) */\n heartbeatInterval?: number\n /** Intervalo do flush do buffer em ms (default: 30000) */\n flushInterval?: number\n /** Desabilitar em desenvolvimento (default: true) */\n disableInDev?: boolean\n}\n\nexport class MonitorClient {\n readonly config: MonitorConfig\n readonly collector: Collector\n private heartbeatTimer: ReturnType<typeof setInterval> | null = null\n private active = false\n\n constructor(config: MonitorConfig) {\n this.config = config\n this.collector = new Collector(\n { endpoint: config.endpoint, apiKey: config.apiKey },\n config.flushInterval,\n )\n }\n\n /** Inicia o monitoring (heartbeat + collector) */\n start() {\n // Não roda em dev por padrão\n if (this.config.disableInDev !== false && this.isDev()) return\n if (this.active) return\n\n this.active = true\n this.collector.start()\n this.startHeartbeat()\n }\n\n /** Para o monitoring */\n stop() {\n this.active = false\n this.collector.stop()\n\n if (this.heartbeatTimer) {\n clearInterval(this.heartbeatTimer)\n this.heartbeatTimer = null\n }\n }\n\n /** Registra um evento de request HTTP (usado pelo middleware) */\n trackRequest(data: {\n method: string\n route: string\n statusCode: number\n responseTimeMs: number\n userAgent?: string\n region?: string\n }) {\n if (!this.active) return\n this.collector.push({ type: 'request', data })\n }\n\n /** Registra um Web Vital (usado pelo MonitorScript) */\n trackVital(data: {\n name: 'LCP' | 'INP' | 'CLS' | 'FCP' | 'TTFB'\n value: number\n rating: 'good' | 'needs-improvement' | 'poor'\n page?: string\n deviceType?: string\n browser?: string\n }) {\n if (!this.active) return\n this.collector.push({ type: 'vital', data })\n }\n\n private startHeartbeat() {\n const interval = this.config.heartbeatInterval ?? 60_000\n\n // Primeiro heartbeat imediato\n this.sendHeartbeat()\n\n this.heartbeatTimer = setInterval(() => {\n this.sendHeartbeat()\n }, interval)\n }\n\n private async sendHeartbeat() {\n const start = performance.now()\n\n try {\n // Ping pro endpoint pra medir latência\n const response = await fetch(this.config.endpoint, {\n method: 'HEAD',\n cache: 'no-store',\n })\n\n const latencyMs = Math.round(performance.now() - start)\n\n this.collector.push({\n type: 'heartbeat',\n data: {\n status: response.ok ? 'online' : 'offline',\n latencyMs,\n },\n })\n } catch {\n this.collector.push({\n type: 'heartbeat',\n data: {\n status: 'online', // O app está rodando, mesmo que o endpoint falhe\n latencyMs: Math.round(performance.now() - start),\n },\n })\n }\n }\n\n private isDev(): boolean {\n if (typeof process !== 'undefined' && process.env?.NODE_ENV === 'development') return true\n if (typeof window !== 'undefined' && window.location?.hostname === 'localhost') return true\n return false\n }\n}\n","// @victor-studio/monitor — SDK de monitoramento\n\nimport { MonitorClient, type MonitorConfig } from './core/client'\n\nexport { MonitorClient, type MonitorConfig } from './core/client'\n\n/**\n * Cria e inicia uma instância do monitor.\n *\n * @example\n * ```ts\n * import { createMonitor } from '@victor-studio/monitor'\n *\n * export const monitor = createMonitor({\n * projectId: 'uuid-do-projeto',\n * apiKey: 'nuvio_mon_xxxxxxxx',\n * endpoint: 'https://app.nuvio.com/api/monitor/ingest',\n * })\n * ```\n */\nexport function createMonitor(config: MonitorConfig): MonitorClient {\n const client = new MonitorClient(config)\n client.start()\n return client\n}\n"]}
1
+ {"version":3,"sources":["../src/core/transport.ts","../src/core/collector.ts","../src/core/env.ts","../src/core/logger.ts","../src/core/client.ts","../src/index.ts"],"names":[],"mappings":";AAmBA,IAAM,eAAA,GAAkB,GAAA;AACxB,IAAM,mBAAA,GAAsB,CAAA;AAC5B,IAAM,iBAAA,GAAoB,GAAA;AAM1B,eAAsB,SAAA,CACpB,MAAA,EACA,MAAA,EACA,MAAA,EACA,OAAA,EACkB;AAClB,EA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CAAK,UAAU,IAAA,CAAK;AAAA,QAClB,IAAA,EAAM,WAAA;AAAA,QACN,IAAA,EAAM;AAAA,UACJ,MAAA,EAAQ,SAAA;AAAA,UACR,WAAW,IAAA,CAAK,KAAA,CAAM,WAAA,CAAY,GAAA,KAAQ,KAAK;AAAA;AACjD,OACD,CAAA;AAAA,IACH;AAAA,EACF;AACF;;;ACnJO,SAAS,cAAc,MAAA,EAAsC;AAClE,EAAA,MAAM,MAAA,GAAS,IAAI,aAAA,CAAc,MAAM,CAAA;AACvC,EAAA,MAAA,CAAO,KAAA,EAAM;AACb,EAAA,OAAO,MAAA;AACT","file":"index.js","sourcesContent":["// Transport — envia batch de eventos pro backend Nuvio\n\nimport type { MonitorEvent } from '../types'\nimport type { Logger } from './logger'\n\nexport interface TransportConfig {\n endpoint: string\n apiKey: string\n /** Timeout do fetch em ms (default: 10000) */\n timeout?: number\n /** Max tentativas de retry (default: 3) */\n maxRetries?: number\n}\n\ninterface SendOptions {\n /** Usar sendBeacon em vez de fetch (para page unload) */\n useBeacon?: boolean\n}\n\nconst DEFAULT_TIMEOUT = 10_000\nconst DEFAULT_MAX_RETRIES = 3\nconst MAX_PAYLOAD_BYTES = 60_000 // 60KB — abaixo do limite de 64KB do keepalive\n\n/**\n * Envia um batch de eventos para o endpoint.\n * Usa Authorization header, retry com backoff, e sendBeacon como fallback.\n */\nexport async function sendBatch(\n config: TransportConfig,\n events: MonitorEvent[],\n logger: Logger,\n options?: SendOptions,\n): Promise<boolean> {\n if (events.length === 0) return true\n\n const payload = JSON.stringify({ events })\n\n // Se é unload, usa sendBeacon (mais confiável que fetch no page close)\n if (options?.useBeacon && typeof navigator !== 'undefined' && navigator.sendBeacon) {\n // sendBeacon não suporta headers customizados — inclui apiKey no body\n const beaconPayload = JSON.stringify({ apiKey: config.apiKey, events })\n const beaconBlob = new Blob([beaconPayload], { type: 'application/json' })\n const sent = navigator.sendBeacon(config.endpoint, beaconBlob)\n logger.debug('sendBeacon', sent ? 'queued' : 'failed', `${events.length} events`)\n return sent\n }\n\n // Dividir em batches menores se payload é muito grande\n const payloadSize = new Blob([payload]).size\n if (payloadSize > MAX_PAYLOAD_BYTES && events.length > 1) {\n const mid = Math.floor(events.length / 2)\n const [first, second] = await Promise.all([\n sendBatch(config, events.slice(0, mid), logger),\n sendBatch(config, events.slice(mid), logger),\n ])\n return first && second\n }\n\n return sendWithRetry(config, payload, logger)\n}\n\nasync function sendWithRetry(\n config: TransportConfig,\n payload: string,\n logger: Logger,\n): Promise<boolean> {\n const maxRetries = config.maxRetries ?? DEFAULT_MAX_RETRIES\n const timeout = config.timeout ?? DEFAULT_TIMEOUT\n\n for (let attempt = 0; attempt <= maxRetries; attempt++) {\n try {\n const controller = new AbortController()\n const timer = setTimeout(() => controller.abort(), timeout)\n\n const response = await fetch(config.endpoint, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n 'Authorization': `Bearer ${config.apiKey}`,\n },\n body: payload,\n signal: controller.signal,\n keepalive: attempt === 0, // keepalive só na primeira tentativa\n })\n\n clearTimeout(timer)\n\n if (response.ok) {\n logger.debug('sent', `attempt ${attempt + 1}`, response.status)\n return true\n }\n\n // 4xx — erro do cliente, não faz retry (apiKey inválida, payload mal formado, etc.)\n if (response.status >= 400 && response.status < 500) {\n logger.warn('client error', response.status, '— no retry')\n return false\n }\n\n // 5xx — erro do servidor, faz retry\n logger.warn('server error', response.status, `attempt ${attempt + 1}/${maxRetries + 1}`)\n } catch (err) {\n // Network error ou timeout — faz retry\n const message = err instanceof Error ? err.message : 'unknown error'\n logger.warn('network error', message, `attempt ${attempt + 1}/${maxRetries + 1}`)\n }\n\n // Esperar antes do retry (exponential backoff com jitter)\n if (attempt < maxRetries) {\n const delay = Math.min(1000 * Math.pow(2, attempt), 16_000)\n const jitter = Math.random() * 1000\n await sleep(delay + jitter)\n }\n }\n\n logger.error('all retries exhausted, dropping batch')\n return false\n}\n\nfunction sleep(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms))\n}\n","// Collector — acumula eventos em buffer e envia em batch\n\nimport type { MonitorEvent, MonitorEventInput, BeforeSendHook } from '../types'\nimport { sendBatch, type TransportConfig } from './transport'\nimport type { Logger } from './logger'\n\nconst DEFAULT_FLUSH_INTERVAL = 30_000 // 30 segundos\nconst MAX_BUFFER_SIZE = 50\n\nexport class Collector {\n private buffer: MonitorEvent[] = []\n private timer: ReturnType<typeof setInterval> | null = null\n private config: TransportConfig\n private flushInterval: number\n private logger: Logger\n private beforeSend: BeforeSendHook | undefined\n private sampleRate: number\n private visibilityHandler: (() => void) | null = null\n\n constructor(\n config: TransportConfig,\n logger: Logger,\n options?: {\n flushInterval?: number\n beforeSend?: BeforeSendHook\n sampleRate?: number\n },\n ) {\n this.config = config\n this.logger = logger\n this.flushInterval = options?.flushInterval ?? DEFAULT_FLUSH_INTERVAL\n this.beforeSend = options?.beforeSend\n this.sampleRate = options?.sampleRate ?? 1.0\n }\n\n start() {\n if (this.timer) return\n\n this.timer = setInterval(() => {\n this.flush()\n }, this.flushInterval)\n\n // Flush quando a página for fechada (browser) — usa sendBeacon\n if (typeof window !== 'undefined') {\n this.visibilityHandler = () => {\n if (document.visibilityState === 'hidden') {\n this.flush(true)\n }\n }\n window.addEventListener('visibilitychange', this.visibilityHandler)\n }\n }\n\n stop() {\n if (this.timer) {\n clearInterval(this.timer)\n this.timer = null\n }\n\n // Remover listener para evitar memory leak\n if (this.visibilityHandler && typeof window !== 'undefined') {\n window.removeEventListener('visibilitychange', this.visibilityHandler)\n this.visibilityHandler = null\n }\n\n // Flush final\n this.flush()\n }\n\n push(input: MonitorEventInput) {\n // Sampling — heartbeats nunca são amostrados\n if (input.type !== 'heartbeat' && this.sampleRate < 1.0) {\n if (Math.random() >= this.sampleRate) {\n this.logger.debug('sampled out', input.type)\n return\n }\n }\n\n const event: MonitorEvent = {\n ...input,\n timestamp: new Date().toISOString(),\n } as MonitorEvent\n\n // beforeSend hook — permite filtrar ou modificar eventos\n if (this.beforeSend) {\n const result = this.beforeSend(event)\n if (result === null) {\n this.logger.debug('dropped by beforeSend', event.type)\n return\n }\n // Usa o evento possivelmente modificado\n this.buffer.push(result)\n } else {\n this.buffer.push(event)\n }\n\n this.logger.debug('buffered', event.type, `(${this.buffer.length}/${MAX_BUFFER_SIZE})`)\n\n // Se buffer cheio, flush imediato\n if (this.buffer.length >= MAX_BUFFER_SIZE) {\n this.flush()\n }\n }\n\n /** Flush manual — exposto via MonitorClient.flush() */\n flush(useBeacon = false) {\n if (this.buffer.length === 0) return\n\n const events = [...this.buffer]\n this.buffer = []\n\n this.logger.debug('flushing', events.length, 'events', useBeacon ? '(beacon)' : '')\n\n // Fire-and-forget — não bloqueia o app\n sendBatch(this.config, events, this.logger, { useBeacon }).catch(() => {\n // Silencioso — transport já loga erros via logger\n })\n }\n\n /** Número de eventos no buffer (para debug/testes) */\n get pending(): number {\n return this.buffer.length\n }\n}\n","// Detecção de ambiente — centraliza lógica de dev/server\n\nconst LOCAL_HOSTNAMES = new Set(['localhost', '127.0.0.1', '0.0.0.0', '[::1]'])\n\n/** Detecta se estamos em ambiente de desenvolvimento */\nexport function isDev(): boolean {\n // Node.js / bundler env\n if (typeof process !== 'undefined' && process.env?.NODE_ENV === 'development') return true\n if (typeof process !== 'undefined' && process.env?.NODE_ENV === 'test') return true\n\n // Browser\n if (typeof window !== 'undefined' && LOCAL_HOSTNAMES.has(window.location?.hostname)) return true\n\n return false\n}\n\n/** Detecta se estamos rodando no servidor (Node.js) */\nexport function isServer(): boolean {\n return typeof window === 'undefined'\n}\n\n/** Detecta se estamos no browser */\nexport function isBrowser(): boolean {\n return typeof window !== 'undefined'\n}\n","// Logger — debug mode com prefixo [monitor]\n\nconst PREFIX = '[monitor]'\n\nexport interface Logger {\n debug(...args: unknown[]): void\n warn(...args: unknown[]): void\n error(...args: unknown[]): void\n}\n\n/** Cria logger que loga no console quando debug=true, noop caso contrário */\nexport function createLogger(debug: boolean): Logger {\n if (!debug) {\n return { debug: noop, warn: noop, error: noop }\n }\n\n return {\n debug: (...args: unknown[]) => console.debug(PREFIX, ...args),\n warn: (...args: unknown[]) => console.warn(PREFIX, ...args),\n error: (...args: unknown[]) => console.error(PREFIX, ...args),\n }\n}\n\nfunction noop() {\n // silencioso\n}\n","// MonitorClient — instância principal do SDK\n\nimport type {\n HeartbeatData,\n RequestData,\n VitalData,\n AdapterData,\n ErrorData,\n DeployData,\n BeforeSendHook,\n} from '../types'\nimport { Collector } from './collector'\nimport { isDev } from './env'\nimport { createLogger, type Logger } from './logger'\n\nexport interface MonitorConfig {\n /** ID do projeto no Nuvio */\n projectId: string\n /** API key gerada no Nuvio */\n apiKey: string\n /** URL do endpoint de ingest */\n endpoint: string\n /** Intervalo do heartbeat em ms (default: 60000) */\n heartbeatInterval?: number\n /** Intervalo do flush do buffer em ms (default: 30000) */\n flushInterval?: number\n /** Timeout do fetch em ms (default: 10000) */\n timeout?: number\n /** Max tentativas de retry (default: 3) */\n maxRetries?: number\n /** Desabilitar em desenvolvimento (default: true) */\n disableInDev?: boolean\n /** Taxa de amostragem 0.0-1.0 (default: 1.0). Heartbeats nunca são amostrados */\n sampleRate?: number\n /** Hook chamado antes de enfileirar cada evento. Retorna null para dropar */\n beforeSend?: BeforeSendHook\n /** Habilitar logs de debug no console (default: false) */\n debug?: boolean\n}\n\nexport class MonitorClient {\n readonly config: MonitorConfig\n private readonly collector: Collector\n private readonly logger: Logger\n private heartbeatTimer: ReturnType<typeof setInterval> | null = null\n private active = false\n\n constructor(config: MonitorConfig) {\n this.config = config\n this.logger = createLogger(config.debug ?? false)\n this.collector = new Collector(\n {\n endpoint: config.endpoint,\n apiKey: config.apiKey,\n timeout: config.timeout,\n maxRetries: config.maxRetries,\n },\n this.logger,\n {\n flushInterval: config.flushInterval,\n beforeSend: config.beforeSend,\n sampleRate: config.sampleRate,\n },\n )\n }\n\n /** Inicia o monitoring (heartbeat + collector) */\n start() {\n // Não roda em dev por padrão\n if (this.config.disableInDev !== false && isDev()) {\n this.logger.debug('disabled in dev — call start() with disableInDev: false to override')\n return\n }\n\n if (this.active) return\n\n this.active = true\n this.collector.start()\n this.startHeartbeat()\n this.logger.debug('started', `endpoint=${this.config.endpoint}`)\n }\n\n /** Para o monitoring */\n stop() {\n if (!this.active) return\n\n this.active = false\n this.collector.stop()\n\n if (this.heartbeatTimer) {\n clearInterval(this.heartbeatTimer)\n this.heartbeatTimer = null\n }\n\n this.logger.debug('stopped')\n }\n\n /** Força um flush imediato do buffer */\n flush() {\n this.collector.flush()\n }\n\n /** Verifica se o monitoring está ativo */\n get isActive(): boolean {\n return this.active\n }\n\n /** Registra um evento de request HTTP (usado pelo middleware) */\n trackRequest(data: RequestData) {\n if (!this.active) return\n this.collector.push({ type: 'request', data })\n }\n\n /** Registra um Web Vital (usado pelo MonitorScript) */\n trackVital(data: VitalData) {\n if (!this.active) return\n this.collector.push({ type: 'vital', data })\n }\n\n /** Registra um evento de adapter (DB, cache, AI, queue, email) */\n trackAdapter(data: AdapterData) {\n if (!this.active) return\n this.collector.push({ type: 'adapter', data })\n }\n\n /** Registra um erro capturado */\n captureError(data: ErrorData) {\n if (!this.active) return\n this.collector.push({ type: 'error', data })\n }\n\n /** Registra um evento de deploy */\n trackDeploy(data: DeployData) {\n if (!this.active) return\n this.collector.push({ type: 'deploy', data })\n }\n\n // ─── Private ────────────────────────────────────────\n\n private startHeartbeat() {\n const interval = this.config.heartbeatInterval ?? 60_000\n\n // Primeiro heartbeat imediato\n this.sendHeartbeat()\n\n this.heartbeatTimer = setInterval(() => {\n this.sendHeartbeat()\n }, interval)\n }\n\n private async sendHeartbeat() {\n const start = performance.now()\n\n try {\n const response = await fetch(this.config.endpoint, {\n method: 'HEAD',\n cache: 'no-store',\n })\n\n const latencyMs = Math.round(performance.now() - start)\n\n this.collector.push({\n type: 'heartbeat',\n data: {\n status: response.ok ? 'online' : 'offline',\n latencyMs,\n } satisfies HeartbeatData,\n })\n } catch {\n // Network error — o endpoint não respondeu, reporta offline\n this.collector.push({\n type: 'heartbeat',\n data: {\n status: 'offline',\n latencyMs: Math.round(performance.now() - start),\n } satisfies HeartbeatData,\n })\n }\n }\n}\n","// @victor-studio/monitor — SDK de monitoramento\n\nimport { MonitorClient, type MonitorConfig } from './core/client'\n\nexport { MonitorClient, type MonitorConfig } from './core/client'\nexport type {\n MonitorEvent,\n MonitorEventInput,\n MonitorEventType,\n BeforeSendHook,\n HeartbeatData,\n RequestData,\n VitalData,\n ErrorData,\n DeployData,\n AdapterData,\n} from './types'\n\n/**\n * Cria e inicia uma instância do monitor.\n *\n * @example\n * ```ts\n * import { createMonitor } from '@victor-studio/monitor'\n *\n * export const monitor = createMonitor({\n * projectId: 'uuid-do-projeto',\n * apiKey: 'nuvio_mon_xxxxxxxx',\n * endpoint: 'https://nuvio.app/api/monitor/ingest',\n * })\n * ```\n */\nexport function createMonitor(config: MonitorConfig): MonitorClient {\n const client = new MonitorClient(config)\n client.start()\n return client\n}\n"]}
@@ -1,28 +1,47 @@
1
1
  'use strict';
2
2
 
3
3
  // src/next/middleware.ts
4
- function withMonitor(monitor, middleware) {
4
+ var STATIC_ASSET_PATTERN = /^\/(_next\/|favicon|.*\.(ico|png|jpg|jpeg|gif|svg|css|woff2?|ttf|eot)$)/;
5
+ var REGION_HEADERS = [
6
+ "x-vercel-ip-country",
7
+ // Vercel
8
+ "x-railway-region",
9
+ // Railway
10
+ "cf-ipcountry",
11
+ // Cloudflare
12
+ "x-country-code"
13
+ // Generic CDN
14
+ ];
15
+ function withMonitor(monitor, middleware, options) {
5
16
  return async (request) => {
17
+ const { pathname } = new URL(request.url);
18
+ if (!options?.includeStaticAssets && STATIC_ASSET_PATTERN.test(pathname)) {
19
+ return middleware ? middleware(request) : void 0;
20
+ }
21
+ if (options?.excludeRoutes?.some((pattern) => pattern.test(pathname))) {
22
+ return middleware ? middleware(request) : void 0;
23
+ }
6
24
  const start = performance.now();
7
25
  let response;
8
26
  if (middleware) {
9
27
  response = await middleware(request);
10
28
  }
11
29
  const responseTimeMs = Math.round(performance.now() - start);
12
- const method = request.method;
13
- const route = new URL(request.url).pathname;
14
- const statusCode = response instanceof Response ? response.status : 200;
15
- const userAgent = request.headers.get("user-agent") ?? void 0;
16
- const region = request.headers.get("x-vercel-ip-country") ?? void 0;
17
- if (route.startsWith("/_next/") || route.startsWith("/favicon") || route.endsWith(".ico") || route.endsWith(".png") || route.endsWith(".jpg") || route.endsWith(".svg") || route.endsWith(".css") || route.endsWith(".js")) {
18
- return response;
30
+ let region;
31
+ for (const header of REGION_HEADERS) {
32
+ const value = request.headers.get(header);
33
+ if (value) {
34
+ region = value;
35
+ break;
36
+ }
19
37
  }
20
38
  monitor.trackRequest({
21
- method,
22
- route,
23
- statusCode,
39
+ method: request.method,
40
+ route: pathname,
41
+ // Não assumir 200 quando middleware retorna undefined (pass-through)
42
+ statusCode: response instanceof Response ? response.status : 0,
24
43
  responseTimeMs,
25
- userAgent,
44
+ userAgent: request.headers.get("user-agent") ?? void 0,
26
45
  region
27
46
  });
28
47
  return response;