@remote-logger/sdk 0.1.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.js ADDED
@@ -0,0 +1,548 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+
20
+ // src/index.ts
21
+ var index_exports = {};
22
+ __export(index_exports, {
23
+ Logger: () => Logger,
24
+ createLogger: () => createLogger,
25
+ default: () => index_default
26
+ });
27
+ module.exports = __toCommonJS(index_exports);
28
+ var LEVEL_ORDER = {
29
+ DEBUG: 0,
30
+ INFO: 1,
31
+ WARN: 2,
32
+ ERROR: 3,
33
+ FATAL: 4
34
+ };
35
+ var SDK_VERSION = "0.1.0";
36
+ var DEFAULT_BASE_URL = "https://log.terodato.com";
37
+ var BATCH_SIZE = 50;
38
+ var MAX_BUFFER_SIZE = 1e3;
39
+ var FLUSH_INTERVAL_MS = 1e3;
40
+ var FETCH_TIMEOUT_MS = 1e4;
41
+ var batchCounter = 0;
42
+ var generateBatchId = () => `${Date.now()}-${++batchCounter}`;
43
+ var originalConsole = {
44
+ log: console.log.bind(console),
45
+ info: console.info.bind(console),
46
+ warn: console.warn.bind(console),
47
+ error: console.error.bind(console),
48
+ debug: console.debug.bind(console)
49
+ };
50
+ function resolveLevel(level) {
51
+ if (!level) return "DEBUG";
52
+ if (level in LEVEL_ORDER) return level;
53
+ return "INFO";
54
+ }
55
+ function safeStringify(value) {
56
+ try {
57
+ return JSON.stringify(value);
58
+ } catch {
59
+ const seen = /* @__PURE__ */ new WeakSet();
60
+ return JSON.stringify(value, (_key, val) => {
61
+ if (typeof val === "object" && val !== null) {
62
+ if (seen.has(val)) return "[Circular]";
63
+ seen.add(val);
64
+ }
65
+ return val;
66
+ });
67
+ }
68
+ }
69
+ var _Logger = class _Logger {
70
+ constructor(config) {
71
+ this.buffer = [];
72
+ this.flushTimer = null;
73
+ this.flushPromise = null;
74
+ this.consoleIntercepted = false;
75
+ this.httpBackoffMs = 0;
76
+ this.maxBackoffMs = 6e4;
77
+ this.consecutiveHttpFailures = 0;
78
+ // Error capture via window event listeners (no console.error wrapping to
79
+ // avoid polluting stack traces shown in Next.js / React error overlays)
80
+ this._onError = null;
81
+ this._onUnhandledRejection = null;
82
+ // WebSocket state
83
+ this.ws = null;
84
+ this.wsState = "disconnected";
85
+ this.wsReconnectTimer = null;
86
+ this.wsReconnectAttempts = 0;
87
+ this.maxWsReconnectAttempts = 5;
88
+ // Browser lifecycle hooks for best-effort flush on page unload
89
+ this._onVisibilityChange = null;
90
+ this._onBeforeUnload = null;
91
+ this.config = {
92
+ logId: config.logId,
93
+ apiKey: config.apiKey,
94
+ group: config.group,
95
+ level: resolveLevel(config.level),
96
+ onError: config.onError,
97
+ traceId: config.traceId,
98
+ silent: config.silent ?? false,
99
+ debug: config.debug ?? false
100
+ };
101
+ this.proxyMode = !!config._ingestUrl;
102
+ const baseUrl = config._endpoint ?? DEFAULT_BASE_URL;
103
+ this.baseUrl = baseUrl;
104
+ const wsBaseUrl = config._wsEndpoint ?? baseUrl;
105
+ this.httpIngestUrl = config._ingestUrl ?? `${baseUrl}/ingest/http`;
106
+ this.wsIngestUrl = `${wsBaseUrl.replace(/^http/, "ws")}/ingest/ws`;
107
+ this.startFlushTimer();
108
+ if (!this.proxyMode && typeof WebSocket !== "undefined") {
109
+ this.connectWebSocket();
110
+ } else if (this.proxyMode) {
111
+ this.debugLog("Proxy mode enabled, using HTTP transport only");
112
+ } else {
113
+ this.debugLog("WebSocket not available, using HTTP transport only");
114
+ }
115
+ this.registerLifecycleHooks();
116
+ }
117
+ debugLog(msg, ...args) {
118
+ if (this.config.debug) {
119
+ originalConsole.debug("[RemoteLogger]", msg, ...args);
120
+ }
121
+ }
122
+ connectWebSocket() {
123
+ if (this.wsState === "connecting" || this.wsState === "connected") {
124
+ return;
125
+ }
126
+ this.wsState = "connecting";
127
+ this.debugLog("WebSocket connecting to", this.wsIngestUrl);
128
+ try {
129
+ this.ws = new WebSocket(this.wsIngestUrl, ["api_key", this.config.apiKey]);
130
+ this.ws.onopen = () => {
131
+ this.wsReconnectAttempts = 0;
132
+ this.wsState = "connected";
133
+ this.debugLog("WebSocket connected");
134
+ };
135
+ this.ws.onmessage = (event) => {
136
+ try {
137
+ const msg = JSON.parse(event.data);
138
+ if (!msg.success) {
139
+ originalConsole.error("[RemoteLogger] WebSocket log ingestion failed:", msg.error);
140
+ }
141
+ } catch {
142
+ }
143
+ };
144
+ this.ws.onerror = () => {
145
+ };
146
+ this.ws.onclose = () => {
147
+ this.wsState = "disconnected";
148
+ this.ws = null;
149
+ if (this.wsReconnectAttempts < this.maxWsReconnectAttempts) {
150
+ const delay = Math.min(1e3 * Math.pow(2, this.wsReconnectAttempts), 3e4);
151
+ this.wsReconnectAttempts++;
152
+ this.debugLog(`WebSocket disconnected, reconnecting in ${delay}ms (attempt ${this.wsReconnectAttempts}/${this.maxWsReconnectAttempts})`);
153
+ this.wsReconnectTimer = setTimeout(() => this.connectWebSocket(), delay);
154
+ } else {
155
+ this.debugLog("WebSocket max reconnect attempts reached, using HTTP only");
156
+ }
157
+ };
158
+ } catch {
159
+ this.wsState = "failed";
160
+ this.debugLog("WebSocket connection failed");
161
+ }
162
+ }
163
+ startFlushTimer() {
164
+ if (this.flushTimer) {
165
+ clearInterval(this.flushTimer);
166
+ }
167
+ this.flushTimer = setInterval(() => {
168
+ this.flush();
169
+ }, FLUSH_INTERVAL_MS);
170
+ }
171
+ shouldLog(level) {
172
+ return LEVEL_ORDER[level] >= LEVEL_ORDER[this.config.level];
173
+ }
174
+ formatArgs(args) {
175
+ return args.map((arg) => {
176
+ if (typeof arg === "string") return arg;
177
+ if (arg instanceof Error) return `${arg.message}
178
+ ${arg.stack}`;
179
+ try {
180
+ return JSON.stringify(arg, null, 2);
181
+ } catch {
182
+ return String(arg);
183
+ }
184
+ }).join(" ");
185
+ }
186
+ log(level, message, options) {
187
+ if (!this.shouldLog(level)) return;
188
+ if (!this.config.silent) {
189
+ const method = _Logger.CONSOLE_METHOD[level];
190
+ const consoleArgs = [message];
191
+ if (options?.metadata && Object.keys(options.metadata).length > 0) {
192
+ consoleArgs.push(options.metadata);
193
+ }
194
+ if (options?.stack) {
195
+ consoleArgs.push("\n" + options.stack);
196
+ }
197
+ originalConsole[method](...consoleArgs);
198
+ }
199
+ const entry = {
200
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
201
+ level,
202
+ message,
203
+ logId: this.config.logId,
204
+ group: options?.group ?? this.config.group,
205
+ trace_id: options?.traceId ?? this.config.traceId,
206
+ stack: options?.stack,
207
+ error_type: options?.errorType,
208
+ metadata: options?.metadata
209
+ };
210
+ this.buffer.push(entry);
211
+ if (this.buffer.length > MAX_BUFFER_SIZE) {
212
+ const dropped = this.buffer.length - MAX_BUFFER_SIZE;
213
+ this.buffer.splice(0, dropped);
214
+ this.debugLog(`Buffer full, dropped ${dropped} oldest logs`);
215
+ }
216
+ if (this.buffer.length >= BATCH_SIZE) {
217
+ this.flush();
218
+ }
219
+ }
220
+ parseArgs(msgOrObj, metadata) {
221
+ if (typeof msgOrObj === "object") {
222
+ return {
223
+ message: msgOrObj.message,
224
+ options: { traceId: msgOrObj.traceId, group: msgOrObj.group, metadata: msgOrObj.metadata }
225
+ };
226
+ }
227
+ if (metadata !== void 0) {
228
+ return { message: msgOrObj, options: { metadata } };
229
+ }
230
+ return { message: msgOrObj };
231
+ }
232
+ debug(msgOrObj, metadata) {
233
+ const { message, options } = this.parseArgs(msgOrObj, metadata);
234
+ this.log("DEBUG", message, options);
235
+ }
236
+ info(msgOrObj, metadata) {
237
+ const { message, options } = this.parseArgs(msgOrObj, metadata);
238
+ this.log("INFO", message, options);
239
+ }
240
+ warn(msgOrObj, metadata) {
241
+ const { message, options } = this.parseArgs(msgOrObj, metadata);
242
+ this.log("WARN", message, options);
243
+ }
244
+ error(msgOrObj, metadata) {
245
+ if (msgOrObj instanceof Error) {
246
+ this.log("ERROR", msgOrObj.message, {
247
+ metadata,
248
+ stack: msgOrObj.stack,
249
+ errorType: msgOrObj.name
250
+ });
251
+ return;
252
+ }
253
+ const { message, options } = this.parseArgs(msgOrObj, metadata);
254
+ this.log("ERROR", message, options);
255
+ }
256
+ fatal(msgOrObj, metadata) {
257
+ if (msgOrObj instanceof Error) {
258
+ this.log("FATAL", msgOrObj.message, {
259
+ metadata,
260
+ stack: msgOrObj.stack,
261
+ errorType: msgOrObj.name
262
+ });
263
+ return;
264
+ }
265
+ const { message, options } = this.parseArgs(msgOrObj, metadata);
266
+ this.log("FATAL", message, options);
267
+ }
268
+ withTraceId(traceId) {
269
+ return new TraceLogger(this, traceId);
270
+ }
271
+ withGroup(group) {
272
+ return new GroupLogger(this, group);
273
+ }
274
+ setTraceId(traceId) {
275
+ this.config.traceId = traceId;
276
+ }
277
+ setGroup(group) {
278
+ this.config.group = group;
279
+ }
280
+ interceptConsole(group) {
281
+ if (this.consoleIntercepted) return;
282
+ this.consoleIntercepted = true;
283
+ const self = this;
284
+ const logGroup = group ?? "console";
285
+ const wrap = (original, level) => {
286
+ const wrapped = (...args) => {
287
+ queueMicrotask(() => {
288
+ self.log(level, self.formatArgs(args), { group: logGroup });
289
+ });
290
+ return original.apply(console, args);
291
+ };
292
+ Object.defineProperty(wrapped, "name", { value: original.name });
293
+ return wrapped;
294
+ };
295
+ console.debug = wrap(originalConsole.debug, "DEBUG");
296
+ console.log = wrap(originalConsole.log, "INFO");
297
+ console.info = wrap(originalConsole.info, "INFO");
298
+ console.warn = wrap(originalConsole.warn, "WARN");
299
+ if (typeof window !== "undefined") {
300
+ this._onError = (event) => {
301
+ self.log("ERROR", event.message, {
302
+ group: logGroup,
303
+ stack: event.error?.stack,
304
+ errorType: event.error?.name
305
+ });
306
+ };
307
+ this._onUnhandledRejection = (event) => {
308
+ const err = event.reason;
309
+ const message = err instanceof Error ? err.message : String(err);
310
+ self.log("ERROR", message, {
311
+ group: logGroup,
312
+ stack: err instanceof Error ? err.stack : void 0,
313
+ errorType: err instanceof Error ? err.name : "UnhandledRejection"
314
+ });
315
+ };
316
+ window.addEventListener("error", this._onError);
317
+ window.addEventListener("unhandledrejection", this._onUnhandledRejection);
318
+ }
319
+ }
320
+ restoreConsole() {
321
+ if (!this.consoleIntercepted) return;
322
+ this.consoleIntercepted = false;
323
+ console.debug = originalConsole.debug;
324
+ console.log = originalConsole.log;
325
+ console.info = originalConsole.info;
326
+ console.warn = originalConsole.warn;
327
+ if (typeof window !== "undefined") {
328
+ if (this._onError) {
329
+ window.removeEventListener("error", this._onError);
330
+ this._onError = null;
331
+ }
332
+ if (this._onUnhandledRejection) {
333
+ window.removeEventListener("unhandledrejection", this._onUnhandledRejection);
334
+ this._onUnhandledRejection = null;
335
+ }
336
+ }
337
+ }
338
+ async flush() {
339
+ if (this.flushPromise) {
340
+ await this.flushPromise;
341
+ }
342
+ if (this.buffer.length === 0) return;
343
+ const logs = this.buffer.splice(0, this.buffer.length);
344
+ this.flushPromise = this.doFlush(logs);
345
+ try {
346
+ await this.flushPromise;
347
+ } finally {
348
+ this.flushPromise = null;
349
+ }
350
+ }
351
+ async doFlush(logs) {
352
+ const batchId = generateBatchId();
353
+ if (this.wsState === "connected" && typeof WebSocket !== "undefined") {
354
+ const sent = this.sendViaWebSocket(logs, batchId);
355
+ if (sent) return;
356
+ }
357
+ await this.sendViaHttp(logs, batchId);
358
+ }
359
+ sendViaWebSocket(logs, batchId) {
360
+ if (!this.ws || this.ws.readyState !== WebSocket.OPEN) {
361
+ return false;
362
+ }
363
+ try {
364
+ this.ws.send(safeStringify({ type: "logs", batchId, logs }));
365
+ this.debugLog(`Flushed ${logs.length} logs via WebSocket (batch ${batchId})`);
366
+ return true;
367
+ } catch {
368
+ this.debugLog("WebSocket send failed, falling back to HTTP");
369
+ return false;
370
+ }
371
+ }
372
+ async sendViaHttp(logs, batchId) {
373
+ if (this.httpBackoffMs > 0) {
374
+ await new Promise((resolve) => setTimeout(resolve, this.httpBackoffMs));
375
+ }
376
+ const controller = new AbortController();
377
+ const timeout = setTimeout(() => controller.abort(), FETCH_TIMEOUT_MS);
378
+ try {
379
+ const headers = {
380
+ "Content-Type": "application/json",
381
+ "X-Batch-Id": batchId,
382
+ "X-SDK-Version": SDK_VERSION
383
+ };
384
+ if (this.config.apiKey) {
385
+ headers["Authorization"] = `Bearer ${this.config.apiKey}`;
386
+ }
387
+ const response = await fetch(this.httpIngestUrl, {
388
+ method: "POST",
389
+ headers,
390
+ body: safeStringify(logs),
391
+ signal: controller.signal
392
+ });
393
+ if (!response.ok) {
394
+ const error = await response.json().catch(() => ({ error: "Unknown error" }));
395
+ throw new Error(error.error || `HTTP ${response.status}`);
396
+ }
397
+ this.httpBackoffMs = 0;
398
+ this.consecutiveHttpFailures = 0;
399
+ this.debugLog(`Flushed ${logs.length} logs via HTTP (batch ${batchId})`);
400
+ } catch (err) {
401
+ this.buffer.unshift(...logs);
402
+ this.consecutiveHttpFailures++;
403
+ this.httpBackoffMs = Math.min(
404
+ Math.pow(2, this.consecutiveHttpFailures - 1) * 1e3,
405
+ this.maxBackoffMs
406
+ );
407
+ this.debugLog(`HTTP flush failed (retry in ${this.httpBackoffMs / 1e3}s):`, err);
408
+ if (this.config.onError) {
409
+ this.config.onError(err, logs);
410
+ } else {
411
+ originalConsole.error(
412
+ `[RemoteLogger] Failed to flush logs (retry in ${this.httpBackoffMs / 1e3}s):`,
413
+ err
414
+ );
415
+ }
416
+ } finally {
417
+ clearTimeout(timeout);
418
+ }
419
+ }
420
+ /** Fire-and-forget flush using fetch with keepalive (works during page unload) */
421
+ flushSync() {
422
+ if (this.buffer.length === 0) return;
423
+ const logs = this.buffer.splice(0, this.buffer.length);
424
+ try {
425
+ const headers = {
426
+ "Content-Type": "application/json",
427
+ "X-Batch-Id": generateBatchId(),
428
+ "X-SDK-Version": SDK_VERSION
429
+ };
430
+ if (this.config.apiKey) {
431
+ headers["Authorization"] = `Bearer ${this.config.apiKey}`;
432
+ }
433
+ fetch(this.httpIngestUrl, {
434
+ method: "POST",
435
+ headers,
436
+ body: safeStringify(logs),
437
+ keepalive: true
438
+ });
439
+ } catch {
440
+ }
441
+ }
442
+ registerLifecycleHooks() {
443
+ if (typeof window !== "undefined") {
444
+ this._onVisibilityChange = () => {
445
+ if (document.visibilityState === "hidden") {
446
+ this.flushSync();
447
+ }
448
+ };
449
+ document.addEventListener("visibilitychange", this._onVisibilityChange);
450
+ this._onBeforeUnload = () => {
451
+ this.flushSync();
452
+ };
453
+ window.addEventListener("beforeunload", this._onBeforeUnload);
454
+ }
455
+ }
456
+ /** Check server connectivity and API key validity */
457
+ async ping() {
458
+ const start = Date.now();
459
+ const controller = new AbortController();
460
+ const timeout = setTimeout(() => controller.abort(), FETCH_TIMEOUT_MS);
461
+ try {
462
+ const headers = {};
463
+ if (this.config.apiKey) {
464
+ headers["Authorization"] = `Bearer ${this.config.apiKey}`;
465
+ }
466
+ const response = await fetch(`${this.baseUrl}/health`, {
467
+ headers,
468
+ signal: controller.signal
469
+ });
470
+ const latencyMs = Date.now() - start;
471
+ if (!response.ok) {
472
+ const body = await response.json().catch(() => ({ error: `HTTP ${response.status}` }));
473
+ return { ok: false, latencyMs, error: body.error || `HTTP ${response.status}` };
474
+ }
475
+ return { ok: true, latencyMs };
476
+ } catch (err) {
477
+ return { ok: false, latencyMs: Date.now() - start, error: err.message };
478
+ } finally {
479
+ clearTimeout(timeout);
480
+ }
481
+ }
482
+ /** Get current connection status */
483
+ getConnectionStatus() {
484
+ if (this.wsState === "connected") {
485
+ return { transport: "websocket", state: "connected" };
486
+ }
487
+ return { transport: "http", state: "connected" };
488
+ }
489
+ };
490
+ _Logger.CONSOLE_METHOD = {
491
+ DEBUG: "debug",
492
+ INFO: "info",
493
+ WARN: "warn",
494
+ ERROR: "error",
495
+ FATAL: "error"
496
+ };
497
+ var Logger = _Logger;
498
+ var TraceLogger = class {
499
+ constructor(parent, traceId) {
500
+ this.parent = parent;
501
+ this.traceId = traceId;
502
+ }
503
+ debug(message, metadata) {
504
+ this.parent.debug({ message, traceId: this.traceId, metadata });
505
+ }
506
+ info(message, metadata) {
507
+ this.parent.info({ message, traceId: this.traceId, metadata });
508
+ }
509
+ warn(message, metadata) {
510
+ this.parent.warn({ message, traceId: this.traceId, metadata });
511
+ }
512
+ error(message, metadata) {
513
+ this.parent.error({ message, traceId: this.traceId, metadata });
514
+ }
515
+ fatal(message, metadata) {
516
+ this.parent.fatal({ message, traceId: this.traceId, metadata });
517
+ }
518
+ };
519
+ var GroupLogger = class {
520
+ constructor(parent, group) {
521
+ this.parent = parent;
522
+ this.group = group;
523
+ }
524
+ debug(message, metadata) {
525
+ this.parent.debug({ message, group: this.group, metadata });
526
+ }
527
+ info(message, metadata) {
528
+ this.parent.info({ message, group: this.group, metadata });
529
+ }
530
+ warn(message, metadata) {
531
+ this.parent.warn({ message, group: this.group, metadata });
532
+ }
533
+ error(message, metadata) {
534
+ this.parent.error({ message, group: this.group, metadata });
535
+ }
536
+ fatal(message, metadata) {
537
+ this.parent.fatal({ message, group: this.group, metadata });
538
+ }
539
+ };
540
+ function createLogger(config) {
541
+ return new Logger(config);
542
+ }
543
+ var index_default = createLogger;
544
+ // Annotate the CommonJS export names for ESM import in node:
545
+ 0 && (module.exports = {
546
+ Logger,
547
+ createLogger
548
+ });