@namzu/lsp 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/src/index.ts ADDED
@@ -0,0 +1,12 @@
1
+ export { StdioCodeNavigationProvider } from './stdio.js'
2
+ export type { StdioCodeNavigationOptions } from './stdio.js'
3
+ export { RoutingCodeNavigationProvider } from './routing.js'
4
+ export type { CodeNavigationRoute, RoutingCodeNavigationOptions } from './routing.js'
5
+ export type {
6
+ CodeNavigationProvider,
7
+ CodeNavigationResult,
8
+ HoverResult,
9
+ SourceLocation,
10
+ SymbolLocation,
11
+ SymbolSearchResult,
12
+ } from './types.js'
package/src/routing.ts ADDED
@@ -0,0 +1,147 @@
1
+ import { extname } from 'node:path'
2
+
3
+ import { type StdioCodeNavigationOptions, StdioCodeNavigationProvider } from './stdio.js'
4
+ import type {
5
+ CodeNavigationProvider,
6
+ CodeNavigationResult,
7
+ HoverResult,
8
+ SymbolSearchResult,
9
+ } from './types.js'
10
+
11
+ /**
12
+ * One server per language, started when its first file is asked about.
13
+ *
14
+ * A single hard-wired server means the capability exists for one language in
15
+ * a repository that will not stay one language — and the failure is quiet:
16
+ * a `.py` file reaches a server that has never parsed Python, which answers
17
+ * nothing, which reads as a symbol with no references.
18
+ *
19
+ * **A file whose extension maps to nothing is `unsupported`, naming the
20
+ * extension.** Not routed to a default, and not an empty result. A default
21
+ * would send the file to a server that cannot read it and produce exactly
22
+ * the quiet wrong answer above; an empty result would say the symbol has no
23
+ * callers.
24
+ *
25
+ * **Lazy, and reused.** Starting every configured server up front pays for
26
+ * languages a run never touches, and starting one per request would pay the
27
+ * initialize handshake — seconds, for an indexing server — on every call.
28
+ */
29
+
30
+ export interface CodeNavigationRoute {
31
+ /** Extensions this server answers for, with the dot: `['.ts', '.tsx']`. */
32
+ readonly extensions: readonly string[]
33
+ readonly server: StdioCodeNavigationOptions
34
+ }
35
+
36
+ export interface RoutingCodeNavigationOptions {
37
+ readonly routes: readonly CodeNavigationRoute[]
38
+ /**
39
+ * How a route becomes a provider.
40
+ *
41
+ * Injectable so a test can count spawns — the reuse property is about
42
+ * how many processes exist, and asserting it on wall-clock time would
43
+ * pass on a fast machine with the reuse removed.
44
+ */
45
+ readonly createProvider?: (options: StdioCodeNavigationOptions) => CodeNavigationProvider
46
+ }
47
+
48
+ export class RoutingCodeNavigationProvider implements CodeNavigationProvider {
49
+ private readonly byExtension = new Map<string, CodeNavigationRoute>()
50
+ private readonly started = new Map<CodeNavigationRoute, CodeNavigationProvider>()
51
+ private readonly create: (options: StdioCodeNavigationOptions) => CodeNavigationProvider
52
+
53
+ constructor(options: RoutingCodeNavigationOptions) {
54
+ this.create = options.createProvider ?? ((server) => new StdioCodeNavigationProvider(server))
55
+ for (const route of options.routes) {
56
+ for (const extension of route.extensions) {
57
+ // Lower-cased once, here. A `.TS` on a case-insensitive filesystem
58
+ // is the same language, and a lookup that missed it would report
59
+ // the extension as unconfigured.
60
+ this.byExtension.set(extension.toLowerCase(), route)
61
+ }
62
+ }
63
+ }
64
+
65
+ async definition(file: string, line: number, character: number): Promise<CodeNavigationResult> {
66
+ const routed = this.routeFor(file)
67
+ if ('reason' in routed) return { kind: 'unsupported', reason: routed.reason }
68
+ return await routed.provider.definition(file, line, character)
69
+ }
70
+
71
+ async references(file: string, line: number, character: number): Promise<CodeNavigationResult> {
72
+ const routed = this.routeFor(file)
73
+ if ('reason' in routed) return { kind: 'unsupported', reason: routed.reason }
74
+ return await routed.provider.references(file, line, character)
75
+ }
76
+
77
+ async hover(file: string, line: number, character: number): Promise<HoverResult> {
78
+ const routed = this.routeFor(file)
79
+ if ('reason' in routed) return { kind: 'unsupported', reason: routed.reason }
80
+ return await routed.provider.hover(file, line, character)
81
+ }
82
+
83
+ /**
84
+ * Search by name, across one language or all of them.
85
+ *
86
+ * With a scope, the scope's extension picks the server — the ordinary
87
+ * case, and the cheap one. Without, every configured language answers,
88
+ * because "find this symbol" in a mixed repository means all of it and a
89
+ * caller who wanted one language would have said which.
90
+ */
91
+ async symbols(query: string, scope?: string): Promise<SymbolSearchResult> {
92
+ if (scope) {
93
+ const routed = this.routeFor(scope)
94
+ if ('reason' in routed) return { kind: 'unsupported', reason: routed.reason }
95
+ return await routed.provider.symbols(query, scope)
96
+ }
97
+
98
+ const routes = [...new Set(this.byExtension.values())]
99
+ if (routes.length === 0) {
100
+ return { kind: 'unsupported', reason: 'No language servers are configured.' }
101
+ }
102
+
103
+ const answers = await Promise.all(
104
+ routes.map(async (route) => await this.providerFor(route).symbols(query)),
105
+ )
106
+ const found = answers.flatMap((a) => (a.kind === 'symbols' ? a.symbols : []))
107
+ if (found.length > 0) return { kind: 'symbols', symbols: found }
108
+
109
+ // Nothing found anywhere. If EVERY server refused, that is not an empty
110
+ // result — nobody looked. Reporting it as `symbols: []` would tell the
111
+ // caller the name does not exist in the repository.
112
+ const failure = answers.find((a) => a.kind === 'failed')
113
+ if (failure) return failure
114
+ const unsupported = answers.find((a) => a.kind === 'unsupported')
115
+ if (unsupported && answers.every((a) => a.kind === 'unsupported')) return unsupported
116
+ return { kind: 'symbols', symbols: [] }
117
+ }
118
+
119
+ async dispose(): Promise<void> {
120
+ await Promise.all([...this.started.values()].map(async (p) => await p.dispose()))
121
+ this.started.clear()
122
+ }
123
+
124
+ /** How many servers are running. For a test asserting reuse. */
125
+ startedCount(): number {
126
+ return this.started.size
127
+ }
128
+
129
+ private routeFor(file: string): { provider: CodeNavigationProvider } | { reason: string } {
130
+ const extension = extname(file).toLowerCase()
131
+ const route = this.byExtension.get(extension)
132
+ if (!route) {
133
+ return {
134
+ reason: `No language server is configured for "${extension || file}". Configure one, or use \`grep\` and treat the result as textual.`,
135
+ }
136
+ }
137
+ return { provider: this.providerFor(route) }
138
+ }
139
+
140
+ private providerFor(route: CodeNavigationRoute): CodeNavigationProvider {
141
+ const existing = this.started.get(route)
142
+ if (existing) return existing
143
+ const created = this.create(route.server)
144
+ this.started.set(route, created)
145
+ return created
146
+ }
147
+ }
package/src/stdio.ts ADDED
@@ -0,0 +1,534 @@
1
+ import { type ChildProcess, spawn } from 'node:child_process'
2
+ import { pathToFileURL } from 'node:url'
3
+
4
+ import type {
5
+ CodeNavigationProvider,
6
+ CodeNavigationResult,
7
+ HoverResult,
8
+ SourceLocation,
9
+ SymbolLocation,
10
+ SymbolSearchResult,
11
+ } from './types.js'
12
+
13
+ /**
14
+ * One language server, over its stdin and stdout.
15
+ *
16
+ * Stdio rather than a socket for the reason every stdio transport in this
17
+ * repository gives: the client spawns the server, so there is no port, no
18
+ * bind address, and no inbound authentication question to get wrong. The
19
+ * boundary is the process.
20
+ *
21
+ * **The framing is not JSON lines.** This wire prefixes each message with a
22
+ * `Content-Length` header and a blank line, so a reader that split on `\n`
23
+ * would tear a message whose body contains one — which every response
24
+ * carrying source text does.
25
+ *
26
+ * **A server that never initializes is a FAILURE, not an empty answer.**
27
+ * The bounded startup timeout exists so a missing binary, a server that
28
+ * crashes on a malformed workspace, or one waiting on a prompt nobody will
29
+ * answer produces `{ kind: 'failed' }` naming the binary. Returning
30
+ * `{ kind: 'locations', locations: [] }` there tells an agent the symbol has
31
+ * no callers, and the agent then deletes it.
32
+ */
33
+
34
+ export interface StdioCodeNavigationOptions {
35
+ /** The server binary. */
36
+ readonly command: string
37
+ readonly args?: readonly string[]
38
+ /** Workspace root the server indexes. */
39
+ readonly rootDir: string
40
+ /** How long `initialize` may take. */
41
+ readonly startupTimeoutMs?: number
42
+ /** How long any one request may take. */
43
+ readonly requestTimeoutMs?: number
44
+ readonly env?: Readonly<Record<string, string>>
45
+ }
46
+
47
+ const DEFAULT_STARTUP_TIMEOUT_MS = 15_000
48
+ const DEFAULT_REQUEST_TIMEOUT_MS = 20_000
49
+
50
+ interface Pending {
51
+ resolve: (value: unknown) => void
52
+ reject: (error: Error) => void
53
+ timer: NodeJS.Timeout
54
+ }
55
+
56
+ /** LSP's own position shape, before it becomes a {@link SourceLocation}. */
57
+ interface LspLocation {
58
+ uri: string
59
+ range: {
60
+ start: { line: number; character: number }
61
+ end?: { line: number; character: number }
62
+ }
63
+ }
64
+
65
+ function toSourceLocation(location: LspLocation): SourceLocation {
66
+ // `file://` off, so a caller gets a path it can hand to `readFile`. The
67
+ // wire speaks URIs because a server may serve untitled buffers; every
68
+ // path this provider is asked about is a real file.
69
+ const path = location.uri.startsWith('file://')
70
+ ? decodeURIComponent(new URL(location.uri).pathname)
71
+ : location.uri
72
+ const end = location.range.end
73
+ return {
74
+ path,
75
+ line: location.range.start.line,
76
+ character: location.range.start.character,
77
+ ...(end ? { endLine: end.line, endCharacter: end.character } : {}),
78
+ }
79
+ }
80
+
81
+ export class StdioCodeNavigationProvider implements CodeNavigationProvider {
82
+ private child: ChildProcess | undefined
83
+ private buffer = Buffer.alloc(0)
84
+ private seq = 0
85
+ private readonly pending = new Map<number, Pending>()
86
+ private starting: Promise<void> | undefined
87
+ /**
88
+ * What the server said it can do, read from the initialize RESULT.
89
+ *
90
+ * Read rather than probed. Sending `workspace/symbol` to a server that
91
+ * does not implement it and swallowing the error works until a server
92
+ * answers a different error for a different reason — a transient one, a
93
+ * malformed query — and the fallback then fires for a capability the
94
+ * server has. The handshake already carries the answer.
95
+ */
96
+ private capabilities: Record<string, unknown> = {}
97
+ private startupError: string | undefined
98
+ private disposed = false
99
+
100
+ constructor(private readonly options: StdioCodeNavigationOptions) {}
101
+
102
+ async definition(file: string, line: number, character: number): Promise<CodeNavigationResult> {
103
+ return await this.navigate('textDocument/definition', file, line, character, {})
104
+ }
105
+
106
+ async references(file: string, line: number, character: number): Promise<CodeNavigationResult> {
107
+ return await this.navigate('textDocument/references', file, line, character, {
108
+ // The declaration itself is not a "use". An agent asking who calls
109
+ // this wants the call sites; including the declaration inflates the
110
+ // count by one and reads as a caller that does not exist.
111
+ context: { includeDeclaration: false },
112
+ })
113
+ }
114
+
115
+ async hover(file: string, line: number, character: number): Promise<HoverResult> {
116
+ try {
117
+ await this.start()
118
+ } catch (err) {
119
+ return { kind: 'failed', error: err instanceof Error ? err.message : String(err) }
120
+ }
121
+ if (this.capabilities.hoverProvider === false) {
122
+ return { kind: 'unsupported', reason: `${this.options.command} declares no hoverProvider.` }
123
+ }
124
+ try {
125
+ const result = await this.request('textDocument/hover', {
126
+ textDocument: { uri: pathToFileURL(file).href },
127
+ position: { line, character },
128
+ })
129
+ // EMPTY, not failed. Hovering over whitespace or a comment resolves
130
+ // to nothing, and a caller has to be able to tell that from a server
131
+ // that broke — the same distinction `locations: []` carries.
132
+ return { kind: 'hover', contents: hoverText(result) }
133
+ } catch (err) {
134
+ return toFailure(err, `${this.options.command}`, 'textDocument/hover')
135
+ }
136
+ }
137
+
138
+ async symbols(query: string, _scope?: string): Promise<SymbolSearchResult> {
139
+ try {
140
+ await this.start()
141
+ } catch (err) {
142
+ return { kind: 'failed', error: err instanceof Error ? err.message : String(err) }
143
+ }
144
+
145
+ // The DECLARED capability decides which request goes out. A server
146
+ // with a workspace index answers the whole repository; one with only
147
+ // document symbols answers the file it is given; one with neither is
148
+ // told so rather than asked and silently mishandled.
149
+ if (this.capabilities.workspaceSymbolProvider) {
150
+ try {
151
+ const result = await this.request('workspace/symbol', { query })
152
+ return { kind: 'symbols', symbols: toSymbols(result) }
153
+ } catch (err) {
154
+ return toFailure(err, this.options.command, 'workspace/symbol')
155
+ }
156
+ }
157
+ if (this.capabilities.documentSymbolProvider) {
158
+ if (!_scope) {
159
+ return {
160
+ kind: 'unsupported',
161
+ reason: `${this.options.command} has no workspace symbol index, so a symbol search needs a file to look in. Pass a scope.`,
162
+ }
163
+ }
164
+ try {
165
+ const result = await this.request('textDocument/documentSymbol', {
166
+ textDocument: { uri: pathToFileURL(_scope).href },
167
+ })
168
+ return {
169
+ kind: 'symbols',
170
+ symbols: toSymbols(result, _scope).filter((s) => s.name.includes(query)),
171
+ }
172
+ } catch (err) {
173
+ return toFailure(err, this.options.command, 'textDocument/documentSymbol')
174
+ }
175
+ }
176
+ return {
177
+ kind: 'unsupported',
178
+ reason: `${this.options.command} declares neither workspaceSymbolProvider nor documentSymbolProvider, so it cannot find a symbol by name.`,
179
+ }
180
+ }
181
+
182
+ private async navigate(
183
+ method: string,
184
+ file: string,
185
+ line: number,
186
+ character: number,
187
+ extra: Record<string, unknown>,
188
+ ): Promise<CodeNavigationResult> {
189
+ try {
190
+ await this.start()
191
+ } catch (err) {
192
+ return { kind: 'failed', error: err instanceof Error ? err.message : String(err) }
193
+ }
194
+
195
+ try {
196
+ const result = await this.request(method, {
197
+ textDocument: { uri: pathToFileURL(file).href },
198
+ position: { line, character },
199
+ ...extra,
200
+ })
201
+ if (result === null || result === undefined) {
202
+ // A server that answered `null` looked and found nothing. That is
203
+ // an empty location list, not a failure — and saying so is what
204
+ // lets a caller tell it apart from a server that never started.
205
+ return { kind: 'locations', locations: [] }
206
+ }
207
+ const raw = Array.isArray(result) ? result : [result]
208
+ return {
209
+ kind: 'locations',
210
+ locations: raw
211
+ .filter((entry): entry is LspLocation => isLocation(entry))
212
+ .map(toSourceLocation),
213
+ }
214
+ } catch (err) {
215
+ const message = err instanceof Error ? err.message : String(err)
216
+ // A method the server does not implement is `unsupported`, not
217
+ // `failed`: a caller can fall back to grep and say why, where a
218
+ // failure means the answer is unknown.
219
+ if (/method not found|-32601/i.test(message)) {
220
+ return {
221
+ kind: 'unsupported',
222
+ reason: `${this.options.command} does not implement ${method}.`,
223
+ }
224
+ }
225
+ return { kind: 'failed', error: message }
226
+ }
227
+ }
228
+
229
+ /** Spawn and handshake, once, and remember a failure so it is not retried per call. */
230
+ private start(): Promise<void> {
231
+ if (this.disposed)
232
+ return Promise.reject(new Error('This code navigation provider is disposed.'))
233
+ if (this.startupError) return Promise.reject(new Error(this.startupError))
234
+ if (this.starting) return this.starting
235
+
236
+ this.starting = (async () => {
237
+ let child: ChildProcess
238
+ try {
239
+ child = spawn(this.options.command, [...(this.options.args ?? [])], {
240
+ cwd: this.options.rootDir,
241
+ stdio: ['pipe', 'pipe', 'pipe'],
242
+ ...(this.options.env ? { env: { ...process.env, ...this.options.env } } : {}),
243
+ })
244
+ } catch (err) {
245
+ throw new Error(
246
+ `Could not start the language server "${this.options.command}": ${err instanceof Error ? err.message : String(err)}`,
247
+ )
248
+ }
249
+ this.child = child
250
+
251
+ // A spawn failure arrives asynchronously on some platforms, so the
252
+ // error event has to be able to reject the handshake below rather
253
+ // than surface as an unhandled error on a child nobody is watching.
254
+ const spawnFailure = new Promise<never>((_resolve, reject) => {
255
+ child.once('error', (err) =>
256
+ reject(
257
+ new Error(
258
+ `Could not start the language server "${this.options.command}": ${err.message}`,
259
+ ),
260
+ ),
261
+ )
262
+ child.once('exit', (code) =>
263
+ reject(
264
+ new Error(
265
+ `The language server "${this.options.command}" exited with code ${code} before it initialized.`,
266
+ ),
267
+ ),
268
+ )
269
+ })
270
+ // Not unhandled: the race below may settle on the other branch, and
271
+ // an unobserved rejection would take the process down.
272
+ spawnFailure.catch(() => {})
273
+
274
+ child.stdout?.on('data', (chunk: Buffer) => this.consume(chunk))
275
+
276
+ const startupMs = this.options.startupTimeoutMs ?? DEFAULT_STARTUP_TIMEOUT_MS
277
+ const timeout = new Promise<never>((_resolve, reject) => {
278
+ const timer = setTimeout(
279
+ () =>
280
+ reject(
281
+ new Error(
282
+ `The language server "${this.options.command}" did not answer initialize within ${startupMs}ms. Refusing rather than answering navigation queries with an empty result.`,
283
+ ),
284
+ ),
285
+ startupMs,
286
+ )
287
+ timer.unref?.()
288
+ })
289
+
290
+ const initialized = await Promise.race([
291
+ this.request('initialize', {
292
+ processId: process.pid,
293
+ rootUri: pathToFileURL(this.options.rootDir).href,
294
+ workspaceFolders: [{ uri: pathToFileURL(this.options.rootDir).href, name: 'workspace' }],
295
+ capabilities: {},
296
+ }),
297
+ spawnFailure,
298
+ timeout,
299
+ ])
300
+ // Stored from the initialize RESULT, which is the only place a
301
+ // server states what it can do. Everything downstream reads this
302
+ // instead of sending a request and interpreting the error.
303
+ this.capabilities =
304
+ (initialized as { capabilities?: Record<string, unknown> } | undefined)?.capabilities ?? {}
305
+ this.notify('initialized', {})
306
+ })().catch((err: unknown) => {
307
+ // Remembered, so a run that asks twenty times does not spawn twenty
308
+ // servers against a binary that is not there.
309
+ this.startupError = err instanceof Error ? err.message : String(err)
310
+ throw err
311
+ })
312
+
313
+ return this.starting
314
+ }
315
+
316
+ private request(method: string, params: Record<string, unknown>): Promise<unknown> {
317
+ this.seq += 1
318
+ const id = this.seq
319
+ const timeoutMs = this.options.requestTimeoutMs ?? DEFAULT_REQUEST_TIMEOUT_MS
320
+ return new Promise<unknown>((resolve, reject) => {
321
+ const timer = setTimeout(() => {
322
+ this.pending.delete(id)
323
+ reject(new Error(`The language server did not answer ${method} within ${timeoutMs}ms.`))
324
+ }, timeoutMs)
325
+ timer.unref?.()
326
+ this.pending.set(id, { resolve, reject, timer })
327
+ this.write({ jsonrpc: '2.0', id, method, params })
328
+ })
329
+ }
330
+
331
+ private notify(method: string, params: Record<string, unknown>): void {
332
+ this.write({ jsonrpc: '2.0', method, params })
333
+ }
334
+
335
+ private write(message: Record<string, unknown>): void {
336
+ const body = Buffer.from(JSON.stringify(message), 'utf-8')
337
+ this.child?.stdin?.write(`Content-Length: ${body.length}\r\n\r\n`)
338
+ this.child?.stdin?.write(body)
339
+ }
340
+
341
+ /**
342
+ * Read the framed stream.
343
+ *
344
+ * Byte lengths, not characters: `Content-Length` counts bytes, and a
345
+ * response carrying a non-ASCII identifier has more bytes than
346
+ * characters. Slicing a string by that number cuts the message short and
347
+ * leaves the parser permanently out of step.
348
+ */
349
+ private consume(chunk: Buffer): void {
350
+ this.buffer = Buffer.concat([this.buffer, chunk])
351
+ for (;;) {
352
+ const headerEnd = this.buffer.indexOf('\r\n\r\n')
353
+ if (headerEnd === -1) return
354
+ const header = this.buffer.subarray(0, headerEnd).toString('utf-8')
355
+ const match = /content-length:\s*(\d+)/i.exec(header)
356
+ if (!match) {
357
+ // A frame with no length is unrecoverable — there is no way to know
358
+ // where it ends. Drop the header and resynchronise rather than
359
+ // spinning on the same bytes forever.
360
+ this.buffer = this.buffer.subarray(headerEnd + 4)
361
+ continue
362
+ }
363
+ const length = Number(match[1])
364
+ const start = headerEnd + 4
365
+ if (this.buffer.length < start + length) return
366
+ const body = this.buffer.subarray(start, start + length).toString('utf-8')
367
+ this.buffer = this.buffer.subarray(start + length)
368
+ this.deliver(body)
369
+ }
370
+ }
371
+
372
+ private deliver(body: string): void {
373
+ let message: { id?: number; result?: unknown; error?: { message?: string; code?: number } }
374
+ try {
375
+ message = JSON.parse(body) as typeof message
376
+ } catch {
377
+ // A malformed body is one lost message, not a lost connection: the
378
+ // framing already told us where it ended, so the stream is still in
379
+ // step and the next frame is readable.
380
+ return
381
+ }
382
+ if (message.id === undefined) return
383
+ const waiting = this.pending.get(message.id)
384
+ if (!waiting) return
385
+ this.pending.delete(message.id)
386
+ clearTimeout(waiting.timer)
387
+ if (message.error) {
388
+ waiting.reject(new Error(message.error.message ?? `error ${message.error.code ?? 'unknown'}`))
389
+ } else {
390
+ waiting.resolve(message.result)
391
+ }
392
+ }
393
+
394
+ async dispose(): Promise<void> {
395
+ if (this.disposed) return
396
+ this.disposed = true
397
+ const child = this.child
398
+ this.child = undefined
399
+ for (const waiting of this.pending.values()) {
400
+ clearTimeout(waiting.timer)
401
+ waiting.reject(new Error('The code navigation provider was disposed.'))
402
+ }
403
+ this.pending.clear()
404
+ if (!child) return
405
+
406
+ // The handshake FIRST, so a server with unsaved index state gets to
407
+ // finish. A `kill` alone leaves whatever it was writing half-written,
408
+ // and some servers hold a lock file.
409
+ const exited = new Promise<void>((resolve) => {
410
+ child.once('exit', () => resolve())
411
+ })
412
+ try {
413
+ this.child = child
414
+ this.write({ jsonrpc: '2.0', id: ++this.seq, method: 'shutdown', params: {} })
415
+ this.write({ jsonrpc: '2.0', method: 'exit', params: {} })
416
+ } catch {
417
+ // The pipe is already gone. Falling through to the kill is right.
418
+ }
419
+ this.child = undefined
420
+ child.stdin?.end()
421
+
422
+ // Bounded, because a server that ignores `exit` must not keep the run
423
+ // alive. This is the same trade `kill-tree` makes: ask, then insist.
424
+ await Promise.race([
425
+ exited,
426
+ new Promise<void>((resolve) => {
427
+ const timer = setTimeout(() => {
428
+ child.kill('SIGKILL')
429
+ resolve()
430
+ }, 2_000)
431
+ timer.unref?.()
432
+ }),
433
+ ])
434
+ }
435
+ }
436
+
437
+ function isLocation(value: unknown): value is LspLocation {
438
+ if (typeof value !== 'object' || value === null) return false
439
+ const candidate = value as { uri?: unknown; range?: { start?: unknown } }
440
+ return typeof candidate.uri === 'string' && typeof candidate.range?.start === 'object'
441
+ }
442
+
443
+ /**
444
+ * A thrown error as the right member of a result union.
445
+ *
446
+ * The two `unsupported`/`failed` arms are identical across all three result
447
+ * types, so this returns that shared shape and each caller widens it. A
448
+ * generic that claimed to produce `T` would be asserting into a union it
449
+ * cannot construct.
450
+ */
451
+ function toFailure(
452
+ err: unknown,
453
+ command: string,
454
+ method: string,
455
+ ): { kind: 'unsupported'; reason: string } | { kind: 'failed'; error: string } {
456
+ const message = err instanceof Error ? err.message : String(err)
457
+ // A method the server does not implement is `unsupported`, not `failed`:
458
+ // a caller can fall back and say why the answer is approximate, where a
459
+ // failure means the answer is unknown.
460
+ if (/method not found|-32601/i.test(message)) {
461
+ return { kind: 'unsupported', reason: `${command} does not implement ${method}.` }
462
+ }
463
+ return { kind: 'failed', error: message }
464
+ }
465
+
466
+ /**
467
+ * The wire's several hover shapes, as one string.
468
+ *
469
+ * `contents` has been a string, a `{ language, value }` pair, an array of
470
+ * either, and a `{ kind, value }` markup object across revisions of the
471
+ * protocol, and servers in the field still send all of them. A reader that
472
+ * handled only the newest returns empty for a server that answered — which
473
+ * is indistinguishable, at the call site, from a symbol with no type.
474
+ */
475
+ function hoverText(result: unknown): string {
476
+ if (result === null || result === undefined) return ''
477
+ const contents = (result as { contents?: unknown }).contents
478
+ return flattenHover(contents).join('\n').trim()
479
+ }
480
+
481
+ function flattenHover(value: unknown): string[] {
482
+ if (value === null || value === undefined) return []
483
+ if (typeof value === 'string') return [value]
484
+ if (Array.isArray(value)) return value.flatMap(flattenHover)
485
+ if (typeof value === 'object') {
486
+ const record = value as { value?: unknown; language?: unknown }
487
+ if (typeof record.value === 'string') return [record.value]
488
+ }
489
+ return []
490
+ }
491
+
492
+ /** `workspace/symbol` and `textDocument/documentSymbol` answer differently. */
493
+ function toSymbols(result: unknown, fallbackPath?: string): SymbolLocation[] {
494
+ if (!Array.isArray(result)) return []
495
+ const out: SymbolLocation[] = []
496
+ for (const entry of result) {
497
+ if (typeof entry !== 'object' || entry === null) continue
498
+ const item = entry as {
499
+ name?: unknown
500
+ kind?: unknown
501
+ containerName?: unknown
502
+ location?: LspLocation
503
+ range?: LspLocation['range']
504
+ selectionRange?: LspLocation['range']
505
+ children?: unknown
506
+ }
507
+ if (typeof item.name !== 'string') continue
508
+
509
+ // `workspace/symbol` carries a `location`; `documentSymbol` carries a
510
+ // `range` and leaves the file implied by the request. Both are handled
511
+ // because the fallback path produces the second shape.
512
+ const location = item.location
513
+ ? toSourceLocation(item.location)
514
+ : item.selectionRange || item.range
515
+ ? toSourceLocation({
516
+ uri: fallbackPath ? pathToFileURL(fallbackPath).href : '',
517
+ range: (item.selectionRange ?? item.range) as LspLocation['range'],
518
+ })
519
+ : undefined
520
+ if (location) {
521
+ out.push({
522
+ ...location,
523
+ name: item.name,
524
+ ...(typeof item.kind === 'number' ? { symbolKind: item.kind } : {}),
525
+ ...(typeof item.containerName === 'string' ? { containerName: item.containerName } : {}),
526
+ })
527
+ }
528
+ // `documentSymbol` is a TREE. A reader that took only the top level
529
+ // would miss every method, which is most of what somebody searching by
530
+ // name is looking for.
531
+ if (Array.isArray(item.children)) out.push(...toSymbols(item.children, fallbackPath))
532
+ }
533
+ return out
534
+ }