@graphty/remote-logger 0.0.1 → 1.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.
Files changed (138) hide show
  1. package/README.md +944 -28
  2. package/bin/remote-log-server.js +3 -0
  3. package/dist/client/RemoteLogClient.d.ts +116 -0
  4. package/dist/client/RemoteLogClient.d.ts.map +1 -0
  5. package/dist/client/RemoteLogClient.js +269 -0
  6. package/dist/client/RemoteLogClient.js.map +1 -0
  7. package/dist/client/index.d.ts +7 -0
  8. package/dist/client/index.d.ts.map +1 -0
  9. package/dist/client/index.js +6 -0
  10. package/dist/client/index.js.map +1 -0
  11. package/dist/client/types.d.ts +60 -0
  12. package/dist/client/types.d.ts.map +1 -0
  13. package/dist/client/types.js +6 -0
  14. package/dist/client/types.js.map +1 -0
  15. package/dist/index.d.ts +22 -0
  16. package/dist/index.d.ts.map +1 -0
  17. package/dist/index.js +23 -0
  18. package/dist/index.js.map +1 -0
  19. package/dist/mcp/index.d.ts +9 -0
  20. package/dist/mcp/index.d.ts.map +1 -0
  21. package/dist/mcp/index.js +9 -0
  22. package/dist/mcp/index.js.map +1 -0
  23. package/dist/mcp/mcp-server.d.ts +32 -0
  24. package/dist/mcp/mcp-server.d.ts.map +1 -0
  25. package/dist/mcp/mcp-server.js +270 -0
  26. package/dist/mcp/mcp-server.js.map +1 -0
  27. package/dist/mcp/tools/index.d.ts +14 -0
  28. package/dist/mcp/tools/index.d.ts.map +1 -0
  29. package/dist/mcp/tools/index.js +14 -0
  30. package/dist/mcp/tools/index.js.map +1 -0
  31. package/dist/mcp/tools/logs-clear.d.ts +76 -0
  32. package/dist/mcp/tools/logs-clear.d.ts.map +1 -0
  33. package/dist/mcp/tools/logs-clear.js +58 -0
  34. package/dist/mcp/tools/logs-clear.js.map +1 -0
  35. package/dist/mcp/tools/logs-get-all.d.ts +60 -0
  36. package/dist/mcp/tools/logs-get-all.d.ts.map +1 -0
  37. package/dist/mcp/tools/logs-get-all.js +50 -0
  38. package/dist/mcp/tools/logs-get-all.js.map +1 -0
  39. package/dist/mcp/tools/logs-get-errors.d.ts +65 -0
  40. package/dist/mcp/tools/logs-get-errors.d.ts.map +1 -0
  41. package/dist/mcp/tools/logs-get-errors.js +46 -0
  42. package/dist/mcp/tools/logs-get-errors.js.map +1 -0
  43. package/dist/mcp/tools/logs-get-file-path.d.ts +75 -0
  44. package/dist/mcp/tools/logs-get-file-path.d.ts.map +1 -0
  45. package/dist/mcp/tools/logs-get-file-path.js +90 -0
  46. package/dist/mcp/tools/logs-get-file-path.js.map +1 -0
  47. package/dist/mcp/tools/logs-get-recent.d.ts +89 -0
  48. package/dist/mcp/tools/logs-get-recent.d.ts.map +1 -0
  49. package/dist/mcp/tools/logs-get-recent.js +74 -0
  50. package/dist/mcp/tools/logs-get-recent.js.map +1 -0
  51. package/dist/mcp/tools/logs-list-sessions.d.ts +64 -0
  52. package/dist/mcp/tools/logs-list-sessions.d.ts.map +1 -0
  53. package/dist/mcp/tools/logs-list-sessions.js +48 -0
  54. package/dist/mcp/tools/logs-list-sessions.js.map +1 -0
  55. package/dist/mcp/tools/logs-receive.d.ts +150 -0
  56. package/dist/mcp/tools/logs-receive.d.ts.map +1 -0
  57. package/dist/mcp/tools/logs-receive.js +68 -0
  58. package/dist/mcp/tools/logs-receive.js.map +1 -0
  59. package/dist/mcp/tools/logs-search.d.ts +91 -0
  60. package/dist/mcp/tools/logs-search.d.ts.map +1 -0
  61. package/dist/mcp/tools/logs-search.js +68 -0
  62. package/dist/mcp/tools/logs-search.js.map +1 -0
  63. package/dist/mcp/tools/logs-status.d.ts +45 -0
  64. package/dist/mcp/tools/logs-status.d.ts.map +1 -0
  65. package/dist/mcp/tools/logs-status.js +45 -0
  66. package/dist/mcp/tools/logs-status.js.map +1 -0
  67. package/dist/server/dual-server.d.ts +76 -0
  68. package/dist/server/dual-server.d.ts.map +1 -0
  69. package/dist/server/dual-server.js +214 -0
  70. package/dist/server/dual-server.js.map +1 -0
  71. package/dist/server/index.d.ts +12 -0
  72. package/dist/server/index.d.ts.map +1 -0
  73. package/dist/server/index.js +12 -0
  74. package/dist/server/index.js.map +1 -0
  75. package/dist/server/jsonl-writer.d.ts +93 -0
  76. package/dist/server/jsonl-writer.d.ts.map +1 -0
  77. package/dist/server/jsonl-writer.js +205 -0
  78. package/dist/server/jsonl-writer.js.map +1 -0
  79. package/dist/server/log-server.d.ts +126 -0
  80. package/dist/server/log-server.d.ts.map +1 -0
  81. package/dist/server/log-server.js +589 -0
  82. package/dist/server/log-server.js.map +1 -0
  83. package/dist/server/log-storage.d.ts +301 -0
  84. package/dist/server/log-storage.d.ts.map +1 -0
  85. package/dist/server/log-storage.js +408 -0
  86. package/dist/server/log-storage.js.map +1 -0
  87. package/dist/server/marker-utils.d.ts +69 -0
  88. package/dist/server/marker-utils.d.ts.map +1 -0
  89. package/dist/server/marker-utils.js +118 -0
  90. package/dist/server/marker-utils.js.map +1 -0
  91. package/dist/server/self-signed-cert.d.ts +30 -0
  92. package/dist/server/self-signed-cert.d.ts.map +1 -0
  93. package/dist/server/self-signed-cert.js +83 -0
  94. package/dist/server/self-signed-cert.js.map +1 -0
  95. package/dist/ui/ConsoleCaptureUI.d.ts +118 -0
  96. package/dist/ui/ConsoleCaptureUI.d.ts.map +1 -0
  97. package/dist/ui/ConsoleCaptureUI.js +571 -0
  98. package/dist/ui/ConsoleCaptureUI.js.map +1 -0
  99. package/dist/ui/index.d.ts +15 -0
  100. package/dist/ui/index.d.ts.map +1 -0
  101. package/dist/ui/index.js +15 -0
  102. package/dist/ui/index.js.map +1 -0
  103. package/dist/vite/index.d.ts +8 -0
  104. package/dist/vite/index.d.ts.map +1 -0
  105. package/dist/vite/index.js +8 -0
  106. package/dist/vite/index.js.map +1 -0
  107. package/dist/vite/plugin.d.ts +42 -0
  108. package/dist/vite/plugin.d.ts.map +1 -0
  109. package/dist/vite/plugin.js +46 -0
  110. package/dist/vite/plugin.js.map +1 -0
  111. package/package.json +90 -7
  112. package/src/client/RemoteLogClient.ts +328 -0
  113. package/src/client/index.ts +7 -0
  114. package/src/client/types.ts +62 -0
  115. package/src/index.ts +28 -0
  116. package/src/mcp/index.ts +25 -0
  117. package/src/mcp/mcp-server.ts +364 -0
  118. package/src/mcp/tools/index.ts +69 -0
  119. package/src/mcp/tools/logs-clear.ts +86 -0
  120. package/src/mcp/tools/logs-get-all.ts +78 -0
  121. package/src/mcp/tools/logs-get-errors.ts +71 -0
  122. package/src/mcp/tools/logs-get-file-path.ts +121 -0
  123. package/src/mcp/tools/logs-get-recent.ts +104 -0
  124. package/src/mcp/tools/logs-list-sessions.ts +71 -0
  125. package/src/mcp/tools/logs-receive.ts +96 -0
  126. package/src/mcp/tools/logs-search.ts +95 -0
  127. package/src/mcp/tools/logs-status.ts +69 -0
  128. package/src/server/dual-server.ts +308 -0
  129. package/src/server/index.ts +54 -0
  130. package/src/server/jsonl-writer.ts +277 -0
  131. package/src/server/log-server.ts +763 -0
  132. package/src/server/log-storage.ts +651 -0
  133. package/src/server/marker-utils.ts +144 -0
  134. package/src/server/self-signed-cert.ts +93 -0
  135. package/src/ui/ConsoleCaptureUI.ts +649 -0
  136. package/src/ui/index.ts +15 -0
  137. package/src/vite/index.ts +8 -0
  138. package/src/vite/plugin.ts +59 -0
@@ -0,0 +1,42 @@
1
+ /**
2
+ * Vite plugin for automatic project marker injection.
3
+ *
4
+ * This plugin injects global variables that the RemoteLogClient
5
+ * can use to automatically identify which project/worktree logs
6
+ * are coming from.
7
+ * @module vite/plugin
8
+ */
9
+ /**
10
+ * Vite plugin configuration object.
11
+ * Matches Vite's Plugin type but without requiring the full vite dependency.
12
+ */
13
+ interface VitePlugin {
14
+ name: string;
15
+ config: () => {
16
+ define: Record<string, string>;
17
+ };
18
+ }
19
+ /**
20
+ * Creates a Vite plugin that injects project marker globals.
21
+ *
22
+ * The plugin detects the current working directory and:
23
+ * 1. Extracts a project marker (worktree name or directory basename)
24
+ * 2. Injects `__REMOTE_LOG_PROJECT_MARKER__` with the marker
25
+ * 3. Injects `__REMOTE_LOG_WORKTREE_PATH__` with the full path
26
+ *
27
+ * These globals are automatically read by RemoteLogClient when no
28
+ * explicit projectMarker/worktreePath options are provided.
29
+ * @returns A Vite plugin configuration object
30
+ * @example
31
+ * ```typescript
32
+ * // vite.config.ts
33
+ * import { remoteLoggerPlugin } from "@graphty/remote-logger/vite";
34
+ *
35
+ * export default defineConfig({
36
+ * plugins: [remoteLoggerPlugin()]
37
+ * });
38
+ * ```
39
+ */
40
+ export declare function remoteLoggerPlugin(): VitePlugin;
41
+ export {};
42
+ //# sourceMappingURL=plugin.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"plugin.d.ts","sourceRoot":"","sources":["../../src/vite/plugin.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AAIH;;;GAGG;AACH,UAAU,UAAU;IAChB,IAAI,EAAE,MAAM,CAAC;IACb,MAAM,EAAE,MAAM;QACV,MAAM,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;KAClC,CAAC;CACL;AAED;;;;;;;;;;;;;;;;;;;;GAoBG;AACH,wBAAgB,kBAAkB,IAAI,UAAU,CAe/C"}
@@ -0,0 +1,46 @@
1
+ /**
2
+ * Vite plugin for automatic project marker injection.
3
+ *
4
+ * This plugin injects global variables that the RemoteLogClient
5
+ * can use to automatically identify which project/worktree logs
6
+ * are coming from.
7
+ * @module vite/plugin
8
+ */
9
+ import { extractMarkerFromPath } from "../server/marker-utils.js";
10
+ /**
11
+ * Creates a Vite plugin that injects project marker globals.
12
+ *
13
+ * The plugin detects the current working directory and:
14
+ * 1. Extracts a project marker (worktree name or directory basename)
15
+ * 2. Injects `__REMOTE_LOG_PROJECT_MARKER__` with the marker
16
+ * 3. Injects `__REMOTE_LOG_WORKTREE_PATH__` with the full path
17
+ *
18
+ * These globals are automatically read by RemoteLogClient when no
19
+ * explicit projectMarker/worktreePath options are provided.
20
+ * @returns A Vite plugin configuration object
21
+ * @example
22
+ * ```typescript
23
+ * // vite.config.ts
24
+ * import { remoteLoggerPlugin } from "@graphty/remote-logger/vite";
25
+ *
26
+ * export default defineConfig({
27
+ * plugins: [remoteLoggerPlugin()]
28
+ * });
29
+ * ```
30
+ */
31
+ export function remoteLoggerPlugin() {
32
+ return {
33
+ name: "remote-logger",
34
+ config() {
35
+ const cwd = process.cwd();
36
+ const marker = extractMarkerFromPath(cwd);
37
+ return {
38
+ define: {
39
+ __REMOTE_LOG_PROJECT_MARKER__: JSON.stringify(marker),
40
+ __REMOTE_LOG_WORKTREE_PATH__: JSON.stringify(cwd),
41
+ },
42
+ };
43
+ },
44
+ };
45
+ }
46
+ //# sourceMappingURL=plugin.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"plugin.js","sourceRoot":"","sources":["../../src/vite/plugin.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AAEH,OAAO,EAAE,qBAAqB,EAAE,MAAM,2BAA2B,CAAC;AAalE;;;;;;;;;;;;;;;;;;;;GAoBG;AACH,MAAM,UAAU,kBAAkB;IAC9B,OAAO;QACH,IAAI,EAAE,eAAe;QACrB,MAAM;YACF,MAAM,GAAG,GAAG,OAAO,CAAC,GAAG,EAAE,CAAC;YAC1B,MAAM,MAAM,GAAG,qBAAqB,CAAC,GAAG,CAAC,CAAC;YAE1C,OAAO;gBACH,MAAM,EAAE;oBACJ,6BAA6B,EAAE,IAAI,CAAC,SAAS,CAAC,MAAM,CAAC;oBACrD,4BAA4B,EAAE,IAAI,CAAC,SAAS,CAAC,GAAG,CAAC;iBACpD;aACJ,CAAC;QACN,CAAC;KACJ,CAAC;AACN,CAAC"}
package/package.json CHANGED
@@ -1,10 +1,93 @@
1
1
  {
2
2
  "name": "@graphty/remote-logger",
3
- "version": "0.0.1",
4
- "description": "OIDC trusted publishing setup package for @graphty/remote-logger",
3
+ "version": "1.2.0",
4
+ "description": "Remote logging client and server for browser debugging",
5
+ "author": "Adam Powers <apowers@ato.ms>",
6
+ "main": "dist/index.js",
7
+ "type": "module",
8
+ "exports": {
9
+ ".": {
10
+ "import": "./dist/index.js",
11
+ "types": "./dist/index.d.ts"
12
+ },
13
+ "./server": {
14
+ "import": "./dist/server/index.js",
15
+ "types": "./dist/server/index.d.ts"
16
+ },
17
+ "./client": {
18
+ "import": "./dist/client/index.js",
19
+ "types": "./dist/client/index.d.ts"
20
+ },
21
+ "./ui": {
22
+ "import": "./dist/ui/index.js",
23
+ "types": "./dist/ui/index.d.ts"
24
+ },
25
+ "./mcp": {
26
+ "import": "./dist/mcp/index.js",
27
+ "types": "./dist/mcp/index.d.ts"
28
+ },
29
+ "./vite": {
30
+ "import": "./dist/vite/index.js",
31
+ "types": "./dist/vite/index.d.ts"
32
+ }
33
+ },
34
+ "types": "dist/index.d.ts",
35
+ "bin": {
36
+ "remote-log-server": "./bin/remote-log-server.js"
37
+ },
38
+ "files": [
39
+ "dist/",
40
+ "bin/",
41
+ "src/",
42
+ "README.md",
43
+ "LICENSE"
44
+ ],
45
+ "repository": {
46
+ "type": "git",
47
+ "url": "git+https://github.com/graphty-org/graphty-monorepo.git",
48
+ "directory": "remote-logger"
49
+ },
5
50
  "keywords": [
6
- "oidc",
7
- "trusted-publishing",
8
- "setup"
9
- ]
10
- }
51
+ "logging",
52
+ "remote-logging",
53
+ "debug",
54
+ "browser",
55
+ "server",
56
+ "typescript"
57
+ ],
58
+ "license": "MIT",
59
+ "publishConfig": {
60
+ "access": "public",
61
+ "provenance": true
62
+ },
63
+ "bugs": {
64
+ "url": "https://github.com/graphty-org/graphty-monorepo/issues"
65
+ },
66
+ "homepage": "https://github.com/graphty-org/graphty-monorepo/tree/master/remote-logger#readme",
67
+ "engines": {
68
+ "node": ">=18.19.0"
69
+ },
70
+ "dependencies": {
71
+ "@modelcontextprotocol/sdk": "^1.0.0",
72
+ "selfsigned": "^2.4.1",
73
+ "zod": "^3.25.0"
74
+ },
75
+ "devDependencies": {
76
+ "@types/node": "^20.0.0",
77
+ "@vitest/coverage-v8": "^3.2.3",
78
+ "typescript": "^5.8.3",
79
+ "vitest": "^3.2.3"
80
+ },
81
+ "scripts": {
82
+ "test": "vitest",
83
+ "test:run": "vitest run",
84
+ "coverage": "vitest run --coverage",
85
+ "coverage:preview": "npx serve coverage -p 9055",
86
+ "lint": "eslint && tsc --noEmit -p tsconfig.eslint.json",
87
+ "lint:fix": "eslint --fix",
88
+ "typecheck": "tsc --noEmit",
89
+ "build": "tsc",
90
+ "build:watch": "tsc --watch",
91
+ "dev": "tsc --watch"
92
+ }
93
+ }
@@ -0,0 +1,328 @@
1
+ /**
2
+ * Browser client for sending log messages to a remote server.
3
+ * Provides batching and automatic retry with exponential backoff.
4
+ * @module client/RemoteLogClient
5
+ */
6
+
7
+ import type { LogEntry, RemoteLogClientOptions, ThrottlePattern } from "./types.js";
8
+
9
+ /**
10
+ * Global variables that may be injected by the Vite plugin.
11
+ * These provide automatic project marker detection.
12
+ */
13
+ declare const __REMOTE_LOG_PROJECT_MARKER__: string | undefined;
14
+ declare const __REMOTE_LOG_WORKTREE_PATH__: string | undefined;
15
+
16
+ /**
17
+ * Safely read a global variable that may or may not be defined.
18
+ * @param name - Name of the global variable
19
+ * @returns The value of the global variable, or undefined if not defined
20
+ */
21
+ function getGlobalValue(name: "__REMOTE_LOG_PROJECT_MARKER__" | "__REMOTE_LOG_WORKTREE_PATH__"): string | undefined {
22
+ try {
23
+ if (name === "__REMOTE_LOG_PROJECT_MARKER__") {
24
+ return typeof __REMOTE_LOG_PROJECT_MARKER__ !== "undefined" ? __REMOTE_LOG_PROJECT_MARKER__ : undefined;
25
+ }
26
+ if (name === "__REMOTE_LOG_WORKTREE_PATH__") {
27
+ return typeof __REMOTE_LOG_WORKTREE_PATH__ !== "undefined" ? __REMOTE_LOG_WORKTREE_PATH__ : undefined;
28
+ }
29
+ } catch {
30
+ // ReferenceError if the global is not defined at all
31
+ return undefined;
32
+ }
33
+ return undefined;
34
+ }
35
+
36
+ /** Default configuration values */
37
+ const DEFAULT_BATCH_INTERVAL_MS = 1000;
38
+ const DEFAULT_MAX_RETRIES = 3;
39
+ const DEFAULT_RETRY_DELAY_MS = 1000;
40
+ const DEFAULT_SESSION_PREFIX = "session";
41
+
42
+ /**
43
+ * Generates a unique session ID with the given prefix.
44
+ * Format: {prefix}-{timestamp}-{random}
45
+ * @param prefix - The prefix to use for the session ID
46
+ * @returns A unique session ID string
47
+ */
48
+ function generateSessionId(prefix: string): string {
49
+ const timestamp = Date.now().toString(36);
50
+ const random = Math.random().toString(36).substring(2, 8);
51
+ return `${prefix}-${timestamp}-${random}`;
52
+ }
53
+
54
+ /**
55
+ * Client for sending log messages to a remote logging server.
56
+ *
57
+ * Features:
58
+ * - Batches multiple log entries before sending
59
+ * - Automatic retry with exponential backoff on network failures
60
+ * - Unique session ID for correlating logs
61
+ * @example
62
+ * ```typescript
63
+ * const client = new RemoteLogClient({
64
+ * serverUrl: "http://localhost:9080",
65
+ * sessionPrefix: "myapp",
66
+ * });
67
+ *
68
+ * client.log("INFO", "User logged in", { userId: 123 });
69
+ * client.log("DEBUG", "Loading data...");
70
+ *
71
+ * // Flush immediately when needed
72
+ * await client.flush();
73
+ *
74
+ * // Clean up when done
75
+ * await client.close();
76
+ * ```
77
+ */
78
+ export class RemoteLogClient {
79
+ /** Unique identifier for this logging session */
80
+ readonly sessionId: string;
81
+
82
+ private readonly serverUrl: string;
83
+ private readonly batchIntervalMs: number;
84
+ private readonly maxRetries: number;
85
+ private readonly retryDelayMs: number;
86
+ private readonly throttlePatterns: ThrottlePattern[];
87
+ private readonly projectMarker: string | undefined;
88
+ private readonly worktreePath: string | undefined;
89
+
90
+ private pendingLogs: LogEntry[] = [];
91
+ private batchTimer: ReturnType<typeof setTimeout> | null = null;
92
+ private isClosed = false;
93
+ private flushPromise: Promise<void> | null = null;
94
+
95
+ /** Tracks when each throttle pattern was last allowed through */
96
+ private throttleLastTimes = new Map<string, number>();
97
+
98
+ /**
99
+ * Creates a new RemoteLogClient.
100
+ * @param options - Configuration options
101
+ */
102
+ constructor(options: RemoteLogClientOptions) {
103
+ this.serverUrl = options.serverUrl;
104
+ this.sessionId = generateSessionId(options.sessionPrefix ?? DEFAULT_SESSION_PREFIX);
105
+ this.batchIntervalMs = options.batchIntervalMs ?? DEFAULT_BATCH_INTERVAL_MS;
106
+ this.maxRetries = options.maxRetries ?? DEFAULT_MAX_RETRIES;
107
+ this.retryDelayMs = options.retryDelayMs ?? DEFAULT_RETRY_DELAY_MS;
108
+ this.throttlePatterns = options.throttlePatterns ?? [];
109
+
110
+ // Priority: explicit option > global variable
111
+ this.projectMarker = options.projectMarker ?? getGlobalValue("__REMOTE_LOG_PROJECT_MARKER__");
112
+ this.worktreePath = options.worktreePath ?? getGlobalValue("__REMOTE_LOG_WORKTREE_PATH__");
113
+ }
114
+
115
+ /**
116
+ * Checks if a message should be throttled based on configured patterns.
117
+ * Updates the last time tracking if the message is allowed through.
118
+ * @param message - The message to check
119
+ * @returns true if the message should be dropped (throttled)
120
+ */
121
+ private shouldThrottle(message: string): boolean {
122
+ const now = Date.now();
123
+
124
+ for (const { pattern, intervalMs } of this.throttlePatterns) {
125
+ if (pattern.test(message)) {
126
+ const key = pattern.source;
127
+ const lastTime = this.throttleLastTimes.get(key) ?? 0;
128
+
129
+ if (now - lastTime < intervalMs) {
130
+ // Within throttle window, drop this message
131
+ return true;
132
+ }
133
+
134
+ // Outside throttle window, update timestamp and allow through
135
+ this.throttleLastTimes.set(key, now);
136
+ return false;
137
+ }
138
+ }
139
+
140
+ // No matching pattern, allow through
141
+ return false;
142
+ }
143
+
144
+ /**
145
+ * Logs a message at the specified level.
146
+ * @param level - Log level (e.g., "INFO", "DEBUG", "WARN", "ERROR")
147
+ * @param message - The log message
148
+ * @param data - Optional additional data to include
149
+ */
150
+ log(level: string, message: string, data?: Record<string, unknown>): void {
151
+ if (this.isClosed) {
152
+ return;
153
+ }
154
+
155
+ // Check throttling before adding to buffer
156
+ if (this.shouldThrottle(message)) {
157
+ return;
158
+ }
159
+
160
+ const entry: LogEntry = {
161
+ time: new Date().toISOString(),
162
+ level,
163
+ message,
164
+ ...(data !== undefined && { data }),
165
+ };
166
+
167
+ this.pendingLogs.push(entry);
168
+ this.scheduleBatchSend();
169
+ }
170
+
171
+ /**
172
+ * Schedules a batch send after the configured interval.
173
+ * If a timer is already scheduled, does nothing.
174
+ */
175
+ private scheduleBatchSend(): void {
176
+ if (this.batchTimer !== null || this.isClosed) {
177
+ return;
178
+ }
179
+
180
+ this.batchTimer = setTimeout(() => {
181
+ this.batchTimer = null;
182
+ void this.sendBatch();
183
+ }, this.batchIntervalMs);
184
+ }
185
+
186
+ /**
187
+ * Sends the current batch of logs to the server.
188
+ * Uses retry logic with exponential backoff on failure.
189
+ */
190
+ private async sendBatch(): Promise<void> {
191
+ if (this.pendingLogs.length === 0) {
192
+ return;
193
+ }
194
+
195
+ // Take the current logs and clear the pending array
196
+ const logsToSend = this.pendingLogs;
197
+ this.pendingLogs = [];
198
+
199
+ await this.sendWithRetry(logsToSend);
200
+ }
201
+
202
+ /**
203
+ * Sends logs with retry logic using exponential backoff.
204
+ * @param logs - The log entries to send
205
+ */
206
+ private async sendWithRetry(logs: LogEntry[]): Promise<void> {
207
+ let lastError: Error | null = null;
208
+
209
+ for (let attempt = 0; attempt <= this.maxRetries; attempt++) {
210
+ try {
211
+ await this.sendRequest(logs);
212
+ return; // Success!
213
+ } catch (error) {
214
+ lastError = error instanceof Error ? error : new Error(String(error));
215
+
216
+ if (attempt < this.maxRetries) {
217
+ // Exponential backoff: delay * 2^attempt
218
+ const delay = this.retryDelayMs * Math.pow(2, attempt);
219
+ await this.sleep(delay);
220
+ }
221
+ }
222
+ }
223
+
224
+ // All retries exhausted - log the error but don't throw
225
+ // In a browser context, we don't want to break the application
226
+ console.error("[RemoteLogClient] Failed to send logs after retries:", lastError?.message);
227
+ }
228
+
229
+ /**
230
+ * Makes the actual HTTP request to send logs.
231
+ * @param logs - The log entries to send
232
+ * @throws Error if the request fails
233
+ */
234
+ private async sendRequest(logs: LogEntry[]): Promise<void> {
235
+ const requestBody: {
236
+ sessionId: string;
237
+ logs: LogEntry[];
238
+ projectMarker?: string;
239
+ worktreePath?: string;
240
+ } = {
241
+ sessionId: this.sessionId,
242
+ logs,
243
+ };
244
+
245
+ // Only include these fields if they have values
246
+ if (this.projectMarker !== undefined) {
247
+ requestBody.projectMarker = this.projectMarker;
248
+ }
249
+ if (this.worktreePath !== undefined) {
250
+ requestBody.worktreePath = this.worktreePath;
251
+ }
252
+
253
+ const response = await fetch(`${this.serverUrl}/log`, {
254
+ method: "POST",
255
+ headers: {
256
+ "Content-Type": "application/json",
257
+ },
258
+ body: JSON.stringify(requestBody),
259
+ });
260
+
261
+ if (!response.ok) {
262
+ throw new Error(`HTTP ${response.status}: ${response.statusText}`);
263
+ }
264
+ }
265
+
266
+ /**
267
+ * Helper to sleep for the specified duration.
268
+ * @param ms - Milliseconds to sleep
269
+ * @returns A promise that resolves after the specified time
270
+ */
271
+ private sleep(ms: number): Promise<void> {
272
+ return new Promise((resolve) => setTimeout(resolve, ms));
273
+ }
274
+
275
+ /**
276
+ * Immediately flushes all pending logs to the server.
277
+ * Useful before page unload or when immediate delivery is needed.
278
+ */
279
+ async flush(): Promise<void> {
280
+ // Cancel any scheduled batch
281
+ if (this.batchTimer !== null) {
282
+ clearTimeout(this.batchTimer);
283
+ this.batchTimer = null;
284
+ }
285
+
286
+ // Wait for any in-progress flush
287
+ if (this.flushPromise !== null) {
288
+ await this.flushPromise;
289
+ }
290
+
291
+ // Send any remaining logs
292
+ if (this.pendingLogs.length > 0) {
293
+ this.flushPromise = this.sendBatch();
294
+ await this.flushPromise;
295
+ this.flushPromise = null;
296
+ }
297
+ }
298
+
299
+ /**
300
+ * Closes the client, flushing any pending logs and stopping the batch timer.
301
+ * After calling close(), no more logs will be accepted.
302
+ */
303
+ async close(): Promise<void> {
304
+ if (this.isClosed) {
305
+ return;
306
+ }
307
+
308
+ this.isClosed = true;
309
+
310
+ // Flush remaining logs
311
+ await this.flush();
312
+ }
313
+ }
314
+
315
+ /**
316
+ * Factory function to create a RemoteLogClient.
317
+ * @param options - Configuration options
318
+ * @returns A new RemoteLogClient instance
319
+ * @example
320
+ * ```typescript
321
+ * const client = createRemoteLogClient({
322
+ * serverUrl: "http://localhost:9080",
323
+ * });
324
+ * ```
325
+ */
326
+ export function createRemoteLogClient(options: RemoteLogClientOptions): RemoteLogClient {
327
+ return new RemoteLogClient(options);
328
+ }
@@ -0,0 +1,7 @@
1
+ /**
2
+ * Browser client for remote logging.
3
+ * @module client
4
+ */
5
+
6
+ export { createRemoteLogClient, RemoteLogClient } from "./RemoteLogClient.js";
7
+ export type { LogEntry, RemoteLogClientOptions, ThrottlePattern } from "./types.js";
@@ -0,0 +1,62 @@
1
+ /**
2
+ * Type definitions for the remote logging client.
3
+ * @module client/types
4
+ */
5
+
6
+ /**
7
+ * A single log entry to be sent to the remote server.
8
+ */
9
+ export interface LogEntry {
10
+ /** ISO 8601 timestamp when the log was created */
11
+ time: string;
12
+ /** Log level (e.g., "INFO", "DEBUG", "WARN", "ERROR") */
13
+ level: string;
14
+ /** The log message */
15
+ message: string;
16
+ /** Optional additional data to include with the log */
17
+ data?: Record<string, unknown>;
18
+ }
19
+
20
+ /**
21
+ * Configuration for throttling specific message patterns.
22
+ */
23
+ export interface ThrottlePattern {
24
+ /** Regular expression pattern to match log messages */
25
+ pattern: RegExp;
26
+ /** Minimum interval in milliseconds between matching messages */
27
+ intervalMs: number;
28
+ }
29
+
30
+ /**
31
+ * Configuration options for the RemoteLogClient.
32
+ */
33
+ export interface RemoteLogClientOptions {
34
+ /** URL of the remote log server (e.g., "http://localhost:9080") */
35
+ serverUrl: string;
36
+ /** Prefix for the generated session ID (default: "session") */
37
+ sessionPrefix?: string;
38
+ /** Interval in milliseconds between batch sends (default: 1000) */
39
+ batchIntervalMs?: number;
40
+ /** Maximum number of retry attempts for failed sends (default: 3) */
41
+ maxRetries?: number;
42
+ /** Base delay in milliseconds between retries (uses exponential backoff) (default: 1000) */
43
+ retryDelayMs?: number;
44
+ /**
45
+ * Patterns to throttle to prevent log flooding.
46
+ * Messages matching a pattern will only be sent once per the configured interval.
47
+ */
48
+ throttlePatterns?: ThrottlePattern[];
49
+ /**
50
+ * Project marker to identify logs from this project.
51
+ * If not provided, the client will attempt to read from the
52
+ * __REMOTE_LOG_PROJECT_MARKER__ global variable (injected by Vite plugin).
53
+ */
54
+ projectMarker?: string;
55
+ /**
56
+ * Full path to the worktree or project directory.
57
+ * Used for debugging and log organization.
58
+ * If not provided, the client will attempt to read from the
59
+ * __REMOTE_LOG_WORKTREE_PATH__ global variable (injected by Vite plugin).
60
+ */
61
+ worktreePath?: string;
62
+ }
package/src/index.ts ADDED
@@ -0,0 +1,28 @@
1
+ /**
2
+ * Remote logging client and server for browser debugging.
3
+ *
4
+ * Client usage (Browser):
5
+ * import { RemoteLogClient } from "@graphty/remote-logger";
6
+ * const client = new RemoteLogClient({ serverUrl: "http://localhost:9080" });
7
+ * client.log("INFO", "Hello from browser");
8
+ *
9
+ * Server usage (Node.js):
10
+ * import { startLogServer } from "@graphty/remote-logger/server";
11
+ * startLogServer({ port: 9080 });
12
+ *
13
+ * Or via CLI:
14
+ * npx remote-log-server --port 9080
15
+ *
16
+ * UI usage (Browser):
17
+ * import { initConsoleCaptureUI } from "@graphty/remote-logger/ui";
18
+ * initConsoleCaptureUI();
19
+ */
20
+
21
+ // Client exports (primary exports for browser usage)
22
+ // Note: Server components are NOT re-exported here because they use Node.js APIs.
23
+ // Import from "@graphty/remote-logger/server" for server-side usage.
24
+ export type { LogEntry, RemoteLogClientOptions, ThrottlePattern } from "./client/index.js";
25
+ export { createRemoteLogClient, RemoteLogClient } from "./client/index.js";
26
+
27
+ // Note: UI components are NOT re-exported here to keep the main entry lightweight.
28
+ // Import from "@graphty/remote-logger/ui" for UI usage.
@@ -0,0 +1,25 @@
1
+ /**
2
+ * MCP server module exports.
3
+ *
4
+ * Provides Model Context Protocol interface for log queries.
5
+ * @module mcp
6
+ */
7
+
8
+ export { createMcpServer, getToolNames, startMcpServer } from "./mcp-server.js";
9
+ export {
10
+ logsGetRecentHandler,
11
+ type LogsGetRecentInput,
12
+ logsGetRecentInputSchema,
13
+ type LogsGetRecentOutput,
14
+ logsGetRecentTool,
15
+ logsListSessionsHandler,
16
+ type LogsListSessionsInput,
17
+ logsListSessionsInputSchema,
18
+ type LogsListSessionsOutput,
19
+ logsListSessionsTool,
20
+ logsStatusHandler,
21
+ type LogsStatusInput,
22
+ logsStatusInputSchema,
23
+ type LogsStatusOutput,
24
+ logsStatusTool,
25
+ } from "./tools/index.js";