funkscript 0.2.6 → 0.2.7

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 (171) hide show
  1. package/README.md +1 -1
  2. package/dist/cli/build-watch.d.ts.map +1 -1
  3. package/dist/cli/build-watch.js +4 -24
  4. package/dist/cli/build-watch.js.map +1 -1
  5. package/dist/cli/build.d.ts.map +1 -1
  6. package/dist/cli/build.js +3 -58
  7. package/dist/cli/build.js.map +1 -1
  8. package/dist/cli/check-policy.d.ts +9 -0
  9. package/dist/cli/check-policy.d.ts.map +1 -0
  10. package/dist/cli/check-policy.js +39 -0
  11. package/dist/cli/check-policy.js.map +1 -0
  12. package/dist/cli/check.d.ts.map +1 -1
  13. package/dist/cli/check.js +16 -30
  14. package/dist/cli/check.js.map +1 -1
  15. package/dist/cli/commands.d.ts.map +1 -1
  16. package/dist/cli/commands.js +11 -0
  17. package/dist/cli/commands.js.map +1 -1
  18. package/dist/cli/doctor.d.ts.map +1 -1
  19. package/dist/cli/doctor.js +2 -6
  20. package/dist/cli/doctor.js.map +1 -1
  21. package/dist/cli/index.js +3 -0
  22. package/dist/cli/index.js.map +1 -1
  23. package/dist/cli/query.d.ts +3 -0
  24. package/dist/cli/query.d.ts.map +1 -0
  25. package/dist/cli/query.js +152 -0
  26. package/dist/cli/query.js.map +1 -0
  27. package/dist/cli/run.d.ts.map +1 -1
  28. package/dist/cli/run.js +2 -29
  29. package/dist/cli/run.js.map +1 -1
  30. package/dist/cli/tsc.d.ts.map +1 -1
  31. package/dist/cli/tsc.js +2 -6
  32. package/dist/cli/tsc.js.map +1 -1
  33. package/dist/compiler/check.d.ts.map +1 -1
  34. package/dist/compiler/check.js +18 -28
  35. package/dist/compiler/check.js.map +1 -1
  36. package/dist/compiler/diagnostics-json.d.ts +73 -0
  37. package/dist/compiler/diagnostics-json.d.ts.map +1 -0
  38. package/dist/compiler/diagnostics-json.js +957 -0
  39. package/dist/compiler/diagnostics-json.js.map +1 -0
  40. package/dist/compiler/escape-audit.d.ts +46 -0
  41. package/dist/compiler/escape-audit.d.ts.map +1 -0
  42. package/dist/compiler/escape-audit.js +682 -0
  43. package/dist/compiler/escape-audit.js.map +1 -0
  44. package/dist/compiler/modules/output-plan.d.ts.map +1 -1
  45. package/dist/compiler/modules/output-plan.js +10 -5
  46. package/dist/compiler/modules/output-plan.js.map +1 -1
  47. package/dist/compiler/modules/source-files.d.ts +2 -0
  48. package/dist/compiler/modules/source-files.d.ts.map +1 -1
  49. package/dist/compiler/modules/source-files.js +8 -0
  50. package/dist/compiler/modules/source-files.js.map +1 -1
  51. package/dist/compiler/numeric-comparisons.d.ts.map +1 -1
  52. package/dist/compiler/numeric-comparisons.js +13 -7
  53. package/dist/compiler/numeric-comparisons.js.map +1 -1
  54. package/dist/compiler/pipelines/resolution.d.ts.map +1 -1
  55. package/dist/compiler/pipelines/resolution.js +24 -23
  56. package/dist/compiler/pipelines/resolution.js.map +1 -1
  57. package/dist/compiler/query.d.ts +53 -0
  58. package/dist/compiler/query.d.ts.map +1 -0
  59. package/dist/compiler/query.js +781 -0
  60. package/dist/compiler/query.js.map +1 -0
  61. package/dist/compiler/source-map.d.ts.map +1 -1
  62. package/dist/compiler/source-map.js +2 -7
  63. package/dist/compiler/source-map.js.map +1 -1
  64. package/dist/compiler/type-view-paths.d.ts +2 -0
  65. package/dist/compiler/type-view-paths.d.ts.map +1 -1
  66. package/dist/compiler/type-view-paths.js +8 -0
  67. package/dist/compiler/type-view-paths.js.map +1 -1
  68. package/dist/compiler/typescript-context.d.ts.map +1 -1
  69. package/dist/compiler/typescript-context.js +5 -7
  70. package/dist/compiler/typescript-context.js.map +1 -1
  71. package/dist/emitter/assemblyscript.d.ts.map +1 -1
  72. package/dist/emitter/assemblyscript.js +120 -136
  73. package/dist/emitter/assemblyscript.js.map +1 -1
  74. package/dist/formatter/index.d.ts +9 -0
  75. package/dist/formatter/index.d.ts.map +1 -1
  76. package/dist/formatter/index.js +158 -2
  77. package/dist/formatter/index.js.map +1 -1
  78. package/dist/index.d.ts +3 -0
  79. package/dist/index.d.ts.map +1 -1
  80. package/dist/index.js +3 -0
  81. package/dist/index.js.map +1 -1
  82. package/dist/lsp/completion.d.ts +25 -0
  83. package/dist/lsp/completion.d.ts.map +1 -1
  84. package/dist/lsp/completion.js +1114 -51
  85. package/dist/lsp/completion.js.map +1 -1
  86. package/dist/lsp/definition.d.ts +2 -0
  87. package/dist/lsp/definition.d.ts.map +1 -1
  88. package/dist/lsp/definition.js +52 -58
  89. package/dist/lsp/definition.js.map +1 -1
  90. package/dist/lsp/hover.d.ts +5 -1
  91. package/dist/lsp/hover.d.ts.map +1 -1
  92. package/dist/lsp/hover.js +1000 -41
  93. package/dist/lsp/hover.js.map +1 -1
  94. package/dist/lsp/imports.d.ts +2 -0
  95. package/dist/lsp/imports.d.ts.map +1 -1
  96. package/dist/lsp/imports.js +35 -20
  97. package/dist/lsp/imports.js.map +1 -1
  98. package/dist/lsp/navigation.d.ts +1 -1
  99. package/dist/lsp/navigation.d.ts.map +1 -1
  100. package/dist/lsp/navigation.js +30 -12
  101. package/dist/lsp/navigation.js.map +1 -1
  102. package/dist/lsp/range-format.d.ts +4 -0
  103. package/dist/lsp/range-format.d.ts.map +1 -0
  104. package/dist/lsp/range-format.js +88 -0
  105. package/dist/lsp/range-format.js.map +1 -0
  106. package/dist/lsp/schema-import-hover.d.ts +8 -0
  107. package/dist/lsp/schema-import-hover.d.ts.map +1 -0
  108. package/dist/lsp/schema-import-hover.js +52 -0
  109. package/dist/lsp/schema-import-hover.js.map +1 -0
  110. package/dist/lsp/server.d.ts +1 -0
  111. package/dist/lsp/server.d.ts.map +1 -1
  112. package/dist/lsp/server.js +53 -48
  113. package/dist/lsp/server.js.map +1 -1
  114. package/dist/lsp/workspace.d.ts +3 -1
  115. package/dist/lsp/workspace.d.ts.map +1 -1
  116. package/dist/lsp/workspace.js +66 -10
  117. package/dist/lsp/workspace.js.map +1 -1
  118. package/dist/plugins/bun.d.ts +2 -18
  119. package/dist/plugins/bun.d.ts.map +1 -1
  120. package/dist/plugins/bun.js +5 -30
  121. package/dist/plugins/bun.js.map +1 -1
  122. package/dist/plugins/esbuild.d.ts +1 -1
  123. package/dist/plugins/esbuild.d.ts.map +1 -1
  124. package/dist/plugins/esbuild.js +10 -36
  125. package/dist/plugins/esbuild.js.map +1 -1
  126. package/dist/plugins/server-boundary.d.ts +14 -0
  127. package/dist/plugins/server-boundary.d.ts.map +1 -0
  128. package/dist/plugins/server-boundary.js +25 -0
  129. package/dist/plugins/server-boundary.js.map +1 -0
  130. package/dist/plugins/vite.d.ts +2 -18
  131. package/dist/plugins/vite.d.ts.map +1 -1
  132. package/dist/plugins/vite.js +4 -29
  133. package/dist/plugins/vite.js.map +1 -1
  134. package/package.json +1 -1
  135. package/src/cli/build-watch.ts +4 -26
  136. package/src/cli/build.ts +9 -60
  137. package/src/cli/check-policy.ts +54 -0
  138. package/src/cli/check.ts +19 -31
  139. package/src/cli/commands.ts +13 -0
  140. package/src/cli/doctor.ts +2 -5
  141. package/src/cli/index.ts +3 -0
  142. package/src/cli/query.ts +191 -0
  143. package/src/cli/run.ts +5 -30
  144. package/src/cli/tsc.ts +2 -5
  145. package/src/compiler/check.ts +28 -48
  146. package/src/compiler/diagnostics-json.ts +1205 -0
  147. package/src/compiler/escape-audit.ts +913 -0
  148. package/src/compiler/modules/output-plan.ts +11 -9
  149. package/src/compiler/modules/source-files.ts +9 -0
  150. package/src/compiler/numeric-comparisons.ts +14 -8
  151. package/src/compiler/pipelines/resolution.ts +30 -26
  152. package/src/compiler/query.ts +1177 -0
  153. package/src/compiler/source-map.ts +3 -7
  154. package/src/compiler/type-view-paths.ts +7 -0
  155. package/src/compiler/typescript-context.ts +6 -7
  156. package/src/emitter/assemblyscript.ts +101 -147
  157. package/src/formatter/index.ts +229 -2
  158. package/src/index.ts +3 -0
  159. package/src/lsp/completion.ts +1452 -66
  160. package/src/lsp/definition.ts +50 -58
  161. package/src/lsp/hover.ts +1442 -40
  162. package/src/lsp/imports.ts +55 -21
  163. package/src/lsp/navigation.ts +41 -22
  164. package/src/lsp/range-format.ts +102 -0
  165. package/src/lsp/schema-import-hover.ts +76 -0
  166. package/src/lsp/server.ts +69 -69
  167. package/src/lsp/workspace.ts +63 -9
  168. package/src/plugins/bun.ts +14 -66
  169. package/src/plugins/esbuild.ts +16 -55
  170. package/src/plugins/server-boundary.ts +41 -0
  171. package/src/plugins/vite.ts +12 -62
package/src/lsp/hover.ts CHANGED
@@ -1,17 +1,49 @@
1
+ import { existsSync, readFileSync } from "node:fs";
2
+ import { dirname, resolve } from "node:path";
3
+ import { fileURLToPath, pathToFileURL } from "node:url";
1
4
  import * as Effect from "effect/Effect";
2
- import { fileURLToPath } from "node:url";
3
5
  import ts from "typescript";
4
6
  import {
5
7
  MarkupKind,
6
8
  type Hover,
7
9
  type Position,
8
10
  } from "vscode-languageserver/node";
11
+ import type {
12
+ BindingDeclaration,
13
+ BindingTarget,
14
+ BlockStatement,
15
+ EffectBindStatement,
16
+ ErrorDeclaration,
17
+ ExportDeclaration,
18
+ Expression,
19
+ FunctionExpression,
20
+ ImportDeclaration,
21
+ ImportSpecifier,
22
+ JSXAttribute,
23
+ JSXElement,
24
+ JSXTagName,
25
+ Parameter,
26
+ Program,
27
+ RecordFieldSchema,
28
+ SchemaDeclaration,
29
+ ServiceDeclaration,
30
+ ServiceMember,
31
+ TopLevelDeclaration,
32
+ TypeNode,
33
+ VariantDeclaration,
34
+ } from "../ast/types.js";
9
35
  import { compileString, type CompileResult } from "../compiler.js";
10
- import { resolveImportedSchemas } from "../compiler/schemas/imported-schemas.js";
36
+ import { pipelineCompanionCandidates } from "../compiler/pipelines/catalog.js";
11
37
  import { inferPipelineCompanions } from "../compiler/pipelines/companions.js";
38
+ import { resolveImportedSchemas } from "../compiler/schemas/imported-schemas.js";
12
39
  import { TypeScriptCompilationContext } from "../compiler/typescript-context.js";
13
40
  import { Emitter } from "../emitter/emitter.js";
14
- import { pipelineCompanionCandidates } from "../compiler/pipelines/catalog.js";
41
+ import {
42
+ FunScriptError,
43
+ isExpectedSyntaxError,
44
+ isExpectedUriError,
45
+ isFileNotFoundError,
46
+ } from "../errors.js";
15
47
  import { Lexer } from "../lexer/lexer.js";
16
48
  import {
17
49
  BANNED_KEYWORDS,
@@ -20,14 +52,1261 @@ import {
20
52
  type Token,
21
53
  } from "../lexer/tokens.js";
22
54
  import { Parser } from "../parser/parser.js";
23
- import { spanToRange } from "./definition.js";
55
+ import { detectJsxContext } from "./completion.js";
56
+ import {
57
+ DefinitionFinder,
58
+ findDefinition,
59
+ isPositionInSpan,
60
+ spanToRange,
61
+ } from "./definition.js";
24
62
  import { getHoverDocumentation } from "./docs.js";
25
- import { FunScriptError } from "../errors.js";
63
+
64
+ export interface HoverDocument {
65
+ uri: string;
66
+ text: string;
67
+ }
68
+
69
+ type JsxAttrHit = { tagName: JSXTagName; attr: JSXAttribute };
70
+
71
+ type AstDeclNode =
72
+ | ExportDeclaration
73
+ | SchemaDeclaration
74
+ | ErrorDeclaration
75
+ | ServiceDeclaration
76
+ | BindingDeclaration
77
+ | ImportSpecifier
78
+ | VariantDeclaration
79
+ | ServiceMember
80
+ | RecordFieldSchema
81
+ | Parameter
82
+ | EffectBindStatement;
26
83
 
27
84
  function isExpectedHoverError(error: unknown): boolean {
28
85
  return error instanceof FunScriptError || error instanceof URIError;
29
86
  }
30
87
 
88
+ function isWordChar(ch: string): boolean {
89
+ return /[A-Za-z0-9_]/.test(ch);
90
+ }
91
+
92
+ function tryParseProgram(
93
+ source: string,
94
+ uri: string,
95
+ existingTokens?: Token[] | null,
96
+ ): Program | null {
97
+ try {
98
+ const tokens = existingTokens ?? new Lexer(source, uri).tokenize();
99
+ return new Parser(tokens, uri, source).parse();
100
+ } catch (error) {
101
+ if (!isExpectedSyntaxError(error)) throw error;
102
+ return null;
103
+ }
104
+ }
105
+
106
+ function formatBindingTarget(target: BindingTarget): string {
107
+ if (target.kind === "Identifier" || target.kind === "UpperIdentifier") {
108
+ return target.name;
109
+ }
110
+ if (target.kind === "RecordPattern") {
111
+ return `{ ${target.fields
112
+ .map((f) =>
113
+ f.pattern
114
+ ? `${f.key.name}: ${formatBindingTarget(f.pattern as BindingTarget)}`
115
+ : f.key.name,
116
+ )
117
+ .join(", ")} }`;
118
+ }
119
+ return `[${target.elements.map((e) => ("name" in e && typeof e.name === "object" && e.name && "name" in e.name ? String(e.name.name) : "_")).join(", ")}]`;
120
+ }
121
+
122
+ function formatTypeNode(typeNode: TypeNode): string {
123
+ switch (typeNode.kind) {
124
+ case "TypeReferenceNode": {
125
+ const args =
126
+ typeNode.typeArgs && typeNode.typeArgs.length > 0
127
+ ? `<${typeNode.typeArgs.map(formatTypeNode).join(", ")}>`
128
+ : "";
129
+ return `${typeNode.name.name}${args}`;
130
+ }
131
+ case "QualifiedTypeReferenceNode": {
132
+ const args =
133
+ typeNode.typeArgs && typeNode.typeArgs.length > 0
134
+ ? `<${typeNode.typeArgs.map(formatTypeNode).join(", ")}>`
135
+ : "";
136
+ return `${typeNode.parts.map((p) => p.name).join(".")}${args}`;
137
+ }
138
+ case "FunctionTypeNode": {
139
+ const tp =
140
+ typeNode.typeParams && typeNode.typeParams.length > 0
141
+ ? `<${typeNode.typeParams.map((p) => p.name.name).join(", ")}>`
142
+ : "";
143
+ const params = typeNode.params
144
+ .map((p) =>
145
+ p.typeAnnotation
146
+ ? `${formatBindingTarget(p.name)}: ${formatTypeNode(p.typeAnnotation)}`
147
+ : formatBindingTarget(p.name),
148
+ )
149
+ .join(", ");
150
+ return `${tp}(${params}) => ${formatTypeNode(typeNode.returnType)}`;
151
+ }
152
+ case "EffectTypeNode": {
153
+ const parts = [formatTypeNode(typeNode.success)];
154
+ if (typeNode.error) parts.push(formatTypeNode(typeNode.error));
155
+ if (typeNode.requirements) {
156
+ if (!typeNode.error) parts.push("never");
157
+ parts.push(formatTypeNode(typeNode.requirements));
158
+ }
159
+ return `Effect<${parts.join(", ")}>`;
160
+ }
161
+ case "RecordTypeNode": {
162
+ if (typeNode.fields.length === 0) return "{}";
163
+ const fields = typeNode.fields
164
+ .map(
165
+ (f) =>
166
+ `${f.name.name}${f.optional ? "?" : ""}: ${formatTypeNode(f.typeAnnotation)}`,
167
+ )
168
+ .join(", ");
169
+ return `{ ${fields} }`;
170
+ }
171
+ case "ArrayTypeNode":
172
+ return `Array<${formatTypeNode(typeNode.elementType)}>`;
173
+ case "UnionTypeNode":
174
+ return typeNode.types.map(formatTypeNode).join(" | ");
175
+ case "IntersectionTypeNode":
176
+ return typeNode.types.map(formatTypeNode).join(" & ");
177
+ case "LiteralTypeNode":
178
+ return typeof typeNode.value === "string"
179
+ ? JSON.stringify(typeNode.value)
180
+ : String(typeNode.value);
181
+ case "ParenthesizedTypeNode":
182
+ return `(${formatTypeNode(typeNode.typeNode)})`;
183
+ case "TypeQueryNode":
184
+ return "typeof ...";
185
+ case "IndexedAccessTypeNode":
186
+ return `${formatTypeNode(typeNode.objectType)}[${formatTypeNode(typeNode.indexType)}]`;
187
+ case "TsEscapeTypeNode":
188
+ return `ts { ${typeNode.code.trim()} }`;
189
+ }
190
+ }
191
+
192
+ function inferQuickExprType(expr: Expression): string {
193
+ switch (expr.kind) {
194
+ case "NumberLiteral":
195
+ return "number";
196
+ case "StringLiteral":
197
+ return "string";
198
+ case "BooleanLiteral":
199
+ return "boolean";
200
+ case "ArrayExpression":
201
+ return "Array<unknown>";
202
+ case "RecordExpression":
203
+ return "{ ... }";
204
+ case "EffectBlockExpression":
205
+ return "Effect<...>";
206
+ case "JSXElement":
207
+ case "JSXSelfClosingElement":
208
+ return "JSX.Element";
209
+ case "FunctionExpression":
210
+ return formatFunctionSignature("fn", expr).replace(/^fn = /, "");
211
+ default:
212
+ return "unknown";
213
+ }
214
+ }
215
+
216
+ function formatFunctionSignature(
217
+ name: string,
218
+ fn: FunctionExpression,
219
+ explicitType?: TypeNode,
220
+ ): string {
221
+ if (explicitType) {
222
+ return `${name}: ${formatTypeNode(explicitType)}`;
223
+ }
224
+ const tp =
225
+ fn.typeParams && fn.typeParams.length > 0
226
+ ? `<${fn.typeParams.map((p) => p.name.name).join(", ")}>`
227
+ : "";
228
+ const params = fn.params
229
+ .map((p) =>
230
+ p.typeAnnotation
231
+ ? `${formatBindingTarget(p.name)}: ${formatTypeNode(p.typeAnnotation)}`
232
+ : formatBindingTarget(p.name),
233
+ )
234
+ .join(", ");
235
+ const ret = fn.returnType
236
+ ? formatTypeNode(fn.returnType)
237
+ : fn.body.kind === "BlockStatement"
238
+ ? "unknown"
239
+ : inferQuickExprType(fn.body);
240
+ return `${name} = ${tp}(${params}) => ${ret}`;
241
+ }
242
+
243
+ function extractLeadingDocComment(
244
+ source: string,
245
+ oneBasedLine: number,
246
+ ): string | null {
247
+ const lines = source.split(/\r?\n/);
248
+ const commentLines: string[] = [];
249
+ let idx = oneBasedLine - 2;
250
+ while (idx >= 0) {
251
+ const trimmed = lines[idx].trim();
252
+ if (trimmed.startsWith("//")) {
253
+ commentLines.push(trimmed.replace(/^\/\/\/?\s?/, ""));
254
+ idx--;
255
+ continue;
256
+ }
257
+ break;
258
+ }
259
+ if (commentLines.length === 0) return null;
260
+ return commentLines.reverse().join("\n").trim() || null;
261
+ }
262
+
263
+ function formatMarkdownHover(
264
+ signature: string,
265
+ kindLabel: string,
266
+ name: string,
267
+ docComment: string | null,
268
+ originInfo?: string,
269
+ ): string {
270
+ const parts = [`\`\`\`funscript\n${signature}\n\`\`\``, "***"];
271
+ const header = originInfo
272
+ ? `**${kindLabel}** \`${name}\` — ${originInfo}`
273
+ : `**${kindLabel}** \`${name}\``;
274
+ parts.push(header);
275
+ if (docComment) {
276
+ parts.push(docComment);
277
+ }
278
+ return parts.join("\n\n");
279
+ }
280
+
281
+ function resolveRelativeModule(
282
+ fromUri: string,
283
+ modulePath: string,
284
+ documents?: HoverDocument[],
285
+ ): HoverDocument | null {
286
+ if (!modulePath.startsWith(".")) return null;
287
+ let base: string;
288
+ try {
289
+ base = resolve(dirname(fileURLToPath(fromUri)), modulePath);
290
+ } catch (error) {
291
+ if (!isExpectedUriError(error)) throw error;
292
+ return null;
293
+ }
294
+
295
+ const candidates = [
296
+ base,
297
+ `${base}.fun`,
298
+ `${base}.funs`,
299
+ `${base}.funx`,
300
+ `${base}.ts`,
301
+ `${base}.tsx`,
302
+ resolve(base, "index.fun"),
303
+ resolve(base, "index.funs"),
304
+ resolve(base, "index.funx"),
305
+ ];
306
+
307
+ if (documents) {
308
+ for (const doc of documents) {
309
+ try {
310
+ if (candidates.includes(fileURLToPath(doc.uri))) {
311
+ return doc;
312
+ }
313
+ } catch (error) {
314
+ if (!isExpectedUriError(error)) throw error;
315
+ }
316
+ }
317
+ }
318
+
319
+ for (const candidate of candidates) {
320
+ try {
321
+ if (existsSync(candidate)) {
322
+ return {
323
+ uri: pathToFileURL(candidate).href,
324
+ text: readFileSync(candidate, "utf8"),
325
+ };
326
+ }
327
+ } catch (error) {
328
+ if (!isFileNotFoundError(error) && !isExpectedUriError(error))
329
+ throw error;
330
+ }
331
+ }
332
+
333
+ return null;
334
+ }
335
+
336
+ function findExportedDeclaration(
337
+ program: Program,
338
+ name: string,
339
+ ): { outer: ExportDeclaration; decl: ExportDeclaration["declaration"] } | null {
340
+ for (const entry of program.body) {
341
+ if (entry.kind !== "ExportDeclaration") continue;
342
+ if (
343
+ "id" in entry.declaration &&
344
+ "name" in entry.declaration.id &&
345
+ entry.declaration.id.name === name
346
+ ) {
347
+ return { outer: entry, decl: entry.declaration };
348
+ }
349
+ }
350
+ return null;
351
+ }
352
+
353
+ function findImportedDeclaration(
354
+ program: Program,
355
+ uri: string,
356
+ localName: string,
357
+ documents?: HoverDocument[],
358
+ ): {
359
+ doc: HoverDocument;
360
+ modulePath: string;
361
+ outer: ExportDeclaration;
362
+ decl: ExportDeclaration["declaration"];
363
+ } | null {
364
+ for (const item of program.body) {
365
+ if (item.kind !== "ImportDeclaration") continue;
366
+ const spec = item.specifiers.find(
367
+ (s) => (s.local ?? s.imported).name === localName,
368
+ );
369
+ if (!spec) continue;
370
+ const modulePath = item.source.parts
371
+ .map((part) => (part.kind === "StringRawPart" ? part.value : ""))
372
+ .join("");
373
+ const targetDoc = resolveRelativeModule(uri, modulePath, documents);
374
+ if (!targetDoc) continue;
375
+ const targetAst = tryParseProgram(targetDoc.text, targetDoc.uri);
376
+ if (!targetAst) continue;
377
+ const found = findExportedDeclaration(targetAst, spec.imported.name);
378
+ if (found) {
379
+ return {
380
+ doc: targetDoc,
381
+ modulePath,
382
+ outer: found.outer,
383
+ decl: found.decl,
384
+ };
385
+ }
386
+ }
387
+ return null;
388
+ }
389
+
390
+ function formatSchemaSignature(
391
+ decl: SchemaDeclaration,
392
+ isExported: boolean,
393
+ ): string {
394
+ const prefix = isExported ? "export " : "";
395
+ const tp =
396
+ decl.typeParams && decl.typeParams.length > 0
397
+ ? `<${decl.typeParams.map((p) => p.name.name).join(", ")}>`
398
+ : "";
399
+ const header = `${prefix}schema ${decl.id.name}${tp}`;
400
+ switch (decl.body.kind) {
401
+ case "RecordSchema": {
402
+ if (decl.body.fields.length === 0) return `${header} = {}`;
403
+ const fields = decl.body.fields
404
+ .map((f) => ` ${f.name.name}: ${formatTypeNode(f.typeAnnotation)}`)
405
+ .join("\n");
406
+ return `${header} = {\n${fields}\n}`;
407
+ }
408
+ case "TaggedUnionSchema": {
409
+ const variants = decl.body.variants
410
+ .map((v) => {
411
+ if (v.fields.length === 0) return ` | ${v.name.name}`;
412
+ const fields = v.fields
413
+ .map((f) => `${f.name.name}: ${formatTypeNode(f.typeAnnotation)}`)
414
+ .join(", ");
415
+ return ` | ${v.name.name}(${fields})`;
416
+ })
417
+ .join("\n");
418
+ return `${header} =\n${variants}`;
419
+ }
420
+ case "StructuralUnionSchema":
421
+ return `${header} = ${decl.body.members.map(formatTypeNode).join(" | ")}`;
422
+ case "RefinementSchema":
423
+ return `${header} = ${formatTypeNode(decl.body.baseType)} |> ...`;
424
+ case "TypeSignatureSchema":
425
+ return `${header} = ${formatTypeNode(decl.body.signature)}`;
426
+ case "TsDerivedSchema":
427
+ return `${header} = ts ${formatTypeNode(decl.body.targetType)}`;
428
+ case "ImportedTsSchema":
429
+ return `${header} = from ts<${formatTypeNode(decl.body.typeNode)}>`;
430
+ }
431
+ }
432
+
433
+ function formatErrorSignature(
434
+ decl: ErrorDeclaration,
435
+ isExported: boolean,
436
+ ): string {
437
+ const prefix = isExported ? "export " : "";
438
+ if (decl.fields.length === 0) {
439
+ return `${prefix}error ${decl.id.name}`;
440
+ }
441
+ const fields = decl.fields
442
+ .map((f) => `${f.name.name}: ${formatTypeNode(f.typeAnnotation)}`)
443
+ .join(", ");
444
+ return `${prefix}error ${decl.id.name}(${fields})`;
445
+ }
446
+
447
+ function formatServiceSignature(
448
+ decl: ServiceDeclaration,
449
+ isExported: boolean,
450
+ ): string {
451
+ const prefix = isExported ? "export " : "";
452
+ if (decl.members.length === 0) {
453
+ return `${prefix}service ${decl.id.name}`;
454
+ }
455
+ const members = decl.members
456
+ .map((m) => ` ${m.name.name}: ${formatTypeNode(m.signature)}`)
457
+ .join("\n");
458
+ return `${prefix}service ${decl.id.name}\n${members}`;
459
+ }
460
+
461
+ function formatTopLevelDeclarationHover(
462
+ decl:
463
+ | SchemaDeclaration
464
+ | ErrorDeclaration
465
+ | ServiceDeclaration
466
+ | BindingDeclaration,
467
+ outer: TopLevelDeclaration,
468
+ source: string,
469
+ originInfo?: string,
470
+ ): string {
471
+ const isExported = outer.kind === "ExportDeclaration";
472
+ const docComment = extractLeadingDocComment(source, outer.span.start.line);
473
+
474
+ switch (decl.kind) {
475
+ case "SchemaDeclaration":
476
+ return formatMarkdownHover(
477
+ formatSchemaSignature(decl, isExported),
478
+ "schema",
479
+ decl.id.name,
480
+ docComment,
481
+ originInfo,
482
+ );
483
+ case "ErrorDeclaration":
484
+ return formatMarkdownHover(
485
+ formatErrorSignature(decl, isExported),
486
+ "error",
487
+ decl.id.name,
488
+ docComment,
489
+ originInfo,
490
+ );
491
+ case "ServiceDeclaration":
492
+ return formatMarkdownHover(
493
+ formatServiceSignature(decl, isExported),
494
+ "service",
495
+ decl.id.name,
496
+ docComment,
497
+ originInfo,
498
+ );
499
+ case "BindingDeclaration": {
500
+ const bindingName = formatBindingTarget(decl.id);
501
+ const prefix = `${isExported ? "export " : ""}${decl.isMut ? "mut " : ""}`;
502
+ if (decl.init.kind === "FunctionExpression") {
503
+ const sig = `${prefix}${formatFunctionSignature(bindingName, decl.init, decl.typeAnnotation)}`;
504
+ return formatMarkdownHover(
505
+ sig,
506
+ "function",
507
+ bindingName,
508
+ docComment,
509
+ originInfo,
510
+ );
511
+ }
512
+ const typeStr = decl.typeAnnotation
513
+ ? `: ${formatTypeNode(decl.typeAnnotation)}`
514
+ : ` = ${inferQuickExprType(decl.init)}`;
515
+ return formatMarkdownHover(
516
+ `${prefix}${bindingName}${typeStr}`,
517
+ "binding",
518
+ bindingName,
519
+ docComment,
520
+ originInfo,
521
+ );
522
+ }
523
+ }
524
+ }
525
+
526
+ function findHoverInAst(
527
+ source: string,
528
+ uri: string,
529
+ posLine: number,
530
+ posCol: number,
531
+ tokens?: Token[] | null,
532
+ documents?: HoverDocument[],
533
+ ): Hover | null {
534
+ const program = tryParseProgram(source, uri, tokens);
535
+ if (!program) return null;
536
+
537
+ const finder = new DefinitionFinder(posLine, posCol);
538
+ const match = finder.find(program);
539
+ if (!match) return null;
540
+
541
+ const range = spanToRange(match.originNode.span);
542
+ const declNode = match.declarationNode as AstDeclNode;
543
+
544
+ if (declNode.kind === "ExportDeclaration") {
545
+ return {
546
+ contents: {
547
+ kind: MarkupKind.Markdown,
548
+ value: formatTopLevelDeclarationHover(
549
+ declNode.declaration,
550
+ declNode,
551
+ source,
552
+ ),
553
+ },
554
+ range,
555
+ };
556
+ }
557
+
558
+ if (
559
+ declNode.kind === "SchemaDeclaration" ||
560
+ declNode.kind === "ErrorDeclaration" ||
561
+ declNode.kind === "ServiceDeclaration" ||
562
+ declNode.kind === "BindingDeclaration"
563
+ ) {
564
+ return {
565
+ contents: {
566
+ kind: MarkupKind.Markdown,
567
+ value: formatTopLevelDeclarationHover(declNode, declNode, source),
568
+ },
569
+ range,
570
+ };
571
+ }
572
+
573
+ if (declNode.kind === "ImportSpecifier") {
574
+ const spec = declNode;
575
+ const importDecl = program.body.find(
576
+ (entry): entry is ImportDeclaration =>
577
+ entry.kind === "ImportDeclaration" && entry.specifiers.includes(spec),
578
+ );
579
+ if (!importDecl) return null;
580
+ const localName = (spec.local ?? spec.imported).name;
581
+ const imported = findImportedDeclaration(
582
+ program,
583
+ uri,
584
+ localName,
585
+ documents,
586
+ );
587
+ if (!imported) return null;
588
+ return {
589
+ contents: {
590
+ kind: MarkupKind.Markdown,
591
+ value: formatTopLevelDeclarationHover(
592
+ imported.decl,
593
+ imported.outer,
594
+ imported.doc.text,
595
+ `imported from \`${imported.modulePath}\``,
596
+ ),
597
+ },
598
+ range,
599
+ };
600
+ }
601
+
602
+ return null;
603
+ }
604
+
605
+ function findTokenAtPosition(
606
+ tokens: Token[],
607
+ posLine: number,
608
+ posCol: number,
609
+ ): { token: Token; index: number } | null {
610
+ const lineTokens: { token: Token; index: number }[] = [];
611
+ for (let i = 0; i < tokens.length; i++) {
612
+ const t = tokens[i];
613
+ if (t.span.start.line === posLine) {
614
+ lineTokens.push({ token: t, index: i });
615
+ }
616
+ }
617
+ if (lineTokens.length === 0) return null;
618
+
619
+ for (const entry of lineTokens) {
620
+ if (
621
+ posCol >= entry.token.span.start.column &&
622
+ posCol < entry.token.span.end.column
623
+ ) {
624
+ return entry;
625
+ }
626
+ }
627
+ for (const entry of lineTokens) {
628
+ if (posCol === entry.token.span.end.column) {
629
+ return entry;
630
+ }
631
+ }
632
+ return null;
633
+ }
634
+
635
+ function isJsxPunctuationOrTextToken(type: TokenType): boolean {
636
+ return (
637
+ type === TokenType.JSX_TEXT ||
638
+ type === TokenType.JSX_TAG_OPEN ||
639
+ type === TokenType.JSX_TAG_CLOSE ||
640
+ type === TokenType.JSX_SLASH_CLOSE ||
641
+ type === TokenType.JSX_CLOSING_TAG_OPEN ||
642
+ type === TokenType.JSX_ATTRIBUTE_NAME
643
+ );
644
+ }
645
+
646
+ function isJsxTagNameToken(tokens: Token[], index: number): boolean {
647
+ const tok = tokens[index];
648
+ if (
649
+ tok.type !== TokenType.IDENTIFIER &&
650
+ tok.type !== TokenType.UPPER_IDENTIFIER
651
+ ) {
652
+ return false;
653
+ }
654
+ let i = index - 1;
655
+ while (i >= 1 && tokens[i].type === TokenType.DOT) {
656
+ const prev = tokens[i - 1];
657
+ if (
658
+ prev.type !== TokenType.IDENTIFIER &&
659
+ prev.type !== TokenType.UPPER_IDENTIFIER
660
+ ) {
661
+ return false;
662
+ }
663
+ i -= 2;
664
+ }
665
+ if (i < 0) return false;
666
+ return (
667
+ tokens[i].type === TokenType.JSX_TAG_OPEN ||
668
+ tokens[i].type === TokenType.JSX_CLOSING_TAG_OPEN
669
+ );
670
+ }
671
+
672
+ function formatTagName(tagName: JSXTagName): string {
673
+ if (tagName.kind === "Identifier" || tagName.kind === "UpperIdentifier") {
674
+ return tagName.name;
675
+ }
676
+ return `${formatTagName(tagName.object as JSXTagName)}.${tagName.property.name}`;
677
+ }
678
+
679
+ function findJsxAttributeInList(
680
+ tagName: JSXTagName,
681
+ attributes: JSXElement["openingElement"]["attributes"],
682
+ posLine: number,
683
+ posCol: number,
684
+ ): JsxAttrHit | null {
685
+ for (const attr of attributes) {
686
+ if (attr.kind === "JSXSpreadAttribute") {
687
+ const nested = findJsxAttributeInExpr(attr.argument, posLine, posCol);
688
+ if (nested) return nested;
689
+ continue;
690
+ }
691
+ if (isPositionInSpan(posLine, posCol, attr.name.span)) {
692
+ return { tagName, attr };
693
+ }
694
+ if (attr.value?.kind === "JSXExpressionContainer") {
695
+ const nested = findJsxAttributeInExpr(
696
+ attr.value.expression,
697
+ posLine,
698
+ posCol,
699
+ );
700
+ if (nested) return nested;
701
+ }
702
+ }
703
+ return null;
704
+ }
705
+
706
+ function findJsxAttributeInExpr(
707
+ expr: Expression,
708
+ posLine: number,
709
+ posCol: number,
710
+ ): JsxAttrHit | null {
711
+ switch (expr.kind) {
712
+ case "JSXElement": {
713
+ const inAttrs = findJsxAttributeInList(
714
+ expr.openingElement.name,
715
+ expr.openingElement.attributes,
716
+ posLine,
717
+ posCol,
718
+ );
719
+ if (inAttrs) return inAttrs;
720
+ for (const child of expr.children) {
721
+ if (
722
+ child.kind === "JSXElement" ||
723
+ child.kind === "JSXSelfClosingElement"
724
+ ) {
725
+ const nested = findJsxAttributeInExpr(child, posLine, posCol);
726
+ if (nested) return nested;
727
+ } else if (child.kind === "JSXExpressionContainer") {
728
+ const nested = findJsxAttributeInExpr(
729
+ child.expression,
730
+ posLine,
731
+ posCol,
732
+ );
733
+ if (nested) return nested;
734
+ }
735
+ }
736
+ return null;
737
+ }
738
+ case "JSXSelfClosingElement":
739
+ return findJsxAttributeInList(
740
+ expr.name,
741
+ expr.attributes,
742
+ posLine,
743
+ posCol,
744
+ );
745
+ case "FunctionExpression":
746
+ case "MutBlockExpression":
747
+ return expr.body.kind === "BlockStatement"
748
+ ? findJsxAttributeInBlock(expr.body, posLine, posCol)
749
+ : findJsxAttributeInExpr(expr.body, posLine, posCol);
750
+ case "PipelineExpression":
751
+ case "BinaryExpression":
752
+ return (
753
+ findJsxAttributeInExpr(expr.left, posLine, posCol) ??
754
+ findJsxAttributeInExpr(expr.right, posLine, posCol)
755
+ );
756
+ case "UnaryExpression":
757
+ return findJsxAttributeInExpr(expr.argument, posLine, posCol);
758
+ case "CallExpression": {
759
+ const inCallee = findJsxAttributeInExpr(expr.callee, posLine, posCol);
760
+ if (inCallee) return inCallee;
761
+ for (const arg of expr.args) {
762
+ const inArg = findJsxAttributeInExpr(arg, posLine, posCol);
763
+ if (inArg) return inArg;
764
+ }
765
+ return null;
766
+ }
767
+ case "MemberExpression":
768
+ return findJsxAttributeInExpr(expr.object, posLine, posCol);
769
+ case "IndexExpression":
770
+ return (
771
+ findJsxAttributeInExpr(expr.object, posLine, posCol) ??
772
+ findJsxAttributeInExpr(expr.index, posLine, posCol)
773
+ );
774
+ case "RecordExpression": {
775
+ for (const entry of expr.entries) {
776
+ if (entry.kind === "ShorthandEntry") continue;
777
+ const inner =
778
+ entry.kind === "SpreadEntry" ? entry.argument : entry.value;
779
+ const found = findJsxAttributeInExpr(inner, posLine, posCol);
780
+ if (found) return found;
781
+ }
782
+ return null;
783
+ }
784
+ case "ArrayExpression": {
785
+ for (const el of expr.elements) {
786
+ const found = findJsxAttributeInExpr(el, posLine, posCol);
787
+ if (found) return found;
788
+ }
789
+ return null;
790
+ }
791
+ case "MatchExpression": {
792
+ const inSubj = expr.scrutinee
793
+ ? findJsxAttributeInExpr(expr.scrutinee, posLine, posCol)
794
+ : null;
795
+ if (inSubj) return inSubj;
796
+ for (const arm of expr.arms) {
797
+ if (arm.guard) {
798
+ const inGuard = findJsxAttributeInExpr(arm.guard, posLine, posCol);
799
+ if (inGuard) return inGuard;
800
+ }
801
+ const inBody =
802
+ arm.body.kind === "BlockStatement"
803
+ ? findJsxAttributeInBlock(arm.body, posLine, posCol)
804
+ : findJsxAttributeInExpr(arm.body, posLine, posCol);
805
+ if (inBody) return inBody;
806
+ }
807
+ return null;
808
+ }
809
+ case "EffectBlockExpression": {
810
+ for (const stmt of expr.body) {
811
+ if (
812
+ stmt.kind === "EffectBindStatement" ||
813
+ stmt.kind === "EffectDiscardStatement"
814
+ ) {
815
+ const found = findJsxAttributeInExpr(stmt.effect, posLine, posCol);
816
+ if (found) return found;
817
+ } else if (stmt.kind === "EffectControlFlowStatement") {
818
+ const found = findJsxAttributeInExpr(stmt.statement, posLine, posCol);
819
+ if (found) return found;
820
+ } else if (stmt.kind === "BindingDeclaration") {
821
+ const found = findJsxAttributeInExpr(stmt.init, posLine, posCol);
822
+ if (found) return found;
823
+ } else if (stmt.kind === "AssignmentStatement") {
824
+ const found = findJsxAttributeInExpr(stmt.value, posLine, posCol);
825
+ if (found) return found;
826
+ } else if (stmt.kind === "WhenStatement") {
827
+ const inCond = findJsxAttributeInExpr(
828
+ stmt.condition,
829
+ posLine,
830
+ posCol,
831
+ );
832
+ if (inCond) return inCond;
833
+ const inCons = stmt.isEarlyReturn
834
+ ? findJsxAttributeInExpr(
835
+ stmt.consequent as Expression,
836
+ posLine,
837
+ posCol,
838
+ )
839
+ : findJsxAttributeInBlock(
840
+ stmt.consequent as BlockStatement,
841
+ posLine,
842
+ posCol,
843
+ );
844
+ if (inCons) return inCons;
845
+ }
846
+ }
847
+ return findJsxAttributeInExpr(expr.finalExpression, posLine, posCol);
848
+ }
849
+ case "StringLiteral":
850
+ case "TemplateLiteral": {
851
+ for (const part of expr.parts) {
852
+ if (part.kind === "StringInterpolationPart") {
853
+ const found = findJsxAttributeInExpr(
854
+ part.expression,
855
+ posLine,
856
+ posCol,
857
+ );
858
+ if (found) return found;
859
+ }
860
+ }
861
+ return null;
862
+ }
863
+ default:
864
+ return null;
865
+ }
866
+ }
867
+
868
+ function findJsxAttributeInBlock(
869
+ block: Pick<BlockStatement, "statements" | "finalExpression">,
870
+ posLine: number,
871
+ posCol: number,
872
+ ): JsxAttrHit | null {
873
+ for (const stmt of block.statements) {
874
+ if (stmt.kind === "BindingDeclaration") {
875
+ const found = findJsxAttributeInExpr(stmt.init, posLine, posCol);
876
+ if (found) return found;
877
+ } else if (stmt.kind === "AssignmentStatement") {
878
+ const found = findJsxAttributeInExpr(stmt.value, posLine, posCol);
879
+ if (found) return found;
880
+ } else if (stmt.kind === "ExpressionStatement") {
881
+ const found = findJsxAttributeInExpr(stmt.expression, posLine, posCol);
882
+ if (found) return found;
883
+ } else if (stmt.kind === "ReturnStatement") {
884
+ const found = findJsxAttributeInExpr(stmt.argument, posLine, posCol);
885
+ if (found) return found;
886
+ } else if (stmt.kind === "WhenStatement") {
887
+ const inCond = findJsxAttributeInExpr(stmt.condition, posLine, posCol);
888
+ if (inCond) return inCond;
889
+ const inCons = stmt.isEarlyReturn
890
+ ? findJsxAttributeInExpr(stmt.consequent as Expression, posLine, posCol)
891
+ : findJsxAttributeInBlock(
892
+ stmt.consequent as BlockStatement,
893
+ posLine,
894
+ posCol,
895
+ );
896
+ if (inCons) return inCons;
897
+ }
898
+ }
899
+ return block.finalExpression
900
+ ? findJsxAttributeInExpr(block.finalExpression, posLine, posCol)
901
+ : null;
902
+ }
903
+
904
+ function findJsxAttributeInProgram(
905
+ program: Program,
906
+ posLine: number,
907
+ posCol: number,
908
+ ): JsxAttrHit | null {
909
+ for (const top of program.body) {
910
+ const inner = top.kind === "ExportDeclaration" ? top.declaration : top;
911
+ if (inner.kind === "BindingDeclaration") {
912
+ const found = findJsxAttributeInExpr(inner.init, posLine, posCol);
913
+ if (found) return found;
914
+ } else if (inner.kind === "ExportDefaultDeclaration") {
915
+ const found = findJsxAttributeInExpr(inner.expression, posLine, posCol);
916
+ if (found) return found;
917
+ }
918
+ }
919
+ return null;
920
+ }
921
+
922
+ function resolveBindingDeclaration(
923
+ program: Program,
924
+ source: string,
925
+ uri: string,
926
+ name: string,
927
+ usageLine: number,
928
+ usageCol: number,
929
+ documents?: HoverDocument[],
930
+ ): {
931
+ decl: BindingDeclaration;
932
+ ownerProgram: Program;
933
+ ownerSource: string;
934
+ ownerUri: string;
935
+ originInfo?: string;
936
+ } | null {
937
+ const def = new DefinitionFinder(usageLine, usageCol).find(program);
938
+ if (def) {
939
+ const declNode = def.declarationNode as AstDeclNode;
940
+ const raw =
941
+ declNode.kind === "ExportDeclaration" ? declNode.declaration : declNode;
942
+ if (raw.kind === "BindingDeclaration") {
943
+ return {
944
+ decl: raw,
945
+ ownerProgram: program,
946
+ ownerSource: source,
947
+ ownerUri: uri,
948
+ };
949
+ }
950
+ if (raw.kind === "ImportSpecifier") {
951
+ const localName = (raw.local ?? raw.imported).name;
952
+ const imported = findImportedDeclaration(
953
+ program,
954
+ uri,
955
+ localName,
956
+ documents,
957
+ );
958
+ if (imported && imported.decl.kind === "BindingDeclaration") {
959
+ const ownerProgram = tryParseProgram(
960
+ imported.doc.text,
961
+ imported.doc.uri,
962
+ );
963
+ if (ownerProgram) {
964
+ return {
965
+ decl: imported.decl,
966
+ ownerProgram,
967
+ ownerSource: imported.doc.text,
968
+ ownerUri: imported.doc.uri,
969
+ originInfo: `imported from \`${imported.modulePath}\``,
970
+ };
971
+ }
972
+ }
973
+ }
974
+ }
975
+
976
+ for (const top of program.body) {
977
+ const inner = top.kind === "ExportDeclaration" ? top.declaration : top;
978
+ if (
979
+ inner.kind === "BindingDeclaration" &&
980
+ "name" in inner.id &&
981
+ inner.id.name === name
982
+ ) {
983
+ return {
984
+ decl: inner,
985
+ ownerProgram: program,
986
+ ownerSource: source,
987
+ ownerUri: uri,
988
+ };
989
+ }
990
+ }
991
+
992
+ const imported = findImportedDeclaration(program, uri, name, documents);
993
+ if (imported && imported.decl.kind === "BindingDeclaration") {
994
+ const ownerProgram = tryParseProgram(imported.doc.text, imported.doc.uri);
995
+ if (ownerProgram) {
996
+ return {
997
+ decl: imported.decl,
998
+ ownerProgram,
999
+ ownerSource: imported.doc.text,
1000
+ ownerUri: imported.doc.uri,
1001
+ originInfo: `imported from \`${imported.modulePath}\``,
1002
+ };
1003
+ }
1004
+ }
1005
+ return null;
1006
+ }
1007
+
1008
+ function resolveRecordMemberEntry(
1009
+ program: Program,
1010
+ source: string,
1011
+ uri: string,
1012
+ objectName: string,
1013
+ memberName: string,
1014
+ usageLine: number,
1015
+ usageCol: number,
1016
+ documents?: HoverDocument[],
1017
+ ): {
1018
+ expr: Expression;
1019
+ ownerProgram: Program;
1020
+ ownerSource: string;
1021
+ ownerUri: string;
1022
+ originInfo?: string;
1023
+ } | null {
1024
+ const resolved = resolveBindingDeclaration(
1025
+ program,
1026
+ source,
1027
+ uri,
1028
+ objectName,
1029
+ usageLine,
1030
+ usageCol,
1031
+ documents,
1032
+ );
1033
+ if (!resolved || resolved.decl.init.kind !== "RecordExpression") {
1034
+ return null;
1035
+ }
1036
+ const rec = resolved.decl.init;
1037
+ const field = rec.entries.find(
1038
+ (e) => e.kind === "FieldEntry" && e.key.name === memberName,
1039
+ );
1040
+ if (!field || field.kind !== "FieldEntry") {
1041
+ return null;
1042
+ }
1043
+ return {
1044
+ expr: field.value,
1045
+ ownerProgram: resolved.ownerProgram,
1046
+ ownerSource: resolved.ownerSource,
1047
+ ownerUri: resolved.ownerUri,
1048
+ originInfo: resolved.originInfo,
1049
+ };
1050
+ }
1051
+
1052
+ function findPropInTypeNode(
1053
+ typeNode: TypeNode,
1054
+ propName: string,
1055
+ ownerProgram: Program,
1056
+ ownerSource: string,
1057
+ ownerUri: string,
1058
+ documents?: HoverDocument[],
1059
+ ): { typeText: string; docComment: string | null } | null {
1060
+ if (typeNode.kind === "RecordTypeNode") {
1061
+ const field = typeNode.fields.find((f) => f.name.name === propName);
1062
+ if (!field) return null;
1063
+ return {
1064
+ typeText: formatTypeNode(field.typeAnnotation),
1065
+ docComment: extractLeadingDocComment(ownerSource, field.span.start.line),
1066
+ };
1067
+ }
1068
+ if (typeNode.kind === "TypeReferenceNode") {
1069
+ const schemaName = typeNode.name.name;
1070
+ let targetSchema: SchemaDeclaration | null = null;
1071
+ let schemaSource = ownerSource;
1072
+
1073
+ for (const top of ownerProgram.body) {
1074
+ const inner = top.kind === "ExportDeclaration" ? top.declaration : top;
1075
+ if (inner.kind === "SchemaDeclaration" && inner.id.name === schemaName) {
1076
+ targetSchema = inner;
1077
+ break;
1078
+ }
1079
+ }
1080
+
1081
+ if (!targetSchema) {
1082
+ const imported = findImportedDeclaration(
1083
+ ownerProgram,
1084
+ ownerUri,
1085
+ schemaName,
1086
+ documents,
1087
+ );
1088
+ if (imported && imported.decl.kind === "SchemaDeclaration") {
1089
+ targetSchema = imported.decl;
1090
+ schemaSource = imported.doc.text;
1091
+ }
1092
+ }
1093
+
1094
+ if (!targetSchema) return null;
1095
+ if (targetSchema.body.kind === "RecordSchema") {
1096
+ const field = targetSchema.body.fields.find(
1097
+ (f) => f.name.name === propName,
1098
+ );
1099
+ if (!field) return null;
1100
+ return {
1101
+ typeText: formatTypeNode(field.typeAnnotation),
1102
+ docComment: extractLeadingDocComment(
1103
+ schemaSource,
1104
+ field.span.start.line,
1105
+ ),
1106
+ };
1107
+ }
1108
+ }
1109
+ return null;
1110
+ }
1111
+
1112
+ function findJsxAttributeHover(
1113
+ source: string,
1114
+ uri: string,
1115
+ posLine: number,
1116
+ posCol: number,
1117
+ tokens: Token[],
1118
+ documents?: HoverDocument[],
1119
+ ): Hover | null {
1120
+ const program = tryParseProgram(source, uri, tokens);
1121
+ if (!program) return null;
1122
+ const hit = findJsxAttributeInProgram(program, posLine, posCol);
1123
+ if (!hit || hit.attr.kind !== "JSXAttribute") return null;
1124
+
1125
+ const { tagName, attr } = hit;
1126
+ let paramType: TypeNode | undefined;
1127
+ let ownerProgram: Program | null = null;
1128
+ let ownerSource = source;
1129
+ let ownerUri = uri;
1130
+ let originInfo: string | undefined;
1131
+
1132
+ if (
1133
+ tagName.kind === "MemberExpression" &&
1134
+ (tagName.object.kind === "Identifier" ||
1135
+ tagName.object.kind === "UpperIdentifier")
1136
+ ) {
1137
+ const member = resolveRecordMemberEntry(
1138
+ program,
1139
+ source,
1140
+ uri,
1141
+ tagName.object.name,
1142
+ tagName.property.name,
1143
+ tagName.object.span.start.line,
1144
+ tagName.object.span.start.column,
1145
+ documents,
1146
+ );
1147
+ if (member && member.expr.kind === "FunctionExpression") {
1148
+ paramType = member.expr.params[0]?.typeAnnotation;
1149
+ ownerProgram = member.ownerProgram;
1150
+ ownerSource = member.ownerSource;
1151
+ ownerUri = member.ownerUri;
1152
+ originInfo = member.originInfo;
1153
+ }
1154
+ } else if (
1155
+ tagName.kind === "Identifier" ||
1156
+ tagName.kind === "UpperIdentifier"
1157
+ ) {
1158
+ const resolved = resolveBindingDeclaration(
1159
+ program,
1160
+ source,
1161
+ uri,
1162
+ tagName.name,
1163
+ tagName.span.start.line,
1164
+ tagName.span.start.column,
1165
+ documents,
1166
+ );
1167
+ if (resolved) {
1168
+ ownerProgram = resolved.ownerProgram;
1169
+ ownerSource = resolved.ownerSource;
1170
+ ownerUri = resolved.ownerUri;
1171
+ originInfo = resolved.originInfo;
1172
+ if (resolved.decl.init.kind === "FunctionExpression") {
1173
+ paramType = resolved.decl.init.params[0]?.typeAnnotation;
1174
+ } else if (resolved.decl.typeAnnotation?.kind === "FunctionTypeNode") {
1175
+ paramType = resolved.decl.typeAnnotation.params[0]?.typeAnnotation;
1176
+ }
1177
+ }
1178
+ }
1179
+
1180
+ if (!paramType || !ownerProgram) return null;
1181
+ const prop = findPropInTypeNode(
1182
+ paramType,
1183
+ attr.name.name,
1184
+ ownerProgram,
1185
+ ownerSource,
1186
+ ownerUri,
1187
+ documents,
1188
+ );
1189
+ if (!prop) return null;
1190
+
1191
+ const fullTag = formatTagName(tagName);
1192
+ return {
1193
+ contents: {
1194
+ kind: MarkupKind.Markdown,
1195
+ value: formatMarkdownHover(
1196
+ `${fullTag}.${attr.name.name}: ${prop.typeText}`,
1197
+ "prop",
1198
+ attr.name.name,
1199
+ prop.docComment,
1200
+ originInfo,
1201
+ ),
1202
+ },
1203
+ range: spanToRange(attr.name.span),
1204
+ };
1205
+ }
1206
+
1207
+ function formatRecordMemberHover(
1208
+ tokens: Token[],
1209
+ matchedIndex: number,
1210
+ source: string,
1211
+ uri: string,
1212
+ documents?: HoverDocument[],
1213
+ ): Hover | null {
1214
+ if (
1215
+ matchedIndex < 2 ||
1216
+ tokens[matchedIndex - 1].type !== TokenType.DOT ||
1217
+ (tokens[matchedIndex - 2].type !== TokenType.UPPER_IDENTIFIER &&
1218
+ tokens[matchedIndex - 2].type !== TokenType.IDENTIFIER)
1219
+ ) {
1220
+ return null;
1221
+ }
1222
+ const program = tryParseProgram(source, uri, tokens);
1223
+ if (!program) return null;
1224
+ const objTok = tokens[matchedIndex - 2];
1225
+ const token = tokens[matchedIndex];
1226
+ const recMember = resolveRecordMemberEntry(
1227
+ program,
1228
+ source,
1229
+ uri,
1230
+ objTok.value,
1231
+ token.value,
1232
+ objTok.span.start.line,
1233
+ objTok.span.start.column,
1234
+ documents,
1235
+ );
1236
+ if (!recMember) return null;
1237
+ const sig =
1238
+ recMember.expr.kind === "FunctionExpression"
1239
+ ? formatFunctionSignature(
1240
+ `${objTok.value}.${token.value}`,
1241
+ recMember.expr,
1242
+ )
1243
+ : `${objTok.value}.${token.value}: ${inferQuickExprType(recMember.expr)}`;
1244
+ const docComment = extractLeadingDocComment(
1245
+ recMember.ownerSource,
1246
+ recMember.expr.span.start.line,
1247
+ );
1248
+ return {
1249
+ contents: {
1250
+ kind: MarkupKind.Markdown,
1251
+ value: formatMarkdownHover(
1252
+ sig,
1253
+ recMember.expr.kind === "FunctionExpression" ? "function" : "property",
1254
+ `${objTok.value}.${token.value}`,
1255
+ docComment,
1256
+ recMember.originInfo,
1257
+ ),
1258
+ },
1259
+ range: spanToRange(token.span),
1260
+ };
1261
+ }
1262
+
1263
+ function findJsxTagHover(
1264
+ tokens: Token[],
1265
+ matchedIndex: number,
1266
+ posLine: number,
1267
+ posCol: number,
1268
+ source: string,
1269
+ uri: string,
1270
+ skipSymbol: boolean,
1271
+ documents?: HoverDocument[],
1272
+ ): Hover | null {
1273
+ const token = tokens[matchedIndex];
1274
+ const isMemberSegment =
1275
+ matchedIndex >= 2 && tokens[matchedIndex - 1].type === TokenType.DOT;
1276
+ const hasMemberSuffix =
1277
+ matchedIndex + 2 < tokens.length &&
1278
+ tokens[matchedIndex + 1].type === TokenType.DOT;
1279
+
1280
+ if (isMemberSegment) {
1281
+ const memberHover = formatRecordMemberHover(
1282
+ tokens,
1283
+ matchedIndex,
1284
+ source,
1285
+ uri,
1286
+ documents,
1287
+ );
1288
+ if (memberHover) return memberHover;
1289
+ } else if (token.type === TokenType.UPPER_IDENTIFIER || hasMemberSuffix) {
1290
+ const astHover = findHoverInAst(
1291
+ source,
1292
+ uri,
1293
+ posLine,
1294
+ posCol,
1295
+ tokens,
1296
+ documents,
1297
+ );
1298
+ if (astHover) return astHover;
1299
+ } else {
1300
+ // Lowercase intrinsic JSX tag (e.g. `<div>`, `<span>`)
1301
+ return null;
1302
+ }
1303
+
1304
+ if (!skipSymbol && posCol < token.span.end.column) {
1305
+ return symbolHover(source, uri, token);
1306
+ }
1307
+ return null;
1308
+ }
1309
+
31
1310
  function symbolHover(
32
1311
  source: string,
33
1312
  uri: string,
@@ -60,6 +1339,30 @@ function symbolHoverFromResult(
60
1339
  companion?: string,
61
1340
  ): Hover | null {
62
1341
  try {
1342
+ const schemaDeclaration = result.ast.body.flatMap((entry) => {
1343
+ const decl =
1344
+ entry.kind === "ExportDeclaration" ? entry.declaration : entry;
1345
+ return decl.kind === "SchemaDeclaration" &&
1346
+ decl.body.kind !== "RecordSchema" &&
1347
+ decl.body.kind !== "ImportedTsSchema" &&
1348
+ decl.id.span.start.offset === token.span.start.offset
1349
+ ? [decl]
1350
+ : [];
1351
+ });
1352
+ if (schemaDeclaration.length === 1) {
1353
+ const decl = schemaDeclaration[0];
1354
+ const signature = source.slice(
1355
+ decl.id.span.start.offset,
1356
+ decl.body.span.end.offset,
1357
+ );
1358
+ return {
1359
+ contents: {
1360
+ kind: MarkupKind.Markdown,
1361
+ value: `\`\`\`fun\nschema ${signature}\n\`\`\``,
1362
+ },
1363
+ range: spanToRange(token.span),
1364
+ };
1365
+ }
63
1366
  const schema = result.ast.body.flatMap((entry) => {
64
1367
  const decl =
65
1368
  entry.kind === "ExportDeclaration" ? entry.declaration : entry;
@@ -162,8 +1465,58 @@ function symbolHoverFromResult(
162
1465
  symbol = candidates[0].symbol;
163
1466
  node = candidates[0].node;
164
1467
  }
1468
+ const valueType = checked.checker.getTypeOfSymbolAtLocation(symbol, node);
1469
+ const resolvedType =
1470
+ valueType.flags & ts.TypeFlags.Any &&
1471
+ symbol.flags & ts.SymbolFlags.TypeAlias
1472
+ ? checked.checker.getDeclaredTypeOfSymbol(symbol)
1473
+ : valueType;
1474
+ if (
1475
+ resolvedType.flags & ts.TypeFlags.Any ||
1476
+ checked.checker.typeToString(resolvedType, node) === token.value ||
1477
+ checked.checker
1478
+ .typeToString(resolvedType, node)
1479
+ .startsWith(`${token.value}<`)
1480
+ ) {
1481
+ const location = findDefinition(
1482
+ source,
1483
+ "file:///hover.fun",
1484
+ {
1485
+ line: token.span.start.line - 1,
1486
+ character: token.span.start.column - 1,
1487
+ },
1488
+ true,
1489
+ );
1490
+ const target = Array.isArray(location)
1491
+ ? location[0]?.targetSelectionRange.start
1492
+ : undefined;
1493
+ const declaration = result.ast.body.flatMap((entry) => {
1494
+ const decl =
1495
+ entry.kind === "ExportDeclaration" ? entry.declaration : entry;
1496
+ return decl.kind === "SchemaDeclaration" &&
1497
+ target &&
1498
+ decl.id.span.start.line - 1 === target.line &&
1499
+ decl.id.span.start.column - 1 === target.character
1500
+ ? [decl]
1501
+ : [];
1502
+ });
1503
+ if (declaration.length === 1) {
1504
+ const decl = declaration[0];
1505
+ const signature = source.slice(
1506
+ decl.id.span.start.offset,
1507
+ decl.body.span.end.offset,
1508
+ );
1509
+ return {
1510
+ contents: {
1511
+ kind: MarkupKind.Markdown,
1512
+ value: `\`\`\`fun\nschema ${signature}\n\`\`\``,
1513
+ },
1514
+ range: spanToRange(token.span),
1515
+ };
1516
+ }
1517
+ }
165
1518
  const type = checked.checker.typeToString(
166
- checked.checker.getTypeOfSymbolAtLocation(symbol, node),
1519
+ resolvedType,
167
1520
  node,
168
1521
  ts.TypeFormatFlags.NoTruncation,
169
1522
  );
@@ -302,10 +1655,6 @@ function importedSchemaHover(
302
1655
  }
303
1656
  }
304
1657
 
305
- function isWordChar(ch: string): boolean {
306
- return /[A-Za-z0-9_]/.test(ch);
307
- }
308
-
309
1658
  function findHoverInTokens(
310
1659
  tokens: Token[],
311
1660
  posLine: number,
@@ -314,44 +1663,42 @@ function findHoverInTokens(
314
1663
  source: string,
315
1664
  uri: string,
316
1665
  skipSymbol = false,
1666
+ documents?: HoverDocument[],
317
1667
  ): Hover | null {
318
- // Find token on posLine that strictly or best matches posCol
319
- const lineTokens: { token: Token; index: number }[] = [];
320
- for (let i = 0; i < tokens.length; i++) {
321
- const t = tokens[i];
322
- if (t.span.start.line === posLine) {
323
- lineTokens.push({ token: t, index: i });
324
- }
325
- }
326
-
327
- if (lineTokens.length === 0) {
1668
+ const matched = findTokenAtPosition(tokens, posLine, posCol);
1669
+ if (!matched) {
328
1670
  return null;
329
1671
  }
330
1672
 
331
- // 1. Check for token that strictly encompasses posCol
332
- let matchedIndex = -1;
333
- for (const { token, index } of lineTokens) {
334
- if (posCol >= token.span.start.column && posCol < token.span.end.column) {
335
- matchedIndex = index;
336
- break;
337
- }
338
- }
1673
+ const { token, index: matchedIndex } = matched;
339
1674
 
340
- // 2. If no strict match, check if cursor is at token end boundary
341
- if (matchedIndex === -1) {
342
- for (const { token, index } of lineTokens) {
343
- if (posCol === token.span.end.column) {
344
- matchedIndex = index;
345
- break;
346
- }
347
- }
1675
+ if (token.type === TokenType.JSX_ATTRIBUTE_NAME) {
1676
+ return findJsxAttributeHover(
1677
+ source,
1678
+ uri,
1679
+ posLine,
1680
+ posCol,
1681
+ tokens,
1682
+ documents,
1683
+ );
348
1684
  }
349
1685
 
350
- if (matchedIndex === -1) {
1686
+ if (isJsxPunctuationOrTextToken(token.type)) {
351
1687
  return null;
352
1688
  }
353
1689
 
354
- const token = tokens[matchedIndex];
1690
+ if (isJsxTagNameToken(tokens, matchedIndex)) {
1691
+ return findJsxTagHover(
1692
+ tokens,
1693
+ matchedIndex,
1694
+ posLine,
1695
+ posCol,
1696
+ source,
1697
+ uri,
1698
+ skipSymbol,
1699
+ documents,
1700
+ );
1701
+ }
355
1702
 
356
1703
  // Case A: token is a member after a dot (e.g. `succeed` in `Effect.succeed` or `scoped` in `Layer.scoped`)
357
1704
  if (
@@ -529,11 +1876,47 @@ function findHoverInTokens(
529
1876
  return null;
530
1877
  }
531
1878
 
1879
+ function isSuppressedInFunxLineFallback(
1880
+ lines: string[],
1881
+ lineIndex: number,
1882
+ charIndex: number,
1883
+ uri: string,
1884
+ ): boolean {
1885
+ if (!uri.endsWith(".funx")) return false;
1886
+ const currentLine = lines[lineIndex] ?? "";
1887
+ const upToCursor = lines
1888
+ .slice(0, lineIndex)
1889
+ .concat(currentLine.slice(0, charIndex))
1890
+ .join("\n");
1891
+ const ctx = detectJsxContext(upToCursor);
1892
+ if (ctx.kind !== "normal") return true;
1893
+ if (charIndex < currentLine.length) {
1894
+ const throughChar = lines
1895
+ .slice(0, lineIndex)
1896
+ .concat(currentLine.slice(0, charIndex + 1))
1897
+ .join("\n");
1898
+ if (detectJsxContext(throughChar).kind !== "normal") {
1899
+ return true;
1900
+ }
1901
+ }
1902
+ return false;
1903
+ }
1904
+
532
1905
  function findHoverInLineText(
533
1906
  currentLine: string,
534
1907
  lineIndex: number,
535
1908
  charIndex: number,
1909
+ lines?: string[],
1910
+ uri?: string,
536
1911
  ): Hover | null {
1912
+ if (
1913
+ lines &&
1914
+ uri &&
1915
+ isSuppressedInFunxLineFallback(lines, lineIndex, charIndex, uri)
1916
+ ) {
1917
+ return null;
1918
+ }
1919
+
537
1920
  // 1. Check multi-character operators first (e.g. `???`, `|>`, `<-`, `=>`, and banned symbols)
538
1921
  const bannedOps = Object.keys(BANNED_SYMBOLS);
539
1922
  const operators = [
@@ -733,12 +2116,19 @@ export function findHover(
733
2116
  source: string,
734
2117
  uri: string,
735
2118
  position: Position,
736
- skipSymbol = false,
2119
+ skipSymbolOrDocuments: boolean | HoverDocument[] = false,
2120
+ documents?: HoverDocument[],
737
2121
  ): Hover | null {
738
2122
  if (!source || source.trim().length === 0) {
739
2123
  return null;
740
2124
  }
741
2125
 
2126
+ const skipSymbol =
2127
+ typeof skipSymbolOrDocuments === "boolean" ? skipSymbolOrDocuments : false;
2128
+ const resolvedDocuments = Array.isArray(skipSymbolOrDocuments)
2129
+ ? skipSymbolOrDocuments
2130
+ : documents;
2131
+
742
2132
  const lines = source.split("\n");
743
2133
  const lineIndex = position.line;
744
2134
  const charIndex = position.character;
@@ -776,14 +2166,26 @@ export function findHover(
776
2166
  source,
777
2167
  uri,
778
2168
  skipSymbol,
2169
+ resolvedDocuments,
779
2170
  );
780
2171
  if (hoverFromTokens) {
781
2172
  return hoverFromTokens;
782
2173
  }
2174
+
2175
+ const matched = findTokenAtPosition(tokens, posLine, posCol);
2176
+ if (
2177
+ matched &&
2178
+ (isJsxPunctuationOrTextToken(matched.token.type) ||
2179
+ isJsxTagNameToken(tokens, matched.index) ||
2180
+ matched.token.type === TokenType.STRING ||
2181
+ matched.token.type === TokenType.STRING_PART)
2182
+ ) {
2183
+ return null;
2184
+ }
783
2185
  }
784
2186
 
785
2187
  // 2. Fallback to line text-based inspection (e.g. if lexer threw or comments/unparsed code)
786
- return findHoverInLineText(currentLine, lineIndex, charIndex);
2188
+ return findHoverInLineText(currentLine, lineIndex, charIndex, lines, uri);
787
2189
  }
788
2190
 
789
2191
  /** Async hover retains synchronous behavior for ordinary sources and compiles Wasm blocks when needed. */