pi-lens 3.1.2 → 3.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 (154) hide show
  1. package/CHANGELOG.md +55 -0
  2. package/README.md +16 -12
  3. package/clients/ast-grep-client.js +8 -1
  4. package/clients/ast-grep-client.ts +9 -1
  5. package/clients/biome-client.js +51 -38
  6. package/clients/biome-client.ts +60 -58
  7. package/clients/dependency-checker.js +30 -1
  8. package/clients/dependency-checker.ts +35 -1
  9. package/clients/dispatch/__tests__/runner-registration.test.ts +286 -282
  10. package/clients/dispatch/bus-dispatcher.js +15 -14
  11. package/clients/dispatch/bus-dispatcher.ts +32 -25
  12. package/clients/dispatch/dispatcher.js +18 -25
  13. package/clients/dispatch/dispatcher.test.ts +2 -1
  14. package/clients/dispatch/dispatcher.ts +17 -28
  15. package/clients/dispatch/plan.js +77 -32
  16. package/clients/dispatch/plan.ts +78 -32
  17. package/clients/dispatch/runners/ast-grep-napi.js +36 -376
  18. package/clients/dispatch/runners/ast-grep-napi.ts +60 -433
  19. package/clients/dispatch/runners/index.js +8 -4
  20. package/clients/dispatch/runners/index.ts +8 -4
  21. package/clients/dispatch/runners/lsp.js +65 -0
  22. package/clients/dispatch/runners/lsp.ts +125 -0
  23. package/clients/dispatch/runners/oxlint.js +2 -2
  24. package/clients/dispatch/runners/oxlint.ts +2 -2
  25. package/clients/dispatch/runners/pyright.js +24 -8
  26. package/clients/dispatch/runners/pyright.ts +28 -14
  27. package/clients/dispatch/runners/rust-clippy.js +2 -2
  28. package/clients/dispatch/runners/rust-clippy.ts +2 -4
  29. package/clients/dispatch/runners/tree-sitter.js +14 -2
  30. package/clients/dispatch/runners/tree-sitter.ts +15 -2
  31. package/clients/dispatch/runners/ts-lsp.js +3 -3
  32. package/clients/dispatch/runners/ts-lsp.ts +8 -5
  33. package/clients/dispatch/runners/yaml-rule-parser.js +292 -0
  34. package/clients/dispatch/runners/yaml-rule-parser.ts +338 -0
  35. package/clients/dispatch/types.js +3 -0
  36. package/clients/dispatch/types.ts +3 -0
  37. package/clients/formatters.js +67 -14
  38. package/clients/formatters.ts +68 -15
  39. package/clients/installer/index.js +78 -10
  40. package/clients/installer/index.ts +519 -426
  41. package/clients/jscpd-client.js +28 -0
  42. package/clients/jscpd-client.ts +41 -3
  43. package/clients/knip-client.js +30 -1
  44. package/clients/knip-client.ts +34 -2
  45. package/clients/lsp/__tests__/client.test.ts +64 -41
  46. package/clients/lsp/__tests__/config.test.ts +25 -17
  47. package/clients/lsp/__tests__/launch.test.ts +108 -43
  48. package/clients/lsp/__tests__/service.test.ts +76 -48
  49. package/clients/lsp/client.js +87 -2
  50. package/clients/lsp/client.ts +150 -6
  51. package/clients/lsp/config.js +8 -11
  52. package/clients/lsp/config.ts +24 -21
  53. package/clients/lsp/index.js +69 -0
  54. package/clients/lsp/index.ts +82 -0
  55. package/clients/lsp/interactive-install.js +19 -8
  56. package/clients/lsp/interactive-install.ts +52 -27
  57. package/clients/lsp/launch.js +182 -32
  58. package/clients/lsp/launch.ts +241 -38
  59. package/clients/lsp/path-utils.js +3 -46
  60. package/clients/lsp/path-utils.ts +11 -51
  61. package/clients/lsp/server.js +93 -71
  62. package/clients/lsp/server.ts +173 -131
  63. package/clients/path-utils.js +142 -0
  64. package/clients/path-utils.ts +153 -0
  65. package/clients/ruff-client.js +33 -4
  66. package/clients/ruff-client.ts +44 -13
  67. package/clients/safe-spawn.js +3 -1
  68. package/clients/safe-spawn.ts +3 -1
  69. package/clients/services/effect-integration.js +11 -7
  70. package/clients/services/effect-integration.ts +34 -26
  71. package/clients/sg-runner.js +51 -9
  72. package/clients/sg-runner.ts +58 -15
  73. package/clients/tree-sitter-client.js +12 -0
  74. package/clients/tree-sitter-client.ts +12 -0
  75. package/clients/typescript-client.js +6 -2
  76. package/clients/typescript-client.ts +9 -2
  77. package/commands/booboo.js +2 -4
  78. package/commands/booboo.ts +2 -4
  79. package/index.ts +377 -93
  80. package/package.json +2 -1
  81. package/rules/tree-sitter-queries/tsx/no-nested-links.yml +45 -0
  82. package/rules/tree-sitter-queries/typescript/constructor-super.yml +55 -0
  83. package/rules/tree-sitter-queries/typescript/debugger.yml +1 -1
  84. package/rules/tree-sitter-queries/typescript/no-dupe-class-members.yml +47 -0
  85. package/tsconfig.json +1 -1
  86. package/clients/__tests__/file-time.test.js +0 -216
  87. package/clients/__tests__/format-service.test.js +0 -245
  88. package/clients/__tests__/formatters.test.js +0 -271
  89. package/clients/agent-behavior-client.test.js +0 -94
  90. package/clients/ast-grep-client.test.js +0 -129
  91. package/clients/ast-grep-client.test.ts +0 -155
  92. package/clients/biome-client.test.js +0 -144
  93. package/clients/cache-manager.test.js +0 -197
  94. package/clients/complexity-client.test.js +0 -234
  95. package/clients/dependency-checker.test.js +0 -60
  96. package/clients/dispatch/__tests__/autofix-integration.test.js +0 -245
  97. package/clients/dispatch/__tests__/runner-registration.test.js +0 -236
  98. package/clients/dispatch/dispatcher.edge.test.js +0 -82
  99. package/clients/dispatch/dispatcher.format.test.js +0 -46
  100. package/clients/dispatch/dispatcher.inline.test.js +0 -74
  101. package/clients/dispatch/dispatcher.test.js +0 -115
  102. package/clients/dispatch/runners/architect.test.js +0 -138
  103. package/clients/dispatch/runners/ast-grep-napi.test.js +0 -106
  104. package/clients/dispatch/runners/oxlint.test.js +0 -230
  105. package/clients/dispatch/runners/pyright.test.js +0 -98
  106. package/clients/dispatch/runners/python-slop.test.js +0 -203
  107. package/clients/dispatch/runners/scan_codebase.test.js +0 -89
  108. package/clients/dispatch/runners/shellcheck.test.js +0 -98
  109. package/clients/dispatch/runners/spellcheck.test.js +0 -158
  110. package/clients/dispatch/runners/ts-slop.test.js +0 -180
  111. package/clients/dispatch/runners/ts-slop.test.ts +0 -230
  112. package/clients/dogfood.test.js +0 -201
  113. package/clients/file-kinds.test.js +0 -169
  114. package/clients/go-client.test.js +0 -127
  115. package/clients/jscpd-client.test.js +0 -127
  116. package/clients/knip-client.test.js +0 -112
  117. package/clients/lsp/__tests__/client.test.js +0 -325
  118. package/clients/lsp/__tests__/config.test.js +0 -166
  119. package/clients/lsp/__tests__/error-recovery.test.js +0 -213
  120. package/clients/lsp/__tests__/integration.test.js +0 -127
  121. package/clients/lsp/__tests__/launch.test.js +0 -260
  122. package/clients/lsp/__tests__/server.test.js +0 -259
  123. package/clients/lsp/__tests__/service.test.js +0 -417
  124. package/clients/metrics-client.test.js +0 -141
  125. package/clients/ruff-client.test.js +0 -132
  126. package/clients/rust-client.test.js +0 -108
  127. package/clients/sanitize.test.js +0 -177
  128. package/clients/secrets-scanner.test.js +0 -100
  129. package/clients/services/__tests__/effect-integration.test.js +0 -86
  130. package/clients/test-runner-client.test.js +0 -192
  131. package/clients/todo-scanner.test.js +0 -301
  132. package/clients/type-coverage-client.test.js +0 -105
  133. package/clients/typescript-client.codefix.test.js +0 -157
  134. package/clients/typescript-client.test.js +0 -105
  135. package/commands/clients/ast-grep-client.js +0 -250
  136. package/commands/clients/ast-grep-parser.js +0 -86
  137. package/commands/clients/ast-grep-rule-manager.js +0 -91
  138. package/commands/clients/ast-grep-types.js +0 -9
  139. package/commands/clients/biome-client.js +0 -380
  140. package/commands/clients/complexity-client.js +0 -667
  141. package/commands/clients/file-kinds.js +0 -177
  142. package/commands/clients/file-utils.js +0 -40
  143. package/commands/clients/jscpd-client.js +0 -169
  144. package/commands/clients/knip-client.js +0 -211
  145. package/commands/clients/ruff-client.js +0 -297
  146. package/commands/clients/safe-spawn.js +0 -88
  147. package/commands/clients/scan-utils.js +0 -83
  148. package/commands/clients/sg-runner.js +0 -190
  149. package/commands/clients/types.js +0 -11
  150. package/commands/clients/typescript-client.js +0 -505
  151. package/commands/rate.test.js +0 -119
  152. package/rules/ast-grep-rules/rules/no-dangerously-set-inner-html.yml +0 -13
  153. package/rules/ast-grep-rules/rules/no-debugger.yml +0 -12
  154. package/rules/ast-grep-rules/rules/no-eval.yml +0 -13
@@ -1,213 +0,0 @@
1
- /**
2
- * LSP Error Recovery Tests
3
- *
4
- * Tests for LSP failure scenarios and recovery mechanisms.
5
- * Critical for stability in real-world usage.
6
- */
7
- import { Effect } from "effect";
8
- import { afterEach, beforeEach, describe, expect, it } from "vitest";
9
- import { getLSPService, resetLSPService } from "../index.js";
10
- // Check if we should run real LSP tests
11
- const runRealLSPTests = process.env.RUN_REAL_LSP_TESTS === "true";
12
- describe("LSP Error Recovery", () => {
13
- let service;
14
- beforeEach(() => {
15
- resetLSPService();
16
- service = getLSPService();
17
- });
18
- afterEach(async () => {
19
- await service.shutdown();
20
- resetLSPService();
21
- });
22
- describe("Spawn Failures", () => {
23
- it("should handle LSP spawn failure gracefully", async () => {
24
- // Simulate spawn failure by using invalid command
25
- const result = await service.hasLSP("/test/invalid-file.xyz");
26
- // Should return false without throwing
27
- expect(result).toBe(false);
28
- });
29
- it("should handle missing LSP server binary", async () => {
30
- // Test with a file type that has no installed LSP
31
- const result = await service.hasLSP("/test/file.unknown");
32
- expect(result).toBe(false);
33
- });
34
- it("should handle permission denied on spawn", async () => {
35
- // This would require mocking at a lower level
36
- // For now, just verify it doesn't crash
37
- await expect(service.openFile("/test.ts", "content")).resolves.not.toThrow();
38
- });
39
- });
40
- describe("Runtime Crashes", () => {
41
- it("should handle LSP crash during operation", async () => {
42
- // Open a file first
43
- await service.openFile("/test.ts", "const x = 1;");
44
- // Simulate crash by shutting down abruptly
45
- await service.shutdown();
46
- // Subsequent operations should handle gracefully
47
- const diags = await service.getDiagnostics("/test.ts");
48
- expect(diags).toEqual([]);
49
- });
50
- it("should handle multiple rapid shutdown calls", async () => {
51
- // First shutdown
52
- await expect(service.shutdown()).resolves.not.toThrow();
53
- // Second shutdown should also not throw
54
- await expect(service.shutdown()).resolves.not.toThrow();
55
- // Third shutdown
56
- await expect(service.shutdown()).resolves.not.toThrow();
57
- });
58
- it("should handle getDiagnostics on crashed server", async () => {
59
- // Get diagnostics without opening (simulates crash state)
60
- const diags = await service.getDiagnostics("/nonexistent/crashed.ts");
61
- expect(diags).toEqual([]);
62
- });
63
- });
64
- describe("Root Detection Edge Cases", () => {
65
- it("should exclude .pi-lens from root detection", async () => {
66
- // This was a real bug where .pi-lens/tools/package.json was found as root
67
- // We verify the config excludes .pi-lens
68
- const { getAllServers } = await import("../config.js");
69
- const servers = getAllServers();
70
- // Should return array (verification that config loads)
71
- expect(Array.isArray(servers)).toBe(true);
72
- });
73
- it("should handle deeply nested file paths", async () => {
74
- const deepPath = "/very/deep/nested/path/to/the/file.ts";
75
- // Should not throw on deep paths
76
- await expect(service.openFile(deepPath, "content")).resolves.not.toThrow();
77
- await expect(service.getDiagnostics(deepPath)).resolves.not.toThrow();
78
- });
79
- it("should handle paths with special characters", async () => {
80
- const specialPaths = [
81
- "/path with spaces/file.ts",
82
- "/path-with-dashes/file.ts",
83
- "/path_with_underscores/file.ts",
84
- "/path.with.dots/file.ts",
85
- ];
86
- for (const path of specialPaths) {
87
- await expect(service.openFile(path, "content")).resolves.not.toThrow();
88
- }
89
- });
90
- });
91
- describe("Timeout Handling", () => {
92
- it("should handle slow LSP operations", async () => {
93
- // Create a mock slow operation
94
- const slowPromise = new Promise((resolve) => {
95
- setTimeout(() => resolve("done"), 5000);
96
- });
97
- // Should not hang indefinitely
98
- const timeoutPromise = Promise.race([
99
- slowPromise,
100
- new Promise((_, reject) => setTimeout(() => reject(new Error("Timeout")), 100)),
101
- ]);
102
- await expect(timeoutPromise).rejects.toThrow("Timeout");
103
- });
104
- it("should handle hanging getDiagnostics", async () => {
105
- // Start diagnostics request
106
- const diagPromise = service.getDiagnostics("/test.ts");
107
- // Should complete (even if empty) within reasonable time
108
- const result = await Promise.race([
109
- diagPromise,
110
- new Promise((resolve) => setTimeout(() => resolve("timeout"), 1000)),
111
- ]);
112
- // Either completes or times out gracefully
113
- expect(result).toBeDefined();
114
- });
115
- });
116
- describe("Multiple LSP Coordination", () => {
117
- it("should handle multiple LSPs running simultaneously", async () => {
118
- // This tests that multiple LSP servers don't interfere
119
- const files = [
120
- { path: "/test.ts", content: "const x: number = 1;" },
121
- { path: "/test.py", content: "x = 1" },
122
- { path: "/test.rs", content: "let x = 1;" },
123
- ];
124
- // Open multiple files
125
- for (const file of files) {
126
- await expect(service.openFile(file.path, file.content)).resolves.not.toThrow();
127
- }
128
- // Get diagnostics for all
129
- for (const file of files) {
130
- const diags = await service.getDiagnostics(file.path);
131
- expect(Array.isArray(diags)).toBe(true);
132
- }
133
- });
134
- it("should handle rapid file switching", async () => {
135
- const files = ["/a.ts", "/b.ts", "/c.ts"];
136
- // Rapidly switch between files
137
- for (let i = 0; i < 10; i++) {
138
- const file = files[i % files.length];
139
- await service.openFile(file, `content ${i}`);
140
- await service.getDiagnostics(file);
141
- }
142
- // Should not crash or hang
143
- expect(true).toBe(true);
144
- });
145
- });
146
- describe("Effect Integration Error Handling", () => {
147
- it("should handle errors in Effect context", async () => {
148
- const { lspEffect } = await import("../index.js");
149
- // Try to get LSP for non-existent file type
150
- const { hasLSP } = lspEffect(service);
151
- const program = hasLSP("/test.unknownxyz");
152
- // Should complete without throwing
153
- const result = await Effect.runPromise(program);
154
- expect(typeof result).toBe("boolean");
155
- });
156
- it("should recover from Effect failures", async () => {
157
- const { lspEffect } = await import("../index.js");
158
- // Shutdown then try operations
159
- await service.shutdown();
160
- const { shutdown } = lspEffect(service);
161
- const program = shutdown();
162
- // Should not throw even after shutdown
163
- await expect(Effect.runPromise(program)).resolves.not.toThrow();
164
- });
165
- });
166
- });
167
- // Real server tests - these require actual LSP servers
168
- // These catch real-world issues like the ESLintServer spawn error
169
- describe.skipIf(!runRealLSPTests)("Real Server Error Recovery", () => {
170
- let service;
171
- beforeEach(() => {
172
- resetLSPService();
173
- service = getLSPService();
174
- });
175
- afterEach(async () => {
176
- await service.shutdown();
177
- resetLSPService();
178
- });
179
- it("should handle real TypeScript LSP spawn", async () => {
180
- const hasTsLsp = await service.hasLSP("/test.ts");
181
- if (hasTsLsp) {
182
- // If installed, should be able to open and diagnose
183
- await service.openFile("/test.ts", "const x: string = 1;");
184
- const diags = await service.getDiagnostics("/test.ts");
185
- // Should get type error
186
- expect(diags.length).toBeGreaterThan(0);
187
- expect(diags[0].message).toContain("Type");
188
- }
189
- });
190
- it("should handle real Python LSP spawn", async () => {
191
- const hasPyLsp = await service.hasLSP("/test.py");
192
- if (hasPyLsp) {
193
- await service.openFile("/test.py", "x = 1\nprint(y)"); // y is undefined
194
- const diags = await service.getDiagnostics("/test.py");
195
- // Should have errors about undefined y
196
- expect(diags.length).toBeGreaterThan(0);
197
- }
198
- });
199
- it("should restart crashed LSP server", async () => {
200
- const hasTsLsp = await service.hasLSP("/test.ts");
201
- if (hasTsLsp) {
202
- // Open file
203
- await service.openFile("/test.ts", "const x = 1;");
204
- // Get diagnostics (server should be running)
205
- const _diags1 = await service.getDiagnostics("/test.ts");
206
- // Shutdown (simulates crash)
207
- await service.shutdown();
208
- // Try to use again - should handle gracefully
209
- const diags2 = await service.getDiagnostics("/test.ts");
210
- expect(Array.isArray(diags2)).toBe(true);
211
- }
212
- });
213
- });
@@ -1,127 +0,0 @@
1
- /**
2
- * LSP Integration Test Suite
3
- *
4
- * End-to-end tests for the LSP system including:
5
- * - Full workflow: detect -> spawn -> open -> diagnose -> shutdown
6
- * - Multiple server coordination
7
- * - Error recovery scenarios
8
- * - Real TypeScript server integration (optional)
9
- */
10
- import { describe, it, expect, beforeEach, afterEach } from "vitest";
11
- import { getLSPService, resetLSPService } from "../index.js";
12
- import { Effect } from "effect";
13
- // Check if we should run real LSP tests
14
- const runRealLSPTests = process.env.RUN_REAL_LSP_TESTS === "true";
15
- describe("LSP Integration", () => {
16
- let service;
17
- beforeEach(() => {
18
- resetLSPService();
19
- service = getLSPService();
20
- });
21
- afterEach(async () => {
22
- await service.shutdown();
23
- resetLSPService();
24
- });
25
- describe("Service Lifecycle", () => {
26
- it("should handle complete lifecycle without errors", async () => {
27
- // This is a basic smoke test
28
- const hasLSP = await service.hasLSP("/test.ts");
29
- // Result depends on whether TypeScript LSP is installed
30
- // Just verify it doesn't throw
31
- expect(typeof hasLSP).toBe("boolean");
32
- });
33
- it("should handle multiple shutdown calls gracefully", async () => {
34
- // First shutdown
35
- await expect(service.shutdown()).resolves.not.toThrow();
36
- // Second shutdown should also not throw
37
- await expect(service.shutdown()).resolves.not.toThrow();
38
- });
39
- it("should report status correctly", async () => {
40
- const status = service.getStatus();
41
- // Should return array (may be empty if no clients active)
42
- expect(Array.isArray(status)).toBe(true);
43
- });
44
- });
45
- describe("Effect Integration", () => {
46
- it("should run hasLSP effect successfully", async () => {
47
- const { hasLSP } = await import("../index.js").then((m) => m.lspEffect(service));
48
- const program = hasLSP("/test.ts");
49
- const result = await Effect.runPromise(program);
50
- expect(typeof result).toBe("boolean");
51
- });
52
- it("should run shutdown effect successfully", async () => {
53
- const { shutdown } = await import("../index.js").then((m) => m.lspEffect(service));
54
- const program = shutdown();
55
- const result = await Effect.runPromise(program);
56
- expect(result).toBeUndefined();
57
- });
58
- });
59
- describe("Error Handling", () => {
60
- it("should handle operations on non-existent files", async () => {
61
- await expect(service.openFile("/nonexistent/file.ts", "content"))
62
- .resolves.not.toThrow();
63
- });
64
- it("should handle getDiagnostics on non-existent files", async () => {
65
- const diags = await service.getDiagnostics("/nonexistent/file.ts");
66
- expect(diags).toEqual([]);
67
- });
68
- it("should handle updateFile on non-existent files", async () => {
69
- await expect(service.updateFile("/nonexistent/file.ts", "new content"))
70
- .resolves.not.toThrow();
71
- });
72
- });
73
- });
74
- // Real server tests - these require actual LSP servers to be installed
75
- // Run with: RUN_REAL_LSP_TESTS=true npm test
76
- describe.skipIf(!runRealLSPTests)("Real Server Tests", () => {
77
- let service;
78
- beforeEach(() => {
79
- resetLSPService();
80
- service = getLSPService();
81
- });
82
- afterEach(async () => {
83
- await service.shutdown();
84
- resetLSPService();
85
- });
86
- it("should detect TypeScript LSP if available", async () => {
87
- const hasLSP = await service.hasLSP(process.cwd() + "/test.ts");
88
- if (hasLSP) {
89
- console.log("✅ TypeScript LSP detected");
90
- }
91
- else {
92
- console.log("⚠️ TypeScript LSP not available");
93
- }
94
- });
95
- });
96
- describe("Concurrent Operations", () => {
97
- let service;
98
- beforeEach(() => {
99
- resetLSPService();
100
- service = getLSPService();
101
- });
102
- afterEach(async () => {
103
- await service.shutdown();
104
- resetLSPService();
105
- });
106
- it("should handle concurrent hasLSP checks", async () => {
107
- const checks = [
108
- service.hasLSP("/file1.ts"),
109
- service.hasLSP("/file2.ts"),
110
- service.hasLSP("/file3.ts"),
111
- ];
112
- const results = await Promise.all(checks);
113
- expect(results).toHaveLength(3);
114
- results.forEach((r) => expect(typeof r).toBe("boolean"));
115
- });
116
- it("should handle concurrent diagnostics requests", async () => {
117
- // These should not throw even if files don't exist
118
- const requests = [
119
- service.getDiagnostics("/file1.ts"),
120
- service.getDiagnostics("/file2.ts"),
121
- service.getDiagnostics("/file3.ts"),
122
- ];
123
- const results = await Promise.all(requests);
124
- expect(results).toHaveLength(3);
125
- results.forEach((r) => expect(Array.isArray(r)).toBe(true));
126
- });
127
- });
@@ -1,260 +0,0 @@
1
- /**
2
- * LSP Launch Utilities Test Suite
3
- *
4
- * Tests for launching LSP servers including:
5
- * - Direct binary execution
6
- * - Package manager execution (npx/bun)
7
- * - Node.js script execution
8
- * - Python module execution
9
- * - Process cleanup
10
- */
11
- import { describe, it, expect, beforeEach, afterEach, vi } from "vitest";
12
- import { spawn } from "child_process";
13
- import { launchLSP, launchViaPackageManager, launchViaNode, launchViaPython, stopLSP, } from "../launch.js";
14
- // Mock child_process
15
- vi.mock("child_process", () => ({
16
- spawn: vi.fn(),
17
- }));
18
- const mockSpawn = vi.mocked(spawn);
19
- // Helper to create mock child process
20
- function createMockChildProcess(pid = 123) {
21
- return {
22
- pid,
23
- stdin: { write: vi.fn() },
24
- stdout: { on: vi.fn(), pipe: vi.fn() },
25
- stderr: { on: vi.fn(), pipe: vi.fn() },
26
- kill: vi.fn(),
27
- on: vi.fn(),
28
- connected: true,
29
- };
30
- }
31
- describe("launchLSP", () => {
32
- beforeEach(() => {
33
- vi.clearAllMocks();
34
- });
35
- it("should spawn process with correct parameters", async () => {
36
- const mockProcess = createMockChildProcess();
37
- mockSpawn.mockReturnValue(mockProcess);
38
- launchLSP("typescript-language-server", ["--stdio"], { cwd: "/test" });
39
- expect(mockSpawn).toHaveBeenCalled();
40
- const [cmd, args, options] = mockSpawn.mock.calls[0];
41
- // Command should be provided (format depends on platform)
42
- expect(cmd).toBeTruthy();
43
- expect(options).toMatchObject({
44
- cwd: "/test",
45
- stdio: ["pipe", "pipe", "pipe"],
46
- detached: false,
47
- windowsHide: true,
48
- });
49
- });
50
- it("should merge environment variables", async () => {
51
- const mockProcess = createMockChildProcess();
52
- mockSpawn.mockReturnValue(mockProcess);
53
- const customEnv = { CUSTOM_VAR: "value" };
54
- launchLSP("server", [], { env: customEnv });
55
- const [, , options] = mockSpawn.mock.calls[0];
56
- expect(options?.env).toMatchObject({
57
- CUSTOM_VAR: "value",
58
- });
59
- });
60
- it("should return LSPProcess with all streams", async () => {
61
- const mockProcess = createMockChildProcess(456);
62
- mockSpawn.mockReturnValue(mockProcess);
63
- const result = launchLSP("server", [], {});
64
- expect(result.pid).toBe(456);
65
- expect(result.stdin).toBeDefined();
66
- expect(result.stdout).toBeDefined();
67
- expect(result.stderr).toBeDefined();
68
- });
69
- it("should throw if stdin is not available", async () => {
70
- const mockProcess = { ...createMockChildProcess(), stdin: null };
71
- mockSpawn.mockReturnValue(mockProcess);
72
- expect(() => launchLSP("server", [], {})).toThrow("Failed to spawn LSP server");
73
- });
74
- it("should throw if stdout is not available", async () => {
75
- const mockProcess = { ...createMockChildProcess(), stdout: null };
76
- mockSpawn.mockReturnValue(mockProcess);
77
- expect(() => launchLSP("server", [], {})).toThrow("Failed to spawn LSP server");
78
- });
79
- it("should throw if stderr is not available", async () => {
80
- const mockProcess = { ...createMockChildProcess(), stderr: null };
81
- mockSpawn.mockReturnValue(mockProcess);
82
- expect(() => launchLSP("server", [], {})).toThrow("Failed to spawn LSP server");
83
- });
84
- it("should default to process.cwd() when cwd not provided", async () => {
85
- const mockProcess = createMockChildProcess();
86
- mockSpawn.mockReturnValue(mockProcess);
87
- launchLSP("server", [], {});
88
- const [, , options] = mockSpawn.mock.calls[0];
89
- expect(options?.cwd).toBe(process.cwd());
90
- });
91
- it("should use shell mode on Windows for .cmd files", async () => {
92
- const mockProcess = createMockChildProcess();
93
- mockSpawn.mockReturnValue(mockProcess);
94
- // Save original platform
95
- const originalPlatform = Object.getOwnPropertyDescriptor(process, "platform");
96
- Object.defineProperty(process, "platform", { value: "win32" });
97
- try {
98
- launchLSP("server.cmd", ["--arg"], {});
99
- const [, , options] = mockSpawn.mock.calls[0];
100
- expect(options?.shell).toBe(true);
101
- }
102
- finally {
103
- // Restore original platform
104
- if (originalPlatform) {
105
- Object.defineProperty(process, "platform", originalPlatform);
106
- }
107
- }
108
- });
109
- });
110
- describe("launchViaPackageManager", () => {
111
- beforeEach(() => {
112
- vi.clearAllMocks();
113
- // Clear BUN_INSTALL env var
114
- delete process.env.BUN_INSTALL;
115
- });
116
- it("should spawn via package manager", async () => {
117
- const mockProcess = createMockChildProcess();
118
- mockSpawn.mockReturnValue(mockProcess);
119
- launchViaPackageManager("typescript-language-server", ["--stdio"], {});
120
- expect(mockSpawn).toHaveBeenCalled();
121
- const [cmd] = mockSpawn.mock.calls[0];
122
- // Command should contain npx or bun
123
- expect(String(cmd)).toMatch(/npx|bun/);
124
- });
125
- it("should use bun when BUN_INSTALL is set", async () => {
126
- const mockProcess = createMockChildProcess();
127
- mockSpawn.mockReturnValue(mockProcess);
128
- process.env.BUN_INSTALL = "/path/to/bun";
129
- launchViaPackageManager("typescript-language-server", ["--stdio"], {});
130
- const [cmd, args] = mockSpawn.mock.calls[0];
131
- // On Windows with shell mode, args may be concatenated into cmd
132
- const cmdStr = String(cmd);
133
- const hasBun = cmdStr.includes("bun") || (args && args.some((a) => a && a.includes("bun")));
134
- const hasX = cmdStr.includes(" x ") || (args && args.includes("x"));
135
- expect(hasBun).toBe(true);
136
- // Note: 'x' arg may be in command string on Windows
137
- });
138
- it("should pass through options", async () => {
139
- const mockProcess = createMockChildProcess();
140
- mockSpawn.mockReturnValue(mockProcess);
141
- launchViaPackageManager("server", ["--flag"], { cwd: "/test" });
142
- const [, , options] = mockSpawn.mock.calls[0];
143
- expect(options?.cwd).toBe("/test");
144
- });
145
- });
146
- describe("launchViaNode", () => {
147
- beforeEach(() => {
148
- vi.clearAllMocks();
149
- });
150
- it("should spawn node with script path", async () => {
151
- const mockProcess = createMockChildProcess();
152
- mockSpawn.mockReturnValue(mockProcess);
153
- launchViaNode("/path/to/script.js", ["--arg"], { cwd: "/test" });
154
- expect(mockSpawn).toHaveBeenCalled();
155
- const [cmd, args, options] = mockSpawn.mock.calls[0];
156
- // On Windows, command is combined; on Unix, it's separate
157
- expect(String(cmd)).toContain("node");
158
- expect(options?.cwd).toBe("/test");
159
- });
160
- });
161
- describe("launchViaPython", () => {
162
- beforeEach(() => {
163
- vi.clearAllMocks();
164
- });
165
- it("should spawn Python module", async () => {
166
- const mockProcess = createMockChildProcess();
167
- mockSpawn.mockReturnValue(mockProcess);
168
- launchViaPython("pylsp", [], {});
169
- expect(mockSpawn).toHaveBeenCalled();
170
- const [cmd] = mockSpawn.mock.calls[0];
171
- expect(String(cmd)).toMatch(/python|py/);
172
- });
173
- it("should pass args to module", async () => {
174
- const mockProcess = createMockChildProcess();
175
- mockSpawn.mockReturnValue(mockProcess);
176
- launchViaPython("pylsp", ["--verbose", "--log-file", "/tmp/log"], {});
177
- expect(mockSpawn).toHaveBeenCalled();
178
- const [cmd, args] = mockSpawn.mock.calls[0];
179
- // Args should include the module and the passed args
180
- expect(args).toContain("-m");
181
- expect(args).toContain("pylsp");
182
- expect(args).toContain("--verbose");
183
- });
184
- });
185
- describe("stopLSP", () => {
186
- beforeEach(() => {
187
- vi.clearAllMocks();
188
- vi.useFakeTimers({ shouldAdvanceTime: true });
189
- });
190
- afterEach(() => {
191
- vi.useRealTimers();
192
- });
193
- it("should send SIGTERM first", async () => {
194
- const mockKill = vi.fn();
195
- const exitHandlers = [];
196
- const mockProcess = {
197
- ...createMockChildProcess(),
198
- kill: mockKill,
199
- on: vi.fn((event, handler) => {
200
- if (event === "exit") {
201
- exitHandlers.push(handler);
202
- // Simulate immediate exit
203
- setTimeout(() => handler(), 10);
204
- }
205
- }),
206
- };
207
- const stopPromise = stopLSP({
208
- process: mockProcess,
209
- stdin: {},
210
- stdout: {},
211
- stderr: {},
212
- pid: 123,
213
- });
214
- // Let the exit handler fire
215
- await new Promise(r => setTimeout(r, 20));
216
- expect(mockKill).toHaveBeenCalledWith("SIGTERM");
217
- });
218
- it.skip("should send SIGKILL if process doesn't exit in time", async () => {
219
- // This test is flaky with fake timers - skipping for now
220
- // The actual implementation works correctly in production
221
- }, 15000);
222
- it("should resolve immediately on exit", async () => {
223
- const mockProcess = {
224
- ...createMockChildProcess(),
225
- on: vi.fn((event, handler) => {
226
- if (event === "exit") {
227
- // Call handler immediately
228
- handler();
229
- }
230
- }),
231
- };
232
- await expect(stopLSP({
233
- process: mockProcess,
234
- stdin: {},
235
- stdout: {},
236
- stderr: {},
237
- pid: 123,
238
- })).resolves.toBeUndefined();
239
- });
240
- it("should resolve on error event", async () => {
241
- const mockProcess = {
242
- ...createMockChildProcess(),
243
- on: vi.fn((event, handler) => {
244
- if (event === "error") {
245
- setTimeout(handler, 10);
246
- }
247
- }),
248
- };
249
- const stopPromise = stopLSP({
250
- process: mockProcess,
251
- stdin: {},
252
- stdout: {},
253
- stderr: {},
254
- pid: 123,
255
- });
256
- // Let the error handler fire
257
- await new Promise(r => setTimeout(r, 20));
258
- await expect(stopPromise).resolves.toBeUndefined();
259
- });
260
- });