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
@@ -0,0 +1,1999 @@
1
+ "use strict";
2
+ // ============================================================================
3
+ // Import Inference Context — encapsulates cross-file caching & resolution
4
+ //
5
+ // Plain language: analysing one file often requires analysing the files it
6
+ // imports — which import files of their own. This context object manages
7
+ // that chain: it analyses imported files on demand, caches their results so
8
+ // repeated requests are instant, detects cycles, and keeps the global
9
+ // registries consistent while switching between files.
10
+ // ============================================================================
11
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
12
+ if (k2 === undefined) k2 = k;
13
+ var desc = Object.getOwnPropertyDescriptor(m, k);
14
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
15
+ desc = { enumerable: true, get: function() { return m[k]; } };
16
+ }
17
+ Object.defineProperty(o, k2, desc);
18
+ }) : (function(o, m, k, k2) {
19
+ if (k2 === undefined) k2 = k;
20
+ o[k2] = m[k];
21
+ }));
22
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
23
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
24
+ }) : function(o, v) {
25
+ o["default"] = v;
26
+ });
27
+ var __importStar = (this && this.__importStar) || (function () {
28
+ var ownKeys = function(o) {
29
+ ownKeys = Object.getOwnPropertyNames || function (o) {
30
+ var ar = [];
31
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
32
+ return ar;
33
+ };
34
+ return ownKeys(o);
35
+ };
36
+ return function (mod) {
37
+ if (mod && mod.__esModule) return mod;
38
+ var result = {};
39
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
40
+ __setModuleDefault(result, mod);
41
+ return result;
42
+ };
43
+ })();
44
+ Object.defineProperty(exports, "__esModule", { value: true });
45
+ exports.ImportInferenceContext = void 0;
46
+ exports.setBuiltinTypesDir = setBuiltinTypesDir;
47
+ const fs = __importStar(require("fs"));
48
+ const url_1 = require("url");
49
+ const infer_1 = require("../infer");
50
+ const types_1 = require("../infer/types");
51
+ const types_2 = require("../hm/types");
52
+ const session_1 = require("../registries/session");
53
+ const files_1 = require("./files");
54
+ const fsProbe_1 = require("./fsProbe");
55
+ const sidecarPerf_1 = require("./sidecarPerf");
56
+ const moduleReps_1 = require("../infer/moduleReps");
57
+ const commentParser_1 = require("../commentParser");
58
+ const path = __importStar(require("path"));
59
+ /** True when an absolute path lives under a `node_modules` directory. */
60
+ function isUnderNodeModules(absPath) {
61
+ const parts = absPath.split(path.sep);
62
+ return parts.includes('node_modules');
63
+ }
64
+ // ---------------------------------------------------------------------------
65
+ // Built-in bundled typings (`hm-types-builtin/`)
66
+ // ---------------------------------------------------------------------------
67
+ // The extension ships `.hm` typings for a handful of popular packages
68
+ // (react, react-dom) so those work with ZERO configuration. They form the
69
+ // weakest layer of the resolution chain: project overrides, conventional
70
+ // `hm-types/<pkg>.hm` stubs and package sidecars all merge ON TOP of them
71
+ // per export name. Export maps that include a builtin layer are marked
72
+ // open-world (see {@link markOpenWorldExports}) so names missing from the
73
+ // bundled catalogue bind to `Any` instead of erroring.
74
+ let _builtinTypesDir;
75
+ /** Override the bundled-typings directory (tests, packaging). `null` disables. */
76
+ function setBuiltinTypesDir(dir) {
77
+ _builtinTypesDir = dir;
78
+ }
79
+ function getBuiltinTypesDir() {
80
+ if (_builtinTypesDir !== undefined)
81
+ return _builtinTypesDir;
82
+ // Compiled layout (`dist/services/`) and source layout (`src/services/`)
83
+ // both sit two levels below the package root that carries the folder.
84
+ for (const candidate of [
85
+ path.resolve(__dirname, '..', '..', 'hm-types-builtin'),
86
+ path.resolve(__dirname, '..', '..', '..', 'hm-types-builtin'),
87
+ ]) {
88
+ try {
89
+ if (fs.statSync(candidate).isDirectory())
90
+ return (_builtinTypesDir = candidate);
91
+ }
92
+ catch { /* try next */ }
93
+ }
94
+ return (_builtinTypesDir = null);
95
+ }
96
+ /** Absolute path of the bundled `<pkgName>.hm`, or null when not shipped. */
97
+ /** The `// ::builtin Name` anchor of a built-in type in the bundled stubs
98
+ * (`hm-types-builtin/*.hm`), with the range of the anchor line, or null. */
99
+ function findBuiltinTypeAnchor(name) {
100
+ const dir = getBuiltinTypesDir();
101
+ if (!dir || !/^[A-Za-z_$][\w$]*$/.test(name))
102
+ return null;
103
+ const re = new RegExp('^\\s*//\\s*::builtin\\s+' + name + '\\b');
104
+ let files;
105
+ try {
106
+ files = fs.readdirSync(dir).filter(f => f.endsWith('.hm')).sort();
107
+ }
108
+ catch {
109
+ return null;
110
+ }
111
+ for (const f of files) {
112
+ const filePath = path.join(dir, f);
113
+ let text;
114
+ try {
115
+ text = fs.readFileSync(filePath, 'utf-8');
116
+ }
117
+ catch {
118
+ continue;
119
+ }
120
+ let cursor = 0;
121
+ for (const line of text.split('\n')) {
122
+ if (re.test(line))
123
+ return { sourcePath: filePath, commentStart: cursor, commentEnd: cursor + line.length };
124
+ cursor += line.length + 1;
125
+ }
126
+ }
127
+ return null;
128
+ }
129
+ function builtinHmPath(pkgName) {
130
+ const dir = getBuiltinTypesDir();
131
+ // Node core modules may be imported with the `node:` scheme
132
+ // (`import { join } from "node:path"`); both forms share one stub.
133
+ if (pkgName.startsWith('node:'))
134
+ pkgName = pkgName.slice('node:'.length);
135
+ // Flat names only — refuses scoped names ('@a/b') and anything that could
136
+ // escape the directory.
137
+ if (!dir || !/^[\w.-]+$/.test(pkgName))
138
+ return null;
139
+ const p = path.join(dir, pkgName + '.hm');
140
+ try {
141
+ return (0, fsProbe_1.isFile)(p) ? p : null;
142
+ }
143
+ catch {
144
+ return null;
145
+ }
146
+ }
147
+ /**
148
+ * Merge a project-level `.hm` override on top of a package-level export
149
+ * map. Override entries win on name collision; absent names fall through
150
+ * to the package map. Returns the package map unchanged when there is
151
+ * no override.
152
+ */
153
+ function mergeOverride(override, base) {
154
+ if (!override || override.size === 0)
155
+ return base;
156
+ const merged = new Map(base);
157
+ for (const [name, scheme] of override)
158
+ merged.set(name, scheme);
159
+ return merged;
160
+ }
161
+ /**
162
+ * Merge two optional Scheme maps into one with `b` overriding `a` on
163
+ * conflict. Returns the unwrapped non-null side when only one is
164
+ * present, or an empty map when both are absent.
165
+ */
166
+ function mergeMaps(a, b) {
167
+ if (!a && !b)
168
+ return new Map();
169
+ if (!a)
170
+ return b;
171
+ if (!b)
172
+ return a;
173
+ const out = new Map(a);
174
+ for (const [k, v] of b)
175
+ out.set(k, v);
176
+ return out;
177
+ }
178
+ /**
179
+ * Walk up from a node_modules entry path to the package root (the
180
+ * directory containing the closest `package.json`). Returns the package
181
+ * directory or null when none can be located.
182
+ */
183
+ function findPackageRoot(entryPath) {
184
+ let dir = path.dirname(entryPath);
185
+ while (true) {
186
+ if ((0, fsProbe_1.isFile)(path.join(dir, 'package.json')))
187
+ return dir;
188
+ const parent = path.dirname(dir);
189
+ if (parent === dir)
190
+ return null;
191
+ dir = parent;
192
+ }
193
+ }
194
+ /**
195
+ * Given a typed export map for an npm package, add an `Any`-typed entry
196
+ * for every name that the package's runtime JS module actually exports
197
+ * but that is not yet covered by the typed map. Unlike a fresh tvar,
198
+ * `Any` is opaque under unification — it does not pick up a type from
199
+ * the way the import is *used*, which prevents plausible-looking but
200
+ * hallucinated signatures (e.g. inferring `Limit :: Number -> QueryTag b`
201
+ * from a single `Limit(5)` call site).
202
+ *
203
+ * Loading the JS module via `require` is best-effort — failures are
204
+ * swallowed and the original map is returned unchanged.
205
+ */
206
+ function supplementWithRuntimeExports(exports, entryPath, logger) {
207
+ const pkgRoot = findPackageRoot(entryPath);
208
+ if (!pkgRoot)
209
+ return exports;
210
+ // Load the RESOLVED module, not the package root: for a subpath import
211
+ // (`FP-library/RTask`) the root's names (`RTask`, `Future`, …) are not this
212
+ // module's exports and must not be bound to `Any`.
213
+ const target = entryPath.endsWith('.hm') ? pkgRoot : entryPath;
214
+ let runtimeExports = files_1.runtimeExportNamesCache.get(target);
215
+ if (runtimeExports === undefined) {
216
+ try {
217
+ // eslint-disable-next-line @typescript-eslint/no-require-imports
218
+ const mod = require(target);
219
+ runtimeExports = mod && typeof mod === 'object' ? Object.keys(mod) : [];
220
+ }
221
+ catch (e) {
222
+ const msg = e instanceof Error ? e.message : String(e);
223
+ logger.warn(`[hinmil] could not load runtime exports of '${pkgRoot}': ${msg}`);
224
+ runtimeExports = null;
225
+ }
226
+ files_1.runtimeExportNamesCache.set(target, runtimeExports);
227
+ }
228
+ if (!runtimeExports || runtimeExports.length === 0)
229
+ return exports;
230
+ const merged = new Map(exports);
231
+ for (const name of runtimeExports) {
232
+ if (!merged.has(name))
233
+ merged.set(name, (0, types_2.mono)(types_2.tAnyType));
234
+ }
235
+ (0, moduleReps_1.setModuleReps)(merged, (0, moduleReps_1.getModuleReps)(exports));
236
+ return merged;
237
+ }
238
+ /**
239
+ * Manages the cross-file inference cache and dependency graph.
240
+ *
241
+ * Centralises the fragile snapshot/restore dance that was previously
242
+ * spread across several loose functions: every import-file inference
243
+ * must snapshot the global method/constraint registries and the
244
+ * type-variable counter, run a *separate* engine, restore the
245
+ * caller's registries, then merge in the import's registrations.
246
+ *
247
+ * By encapsulating this in a single class the logic is easier to
248
+ * reason about, test, and extend (e.g. with parallel inference).
249
+ */
250
+ class ImportInferenceContext {
251
+ resetPerfCounters() {
252
+ this.perfInferCalls = 0;
253
+ this.perfCacheHits = 0;
254
+ this.perfCacheMisses = 0;
255
+ this.perfCircular = 0;
256
+ }
257
+ getPerfCounters() {
258
+ return {
259
+ inferCalls: this.perfInferCalls,
260
+ cacheHits: this.perfCacheHits,
261
+ cacheMisses: this.perfCacheMisses,
262
+ circular: this.perfCircular,
263
+ };
264
+ }
265
+ constructor(documents, logger) {
266
+ this.documents = documents;
267
+ this.logger = logger;
268
+ /** Cached inference results per file URI — stores exports for import resolution. */
269
+ this.fileExports = new Map();
270
+ /** Cached registry/counter state per file URI — re-merged on cache hit. */
271
+ this.fileStateSnapshots = new Map();
272
+ /** Reverse dependency map: importedFileUri → Set of fileUris that import it. */
273
+ this.fileDependents = new Map();
274
+ /** Forward dependency map: fileUri → Set of fileUris it imports. */
275
+ this.fileImports = new Map();
276
+ /** LRU order: Map insertion order tracks recency (oldest first). */
277
+ this.lruOrder = new Map();
278
+ /** Files currently being inferred — used for circular import detection. */
279
+ this.inferring = new Set();
280
+ /** Have we already warned the user about LRU evictions? */
281
+ this.hasWarnedAboutEviction = false;
282
+ /** Have we already warned the user about exceeding import depth? */
283
+ this.hasWarnedAboutImportDepth = false;
284
+ /** Phase K perf counters — reset by {@link resetPerfCounters} at the
285
+ * start of each top-level validate, read via {@link getPerfCounters}. */
286
+ this.perfInferCalls = 0;
287
+ /**
288
+ * Memo of {@link createImportTypeAliasResolver} results per resolved import
289
+ * target (`b|`/`r|` + URI: a bare specifier also consults project
290
+ * overrides). The result depends only on the target and the files it
291
+ * reaches, not on the importer, so every consumer of e.g. `FP-library/RTask`
292
+ * shares one walk. Cleared on any file invalidation and on a new project
293
+ * configuration — the LSP routes every document and watched-file change
294
+ * through {@link invalidateFileCache}.
295
+ */
296
+ this.importTypeAliasCache = new Map();
297
+ this.perfCacheHits = 0;
298
+ this.perfCacheMisses = 0;
299
+ this.perfCircular = 0;
300
+ /**
301
+ * Union of all package globals files (`package.json#hinmil.globals`)
302
+ * ever encountered across any consumer. Used by
303
+ * {@link getAllPackageGlobalsAddendum} to compose the server's
304
+ * effective globals source in one shot.
305
+ */
306
+ this.allPackageGlobals = new Set();
307
+ /**
308
+ * Per-sidecar parse artifact cache, keyed by absolute file path. Each
309
+ * entry is stamp-validated on access (open-doc version or disk
310
+ * mtime:size), so edits AND out-of-band regeneration (e.g. re-running a
311
+ * package's introspect script) invalidate automatically.
312
+ */
313
+ this.sidecarArtifacts = new Map();
314
+ /** Project root used to resolve user-side `.hm` overrides + conventional `hm-types/` directory. */
315
+ this.projectRoot = null;
316
+ /** Per-package `.hm` path overrides keyed by bare package name. */
317
+ this.packageOverrides = {};
318
+ /** Project-relative directory checked for `<typesDir>/<pkgName>.hm` stubs. */
319
+ this.typesDir = 'hm-types';
320
+ /** Project globals source (e.g. content of `globals.hm`). Cached so the
321
+ * globals-level `// ::types <specifier>` directives can be resolved at
322
+ * any time without re-reading the file. Set via {@link setProjectConfig}. */
323
+ this.globalsSource = null;
324
+ /** Absolute path to the project globals file. Used as the `from` location
325
+ * when resolving `// ::types` specifiers declared inside the globals. */
326
+ this.globalsFilePath = null;
327
+ }
328
+ /**
329
+ * Configure project-level `.hm` resolution: an `overrides` map, a
330
+ * `typesDir` to scan for conventional `<pkgName>.hm` stub files, and
331
+ * the current project globals source/path. The globals are stored so
332
+ * that {@link getProjectGlobalsAddendum} can resolve `// ::types`
333
+ * directives declared inside `globals.hm` and so that methods declared
334
+ * in the resolved sidecars can be eagerly registered.
335
+ *
336
+ * Call this whenever the workspace root, `hinmil` config, or globals
337
+ * file changes.
338
+ */
339
+ setProjectConfig(root, cfg = {}) {
340
+ // A (new) project configuration starts from a fresh view of the disk:
341
+ // memoised existence probes from an earlier configuration (e.g. a
342
+ // conventional `hm-types/<pkg>.hm` stub that did not exist yet) must not
343
+ // hide files created since.
344
+ (0, fsProbe_1.clearFsProbeCache)();
345
+ this.importTypeAliasCache.clear();
346
+ this.projectRoot = root;
347
+ this.packageOverrides = cfg.overrides ?? {};
348
+ if (cfg.typesDir)
349
+ this.typesDir = cfg.typesDir;
350
+ this.globalsSource = cfg.globalsSource ?? null;
351
+ this.globalsFilePath = cfg.globalsFilePath ?? null;
352
+ // Eagerly register methods declared in every sidecar referenced by a
353
+ // `// ::types <specifier>` directive in the project globals file, so
354
+ // that `Type#m` annotations from those sidecars are available before
355
+ // any individual file triggers their import.
356
+ for (const sidecarPath of this.collectGlobalDirectiveSidecarPaths()) {
357
+ this.registerSidecarMethods(sidecarPath);
358
+ }
359
+ }
360
+ /**
361
+ * Resolve every `// ::types <specifier>` directive in the project globals
362
+ * file to its concrete sidecar `.hm` file path(s). Each specifier is
363
+ * resolved through the same chain used by per-file `::types`:
364
+ * - project-level `hinmil.overrides.<pkg>` (for bare specifiers);
365
+ * - conventional `<typesDir>/<pkg>.hm` stub (for bare specifiers);
366
+ * - the package's own `package.json#hinmil.sidecars` sidecar(s) (for bare specifiers);
367
+ * - or, for relative/absolute paths, the resolved file directly.
368
+ * Returns an empty array when no globals file is configured.
369
+ */
370
+ collectGlobalDirectiveSidecarPaths() {
371
+ if (!this.globalsSource || !this.globalsFilePath)
372
+ return [];
373
+ const { extractTypeDirectives } = require('../commentParser');
374
+ const fromUri = (0, url_1.pathToFileURL)(this.globalsFilePath).href;
375
+ const out = [];
376
+ const seen = new Set();
377
+ const push = (p) => {
378
+ if (seen.has(p))
379
+ return;
380
+ seen.add(p);
381
+ out.push(p);
382
+ };
383
+ for (const specifier of extractTypeDirectives(this.globalsSource)) {
384
+ if (this.projectRoot && (0, files_1.isBareSpecifier)(specifier)) {
385
+ const pkgName = (0, files_1.getBarePackageName)(specifier);
386
+ const overrideRel = this.packageOverrides[pkgName];
387
+ if (overrideRel) {
388
+ const op = path.resolve(this.projectRoot, overrideRel);
389
+ try {
390
+ if ((0, fsProbe_1.isFile)(op))
391
+ push(op);
392
+ }
393
+ catch { /* missing */ }
394
+ }
395
+ const conv = this.conventionalStubPath(specifier);
396
+ if (conv)
397
+ push(conv);
398
+ }
399
+ const targetPath = (0, files_1.resolveTypeDirectiveSpecifier)(specifier, fromUri);
400
+ if (!targetPath)
401
+ continue;
402
+ if ((0, files_1.isBareSpecifier)(specifier)) {
403
+ for (const sp of (0, files_1.findHmSidecarPaths)(targetPath))
404
+ push(sp);
405
+ }
406
+ else {
407
+ // Relative / absolute path — use the resolved file directly.
408
+ push(targetPath);
409
+ }
410
+ }
411
+ return out;
412
+ }
413
+ /**
414
+ * First existing conventional `<typesDir>/…` stub for a bare specifier,
415
+ * subpath-aware (see `conventionalStubRelPaths`): a deep import like
416
+ * `FP-library/RTask/index.js` prefers `<typesDir>/FP-library/RTask/index.hm`, then
417
+ * `<typesDir>/FP-library/RTask.hm`, falling back to the package-level
418
+ * `<typesDir>/FP-library.hm` stub. Returns null when none exists.
419
+ */
420
+ conventionalStubPath(specifier) {
421
+ if (!this.projectRoot)
422
+ return null;
423
+ for (const rel of (0, files_1.conventionalStubRelPaths)(specifier)) {
424
+ const p = path.join(this.projectRoot, this.typesDir, rel);
425
+ try {
426
+ if ((0, fsProbe_1.isFile)(p))
427
+ return p;
428
+ }
429
+ catch { /* missing */ }
430
+ }
431
+ return null;
432
+ }
433
+ /**
434
+ * If `fromUri` points at one of this project's `.hm` override files —
435
+ * either a configured `package.json#hinmil.overrides.<pkg>` entry or a
436
+ * conventional `<typesDir>/<pkg>.hm` stub — return that package's bare
437
+ * specifier (e.g. `"query-builder"`). Otherwise return null.
438
+ *
439
+ * Used so cross-file lookups originating from the override file can
440
+ * still walk the underlying package's own sidecar(s) for peer
441
+ * declarations like `Limit` / `Offset` / `Selector`.
442
+ */
443
+ implicitSpecifierFromOverrideUri(fromUri) {
444
+ let fromPath;
445
+ try {
446
+ fromPath = (0, url_1.fileURLToPath)(fromUri);
447
+ }
448
+ catch {
449
+ return null;
450
+ }
451
+ if (!fromPath.endsWith('.hm'))
452
+ return null;
453
+ const fromAbs = path.resolve(fromPath);
454
+ // 0. Bundled builtin typings directory (`hm-types-builtin/react.hm` →
455
+ // "react") — recognised without a project root so cross-file lookups
456
+ // inside the bundled files resolve their peer declarations.
457
+ const builtinDir = getBuiltinTypesDir();
458
+ if (builtinDir && fromAbs.startsWith(path.resolve(builtinDir) + path.sep)) {
459
+ const rel = path.relative(path.resolve(builtinDir), fromAbs);
460
+ if (!rel.includes(path.sep) && rel.endsWith('.hm')) {
461
+ return rel.slice(0, -'.hm'.length);
462
+ }
463
+ }
464
+ if (!this.projectRoot)
465
+ return null;
466
+ // 1. Explicit override match.
467
+ for (const [pkgName, rel] of Object.entries(this.packageOverrides)) {
468
+ const overridePath = path.resolve(this.projectRoot, rel);
469
+ if (path.resolve(fromPath) === overridePath)
470
+ return pkgName;
471
+ }
472
+ // 2. Conventional `<typesDir>/…` stub — either the package-level
473
+ // `<pkgName>.hm` or a subpath stub like `<pkg>/<subpath>.hm`. The
474
+ // relative path minus `.hm` doubles as the (extensionless) import
475
+ // specifier the stub serves.
476
+ const typesRoot = path.resolve(this.projectRoot, this.typesDir);
477
+ if (fromAbs.startsWith(typesRoot + path.sep)) {
478
+ const rel = path.relative(typesRoot, fromAbs);
479
+ if (rel.endsWith('.hm')) {
480
+ return rel.slice(0, -'.hm'.length).split(path.sep).join('/');
481
+ }
482
+ }
483
+ return null;
484
+ }
485
+ /**
486
+ * Return additional `.hm`-wrapped source to be appended to the project
487
+ * globals file. Built by walking every `// ::types <specifier>`
488
+ * directive in `globals.hm` and resolving it through the same chain as
489
+ * per-file `::types` (project override + conventional `hm-types/<pkg>.hm`
490
+ * + package `hinmil.sidecars` sidecars, or a relative/absolute path). Returns
491
+ * `null` when the globals file has no `::types` directives or no
492
+ * sidecars resolved. Consumers are expected to concatenate this with
493
+ * the user-authored globals before assigning to `engine.globalsSource`.
494
+ */
495
+ getProjectGlobalsAddendum() {
496
+ const sidecarPaths = this.collectGlobalDirectiveSidecarPaths();
497
+ if (sidecarPaths.length === 0)
498
+ return null;
499
+ const { wrapHmSource } = require('./files');
500
+ const parts = [];
501
+ for (const p of sidecarPaths) {
502
+ try {
503
+ const docUri = (0, url_1.pathToFileURL)(p).href;
504
+ const doc = this.documents.get(docUri);
505
+ const raw = doc ? doc.getText() : fs.readFileSync(p, 'utf-8');
506
+ parts.push(wrapHmSource(raw));
507
+ }
508
+ catch { /* unreadable — skip */ }
509
+ }
510
+ if (parts.length === 0)
511
+ return null;
512
+ return parts.join('\n' + commentParser_1.TYPE_DIRECTIVE_PART_BOUNDARY + '\n');
513
+ }
514
+ // ------- LRU cache management -------
515
+ /** Move `uri` to the end of the LRU map (most recently used). */
516
+ touchLru(uri) {
517
+ this.lruOrder.delete(uri);
518
+ this.lruOrder.set(uri, true);
519
+ }
520
+ /** Evict the least-recently-used entries until cache is within bounds. */
521
+ evictIfNeeded() {
522
+ while (this.lruOrder.size > ImportInferenceContext.MAX_CACHE_SIZE) {
523
+ const victim = this.lruOrder.keys().next().value;
524
+ if (victim !== undefined) {
525
+ this.lruOrder.delete(victim);
526
+ this.evictEntry(victim);
527
+ if (!this.hasWarnedAboutEviction) {
528
+ this.hasWarnedAboutEviction = true;
529
+ this.logger.warn(`[hinmil] Import cache exceeded ${ImportInferenceContext.MAX_CACHE_SIZE} files; ` +
530
+ `least-recently-used entries will be re-inferred on demand. ` +
531
+ `Cross-file features may be slower until the cache warms up again.`);
532
+ }
533
+ }
534
+ }
535
+ }
536
+ /** Remove all cached data for a single file without touching the LRU list. */
537
+ evictEntry(uri) {
538
+ this.fileExports.delete(uri);
539
+ this.fileStateSnapshots.delete(uri);
540
+ }
541
+ // ------- dependency tracking -------
542
+ /** Record that `fromUri` depends on `targetUri` (both forward and reverse). */
543
+ trackDependency(fromUri, targetUri) {
544
+ if (!this.fileDependents.has(targetUri))
545
+ this.fileDependents.set(targetUri, new Set());
546
+ this.fileDependents.get(targetUri).add(fromUri);
547
+ if (!this.fileImports.has(fromUri))
548
+ this.fileImports.set(fromUri, new Set());
549
+ this.fileImports.get(fromUri).add(targetUri);
550
+ }
551
+ getDependents(uri) {
552
+ return this.fileDependents.get(uri);
553
+ }
554
+ getImports(uri) {
555
+ return this.fileImports.get(uri);
556
+ }
557
+ /**
558
+ * Record that `fromUri` (a consumer file) saw a package globals file
559
+ * along the resolution chain. Registers the globals path so it
560
+ * contributes to {@link getAllPackageGlobalsAddendum}, and ties the
561
+ * consumer's cache freshness to the globals file via
562
+ * {@link trackDependency}. No-op when the package has no globals.
563
+ */
564
+ recordPackageGlobals(fromUri, targetPath) {
565
+ const globalsPaths = (0, files_1.findPackageGlobalsPaths)(targetPath, this.logger);
566
+ if (globalsPaths.length === 0)
567
+ return;
568
+ for (const globalsPath of globalsPaths) {
569
+ this.allPackageGlobals.add(globalsPath);
570
+ // Tie the consumer's freshness to changes in the globals file too.
571
+ this.trackDependency(fromUri, (0, url_1.pathToFileURL)(globalsPath).href);
572
+ }
573
+ }
574
+ /** Drop any cached package globals (used on full reload). */
575
+ clearPackageGlobals() {
576
+ this.allPackageGlobals.clear();
577
+ }
578
+ /**
579
+ * Concatenated source of every package globals file ever seen across
580
+ * all consumers, deduped by absolute path. Returned in deterministic
581
+ * (insertion) order. `null` when none have been recorded.
582
+ */
583
+ getAllPackageGlobalsAddendum() {
584
+ if (this.allPackageGlobals.size === 0)
585
+ return null;
586
+ const parts = [];
587
+ for (const p of this.allPackageGlobals) {
588
+ try {
589
+ const docUri = (0, url_1.pathToFileURL)(p).href;
590
+ const doc = this.documents.get(docUri);
591
+ parts.push(doc ? doc.getText() : fs.readFileSync(p, 'utf-8'));
592
+ }
593
+ catch { /* unreadable — skip */ }
594
+ }
595
+ return parts.length > 0 ? parts.join('\n') : null;
596
+ }
597
+ /**
598
+ * Eagerly scan `dependencies` + `devDependencies` of the workspace
599
+ * `package.json` and pre-register any package-level globals declared
600
+ * via `hinmil.globals`. This ensures the very first inference of any
601
+ * consumer file already sees those globals, instead of only after a
602
+ * second re-validate triggers re-discovery.
603
+ */
604
+ preloadPackageGlobalsFromWorkspace(workspaceRoot) {
605
+ let manifest;
606
+ try {
607
+ manifest = JSON.parse(fs.readFileSync(path.join(workspaceRoot, 'package.json'), 'utf-8'));
608
+ }
609
+ catch {
610
+ return;
611
+ }
612
+ const deps = {
613
+ ...(manifest.dependencies ?? {}),
614
+ ...(manifest.devDependencies ?? {}),
615
+ ...(manifest.peerDependencies ?? {}),
616
+ ...(manifest.optionalDependencies ?? {}),
617
+ };
618
+ for (const pkgName of Object.keys(deps)) {
619
+ try {
620
+ const pkgJsonPath = require.resolve(path.posix.join(pkgName, 'package.json'), { paths: [workspaceRoot] });
621
+ const pkgDir = path.dirname(pkgJsonPath);
622
+ for (const globalsPath of (0, files_1.findPackageGlobalsPaths)(pkgDir, this.logger)) {
623
+ this.allPackageGlobals.add(globalsPath);
624
+ }
625
+ }
626
+ catch { /* unresolved — skip */ }
627
+ }
628
+ }
629
+ /**
630
+ * Warm the inline-annotation BFS cache for every direct workspace
631
+ * dependency. Each scan walks up to {@link INLINE_PACKAGE_MAX_FILES}
632
+ * JS files inside a package; doing this synchronously inside
633
+ * {@link createImportResolver} is the dominant factor in cold-hover
634
+ * latency. Pre-running the scans here moves that cost out of the
635
+ * critical path so the first hover/validation lands on a warm cache.
636
+ *
637
+ * Safe to call from a background task ({@link setImmediate}) — the
638
+ * underlying cache is keyed by `pkgRoot\0effectiveEntry`, so a later
639
+ * resolver invocation that arrives mid-scan simply re-uses or
640
+ * re-populates the same entry idempotently.
641
+ *
642
+ * Called from the server right after {@link setProjectConfig}.
643
+ */
644
+ preloadInlinePackageAnnotationsFromWorkspace(workspaceRoot) {
645
+ let manifest;
646
+ try {
647
+ manifest = JSON.parse(fs.readFileSync(path.join(workspaceRoot, 'package.json'), 'utf-8'));
648
+ }
649
+ catch {
650
+ return;
651
+ }
652
+ const deps = {
653
+ ...(manifest.dependencies ?? {}),
654
+ ...(manifest.devDependencies ?? {}),
655
+ ...(manifest.peerDependencies ?? {}),
656
+ ...(manifest.optionalDependencies ?? {}),
657
+ };
658
+ const pkgNames = Object.keys(deps);
659
+ for (const pkgName of pkgNames) {
660
+ try {
661
+ const mainEntry = require.resolve(pkgName, { paths: [workspaceRoot] });
662
+ (0, files_1.collectInlinePackageAnnotations)(mainEntry, this.logger);
663
+ }
664
+ catch { /* unresolved or no JS entry — skip */ }
665
+ }
666
+ }
667
+ /**
668
+ * Return the set of direct imports of `uri` that participate in a cycle
669
+ * back to `uri`. Works for both direct (A→B→A) and indirect (A→B→C→A)
670
+ * cycles by doing a DFS from each import to see if it can reach `uri`.
671
+ */
672
+ getCircularImports(uri) {
673
+ const circular = new Set();
674
+ const imports = this.fileImports.get(uri);
675
+ if (!imports)
676
+ return circular;
677
+ for (const dep of imports) {
678
+ // DFS from `dep` following fileImports edges; if we reach `uri` it's a cycle
679
+ const visited = new Set();
680
+ const stack = [dep];
681
+ while (stack.length > 0) {
682
+ const current = stack.pop();
683
+ if (current === uri) {
684
+ circular.add(dep);
685
+ break;
686
+ }
687
+ if (visited.has(current))
688
+ continue;
689
+ visited.add(current);
690
+ const next = this.fileImports.get(current);
691
+ if (next)
692
+ for (const n of next)
693
+ stack.push(n);
694
+ }
695
+ }
696
+ return circular;
697
+ }
698
+ // ------- cache management -------
699
+ /** Cache only the exports (used by validateTextDocument for the open file). */
700
+ cacheExports(uri, exports) {
701
+ this.fileExports.set(uri, exports);
702
+ }
703
+ /**
704
+ * Cache exports plus the post-inference snapshot of the global
705
+ * method/constraint/dataType registries and the tvar counter, so a
706
+ * later cross-file import of this URI hits the cache in
707
+ * {@link inferFileAndCacheExports} instead of re-running the engine.
708
+ *
709
+ * The snapshots are full registry dumps taken AFTER the open document
710
+ * was inferred — a superset of "what this file added". Merging a
711
+ * superset back into a different engine is safe because every snapshot
712
+ * entry is keyed by `(typeName, methodName)` / `(typeName, classKey)` /
713
+ * `(typeName)`; identical keys overwrite identically, and extra keys
714
+ * never affect inference of code that does not reference them.
715
+ *
716
+ * Called from {@link validateTextDocument} after every successful
717
+ * `engine.infer` on the open file.
718
+ */
719
+ cacheExportsWithSnapshot(uri, exports, methodSnapshot) {
720
+ this.fileExports.set(uri, exports);
721
+ this.fileStateSnapshots.set(uri, (0, session_1.snapshotGlobalState)(methodSnapshot));
722
+ this.touchLru(uri);
723
+ this.evictIfNeeded();
724
+ }
725
+ /** Invalidate all cached data for a single file. */
726
+ invalidateFileCache(uri) {
727
+ this.importTypeAliasCache.clear();
728
+ this.evictEntry(uri);
729
+ this.lruOrder.delete(uri);
730
+ }
731
+ // ------- import inference -------
732
+ /**
733
+ * Infer a file and cache its exports. If the file is open in the
734
+ * editor, use its current content; otherwise read from disk.
735
+ *
736
+ * Handles the full snapshot → infer → restore → merge cycle for
737
+ * method/constraint registries and the type-variable counter.
738
+ */
739
+ inferFileAndCacheExports(fileUri) {
740
+ // --- Circular import detection ---
741
+ if (this.inferring.has(fileUri)) {
742
+ this.perfCircular++;
743
+ this.logger.warn(`[hinmil] Circular import detected: ${fileUri}`);
744
+ // Return whatever partial exports we have cached, or empty
745
+ return this.fileExports.get(fileUri) ?? new Map();
746
+ }
747
+ // --- Import-chain depth guard ---
748
+ // The size of `this.inferring` reflects the current call-stack depth
749
+ // through nested imports. Bail out before recursion gets out of hand.
750
+ if (this.inferring.size >= ImportInferenceContext.MAX_IMPORT_DEPTH) {
751
+ if (!this.hasWarnedAboutImportDepth) {
752
+ this.hasWarnedAboutImportDepth = true;
753
+ this.logger.warn(`[hinmil] Import chain depth exceeded ${ImportInferenceContext.MAX_IMPORT_DEPTH}; ` +
754
+ `further nested imports will be skipped. Check for accidental fan-out or ` +
755
+ `restructure deeply-nested module graphs.`);
756
+ }
757
+ return this.fileExports.get(fileUri) ?? new Map();
758
+ }
759
+ // Check cache — only use if we have COMPLETE data (exports + registry
760
+ // state snapshot). validateTextDocument may have cached only exports,
761
+ // which would cause method registrations to be silently skipped.
762
+ const cached = this.fileExports.get(fileUri);
763
+ const stateSnap = this.fileStateSnapshots.get(fileUri);
764
+ if (cached && stateSnap) {
765
+ this.perfCacheHits++;
766
+ this.touchLru(fileUri);
767
+ (0, session_1.mergeGlobalState)(stateSnap);
768
+ return cached;
769
+ }
770
+ // Get source: prefer open document, fall back to disk
771
+ let source;
772
+ const doc = this.documents.get(fileUri);
773
+ if (doc) {
774
+ source = doc.getText();
775
+ }
776
+ else {
777
+ try {
778
+ const filePath = (0, url_1.fileURLToPath)(fileUri);
779
+ source = fs.readFileSync(filePath, 'utf-8');
780
+ }
781
+ catch (e) {
782
+ const msg = e instanceof Error ? e.message : String(e);
783
+ this.logger.warn(`[hinmil] Failed to read import '${fileUri}': ${msg}`);
784
+ return null;
785
+ }
786
+ }
787
+ // Mark as in-progress for circular import detection
788
+ this.inferring.add(fileUri);
789
+ // Snapshot global state before the import's inference.
790
+ //
791
+ // Built-in override policy: a `// Array#every :: ...` declaration in an
792
+ // imported file IS allowed to take effect for the duration of the
793
+ // importer's inference pass — the LSP-level wrapper around engine.infer
794
+ // (`safeEngineInfer` in server.ts) and the workspace scan wrapper in
795
+ // `getWorkspaceExports` already snapshot+restore built-in original
796
+ // entries at the request boundary, so the override stays scoped to the
797
+ // request that explicitly required the file.
798
+ const saved = (0, session_1.snapshotGlobalState)();
799
+ try {
800
+ // Run a separate engine so the caller's in-progress state is not corrupted
801
+ const importEngine = new infer_1.InferenceEngine();
802
+ this.perfCacheMisses++;
803
+ this.perfInferCalls++;
804
+ // Forward project globals so imported files see the same globals
805
+ // (e.g. query-builder sidecar tables, project-wide aliases, AND project-wide
806
+ // `::constraint` definitions) as the entry file. This MUST mirror the
807
+ // composition the server builds for the main engine
808
+ // (`globalsSource + ::types-addendum + package-addendum`): the
809
+ // user-authored `globalsSource` carries `::constraint Foldable …`
810
+ // declarations, and `infer()` calls `clearConstraints()` then
811
+ // re-registers ONLY from `globalsSource`. Forwarding just the sidecar
812
+ // addendum (the old behavior) dropped those constraints, so a `::rep`
813
+ // whose constraint lives in the project globals failed to bind during
814
+ // any cache-cold cross-file inference (e.g. the re-inference a save
815
+ // forces after invalidating the export cache), silently stripping the
816
+ // rep from the imported scheme.
817
+ const addendum = this.getProjectGlobalsAddendum();
818
+ const pkgAddendum = this.getAllPackageGlobalsAddendum();
819
+ let importGlobals = this.globalsSource ?? null;
820
+ if (addendum)
821
+ importGlobals = importGlobals ? `${importGlobals}\n${addendum}` : addendum;
822
+ if (pkgAddendum)
823
+ importGlobals = importGlobals ? `${importGlobals}\n${pkgAddendum}` : pkgAddendum;
824
+ if (importGlobals)
825
+ importEngine.globalsSource = importGlobals;
826
+ const resolver = this.createImportResolver(fileUri);
827
+ const typeResolver = this.createTypeDirectiveResolver(fileUri);
828
+ const aliasResolver = this.createImportTypeAliasResolver(fileUri);
829
+ const result = importEngine.infer(source, undefined, resolver, typeResolver, aliasResolver);
830
+ // Counter reconciliation: never go backwards
831
+ (0, session_1.bumpTypeVarCounterTo)(saved.tvarCounter);
832
+ // Capture → restore → merge registries. `mergeMethodRegistry` carries
833
+ // any builtin override verbatim from the import snapshot into the host
834
+ // registry (see the builtin-override policy note above).
835
+ const imported = (0, session_1.snapshotGlobalState)();
836
+ (0, session_1.restoreGlobalRegistries)(saved);
837
+ (0, session_1.mergeGlobalState)(imported);
838
+ // Persist in cache and update LRU
839
+ this.fileExports.set(fileUri, result.exports);
840
+ this.fileStateSnapshots.set(fileUri, imported);
841
+ this.touchLru(fileUri);
842
+ this.evictIfNeeded();
843
+ return result.exports;
844
+ }
845
+ finally {
846
+ this.inferring.delete(fileUri);
847
+ }
848
+ }
849
+ // ------- resolver factories -------
850
+ /**
851
+ * Central stamp-validated accessor for {@link sidecarArtifacts}. Returns
852
+ * the cached entry when the stamp still matches (open-doc version or disk
853
+ * mtime:size); otherwise reads the source and starts a fresh entry.
854
+ * Returns `null` when the file is neither open nor readable.
855
+ */
856
+ getSidecarArtifacts(filePath) {
857
+ const docUri = (0, url_1.pathToFileURL)(filePath).href;
858
+ const doc = this.documents.get(docUri);
859
+ let stamp;
860
+ let readSource;
861
+ if (doc) {
862
+ stamp = `doc:${doc.version}`;
863
+ readSource = () => doc.getText();
864
+ }
865
+ else {
866
+ let st;
867
+ try {
868
+ st = fs.statSync(filePath);
869
+ }
870
+ catch {
871
+ this.sidecarArtifacts.delete(filePath);
872
+ return null;
873
+ }
874
+ stamp = `disk:${st.mtimeMs}:${st.size}`;
875
+ readSource = () => fs.readFileSync(filePath, 'utf-8');
876
+ }
877
+ const cached = this.sidecarArtifacts.get(filePath);
878
+ if (cached && cached.stamp === stamp)
879
+ return cached;
880
+ let source;
881
+ try {
882
+ source = readSource();
883
+ }
884
+ catch {
885
+ this.sidecarArtifacts.delete(filePath);
886
+ return null;
887
+ }
888
+ const fresh = { stamp, source };
889
+ this.sidecarArtifacts.set(filePath, fresh);
890
+ return fresh;
891
+ }
892
+ /**
893
+ * Load a `.hm` annotation file, preferring an open editor document over
894
+ * the on-disk version so unsaved sidecar edits are reflected immediately.
895
+ */
896
+ loadHmFileLive(filePath) {
897
+ const art = this.getSidecarArtifacts(filePath);
898
+ if (!art)
899
+ return null;
900
+ if (art.exports === undefined) {
901
+ art.exports = (0, sidecarPerf_1.timeSidecarStage)('parse', () => (0, files_1.parseHmSource)(art.source));
902
+ }
903
+ return art.exports;
904
+ }
905
+ /** Sidecar variant: resolve `entryPath` → all `hinmil.sidecars` paths and load live, merging in declared order (later overrides earlier). */
906
+ loadHmSidecarLive(entryPath) {
907
+ const paths = (0, files_1.findHmSidecarPaths)(entryPath);
908
+ if (paths.length === 0)
909
+ return null;
910
+ const merged = new Map();
911
+ let any = false;
912
+ for (const p of paths) {
913
+ const m = this.loadHmFileLive(p);
914
+ if (!m)
915
+ continue;
916
+ any = true;
917
+ for (const [k, v] of m)
918
+ merged.set(k, v);
919
+ }
920
+ return any ? merged : null;
921
+ }
922
+ /**
923
+ * Shared body of {@link registerSidecarMethods} and
924
+ * {@link registerInlinePackageMethods}. Registers `Type#method` /
925
+ * `Type.method` annotations into the global method registry, plus
926
+ * any `::constraint` / `data ...` directives found in the source.
927
+ *
928
+ * @param source Raw source text.
929
+ * @param sourceUri `file://` URI used as the origin for constraint
930
+ * directive locations.
931
+ * @param wrapAliases When `true`, alias parsing runs against the
932
+ * wrapped (`// `-prefixed) `.hm` form. When
933
+ * `false`, the source is already JS (annotations
934
+ * live inside real `// ` comments) and is parsed
935
+ * as-is.
936
+ */
937
+ registerAnnotationsFromSource(source, sourceUri, wrapAliases) {
938
+ const prepared = (0, sidecarPerf_1.timeSidecarStage)('register', () => this.prepareRegistration(source, wrapAliases));
939
+ this.applyRegistration(prepared, sourceUri);
940
+ }
941
+ /**
942
+ * Parsing half of {@link registerAnnotationsFromSource}: extract method /
943
+ * constraint / data declarations and pre-expand sidecar-local aliases.
944
+ * Pure with respect to global state — the result can be cached per
945
+ * sidecar (see {@link registerSidecarMethods}) and re-applied cheaply.
946
+ */
947
+ prepareRegistration(source, wrapAliases) {
948
+ const { buildAnnotationMap, extractConstraintDirectives, extractDataDirectives } = require('../commentParser');
949
+ const { expandAliases, buildDeclaredTypeParamMap } = require('../infer/annotations');
950
+ const { wrapHmSource } = require('./files');
951
+ const { parseConstraintDirective } = require('../registries/constraintRegistry');
952
+ const wrapped = wrapAliases ? wrapHmSource(source) : source;
953
+ const annotations = buildAnnotationMap(wrapped);
954
+ const constraintDefs = [];
955
+ for (const directive of extractConstraintDirectives(wrapped)) {
956
+ const def = parseConstraintDirective(directive.text);
957
+ if (def) {
958
+ def.commentStart = directive.start;
959
+ def.commentEnd = directive.end;
960
+ constraintDefs.push(def);
961
+ }
962
+ }
963
+ const dataDecls = extractDataDirectives(wrapped);
964
+ const { aliases: sidecarAliases, aliasVars: sidecarAliasVars } = (0, files_1.parseHmTypeAliases)(source, { wrap: wrapAliases });
965
+ const declaredTypeParams = buildDeclaredTypeParamMap(annotations);
966
+ const methodAnns = [];
967
+ for (const [name, ann] of annotations) {
968
+ if (name.includes('#') || name.includes('.')) {
969
+ if (sidecarAliases.size > 0 && ann.scheme) {
970
+ ann.scheme = {
971
+ ...ann.scheme,
972
+ type: expandAliases(sidecarAliases, ann.scheme.type, undefined, sidecarAliasVars),
973
+ };
974
+ if (ann.receiver) {
975
+ ann.receiver = expandAliases(sidecarAliases, ann.receiver, undefined, sidecarAliasVars);
976
+ }
977
+ if (ann.methodType) {
978
+ ann.methodType = expandAliases(sidecarAliases, ann.methodType, undefined, sidecarAliasVars);
979
+ }
980
+ }
981
+ const typeName = name.includes('#') ? name.split('#')[0] : undefined;
982
+ methodAnns.push({ name, ann, typeParams: typeName ? declaredTypeParams.get(typeName) : undefined });
983
+ }
984
+ }
985
+ return { constraintDefs, dataDecls, methodAnns };
986
+ }
987
+ /**
988
+ * Registration half of {@link registerAnnotationsFromSource}: write a
989
+ * prepared payload into the global registries. Cheap (no parsing) —
990
+ * safe to re-run on every inference pass.
991
+ */
992
+ applyRegistration(prepared, sourceUri) {
993
+ const { registerAnnotationMethod } = require('../infer/annotations');
994
+ const { registerConstraint } = require('../registries/constraintRegistry');
995
+ const { registerDataType } = require('../registries/dataTypeRegistry');
996
+ for (const def of prepared.constraintDefs) {
997
+ def.uri = sourceUri;
998
+ registerConstraint(def);
999
+ }
1000
+ for (const decl of prepared.dataDecls) {
1001
+ registerDataType(decl);
1002
+ }
1003
+ for (const { name, ann, typeParams } of prepared.methodAnns) {
1004
+ registerAnnotationMethod(name, ann, typeParams);
1005
+ }
1006
+ }
1007
+ /**
1008
+ * Extract `Type#method` / `Type.method` annotations from the given `.hm`
1009
+ * sidecar and register them in the global method registry, so that
1010
+ * property access on the sidecar's types resolves them. Used for both
1011
+ * per-file and package-level sidecars. Idempotent (re-registration is
1012
+ * harmless — same factory wins).
1013
+ */
1014
+ registerSidecarMethods(sidecarPath) {
1015
+ const art = this.getSidecarArtifacts(sidecarPath);
1016
+ if (!art)
1017
+ return;
1018
+ if (art.registration === undefined) {
1019
+ art.registration = (0, sidecarPerf_1.timeSidecarStage)('register', () => this.prepareRegistration(art.source, /* wrapAliases */ true));
1020
+ }
1021
+ this.applyRegistration(art.registration, (0, url_1.pathToFileURL)(sidecarPath).href);
1022
+ }
1023
+ /**
1024
+ * Register `Type#method` / `Type.method` annotations and constraint /
1025
+ * data directives discovered inline in a package's JS source files.
1026
+ * Mirrors {@link registerSidecarMethods} but skips the `wrapHmSource`
1027
+ * step — the methodSource is already JavaScript with comment-embedded
1028
+ * annotations.
1029
+ */
1030
+ registerInlinePackageMethods(scan, targetUri) {
1031
+ if (!scan.methodSource)
1032
+ return;
1033
+ this.registerAnnotationsFromSource(scan.methodSource, targetUri, /* wrapAliases */ false);
1034
+ }
1035
+ /**
1036
+ * Read a `.hm` source as a map of raw signature texts (preferring an open
1037
+ * editor doc), used by hover/completion to surface the user's verbatim
1038
+ * annotation rather than a re-printed scheme.
1039
+ */
1040
+ readHmRawMap(filePath) {
1041
+ const art = this.getSidecarArtifacts(filePath);
1042
+ if (!art)
1043
+ return null;
1044
+ if (art.rawMap === undefined)
1045
+ art.rawMap = (0, files_1.parseHmSourceRaw)(art.source);
1046
+ return art.rawMap;
1047
+ }
1048
+ /**
1049
+ * Read a JS source file's leading-comment annotations as a map of
1050
+ * `name → raw signature text`. Used by {@link getImportedRawSignature}
1051
+ * to surface a user's verbatim `// name :: ...` comment when hovering
1052
+ * an imported binding whose providing module is a JS file (no `.hm`
1053
+ * sidecar present). Prefers an open editor doc; falls back to disk.
1054
+ */
1055
+ readJsRawAnnotationMap(filePath) {
1056
+ let source;
1057
+ try {
1058
+ const docUri = (0, url_1.pathToFileURL)(filePath).href;
1059
+ const doc = this.documents.get(docUri);
1060
+ source = doc ? doc.getText() : fs.readFileSync(filePath, 'utf-8');
1061
+ }
1062
+ catch {
1063
+ return null;
1064
+ }
1065
+ const out = new Map();
1066
+ for (const ann of (0, commentParser_1.extractAnnotations)(source)) {
1067
+ if (!ann.name || !ann.raw)
1068
+ continue;
1069
+ const prev = out.get(ann.name);
1070
+ // Preserve overloads: when the same name has multiple `name :: ...`
1071
+ // comment annotations, join them with `\n${name} :: ` so hover renders
1072
+ // every overload (mirrors `parseHmSourceRaw` for `.hm` files).
1073
+ out.set(ann.name, prev ? `${prev}\n${ann.name} :: ${ann.raw}` : ann.raw);
1074
+ }
1075
+ return out;
1076
+ }
1077
+ /**
1078
+ * Look up the verbatim raw signature text (as written in a `.hm` file)
1079
+ * for `exportName` imported via `specifier` from `fromUri`. Mirrors the
1080
+ * lookup chain in `createImportResolver` but only consults `.hm`
1081
+ * sources — never inferred JS — because only `.hm` files have a raw
1082
+ * user-written signature to preserve.
1083
+ */
1084
+ getImportedRawSignature(specifier, exportName, fromUri) {
1085
+ // Bundled builtin typings — weakest layer, consulted when nothing
1086
+ // user-side or package-side yielded a raw signature.
1087
+ const builtinRaw = () => {
1088
+ const bp = (0, files_1.isBareSpecifier)(specifier) ? builtinHmPath((0, files_1.getBarePackageName)(specifier)) : null;
1089
+ if (!bp)
1090
+ return null;
1091
+ return this.readHmRawMap(bp)?.get(exportName) ?? null;
1092
+ };
1093
+ // Project overrides + conventional `<typesDir>/` stubs (subpath-aware)
1094
+ if (this.projectRoot && (0, files_1.isBareSpecifier)(specifier)) {
1095
+ const pkgName = (0, files_1.getBarePackageName)(specifier);
1096
+ const overrideRel = this.packageOverrides[pkgName];
1097
+ if (overrideRel) {
1098
+ const overridePath = path.resolve(this.projectRoot, overrideRel);
1099
+ const raws = this.readHmRawMap(overridePath);
1100
+ const raw = raws?.get(exportName);
1101
+ if (raw)
1102
+ return raw;
1103
+ }
1104
+ for (const rel of (0, files_1.conventionalStubRelPaths)(specifier)) {
1105
+ const conventional = path.join(this.projectRoot, this.typesDir, rel);
1106
+ try {
1107
+ if ((0, fsProbe_1.isFile)(conventional)) {
1108
+ const raws = this.readHmRawMap(conventional);
1109
+ const raw = raws?.get(exportName);
1110
+ if (raw)
1111
+ return raw;
1112
+ }
1113
+ }
1114
+ catch { /* not present */ }
1115
+ }
1116
+ }
1117
+ const targetUri = (0, files_1.resolveImportSpecifier)(specifier, fromUri);
1118
+ if (!targetUri)
1119
+ return builtinRaw();
1120
+ const targetPath = (0, url_1.fileURLToPath)(targetUri);
1121
+ if (isUnderNodeModules(targetPath)) {
1122
+ // Package's own `hinmil.sidecars` sidecars (later entries override earlier).
1123
+ // Walk in reverse so the last-declared sidecar's raw text wins.
1124
+ const sidecarPaths = (0, files_1.findHmSidecarPaths)(targetPath);
1125
+ for (let i = sidecarPaths.length - 1; i >= 0; i--) {
1126
+ const raws = this.readHmRawMap(sidecarPaths[i]);
1127
+ const raw = raws?.get(exportName);
1128
+ if (raw)
1129
+ return raw;
1130
+ }
1131
+ // `@hm/<pkg>` companion sidecar
1132
+ if ((0, files_1.isBareSpecifier)(specifier)) {
1133
+ const companionSpec = (0, files_1.hmCompanionPackageName)((0, files_1.getBarePackageName)(specifier));
1134
+ const companionUri = (0, files_1.resolveImportSpecifier)(companionSpec, fromUri);
1135
+ if (companionUri) {
1136
+ const companionPath = (0, url_1.fileURLToPath)(companionUri);
1137
+ const companionSidecars = (0, files_1.findHmSidecarPaths)(companionPath);
1138
+ for (let i = companionSidecars.length - 1; i >= 0; i--) {
1139
+ const raws = this.readHmRawMap(companionSidecars[i]);
1140
+ const raw = raws?.get(exportName);
1141
+ if (raw)
1142
+ return raw;
1143
+ }
1144
+ }
1145
+ }
1146
+ // Inline annotations (last fallback — sidecars win on conflict).
1147
+ const inlineScan = (0, files_1.collectInlinePackageAnnotations)(targetPath, this.logger);
1148
+ const inlineRaw = inlineScan?.inlineRawSignatures.get(exportName);
1149
+ if (inlineRaw)
1150
+ return inlineRaw;
1151
+ }
1152
+ // Project-local JS source: fall back to a leading `// name :: ...`
1153
+ // comment annotation in the providing module. This lets hover show
1154
+ // the user's verbatim signature for an imported binding even when
1155
+ // the target is a regular .js file (no .hm sidecar).
1156
+ if (!isUnderNodeModules(targetPath) && /\.(?:m|c)?jsx?$/i.test(targetPath)) {
1157
+ const jsRaws = this.readJsRawAnnotationMap(targetPath);
1158
+ const jsRaw = jsRaws?.get(exportName);
1159
+ if (jsRaw)
1160
+ return jsRaw;
1161
+ }
1162
+ return builtinRaw();
1163
+ }
1164
+ /**
1165
+ * Find every `.hm` source reachable from `fromUri` that declares a
1166
+ * type/constructor named `name`, returning the raw signature(s) and an
1167
+ * `origin` label. Used by hover to surface a definition for an
1168
+ * uppercase name appearing inside an annotation when the user has not
1169
+ * imported it locally (e.g. `Prop` from a project-globals or sidecar
1170
+ * file). Multiple entries indicate ambiguity; the consumer can
1171
+ * disambiguate via a `// ::prefer Name from <specifier>` directive.
1172
+ *
1173
+ * Sources searched (in order):
1174
+ * 1. Project globals file (e.g. `globals.hm`).
1175
+ * 2. Sidecars referenced by `// ::types` directives in the project
1176
+ * globals file (e.g. `// ::types query-builder` makes a query builder's sidecar
1177
+ * declarations globally visible).
1178
+ * 3. For every `import` in `source`:
1179
+ * a. Project override `<override>.hm` for the package.
1180
+ * b. Conventional `<typesDir>/<pkg>.hm` stub.
1181
+ * c. The package's own `hinmil.sidecars` sidecars.
1182
+ * d. A per-file `<targetPath>.hm` sidecar.
1183
+ * 4. Last-resort project-wide scan: any `.js`/`.hm` file under the
1184
+ * project root that declares the name as a top-level annotation.
1185
+ * This catches types like `RTask` that live in a sibling source
1186
+ * file but are not transitively imported from `fromUri`.
1187
+ */
1188
+ findTypeDefinitions(name, fromUri, source, globalsSource, globalsPath) {
1189
+ const results = [];
1190
+ const seenRaw = new Set();
1191
+ // Lazy require to avoid load-time cycles.
1192
+ const { extractAnnotations } = require('../commentParser');
1193
+ const { extractImportSpecifiers } = require('./files');
1194
+ const { wrapHmSource } = require('./files');
1195
+ const addFromText = (text, origin, sourcePath, isHm) => {
1196
+ // For .hm files we wrap the source so the JS comment-parser can read
1197
+ // it; the wrapper prepends `// ` to every non-comment line. Because
1198
+ // each non-comment line gains 3 characters, a uniform offset shift
1199
+ // (wrapped.length - text.length) cannot be used to translate offsets
1200
+ // back to the original file — the cumulative shift differs per line.
1201
+ // Instead, locate the declaration directly in the original `text` by
1202
+ // scanning for the matching `<name> ::` line.
1203
+ const wrapped = isHm ? wrapHmSource(text) : text;
1204
+ let raw = null;
1205
+ for (const ann of extractAnnotations(wrapped)) {
1206
+ if (ann.name === name && ann.raw && !ann.receiver) {
1207
+ raw = ann.raw;
1208
+ break;
1209
+ }
1210
+ }
1211
+ if (!raw)
1212
+ return;
1213
+ // Dedup on raw signature alone: two sidecar files containing the
1214
+ // bitwise-identical declaration represent the same definition (the
1215
+ // common case is an auto-generated mirror of a hand-written stub).
1216
+ if (seenRaw.has(raw))
1217
+ return;
1218
+ seenRaw.add(raw);
1219
+ // Locate `<name> ::` in the original source by scanning lines. This
1220
+ // gives an accurate range that points at the user's declaration line
1221
+ // (not at a preceding comment block, which is what extractAnnotations
1222
+ // returns when consecutive line-comments are grouped together).
1223
+ let commentStart = 0;
1224
+ let commentEnd = text.length;
1225
+ const declRe = new RegExp('^[\\s/*]*' + name.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\$&') + '\\s*::');
1226
+ let cursor = 0;
1227
+ for (const line of text.split('\n')) {
1228
+ if (declRe.test(line)) {
1229
+ commentStart = cursor;
1230
+ commentEnd = cursor + line.length;
1231
+ break;
1232
+ }
1233
+ cursor += line.length + 1;
1234
+ }
1235
+ results.push({ raw, origin, sourcePath, commentStart, commentEnd });
1236
+ };
1237
+ const readFileText = (filePath) => {
1238
+ const docUri = (0, url_1.pathToFileURL)(filePath).href;
1239
+ const doc = this.documents.get(docUri);
1240
+ if (doc)
1241
+ return doc.getText();
1242
+ try {
1243
+ return fs.readFileSync(filePath, 'utf-8');
1244
+ }
1245
+ catch {
1246
+ return null;
1247
+ }
1248
+ };
1249
+ // 1. Project globals
1250
+ if (globalsSource) {
1251
+ addFromText(globalsSource, '<globals>', globalsPath, true);
1252
+ }
1253
+ // 2. Sidecars referenced by `// ::types <specifier>` directives in
1254
+ // the project globals file. These declarations are visible to
1255
+ // every file via `engine.globalsSource`, so go-to-definition
1256
+ // should surface them just like the per-file directive case.
1257
+ for (const sidecarPath of this.collectGlobalDirectiveSidecarPaths()) {
1258
+ const text = readFileText(sidecarPath);
1259
+ if (text)
1260
+ addFromText(text, '<globals ::types>', sidecarPath, true);
1261
+ }
1262
+ // 3. Per-import sidecars + per-type-directive sidecars.
1263
+ // `// ::types <pkg>` directives are treated the same way as bare
1264
+ // imports here: project override (if any) + conventional
1265
+ // `<typesDir>/<pkg>.hm` + the package's own `hinmil.sidecars` sidecars
1266
+ // are all searched, so go-to-definition surfaces both the base
1267
+ // sidecar declaration and any project override.
1268
+ const { extractTypeDirectives } = require('../commentParser');
1269
+ // When `fromUri` is itself a `.hm` sidecar, the source has bare
1270
+ // directive lines (no leading `// `) — wrap it so the comment-based
1271
+ // directive/import extractors pick them up. JS sources are used
1272
+ // as-is.
1273
+ const fromIsHm = fromUri.endsWith('.hm');
1274
+ const sourceForExtraction = fromIsHm ? wrapHmSource(source) : source;
1275
+ const allSpecifiers = [
1276
+ ...extractImportSpecifiers(sourceForExtraction).values(),
1277
+ ...extractTypeDirectives(sourceForExtraction),
1278
+ ];
1279
+ // When `fromUri` itself IS a project override or conventional
1280
+ // `<typesDir>/<pkg>.hm` stub, that file has no `import`/`::types`
1281
+ // statements of its own — yet we still want references to peer
1282
+ // declarations in the *underlying* package sidecar (`Limit`,
1283
+ // `Offset`, `Selector`, …) to resolve. Synthesise the package
1284
+ // specifier from the file path so the loop below loads the same
1285
+ // sidecars an importing JS file would see.
1286
+ const implicit = this.implicitSpecifierFromOverrideUri(fromUri);
1287
+ if (implicit)
1288
+ allSpecifiers.push(implicit);
1289
+ const seenSpecifiers = new Set();
1290
+ for (const specifier of allSpecifiers) {
1291
+ if (seenSpecifiers.has(specifier))
1292
+ continue;
1293
+ seenSpecifiers.add(specifier);
1294
+ // 3a/3b. Overrides for bare package specifiers
1295
+ if (this.projectRoot && (0, files_1.isBareSpecifier)(specifier)) {
1296
+ const pkgName = (0, files_1.getBarePackageName)(specifier);
1297
+ const overrideRel = this.packageOverrides[pkgName];
1298
+ if (overrideRel) {
1299
+ const overridePath = path.resolve(this.projectRoot, overrideRel);
1300
+ const t = readFileText(overridePath);
1301
+ if (t)
1302
+ addFromText(t, `${pkgName} (override)`, overridePath, true);
1303
+ }
1304
+ const conventional = this.conventionalStubPath(specifier);
1305
+ const tConv = conventional ? readFileText(conventional) : null;
1306
+ if (conventional && tConv)
1307
+ addFromText(tConv, `${pkgName} (${this.typesDir})`, conventional, true);
1308
+ }
1309
+ // Bundled builtin typings — weakest layer (dedup on raw signature
1310
+ // keeps user-side duplicates first).
1311
+ if ((0, files_1.isBareSpecifier)(specifier)) {
1312
+ const pkgName = (0, files_1.getBarePackageName)(specifier);
1313
+ const builtinPath = builtinHmPath(pkgName);
1314
+ if (builtinPath) {
1315
+ const t = readFileText(builtinPath);
1316
+ if (t)
1317
+ addFromText(t, `${pkgName} (builtin)`, builtinPath, true);
1318
+ }
1319
+ }
1320
+ // 3c. Package sidecar(s) under node_modules + 3d. per-file sidecar
1321
+ const targetUri = (0, files_1.resolveImportSpecifier)(specifier, fromUri);
1322
+ if (!targetUri)
1323
+ continue;
1324
+ const targetPath = (0, url_1.fileURLToPath)(targetUri);
1325
+ for (const sp of (0, files_1.findHmSidecarPaths)(targetPath)) {
1326
+ const t = readFileText(sp);
1327
+ if (t)
1328
+ addFromText(t, specifier, sp, true);
1329
+ }
1330
+ const perFile = targetPath + '.hm';
1331
+ const tPerFile = readFileText(perFile);
1332
+ if (tPerFile)
1333
+ addFromText(tPerFile, specifier, perFile, true);
1334
+ }
1335
+ // NOTE: cross-file type definitions are only surfaced when they are
1336
+ // reachable via an explicit `import` / `require`, a `// ::types`
1337
+ // directive, the project globals file, or per-import sidecars (steps
1338
+ // 1–3 above). A project-wide scan that resolved ANY matching `Name ::`
1339
+ // declaration anywhere in the workspace was removed on purpose: it made
1340
+ // types globally available without import and produced ambiguous results
1341
+ // when several modules declared the same name (e.g. multiple `Pair`s).
1342
+ // 4. Own-package inline annotations (library-author mode) — restricted
1343
+ // to `.hm` sidecar files. A `.hm` sidecar that lives inside its own
1344
+ // package may reference inline `// Name :: …` annotations declared in
1345
+ // sibling JS files (the sidecar IS the package's opt-in type surface).
1346
+ // Regular JS sources do NOT get this fallback: they must `import`
1347
+ // a type to resolve it, so unimported names stay unresolved.
1348
+ if (results.length === 0 && fromUri.endsWith('.hm')) {
1349
+ try {
1350
+ const fromPath = (0, url_1.fileURLToPath)(fromUri);
1351
+ const pkgInfo = (0, files_1.findPackageJson)(fromPath);
1352
+ // Skip when the file is under node_modules — that's consumer view,
1353
+ // already covered by per-import sidecar/inline resolution above.
1354
+ if (pkgInfo && !/[\\/]node_modules[\\/]/.test(pkgInfo.pkgDir)) {
1355
+ const scan = (0, files_1.collectInlinePackageAnnotations)(fromPath, this.logger);
1356
+ const raw = scan?.inlineRawSignatures.get(name);
1357
+ if (scan && raw) {
1358
+ // Origin file is recorded during the BFS scan, so we can jump
1359
+ // straight to it instead of re-scanning every visited file.
1360
+ const sourcePath = scan.nameToSource.get(name) ?? null;
1361
+ const origin = sourcePath
1362
+ ? path.relative(pkgInfo.pkgDir, sourcePath)
1363
+ : '<own-package inline>';
1364
+ const text = sourcePath ? readFileText(sourcePath) : null;
1365
+ if (text)
1366
+ addFromText(text, origin, sourcePath, false);
1367
+ }
1368
+ }
1369
+ }
1370
+ catch { /* fromUri not a file URI or pkg lookup failed — ignore */ }
1371
+ }
1372
+ // 5. A built-in type of hinmil itself (`ReactElement`, the type of every
1373
+ // JSX expression) has no `Name ::` declaration anywhere; a bundled
1374
+ // stub documents it with an anchor line `// ::builtin Name`. Found
1375
+ // without an import (JSX needs no `import React`).
1376
+ if (results.length === 0) {
1377
+ const anchor = findBuiltinTypeAnchor(name);
1378
+ if (anchor)
1379
+ results.push({ raw: name, origin: '<builtin>', ...anchor });
1380
+ }
1381
+ return results;
1382
+ }
1383
+ /** Create an ImportResolver for a given file URI. */
1384
+ createImportResolver(fromUri) {
1385
+ return (specifier) => {
1386
+ // ── Step 1: project-level `.hm` overrides + conventional hm-types/ ──
1387
+ // These let a user provide types for an npm package without modifying
1388
+ // the package itself, mirroring `@types/*` packages from TypeScript.
1389
+ // Names declared in the override take precedence; names absent from
1390
+ // the override fall back to the package's own `.hm` sidecar (if any),
1391
+ // and only if neither has them does a diagnostic surface.
1392
+ // The path to the project-level override sidecar (if any) — we
1393
+ // register its methods AFTER the package's own sidecar methods so
1394
+ // that override entries win for `Type#method` / `Type.method`
1395
+ // annotations. Method registration is last-write-wins, so the
1396
+ // package's `Table#update :: Table p ~> [a] -> QueryTag b` would
1397
+ // otherwise overwrite an override's `Table#update :: Table ~> [Selector] -> QueryTag b`.
1398
+ let overrideExports = null;
1399
+ let overrideSidecarPath = null;
1400
+ // Bundled builtin typings (react, react-dom, …) — the WEAKEST layer.
1401
+ // Loaded and method-registered FIRST so every user-side layer that
1402
+ // follows (override / hm-types / package sidecars) wins on collision.
1403
+ let builtinExports = null;
1404
+ if ((0, files_1.isBareSpecifier)(specifier)) {
1405
+ const builtinPath = builtinHmPath((0, files_1.getBarePackageName)(specifier));
1406
+ if (builtinPath) {
1407
+ builtinExports = this.loadHmFileLive(builtinPath);
1408
+ if (builtinExports) {
1409
+ this.registerSidecarMethods(builtinPath);
1410
+ this.trackDependency(fromUri, (0, url_1.pathToFileURL)(builtinPath).href);
1411
+ }
1412
+ }
1413
+ }
1414
+ const finish = (m) => builtinExports ? (0, types_1.markOpenWorldExports)(m) : m;
1415
+ if (this.projectRoot && (0, files_1.isBareSpecifier)(specifier)) {
1416
+ const pkgName = (0, files_1.getBarePackageName)(specifier);
1417
+ const overrideRel = this.packageOverrides[pkgName];
1418
+ if (overrideRel) {
1419
+ const overridePath = path.resolve(this.projectRoot, overrideRel);
1420
+ const exports = this.loadHmFileLive(overridePath);
1421
+ if (exports) {
1422
+ this.registerSidecarMethods(overridePath);
1423
+ overrideExports = exports;
1424
+ overrideSidecarPath = overridePath;
1425
+ // Track the override sidecar as a dependency of the consumer
1426
+ // so that editing it triggers selective revalidation of just
1427
+ // the importers (instead of falling back to all open docs).
1428
+ this.trackDependency(fromUri, (0, url_1.pathToFileURL)(overridePath).href);
1429
+ }
1430
+ else {
1431
+ this.logger.warn(`[hinmil] hm override for '${pkgName}' not found at '${overridePath}'`);
1432
+ }
1433
+ }
1434
+ if (!overrideExports) {
1435
+ const conventional = this.conventionalStubPath(specifier);
1436
+ if (conventional) {
1437
+ const exports = this.loadHmFileLive(conventional);
1438
+ if (exports) {
1439
+ this.registerSidecarMethods(conventional);
1440
+ overrideExports = exports;
1441
+ overrideSidecarPath = conventional;
1442
+ // Same as above — conventional `hm-types/` stubs (package-level
1443
+ // or subpath) must register a reverse-dep so the dep-graph is
1444
+ // not empty when the sidecar changes.
1445
+ this.trackDependency(fromUri, (0, url_1.pathToFileURL)(conventional).href);
1446
+ }
1447
+ }
1448
+ }
1449
+ }
1450
+ // Fold the builtin layer underneath the USER layer only (user wins
1451
+ // per export name). `userPlusBuiltin` serves the paths where no
1452
+ // package-own sidecar participates; the node_modules paths below
1453
+ // fold builtin under the package sidecar instead, preserving the
1454
+ // full precedence chain: user > package sidecar > builtin.
1455
+ const userPlusBuiltin = builtinExports
1456
+ ? mergeOverride(overrideExports, builtinExports)
1457
+ : overrideExports;
1458
+ // Bundler-managed asset (`./hero.png`, `./App.css`): bind imported
1459
+ // names to `Any` instead of "Cannot resolve module" + unbound vars.
1460
+ // Checked before path resolution — the '' entry in jsExtensions
1461
+ // would otherwise resolve the asset as an exact file and route it
1462
+ // into (silently failing) module inference.
1463
+ if ((0, files_1.isAssetImportSpecifier)(specifier, fromUri))
1464
+ return types_1.UNTYPED_MODULE;
1465
+ const targetUri = (0, files_1.resolveImportSpecifier)(specifier, fromUri);
1466
+ if (!targetUri) {
1467
+ // Only the override/builtin layer is available — return it as-is.
1468
+ // Names absent from a plain override produce a "not exported"
1469
+ // diagnostic; with a builtin layer the map is open-world and
1470
+ // unknown names bind to `Any` instead.
1471
+ return userPlusBuiltin ? finish(userPlusBuiltin) : null;
1472
+ }
1473
+ // For npm packages (anything resolved into node_modules) we do NOT
1474
+ // run inference on the compiled source — the signal-to-noise is too
1475
+ // poor (TypeScript-emitted CJS, no generics, internal diagnostics).
1476
+ // Lookup chain:
1477
+ // 2. Package's own `hinmil.sidecars` field in package.json
1478
+ // 3. `@hm/<derived>` companion package (à la `@types/*`)
1479
+ // 4. UNTYPED_MODULE — bind names to fresh type variables
1480
+ const targetPath = (0, url_1.fileURLToPath)(targetUri);
1481
+ if (isUnderNodeModules(targetPath)) {
1482
+ // Inline-annotated package WITHOUT `.hm` sidecars (e.g. a curried FP library, whose
1483
+ // build keeps every `// name :: Type` comment): the author opted
1484
+ // into hinmil in the JS itself, so infer the target module exactly
1485
+ // like local source. That resolves the real CommonJS export shape
1486
+ // per module — `module.exports = _RTask` (default + dotted statics),
1487
+ // re-export barrels `module.exports = { RTask: require ("./RTask") }`
1488
+ // — for every import form (default, named, subpath with or without
1489
+ // `/index` / `.js`, require), instead of the name-based inline scan
1490
+ // which cannot see export structure. Packages that ship sidecars
1491
+ // keep the sidecar path below (sidecars are authoritative there).
1492
+ if ((0, files_1.findHmSidecarPaths)(targetPath).length === 0
1493
+ && (0, files_1.isInlineAnnotatedPackageModule)(targetPath)) {
1494
+ this.recordPackageGlobals(fromUri, targetPath);
1495
+ this.trackDependency(fromUri, targetUri);
1496
+ const inferred = this.inferFileAndCacheExports(targetUri);
1497
+ if (inferred) {
1498
+ if (overrideSidecarPath)
1499
+ this.registerSidecarMethods(overrideSidecarPath);
1500
+ return finish(mergeOverride(overrideExports, mergeMaps(builtinExports, inferred)));
1501
+ }
1502
+ }
1503
+ // Inline annotations live directly in the JS source — collect
1504
+ // them BEFORE sidecars so sidecar entries win on name collision
1505
+ // (`inline < sidecar < companion < override`). Register inline
1506
+ // methods FIRST so that any same-named `Type#method` declared in
1507
+ // a sidecar overrides the inline registration.
1508
+ const inlineScan = (0, files_1.collectInlinePackageAnnotations)(targetPath, this.logger);
1509
+ if (inlineScan) {
1510
+ this.registerInlinePackageMethods(inlineScan, targetUri);
1511
+ for (const f of inlineScan.visitedFiles) {
1512
+ this.trackDependency(fromUri, (0, url_1.pathToFileURL)(f).href);
1513
+ }
1514
+ }
1515
+ // Track package-level globals so the consumer's engine can pull
1516
+ // them into its globals env.
1517
+ this.recordPackageGlobals(fromUri, targetPath);
1518
+ const sidecarExports = this.loadHmSidecarLive(targetPath);
1519
+ if (sidecarExports || inlineScan) {
1520
+ if (sidecarExports) {
1521
+ for (const sp of (0, files_1.findHmSidecarPaths)(targetPath)) {
1522
+ this.registerSidecarMethods(sp);
1523
+ this.trackDependency(fromUri, (0, url_1.pathToFileURL)(sp).href);
1524
+ }
1525
+ }
1526
+ // Re-register override methods last so they win over the
1527
+ // package's same-named `Type#method` annotations.
1528
+ if (overrideSidecarPath)
1529
+ this.registerSidecarMethods(overrideSidecarPath);
1530
+ this.trackDependency(fromUri, targetUri);
1531
+ // builtin < inline < sidecar < user override.
1532
+ const merged = mergeMaps(builtinExports, mergeMaps(inlineScan?.exports ?? null, sidecarExports));
1533
+ return finish(supplementWithRuntimeExports(mergeOverride(overrideExports, merged), targetPath, this.logger));
1534
+ }
1535
+ if ((0, files_1.isBareSpecifier)(specifier)) {
1536
+ const companionSpec = (0, files_1.hmCompanionPackageName)((0, files_1.getBarePackageName)(specifier));
1537
+ const companionUri = (0, files_1.resolveImportSpecifier)(companionSpec, fromUri);
1538
+ if (companionUri) {
1539
+ const companionPath = (0, url_1.fileURLToPath)(companionUri);
1540
+ const companionSidecar = this.loadHmSidecarLive(companionPath);
1541
+ if (companionSidecar) {
1542
+ for (const sp of (0, files_1.findHmSidecarPaths)(companionPath)) {
1543
+ this.registerSidecarMethods(sp);
1544
+ this.trackDependency(fromUri, (0, url_1.pathToFileURL)(sp).href);
1545
+ }
1546
+ if (overrideSidecarPath)
1547
+ this.registerSidecarMethods(overrideSidecarPath);
1548
+ this.trackDependency(fromUri, companionUri);
1549
+ return finish(supplementWithRuntimeExports(mergeOverride(overrideExports, mergeMaps(builtinExports, companionSidecar)), targetPath, this.logger));
1550
+ }
1551
+ }
1552
+ }
1553
+ // No package-level sidecar at all. If the user supplied an
1554
+ // override, supplement it with `Any`-typed entries for every
1555
+ // runtime-exported name that the override does not cover. `Any`
1556
+ // is opaque under unification, so missing names remain usable
1557
+ // without producing a hallucinated signature from usage — and
1558
+ // names truly absent from the JS module still surface a
1559
+ // "not exported" diagnostic. With no override at all, fall back
1560
+ // to UNTYPED_MODULE which binds whole-module imports to `Any`.
1561
+ if (userPlusBuiltin) {
1562
+ return finish(supplementWithRuntimeExports(userPlusBuiltin, targetPath, this.logger));
1563
+ }
1564
+ return types_1.UNTYPED_MODULE;
1565
+ }
1566
+ this.trackDependency(fromUri, targetUri);
1567
+ const inferred = this.inferFileAndCacheExports(targetUri);
1568
+ // Per-file `.hm` sidecar: if `<targetPath>.hm` exists next to the
1569
+ // imported source file, merge its declarations on top of inferred
1570
+ // exports. Sidecar names override inferred ones (e.g. an
1571
+ // auto-generated `tables :: { ... }` shadows a fresh-tvar inference).
1572
+ // Method/static annotations (`Type#m`, `Type.m`) inside the sidecar
1573
+ // are also registered into the global method registry so that
1574
+ // property access on the per-file sidecar's types resolves them.
1575
+ const perFileSidecar = targetPath + '.hm';
1576
+ try {
1577
+ if ((0, fsProbe_1.isFile)(perFileSidecar)) {
1578
+ const sidecarExports = this.loadHmFileLive(perFileSidecar);
1579
+ this.registerSidecarMethods(perFileSidecar);
1580
+ if (sidecarExports && sidecarExports.size > 0) {
1581
+ const merged = new Map(inferred ?? new Map());
1582
+ for (const [name, scheme] of sidecarExports)
1583
+ merged.set(name, scheme);
1584
+ this.trackDependency(fromUri, (0, url_1.pathToFileURL)(perFileSidecar).href);
1585
+ return merged;
1586
+ }
1587
+ }
1588
+ }
1589
+ catch { /* no per-file sidecar */ }
1590
+ return inferred;
1591
+ };
1592
+ }
1593
+ /**
1594
+ * Create a TypeDirectiveResolver for a given file URI.
1595
+ * Reads the target file's source code so the inference engine can
1596
+ * extract and register method annotations from it.
1597
+ *
1598
+ * For bare package specifiers (e.g. `// ::types query-builder`) this loads
1599
+ * EVERY `.hm` sidecar declared in the package's `package.json#hinmil.sidecars`
1600
+ * (which may be an array), then merges the project-level
1601
+ * `hinmil.overrides.<pkg>` file on top so user overrides win on name
1602
+ * collision. All sources are wrapped and concatenated into a single
1603
+ * string the inference engine can consume.
1604
+ */
1605
+ createTypeDirectiveResolver(fromUri) {
1606
+ return (specifier) => {
1607
+ const { wrapHmSource } = require('./files');
1608
+ const readFile = (filePath) => {
1609
+ const fileUri = (0, url_1.pathToFileURL)(filePath).href;
1610
+ this.trackDependency(fromUri, fileUri);
1611
+ const doc = this.documents.get(fileUri);
1612
+ if (doc)
1613
+ return doc.getText();
1614
+ try {
1615
+ return fs.readFileSync(filePath, 'utf-8');
1616
+ }
1617
+ catch (e) {
1618
+ const msg = e instanceof Error ? e.message : String(e);
1619
+ this.logger.warn(`[hinmil] Failed to read type directive '${filePath}': ${msg}`);
1620
+ return null;
1621
+ }
1622
+ };
1623
+ // Bare package specifier — collect all sidecars + project override.
1624
+ // Order: package's own `hinmil.sidecars` (in declared order) first, then the
1625
+ // override last so its declarations win on name collision via the
1626
+ // overload-merge logic in `buildAnnotationMap`.
1627
+ if ((0, files_1.isBareSpecifier)(specifier)) {
1628
+ const sidecarPaths = [];
1629
+ // Bundled builtin typings first — weakest layer, so every later
1630
+ // entry (package sidecars, project override) wins on collision
1631
+ // via the overload-merge logic in `buildAnnotationMap`.
1632
+ const builtinPath = builtinHmPath((0, files_1.getBarePackageName)(specifier));
1633
+ if (builtinPath)
1634
+ sidecarPaths.push(builtinPath);
1635
+ const entryPath = (0, files_1.resolveTypeDirectiveSpecifier)(specifier, fromUri);
1636
+ if (entryPath) {
1637
+ for (const p of (0, files_1.findHmSidecarPaths)(entryPath))
1638
+ sidecarPaths.push(p);
1639
+ }
1640
+ let overridePath = null;
1641
+ if (this.projectRoot) {
1642
+ const pkgName = (0, files_1.getBarePackageName)(specifier);
1643
+ const overrideRel = this.packageOverrides[pkgName];
1644
+ if (overrideRel) {
1645
+ const candidate = path.resolve(this.projectRoot, overrideRel);
1646
+ try {
1647
+ if ((0, fsProbe_1.isFile)(candidate))
1648
+ overridePath = candidate;
1649
+ }
1650
+ catch { /* missing override file */ }
1651
+ }
1652
+ }
1653
+ if (overridePath)
1654
+ sidecarPaths.push(overridePath);
1655
+ if (sidecarPaths.length === 0) {
1656
+ // No `.hm` sources for this package — fall through to the
1657
+ // legacy single-file path below (which may resolve a JS entry
1658
+ // and produce no annotations, but keeps backwards-compat).
1659
+ }
1660
+ else {
1661
+ const parts = [];
1662
+ for (const p of sidecarPaths) {
1663
+ const part = (0, sidecarPerf_1.timeSidecarStage)('directive', () => {
1664
+ if (!p.endsWith('.hm'))
1665
+ return readFile(p);
1666
+ // `.hm` file: serve the wrapped form from the artifact cache
1667
+ // (wrapping a 5000-line generated sidecar per resolution is
1668
+ // measurable). Dependency tracking mirrors `readFile`.
1669
+ const art = this.getSidecarArtifacts(p);
1670
+ if (!art) {
1671
+ readFile(p);
1672
+ return null;
1673
+ } // unreadable — warn via readFile
1674
+ this.trackDependency(fromUri, (0, url_1.pathToFileURL)(p).href);
1675
+ if (art.wrapped === undefined)
1676
+ art.wrapped = wrapHmSource(art.source);
1677
+ return art.wrapped;
1678
+ });
1679
+ if (part != null)
1680
+ parts.push(part);
1681
+ }
1682
+ return parts.length > 0 ? parts.join('\n' + commentParser_1.TYPE_DIRECTIVE_PART_BOUNDARY + '\n') : null;
1683
+ }
1684
+ }
1685
+ // Relative / absolute path specifier (or bare specifier with no
1686
+ // sidecars) — read the single resolved file.
1687
+ const filePath = (0, files_1.resolveTypeDirectiveSpecifier)(specifier, fromUri);
1688
+ if (!filePath)
1689
+ return null;
1690
+ if (filePath.endsWith('.hm')) {
1691
+ const art = this.getSidecarArtifacts(filePath);
1692
+ if (!art) {
1693
+ readFile(filePath);
1694
+ return null;
1695
+ } // unreadable — warn via readFile
1696
+ this.trackDependency(fromUri, (0, url_1.pathToFileURL)(filePath).href);
1697
+ if (art.wrapped === undefined)
1698
+ art.wrapped = wrapHmSource(art.source);
1699
+ return art.wrapped;
1700
+ }
1701
+ return readFile(filePath);
1702
+ };
1703
+ }
1704
+ /**
1705
+ * Create an `ImportTypeAliasResolver` for a given file URI. Mirrors
1706
+ * `createImportResolver` but returns just the type aliases (e.g.
1707
+ * `Selector :: (String | Prop a | …)`) declared in the resolved
1708
+ * `.hm` sidecar / project override. Aliases are needed by the
1709
+ * importing engine so that bare uppercase type names appearing inside
1710
+ * imported schemes get expanded to their full body at unification.
1711
+ *
1712
+ * Lookup chain mirrors `createImportResolver`: project-level override
1713
+ * (or conventional `hm-types/<pkg>.hm`), then the package's own sidecar.
1714
+ * Override aliases win on name collision with the sidecar. Returns
1715
+ * `null` when neither source exists.
1716
+ */
1717
+ createImportTypeAliasResolver(fromUri) {
1718
+ return (specifier) => this.cachedImportTypeAliases(specifier, fromUri);
1719
+ }
1720
+ /**
1721
+ * Memoised {@link resolveImportTypeAliases}. Also used for the nested
1722
+ * imports of an imported JS module, so overlapping closures (every FP-library
1723
+ * module imports `../RTask`, `../more/curry`, …) are walked once. A cycle
1724
+ * sees `null` for the module still being resolved (its names are merged
1725
+ * by the outer call).
1726
+ */
1727
+ cachedImportTypeAliases(specifier, fromUri) {
1728
+ const rootUri = (0, files_1.resolveImportSpecifier)(specifier, fromUri);
1729
+ const cacheKey = rootUri ? ((0, files_1.isBareSpecifier)(specifier) ? 'b|' : 'r|') + rootUri : null;
1730
+ if (cacheKey) {
1731
+ const hit = this.importTypeAliasCache.get(cacheKey);
1732
+ if (hit !== undefined)
1733
+ return hit;
1734
+ this.importTypeAliasCache.set(cacheKey, null);
1735
+ }
1736
+ const result = this.resolveImportTypeAliases(specifier, fromUri);
1737
+ if (cacheKey)
1738
+ this.importTypeAliasCache.set(cacheKey, result);
1739
+ return result;
1740
+ }
1741
+ /** Uncached body of {@link createImportTypeAliasResolver}. */
1742
+ resolveImportTypeAliases(specifier, fromUri) {
1743
+ {
1744
+ const aliases = new Map();
1745
+ const aliasVars = new Map();
1746
+ const constructors = new Map();
1747
+ const instanceCallables = new Map();
1748
+ const aliasExtensions = [];
1749
+ // Dedup key for `::extend` directives — `(name, raw)`. Multiple
1750
+ // sidecars (or transitive walks) frequently emit byte-identical
1751
+ // directives; without this guard the extension list grows linearly
1752
+ // with the number of sources and `applyAliasExtensions` ends up
1753
+ // appending the same branches over and over, ballooning the alias
1754
+ // union (observed: 7× duplication of every relation pair in query-builder
1755
+ // selectors, driving hover/diagnostic latency).
1756
+ const seenExtensionKeys = new Set();
1757
+ let found = false;
1758
+ // Cycle / fan-out guard for transitive walks through project files.
1759
+ // We follow imports of imported project files so that aliases declared
1760
+ // in a deeply-imported package's sidecar (e.g. a query builder's `Tables`) are
1761
+ // accessible to a consumer that only imports them indirectly through
1762
+ // a project module like `db.js`. Bare-package specifiers are not
1763
+ // walked transitively — we only inspect their direct sidecars.
1764
+ const visited = new Set();
1765
+ const MAX_TRANSITIVE_DEPTH = 8;
1766
+ // JS modules whose own type names were already merged (see
1767
+ // `mergeJsModuleTypes`); separate from `visited`, which guards the
1768
+ // sidecar walk.
1769
+ const jsVisited = new Set();
1770
+ const merge = (filePath, asOverride) => {
1771
+ const art = this.getSidecarArtifacts(filePath);
1772
+ if (!art)
1773
+ return;
1774
+ if (art.aliasData === undefined) {
1775
+ art.aliasData = (0, sidecarPerf_1.timeSidecarStage)('alias', () => (0, files_1.parseHmTypeAliases)(art.source));
1776
+ }
1777
+ mergeParsed(art.aliasData, asOverride);
1778
+ };
1779
+ const mergeParsed = (parsed, asOverride) => {
1780
+ if (parsed.aliases.size === 0
1781
+ && parsed.constructors.size === 0
1782
+ && parsed.instanceCallables.size === 0
1783
+ && parsed.aliasExtensions.length === 0)
1784
+ return;
1785
+ found = true;
1786
+ for (const [name, type] of parsed.aliases) {
1787
+ // Override entries always win; sidecar entries fill in only what
1788
+ // the override didn't already provide.
1789
+ if (asOverride || !aliases.has(name))
1790
+ aliases.set(name, type);
1791
+ }
1792
+ for (const [name, vars] of parsed.aliasVars) {
1793
+ if (asOverride || !aliasVars.has(name))
1794
+ aliasVars.set(name, vars);
1795
+ }
1796
+ for (const [name, scheme] of parsed.constructors) {
1797
+ if (asOverride || !constructors.has(name))
1798
+ constructors.set(name, scheme);
1799
+ }
1800
+ for (const [name, schemes] of parsed.instanceCallables) {
1801
+ if (asOverride || !instanceCallables.has(name)) {
1802
+ instanceCallables.set(name, [...schemes]);
1803
+ }
1804
+ }
1805
+ // Extensions stack additively across all sources; ordering is
1806
+ // preserved so override extensions appear after the sidecar's
1807
+ // own (if any). Application happens once, after all merging.
1808
+ // Dedupe identical directives (same target name + same raw RHS)
1809
+ // so multiple sidecars or transitive walks don't push the same
1810
+ // branches multiple times into `applyAliasExtensions`.
1811
+ for (const ext of parsed.aliasExtensions) {
1812
+ const key = `${ext.name}\u0000${ext.raw}`;
1813
+ if (seenExtensionKeys.has(key))
1814
+ continue;
1815
+ seenExtensionKeys.add(key);
1816
+ aliasExtensions.push(ext);
1817
+ }
1818
+ };
1819
+ // Type names visible in an imported JS module: its standalone
1820
+ // `// Name :: …` aliases plus, recursively, everything its own
1821
+ // `// ::types …` directives and imports bring in. A module that names types from
1822
+ // another module in its signatures (FP-library `express/post` →
1823
+ // `::types ./Component`) thereby re-exports those type names, so a
1824
+ // consumer that imports `post` can write `ExpressApp`/`RouteFn` in
1825
+ // its own annotations without repeating the `::types` line.
1826
+ const mergeJsModuleTypes = (targetPath, targetUri, depth) => {
1827
+ if (!/\.(?:[cm]?js|jsx|[cm]?ts|tsx)$/.test(targetPath))
1828
+ return;
1829
+ if (jsVisited.has(targetUri))
1830
+ return;
1831
+ jsVisited.add(targetUri);
1832
+ const art = this.getSidecarArtifacts(targetPath);
1833
+ if (!art)
1834
+ return;
1835
+ if (art.jsAliasData === undefined) {
1836
+ art.jsAliasData = (0, sidecarPerf_1.timeSidecarStage)('alias', () => (0, files_1.parseJsTypeAliases)(art.source));
1837
+ }
1838
+ mergeParsed(art.jsAliasData, false);
1839
+ if (art.typeDirectives === undefined) {
1840
+ art.typeDirectives = art.source.includes('::types') ? (0, commentParser_1.extractTypeDirectives)(art.source) : [];
1841
+ }
1842
+ // Both edge kinds reuse the memoised closure of their target; a
1843
+ // `::types` specifier that only resolves as a package self-reference
1844
+ // (no import target) is walked directly.
1845
+ const mergeEdge = (spec) => {
1846
+ if (!(0, files_1.resolveImportSpecifier)(spec, targetUri)) {
1847
+ // A relative `::types ./money` that only exists as `money.hm`
1848
+ // (the extensionless `.hm` fallback of `::types`): merge that
1849
+ // file's types like any other target of the closure.
1850
+ if (spec.startsWith('.')) {
1851
+ const hmPath = (0, files_1.resolveTypeDirectiveSpecifier)(spec, targetUri);
1852
+ if (hmPath && hmPath.endsWith('.hm')) {
1853
+ merge(hmPath, false);
1854
+ return;
1855
+ }
1856
+ }
1857
+ walk(spec, targetUri, depth + 1, true);
1858
+ return;
1859
+ }
1860
+ const sub = this.cachedImportTypeAliases(spec, targetUri);
1861
+ if (sub) {
1862
+ mergeParsed({
1863
+ aliases: sub.aliases,
1864
+ aliasVars: sub.aliasVars,
1865
+ constructors: sub.constructors ?? new Map(),
1866
+ instanceCallables: sub.instanceCallables ?? new Map(),
1867
+ aliasExtensions: [...(sub.aliasExtensions ?? [])],
1868
+ }, false);
1869
+ }
1870
+ };
1871
+ for (const directive of art.typeDirectives)
1872
+ mergeEdge(directive);
1873
+ // The module's own imports: a type name it uses in a signature may
1874
+ // come from a module it imports (FP-library `Result/parseReq` names
1875
+ // `Errors`, declared in `./Schema`, which it requires).
1876
+ if (art.importSpecifiers === undefined) {
1877
+ art.importSpecifiers = (0, commentParser_1.extractImportModuleSpecifiers)(art.source);
1878
+ }
1879
+ for (const nested of art.importSpecifiers)
1880
+ mergeEdge(nested);
1881
+ };
1882
+ // Walk a single specifier from a given file. Collects sidecars and
1883
+ // overrides for the immediate target; then, if the target resolves
1884
+ // to a project source file, recurses into THAT file's import
1885
+ // specifiers so transitively-reachable aliases are merged in too.
1886
+ // `typeNames`: also merge the JS target's type names (see
1887
+ // `mergeJsModuleTypes`): its own aliases, its `::types` closure and,
1888
+ // recursively, those of its imports (bounded by MAX_TRANSITIVE_DEPTH).
1889
+ // First wins on a name collision, so nearer modules take precedence
1890
+ // along a branch; local declarations always win in the consumer.
1891
+ const walk = (spec, originUri, depth, typeNames) => {
1892
+ if (depth > MAX_TRANSITIVE_DEPTH)
1893
+ return;
1894
+ // Override (or hm-types/ convention, subpath-aware) for bare specifiers.
1895
+ if (this.projectRoot && (0, files_1.isBareSpecifier)(spec)) {
1896
+ const pkgName = (0, files_1.getBarePackageName)(spec);
1897
+ const overrideRel = this.packageOverrides[pkgName];
1898
+ let overridePath = null;
1899
+ if (overrideRel) {
1900
+ overridePath = path.resolve(this.projectRoot, overrideRel);
1901
+ }
1902
+ else {
1903
+ overridePath = this.conventionalStubPath(spec);
1904
+ }
1905
+ if (overridePath) {
1906
+ try {
1907
+ if ((0, fsProbe_1.isFile)(overridePath))
1908
+ merge(overridePath, true);
1909
+ }
1910
+ catch { /* ignore */ }
1911
+ }
1912
+ }
1913
+ // Package sidecar(s) (npm) or per-file sidecar (project source).
1914
+ let targetUri = (0, files_1.resolveImportSpecifier)(spec, originUri);
1915
+ if (!targetUri && typeNames) {
1916
+ // `::types` specifiers also resolve to a package's own sidecar
1917
+ // (package self-reference), like the type-directive resolver.
1918
+ const directivePath = (0, files_1.resolveTypeDirectiveSpecifier)(spec, originUri);
1919
+ if (directivePath)
1920
+ targetUri = (0, url_1.pathToFileURL)(directivePath).href;
1921
+ }
1922
+ if (!targetUri)
1923
+ return;
1924
+ const targetPath = (0, url_1.fileURLToPath)(targetUri);
1925
+ if (typeNames)
1926
+ mergeJsModuleTypes(targetPath, targetUri, depth);
1927
+ if (visited.has(targetUri))
1928
+ return;
1929
+ visited.add(targetUri);
1930
+ const sidecarPaths = (0, files_1.findHmSidecarPaths)(targetPath);
1931
+ // Within a single package's sidecar list, later entries override
1932
+ // earlier ones (e.g. an auto-generated introspect sidecar refines
1933
+ // the hand-written base sidecar). The first sidecar still respects
1934
+ // any project-level override placed before this loop.
1935
+ for (let i = 0; i < sidecarPaths.length; i++) {
1936
+ const sidecarPath = sidecarPaths[i];
1937
+ try {
1938
+ if ((0, fsProbe_1.isFile)(sidecarPath))
1939
+ merge(sidecarPath, i > 0);
1940
+ }
1941
+ catch { /* ignore */ }
1942
+ }
1943
+ // Companion @hm/<pkg> for bare specifiers without their own sidecar.
1944
+ if (sidecarPaths.length === 0 && (0, files_1.isBareSpecifier)(spec)) {
1945
+ const companionSpec = (0, files_1.hmCompanionPackageName)((0, files_1.getBarePackageName)(spec));
1946
+ const companionUri = (0, files_1.resolveImportSpecifier)(companionSpec, originUri);
1947
+ if (companionUri) {
1948
+ const companionPath = (0, url_1.fileURLToPath)(companionUri);
1949
+ const companionSidecars = (0, files_1.findHmSidecarPaths)(companionPath);
1950
+ for (let i = 0; i < companionSidecars.length; i++) {
1951
+ const companionSidecar = companionSidecars[i];
1952
+ try {
1953
+ if ((0, fsProbe_1.isFile)(companionSidecar))
1954
+ merge(companionSidecar, i > 0);
1955
+ }
1956
+ catch { /* ignore */ }
1957
+ }
1958
+ }
1959
+ }
1960
+ // Per-file sidecar for project sources: <target>.hm.
1961
+ const perFileSidecar = targetPath + '.hm';
1962
+ try {
1963
+ if ((0, fsProbe_1.isFile)(perFileSidecar))
1964
+ merge(perFileSidecar, false);
1965
+ }
1966
+ catch { /* no per-file sidecar */ }
1967
+ // Transitive descent: only into project source files (relative
1968
+ // specifiers that resolve to a JS/TS file inside the workspace).
1969
+ // Never recurse through bare-package specifiers — their alias
1970
+ // surface is fully determined by their own sidecar(s) above.
1971
+ if ((0, files_1.isBareSpecifier)(spec))
1972
+ return;
1973
+ let nestedSource;
1974
+ try {
1975
+ const doc = this.documents.get(targetUri);
1976
+ nestedSource = doc ? doc.getText() : fs.readFileSync(targetPath, 'utf-8');
1977
+ }
1978
+ catch {
1979
+ return;
1980
+ }
1981
+ for (const nestedSpec of (0, commentParser_1.extractImportModuleSpecifiers)(nestedSource)) {
1982
+ walk(nestedSpec, targetUri, depth + 1, false);
1983
+ }
1984
+ };
1985
+ walk(specifier, fromUri, 0, true);
1986
+ if (!found)
1987
+ return null;
1988
+ return { aliases, aliasVars, constructors, instanceCallables, aliasExtensions };
1989
+ }
1990
+ }
1991
+ }
1992
+ exports.ImportInferenceContext = ImportInferenceContext;
1993
+ /** Maximum number of cached files before LRU eviction kicks in. */
1994
+ ImportInferenceContext.MAX_CACHE_SIZE = 1000;
1995
+ /** Maximum nested import depth. A real project doesn't exceed ~20;
1996
+ * beyond this we assume an accidental fan-out (or a pathological input)
1997
+ * and bail out with a single warning rather than hanging the server. */
1998
+ ImportInferenceContext.MAX_IMPORT_DEPTH = 64;
1999
+ //# sourceMappingURL=importContext.js.map