hinmil 0.0.0-stage → 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.
Files changed (301) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +2306 -2
  3. package/dist/cli.d.ts +15 -0
  4. package/dist/cli.d.ts.map +1 -0
  5. package/dist/cli.js +338 -0
  6. package/dist/cli.js.map +1 -0
  7. package/dist/commentParser.d.ts +384 -0
  8. package/dist/commentParser.d.ts.map +1 -0
  9. package/dist/commentParser.js +2487 -0
  10. package/dist/commentParser.js.map +1 -0
  11. package/dist/config.d.ts +203 -0
  12. package/dist/config.d.ts.map +1 -0
  13. package/dist/config.js +375 -0
  14. package/dist/config.js.map +1 -0
  15. package/dist/debugLog.d.ts +13 -0
  16. package/dist/debugLog.d.ts.map +1 -0
  17. package/dist/debugLog.js +44 -0
  18. package/dist/debugLog.js.map +1 -0
  19. package/dist/estree.d.ts +100 -0
  20. package/dist/estree.d.ts.map +1 -0
  21. package/dist/estree.js +34 -0
  22. package/dist/estree.js.map +1 -0
  23. package/dist/hm/env.d.ts +134 -0
  24. package/dist/hm/env.d.ts.map +1 -0
  25. package/dist/hm/env.js +939 -0
  26. package/dist/hm/env.js.map +1 -0
  27. package/dist/hm/index.d.ts +7 -0
  28. package/dist/hm/index.d.ts.map +1 -0
  29. package/dist/hm/index.js +26 -0
  30. package/dist/hm/index.js.map +1 -0
  31. package/dist/hm/substitution.d.ts +57 -0
  32. package/dist/hm/substitution.d.ts.map +1 -0
  33. package/dist/hm/substitution.js +546 -0
  34. package/dist/hm/substitution.js.map +1 -0
  35. package/dist/hm/typeParser.d.ts +39 -0
  36. package/dist/hm/typeParser.d.ts.map +1 -0
  37. package/dist/hm/typeParser.js +1285 -0
  38. package/dist/hm/typeParser.js.map +1 -0
  39. package/dist/hm/typeUtils.d.ts +248 -0
  40. package/dist/hm/typeUtils.d.ts.map +1 -0
  41. package/dist/hm/typeUtils.js +905 -0
  42. package/dist/hm/typeUtils.js.map +1 -0
  43. package/dist/hm/types.d.ts +738 -0
  44. package/dist/hm/types.d.ts.map +1 -0
  45. package/dist/hm/types.js +1853 -0
  46. package/dist/hm/types.js.map +1 -0
  47. package/dist/hm/unify.d.ts +59 -0
  48. package/dist/hm/unify.d.ts.map +1 -0
  49. package/dist/hm/unify.js +1700 -0
  50. package/dist/hm/unify.js.map +1 -0
  51. package/dist/index.d.ts +20 -0
  52. package/dist/index.d.ts.map +1 -0
  53. package/dist/index.js +196 -0
  54. package/dist/index.js.map +1 -0
  55. package/dist/infer/annotation-rigid.d.ts +76 -0
  56. package/dist/infer/annotation-rigid.d.ts.map +1 -0
  57. package/dist/infer/annotation-rigid.js +542 -0
  58. package/dist/infer/annotation-rigid.js.map +1 -0
  59. package/dist/infer/annotation-validation.d.ts +109 -0
  60. package/dist/infer/annotation-validation.d.ts.map +1 -0
  61. package/dist/infer/annotation-validation.js +1078 -0
  62. package/dist/infer/annotation-validation.js.map +1 -0
  63. package/dist/infer/annotations.d.ts +277 -0
  64. package/dist/infer/annotations.d.ts.map +1 -0
  65. package/dist/infer/annotations.js +1343 -0
  66. package/dist/infer/annotations.js.map +1 -0
  67. package/dist/infer/call-overloads.d.ts +24 -0
  68. package/dist/infer/call-overloads.d.ts.map +1 -0
  69. package/dist/infer/call-overloads.js +900 -0
  70. package/dist/infer/call-overloads.js.map +1 -0
  71. package/dist/infer/call-rows.d.ts +154 -0
  72. package/dist/infer/call-rows.d.ts.map +1 -0
  73. package/dist/infer/call-rows.js +2162 -0
  74. package/dist/infer/call-rows.js.map +1 -0
  75. package/dist/infer/calls.d.ts +20 -0
  76. package/dist/infer/calls.d.ts.map +1 -0
  77. package/dist/infer/calls.js +1468 -0
  78. package/dist/infer/calls.js.map +1 -0
  79. package/dist/infer/constraints.d.ts +99 -0
  80. package/dist/infer/constraints.d.ts.map +1 -0
  81. package/dist/infer/constraints.js +1208 -0
  82. package/dist/infer/constraints.js.map +1 -0
  83. package/dist/infer/expr-assignment.d.ts +20 -0
  84. package/dist/infer/expr-assignment.d.ts.map +1 -0
  85. package/dist/infer/expr-assignment.js +620 -0
  86. package/dist/infer/expr-assignment.js.map +1 -0
  87. package/dist/infer/expr-constraint-lookup.d.ts +44 -0
  88. package/dist/infer/expr-constraint-lookup.d.ts.map +1 -0
  89. package/dist/infer/expr-constraint-lookup.js +207 -0
  90. package/dist/infer/expr-constraint-lookup.js.map +1 -0
  91. package/dist/infer/expr-functions.d.ts +20 -0
  92. package/dist/infer/expr-functions.d.ts.map +1 -0
  93. package/dist/infer/expr-functions.js +1359 -0
  94. package/dist/infer/expr-functions.js.map +1 -0
  95. package/dist/infer/expr-jsx.d.ts +19 -0
  96. package/dist/infer/expr-jsx.d.ts.map +1 -0
  97. package/dist/infer/expr-jsx.js +310 -0
  98. package/dist/infer/expr-jsx.js.map +1 -0
  99. package/dist/infer/expr-member.d.ts +40 -0
  100. package/dist/infer/expr-member.d.ts.map +1 -0
  101. package/dist/infer/expr-member.js +1154 -0
  102. package/dist/infer/expr-member.js.map +1 -0
  103. package/dist/infer/expr-prototype.d.ts +11 -0
  104. package/dist/infer/expr-prototype.d.ts.map +1 -0
  105. package/dist/infer/expr-prototype.js +202 -0
  106. package/dist/infer/expr-prototype.js.map +1 -0
  107. package/dist/infer/expressions.d.ts +40 -0
  108. package/dist/infer/expressions.d.ts.map +1 -0
  109. package/dist/infer/expressions.js +1497 -0
  110. package/dist/infer/expressions.js.map +1 -0
  111. package/dist/infer/functionPatterns.d.ts +229 -0
  112. package/dist/infer/functionPatterns.d.ts.map +1 -0
  113. package/dist/infer/functionPatterns.js +1035 -0
  114. package/dist/infer/functionPatterns.js.map +1 -0
  115. package/dist/infer/helpers.d.ts +73 -0
  116. package/dist/infer/helpers.d.ts.map +1 -0
  117. package/dist/infer/helpers.js +187 -0
  118. package/dist/infer/helpers.js.map +1 -0
  119. package/dist/infer/index.d.ts +551 -0
  120. package/dist/infer/index.d.ts.map +1 -0
  121. package/dist/infer/index.js +1127 -0
  122. package/dist/infer/index.js.map +1 -0
  123. package/dist/infer/jsx-dom.d.ts +26 -0
  124. package/dist/infer/jsx-dom.d.ts.map +1 -0
  125. package/dist/infer/jsx-dom.js +303 -0
  126. package/dist/infer/jsx-dom.js.map +1 -0
  127. package/dist/infer/moduleReps.d.ts +7 -0
  128. package/dist/infer/moduleReps.d.ts.map +1 -0
  129. package/dist/infer/moduleReps.js +48 -0
  130. package/dist/infer/moduleReps.js.map +1 -0
  131. package/dist/infer/modules.d.ts +10 -0
  132. package/dist/infer/modules.d.ts.map +1 -0
  133. package/dist/infer/modules.js +775 -0
  134. package/dist/infer/modules.js.map +1 -0
  135. package/dist/infer/narrowing.d.ts +199 -0
  136. package/dist/infer/narrowing.d.ts.map +1 -0
  137. package/dist/infer/narrowing.js +1428 -0
  138. package/dist/infer/narrowing.js.map +1 -0
  139. package/dist/infer/results.d.ts +24 -0
  140. package/dist/infer/results.d.ts.map +1 -0
  141. package/dist/infer/results.js +611 -0
  142. package/dist/infer/results.js.map +1 -0
  143. package/dist/infer/setupPass.d.ts +11 -0
  144. package/dist/infer/setupPass.d.ts.map +1 -0
  145. package/dist/infer/setupPass.js +524 -0
  146. package/dist/infer/setupPass.js.map +1 -0
  147. package/dist/infer/statements.d.ts +26 -0
  148. package/dist/infer/statements.d.ts.map +1 -0
  149. package/dist/infer/statements.js +750 -0
  150. package/dist/infer/statements.js.map +1 -0
  151. package/dist/infer/stmt-bindings.d.ts +22 -0
  152. package/dist/infer/stmt-bindings.d.ts.map +1 -0
  153. package/dist/infer/stmt-bindings.js +1482 -0
  154. package/dist/infer/stmt-bindings.js.map +1 -0
  155. package/dist/infer/stmt-destructure.d.ts +29 -0
  156. package/dist/infer/stmt-destructure.d.ts.map +1 -0
  157. package/dist/infer/stmt-destructure.js +490 -0
  158. package/dist/infer/stmt-destructure.js.map +1 -0
  159. package/dist/infer/types.d.ts +220 -0
  160. package/dist/infer/types.d.ts.map +1 -0
  161. package/dist/infer/types.js +46 -0
  162. package/dist/infer/types.js.map +1 -0
  163. package/dist/infer/unifyDiag.d.ts +46 -0
  164. package/dist/infer/unifyDiag.d.ts.map +1 -0
  165. package/dist/infer/unifyDiag.js +642 -0
  166. package/dist/infer/unifyDiag.js.map +1 -0
  167. package/dist/parsing-babel.d.ts +3 -0
  168. package/dist/parsing-babel.d.ts.map +1 -0
  169. package/dist/parsing-babel.js +353 -0
  170. package/dist/parsing-babel.js.map +1 -0
  171. package/dist/parsing.d.ts +69 -0
  172. package/dist/parsing.d.ts.map +1 -0
  173. package/dist/parsing.js +288 -0
  174. package/dist/parsing.js.map +1 -0
  175. package/dist/registries/constraintRegistry.d.ts +233 -0
  176. package/dist/registries/constraintRegistry.d.ts.map +1 -0
  177. package/dist/registries/constraintRegistry.js +803 -0
  178. package/dist/registries/constraintRegistry.js.map +1 -0
  179. package/dist/registries/dataTypeRegistry.d.ts +63 -0
  180. package/dist/registries/dataTypeRegistry.d.ts.map +1 -0
  181. package/dist/registries/dataTypeRegistry.js +180 -0
  182. package/dist/registries/dataTypeRegistry.js.map +1 -0
  183. package/dist/registries/domGlobals.d.ts +33 -0
  184. package/dist/registries/domGlobals.d.ts.map +1 -0
  185. package/dist/registries/domGlobals.js +309 -0
  186. package/dist/registries/domGlobals.js.map +1 -0
  187. package/dist/registries/methodRegistry.d.ts +277 -0
  188. package/dist/registries/methodRegistry.d.ts.map +1 -0
  189. package/dist/registries/methodRegistry.js +2074 -0
  190. package/dist/registries/methodRegistry.js.map +1 -0
  191. package/dist/registries/session.d.ts +38 -0
  192. package/dist/registries/session.d.ts.map +1 -0
  193. package/dist/registries/session.js +75 -0
  194. package/dist/registries/session.js.map +1 -0
  195. package/dist/server.d.ts +2 -0
  196. package/dist/server.d.ts.map +1 -0
  197. package/dist/server.js +1896 -0
  198. package/dist/server.js.map +1 -0
  199. package/dist/services/codeActions.d.ts +22 -0
  200. package/dist/services/codeActions.d.ts.map +1 -0
  201. package/dist/services/codeActions.js +465 -0
  202. package/dist/services/codeActions.js.map +1 -0
  203. package/dist/services/completion.d.ts +259 -0
  204. package/dist/services/completion.d.ts.map +1 -0
  205. package/dist/services/completion.js +2794 -0
  206. package/dist/services/completion.js.map +1 -0
  207. package/dist/services/definitions.d.ts +37 -0
  208. package/dist/services/definitions.d.ts.map +1 -0
  209. package/dist/services/definitions.js +605 -0
  210. package/dist/services/definitions.js.map +1 -0
  211. package/dist/services/diagnosticCodes.d.ts +70 -0
  212. package/dist/services/diagnosticCodes.d.ts.map +1 -0
  213. package/dist/services/diagnosticCodes.js +239 -0
  214. package/dist/services/diagnosticCodes.js.map +1 -0
  215. package/dist/services/diagnostics.d.ts +86 -0
  216. package/dist/services/diagnostics.d.ts.map +1 -0
  217. package/dist/services/diagnostics.js +665 -0
  218. package/dist/services/diagnostics.js.map +1 -0
  219. package/dist/services/documentCache.d.ts +88 -0
  220. package/dist/services/documentCache.d.ts.map +1 -0
  221. package/dist/services/documentCache.js +108 -0
  222. package/dist/services/documentCache.js.map +1 -0
  223. package/dist/services/documentSymbols.d.ts +20 -0
  224. package/dist/services/documentSymbols.d.ts.map +1 -0
  225. package/dist/services/documentSymbols.js +381 -0
  226. package/dist/services/documentSymbols.js.map +1 -0
  227. package/dist/services/fileSelection.d.ts +24 -0
  228. package/dist/services/fileSelection.d.ts.map +1 -0
  229. package/dist/services/fileSelection.js +154 -0
  230. package/dist/services/fileSelection.js.map +1 -0
  231. package/dist/services/fileSelectionRefresh.d.ts +26 -0
  232. package/dist/services/fileSelectionRefresh.d.ts.map +1 -0
  233. package/dist/services/fileSelectionRefresh.js +77 -0
  234. package/dist/services/fileSelectionRefresh.js.map +1 -0
  235. package/dist/services/files.d.ts +342 -0
  236. package/dist/services/files.d.ts.map +1 -0
  237. package/dist/services/files.js +1712 -0
  238. package/dist/services/files.js.map +1 -0
  239. package/dist/services/fsProbe.d.ts +14 -0
  240. package/dist/services/fsProbe.d.ts.map +1 -0
  241. package/dist/services/fsProbe.js +112 -0
  242. package/dist/services/fsProbe.js.map +1 -0
  243. package/dist/services/globalsLoader.d.ts +20 -0
  244. package/dist/services/globalsLoader.d.ts.map +1 -0
  245. package/dist/services/globalsLoader.js +122 -0
  246. package/dist/services/globalsLoader.js.map +1 -0
  247. package/dist/services/hmFileServices.d.ts +113 -0
  248. package/dist/services/hmFileServices.d.ts.map +1 -0
  249. package/dist/services/hmFileServices.js +686 -0
  250. package/dist/services/hmFileServices.js.map +1 -0
  251. package/dist/services/hover.d.ts +280 -0
  252. package/dist/services/hover.d.ts.map +1 -0
  253. package/dist/services/hover.js +1687 -0
  254. package/dist/services/hover.js.map +1 -0
  255. package/dist/services/importContext.d.ts +396 -0
  256. package/dist/services/importContext.d.ts.map +1 -0
  257. package/dist/services/importContext.js +1999 -0
  258. package/dist/services/importContext.js.map +1 -0
  259. package/dist/services/projectChecker.d.ts +50 -0
  260. package/dist/services/projectChecker.d.ts.map +1 -0
  261. package/dist/services/projectChecker.js +228 -0
  262. package/dist/services/projectChecker.js.map +1 -0
  263. package/dist/services/references.d.ts +41 -0
  264. package/dist/services/references.d.ts.map +1 -0
  265. package/dist/services/references.js +757 -0
  266. package/dist/services/references.js.map +1 -0
  267. package/dist/services/rename.d.ts +22 -0
  268. package/dist/services/rename.d.ts.map +1 -0
  269. package/dist/services/rename.js +101 -0
  270. package/dist/services/rename.js.map +1 -0
  271. package/dist/services/shortCircuit.d.ts +27 -0
  272. package/dist/services/shortCircuit.d.ts.map +1 -0
  273. package/dist/services/shortCircuit.js +28 -0
  274. package/dist/services/shortCircuit.js.map +1 -0
  275. package/dist/services/sidecarPerf.d.ts +19 -0
  276. package/dist/services/sidecarPerf.d.ts.map +1 -0
  277. package/dist/services/sidecarPerf.js +59 -0
  278. package/dist/services/sidecarPerf.js.map +1 -0
  279. package/dist/services/signatureHelp.d.ts +27 -0
  280. package/dist/services/signatureHelp.d.ts.map +1 -0
  281. package/dist/services/signatureHelp.js +984 -0
  282. package/dist/services/signatureHelp.js.map +1 -0
  283. package/dist/walking.d.ts +25 -0
  284. package/dist/walking.d.ts.map +1 -0
  285. package/dist/walking.js +107 -0
  286. package/dist/walking.js.map +1 -0
  287. package/hm-types-builtin/assert.hm +20 -0
  288. package/hm-types-builtin/buffer.hm +8 -0
  289. package/hm-types-builtin/child_process.hm +16 -0
  290. package/hm-types-builtin/crypto.hm +17 -0
  291. package/hm-types-builtin/fs.hm +15 -0
  292. package/hm-types-builtin/http.hm +14 -0
  293. package/hm-types-builtin/os.hm +19 -0
  294. package/hm-types-builtin/path.hm +18 -0
  295. package/hm-types-builtin/react-dom.hm +27 -0
  296. package/hm-types-builtin/react.hm +113 -0
  297. package/hm-types-builtin/url.hm +7 -0
  298. package/hm-types-builtin/zlib.hm +12 -0
  299. package/package.json +53 -4
  300. package/schemas/hinmil.config.schema.json +261 -0
  301. package/schemas/package-hinmil.schema.json +59 -0
package/dist/server.js ADDED
@@ -0,0 +1,1896 @@
1
+ "use strict";
2
+ // ============================================================================
3
+ // LSP Server — Language Server Protocol entry point
4
+ //
5
+ // Plain language: the switchboard between the editor and the type checker.
6
+ // VS Code sends requests over the Language Server Protocol ("the user is
7
+ // hovering here", "the file changed", "give completions") and this file
8
+ // routes each request to the right service in src/services/, manages the
9
+ // per-document caches, and sends the answers back. NOTE: this file has no
10
+ // direct test coverage — be extra careful when changing it.
11
+ // ============================================================================
12
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
13
+ if (k2 === undefined) k2 = k;
14
+ var desc = Object.getOwnPropertyDescriptor(m, k);
15
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
16
+ desc = { enumerable: true, get: function() { return m[k]; } };
17
+ }
18
+ Object.defineProperty(o, k2, desc);
19
+ }) : (function(o, m, k, k2) {
20
+ if (k2 === undefined) k2 = k;
21
+ o[k2] = m[k];
22
+ }));
23
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
24
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
25
+ }) : function(o, v) {
26
+ o["default"] = v;
27
+ });
28
+ var __importStar = (this && this.__importStar) || (function () {
29
+ var ownKeys = function(o) {
30
+ ownKeys = Object.getOwnPropertyNames || function (o) {
31
+ var ar = [];
32
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
33
+ return ar;
34
+ };
35
+ return ownKeys(o);
36
+ };
37
+ return function (mod) {
38
+ if (mod && mod.__esModule) return mod;
39
+ var result = {};
40
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
41
+ __setModuleDefault(result, mod);
42
+ return result;
43
+ };
44
+ })();
45
+ Object.defineProperty(exports, "__esModule", { value: true });
46
+ const node_1 = require("vscode-languageserver/node");
47
+ const path = __importStar(require("path"));
48
+ const fs = __importStar(require("fs"));
49
+ const url_1 = require("url");
50
+ const vscode_languageserver_textdocument_1 = require("vscode-languageserver-textdocument");
51
+ const index_1 = require("./index");
52
+ const methodRegistry_1 = require("./registries/methodRegistry");
53
+ const commentParser_1 = require("./commentParser");
54
+ const typeUtils_1 = require("./hm/typeUtils");
55
+ const hover_1 = require("./services/hover");
56
+ const files_1 = require("./services/files");
57
+ const completion_1 = require("./services/completion");
58
+ const codeActions_1 = require("./services/codeActions");
59
+ const documentSymbols_1 = require("./services/documentSymbols");
60
+ const references_1 = require("./services/references");
61
+ const definitions_1 = require("./services/definitions");
62
+ const importContext_1 = require("./services/importContext");
63
+ const signatureHelp_1 = require("./services/signatureHelp");
64
+ const shortCircuit_1 = require("./services/shortCircuit");
65
+ const rename_1 = require("./services/rename");
66
+ const fsProbe_1 = require("./services/fsProbe");
67
+ const hmFileServices_1 = require("./services/hmFileServices");
68
+ const globalsLoader_1 = require("./services/globalsLoader");
69
+ const documentCache_1 = require("./services/documentCache");
70
+ const projectChecker_1 = require("./services/projectChecker");
71
+ const fileSelection_1 = require("./services/fileSelection");
72
+ const fileSelectionRefresh_1 = require("./services/fileSelectionRefresh");
73
+ // ---------------------------------------------------------------------------
74
+ // Create a connection & document manager
75
+ // ---------------------------------------------------------------------------
76
+ const connection = (0, node_1.createConnection)(node_1.ProposedFeatures.all);
77
+ const documents = new node_1.TextDocuments(vscode_languageserver_textdocument_1.TextDocument);
78
+ const config_1 = require("./config");
79
+ const debugLog_1 = require("./debugLog");
80
+ /**
81
+ * Debounce (ms) used for re-validating consumer documents after a `.hm`
82
+ * sidecar change. Much shorter than the keystroke debounce: the user
83
+ * already committed an intent (save), so further coalescing buys little
84
+ * and just adds visible latency before diagnostics refresh in dependent
85
+ * files. Keystroke-driven `.js` edits keep using `diagnostics.debounceMs`.
86
+ */
87
+ const HM_REVALIDATE_DEBOUNCE_MS = 50;
88
+ /**
89
+ * Monotonic counter bumped every time the project globals are (re)loaded
90
+ * (see {@link reloadGlobals}). The source-identity short-circuit records the
91
+ * generation under which each document was last validated; when the globals
92
+ * change, a dependent document whose OWN text is unchanged would otherwise be
93
+ * served stale diagnostics — comparing generations forces a fresh inference
94
+ * with the new globals.
95
+ */
96
+ let globalsGeneration = 0;
97
+ function publishDiagnostics(uri, diagnostics) {
98
+ documentCache_1.lastPublishedDiagnostics.set(uri, diagnostics);
99
+ connection.sendDiagnostics({ uri, diagnostics });
100
+ }
101
+ // ---------------------------------------------------------------------------
102
+ // Configuration
103
+ // ---------------------------------------------------------------------------
104
+ let settings = { ...config_1.defaultSettings };
105
+ /** Is VS Code's built-in TypeScript/JavaScript extension active? Reported by
106
+ * the hinmil client (initializationOptions + `hinmil/typescriptLanguageFeatures`);
107
+ * other clients never report it, so hinmil answers code definitions there. */
108
+ let typescriptLanguageFeaturesActive = false;
109
+ /** The client accepts `LocationLink`s for definitions (with the clicked
110
+ * range, so a whole module path is one link instead of one per word). */
111
+ let definitionLinkSupport = false;
112
+ /** The source extensions of every checked workspace folder together (module
113
+ * resolution and the file watchers are server-wide). */
114
+ let sourceExtensions = (0, fileSelection_1.mergeFileSelection)([]).extensions;
115
+ /** The workspace folder paths (from `workspaceFolders`, else `rootUri`). */
116
+ let workspaceRootPaths = [];
117
+ /** The project configuration of each workspace folder, by path. */
118
+ const workspaceConfigs = new Map();
119
+ /** The workspace folders with their merged settings and file selection. */
120
+ let workspaceRoots = [];
121
+ /** The client reports workspace-folder changes. */
122
+ let supportsWorkspaceFolders = false;
123
+ /** The workspace folder of a document (by URI), if any. */
124
+ function rootForUri(uri) {
125
+ try {
126
+ return uri.startsWith('file:') ? (0, fileSelectionRefresh_1.rootForFile)((0, url_1.fileURLToPath)(uri), workspaceRoots) : undefined;
127
+ }
128
+ catch {
129
+ return undefined;
130
+ }
131
+ }
132
+ /** The settings of a document: those of its workspace folder. */
133
+ function settingsFor(uri) {
134
+ return rootForUri(uri)?.settings ?? settings;
135
+ }
136
+ /** Does hinmil answer requests for this document? Not for a file in a
137
+ * workspace folder that is switched off. */
138
+ function isServedDocument(uri) {
139
+ const root = rootForUri(uri);
140
+ return root === undefined || root.active;
141
+ }
142
+ /** Scopes by root directory, created on first use. */
143
+ const scopes = new Map();
144
+ /** Dependencies for the globals loader (open-doc lookup + warning output). */
145
+ const globalsLoaderDeps = {
146
+ getOpenDocText: (uri) => documents.get(uri)?.getText() ?? null,
147
+ warn: (m) => connection.console.warn(m),
148
+ };
149
+ /** A scope without configuration (before the workspace root is known). */
150
+ function bareScope() {
151
+ return {
152
+ root: '',
153
+ importCtx: new importContext_1.ImportInferenceContext(documents, { warn: (m) => connection.console.warn(m) }),
154
+ engine: new index_1.InferenceEngine(),
155
+ globalsSource: null,
156
+ globalsFilePaths: [],
157
+ };
158
+ }
159
+ /** Load a scope: its configuration, globals and import context. */
160
+ function createScope(root) {
161
+ const config = (0, globalsLoader_1.loadProjectConfig)(root);
162
+ const importCtx = new importContext_1.ImportInferenceContext(documents, { warn: (m) => connection.console.warn(m) });
163
+ const engine = new index_1.InferenceEngine();
164
+ const result = (0, globalsLoader_1.loadGlobalsFile)(root, config, globalsLoaderDeps);
165
+ let globalsSource = result.source;
166
+ const globalsFilePaths = result.filePaths;
167
+ importCtx.setProjectConfig(root, {
168
+ overrides: config.overrides ?? {},
169
+ typesDir: config.typesDir ?? config_1.DEFAULT_TYPES_DIR,
170
+ globalsSource,
171
+ globalsFilePath: globalsFilePaths[0] ?? null,
172
+ });
173
+ // Pre-walk direct deps so package-level `hinmil.globals` files are
174
+ // visible from the very first inference (instead of only after a
175
+ // second re-validate triggers re-discovery).
176
+ importCtx.preloadPackageGlobalsFromWorkspace(root);
177
+ // Append project-level auto-globals derived from `// ::types <specifier>`
178
+ // directives in `globals.hm` (e.g. `// ::types query-builder` pulls in query-builder's
179
+ // sidecar declarations) so aliases like `Selector` and value annotations
180
+ // like `tables` are visible to every file the engine infers.
181
+ const addendum = importCtx.getProjectGlobalsAddendum();
182
+ if (addendum) {
183
+ globalsSource = globalsSource ? `${globalsSource}\n${addendum}` : addendum;
184
+ }
185
+ // Append package-level globals (`package.json#hinmil.globals`) so
186
+ // libraries can ship aliases / constraints visible to every consumer
187
+ // file without forcing the consumer to write a `// ::types` directive.
188
+ const pkgAddendum = importCtx.getAllPackageGlobalsAddendum();
189
+ if (pkgAddendum) {
190
+ globalsSource = globalsSource ? `${globalsSource}\n${pkgAddendum}` : pkgAddendum;
191
+ }
192
+ // The engine's globals source: every infer() call of this scope picks it up.
193
+ engine.globalsSource = globalsSource;
194
+ // Without a globals file the loader still returns the conventional path
195
+ // (watched for a later create); only log a file that was actually read.
196
+ if (result.source !== null) {
197
+ connection.console.log(`[hinmil] Loaded globals from ${globalsFilePaths.join(', ')} (scope ${root})`);
198
+ }
199
+ // Phase J: warm the inline-package annotation cache in the background.
200
+ // Each scan walks up to INLINE_PACKAGE_MAX_FILES JS files; doing this
201
+ // synchronously inside the resolver was the dominant cold-hover cost.
202
+ // setImmediate yields to any pending request first so we never delay
203
+ // initialize / the first onDidOpen.
204
+ setImmediate(() => {
205
+ try {
206
+ importCtx.preloadInlinePackageAnnotationsFromWorkspace(root);
207
+ connection.console.log(`[hinmil] inline-package pre-scan complete (scope ${root})`);
208
+ }
209
+ catch (e) {
210
+ connection.console.warn(`[hinmil] inline-package pre-scan failed: ${e instanceof Error ? e.message : String(e)}`);
211
+ }
212
+ });
213
+ return { root, importCtx, engine, globalsSource, globalsFilePaths };
214
+ }
215
+ /** The scope with this root directory (created on first use). */
216
+ function scopeAt(root) {
217
+ let scope = scopes.get(root);
218
+ if (!scope) {
219
+ scope = root === '' ? bareScope() : createScope(root);
220
+ scopes.set(root, scope);
221
+ }
222
+ return scope;
223
+ }
224
+ /** The scope of a document (by URI). */
225
+ function scopeFor(uri) {
226
+ if (workspaceRoots.length === 0)
227
+ return scopeAt('');
228
+ let filePath;
229
+ try {
230
+ filePath = (0, url_1.fileURLToPath)(uri);
231
+ }
232
+ catch {
233
+ return scopeAt(workspaceRoots[0].path);
234
+ }
235
+ const root = (0, fileSelectionRefresh_1.rootForFile)(filePath, workspaceRoots) ?? workspaceRoots[0];
236
+ return scopeAt((0, config_1.findScopeRoot)(filePath, root.path));
237
+ }
238
+ /** Every scope created so far (cross-file events reach each of them). */
239
+ function allScopes() {
240
+ return [...scopes.values()];
241
+ }
242
+ /** Is this path one of the globals files of any scope? */
243
+ function isGlobalsFile(filePath) {
244
+ return allScopes().some(scope => scope.globalsFilePaths.includes(filePath));
245
+ }
246
+ /** The dependents of a file in every scope (a sidecar or module can be
247
+ * used by files of several scopes). */
248
+ function dependentsOf(uri) {
249
+ let out;
250
+ for (const scope of allScopes()) {
251
+ const deps = scope.importCtx.getDependents(uri);
252
+ if (!deps || deps.size === 0)
253
+ continue;
254
+ if (!out)
255
+ out = new Set();
256
+ for (const d of deps)
257
+ out.add(d);
258
+ }
259
+ return out;
260
+ }
261
+ /** The imports of a file in every scope. */
262
+ function importsOf(uri) {
263
+ let out;
264
+ for (const scope of allScopes()) {
265
+ const imports = scope.importCtx.getImports(uri);
266
+ if (!imports || imports.size === 0)
267
+ continue;
268
+ if (!out)
269
+ out = new Set();
270
+ for (const i of imports)
271
+ out.add(i);
272
+ }
273
+ return out;
274
+ }
275
+ /** Drop the cached inference of a file in every scope. */
276
+ function invalidateEverywhere(uri) {
277
+ for (const scope of allScopes())
278
+ scope.importCtx.invalidateFileCache(uri);
279
+ }
280
+ /** Reload the configuration and globals (on init and when a configuration
281
+ * or globals file changes): every scope is rebuilt on first use. */
282
+ function reloadGlobals() {
283
+ if (workspaceRootPaths.length === 0)
284
+ return;
285
+ // Bump the generation so the source-identity short-circuit re-infers every
286
+ // open document against the new globals (their own text is unchanged).
287
+ globalsGeneration++;
288
+ // Request-path inference results were computed under the old globals.
289
+ documentCache_1.requestInferCache.clear();
290
+ // Project-file settings overrides (`"settings"` key) and file selection
291
+ // of each workspace folder: re-merge so an edit to package.json /
292
+ // hinmil.config.* takes effect immediately (this function runs on
293
+ // watched-file changes for those files).
294
+ workspaceConfigs.clear();
295
+ for (const root of workspaceRootPaths)
296
+ workspaceConfigs.set(root, (0, globalsLoader_1.loadProjectConfig)(root));
297
+ recomputeSettings();
298
+ // Drop any cached `.hm` files so config changes take effect immediately.
299
+ (0, files_1.clearHmSidecarCache)();
300
+ (0, files_1.clearInlinePackageCache)();
301
+ (0, fsProbe_1.clearFsProbeCache)();
302
+ scopes.clear();
303
+ for (const root of workspaceRoots)
304
+ if (root.active)
305
+ scopeAt(root.path);
306
+ }
307
+ // ---------------------------------------------------------------------------
308
+ // Import Inference Context — encapsulates cross-file caching & resolution
309
+ // ---------------------------------------------------------------------------
310
+ /**
311
+ * Manages the cross-file inference cache and dependency graph.
312
+ *
313
+ * Centralises the fragile snapshot/restore dance that was previously
314
+ * spread across several loose functions: every import-file inference
315
+ * must snapshot the global method/constraint registries and the
316
+ * type-variable counter, run a *separate* engine, restore the
317
+ * caller's registries, then merge in the import's registrations.
318
+ *
319
+ * By encapsulating this in a single class the logic is easier to
320
+ * reason about, test, and extend (e.g. with parallel inference).
321
+ */
322
+ // ---------------------------------------------------------------------------
323
+ // Lifecycle
324
+ // ---------------------------------------------------------------------------
325
+ connection.onInitialize((params) => {
326
+ supportsWatchedFilesDynamicRegistration =
327
+ params.capabilities.workspace?.didChangeWatchedFiles?.dynamicRegistration === true;
328
+ definitionLinkSupport = params.capabilities.textDocument?.definition?.linkSupport === true;
329
+ typescriptLanguageFeaturesActive =
330
+ params.initializationOptions?.typescriptLanguageFeatures === true;
331
+ supportsWorkspaceFolders = params.capabilities.workspace?.workspaceFolders === true;
332
+ // The workspace folders, each with its own project configuration. Older
333
+ // clients only send `rootUri` (a single folder).
334
+ if (params.workspaceFolders && params.workspaceFolders.length > 0) {
335
+ workspaceRootPaths = params.workspaceFolders.map(folder => (0, url_1.fileURLToPath)(folder.uri));
336
+ }
337
+ else if (params.rootUri) {
338
+ workspaceRootPaths = [(0, url_1.fileURLToPath)(params.rootUri)];
339
+ }
340
+ reloadGlobals();
341
+ return {
342
+ capabilities: {
343
+ textDocumentSync: node_1.TextDocumentSyncKind.Incremental,
344
+ hoverProvider: true,
345
+ definitionProvider: true,
346
+ completionProvider: {
347
+ triggerCharacters: [
348
+ '.', '/', '\'', '"', ':', '<',
349
+ // Record-literal keys: `f ({|`, `f ({ a: 1, |`. Only the
350
+ // record-field providers answer these (see onCompletion), so a
351
+ // block `{` or an argument `,` never pops up identifier noise.
352
+ '{', ',',
353
+ // Identifier characters — triggers completions while typing names
354
+ ...'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_$'.split(''),
355
+ ],
356
+ completionItem: { labelDetailsSupport: true },
357
+ },
358
+ signatureHelpProvider: {
359
+ triggerCharacters: ['(', ','],
360
+ retriggerCharacters: [',', '[', '{'],
361
+ },
362
+ codeActionProvider: {
363
+ codeActionKinds: [node_1.CodeActionKind.QuickFix],
364
+ },
365
+ documentSymbolProvider: true,
366
+ referencesProvider: true,
367
+ renameProvider: {
368
+ prepareProvider: true,
369
+ },
370
+ workspace: {
371
+ workspaceFolders: { supported: true, changeNotifications: true },
372
+ },
373
+ },
374
+ serverInfo: {
375
+ name: 'hinmil',
376
+ version: '0.2.0',
377
+ },
378
+ };
379
+ });
380
+ connection.onInitialized(() => {
381
+ connection.client.register(node_1.DidChangeConfigurationNotification.type, undefined);
382
+ clientInitialized = true;
383
+ if (!supportsWatchedFilesDynamicRegistration) {
384
+ // VS Code always supports dynamic registration; other clients that do
385
+ // not will miss on-disk dependency invalidation (open-document checking
386
+ // and config-file watching still work).
387
+ connection.console.warn('[hinmil] Client does not support dynamic file-watcher registration; changes to unopened dependency files will not be detected.');
388
+ }
389
+ syncSourceFileWatchers();
390
+ if (supportsWorkspaceFolders) {
391
+ // A folder added to or removed from a multi-root workspace: rebuild the
392
+ // folders, their configuration and scopes, and recheck the open files.
393
+ connection.workspace.onDidChangeWorkspaceFolders((event) => {
394
+ const removed = new Set(event.removed.map(folder => (0, url_1.fileURLToPath)(folder.uri)));
395
+ const added = event.added.map(folder => (0, url_1.fileURLToPath)(folder.uri));
396
+ workspaceRootPaths = [
397
+ ...workspaceRootPaths.filter(root => !removed.has(root)),
398
+ ...added.filter(root => !workspaceRootPaths.includes(root)),
399
+ ];
400
+ reloadGlobals();
401
+ refreshOpenDocumentSelection();
402
+ });
403
+ }
404
+ // Fetch initial settings
405
+ connection.workspace.getConfiguration('hinmil').then((config) => {
406
+ if (config)
407
+ updateSettings(config);
408
+ });
409
+ });
410
+ connection.onNotification('hinmil/typescriptLanguageFeatures', (params) => {
411
+ typescriptLanguageFeaturesActive = params?.active === true;
412
+ });
413
+ connection.onDidChangeConfiguration((change) => {
414
+ const config = change.settings?.['hinmil'];
415
+ if (config) {
416
+ updateSettings(config);
417
+ }
418
+ else {
419
+ // Some clients send empty settings; pull from workspace
420
+ connection.workspace.getConfiguration('hinmil').then((c) => {
421
+ if (c)
422
+ updateSettings(c);
423
+ });
424
+ }
425
+ });
426
+ /** Most recent raw settings payload from the client (VS Code settings). */
427
+ let clientSettingsLayer = {};
428
+ /** Re-merge the settings layers of every workspace folder: defaults < VS Code
429
+ * settings < the folder's project file (`"settings"` and `"files"` of
430
+ * package.json `"hinmil"` or hinmil.config.js / hinmil.config.json, refreshed
431
+ * by reloadGlobals). */
432
+ function recomputeSettings() {
433
+ const warn = (msg) => connection.console.warn(msg);
434
+ const client = typeof clientSettingsLayer === 'object' && clientSettingsLayer !== null
435
+ ? clientSettingsLayer
436
+ : {};
437
+ const requiresConfig = client.requiresConfig === true;
438
+ workspaceRoots = workspaceRootPaths.map((root) => {
439
+ const config = workspaceConfigs.get(root) ?? {};
440
+ return {
441
+ path: root,
442
+ active: config.enable !== false && (!requiresConfig || (0, config_1.hasProjectConfig)(root)),
443
+ settings: (0, config_1.mergeSettings)([clientSettingsLayer, config.settings ?? {}], warn),
444
+ fileSelection: (0, fileSelection_1.mergeFileSelection)([client.files, config.files ?? {}], warn),
445
+ };
446
+ });
447
+ // Server-wide knobs (debounce, DOM typing) follow the first checked folder.
448
+ const active = workspaceRoots.filter(root => root.active);
449
+ const primary = active[0] ?? workspaceRoots[0];
450
+ settings = primary?.settings ?? (0, config_1.mergeSettings)([clientSettingsLayer], warn);
451
+ sourceExtensions = active.length > 0
452
+ ? [...new Set(active.flatMap(root => root.fileSelection.extensions))]
453
+ : (primary?.fileSelection ?? (0, fileSelection_1.mergeFileSelection)([client.files], warn)).extensions;
454
+ (0, files_1.configureModuleExtensions)(sourceExtensions);
455
+ syncSourceFileWatchers();
456
+ // Thread the DOM/Fetch typing knobs into the engine: rebuilds the DOM
457
+ // method bags (strict-null signatures) and invalidates the cached default
458
+ // environment so `document`/`window`/… flip between typed TCons and `Any`.
459
+ (0, methodRegistry_1.applyDomSettings)(settings.dom);
460
+ }
461
+ function updateSettings(config) {
462
+ clientSettingsLayer = config;
463
+ recomputeSettings();
464
+ refreshOpenDocumentSelection();
465
+ }
466
+ // ---------------------------------------------------------------------------
467
+ // Watched-file registration — scoped to the effective source extensions
468
+ // ---------------------------------------------------------------------------
469
+ /** Whether the client allows dynamic `workspace/didChangeWatchedFiles` registration. */
470
+ let supportsWatchedFilesDynamicRegistration = false;
471
+ /** Set once `initialized` arrives — registrations before that are invalid. */
472
+ let clientInitialized = false;
473
+ let sourceWatcherRegistration;
474
+ let registeredWatcherKey = null;
475
+ /**
476
+ * (Re-)register a watcher for exactly the effective source extensions.
477
+ * The client only watches config files statically; source files are watched
478
+ * through this dynamic registration so custom extensions keep working while
479
+ * avoiding a broad `**\/*` watcher. No-op when the extension set is unchanged.
480
+ * Clients without dynamic-registration support get no source watchers (a
481
+ * warning is logged on initialization) — config files are still watched
482
+ * statically by the VS Code client.
483
+ */
484
+ function syncSourceFileWatchers() {
485
+ if (!clientInitialized || !supportsWatchedFilesDynamicRegistration)
486
+ return;
487
+ const extensions = sourceExtensions.map((extension) => extension.replace(/^\./, ''));
488
+ const key = extensions.sort().join(',');
489
+ if (key === registeredWatcherKey || extensions.length === 0)
490
+ return;
491
+ registeredWatcherKey = key;
492
+ const globPattern = extensions.length === 1 ? `**/*.${extensions[0]}` : `**/*.{${key}}`;
493
+ connection.client
494
+ .register(node_1.DidChangeWatchedFilesNotification.type, { watchers: [{ globPattern }] })
495
+ .then((registration) => {
496
+ sourceWatcherRegistration?.dispose();
497
+ sourceWatcherRegistration = registration;
498
+ })
499
+ .catch((error) => {
500
+ registeredWatcherKey = null;
501
+ connection.console.warn(`[hinmil] Failed to register file watchers: ${error instanceof Error ? error.message : String(error)}`);
502
+ });
503
+ }
504
+ function refreshOpenDocumentSelection() {
505
+ if (workspaceRoots.length === 0) {
506
+ // No project root: selection is not enforced, but settings changed —
507
+ // revalidate every open document (the pre-selection behaviour).
508
+ for (const doc of documents.all()) {
509
+ documentCache_1.lastValidatedSource.delete(doc.uri);
510
+ validateTextDocument(doc);
511
+ }
512
+ return;
513
+ }
514
+ const plan = (0, fileSelectionRefresh_1.planFileSelectionRefresh)(Array.from(documents.all()), workspaceRoots);
515
+ for (const doc of plan.clear) {
516
+ const pending = pendingValidations.get(doc.uri);
517
+ if (pending)
518
+ clearTimeout(pending);
519
+ pendingValidations.delete(doc.uri);
520
+ publishDiagnostics(doc.uri, []);
521
+ }
522
+ for (const doc of plan.validate) {
523
+ documentCache_1.lastValidatedSource.delete(doc.uri);
524
+ validateTextDocument(doc);
525
+ }
526
+ }
527
+ // Handle file changes on disk (e.g. saving a dependency file that isn't open,
528
+ // or external edits). This ensures that when RTask.js is saved, demo2.js
529
+ // re-imports and re-validates automatically.
530
+ /**
531
+ * Collect the open documents that should be re-validated after a `.hm`
532
+ * sidecar changes. Uses {@link ImportInferenceContext.getDependents} to
533
+ * walk the reverse-dependency graph transitively — only files that
534
+ * actually import (directly or via re-export chains) the changed sidecar
535
+ * are returned.
536
+ *
537
+ * Conservative fallback: when the dep-graph has no entry for the changed
538
+ * `.hm` URI (typical when the sidecar was never resolved yet because no
539
+ * open file has touched it), return ALL open documents. This matches
540
+ * the previous blanket behaviour and protects against subtle staleness
541
+ * for files that would resolve the sidecar on their next inference.
542
+ * In steady state (after the first validation pass) the graph is
543
+ * populated and the fast path is taken.
544
+ */
545
+ function collectAffectedOpenDocs(hmUri) {
546
+ const directDependents = dependentsOf(hmUri);
547
+ if (!directDependents || directDependents.size === 0) {
548
+ return Array.from(documents.all());
549
+ }
550
+ const visited = new Set();
551
+ const queue = Array.from(directDependents);
552
+ const affected = [];
553
+ while (queue.length > 0) {
554
+ const cur = queue.shift();
555
+ if (visited.has(cur))
556
+ continue;
557
+ visited.add(cur);
558
+ const doc = documents.get(cur);
559
+ if (doc)
560
+ affected.push(doc);
561
+ const transitive = dependentsOf(cur);
562
+ if (transitive) {
563
+ for (const t of transitive)
564
+ if (!visited.has(t))
565
+ queue.push(t);
566
+ }
567
+ }
568
+ return affected;
569
+ }
570
+ /**
571
+ * Selectively invalidate the changed `.hm` sidecar + the open documents
572
+ * that transitively depend on it, then debounce-revalidate each.
573
+ * Uses {@link HM_REVALIDATE_DEBOUNCE_MS} (much shorter than the
574
+ * keystroke debounce) since the user already committed an intent by
575
+ * saving / editing the sidecar.
576
+ */
577
+ function scheduleHmRevalidation(hmUri, skipUri) {
578
+ // Evict only the changed sidecar's parsed entry; other sidecars stay warm.
579
+ (0, files_1.evictHmSidecar)(hmUri);
580
+ // Per-file evict of the small parseCache LRU in hmFileServices — formerly
581
+ // a global wipe, which forced every other `.hm` to re-parse on next touch.
582
+ (0, hmFileServices_1.clearHmParseCacheForFile)(hmUri);
583
+ // The inline-package BFS cache is workspace-wide and expensive to rebuild
584
+ // (up to 256 files per package). Only clear the slice tied to the
585
+ // package this `.hm` actually belongs to. When the .hm is a workspace
586
+ // override (not under node_modules) the inline cache is irrelevant —
587
+ // skip the wipe entirely.
588
+ let inlineScope = 'none';
589
+ try {
590
+ const hmPath = hmUri.startsWith('file://') ? (0, url_1.fileURLToPath)(hmUri) : hmUri;
591
+ if (/[\\/]node_modules[\\/]/.test(hmPath)) {
592
+ const pkg = (0, files_1.findPackageJson)(hmPath);
593
+ if (pkg) {
594
+ (0, files_1.clearInlinePackageCacheForPackage)(pkg.pkgDir);
595
+ inlineScope = `pkg:${path.basename(pkg.pkgDir)}`;
596
+ }
597
+ else {
598
+ (0, files_1.clearInlinePackageCache)();
599
+ inlineScope = 'global(no-pkg)';
600
+ }
601
+ }
602
+ }
603
+ catch {
604
+ // Best-effort: a malformed URI should never block revalidation.
605
+ (0, files_1.clearInlinePackageCache)();
606
+ inlineScope = 'global(error)';
607
+ }
608
+ const direct = dependentsOf(hmUri);
609
+ const directCount = direct?.size ?? 0;
610
+ const affected = collectAffectedOpenDocs(hmUri);
611
+ const fallback = !direct || direct.size === 0;
612
+ // Transitively invalidate export caches of ALL dependents (direct and
613
+ // indirect). A stale intermediate export (e.g. a model file between the
614
+ // sidecar and the open consumer) would otherwise keep serving pre-edit
615
+ // types. Sidecar parse artifacts themselves are stamped by doc-version /
616
+ // mtime and re-validate lazily, so only the JS-side inference caches need
617
+ // explicit eviction here.
618
+ let invalidatedCount = 0;
619
+ const visited = new Set([hmUri]);
620
+ const queue = [{ uri: hmUri, depth: 0 }];
621
+ while (queue.length > 0) {
622
+ const { uri: cur, depth } = queue.shift();
623
+ const deps = dependentsOf(cur);
624
+ if (!deps)
625
+ continue;
626
+ for (const depUri of deps) {
627
+ if (visited.has(depUri))
628
+ continue;
629
+ visited.add(depUri);
630
+ queue.push({ uri: depUri, depth: depth + 1 });
631
+ invalidateEverywhere(depUri);
632
+ documentCache_1.lastValidatedSource.delete(depUri);
633
+ (0, completion_1.invalidateWorkspaceExportEntry)(depUri);
634
+ invalidatedCount++;
635
+ }
636
+ }
637
+ connection.console.log(`[hinmil] hm-revalidate ${path.basename(hmUri)}: directDeps=${directCount} ` +
638
+ `affected=${affected.length} invalidated=${invalidatedCount} ` +
639
+ `fallback=${fallback ? 'yes' : 'no'} inline=${inlineScope}`);
640
+ for (const doc of affected) {
641
+ invalidateEverywhere(doc.uri);
642
+ documentCache_1.lastValidatedSource.delete(doc.uri);
643
+ if (doc.uri === skipUri)
644
+ continue;
645
+ const existing = pendingValidations.get(doc.uri);
646
+ if (existing)
647
+ clearTimeout(existing);
648
+ pendingValidations.set(doc.uri, setTimeout(() => {
649
+ pendingValidations.delete(doc.uri);
650
+ const d = documents.get(doc.uri);
651
+ if (d)
652
+ validateTextDocument(d);
653
+ }, HM_REVALIDATE_DEBOUNCE_MS));
654
+ }
655
+ }
656
+ connection.onDidChangeWatchedFiles((params) => {
657
+ // Created/deleted files change module resolution: forget memoised
658
+ // existence probes before anything below re-resolves imports.
659
+ if (params.changes.length > 0)
660
+ (0, fsProbe_1.clearFsProbeCache)();
661
+ for (const change of params.changes) {
662
+ // Reload globals if any of the globals files changed
663
+ if (isGlobalsFile((0, url_1.fileURLToPath)(change.uri))) {
664
+ // Debounced + staggered: watcher events can arrive in bursts (e.g. a
665
+ // git checkout touching several files) and validating every open
666
+ // document synchronously in one tick froze all pending requests.
667
+ scheduleGlobalsReload();
668
+ continue;
669
+ }
670
+ // Also reload globals if package.json or config files changed
671
+ if (workspaceRootPaths.length > 0) {
672
+ const changedPath = (0, url_1.fileURLToPath)(change.uri);
673
+ const basename = path.basename(changedPath);
674
+ if (basename === 'package.json' || basename === 'hinmil.config.js' || basename === 'hinmil.config.json' || config_1.DEFAULT_GLOBALS_FILES.includes(basename)) {
675
+ scheduleGlobalsReload();
676
+ }
677
+ }
678
+ // `.hm` sidecars (npm package stubs, project type stubs) — selectively
679
+ // evict the changed sidecar and re-validate only the open documents
680
+ // that transitively depend on it (via the import dep-graph), instead
681
+ // of blanket-invalidating every open document.
682
+ if (change.uri.endsWith('.hm')) {
683
+ // Dedup: if the .hm is an open document, `onDidChangeContent`
684
+ // already fired `scheduleHmRevalidation` for this save — running
685
+ // it again would double every cross-file validate. Only handle
686
+ // watched-files events for `.hm` files that are NOT open.
687
+ if (documents.get(change.uri)) {
688
+ continue;
689
+ }
690
+ scheduleHmRevalidation(change.uri);
691
+ continue;
692
+ }
693
+ // Selected/custom source extensions can be dependencies even when their
694
+ // standalone path is excluded. Do not apply include/exclude here.
695
+ let changedExtension = '';
696
+ try {
697
+ changedExtension = path.extname((0, url_1.fileURLToPath)(change.uri)).toLowerCase();
698
+ }
699
+ catch {
700
+ continue;
701
+ }
702
+ if (!sourceExtensions.includes(changedExtension) || changedExtension === '.hm')
703
+ continue;
704
+ invalidateFileAndDependents(change.uri);
705
+ }
706
+ });
707
+ // ---------------------------------------------------------------------------
708
+ // Diagnostics — debounced to avoid noise while typing
709
+ // ---------------------------------------------------------------------------
710
+ const pendingValidations = new Map();
711
+ /**
712
+ * Invalidate the per-file caches of the changed file itself. Cheap (O(1))
713
+ * — safe to run on every keystroke.
714
+ */
715
+ function invalidateFileSelf(changedUri) {
716
+ invalidateEverywhere(changedUri);
717
+ // A change to this file or one of its dependencies makes any cached
718
+ // inference result stale, even if the source text we last validated
719
+ // happens to be unchanged. Forget the fingerprint so the short-circuit
720
+ // doesn't reuse stale data.
721
+ documentCache_1.lastValidatedSource.delete(changedUri);
722
+ documentCache_1.requestInferCache.delete(changedUri);
723
+ // The workspace-export completion cache holds this file's exports keyed
724
+ // by on-disk mtime; an open-editor edit doesn't touch the mtime, so
725
+ // evict explicitly.
726
+ (0, completion_1.invalidateWorkspaceExportEntry)(changedUri);
727
+ }
728
+ /**
729
+ * Walk the dependent graph transitively and invalidate + schedule
730
+ * re-validation of every open file that depends on `changedUri`.
731
+ *
732
+ * NOT called per keystroke: editing a hub file imported by dozens of others
733
+ * would wipe every dependent's import cache (and re-trigger the
734
+ * workspace-export warmer) on each keystroke. The editor-typing path runs
735
+ * this once per debounce window (just before validating the changed file);
736
+ * the watched-files path (on-disk changes) still runs it immediately via
737
+ * {@link invalidateFileAndDependents}.
738
+ */
739
+ function invalidateDependentsOf(changedUri) {
740
+ // A change to file X must invalidate every file that imports X (directly
741
+ // OR via intermediate re-export modules), otherwise an open consumer
742
+ // keeps reusing a stale method-registry snapshot until the LSP is
743
+ // restarted. Concrete case: editing `lib/RTask/RTask.js` to add
744
+ // `// RTask#map :: ...` only marks the immediate re-exporter
745
+ // `lib/RTask/index.js` as stale; the open consumer (`db/Repo.js`) that
746
+ // imports through index.js never sees the new method until next process
747
+ // start.
748
+ const visited = new Set([changedUri]);
749
+ const queue = [changedUri];
750
+ while (queue.length > 0) {
751
+ const cur = queue.shift();
752
+ const dependents = dependentsOf(cur);
753
+ if (!dependents)
754
+ continue;
755
+ for (const depUri of dependents) {
756
+ if (visited.has(depUri))
757
+ continue;
758
+ visited.add(depUri);
759
+ queue.push(depUri);
760
+ invalidateEverywhere(depUri);
761
+ documentCache_1.lastValidatedSource.delete(depUri);
762
+ documentCache_1.requestInferCache.delete(depUri);
763
+ (0, completion_1.invalidateWorkspaceExportEntry)(depUri);
764
+ // Also drop any cached published-diagnostics snapshot so the
765
+ // source-identity short-circuit in `validateTextDocument` cannot
766
+ // re-publish a stale snapshot for a dependent whose inputs just
767
+ // changed. Without this, an open consumer that happens to land
768
+ // on a previously-validated text fingerprint would resurface old
769
+ // diagnostics computed against the pre-invalidation imports.
770
+ documentCache_1.lastPublishedDiagnostics.delete(depUri);
771
+ const depImports = importsOf(depUri);
772
+ if (depImports) {
773
+ for (const importedUri of depImports) {
774
+ invalidateEverywhere(importedUri);
775
+ }
776
+ }
777
+ const depDoc = documents.get(depUri);
778
+ if (depDoc) {
779
+ const existing = pendingValidations.get(depUri);
780
+ if (existing)
781
+ clearTimeout(existing);
782
+ pendingValidations.set(depUri, setTimeout(() => {
783
+ pendingValidations.delete(depUri);
784
+ const doc = documents.get(depUri);
785
+ if (doc)
786
+ validateTextDocument(doc);
787
+ }, settings.diagnostics.debounceMs + 100));
788
+ }
789
+ }
790
+ }
791
+ }
792
+ /**
793
+ * Invalidate a file's cache and schedule re-validation of all open files
794
+ * that depend on it (directly or transitively).
795
+ */
796
+ function invalidateFileAndDependents(changedUri) {
797
+ invalidateFileSelf(changedUri);
798
+ invalidateDependentsOf(changedUri);
799
+ }
800
+ /**
801
+ * Debounced globals reload. Typing in a globals file used to fire the full
802
+ * reload (project config + globals file + package-globals preload + cache
803
+ * wipes) synchronously on EVERY keystroke. Coalesce bursts — editor
804
+ * keystrokes as well as watcher events (a git checkout can touch several
805
+ * config files at once) — into a single reload, then re-validate all open
806
+ * documents with a stagger so the re-validations don't land in one
807
+ * blocking tick.
808
+ */
809
+ let pendingGlobalsReload = null;
810
+ function scheduleGlobalsReload() {
811
+ if (pendingGlobalsReload)
812
+ clearTimeout(pendingGlobalsReload);
813
+ pendingGlobalsReload = setTimeout(() => {
814
+ pendingGlobalsReload = null;
815
+ reloadGlobals();
816
+ scheduleValidationOfAllOpenDocs();
817
+ }, settings.diagnostics.debounceMs);
818
+ }
819
+ /** Schedule (debounced, staggered) re-validation of every open document. */
820
+ function scheduleValidationOfAllOpenDocs() {
821
+ let i = 0;
822
+ for (const openDoc of documents.all()) {
823
+ const openUri = openDoc.uri;
824
+ const existing = pendingValidations.get(openUri);
825
+ if (existing)
826
+ clearTimeout(existing);
827
+ pendingValidations.set(openUri, setTimeout(() => {
828
+ pendingValidations.delete(openUri);
829
+ const d = documents.get(openUri);
830
+ if (d)
831
+ validateTextDocument(d);
832
+ }, settings.diagnostics.debounceMs + i * 50));
833
+ i++;
834
+ }
835
+ }
836
+ documents.onDidChangeContent((change) => {
837
+ const uri = change.document.uri;
838
+ // Track caret position of the latest edit for the word-boundary gate
839
+ // in `validateTextDocument`. Only relevant for source files — `.hm`
840
+ // sidecars have their own dedicated revalidation path.
841
+ if (!uri.endsWith('.hm')) {
842
+ const prev = documentCache_1.lastSeenSource.get(uri) ?? '';
843
+ const curr = change.document.getText();
844
+ const offset = (0, documentCache_1.computeCaretOffset)(prev, curr);
845
+ documentCache_1.lastEditPosition.set(uri, { offset, at: Date.now() });
846
+ documentCache_1.lastSeenSource.set(uri, curr);
847
+ }
848
+ // Detect if the changed document is one of the globals files (any scope)
849
+ {
850
+ try {
851
+ const changedPath = (0, url_1.fileURLToPath)(uri);
852
+ if (isGlobalsFile(changedPath)) {
853
+ // Debounced: reloading globals synchronously on every keystroke in
854
+ // a globals file (config re-read + package-globals preload + full
855
+ // cache wipes + re-validation of every open document) froze the
856
+ // server while typing there.
857
+ scheduleGlobalsReload();
858
+ }
859
+ }
860
+ catch { /* not a file: URI */ }
861
+ }
862
+ // Edits to a `.hm` sidecar in the editor: selectively invalidate only
863
+ // open documents that transitively depend on the changed sidecar (via
864
+ // the import dep-graph), using the short HM-revalidation debounce.
865
+ // CRITICAL: for `.hm` URIs we MUST skip `invalidateFileAndDependents`
866
+ // below — that path was designed for `.js` files and aggressively wipes
867
+ // every transitive importer + each importer's full import graph. For a
868
+ // `.hm` sidecar that wiped 15+ unrelated caches per save, forcing a
869
+ // 4s engine.infer on the next validate. scheduleHmRevalidation already
870
+ // invalidates exactly the open docs that depend on the .hm, surgically.
871
+ if (uri.endsWith('.hm')) {
872
+ scheduleHmRevalidation(uri, /* skipUri */ uri);
873
+ }
874
+ else {
875
+ // Per keystroke only the cheap self-invalidation; the transitive
876
+ // dependents walk is deferred to the debounced validation below.
877
+ invalidateFileSelf(uri);
878
+ }
879
+ // Cancel any pending validation for this document
880
+ const existing = pendingValidations.get(uri);
881
+ if (existing)
882
+ clearTimeout(existing);
883
+ // Schedule a new validation after the user stops typing
884
+ pendingValidations.set(uri, setTimeout(() => {
885
+ pendingValidations.delete(uri);
886
+ const doc = documents.get(uri);
887
+ if (!doc)
888
+ return;
889
+ // Deferred dependents-invalidation (see invalidateDependentsOf):
890
+ // once per debounce window instead of on every keystroke.
891
+ if (!uri.endsWith('.hm'))
892
+ invalidateDependentsOf(uri);
893
+ validateTextDocument(doc);
894
+ }, settings.diagnostics.debounceMs));
895
+ });
896
+ function validateTextDocument(textDocument) {
897
+ if (workspaceRoots.length > 0) {
898
+ try {
899
+ if (!(0, fileSelectionRefresh_1.isFileChecked)((0, url_1.fileURLToPath)(textDocument.uri), workspaceRoots)) {
900
+ publishDiagnostics(textDocument.uri, []);
901
+ return;
902
+ }
903
+ }
904
+ catch {
905
+ publishDiagnostics(textDocument.uri, []);
906
+ return;
907
+ }
908
+ }
909
+ const source = textDocument.getText();
910
+ // Word-boundary gate: if the caret of the most recent edit sits
911
+ // *inside* an identifier (both the character before and after the
912
+ // caret are word-chars), the user is mid-word. Running inference now
913
+ // would generate noisy `Unbound variable: 'foo'` diagnostics on a
914
+ // half-typed name; defer this pass and reschedule. After
915
+ // {@link WORD_BOUNDARY_GATE_MS} elapsed without further edits we
916
+ // accept the user really paused inside a partial word and validate
917
+ // anyway (such a diagnostic is then a legitimate signal).
918
+ //
919
+ // Skipped for `.hm` sidecars (different validation pipeline) and when
920
+ // no edit context is recorded yet (initial open / pre-warm).
921
+ if (!textDocument.uri.endsWith('.hm')) {
922
+ const editPos = documentCache_1.lastEditPosition.get(textDocument.uri);
923
+ if (editPos && (Date.now() - editPos.at) < documentCache_1.WORD_BOUNDARY_GATE_MS) {
924
+ const before = editPos.offset > 0 ? source[editPos.offset - 1] : undefined;
925
+ const after = editPos.offset < source.length ? source[editPos.offset] : undefined;
926
+ if ((0, documentCache_1.isIdentChar)(before) && (0, documentCache_1.isIdentChar)(after)) {
927
+ // Reschedule this file's validation; do NOT publish anything.
928
+ // Previously published diagnostics remain visible in the editor.
929
+ const existing = pendingValidations.get(textDocument.uri);
930
+ if (existing)
931
+ clearTimeout(existing);
932
+ pendingValidations.set(textDocument.uri, setTimeout(() => {
933
+ pendingValidations.delete(textDocument.uri);
934
+ const doc = documents.get(textDocument.uri);
935
+ if (doc)
936
+ validateTextDocument(doc);
937
+ }, settings.diagnostics.debounceMs));
938
+ return;
939
+ }
940
+ }
941
+ }
942
+ // The project scope of this document: its globals, import context, engine.
943
+ const { importCtx, engine, globalsSource, globalsFilePaths } = scopeFor(textDocument.uri);
944
+ // Phase K: per-call circular-import counter (reset by importCtx before any inferFileAndCacheExports walks).
945
+ importCtx.resetPerfCounters?.();
946
+ // `.hm` annotation files have no JS body to infer — they are pure
947
+ // declaration sources. Run the dedicated declarations-only pipeline
948
+ // (parse errors only; cross-sidecar reference checks are intentionally
949
+ // skipped because realistic stubs forward-reference names that arrive
950
+ // via other sidecars or the consumer file).
951
+ if (textDocument.uri.endsWith('.hm')) {
952
+ if (!settingsFor(textDocument.uri).diagnostics.enabled) {
953
+ publishDiagnostics(textDocument.uri, []);
954
+ documentCache_1.lastValidatedSource.set(textDocument.uri, source);
955
+ return;
956
+ }
957
+ const hmCtx = {
958
+ findTypeDefinitions: (n) => importCtx.findTypeDefinitions(n, textDocument.uri, source, globalsSource, globalsFilePaths[0] ?? null),
959
+ globals: globalsSource && globalsFilePaths[0]
960
+ ? { source: globalsSource, uri: (0, url_1.pathToFileURL)(globalsFilePaths[0]).href }
961
+ : null,
962
+ };
963
+ const hmDiags = (0, hmFileServices_1.getHmDiagnostics)(textDocument.uri, source, hmCtx);
964
+ publishDiagnostics(textDocument.uri, hmDiags);
965
+ documentCache_1.lastValidatedSource.set(textDocument.uri, source);
966
+ return;
967
+ }
968
+ // Source-identity short-circuit: if we already validated this exact
969
+ // text for this URI, skip re-parse + re-inference. The cached
970
+ // `InferenceResult` is still in `cachedResults` for code actions and
971
+ // friends — but we MUST re-publish the diagnostics we associated with
972
+ // this exact text, because a subsequent validation for an intermediate
973
+ // edit may have published a different diagnostic set that VS Code
974
+ // would otherwise leave on screen.
975
+ if ((0, shortCircuit_1.canShortCircuit)({
976
+ prevSource: documentCache_1.lastValidatedSource.get(textDocument.uri),
977
+ source,
978
+ hasCached: documentCache_1.cachedResults.has(textDocument.uri),
979
+ prevGeneration: documentCache_1.validatedUnderGeneration.get(textDocument.uri),
980
+ currentGeneration: globalsGeneration,
981
+ })) {
982
+ const prev = documentCache_1.lastPublishedDiagnostics.get(textDocument.uri);
983
+ if (prev) {
984
+ connection.sendDiagnostics({ uri: textDocument.uri, diagnostics: prev });
985
+ }
986
+ return;
987
+ }
988
+ const resolver = importCtx.createImportResolver(textDocument.uri);
989
+ const typeResolver = importCtx.createTypeDirectiveResolver(textDocument.uri);
990
+ const aliasResolver = importCtx.createImportTypeAliasResolver(textDocument.uri);
991
+ // Eagerly pre-warm direct imports so parameter inference inside this
992
+ // file doesn't depend on the order in which the user happens to open
993
+ // dependency files. Without this, inferring `f(other)` where `f` is
994
+ // an imported binding can fail to bind `other`'s type until the
995
+ // user opens `f`'s providing module, producing inconsistent hover
996
+ // and diagnostic output across sessions. `inferFileAndCacheExports`
997
+ // is idempotent and LRU-cached; on warm cache this is a cheap noop.
998
+ // Perf: skip the loop entirely when the specifier list hasn't changed
999
+ // since the previous validation pass.
1000
+ const specifiers = (0, commentParser_1.extractImportModuleSpecifiers)(source);
1001
+ const prevSpecifiers = documentCache_1.lastImportSpecifiers.get(textDocument.uri);
1002
+ const specifiersChanged = !prevSpecifiers
1003
+ || prevSpecifiers.length !== specifiers.length
1004
+ || prevSpecifiers.some((s, i) => s !== specifiers[i]);
1005
+ if (specifiersChanged) {
1006
+ for (const specifier of specifiers) {
1007
+ const targetUri = (0, files_1.resolveImportSpecifier)(specifier, textDocument.uri);
1008
+ if (targetUri && targetUri !== textDocument.uri) {
1009
+ importCtx.inferFileAndCacheExports(targetUri);
1010
+ }
1011
+ }
1012
+ documentCache_1.lastImportSpecifiers.set(textDocument.uri, specifiers);
1013
+ }
1014
+ // Normalize array literal ASI: insert ';' before '[' at line starts
1015
+ // so that `[1,2].map(...)` on a new line is parsed as an array literal.
1016
+ const { patched, insertions } = (0, files_1.normalizeArrayLiteralASI)(source);
1017
+ // Wrap inference in a try/catch so a pathological input (e.g. a deeply
1018
+ // recursive type that exceeds MAX_DEPTH outside the unify catch, or any
1019
+ // other unexpected throw) never takes the whole language server down for
1020
+ // this file. We surface the error as a single file-level diagnostic and
1021
+ // clear cached state so subsequent edits get a clean retry.
1022
+ let result;
1023
+ try {
1024
+ result = safeEngineInfer(engine, patched, resolver, typeResolver, aliasResolver);
1025
+ }
1026
+ catch (e) {
1027
+ documentCache_1.cachedResults.delete(textDocument.uri);
1028
+ documentCache_1.lastValidatedSource.delete(textDocument.uri);
1029
+ const message = e instanceof Error ? e.message : String(e);
1030
+ connection.console.warn(`[hinmil] Inference failed for ${textDocument.uri}: ${message}`);
1031
+ publishDiagnostics(textDocument.uri, [{
1032
+ severity: node_1.DiagnosticSeverity.Warning,
1033
+ range: { start: { line: 0, character: 0 }, end: { line: 0, character: 1 } },
1034
+ message: `Inference aborted: ${message}`,
1035
+ source: 'hinmil',
1036
+ }]);
1037
+ return;
1038
+ }
1039
+ // Cache exports + full registry snapshot so a cross-file import of
1040
+ // this URI in another validation pass hits the cache in
1041
+ // `inferFileAndCacheExports` instead of re-running the engine. Phase I.
1042
+ // Use the method snapshot captured inside `safeEngineInfer` (before the
1043
+ // builtin-originals restore) so importers see exactly what this file
1044
+ // registered, never a stale leaked override re-applied by the restore.
1045
+ importCtx.cacheExportsWithSnapshot(textDocument.uri, result.exports, lastSafeInferMethodSnapshot ?? undefined);
1046
+ // Cache the full inference result for code actions and other features
1047
+ documentCache_1.cachedResults.set(textDocument.uri, result);
1048
+ // Record the exact source text we just validated so a follow-up
1049
+ // change-event with identical content can short-circuit.
1050
+ documentCache_1.lastValidatedSource.set(textDocument.uri, source);
1051
+ // Record the globals generation this validation ran under, so a later
1052
+ // globals reload (which bumps the generation) defeats the short-circuit
1053
+ // even when this document's own text is unchanged.
1054
+ documentCache_1.validatedUnderGeneration.set(textDocument.uri, globalsGeneration);
1055
+ publishDiagnostics(textDocument.uri, (0, projectChecker_1.buildDiagnostics)({
1056
+ source,
1057
+ document: textDocument,
1058
+ result,
1059
+ insertions,
1060
+ settings: settingsFor(textDocument.uri),
1061
+ circularImports: importCtx.getCircularImports(textDocument.uri),
1062
+ }));
1063
+ // Kick off (or continue) background warming of the workspace-export
1064
+ // cache for this file's directory neighbourhood, so the first
1065
+ // auto-import completion doesn't pay for a full workspace scan.
1066
+ scheduleWorkspaceExportWarming(textDocument.uri);
1067
+ }
1068
+ // ---------------------------------------------------------------------------
1069
+ // Workspace-export cache warming (auto-import completions)
1070
+ // ---------------------------------------------------------------------------
1071
+ /** URIs with an active background warming loop. */
1072
+ const wsWarmActive = new Set();
1073
+ /** Files warmed per warm call. One file per call keeps the event-loop
1074
+ * occupancy of a single call bounded by one file's inference time. */
1075
+ const WS_WARM_FILES_PER_TICK = 1;
1076
+ /** Idle gap between background warming ticks (ms). */
1077
+ const WS_WARM_TICK_MS = 50;
1078
+ /** Per-tick time budget: keep warming files (one at a time) until this
1079
+ * much time elapsed, then yield the event loop. */
1080
+ const WS_WARM_TICK_BUDGET_MS = 25;
1081
+ /** Warming only runs after this much typing silence (any document): a
1082
+ * single file's inference can't be preempted, so starting one while the
1083
+ * user is typing risks stalling the next completion request behind it. */
1084
+ const WS_WARM_IDLE_MS = 2000;
1085
+ /** Milliseconds since the most recent edit in ANY open document. */
1086
+ function msSinceLastEditAnywhere() {
1087
+ let latest = 0;
1088
+ for (const { at } of documentCache_1.lastEditPosition.values()) {
1089
+ if (at > latest)
1090
+ latest = at;
1091
+ }
1092
+ return latest === 0 ? Number.POSITIVE_INFINITY : Date.now() - latest;
1093
+ }
1094
+ /**
1095
+ * Incrementally pre-compute the per-file workspace-export cache used by
1096
+ * identifier completion's auto-import suggestions. Each tick infers a
1097
+ * few not-yet-cached files and yields the event loop, so validations and
1098
+ * completion requests interleave freely. The loop stops when every
1099
+ * candidate file is cached; re-scheduling is cheap once warm (stat calls
1100
+ * only).
1101
+ */
1102
+ function scheduleWorkspaceExportWarming(uri) {
1103
+ if (!settingsFor(uri).completion.autoImports)
1104
+ return;
1105
+ if (uri.endsWith('.hm'))
1106
+ return;
1107
+ if (wsWarmActive.has(uri))
1108
+ return;
1109
+ wsWarmActive.add(uri);
1110
+ const tick = () => {
1111
+ if (!documents.get(uri)) {
1112
+ wsWarmActive.delete(uri);
1113
+ return;
1114
+ }
1115
+ // Don't steal CPU while the user is actively typing (any document):
1116
+ // inference of a warm-tick file cannot be preempted and would delay
1117
+ // queued completion/diagnostic work.
1118
+ if (msSinceLastEditAnywhere() < WS_WARM_IDLE_MS) {
1119
+ setTimeout(tick, WS_WARM_TICK_MS);
1120
+ return;
1121
+ }
1122
+ let done = true;
1123
+ try {
1124
+ // Warm one file at a time until the per-tick budget is spent, so a
1125
+ // cheap-files stretch progresses quickly while an expensive import
1126
+ // chain still yields right after it finishes.
1127
+ const tickStart = Date.now();
1128
+ do {
1129
+ done = (0, completion_1.warmWorkspaceExports)(uri, (fileUri) => scopeFor(uri).importCtx.inferFileAndCacheExports(fileUri), WS_WARM_FILES_PER_TICK);
1130
+ } while (!done && Date.now() - tickStart < WS_WARM_TICK_BUDGET_MS);
1131
+ }
1132
+ catch (e) {
1133
+ (0, debugLog_1.debugLog)('server.wsWarm', e);
1134
+ }
1135
+ if (done) {
1136
+ wsWarmActive.delete(uri);
1137
+ return;
1138
+ }
1139
+ setTimeout(tick, WS_WARM_TICK_MS);
1140
+ };
1141
+ setTimeout(tick, WS_WARM_TICK_MS);
1142
+ }
1143
+ // ---------------------------------------------------------------------------
1144
+ // Array literal re-inference helper (wraps engine)
1145
+ // ---------------------------------------------------------------------------
1146
+ /**
1147
+ * Method registry snapshot captured by the most recent {@link safeEngineInfer}
1148
+ * call, taken at the end of `engine.infer` BEFORE built-in originals are
1149
+ * restored. Consumed by {@link validateTextDocument} so the cached
1150
+ * cross-file snapshot reflects what the open file actually registered rather
1151
+ * than any stale leaked builtin override re-applied by the restore step.
1152
+ */
1153
+ let lastSafeInferMethodSnapshot = null;
1154
+ /**
1155
+ * File-scoped builtin-override guard around `engine.infer`. Captures the
1156
+ * pre-inference state of built-in method entries (e.g. `Array.every`) and
1157
+ * restores them afterwards, even on throw. This ensures shorthand
1158
+ * annotations such as `// Array.every :: ...` in one `.js` file cannot
1159
+ * corrupt receiver-binding factories observed by unrelated files. Only
1160
+ * globals.hm (re-processed at the start of every `engine.infer` from
1161
+ * `this.globalsSource`) may permanently mutate these entries.
1162
+ */
1163
+ function safeEngineInfer(engine, source, resolver, typeResolver, aliasResolver) {
1164
+ const snap = (0, methodRegistry_1.snapshotBuiltinOriginalEntries)();
1165
+ try {
1166
+ const result = engine.infer(source, undefined, resolver, typeResolver, aliasResolver);
1167
+ // Capture the method registry exactly as it stands at the end of this
1168
+ // file's own inference — clearCustom() ran at infer start (clearing any
1169
+ // cross-request leaked builtin overrides), and only this file plus its
1170
+ // imports re-registered during the pass. This is the authoritative
1171
+ // "what this file contributes" snapshot. It MUST be taken before the
1172
+ // `finally` restore below, which re-applies the pre-infer builtin
1173
+ // entries (potentially a stale leaked override from a prior request)
1174
+ // and would otherwise poison the cached snapshot consumed by importers.
1175
+ lastSafeInferMethodSnapshot = (0, methodRegistry_1.snapshotMethodRegistry)();
1176
+ return result;
1177
+ }
1178
+ finally {
1179
+ (0, methodRegistry_1.restoreBuiltinOriginalEntries)(snap);
1180
+ }
1181
+ }
1182
+ /**
1183
+ * Re-infer source with `;` inserted before an array literal `[` that was
1184
+ * mis-parsed as computed access. Returns the new InferenceResult + shift,
1185
+ * or null if no fix was applicable.
1186
+ */
1187
+ function reinferWithArrayASIFor(engine) {
1188
+ return (source, closeBracketIdx, resolver, typeResolver, aliasResolver) => {
1189
+ const patch = (0, files_1.patchArrayLiteralASI)(source, closeBracketIdx);
1190
+ if (!patch)
1191
+ return null;
1192
+ const result = safeEngineInfer(engine, patch.patched, resolver, typeResolver, aliasResolver);
1193
+ return { result, shift: patch.shift, patched: patch.patched };
1194
+ };
1195
+ }
1196
+ /**
1197
+ * Request-scoped inference with caching. Returns the validation-pass result
1198
+ * when the document is validated and unchanged; otherwise consults the
1199
+ * per-URI {@link requestInferCache} keyed by the exact source text `key`,
1200
+ * inferring (and caching) only on a genuine miss. This bounds the cost of
1201
+ * a burst of request-path inferences (signature help re-fires on every
1202
+ * keystroke while its popup is open; a completion request runs several
1203
+ * providers that each used to re-infer) to ONE inference per document
1204
+ * version.
1205
+ */
1206
+ function inferForRequest(uri, key, infer) {
1207
+ // A validated, unchanged document: the validation-pass result applies to
1208
+ // every request-path variant (original or ASI-patched) of that text —
1209
+ // same equivalence the hover fast path has always relied on.
1210
+ const doc = documents.get(uri);
1211
+ if (doc && documentCache_1.lastValidatedSource.get(uri) === doc.getText()) {
1212
+ const cached = documentCache_1.cachedResults.get(uri);
1213
+ if (cached)
1214
+ return cached;
1215
+ }
1216
+ const slots = documentCache_1.requestInferCache.get(uri) ?? [];
1217
+ const hit = slots.find(s => s.key === key);
1218
+ if (hit)
1219
+ return hit.result;
1220
+ const result = infer();
1221
+ slots.unshift({ key, result });
1222
+ if (slots.length > documentCache_1.REQUEST_INFER_SLOTS)
1223
+ slots.length = documentCache_1.REQUEST_INFER_SLOTS;
1224
+ documentCache_1.requestInferCache.set(uri, slots);
1225
+ return result;
1226
+ }
1227
+ // ---------------------------------------------------------------------------
1228
+ // Hover — show inferred type at cursor position
1229
+ // ---------------------------------------------------------------------------
1230
+ connection.onHover((params) => {
1231
+ if (!isServedDocument(params.textDocument.uri))
1232
+ return null;
1233
+ const docSettings = settingsFor(params.textDocument.uri);
1234
+ const { importCtx, engine, globalsSource, globalsFilePaths } = scopeFor(params.textDocument.uri);
1235
+ if (!docSettings.hover.enabled)
1236
+ return null;
1237
+ const doc = documents.get(params.textDocument.uri);
1238
+ if (!doc)
1239
+ return null;
1240
+ const source = doc.getText();
1241
+ const offset = doc.offsetAt(params.position);
1242
+ // `.hm` files: delegate to the declarations-only hover provider.
1243
+ if (params.textDocument.uri.endsWith('.hm')) {
1244
+ const hmCtx = {
1245
+ findTypeDefinitions: (n) => importCtx.findTypeDefinitions(n, params.textDocument.uri, source, globalsSource, globalsFilePaths[0] ?? null),
1246
+ globals: globalsSource && globalsFilePaths[0]
1247
+ ? { source: globalsSource, uri: (0, url_1.pathToFileURL)(globalsFilePaths[0]).href }
1248
+ : null,
1249
+ };
1250
+ return (0, hover_1.reflowHover)((0, hmFileServices_1.getHmHover)(params.textDocument.uri, source, offset, hmCtx));
1251
+ }
1252
+ // Only show hover on identifiers — skip keywords, braces, operators, etc.
1253
+ const cursorChar = offset < source.length ? source[offset] : '';
1254
+ const onIdentifier = /[A-Za-z0-9_$]/.test(cursorChar);
1255
+ if (!onIdentifier) {
1256
+ // Still allow alias hover in comments
1257
+ const resolver = importCtx.createImportResolver(params.textDocument.uri);
1258
+ const typeResolver = importCtx.createTypeDirectiveResolver(params.textDocument.uri);
1259
+ const aliasResolver = importCtx.createImportTypeAliasResolver(params.textDocument.uri);
1260
+ // Perf: reuse the cached `InferenceResult` from the last validation
1261
+ // pass when the document text is unchanged. Re-running `engine.infer`
1262
+ // on every hover is the dominant LSP cost on larger files.
1263
+ const cached = documentCache_1.lastValidatedSource.get(params.textDocument.uri) === source
1264
+ ? documentCache_1.cachedResults.get(params.textDocument.uri)
1265
+ : undefined;
1266
+ const result = cached ?? inferForRequest(params.textDocument.uri, source, () => safeEngineInfer(engine, source, resolver, typeResolver, aliasResolver));
1267
+ return (0, hover_1.reflowHover)((0, hover_1.getAliasHoverAtOffset)(source, offset, result, params.textDocument.uri, files_1.resolveImportSpecifier, files_1.extractImportSpecifiers, (name) => importCtx.findTypeDefinitions(name, params.textDocument.uri, source, globalsSource, globalsFilePaths[0] ?? null)));
1268
+ }
1269
+ const resolver = importCtx.createImportResolver(params.textDocument.uri);
1270
+ const typeResolver = importCtx.createTypeDirectiveResolver(params.textDocument.uri);
1271
+ const aliasResolver = importCtx.createImportTypeAliasResolver(params.textDocument.uri);
1272
+ // Normalize ASI for array literals and adjust offset
1273
+ const { patched: normSource, insertions } = (0, files_1.normalizeArrayLiteralASI)(source);
1274
+ const normOffset = (0, files_1.mapOffset)(offset, insertions);
1275
+ // Perf: reuse the cached `InferenceResult` from the last validation
1276
+ // pass when the document text is unchanged. `validateTextDocument`
1277
+ // caches the result of `engine.infer(patched, ...)` where `patched` is
1278
+ // the normalizeArrayLiteralASI output, so reusing it is safe whenever
1279
+ // the original (pre-normalize) source matches.
1280
+ const cachedHover = documentCache_1.lastValidatedSource.get(params.textDocument.uri) === source
1281
+ ? documentCache_1.cachedResults.get(params.textDocument.uri)
1282
+ : undefined;
1283
+ let result = cachedHover ?? inferForRequest(params.textDocument.uri, normSource, () => safeEngineInfer(engine, normSource, resolver, typeResolver, aliasResolver));
1284
+ // Find the most specific node whose range contains the offset
1285
+ let bestType = null;
1286
+ let rawBestType = null;
1287
+ let bestStart = -1;
1288
+ let bestEnd = -1;
1289
+ // True when `bestType` is the frozen annotation snapshot for a parameter.
1290
+ // Rule #1: the signature wins — such a type must render with its OWN
1291
+ // variable letters, so we must NOT seed the pretty-printer from the
1292
+ // enclosing scope (which would re-letter the signature's `a` to `b`).
1293
+ let bestFromFrozen = false;
1294
+ for (const [start, { type, end }] of result.nodeTypes) {
1295
+ if (start <= normOffset && normOffset < end && start > bestStart) {
1296
+ bestType = result.substitution.apply(type);
1297
+ rawBestType = type;
1298
+ bestStart = start;
1299
+ bestEnd = end;
1300
+ }
1301
+ }
1302
+ // Declaration site of a polymorphic top-level binding: show its generic
1303
+ // scheme (freshly instantiated) rather than the live substitution-applied
1304
+ // node type, which a downstream call site may have specialized (e.g. a
1305
+ // generic `getPath` leaking a concrete `{ address :: { zip :: b } }`).
1306
+ // Shared helper — keeps `rawBestType` (the constraint source) intact.
1307
+ ({ bestType, rawBestType } = (0, hover_1.applyDeclaredSchemeDisplay)(result, bestStart, bestType, rawBestType));
1308
+ // A parameter's declared type is the annotation the user wrote. Body
1309
+ // inference may bind the annotation's row / value vars (e.g. `Object.keys`
1310
+ // closing an open `{ a }` row to `{}`), poisoning the live-substituted
1311
+ // type above. When the cursor is on such an annotated parameter, prefer the
1312
+ // frozen annotation snapshot so hover always shows the signature form.
1313
+ //
1314
+ // EXCEPTION: only STRUCTURED annotations (records, arrays, unions, applied
1315
+ // constructors) need this protection. A bare type variable has no structure
1316
+ // to protect, and a "frozen" bare var is often not a user annotation at all
1317
+ // but a caller / overload-provided expected type (e.g. an overloaded `map`
1318
+ // callback parameter) that only resolves to a concrete shape — such as
1319
+ // `Pair Number (f a)` — AFTER unification. Rendering that frozen snapshot
1320
+ // raw would show a meaningless `a`, so keep the live substitution-applied
1321
+ // type in that case.
1322
+ if (bestStart >= 0 && result.frozenParamType?.has(bestStart)) {
1323
+ const frozen = result.frozenParamType.get(bestStart);
1324
+ if (frozen.tag !== 'TVar') {
1325
+ bestType = frozen;
1326
+ rawBestType = frozen;
1327
+ bestFromFrozen = true;
1328
+ }
1329
+ }
1330
+ // Replace any rigid skolem constants (minted while checking annotated
1331
+ // bodies) with the annotation's display letters so hover never shows `§N`.
1332
+ if (bestType && result.skolemDisplayNames && result.skolemDisplayNames.size > 0) {
1333
+ bestType = (0, typeUtils_1.scrubSkolems)(bestType, result.skolemDisplayNames);
1334
+ }
1335
+ // Suppress hover when the cursor is on a property access on an
1336
+ // unconstrained type variable (e.g. `x.name` where `x :: a`).
1337
+ // We check bestStart (the property node's start offset) rather than
1338
+ // normOffset (the cursor position) so suppression works regardless of
1339
+ // which character within the property name the cursor is on.
1340
+ if (bestStart >= 0 && result.unconstrainedPropAccesses.has(bestStart)) {
1341
+ bestType = null;
1342
+ rawBestType = null;
1343
+ bestStart = -1;
1344
+ }
1345
+ // Fallback for array literal member access
1346
+ let arrayShift = 0;
1347
+ if ((!bestType || bestType.tag === 'TVar') && (0, hover_1.validIdentLooksLikeArrayMethod)(normSource, normOffset)) {
1348
+ const arrFix = (0, hover_1.tryArrayLiteralReinfer)(normSource, normOffset, resolver, typeResolver, engine, reinferWithArrayASIFor(engine));
1349
+ if (arrFix) {
1350
+ result = arrFix.result;
1351
+ bestType = arrFix.bestType;
1352
+ rawBestType = null; // no raw type needed for array reinfer
1353
+ bestStart = arrFix.bestStart;
1354
+ arrayShift = arrFix.shift;
1355
+ }
1356
+ }
1357
+ // Find the smallest function type that STRICTLY encloses the hovered node.
1358
+ // Its variable letters seed the hover rendering so a variable shared with
1359
+ // the enclosing scope (e.g. `f :: a -> b` and its `result`) shows the same
1360
+ // letter everywhere in the body, and sibling body-local bindings (`let n`,
1361
+ // `let xs`) get distinct, source-ordered letters instead of colliding.
1362
+ let scopeType = null;
1363
+ if (!bestFromFrozen && bestType && bestStart >= 0 && bestEnd >= 0) {
1364
+ scopeType = (0, hover_1.buildScopeSeedType)(result, result.substitution, bestStart, bestEnd);
1365
+ }
1366
+ return (0, hover_1.reflowHover)((0, hover_1.buildHover)({
1367
+ source, offset, result, bestType, rawBestType, bestStart, arrayShift,
1368
+ scopeType,
1369
+ inferredTypeStyle: docSettings.display.typeVariables,
1370
+ uri: params.textDocument.uri,
1371
+ resolveImportSpecifier: files_1.resolveImportSpecifier,
1372
+ extractImportSpecifiers: files_1.extractImportSpecifiers,
1373
+ getImportedRawSignature: (spec, name, fromUri) => importCtx.getImportedRawSignature(spec, name, fromUri),
1374
+ findTypeDefinitions: (name) => importCtx.findTypeDefinitions(name, params.textDocument.uri, source, globalsSource, globalsFilePaths[0] ?? null),
1375
+ positionAt: (o) => doc.positionAt(o),
1376
+ }));
1377
+ });
1378
+ // ---------------------------------------------------------------------------
1379
+ // Definition — go to definition for type aliases in annotations, and (see
1380
+ // `navigation.definitions`) for module paths, imports and local names
1381
+ // ---------------------------------------------------------------------------
1382
+ /** hinmil answers code definitions (see `navigation.definitions`). */
1383
+ function codeDefinitionsEnabled(uri) {
1384
+ const mode = settingsFor(uri).navigation.definitions;
1385
+ return mode === 'always' || (mode === 'auto' && !typescriptLanguageFeaturesActive);
1386
+ }
1387
+ /** Source of a file for definitions: the open editor buffer, else the disk. */
1388
+ function readSourceForDefinition(filePath) {
1389
+ const open = documents.get((0, url_1.pathToFileURL)(filePath).href);
1390
+ if (open)
1391
+ return open.getText();
1392
+ try {
1393
+ return fs.readFileSync(filePath, 'utf-8');
1394
+ }
1395
+ catch {
1396
+ return null;
1397
+ }
1398
+ }
1399
+ /** A code definition as LSP result. With link support each target is a
1400
+ * `LocationLink` whose origin is the clicked text (a whole module path,
1401
+ * a whole identifier); VS Code underlines exactly that. Otherwise plain
1402
+ * `Location`s, and the editor falls back to its own word range. */
1403
+ function toDefinitionResult(def, source) {
1404
+ const origin = {
1405
+ start: (0, files_1.positionAt)(source, def.origin.start),
1406
+ end: (0, files_1.positionAt)(source, def.origin.end),
1407
+ };
1408
+ const links = [];
1409
+ for (const target of def.targets) {
1410
+ const text = readSourceForDefinition(target.path);
1411
+ if (text === null)
1412
+ continue;
1413
+ const range = { start: (0, files_1.positionAt)(text, target.start), end: (0, files_1.positionAt)(text, target.end) };
1414
+ links.push(node_1.LocationLink.create((0, url_1.pathToFileURL)(target.path).href, range, range, origin));
1415
+ }
1416
+ return definitionLinkSupport
1417
+ ? links
1418
+ : links.map(link => node_1.Location.create(link.targetUri, link.targetRange));
1419
+ }
1420
+ connection.onDefinition((params) => {
1421
+ if (!isServedDocument(params.textDocument.uri))
1422
+ return null;
1423
+ const { importCtx, engine, globalsSource, globalsFilePaths } = scopeFor(params.textDocument.uri);
1424
+ const doc = documents.get(params.textDocument.uri);
1425
+ if (!doc)
1426
+ return null;
1427
+ const source = doc.getText();
1428
+ const offset = doc.offsetAt(params.position);
1429
+ // `.hm` files: delegate to the declarations-only definition provider.
1430
+ if (params.textDocument.uri.endsWith('.hm')) {
1431
+ const hmCtx = {
1432
+ findTypeDefinitions: (n) => importCtx.findTypeDefinitions(n, params.textDocument.uri, source, globalsSource, globalsFilePaths[0] ?? null),
1433
+ globals: globalsSource && globalsFilePaths[0]
1434
+ ? { source: globalsSource, uri: (0, url_1.pathToFileURL)(globalsFilePaths[0]).href }
1435
+ : null,
1436
+ };
1437
+ return (0, hmFileServices_1.getHmDefinition)(params.textDocument.uri, source, offset, hmCtx);
1438
+ }
1439
+ // --- Code: module paths, imported names, local names (syntactic, no
1440
+ // inference needed). Comments are left to the type navigation below. ---
1441
+ if (codeDefinitionsEnabled(params.textDocument.uri) && !(0, hover_1.isOffsetInComment)(source, offset)) {
1442
+ const definition = (0, definitions_1.findCodeDefinition)(source, params.textDocument.uri, offset, {
1443
+ includeLocal: true,
1444
+ readSource: readSourceForDefinition,
1445
+ });
1446
+ if (definition) {
1447
+ const found = toDefinitionResult(definition, source);
1448
+ if (found.length > 0)
1449
+ return found;
1450
+ }
1451
+ }
1452
+ const resolver = importCtx.createImportResolver(params.textDocument.uri);
1453
+ const typeResolver = importCtx.createTypeDirectiveResolver(params.textDocument.uri);
1454
+ const aliasResolver = importCtx.createImportTypeAliasResolver(params.textDocument.uri);
1455
+ // Perf: reuse cached inference result when source is unchanged.
1456
+ const cachedDef = documentCache_1.lastValidatedSource.get(params.textDocument.uri) === source
1457
+ ? documentCache_1.cachedResults.get(params.textDocument.uri)
1458
+ : undefined;
1459
+ const result = cachedDef ?? safeEngineInfer(engine, source, resolver, typeResolver, aliasResolver);
1460
+ const word = (0, hover_1.getWordAt)(source, offset);
1461
+ // --- ::types directive: navigate to the referenced file ---
1462
+ const typeDirectives = (0, index_1.extractTypeDirectivesWithLocations)(source);
1463
+ for (const dir of typeDirectives) {
1464
+ if (offset >= dir.start && offset <= dir.end) {
1465
+ const resolved = (0, files_1.resolveTypeDirectiveSpecifier)(dir.specifier, params.textDocument.uri);
1466
+ if (resolved) {
1467
+ return { uri: (0, url_1.pathToFileURL)(resolved).href, range: { start: { line: 0, character: 0 }, end: { line: 0, character: 0 } } };
1468
+ }
1469
+ }
1470
+ }
1471
+ if (!word)
1472
+ return null;
1473
+ // Build globals context for definition lookup
1474
+ const globalsCtx = globalsSource && globalsFilePaths[0]
1475
+ ? { source: globalsSource, uri: (0, url_1.pathToFileURL)(globalsFilePaths[0]).href }
1476
+ : null;
1477
+ // --- Uppercase words: try type-alias / constructor definition first ---
1478
+ if (/^[A-Z]/.test(word)) {
1479
+ // Trigger when cursor is inside a comment annotation, a ::narrow directive, or a ::constraint directive
1480
+ const inAnnotation = (0, hover_1.isOffsetInAnyAnnotation)(result.annotations, result.annotationsByOffset, offset)
1481
+ || (0, hover_1.isOffsetInComment)(source, offset);
1482
+ const narrowType = (0, hover_1.getNarrowDirectiveTypeAtOffset)(source, offset);
1483
+ const inConstraint = (0, hover_1.isOffsetInConstraintDirective)(source, offset);
1484
+ // Also trigger for uppercase identifiers in code that are known type constructors
1485
+ // (e.g. Box, RTask) — this improves go-to-definition for CJS require() imports
1486
+ // where the built-in JS/TS provider may not follow the require correctly.
1487
+ const inCode = !inAnnotation && !narrowType && !inConstraint;
1488
+ if (!inCode || result.annotations.get(word)?.scheme) {
1489
+ const typeName = narrowType || word;
1490
+ const location = (0, files_1.findTypeDefinitionLocation)(typeName, source, params.textDocument.uri, result, globalsCtx);
1491
+ if (location)
1492
+ return location;
1493
+ // Fallback: search globals + imported sidecars for a matching type
1494
+ // declaration. Honours `// ::prefer Name from <specifier>` to pick
1495
+ // the right one when multiple definitions exist. This makes
1496
+ // go-to-definition work for types like `Prop` from query-builder that
1497
+ // are visible to inference but live only in a sidecar `.hm` file.
1498
+ const defs = importCtx.findTypeDefinitions(typeName, params.textDocument.uri, source, globalsSource, globalsFilePaths[0] ?? null);
1499
+ if (defs.length > 0) {
1500
+ const prefer = require('./commentParser').extractPreferDirectives(source).get(typeName);
1501
+ const matchesPrefer = (origin) => {
1502
+ if (!prefer)
1503
+ return false;
1504
+ if (origin === prefer)
1505
+ return true;
1506
+ return origin.startsWith(prefer + ' ') || origin === `<${prefer}>`;
1507
+ };
1508
+ // When a `// ::prefer` directive picks a single source, return
1509
+ // only that location. Otherwise return ALL matching definitions
1510
+ // so the editor can show e.g. both the base sidecar declaration
1511
+ // and a project-level override.
1512
+ const candidates = prefer
1513
+ ? defs.filter(d => matchesPrefer(d.origin))
1514
+ : defs;
1515
+ const chosen = candidates.length > 0 ? candidates : defs;
1516
+ const locations = [];
1517
+ for (const def of chosen) {
1518
+ if (!def.sourcePath)
1519
+ continue;
1520
+ try {
1521
+ const text = fs.readFileSync(def.sourcePath, 'utf-8');
1522
+ locations.push(node_1.Location.create((0, url_1.pathToFileURL)(def.sourcePath).href, {
1523
+ start: (0, files_1.positionAt)(text, def.commentStart),
1524
+ end: (0, files_1.positionAt)(text, def.commentEnd),
1525
+ }));
1526
+ }
1527
+ catch { /* unreadable — skip */ }
1528
+ }
1529
+ if (locations.length === 1)
1530
+ return locations[0];
1531
+ if (locations.length > 1)
1532
+ return locations;
1533
+ }
1534
+ }
1535
+ }
1536
+ // --- Constraint method: navigate to constraint definition for .method on constrained types ---
1537
+ // Find the most specific node at the cursor offset to look up constraint method signatures
1538
+ let bestStart = -1;
1539
+ for (const [start, { end }] of result.nodeTypes) {
1540
+ if (start <= offset && offset < end && start > bestStart) {
1541
+ bestStart = start;
1542
+ }
1543
+ }
1544
+ if (bestStart >= 0) {
1545
+ const methodSig = result.methodSignatures.get(bestStart);
1546
+ if (methodSig) {
1547
+ // Method signatures from constraints are formatted as "[ConstraintName] method :: ..."
1548
+ const constraintMatch = /^\[([A-Z]\w*)\]/.exec(methodSig);
1549
+ if (constraintMatch) {
1550
+ const constraintName = constraintMatch[1];
1551
+ const location = (0, files_1.findTypeDefinitionLocation)(constraintName, source, params.textDocument.uri, result, globalsCtx);
1552
+ if (location)
1553
+ return location;
1554
+ }
1555
+ }
1556
+ }
1557
+ // --- Import identifiers: skip — the built-in JS/TS service handles
1558
+ // go-to-definition for regular imports. Only intervene for type-
1559
+ // related definitions (handled above). ---
1560
+ const importSpecifiers = (0, files_1.extractImportSpecifiers)(source);
1561
+ if (importSpecifiers.has(word))
1562
+ return null;
1563
+ // --- Fallback: annotation name → code definition ---
1564
+ // When cursor is on the function name inside an HM annotation comment
1565
+ // (e.g. `// intercalate :: ...`), navigate to the code definition.
1566
+ // For regular code identifiers, return null and let the built-in
1567
+ // JS/TS language service handle go-to-definition (avoids duplicates).
1568
+ const allGroups = (0, references_1.collectReferences)(source, result);
1569
+ for (const [, group] of allGroups) {
1570
+ if (group.annotationNameStart !== undefined && group.annotationNameEnd !== undefined) {
1571
+ if (offset >= group.annotationNameStart && offset <= group.annotationNameEnd) {
1572
+ const defLoc = group.locations.find(loc => loc.isDefinition);
1573
+ if (defLoc) {
1574
+ return {
1575
+ uri: params.textDocument.uri,
1576
+ range: {
1577
+ start: doc.positionAt(defLoc.start),
1578
+ end: doc.positionAt(defLoc.end),
1579
+ },
1580
+ };
1581
+ }
1582
+ }
1583
+ }
1584
+ }
1585
+ return null;
1586
+ });
1587
+ // ---------------------------------------------------------------------------
1588
+ // Code Actions — quick-fix suggestions
1589
+ // ---------------------------------------------------------------------------
1590
+ connection.onCodeAction((params) => {
1591
+ if (!isServedDocument(params.textDocument.uri))
1592
+ return [];
1593
+ const doc = documents.get(params.textDocument.uri);
1594
+ if (!doc)
1595
+ return [];
1596
+ if (params.textDocument.uri.endsWith('.hm'))
1597
+ return [];
1598
+ const result = documentCache_1.cachedResults.get(params.textDocument.uri);
1599
+ if (!result)
1600
+ return [];
1601
+ const source = doc.getText();
1602
+ const importSpecifierMap = (0, files_1.extractImportSpecifiers)(source);
1603
+ const ctx = {
1604
+ result,
1605
+ textDocument: doc,
1606
+ inferredTypeStyle: settingsFor(params.textDocument.uri).display.typeVariables,
1607
+ importSpecifierMap,
1608
+ };
1609
+ return (0, codeActions_1.getCodeActions)(params, ctx);
1610
+ });
1611
+ // ---------------------------------------------------------------------------
1612
+ // Document Symbols — outline / breadcrumbs
1613
+ // ---------------------------------------------------------------------------
1614
+ connection.onDocumentSymbol((params) => {
1615
+ if (!isServedDocument(params.textDocument.uri))
1616
+ return [];
1617
+ const doc = documents.get(params.textDocument.uri);
1618
+ if (!doc)
1619
+ return [];
1620
+ const source = doc.getText();
1621
+ // `.hm` files: flat list of annotation declarations (no inference cache).
1622
+ if (params.textDocument.uri.endsWith('.hm')) {
1623
+ return (0, hmFileServices_1.getHmDocumentSymbols)(params.textDocument.uri, source);
1624
+ }
1625
+ const result = documentCache_1.cachedResults.get(params.textDocument.uri);
1626
+ if (!result)
1627
+ return [];
1628
+ const ctx = {
1629
+ result,
1630
+ inferredTypeStyle: settingsFor(params.textDocument.uri).display.typeVariables,
1631
+ };
1632
+ return (0, documentSymbols_1.getDocumentSymbols)(source, ctx);
1633
+ });
1634
+ // ---------------------------------------------------------------------------
1635
+ // Completion — delegate to ./completion module
1636
+ // ---------------------------------------------------------------------------
1637
+ /** The first provider result that is not empty (providers run lazily). */
1638
+ function firstNonEmpty(providers) {
1639
+ for (const provider of providers) {
1640
+ const items = provider();
1641
+ if (items.length > 0)
1642
+ return items;
1643
+ }
1644
+ return [];
1645
+ }
1646
+ connection.onCompletion((params) => {
1647
+ if (!isServedDocument(params.textDocument.uri))
1648
+ return [];
1649
+ const docSettings = settingsFor(params.textDocument.uri);
1650
+ const { importCtx, engine, globalsSource, globalsFilePaths } = scopeFor(params.textDocument.uri);
1651
+ if (!docSettings.completion.enabled)
1652
+ return [];
1653
+ const doc = documents.get(params.textDocument.uri);
1654
+ if (!doc)
1655
+ return [];
1656
+ // Completion in `.hm` files is not yet implemented — the JS-oriented
1657
+ // completers all expect runnable JS source and would produce noise.
1658
+ if (params.textDocument.uri.endsWith('.hm'))
1659
+ return [];
1660
+ const source = doc.getText();
1661
+ const offset = doc.offsetAt(params.position);
1662
+ const uri = params.textDocument.uri;
1663
+ const ctx = {
1664
+ engine,
1665
+ createImportResolver: (fromUri) => importCtx.createImportResolver(fromUri),
1666
+ createTypeDirectiveResolver: (fromUri) => importCtx.createTypeDirectiveResolver(fromUri),
1667
+ createImportTypeAliasResolver: (fromUri) => importCtx.createImportTypeAliasResolver(fromUri),
1668
+ inferFileAndCacheExports: (fileUri) => importCtx.inferFileAndCacheExports(fileUri),
1669
+ inferredTypeStyle: docSettings.display.typeVariables,
1670
+ autoImports: docSettings.completion.autoImports,
1671
+ cachedResult: documentCache_1.cachedResults.get(uri),
1672
+ getImportedRawSignature: (spec, name, fromUri) => importCtx.getImportedRawSignature(spec, name, fromUri),
1673
+ // One completion request runs several providers that each may infer the
1674
+ // current (or ASI-patched) source; the request cache collapses those to
1675
+ // at most one inference per source variant.
1676
+ inferSource: (src) => inferForRequest(uri, src, () => safeEngineInfer(engine, src, importCtx.createImportResolver(uri), importCtx.createTypeDirectiveResolver(uri), importCtx.createImportTypeAliasResolver(uri))),
1677
+ };
1678
+ // `{` / `,` as trigger: only record-field completions (object-literal
1679
+ // arguments, destructuring patterns, returned records, import braces).
1680
+ const trigger = params.context?.triggerKind === node_1.CompletionTriggerKind.TriggerCharacter
1681
+ ? params.context.triggerCharacter
1682
+ : undefined;
1683
+ if (trigger === '{' || trigger === ',') {
1684
+ return (0, completion_1.getImportSpecifierCompletions)(source, offset, uri, ctx)
1685
+ ?? firstNonEmpty([
1686
+ () => (0, completion_1.getDestructuringCompletions)(source, offset, uri, ctx),
1687
+ () => (0, completion_1.getSumTypeRecordCompletions)(source, offset, uri, ctx),
1688
+ () => (0, completion_1.getTypeAliasRecordCompletions)(source, offset, uri, ctx),
1689
+ () => (0, completion_1.getJSXStyleKeyCompletions)(source, offset, ctx) ?? [],
1690
+ ]);
1691
+ }
1692
+ // --- Import specifier completion: import { | } from './module' ---
1693
+ const importSpecifierItems = (0, completion_1.getImportSpecifierCompletions)(source, offset, uri, ctx);
1694
+ if (importSpecifierItems)
1695
+ return importSpecifierItems;
1696
+ // --- Import path completion: from './|' ---
1697
+ const importPathItems = (0, completion_1.getImportPathCompletions)(source, offset, uri, ctx);
1698
+ if (importPathItems)
1699
+ return importPathItems;
1700
+ // --- Destructuring completion: const { | } = expr ---
1701
+ const destructuringItems = (0, completion_1.getDestructuringCompletions)(source, offset, uri, ctx);
1702
+ if (destructuringItems.length > 0)
1703
+ return destructuringItems;
1704
+ // --- sumtype factory record completion: return { | } ---
1705
+ const sumTypeItems = (0, completion_1.getSumTypeRecordCompletions)(source, offset, uri, ctx);
1706
+ if (sumTypeItems.length > 0)
1707
+ return sumTypeItems;
1708
+ // --- Type alias record completion: return { | } or => ({ | }) ---
1709
+ const aliasRecordItems = (0, completion_1.getTypeAliasRecordCompletions)(source, offset, uri, ctx);
1710
+ if (aliasRecordItems.length > 0)
1711
+ return aliasRecordItems;
1712
+ // --- Directive keyword completion: // ::i| → ignore, ignore-file, ... ---
1713
+ const directiveItems = (0, completion_1.getDirectiveCompletions)(source, offset);
1714
+ if (directiveItems.length > 0)
1715
+ return directiveItems;
1716
+ // --- ::types path completion: // ::types ./| or // ::types ../lib/| ---
1717
+ const typeDirectivePathItems = (0, completion_1.getTypeDirectivePathCompletions)(source, offset, uri);
1718
+ if (typeDirectivePathItems)
1719
+ return typeDirectivePathItems;
1720
+ // --- Annotation type completion: // name :: Num| ---
1721
+ const annotationTypeItems = (0, completion_1.getAnnotationTypeCompletions)(source, offset, uri, ctx);
1722
+ if (annotationTypeItems.length > 0)
1723
+ return annotationTypeItems;
1724
+ // --- Annotation name completion: // myF| → suggest existing JS bindings ---
1725
+ const annotationNameItems = (0, completion_1.getAnnotationNameCompletions)(source, offset, uri, ctx);
1726
+ if (annotationNameItems.length > 0)
1727
+ return annotationNameItems;
1728
+ // --- Bracket string completion: expr["| or expr['| ---
1729
+ const bracketStringItems = (0, completion_1.getBracketStringCompletions)(source, offset, uri, ctx);
1730
+ if (bracketStringItems.length > 0)
1731
+ return bracketStringItems;
1732
+ // --- JSX prop completion: <Badge l| ---
1733
+ const jsxPropItems = (0, completion_1.getJSXPropCompletions)(source, offset, uri, ctx);
1734
+ if (jsxPropItems.length > 0)
1735
+ return jsxPropItems;
1736
+ // --- CSS property completion inside style={{ … }} (array = final,
1737
+ // even when empty — key positions must not fall through) ---
1738
+ const jsxStyleKeyItems = (0, completion_1.getJSXStyleKeyCompletions)(source, offset, ctx);
1739
+ if (jsxStyleKeyItems)
1740
+ return jsxStyleKeyItems;
1741
+ // --- JSX component-name completion: <Badg| ---
1742
+ const jsxComponentItems = (0, completion_1.getJSXComponentCompletions)(source, offset, uri, ctx);
1743
+ if (jsxComponentItems.length > 0)
1744
+ return jsxComponentItems;
1745
+ // --- Table-selector completion: PascalCase([ | ]) or PascalCase(["i| ---
1746
+ const tableSelectorItems = (0, completion_1.getTableSelectorCompletions)(source, offset, uri, ctx);
1747
+ if (tableSelectorItems.length > 0)
1748
+ return tableSelectorItems;
1749
+ // --- Dot completion: expr.| ---
1750
+ const dotIdx = offset - 1;
1751
+ if (dotIdx >= 0 && source[dotIdx] === '.') {
1752
+ return (0, completion_1.getDotCompletions)(source, offset, dotIdx, uri, ctx);
1753
+ }
1754
+ // --- Identifier completion with type info + auto-import ---
1755
+ return (0, completion_1.getIdentifierCompletions)(source, offset, uri, ctx);
1756
+ });
1757
+ // ---------------------------------------------------------------------------
1758
+ // Signature Help — show parameter info when typing function arguments
1759
+ // ---------------------------------------------------------------------------
1760
+ connection.onSignatureHelp((params) => {
1761
+ if (!isServedDocument(params.textDocument.uri))
1762
+ return null;
1763
+ const { importCtx, engine, globalsSource, globalsFilePaths } = scopeFor(params.textDocument.uri);
1764
+ if (!settingsFor(params.textDocument.uri).signatureHelp.enabled)
1765
+ return null;
1766
+ const doc = documents.get(params.textDocument.uri);
1767
+ if (!doc)
1768
+ return null;
1769
+ if (params.textDocument.uri.endsWith('.hm'))
1770
+ return null;
1771
+ const uri = params.textDocument.uri;
1772
+ const resolver = importCtx.createImportResolver(uri);
1773
+ const typeResolver = importCtx.createTypeDirectiveResolver(uri);
1774
+ const aliasResolver = importCtx.createImportTypeAliasResolver(uri);
1775
+ return (0, signatureHelp_1.provideSignatureHelp)({
1776
+ source: doc.getText(),
1777
+ offset: doc.offsetAt(params.position),
1778
+ engine,
1779
+ resolver,
1780
+ typeResolver,
1781
+ importTypeAliasResolver: aliasResolver,
1782
+ reinferWithArrayASI: reinferWithArrayASIFor(engine),
1783
+ // Signature help re-fires on every keystroke while its popup is open;
1784
+ // route inference through the request cache so an unchanged document
1785
+ // version never pays for a second inference.
1786
+ inferSource: (src) => inferForRequest(uri, src, () => safeEngineInfer(engine, src, resolver, typeResolver, aliasResolver)),
1787
+ });
1788
+ });
1789
+ // ---------------------------------------------------------------------------
1790
+ // References / Rename — delegated to ./services/rename
1791
+ // ---------------------------------------------------------------------------
1792
+ connection.onReferences((params) => {
1793
+ if (!isServedDocument(params.textDocument.uri))
1794
+ return [];
1795
+ const doc = documents.get(params.textDocument.uri);
1796
+ if (!doc)
1797
+ return [];
1798
+ if (params.textDocument.uri.endsWith('.hm'))
1799
+ return [];
1800
+ return (0, rename_1.provideReferences)(doc, params, documentCache_1.cachedResults.get(params.textDocument.uri));
1801
+ });
1802
+ connection.onPrepareRename((params) => {
1803
+ if (!isServedDocument(params.textDocument.uri))
1804
+ return null;
1805
+ const doc = documents.get(params.textDocument.uri);
1806
+ if (!doc)
1807
+ return null;
1808
+ if (params.textDocument.uri.endsWith('.hm'))
1809
+ return null;
1810
+ return (0, rename_1.providePrepareRename)(doc, params, documentCache_1.cachedResults.get(params.textDocument.uri));
1811
+ });
1812
+ connection.onRenameRequest((params) => {
1813
+ if (!isServedDocument(params.textDocument.uri))
1814
+ return null;
1815
+ const doc = documents.get(params.textDocument.uri);
1816
+ if (!doc)
1817
+ return null;
1818
+ if (params.textDocument.uri.endsWith('.hm'))
1819
+ return null;
1820
+ return (0, rename_1.provideRename)(doc, params, documentCache_1.cachedResults.get(params.textDocument.uri));
1821
+ });
1822
+ // ---------------------------------------------------------------------------
1823
+ // Start
1824
+ // ---------------------------------------------------------------------------
1825
+ // Clean up per-document state when a document is closed so that
1826
+ // `cachedResults` and import-context caches don't accumulate over the
1827
+ // lifetime of the server. We also clear any pending diagnostics so the
1828
+ // editor doesn't keep showing stale ones for a file that's no longer open.
1829
+ documents.onDidClose((event) => {
1830
+ const uri = event.document.uri;
1831
+ documentCache_1.cachedResults.delete(uri);
1832
+ documentCache_1.lastValidatedSource.delete(uri);
1833
+ documentCache_1.requestInferCache.delete(uri);
1834
+ documentCache_1.validatedUnderGeneration.delete(uri);
1835
+ documentCache_1.lastPublishedDiagnostics.delete(uri);
1836
+ documentCache_1.lastImportSpecifiers.delete(uri);
1837
+ documentCache_1.lastSeenSource.delete(uri);
1838
+ documentCache_1.lastEditPosition.delete(uri);
1839
+ const pending = pendingValidations.get(uri);
1840
+ if (pending) {
1841
+ clearTimeout(pending);
1842
+ pendingValidations.delete(uri);
1843
+ }
1844
+ // Only invalidate the import-context entry if no other open file
1845
+ // depends on it; otherwise keep it cached so cross-file inference
1846
+ // still works.
1847
+ const dependents = dependentsOf(uri);
1848
+ const stillNeeded = dependents && Array.from(dependents).some(d => documents.get(d));
1849
+ if (!stillNeeded) {
1850
+ invalidateEverywhere(uri);
1851
+ }
1852
+ connection.sendDiagnostics({ uri, diagnostics: [] });
1853
+ });
1854
+ // Background pre-warm on open: as soon as the user opens a file, fire-and-
1855
+ // forget infer its direct imports so the file-level cache is warm by the
1856
+ // time the first hover or completion request arrives. Without this, the
1857
+ // only thing that warms the import cache is `validateTextDocument`, which
1858
+ // only runs after the keystroke debounce (default 500ms) — so a hover that
1859
+ // lands within that window walks the entire import graph synchronously on
1860
+ // the hover request thread (observed: ~10s on large repos).
1861
+ //
1862
+ // `inferFileAndCacheExports` is idempotent + LRU-cached: subsequent
1863
+ // validations / hovers re-use the warmed entries. We also seed
1864
+ // `lastImportSpecifiers` so the validation pre-warm loop sees no change
1865
+ // and skips its own redundant pass.
1866
+ documents.onDidOpen((event) => {
1867
+ const doc = event.document;
1868
+ const uri = doc.uri;
1869
+ if (uri.endsWith('.hm'))
1870
+ return;
1871
+ if (!uri.endsWith('.js') && !uri.endsWith('.mjs') && !uri.endsWith('.cjs') && !uri.endsWith('.jsx'))
1872
+ return;
1873
+ setImmediate(() => {
1874
+ try {
1875
+ const source = doc.getText();
1876
+ const specifiers = (0, commentParser_1.extractImportModuleSpecifiers)(source);
1877
+ for (const specifier of specifiers) {
1878
+ try {
1879
+ const targetUri = (0, files_1.resolveImportSpecifier)(specifier, uri);
1880
+ if (targetUri && targetUri !== uri) {
1881
+ scopeFor(uri).importCtx.inferFileAndCacheExports(targetUri);
1882
+ }
1883
+ }
1884
+ catch { /* per-specifier failure must not break pre-warm */ }
1885
+ }
1886
+ // Seed so the validation pre-warm loop sees specifiers unchanged.
1887
+ documentCache_1.lastImportSpecifiers.set(uri, specifiers);
1888
+ }
1889
+ catch (e) {
1890
+ connection.console.warn(`[hinmil] pre-warm failed for ${uri}: ${e instanceof Error ? e.message : String(e)}`);
1891
+ }
1892
+ });
1893
+ });
1894
+ documents.listen(connection);
1895
+ connection.listen();
1896
+ //# sourceMappingURL=server.js.map