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,1712 @@
1
+ "use strict";
2
+ // ============================================================================
3
+ // Files — file resolution, ASI normalization, offset mapping, and utilities
4
+ //
5
+ // Plain language: the file-system helper desk. It resolves import paths to
6
+ // actual files (including `.hm` sidecar type files and package annotations),
7
+ // reads and lightly normalises source text, and keeps position bookkeeping
8
+ // so locations still line up when text was preprocessed.
9
+ // ============================================================================
10
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
11
+ if (k2 === undefined) k2 = k;
12
+ var desc = Object.getOwnPropertyDescriptor(m, k);
13
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
14
+ desc = { enumerable: true, get: function() { return m[k]; } };
15
+ }
16
+ Object.defineProperty(o, k2, desc);
17
+ }) : (function(o, m, k, k2) {
18
+ if (k2 === undefined) k2 = k;
19
+ o[k2] = m[k];
20
+ }));
21
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
22
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
23
+ }) : function(o, v) {
24
+ o["default"] = v;
25
+ });
26
+ var __importStar = (this && this.__importStar) || (function () {
27
+ var ownKeys = function(o) {
28
+ ownKeys = Object.getOwnPropertyNames || function (o) {
29
+ var ar = [];
30
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
31
+ return ar;
32
+ };
33
+ return ownKeys(o);
34
+ };
35
+ return function (mod) {
36
+ if (mod && mod.__esModule) return mod;
37
+ var result = {};
38
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
39
+ __setModuleDefault(result, mod);
40
+ return result;
41
+ };
42
+ })();
43
+ Object.defineProperty(exports, "__esModule", { value: true });
44
+ exports.runtimeExportNamesCache = exports.INLINE_PACKAGE_MAX_FILES = void 0;
45
+ exports.configureModuleExtensions = configureModuleExtensions;
46
+ exports.resolveImportSpecifier = resolveImportSpecifier;
47
+ exports.resolveImportSourceFile = resolveImportSourceFile;
48
+ exports.isAssetImportSpecifier = isAssetImportSpecifier;
49
+ exports.resolveTypeDirectiveSpecifier = resolveTypeDirectiveSpecifier;
50
+ exports.extractImportSpecifiers = extractImportSpecifiers;
51
+ exports.normalizeArrayLiteralASI = normalizeArrayLiteralASI;
52
+ exports.mapOffset = mapOffset;
53
+ exports.unmapOffset = unmapOffset;
54
+ exports.patchArrayLiteralASI = patchArrayLiteralASI;
55
+ exports.findExportedIdentifierOffset = findExportedIdentifierOffset;
56
+ exports.positionAt = positionAt;
57
+ exports.findTypeDefinitionLocation = findTypeDefinitionLocation;
58
+ exports.clearHmSidecarCache = clearHmSidecarCache;
59
+ exports.evictHmSidecar = evictHmSidecar;
60
+ exports.wrapHmSource = wrapHmSource;
61
+ exports.parseHmSource = parseHmSource;
62
+ exports.curriedHmDeclarations = curriedHmDeclarations;
63
+ exports.takesSeveralArguments = takesSeveralArguments;
64
+ exports.parseHmSourceRaw = parseHmSourceRaw;
65
+ exports.loadHmFile = loadHmFile;
66
+ exports.parseHmTypeAliases = parseHmTypeAliases;
67
+ exports.parseJsTypeAliases = parseJsTypeAliases;
68
+ exports.findHmSidecarPaths = findHmSidecarPaths;
69
+ exports.findPackageJson = findPackageJson;
70
+ exports.findPackageGlobalsPaths = findPackageGlobalsPaths;
71
+ exports.findHmSidecarPath = findHmSidecarPath;
72
+ exports.loadHmSidecar = loadHmSidecar;
73
+ exports.isBareSpecifier = isBareSpecifier;
74
+ exports.getBarePackageName = getBarePackageName;
75
+ exports.conventionalStubRelPaths = conventionalStubRelPaths;
76
+ exports.hmCompanionPackageName = hmCompanionPackageName;
77
+ exports.clearInlinePackageCache = clearInlinePackageCache;
78
+ exports.isInlineAnnotatedPackageModule = isInlineAnnotatedPackageModule;
79
+ exports.clearInlinePackageCacheForPackage = clearInlinePackageCacheForPackage;
80
+ exports.extractAllModuleSpecifiers = extractAllModuleSpecifiers;
81
+ exports.collectInlinePackageAnnotations = collectInlinePackageAnnotations;
82
+ const path = __importStar(require("path"));
83
+ const fs = __importStar(require("fs"));
84
+ const url_1 = require("url");
85
+ const node_1 = require("vscode-languageserver/node");
86
+ const commentParser_1 = require("../commentParser");
87
+ const dataTypeRegistry_1 = require("../registries/dataTypeRegistry");
88
+ const sidecarPerf_1 = require("./sidecarPerf");
89
+ const fsProbe_1 = require("./fsProbe");
90
+ // ---------------------------------------------------------------------------
91
+ // Import specifier resolution
92
+ // ---------------------------------------------------------------------------
93
+ /** Source extensions used for import resolution; updated from file selection. */
94
+ let jsExtensions = ['', '.js', '.mjs', '.cjs', '.jsx'];
95
+ let indexExtensions = ['.js', '.mjs', '.cjs', '.jsx'];
96
+ /** Keep custom selected source extensions importable (explicit or extensionless).
97
+ *
98
+ * NOTE: mutates process-global resolution state shared by every engine in
99
+ * this process. The LSP server and CLI each run in their own process; API
100
+ * consumers must not run two checkers with different extension sets
101
+ * concurrently in one process. */
102
+ function configureModuleExtensions(extensions) {
103
+ const source = [...new Set(extensions.filter(extension => extension !== '.hm'))];
104
+ jsExtensions = ['', ...source];
105
+ indexExtensions = source;
106
+ MODULE_EXTS.clear();
107
+ for (const extension of extensions)
108
+ MODULE_EXTS.add(extension);
109
+ }
110
+ /**
111
+ * Try to resolve a base path to an existing file by appending common
112
+ * extensions and checking for index files. Returns the resolved path
113
+ * or null.
114
+ */
115
+ function resolveWithExtensions(basePath) {
116
+ for (const ext of jsExtensions) {
117
+ const candidate = basePath + ext;
118
+ if ((0, fsProbe_1.isFile)(candidate))
119
+ return candidate;
120
+ }
121
+ for (const ext of indexExtensions) {
122
+ const candidate = path.join(basePath, 'index' + ext);
123
+ if ((0, fsProbe_1.isFile)(candidate))
124
+ return candidate;
125
+ }
126
+ return null;
127
+ }
128
+ /**
129
+ * Split a bare module specifier into [packageName, subpath].
130
+ * 'lodash' -> ['lodash', '.']
131
+ * 'lodash/fp' -> ['lodash', './fp']
132
+ * '@scope/pkg' -> ['@scope/pkg', '.']
133
+ * '@scope/pkg/sub/x' -> ['@scope/pkg', './sub/x']
134
+ */
135
+ function splitBareSpecifier(specifier) {
136
+ if (specifier.startsWith('@')) {
137
+ const parts = specifier.split('/');
138
+ if (parts.length < 2)
139
+ return [specifier, '.'];
140
+ const pkg = parts.slice(0, 2).join('/');
141
+ const sub = parts.length > 2 ? './' + parts.slice(2).join('/') : '.';
142
+ return [pkg, sub];
143
+ }
144
+ const slash = specifier.indexOf('/');
145
+ if (slash === -1)
146
+ return [specifier, '.'];
147
+ return [specifier.slice(0, slash), './' + specifier.slice(slash + 1)];
148
+ }
149
+ /**
150
+ * Resolve a value from package.json `exports`/`imports` conditional map.
151
+ * Recursively walks nested condition objects, picking the first key matching
152
+ * one of: `types`, `import`, `require`, `node`, `default`.
153
+ * Returns the relative target string, or null if no condition matches.
154
+ */
155
+ function resolveExportsConditions(value) {
156
+ if (typeof value === 'string')
157
+ return value;
158
+ if (value === null || typeof value !== 'object')
159
+ return null;
160
+ if (Array.isArray(value)) {
161
+ for (const item of value) {
162
+ const r = resolveExportsConditions(item);
163
+ if (r)
164
+ return r;
165
+ }
166
+ return null;
167
+ }
168
+ const obj = value;
169
+ const conditionPriority = ['types', 'import', 'require', 'node', 'default'];
170
+ for (const cond of conditionPriority) {
171
+ if (cond in obj) {
172
+ const r = resolveExportsConditions(obj[cond]);
173
+ if (r)
174
+ return r;
175
+ }
176
+ }
177
+ return null;
178
+ }
179
+ /**
180
+ * Resolve a subpath against the package.json `exports` field. Supports:
181
+ * - Direct string mappings: `"./sub": "./lib/sub.js"`
182
+ * - Conditional mappings: `"./sub": { "import": "...", "require": "..." }`
183
+ * - Pattern mappings: `"./*": "./src/*.js"`
184
+ * - Sugar form: `"exports": "./index.js"` or `"exports": { "import": ... }`
185
+ *
186
+ * Returns the relative path within the package, or null if no match.
187
+ */
188
+ function resolveExportsField(exportsField, subpath) {
189
+ // Sugar: string or condition map at top level => only the '.' subpath
190
+ if (typeof exportsField === 'string') {
191
+ return subpath === '.' ? exportsField : null;
192
+ }
193
+ if (exportsField === null || typeof exportsField !== 'object' || Array.isArray(exportsField)) {
194
+ return null;
195
+ }
196
+ const obj = exportsField;
197
+ // If no key starts with '.', this is a sugar condition map for '.'
198
+ const hasSubpathKeys = Object.keys(obj).some(k => k.startsWith('.'));
199
+ if (!hasSubpathKeys) {
200
+ return subpath === '.' ? resolveExportsConditions(obj) : null;
201
+ }
202
+ // Exact match
203
+ if (subpath in obj)
204
+ return resolveExportsConditions(obj[subpath]);
205
+ // Pattern match (longest prefix wins)
206
+ let bestMatchKey = null;
207
+ for (const key of Object.keys(obj)) {
208
+ const star = key.indexOf('*');
209
+ if (star === -1)
210
+ continue;
211
+ const prefix = key.slice(0, star);
212
+ const suffix = key.slice(star + 1);
213
+ if (subpath.startsWith(prefix) && subpath.endsWith(suffix)
214
+ && subpath.length >= prefix.length + suffix.length) {
215
+ if (!bestMatchKey || prefix.length > bestMatchKey.indexOf('*')) {
216
+ bestMatchKey = key;
217
+ }
218
+ }
219
+ }
220
+ if (bestMatchKey) {
221
+ const star = bestMatchKey.indexOf('*');
222
+ const prefix = bestMatchKey.slice(0, star);
223
+ const suffix = bestMatchKey.slice(star + 1);
224
+ const captured = subpath.slice(prefix.length, subpath.length - suffix.length);
225
+ const target = resolveExportsConditions(obj[bestMatchKey]);
226
+ if (target)
227
+ return target.replace(/\*/g, captured);
228
+ }
229
+ return null;
230
+ }
231
+ /**
232
+ * Walk up from `fromDir` looking for `node_modules/<specifier>` and resolve
233
+ * the package's entry file. Honours, in order:
234
+ * - `hinmil.sidecars` field (first existing entry)
235
+ * - `exports` field (subpath + conditional resolution)
236
+ * - `main` field
237
+ * - `index.{js,mjs,cjs}` fallback
238
+ *
239
+ * Supports subpath imports like `lodash/fp` or `@scope/pkg/sub/path`.
240
+ */
241
+ function resolveNodeModulePackage(specifier, fromDir) {
242
+ const [pkgName, subpath] = splitBareSpecifier(specifier);
243
+ let searchDir = fromDir;
244
+ while (true) {
245
+ const nodeModulesDir = path.join(searchDir, 'node_modules', pkgName);
246
+ try {
247
+ if ((0, fsProbe_1.isDir)(nodeModulesDir)) {
248
+ const pkgJsonPath = path.join(nodeModulesDir, 'package.json');
249
+ const pkgJson = (0, fsProbe_1.readJsonCached)(pkgJsonPath) ?? null;
250
+ if (pkgJson) {
251
+ // Prefer hinmil.sidecars field (only honoured for the package root).
252
+ // Accepts either a single string or an array — for arrays we
253
+ // return the first existing entry so `::types <pkg>` lands on
254
+ // the package's primary sidecar.
255
+ if (subpath === '.') {
256
+ for (const rel of readPkgSidecarPathsFromJson(pkgJson)) {
257
+ const hmPath = path.resolve(nodeModulesDir, rel);
258
+ if ((0, fsProbe_1.isFile)(hmPath))
259
+ return hmPath;
260
+ }
261
+ }
262
+ // Modern exports field
263
+ if (pkgJson.exports !== undefined) {
264
+ const target = resolveExportsField(pkgJson.exports, subpath);
265
+ if (target) {
266
+ const resolved = resolveWithExtensions(path.resolve(nodeModulesDir, target));
267
+ if (resolved)
268
+ return resolved;
269
+ }
270
+ }
271
+ // main / module fallback (only for package root)
272
+ if (subpath === '.') {
273
+ for (const field of ['main', 'module']) {
274
+ const v = pkgJson[field];
275
+ if (typeof v === 'string') {
276
+ const mainPath = path.resolve(nodeModulesDir, v);
277
+ const resolved = resolveWithExtensions(mainPath);
278
+ if (resolved)
279
+ return resolved;
280
+ }
281
+ }
282
+ }
283
+ }
284
+ // Subpath fallback: treat as relative to package root
285
+ if (subpath !== '.') {
286
+ const subResolved = resolveWithExtensions(path.resolve(nodeModulesDir, subpath));
287
+ if (subResolved)
288
+ return subResolved;
289
+ }
290
+ else {
291
+ // Default: index.{js,mjs,cjs}
292
+ const indexResolved = resolveWithExtensions(path.join(nodeModulesDir, 'index'));
293
+ if (indexResolved)
294
+ return indexResolved;
295
+ }
296
+ }
297
+ }
298
+ catch { /* continue */ }
299
+ const parentDir = path.dirname(searchDir);
300
+ if (parentDir === searchDir)
301
+ break; // reached filesystem root
302
+ searchDir = parentDir;
303
+ }
304
+ return null;
305
+ }
306
+ /**
307
+ * Resolve an import specifier (relative path or bare package name) to a file URI.
308
+ */
309
+ function resolveImportSpecifier(specifier, fromUri) {
310
+ const fromPath = (0, url_1.fileURLToPath)(fromUri);
311
+ const fromDir = path.dirname(fromPath);
312
+ if (specifier.startsWith('.') || specifier.startsWith('/')) {
313
+ const resolved = resolveWithExtensions(path.resolve(fromDir, specifier));
314
+ return resolved ? (0, url_1.pathToFileURL)(resolved).href : null;
315
+ }
316
+ // Bare specifier — look up in node_modules
317
+ const resolved = resolveNodeModulePackage(specifier, fromDir);
318
+ return resolved ? (0, url_1.pathToFileURL)(resolved).href : null;
319
+ }
320
+ /**
321
+ * Resolve an import specifier (seen from the file `fromPath`) to the SOURCE
322
+ * file a reader would want to open: like {@link resolveImportSpecifier}, but
323
+ * a package whose root resolves to an `.hm` sidecar yields its JavaScript
324
+ * entry (`main` / `module` / `index`) instead. Used by go-to-definition.
325
+ */
326
+ function resolveImportSourceFile(specifier, fromPath) {
327
+ const uri = resolveImportSpecifier(specifier, (0, url_1.pathToFileURL)(fromPath).href);
328
+ if (!uri)
329
+ return null;
330
+ const resolved = (0, url_1.fileURLToPath)(uri);
331
+ return resolved.endsWith('.hm') ? (effectiveJsEntry(resolved) ?? resolved) : resolved;
332
+ }
333
+ /** Module-ish extensions that are handled by inference rather than a bundler. */
334
+ const MODULE_EXTS = new Set(['.js', '.mjs', '.cjs', '.jsx', '.hm']);
335
+ /**
336
+ * True when `specifier` is a bundler-managed asset import — a relative (or
337
+ * absolute) path to an existing file whose extension is not a JS module
338
+ * (e.g. `./assets/hero.png`, `./App.css`, `./logo.svg?url`). Such imports
339
+ * are resolved by the bundler (Vite, webpack) at build time; the engine
340
+ * binds their names to the opaque `Any` type instead of reporting
341
+ * "Cannot resolve module" / "Unbound variable".
342
+ */
343
+ function isAssetImportSpecifier(specifier, fromUri) {
344
+ if (!specifier.startsWith('.') && !specifier.startsWith('/'))
345
+ return false;
346
+ // Strip bundler query/hash suffixes (Vite's `?url`, `?raw`, …).
347
+ const clean = specifier.replace(/[?#].*$/, '');
348
+ const ext = path.extname(clean).toLowerCase();
349
+ if (!ext || MODULE_EXTS.has(ext))
350
+ return false;
351
+ try {
352
+ const fromDir = path.dirname((0, url_1.fileURLToPath)(fromUri));
353
+ return (0, fsProbe_1.isFile)(path.resolve(fromDir, clean));
354
+ }
355
+ catch {
356
+ return false;
357
+ }
358
+ }
359
+ // ---------------------------------------------------------------------------
360
+ // ::types directive resolution
361
+ // ---------------------------------------------------------------------------
362
+ /**
363
+ * Resolve a `// ::types <specifier>` directive to a file path.
364
+ * Supports:
365
+ * - Relative paths: `./demo`, `../lib/types`
366
+ * - Package names: `fantasy-box`
367
+ * - Scoped packages: `@scope/package`
368
+ */
369
+ function resolveTypeDirectiveSpecifier(specifier, fromUri) {
370
+ const fromPath = (0, url_1.fileURLToPath)(fromUri);
371
+ const fromDir = path.dirname(fromPath);
372
+ if (specifier.startsWith('.') || specifier.startsWith('/')) {
373
+ // Relative path — resolve against the current file's directory. A
374
+ // `::types` file is often a `.hm` file: `./types` finds `types.hm` when
375
+ // there is no JS module of that name (`.hm` exact paths already match).
376
+ const base = path.resolve(fromDir, specifier);
377
+ const js = resolveWithExtensions(base);
378
+ if (js)
379
+ return js;
380
+ if (!base.endsWith('.hm') && (0, fsProbe_1.isFile)(base + '.hm'))
381
+ return base + '.hm';
382
+ return null;
383
+ }
384
+ const fromNodeModules = resolveNodeModulePackage(specifier, fromDir);
385
+ if (fromNodeModules)
386
+ return fromNodeModules;
387
+ return resolvePackageSelfSidecar(specifier, fromPath);
388
+ }
389
+ /**
390
+ * Package self-reference for `::types <own-package-name>`: a file INSIDE a
391
+ * package's source tree names its own package (a query builder's generated
392
+ * `src/generated/client/index.hm` starts with `::types query-builder`), which has no
393
+ * `node_modules/<name>` entry in the source repository. Resolve it to the
394
+ * package's own primary sidecar — the same target a consumer reaches through
395
+ * `node_modules`. Package root only.
396
+ */
397
+ function resolvePackageSelfSidecar(specifier, fromPath) {
398
+ const [pkgName, subpath] = splitBareSpecifier(specifier);
399
+ if (subpath !== '.')
400
+ return null;
401
+ const own = findPackageJson(fromPath);
402
+ if (!own || own.pkgJson.name !== pkgName)
403
+ return null;
404
+ for (const rel of readPkgSidecarPathsFromJson(own.pkgJson)) {
405
+ const hmPath = path.resolve(own.pkgDir, rel);
406
+ if ((0, fsProbe_1.isFile)(hmPath))
407
+ return hmPath;
408
+ }
409
+ return null;
410
+ }
411
+ // ---------------------------------------------------------------------------
412
+ // Import specifier extraction
413
+ // ---------------------------------------------------------------------------
414
+ /**
415
+ * Extract import specifiers mapping imported name → module specifier.
416
+ * Handles: `import Foo from './foo'`, `const { Foo } = require('./foo')`
417
+ */
418
+ function extractImportSpecifiers(source) {
419
+ const result = new Map();
420
+ // import Name from 'specifier'
421
+ const defaultImportRe = /import\s+(\w+)\s+from\s+['"]([^'"]+)['"]/g;
422
+ let m;
423
+ while ((m = defaultImportRe.exec(source)) !== null) {
424
+ result.set(m[1], m[2]);
425
+ }
426
+ // import { Name } from 'specifier' or import { Name as Alias } from 'specifier'
427
+ const namedImportRe = /import\s+\{([^}]+)\}\s+from\s+['"]([^'"]+)['"]/g;
428
+ while ((m = namedImportRe.exec(source)) !== null) {
429
+ for (const part of m[1].split(',')) {
430
+ const name = part.trim().split(/\s+as\s+/).pop()?.trim();
431
+ if (name)
432
+ result.set(name, m[2]);
433
+ }
434
+ }
435
+ // const { Name } = require('specifier')
436
+ const requireRe = /const\s+\{([^}]+)\}\s*=\s*require\s*\(\s*['"]([^'"]+)['"]\s*\)/g;
437
+ while ((m = requireRe.exec(source)) !== null) {
438
+ for (const part of m[1].split(',')) {
439
+ const name = part.trim().split(/\s+as\s+/).pop()?.trim();
440
+ if (name)
441
+ result.set(name, m[2]);
442
+ }
443
+ }
444
+ // const Name = require('specifier') — single-name CJS import (no destructure)
445
+ const requireDefaultRe = /const\s+(\w+)\s*=\s*require\s*\(\s*['"]([^'"]+)['"]\s*\)/g;
446
+ while ((m = requireDefaultRe.exec(source)) !== null) {
447
+ result.set(m[1], m[2]);
448
+ }
449
+ return result;
450
+ }
451
+ // ---------------------------------------------------------------------------
452
+ // Array literal ASI normalization
453
+ // ---------------------------------------------------------------------------
454
+ /**
455
+ * Pre-process source to insert `;` before `[` at line starts where JS parsers
456
+ * would otherwise treat the array literal as a computed member access on the
457
+ * previous expression (the well-known ASI hazard).
458
+ *
459
+ * Returns the patched source and an array of insertion offsets so that
460
+ * diagnostic positions can be mapped back to the original source.
461
+ *
462
+ * Heuristic: a `[` at the start of a line (after optional whitespace) is
463
+ * treated as an array literal start when the last significant character of
464
+ * the previous line is one of: ) ] } identifier-char " ' ` digit
465
+ * (i.e. something that ends a complete expression/statement).
466
+ */
467
+ function normalizeArrayLiteralASI(source) {
468
+ const lines = source.split('\n');
469
+ const insertions = [];
470
+ let offset = 0; // running offset in the *original* source
471
+ for (let lineIdx = 0; lineIdx < lines.length; lineIdx++) {
472
+ const line = lines[lineIdx];
473
+ const trimmed = line.trimStart();
474
+ if (trimmed.startsWith('[') && lineIdx > 0) {
475
+ // Check if previous line ends with something that completes an expression
476
+ let prevLineIdx = lineIdx - 1;
477
+ // Skip blank lines
478
+ while (prevLineIdx >= 0 && lines[prevLineIdx].trim() === '')
479
+ prevLineIdx--;
480
+ if (prevLineIdx >= 0) {
481
+ const prevTrimmed = lines[prevLineIdx].trimEnd();
482
+ const lastChar = prevTrimmed[prevTrimmed.length - 1];
483
+ if (lastChar && /[)\]}'"`0-9A-Za-z_$]/.test(lastChar)) {
484
+ // Insert ';' at the beginning of the trimmed content
485
+ const leadingSpaces = line.length - trimmed.length;
486
+ const insertPos = offset + leadingSpaces;
487
+ insertions.push(insertPos);
488
+ lines[lineIdx] = line.substring(0, leadingSpaces) + ';' + trimmed;
489
+ }
490
+ }
491
+ }
492
+ offset += line.length + 1; // +1 for the '\n'
493
+ }
494
+ return { patched: lines.join('\n'), insertions };
495
+ }
496
+ /**
497
+ * Map an offset from original source to the patched source,
498
+ * accounting for all `;` insertions.
499
+ */
500
+ function mapOffset(offset, insertions) {
501
+ let mapped = offset;
502
+ for (const ins of insertions) {
503
+ if (ins <= offset)
504
+ mapped++;
505
+ else
506
+ break;
507
+ }
508
+ return mapped;
509
+ }
510
+ /**
511
+ * Map an offset from patched source back to the original source,
512
+ * accounting for all `;` insertions.
513
+ */
514
+ function unmapOffset(patchedOffset, insertions) {
515
+ let shift = 0;
516
+ for (const ins of insertions) {
517
+ if (ins + shift < patchedOffset)
518
+ shift++;
519
+ else
520
+ break;
521
+ }
522
+ return patchedOffset - shift;
523
+ }
524
+ /**
525
+ * Find the matching `[` for a `]` at `closeBracketIdx` in `source` and
526
+ * return a patched source with `;` inserted before the `[`.
527
+ *
528
+ * This is the single, reusable fix for the ASI ambiguity where JavaScript
529
+ * (and the parser) treat `[...]` on a new line as computed member access on
530
+ * the previous expression rather than as an array literal.
531
+ */
532
+ function patchArrayLiteralASI(source, closeBracketIdx) {
533
+ let bracketDepth = 0;
534
+ let openBracket = -1;
535
+ for (let i = closeBracketIdx - 1; i >= 0; i--) {
536
+ if (source[i] === ']')
537
+ bracketDepth++;
538
+ if (source[i] === '[') {
539
+ if (bracketDepth === 0) {
540
+ openBracket = i;
541
+ break;
542
+ }
543
+ bracketDepth--;
544
+ }
545
+ }
546
+ if (openBracket < 0)
547
+ return null;
548
+ return {
549
+ patched: source.substring(0, openBracket) + ';' + source.substring(openBracket),
550
+ openBracket,
551
+ shift: 1,
552
+ };
553
+ }
554
+ // ---------------------------------------------------------------------------
555
+ // Export location lookup
556
+ // ---------------------------------------------------------------------------
557
+ /**
558
+ * Find the offset of an exported identifier in a source file.
559
+ * Handles: `export const name`, `export function name`, `export default name`,
560
+ * `export { name }`, and `const name` / `function name` (for default
561
+ * or re-export patterns).
562
+ * Returns the start offset of the identifier or -1 if not found.
563
+ */
564
+ function findExportedIdentifierOffset(source, name) {
565
+ // export const name / export let name / export var name / export function name
566
+ const exportDeclRe = new RegExp(`export\\s+(?:const|let|var|function)\\s+(${escapeRegExp(name)})\\b`);
567
+ let m = exportDeclRe.exec(source);
568
+ if (m)
569
+ return m.index + m[0].length - name.length;
570
+ // export default name (rare but possible)
571
+ const exportDefaultRe = new RegExp(`export\\s+default\\s+(${escapeRegExp(name)})\\b`);
572
+ m = exportDefaultRe.exec(source);
573
+ if (m)
574
+ return m.index + m[0].length - name.length;
575
+ // export { name } or export { something as name }
576
+ const exportListRe = /export\s+\{([^}]+)\}/g;
577
+ let em;
578
+ while ((em = exportListRe.exec(source)) !== null) {
579
+ for (const part of em[1].split(',')) {
580
+ const trimmed = part.trim();
581
+ const asMatch = trimmed.match(/\w+\s+as\s+(\w+)/);
582
+ const exported = asMatch ? asMatch[1] : trimmed;
583
+ if (exported === name) {
584
+ // Point to the actual declaration in the file
585
+ const declRe = new RegExp(`(?:const|let|var|function)\\s+(${escapeRegExp(name)})\\b`);
586
+ const dm = declRe.exec(source);
587
+ if (dm)
588
+ return dm.index + dm[0].length - name.length;
589
+ // Fall back to the export list position
590
+ return em.index;
591
+ }
592
+ }
593
+ }
594
+ // Plain declaration (for module.exports patterns or default export after decl)
595
+ const plainDeclRe = new RegExp(`(?:const|let|var|function)\\s+(${escapeRegExp(name)})\\b`);
596
+ m = plainDeclRe.exec(source);
597
+ if (m)
598
+ return m.index + m[0].length - name.length;
599
+ return -1;
600
+ }
601
+ /** Escape special regex characters in a string. */
602
+ function escapeRegExp(s) {
603
+ return s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
604
+ }
605
+ // ---------------------------------------------------------------------------
606
+ // Offset / position conversion
607
+ // ---------------------------------------------------------------------------
608
+ /** Convert a character offset to a Position {line, character}. */
609
+ function positionAt(source, offset) {
610
+ let line = 0;
611
+ let lastNewline = -1;
612
+ for (let i = 0; i < offset && i < source.length; i++) {
613
+ if (source[i] === '\n') {
614
+ line++;
615
+ lastNewline = i;
616
+ }
617
+ }
618
+ return { line, character: offset - lastNewline - 1 };
619
+ }
620
+ // ---------------------------------------------------------------------------
621
+ // Type definition location
622
+ // ---------------------------------------------------------------------------
623
+ /**
624
+ * Escape a string for safe inclusion inside a RegExp source.
625
+ */
626
+ function escapeRegex(s) {
627
+ return s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
628
+ }
629
+ /**
630
+ * Check whether a comment slice is the actual local annotation / sumtype
631
+ * declaration for `typeName` (i.e. `// typeName :: ...`). Used to guard
632
+ * against false positives where the globally-merged annotation/registry
633
+ * entries point at unrelated comment ranges in the current file (e.g. a
634
+ * `::types ./Either2` directive that happens to contain both `::` and
635
+ * `Either2`).
636
+ */
637
+ function isOwnAnnotationSlice(slice, typeName) {
638
+ if (!slice)
639
+ return false;
640
+ const pattern = new RegExp(`^\\s*//\\s*${escapeRegex(typeName)}\\s*::`);
641
+ return pattern.test(slice);
642
+ }
643
+ /**
644
+ * Find the definition location of a type name.
645
+ * Checks: 1) type aliases, 2) local constructor annotations,
646
+ * 3) imported files, 4) ::types directive targets,
647
+ * 5) globals file.
648
+ */
649
+ function findTypeDefinitionLocation(typeName, source, fromUri, result, globals) {
650
+ // 1) Type alias in current file. The typeAliases map also contains
651
+ // entries merged from project globals — those carry offsets from the
652
+ // GLOBALS source, not the current file. Anchor-check the slice (must
653
+ // start with `// <typeName> ::`) so we only return a local location
654
+ // for aliases that are genuinely declared in this file; foreign
655
+ // entries fall through to the globals lookup below (step 5).
656
+ const alias = result.typeAliases.get(typeName);
657
+ if (alias) {
658
+ const aliasSlice = alias.commentEnd <= source.length
659
+ ? source.slice(alias.commentStart, alias.commentEnd)
660
+ : '';
661
+ if (isOwnAnnotationSlice(aliasSlice, typeName)) {
662
+ return node_1.Location.create(fromUri, {
663
+ start: positionAt(source, alias.commentStart),
664
+ end: positionAt(source, alias.commentEnd),
665
+ });
666
+ }
667
+ }
668
+ // 2) Constructor annotation in current file (e.g. // RTask :: ... -> RTask r e a)
669
+ // The annotations map may also contain entries merged from ::types directive
670
+ // targets — those have offsets from the OTHER file. Verify the comment
671
+ // text at those offsets actually references this type in the current source
672
+ // before using it as a local location. The slice must start with an
673
+ // anchored `// <typeName> ::` pattern; a loose includes() check is too
674
+ // permissive (e.g. `// ::types ./Either2` coincidentally contains both
675
+ // `::` and `Either2`, which used to fool this heuristic).
676
+ const localAnn = result.annotations.get(typeName);
677
+ if (localAnn?.scheme) {
678
+ const annSlice = localAnn.commentEnd <= source.length
679
+ ? source.slice(localAnn.commentStart, localAnn.commentEnd)
680
+ : '';
681
+ if (isOwnAnnotationSlice(annSlice, typeName)) {
682
+ return node_1.Location.create(fromUri, {
683
+ start: positionAt(source, localAnn.commentStart),
684
+ end: positionAt(source, localAnn.commentEnd),
685
+ });
686
+ }
687
+ }
688
+ // 2b) Sum type declaration in current file (e.g. // Either :: Left e | Right a)
689
+ // Same anchoring check: the comment must start with
690
+ // `// <typeName> ::` to be considered a definition in the current file.
691
+ const dataType = (0, dataTypeRegistry_1.getDataType)(typeName);
692
+ const sumtypeSlice = dataType && dataType.decl.commentEnd <= source.length
693
+ ? source.slice(dataType.decl.commentStart, dataType.decl.commentEnd)
694
+ : '';
695
+ if (dataType && isOwnAnnotationSlice(sumtypeSlice, typeName)) {
696
+ return node_1.Location.create(fromUri, {
697
+ start: positionAt(source, dataType.decl.commentStart),
698
+ end: positionAt(source, dataType.decl.commentEnd),
699
+ });
700
+ }
701
+ // 2c) ::constraint directive in current file (e.g. // ::constraint Functor f { map :: ... })
702
+ const constraintLoc = findConstraintDirectiveLocation(typeName, source, fromUri);
703
+ if (constraintLoc)
704
+ return constraintLoc;
705
+ // 3+4) Breadth-first search across reachable files via runtime imports
706
+ // and `::types` directive targets. This lets go-to-definition follow
707
+ // transitive paths: e.g. Repo.js imports `one` from db/one.js, which
708
+ // has `// ::types ../lib/RTask` — looking up `RTask` from Repo.js
709
+ // reaches the annotations in lib/RTask/RTask.js by following the
710
+ // `::types` directive of the imported module.
711
+ const visited = new Set([fromUri]);
712
+ const queue = [{ uri: fromUri, source }];
713
+ const MAX_VISIT = 64;
714
+ let visits = 0;
715
+ while (queue.length > 0 && visits < MAX_VISIT) {
716
+ const { uri: curUri, source: curSource } = queue.shift();
717
+ // Enqueue runtime imports
718
+ for (const specifier of new Set(extractImportSpecifiers(curSource).values())) {
719
+ const nextUri = resolveImportSpecifier(specifier, curUri);
720
+ if (!nextUri || visited.has(nextUri))
721
+ continue;
722
+ visited.add(nextUri);
723
+ try {
724
+ const p = (0, url_1.fileURLToPath)(nextUri);
725
+ const s = fs.readFileSync(p, 'utf-8');
726
+ queue.push({ uri: nextUri, source: s });
727
+ }
728
+ catch {
729
+ // unreadable file — skip
730
+ }
731
+ }
732
+ // Enqueue ::types directive targets
733
+ for (const specifier of (0, commentParser_1.extractTypeDirectives)(curSource)) {
734
+ const targetPath = resolveTypeDirectiveSpecifier(specifier, curUri);
735
+ if (!targetPath)
736
+ continue;
737
+ const nextUri = (0, url_1.pathToFileURL)(targetPath).href;
738
+ if (visited.has(nextUri))
739
+ continue;
740
+ visited.add(nextUri);
741
+ try {
742
+ const s = fs.readFileSync(targetPath, 'utf-8');
743
+ queue.push({ uri: nextUri, source: s });
744
+ }
745
+ catch {
746
+ // unreadable file — skip
747
+ }
748
+ }
749
+ // Skip the seed file (already searched above as steps 1, 2, 2b, 2c)
750
+ if (curUri === fromUri)
751
+ continue;
752
+ visits++;
753
+ // Annotation in this file
754
+ const anns = (0, commentParser_1.buildAnnotationMap)(curSource);
755
+ const ann = anns.get(typeName);
756
+ if (ann) {
757
+ return node_1.Location.create(curUri, {
758
+ start: positionAt(curSource, ann.commentStart),
759
+ end: positionAt(curSource, ann.commentEnd),
760
+ });
761
+ }
762
+ // Sumtype declaration in this file
763
+ for (const decl of (0, commentParser_1.extractDataDirectives)(curSource)) {
764
+ if (decl.name === typeName) {
765
+ return node_1.Location.create(curUri, {
766
+ start: positionAt(curSource, decl.commentStart),
767
+ end: positionAt(curSource, decl.commentEnd),
768
+ });
769
+ }
770
+ }
771
+ // ::constraint directive in this file
772
+ const constraintLoc2 = findConstraintDirectiveLocation(typeName, curSource, curUri);
773
+ if (constraintLoc2)
774
+ return constraintLoc2;
775
+ }
776
+ // 5) Look in globals file (project-level globals with ::constraint, ::global, sumtype)
777
+ if (globals) {
778
+ const globalsAnns = (0, commentParser_1.buildAnnotationMap)(globals.source);
779
+ const ann = globalsAnns.get(typeName);
780
+ if (ann) {
781
+ return node_1.Location.create(globals.uri, {
782
+ start: positionAt(globals.source, ann.commentStart),
783
+ end: positionAt(globals.source, ann.commentEnd),
784
+ });
785
+ }
786
+ const globalsDataDirectives = (0, commentParser_1.extractDataDirectives)(globals.source);
787
+ for (const decl of globalsDataDirectives) {
788
+ if (decl.name === typeName) {
789
+ return node_1.Location.create(globals.uri, {
790
+ start: positionAt(globals.source, decl.commentStart),
791
+ end: positionAt(globals.source, decl.commentEnd),
792
+ });
793
+ }
794
+ }
795
+ const globalsConstraintLoc = findConstraintDirectiveLocation(typeName, globals.source, globals.uri);
796
+ if (globalsConstraintLoc)
797
+ return globalsConstraintLoc;
798
+ }
799
+ return null;
800
+ }
801
+ // ---------------------------------------------------------------------------
802
+ // Constraint directive location lookup
803
+ // ---------------------------------------------------------------------------
804
+ /** Pattern to extract the constraint name from a ::constraint directive text. */
805
+ const CONSTRAINT_NAME_PATTERN = /^[\s*]*::constraint\s+([A-Z]\w*)/;
806
+ /**
807
+ * Search `// ::constraint Name v { ... }` directives in `source` for one
808
+ * whose constraint name matches `name`. Returns the Location of the
809
+ * directive comment, or null if not found.
810
+ */
811
+ function findConstraintDirectiveLocation(name, source, uri) {
812
+ for (const directive of (0, commentParser_1.extractConstraintDirectives)(source)) {
813
+ const m = CONSTRAINT_NAME_PATTERN.exec(directive.text);
814
+ if (m && m[1] === name) {
815
+ return node_1.Location.create(uri, {
816
+ start: positionAt(source, directive.start),
817
+ end: positionAt(source, directive.end),
818
+ });
819
+ }
820
+ }
821
+ return null;
822
+ }
823
+ const NOOP_LOGGER = { warn: () => { } };
824
+ const hmFileCache = new Map();
825
+ /** Cheap freshness stamp for a sidecar on disk (mtime + size). */
826
+ function hmFileStamp(filePath) {
827
+ try {
828
+ const st = fs.statSync(filePath);
829
+ return `${st.mtimeMs}:${st.size}`;
830
+ }
831
+ catch {
832
+ return null;
833
+ }
834
+ }
835
+ function clearHmSidecarCache() {
836
+ hmFileCache.clear();
837
+ }
838
+ /**
839
+ * Evict a single `.hm` sidecar entry from the parse cache. Used by the
840
+ * selective-invalidation path so unrelated sidecars stay parsed when one
841
+ * sidecar changes. Accepts either an absolute file path (the cache key)
842
+ * or a `file://` URI — converts the URI form to a path before lookup.
843
+ */
844
+ function evictHmSidecar(pathOrUri) {
845
+ const key = pathOrUri.startsWith('file://')
846
+ ? (0, url_1.fileURLToPath)(pathOrUri)
847
+ : pathOrUri;
848
+ hmFileCache.delete(key);
849
+ }
850
+ /**
851
+ * Wrap every non-comment line of a `.hm` source with `// ` so that the
852
+ * existing comment-based annotation parser can extract `Name :: Type`
853
+ * declarations.
854
+ *
855
+ * Comment semantics inside `.hm`:
856
+ * - A line starting with `//` (after trimming) is a true source-level
857
+ * comment and is NOT registered. Its bytes are blanked out (replaced
858
+ * by spaces of the same length) so directive/annotation regexes can
859
+ * never see them, while line offsets remain stable for diagnostics.
860
+ * - Block comments (`/* ... *\/`) are likewise stripped to whitespace.
861
+ * - Bare directive/annotation lines are wrapped with `// ` so the
862
+ * existing JS comment parser picks them up.
863
+ */
864
+ function wrapHmSource(source) {
865
+ const blank = (line) => ' '.repeat(line.length);
866
+ let inBlock = false;
867
+ return source
868
+ .split('\n')
869
+ .map(line => {
870
+ if (inBlock) {
871
+ const end = line.indexOf('*/');
872
+ if (end >= 0)
873
+ inBlock = false;
874
+ return blank(line);
875
+ }
876
+ const trimmed = line.trimStart();
877
+ if (trimmed === '')
878
+ return line;
879
+ if (trimmed.startsWith('//'))
880
+ return blank(line);
881
+ if (trimmed.startsWith('/*')) {
882
+ if (!line.includes('*/'))
883
+ inBlock = true;
884
+ return blank(line);
885
+ }
886
+ if (trimmed.startsWith('*'))
887
+ return blank(line);
888
+ return "// " + blankTrailingHmComment(line);
889
+ })
890
+ .join('\n');
891
+ }
892
+ /**
893
+ * Blank a trailing `// remark` on a `.hm` declaration line (same length, so
894
+ * offsets stay put). `//` never occurs in type syntax, except inside a
895
+ * string-literal type (`'https://…'`), which is skipped.
896
+ */
897
+ function blankTrailingHmComment(line) {
898
+ let quote = null;
899
+ for (let i = 0; i < line.length - 1; i++) {
900
+ const c = line[i];
901
+ if (quote) {
902
+ if (c === quote)
903
+ quote = null;
904
+ }
905
+ else if (c === "'" || c === '"') {
906
+ quote = c;
907
+ }
908
+ else if (c === '/' && line[i + 1] === '/') {
909
+ return line.slice(0, i) + ' '.repeat(line.length - i);
910
+ }
911
+ }
912
+ return line;
913
+ }
914
+ /**
915
+ * Parse a `.hm` annotation source into a map from exported name to its
916
+ * `Scheme`. By default the source is wrapped via {@link wrapHmSource} so
917
+ * the JS comment-parser can read bare-line `Name :: Type` declarations.
918
+ * Pass `{ wrap: false }` when the source is JS (or any file whose
919
+ * annotations already live inside `// ` comments) — e.g. when scanning
920
+ * a package's JS entries for inline signatures next to definitions.
921
+ */
922
+ function parseHmSource(source, opts = {}) {
923
+ const wrap = opts.wrap !== false;
924
+ const wrapped = wrap ? wrapHmSource(source) : source;
925
+ const { extractAnnotations } = require('../commentParser');
926
+ const { mergeOverloadSchemes } = require('../hm/env');
927
+ const annotations = extractAnnotations(wrapped);
928
+ const { curryWrapperLeadingArgs } = require('../infer/annotations');
929
+ const curried = wrap ? new Set(curriedHmDeclarations(source).map(d => d.name)) : new Set();
930
+ const exports = new Map();
931
+ for (const rawAnn of annotations) {
932
+ const ann = rawAnn.scheme && rawAnn.name && curried.has(rawAnn.name)
933
+ && takesSeveralArguments(rawAnn.scheme.type)
934
+ ? { ...rawAnn, scheme: { ...rawAnn.scheme, isCurriedResult: true } }
935
+ : rawAnn;
936
+ if (!ann.name || !ann.scheme)
937
+ continue;
938
+ const existing = exports.get(ann.name);
939
+ if (existing) {
940
+ // Same name already declared — merge into an overloaded (Union) scheme.
941
+ // Skip merging for method/static annotations (`Type#m`, `Type.m`); those
942
+ // go through the method registry which has its own overload semantics.
943
+ if (ann.name.includes('#') || ann.name.includes('.')) {
944
+ exports.set(ann.name, ann.scheme);
945
+ }
946
+ else {
947
+ const merged = mergeOverloadSchemes(existing, ann.scheme);
948
+ if (existing.isCurriedResult || ann.scheme.isCurriedResult)
949
+ merged.isCurriedResult = true;
950
+ exports.set(ann.name, merged);
951
+ }
952
+ }
953
+ else {
954
+ exports.set(ann.name, ann.scheme);
955
+ }
956
+ }
957
+ // A curry wrapper declared in a `.hm` file (`curry :: ((a, b, ...) -> z) ->
958
+ // a -> b -> ... -> z`) is recognised by its signature, as in JavaScript:
959
+ // a function built with it takes its arguments in any grouping, also when
960
+ // the binding carries its own annotation.
961
+ for (const [name, scheme] of exports) {
962
+ if (name.includes('#') || name.includes('.'))
963
+ continue;
964
+ const leading = curryWrapperLeadingArgs(scheme.type);
965
+ if (leading === 0)
966
+ exports.set(name, { ...scheme, isCurryWrapper: true });
967
+ else if (leading !== null)
968
+ exports.set(name, { ...scheme, curryLeadingArgs: leading });
969
+ }
970
+ return exports;
971
+ }
972
+ /**
973
+ * The `::curried` lines of a `.hm` source, each with the name declared on
974
+ * the line directly below it (`null` when that line declares nothing). The
975
+ * function with that name is curried the way Ramda's functions are: it
976
+ * accepts its arguments in any grouping (`f (a, b)`, `f (a) (b)`), like the
977
+ * result of a `curry (…)` call in JavaScript. Its overload lines share the
978
+ * marker.
979
+ */
980
+ function curriedHmDeclarations(source) {
981
+ const lines = source.split('\n');
982
+ const out = [];
983
+ lines.forEach((text, i) => {
984
+ if (text.trim() !== '::curried')
985
+ return;
986
+ const next = /^\s*([A-Za-z_$][\w$]*)\s*::\s/.exec(lines[i + 1] ?? '');
987
+ out.push({ line: i, name: next ? next[1] : null });
988
+ });
989
+ return out;
990
+ }
991
+ /** `a -> b -> c` (or longer): a function whose result is again a function. */
992
+ function takesSeveralArguments(type) {
993
+ return type.tag === 'TFun' && type.result.tag === 'TFun';
994
+ }
995
+ /**
996
+ * Like `parseHmSource` but returns the raw signature text exactly as the
997
+ * user wrote it, indexed by export name. Used by hover / completion to
998
+ * preserve the user's parens, whitespace and ordering instead of
999
+ * round-tripping through the type printer (which loses redundant parens).
1000
+ */
1001
+ function parseHmSourceRaw(source) {
1002
+ const wrapped = wrapHmSource(source);
1003
+ const { extractAnnotations } = require('../commentParser');
1004
+ const annotations = extractAnnotations(wrapped);
1005
+ const raws = new Map();
1006
+ for (const ann of annotations) {
1007
+ if (!ann.name || !ann.raw)
1008
+ continue;
1009
+ const prev = raws.get(ann.name);
1010
+ // Preserve overloads: when the same name has multiple `Name :: ...`
1011
+ // declarations, join them with `\n${name} :: ` so the consumer (hover)
1012
+ // can render each overload on its own line.
1013
+ raws.set(ann.name, prev ? `${prev}\n${ann.name} :: ${ann.raw}` : ann.raw);
1014
+ }
1015
+ return raws;
1016
+ }
1017
+ /**
1018
+ * Read and parse a standalone `.hm` annotation file. Returns a map from
1019
+ * exported name to its parsed `Scheme`, or `null` when the file can't be
1020
+ * read. Results are cached by absolute path.
1021
+ */
1022
+ function loadHmFile(filePath, logger = NOOP_LOGGER) {
1023
+ const stamp = hmFileStamp(filePath);
1024
+ const cached = hmFileCache.get(filePath);
1025
+ if (cached !== undefined && cached.stamp === (stamp ?? 'missing'))
1026
+ return cached.exports;
1027
+ let source;
1028
+ try {
1029
+ source = fs.readFileSync(filePath, 'utf-8');
1030
+ }
1031
+ catch (e) {
1032
+ logger.warn(`[hinmil] Failed to read '${filePath}': ${e instanceof Error ? e.message : String(e)}`);
1033
+ hmFileCache.set(filePath, { stamp: stamp ?? 'missing', exports: null });
1034
+ return null;
1035
+ }
1036
+ const exports = (0, sidecarPerf_1.timeSidecarStage)('parse', () => parseHmSource(source));
1037
+ hmFileCache.set(filePath, { stamp: stamp ?? 'missing', exports });
1038
+ return exports;
1039
+ }
1040
+ /**
1041
+ * Parse the contents of a `.hm` annotation source and extract the type
1042
+ * aliases declared in it. An entry is treated as an alias when the name
1043
+ * is uppercase, is not a method (no `#`/`.`), is not a sumtype declaration
1044
+ * or constructor, and is not a registered data-type variant. Returned
1045
+ * alongside each alias is the ordered list of free type-variable names
1046
+ * appearing in the alias body — needed for polymorphic alias expansion.
1047
+ */
1048
+ function parseHmTypeAliases(source, opts = {}) {
1049
+ const wrap = opts.wrap !== false;
1050
+ const wrapped = wrap ? wrapHmSource(source) : source;
1051
+ const { buildAnnotationMap, extractInstanceCallables, extractAliasExtensions } = require('../commentParser');
1052
+ const { buildTypeAliases, buildTypeAliasVars } = require('../infer/annotations');
1053
+ const { T_UNION } = require('../hm/types');
1054
+ const annotationMap = buildAnnotationMap(wrapped);
1055
+ const allAliases = buildTypeAliases(annotationMap);
1056
+ // Restrict to non-functional bodies. Constructor / factory annotations
1057
+ // such as `BooleanProp :: (String, a) -> Prop Boolean` would otherwise
1058
+ // be classified as aliases by `buildTypeAliases` (because their return
1059
+ // type's name does not match the binding's name). Treating them as
1060
+ // aliases would cause bare `TCon('BooleanProp', [])` references to
1061
+ // expand into a function type at use sites — which is never what we
1062
+ // want for a value-level factory.
1063
+ //
1064
+ // Repeated annotations for the same name (e.g. two overloaded
1065
+ // `Table :: ... -> ...` declarations) are merged into a union by
1066
+ // `buildTypeAliases`. When every branch of that union is a function
1067
+ // type, the binding is still a value-level factory rather than a
1068
+ // type alias — so we filter those too. Otherwise references to
1069
+ // `Table` in another sidecar's signatures would expand to a union of
1070
+ // function types and lose access to the registered `Table#...` methods.
1071
+ const isFunctionalUnion = (t) => t.tag === 'TCon' && t.name === T_UNION
1072
+ && t.args.length > 0 && t.args.every(a => a.tag === 'TFun');
1073
+ const aliases = new Map();
1074
+ for (const [name, type] of allAliases) {
1075
+ if (type.tag === 'TFun')
1076
+ continue;
1077
+ if (isFunctionalUnion(type))
1078
+ continue;
1079
+ aliases.set(name, type);
1080
+ }
1081
+ // Constructor / callable-value annotations: uppercase-named entries
1082
+ // whose scheme body is a TFun, or a Union containing at least one TFun
1083
+ // branch. These power the "constructor as callable" bridge so that a
1084
+ // value of an uppercase TCon (e.g. `QueryTag a` returned from
1085
+ // `Organisation([...])`) can be invoked when the imported sidecar
1086
+ // declares `QueryTag :: a -> RTask r e [b]`. Method annotations and
1087
+ // lowercase-named values are excluded.
1088
+ const constructors = new Map();
1089
+ for (const [name, ann] of annotationMap) {
1090
+ if (!ann.scheme)
1091
+ continue;
1092
+ if (name.includes('#') || name.includes('.'))
1093
+ continue;
1094
+ if (!/^[A-Z]/.test(name))
1095
+ continue;
1096
+ const t = ann.scheme.type;
1097
+ const isCallable = t.tag === 'TFun'
1098
+ || (t.tag === 'TCon' && t.name === T_UNION
1099
+ && t.args.some(a => a.tag === 'TFun'));
1100
+ if (isCallable)
1101
+ constructors.set(name, ann.scheme);
1102
+ }
1103
+ const aliasVars = buildTypeAliasVars(annotationMap, aliases);
1104
+ // Return all `Name() :: ...` entries verbatim — DO NOT filter orphans
1105
+ // here. In an override sidecar (project `hm-types/<pkg>.hm` registered
1106
+ // via `package.json#hinmil.overrides`) it is intentional to declare only
1107
+ // an instance-callable while the matching constructor lives in the
1108
+ // base package sidecar. The consumer engine merges constructors from
1109
+ // all sources and validates orphans against the union; doing it here
1110
+ // would silently drop a valid override.
1111
+ const instanceCallables = extractInstanceCallables(wrapped);
1112
+ const aliasExtensions = extractAliasExtensions(wrapped);
1113
+ return { aliases, aliasVars, constructors, instanceCallables, aliasExtensions };
1114
+ }
1115
+ /**
1116
+ * Type aliases declared in a JavaScript/TypeScript module's own comment
1117
+ * annotations (`// RequestObj :: { … }`, `// Rule :: (String, Any) -> …`).
1118
+ *
1119
+ * Only STANDALONE annotations count: an uppercase annotation that is not
1120
+ * attached to a declaration (`nodeStart === undefined`). An annotation on a
1121
+ * declaration (`// Engine :: (String, EngineFn) -> Component` above
1122
+ * `const Engine = …`) types a value, not a type name. Unlike `.hm`
1123
+ * sidecars, function-bodied aliases (`RouteFn :: RequestObj -> …`) stay
1124
+ * aliases: in a JS module the standalone form is always a type name.
1125
+ *
1126
+ * Used by the import-alias resolver so that importing a value from a module
1127
+ * also brings the type names that module (and its `::types` closure)
1128
+ * declares — consumers no longer need an explicit `// ::types` for them.
1129
+ */
1130
+ function parseJsTypeAliases(source) {
1131
+ const { extractAliasExtensions } = require('../commentParser');
1132
+ const { buildTypeAliases, buildTypeAliasVars } = require('../infer/annotations');
1133
+ const standalone = new Map();
1134
+ for (const [name, ann] of (0, commentParser_1.buildAnnotationMap)(source)) {
1135
+ if (!ann.scheme || ann.nodeStart !== undefined)
1136
+ continue;
1137
+ if (name.includes('#') || name.includes('.'))
1138
+ continue;
1139
+ if (!/^[A-Z]/.test(name))
1140
+ continue;
1141
+ standalone.set(name, ann);
1142
+ }
1143
+ const aliases = standalone.size > 0
1144
+ ? buildTypeAliases(standalone)
1145
+ : new Map();
1146
+ const aliasVars = aliases.size > 0 ? buildTypeAliasVars(standalone, aliases) : new Map();
1147
+ return {
1148
+ aliases,
1149
+ aliasVars,
1150
+ constructors: new Map(),
1151
+ instanceCallables: new Map(),
1152
+ aliasExtensions: extractAliasExtensions(source),
1153
+ };
1154
+ }
1155
+ /**
1156
+ * Read the `hinmil.sidecars` field from an already-parsed package.json.
1157
+ * Returns the list of relative paths declared (single-string or array form),
1158
+ * or an empty array when the field is absent / malformed. Filtering by
1159
+ * file existence is the caller's responsibility.
1160
+ */
1161
+ function readPkgSidecarPathsFromJson(pkgJson) {
1162
+ if (!pkgJson)
1163
+ return [];
1164
+ const hinMil = pkgJson['hinmil'];
1165
+ if (!hinMil || typeof hinMil !== 'object')
1166
+ return [];
1167
+ const raw = hinMil.sidecars;
1168
+ if (typeof raw === 'string')
1169
+ return [raw];
1170
+ if (Array.isArray(raw))
1171
+ return raw.filter((x) => typeof x === 'string');
1172
+ return [];
1173
+ }
1174
+ /**
1175
+ * Read the `hinmil.globals` field from an already-parsed package.json.
1176
+ * Returns the relative paths (always an array). A non-array value is
1177
+ * rejected with a warning — library authors must use `"globals": ["..."]`.
1178
+ */
1179
+ function readPkgGlobalsFromJson(pkgJson, pkgJsonPath = null, logger = NOOP_LOGGER) {
1180
+ if (!pkgJson)
1181
+ return [];
1182
+ const hinMil = pkgJson['hinmil'];
1183
+ if (!hinMil || typeof hinMil !== 'object')
1184
+ return [];
1185
+ const raw = hinMil.globals;
1186
+ if (raw === undefined || raw === null)
1187
+ return [];
1188
+ if (Array.isArray(raw))
1189
+ return raw.filter((x) => typeof x === 'string');
1190
+ const loc = pkgJsonPath ? ` in ${pkgJsonPath}` : '';
1191
+ logger.warn(`[hinmil] 'hinmil.globals'${loc} must be an array of paths (got ${typeof raw}); ignoring.`);
1192
+ return [];
1193
+ }
1194
+ /**
1195
+ * Walk up from `entryPath` to the nearest `package.json` and collect every
1196
+ * sidecar declared in its `hinmil.sidecars` field. The field may be a single
1197
+ * string or an array of strings — entries are resolved relative to the
1198
+ * `package.json` directory. Missing files are silently skipped. Order
1199
+ * is preserved: when consumers merge the results, later entries should
1200
+ * override earlier ones.
1201
+ */
1202
+ function findHmSidecarPaths(entryPath) {
1203
+ let dir = path.dirname(entryPath);
1204
+ while (true) {
1205
+ const pkgJsonPath = path.join(dir, 'package.json');
1206
+ const pkgJson = (0, fsProbe_1.readJsonCached)(pkgJsonPath);
1207
+ if (pkgJson === null)
1208
+ return []; // malformed package.json
1209
+ if (pkgJson !== undefined) {
1210
+ const out = [];
1211
+ for (const rel of readPkgSidecarPathsFromJson(pkgJson)) {
1212
+ const sidecar = path.resolve(dir, rel);
1213
+ if ((0, fsProbe_1.isFile)(sidecar))
1214
+ out.push(sidecar); // declared but missing → skipped
1215
+ }
1216
+ return out;
1217
+ }
1218
+ const parent = path.dirname(dir);
1219
+ if (parent === dir)
1220
+ return [];
1221
+ dir = parent;
1222
+ }
1223
+ }
1224
+ /**
1225
+ * Walk up from `entryPath` to the nearest `package.json` and return the
1226
+ * package directory plus its parsed JSON. Returns null when no
1227
+ * `package.json` is found.
1228
+ */
1229
+ function findPackageJson(entryPath) {
1230
+ let dir = path.dirname(entryPath);
1231
+ while (true) {
1232
+ const pkgJsonPath = path.join(dir, 'package.json');
1233
+ const pkgJson = (0, fsProbe_1.readJsonCached)(pkgJsonPath);
1234
+ if (pkgJson === null)
1235
+ return null; // malformed package.json
1236
+ if (pkgJson !== undefined)
1237
+ return { pkgDir: dir, pkgJson };
1238
+ const parent = path.dirname(dir);
1239
+ if (parent === dir)
1240
+ return null;
1241
+ dir = parent;
1242
+ }
1243
+ }
1244
+ /**
1245
+ * Resolve the absolute paths of a package's `hinmil.globals` files.
1246
+ * Returns an empty array when the package declares no globals. Each
1247
+ * declared entry must point at an existing file; unresolvable entries
1248
+ * are warned about and skipped.
1249
+ */
1250
+ function findPackageGlobalsPaths(entryPath, logger = NOOP_LOGGER) {
1251
+ const found = findPackageJson(entryPath);
1252
+ if (!found)
1253
+ return [];
1254
+ const pkgJsonPath = path.join(found.pkgDir, 'package.json');
1255
+ const rels = readPkgGlobalsFromJson(found.pkgJson, pkgJsonPath, logger);
1256
+ const out = [];
1257
+ for (const rel of rels) {
1258
+ const abs = path.resolve(found.pkgDir, rel);
1259
+ if ((0, fsProbe_1.isFile)(abs)) {
1260
+ out.push(abs);
1261
+ continue;
1262
+ }
1263
+ logger.warn(`[hinmil] 'hinmil.globals' entry '${rel}' in ${pkgJsonPath} does not exist; skipping.`);
1264
+ }
1265
+ return out;
1266
+ }
1267
+ /** Backward-compatible single-result helper: returns the first sidecar, or null. */
1268
+ function findHmSidecarPath(entryPath) {
1269
+ const all = findHmSidecarPaths(entryPath);
1270
+ return all.length > 0 ? all[0] : null;
1271
+ }
1272
+ function loadHmSidecar(entryPath, logger = NOOP_LOGGER) {
1273
+ const paths = findHmSidecarPaths(entryPath);
1274
+ if (paths.length === 0)
1275
+ return null;
1276
+ const merged = new Map();
1277
+ let any = false;
1278
+ for (const p of paths) {
1279
+ const m = loadHmFile(p, logger);
1280
+ if (!m)
1281
+ continue;
1282
+ any = true;
1283
+ for (const [k, v] of m)
1284
+ merged.set(k, v); // later overrides earlier
1285
+ }
1286
+ return any ? merged : null;
1287
+ }
1288
+ // ---------------------------------------------------------------------------
1289
+ // Bare specifier helpers (re-exported for use by the import resolver)
1290
+ // ---------------------------------------------------------------------------
1291
+ /** True for an import specifier that targets a node_modules package. */
1292
+ function isBareSpecifier(specifier) {
1293
+ if (!specifier)
1294
+ return false;
1295
+ if (specifier.startsWith('.'))
1296
+ return false;
1297
+ if (specifier.startsWith('/'))
1298
+ return false;
1299
+ if (path.isAbsolute(specifier))
1300
+ return false;
1301
+ return true;
1302
+ }
1303
+ /** Public re-export of the internal `splitBareSpecifier` helper. */
1304
+ function getBarePackageName(specifier) {
1305
+ return splitBareSpecifier(specifier)[0];
1306
+ }
1307
+ /**
1308
+ * Candidate conventional stub paths (relative to `<typesDir>/`) for a bare
1309
+ * specifier, most specific first. Deep imports of CJS utility packages
1310
+ * (`import RTask from "pkg/RTask/index.js"`) need a stub describing the
1311
+ * SUBPATH module's exports — the package-level `<pkg>.hm` stub describes
1312
+ * the root module and is only the last-resort fallback:
1313
+ *
1314
+ * `pkg/RTask/index.js` → [`pkg/RTask/index.hm`, `pkg/RTask.hm`, `pkg.hm`]
1315
+ * `pkg/RTask` → [`pkg/RTask.hm`, `pkg/RTask/index.hm`, `pkg.hm`]
1316
+ * `pkg` → [`pkg.hm`]
1317
+ */
1318
+ function conventionalStubRelPaths(specifier) {
1319
+ const [pkg, sub] = splitBareSpecifier(specifier);
1320
+ const out = [];
1321
+ if (sub !== '.') {
1322
+ const subRel = sub.slice(2).replace(/\.(?:m|c)?jsx?$/i, '');
1323
+ out.push(path.join(pkg, subRel + '.hm'));
1324
+ if (subRel.endsWith('/index')) {
1325
+ out.push(path.join(pkg, subRel.slice(0, -'/index'.length) + '.hm'));
1326
+ }
1327
+ else {
1328
+ out.push(path.join(pkg, subRel, 'index.hm'));
1329
+ }
1330
+ }
1331
+ out.push(pkg + '.hm');
1332
+ return out;
1333
+ }
1334
+ /**
1335
+ * Derive the conventional `@hm/*` companion package name for a given
1336
+ * bare package specifier. Mirrors the DefinitelyTyped (`@types/*`) scheme:
1337
+ * `lodash` → `@hm/lodash`
1338
+ * `@scope/pkg` → `@hm/scope__pkg`
1339
+ */
1340
+ function hmCompanionPackageName(pkgName) {
1341
+ if (pkgName.startsWith('@')) {
1342
+ return '@hm/' + pkgName.slice(1).replace('/', '__');
1343
+ }
1344
+ return '@hm/' + pkgName;
1345
+ }
1346
+ // ---------------------------------------------------------------------------
1347
+ // Inline package annotations
1348
+ // ---------------------------------------------------------------------------
1349
+ //
1350
+ // A library author may ship HM signatures inline next to JS definitions
1351
+ // (e.g. `// limit :: Number -> Limit` immediately above `export const
1352
+ // limit = ...`) instead of a `.hm` sidecar. Consumers picking the
1353
+ // package up via `import { limit } from "pkg"` should see those
1354
+ // signatures automatically.
1355
+ //
1356
+ // Strategy: BFS from the package's JS entry, following `import` /
1357
+ // `export ... from` / `require` edges, staying inside `pkgRoot`, and
1358
+ // merging all annotations found.
1359
+ /** Hard cap on visited files per scan to keep cost bounded. */
1360
+ exports.INLINE_PACKAGE_MAX_FILES = 256;
1361
+ const inlinePackageCache = new Map();
1362
+ /** Package roots known to ship inline `// name :: Type` annotations. */
1363
+ const inlineAnnotatedPackages = new Set();
1364
+ /** Max files probed per lookup by {@link isInlineAnnotatedPackageModule}. */
1365
+ const INLINE_ANNOTATED_PROBE_FILES = 16;
1366
+ /**
1367
+ * Runtime export names per `require` target, as read by
1368
+ * `supplementWithRuntimeExports` (importContext.ts); `null` = the module
1369
+ * could not be loaded. Without this cache every import of a package re-ran
1370
+ * the `require` attempt and — for a package whose `main` is missing — logged
1371
+ * the same warning once per importing module. Cleared together with the
1372
+ * inline-package cache (package changes on disk).
1373
+ */
1374
+ exports.runtimeExportNamesCache = new Map();
1375
+ function clearInlinePackageCache() {
1376
+ inlinePackageCache.clear();
1377
+ inlineAnnotatedPackages.clear();
1378
+ exports.runtimeExportNamesCache.clear();
1379
+ }
1380
+ /**
1381
+ * Does the package that owns `targetPath` (a JS module under node_modules)
1382
+ * ship inline HM annotations in its own source? Such a package (e.g. a curried FP library,
1383
+ * whose buble build keeps every `// name :: Type` comment) has opted into
1384
+ * hinmil: its modules are inferred exactly like local source, so CommonJS
1385
+ * export shapes (`module.exports = _RTask` + dotted statics, re-export
1386
+ * barrels `module.exports = { RTask: require ("./RTask") }`) resolve
1387
+ * per module instead of through the name-based inline scan.
1388
+ *
1389
+ * Probes the target and a few same-package modules it requires (a barrel
1390
+ * `index.js` usually has no annotations itself). Positive answers are
1391
+ * cached per package root.
1392
+ */
1393
+ function isInlineAnnotatedPackageModule(targetPath) {
1394
+ if (targetPath.endsWith('.hm'))
1395
+ return false;
1396
+ const pkgRoot = inlinePkgRoot(targetPath);
1397
+ if (!pkgRoot)
1398
+ return false;
1399
+ if (inlineAnnotatedPackages.has(pkgRoot))
1400
+ return true;
1401
+ const { extractAnnotations } = require('../commentParser');
1402
+ const queue = [path.resolve(targetPath)];
1403
+ const seen = new Set();
1404
+ while (queue.length > 0 && seen.size < INLINE_ANNOTATED_PROBE_FILES) {
1405
+ const cur = queue.shift();
1406
+ if (seen.has(cur))
1407
+ continue;
1408
+ seen.add(cur);
1409
+ let source;
1410
+ try {
1411
+ source = fs.readFileSync(cur, 'utf-8');
1412
+ }
1413
+ catch {
1414
+ continue;
1415
+ }
1416
+ // Cheap pre-filter before the real annotation parse.
1417
+ if (/^[ \t]*(?:\/\/|\*)[ \t]*[\w$]+(?:[#.][\w$]+)?[ \t]*::[ \t]/m.test(source)
1418
+ && extractAnnotations(source).some(a => !!a.name && !!a.scheme)) {
1419
+ inlineAnnotatedPackages.add(pkgRoot);
1420
+ return true;
1421
+ }
1422
+ for (const spec of extractAllModuleSpecifiers(source)) {
1423
+ if (!spec.startsWith('.'))
1424
+ continue;
1425
+ const next = resolveWithExtensions(path.resolve(path.dirname(cur), spec));
1426
+ if (next && path.resolve(next).startsWith(pkgRoot + path.sep))
1427
+ queue.push(path.resolve(next));
1428
+ }
1429
+ }
1430
+ return false;
1431
+ }
1432
+ /**
1433
+ * Evict every inline-annotation scan whose cache key starts with the
1434
+ * given package root. Use this instead of {@link clearInlinePackageCache}
1435
+ * when a single package's `.hm` sidecar changes — wiping the whole map
1436
+ * forces every other imported package to re-do its BFS scan on the next
1437
+ * resolver call (up to {@link INLINE_PACKAGE_MAX_FILES} files each),
1438
+ * which dominates cold-hover latency in workspaces with several heavy
1439
+ * dependencies.
1440
+ *
1441
+ * The cache key shape is `${pkgRoot}\0${effectiveEntry}` (see
1442
+ * {@link collectInlinePackageAnnotations}), so a prefix match on
1443
+ * `${pkgRoot}\0` cleanly targets the package.
1444
+ */
1445
+ function clearInlinePackageCacheForPackage(pkgRoot) {
1446
+ inlineAnnotatedPackages.delete(pkgRoot);
1447
+ const prefix = pkgRoot + '\0';
1448
+ for (const key of inlinePackageCache.keys()) {
1449
+ if (key.startsWith(prefix))
1450
+ inlinePackageCache.delete(key);
1451
+ }
1452
+ }
1453
+ /**
1454
+ * Extract every module specifier referenced by a JS source. Handles:
1455
+ * - `import x from '...'`
1456
+ * - `import { x } from '...'`
1457
+ * - `export { x } from '...'`
1458
+ * - `export * from '...'`
1459
+ * - `require('...')` (call expressions, anywhere)
1460
+ * Uses the parser when possible and falls back to a permissive regex when
1461
+ * the parse fails (e.g. flow / TS-only syntax).
1462
+ */
1463
+ function extractAllModuleSpecifiers(source) {
1464
+ const seen = new Set();
1465
+ try {
1466
+ // eslint-disable-next-line @typescript-eslint/no-require-imports
1467
+ const walk = require('../walking');
1468
+ // eslint-disable-next-line @typescript-eslint/no-require-imports
1469
+ const { parseStrict } = require('../parsing');
1470
+ const ast = parseStrict(source);
1471
+ walk.simple(ast, {
1472
+ ImportDeclaration(node) {
1473
+ if (typeof node.source?.value === 'string')
1474
+ seen.add(node.source.value);
1475
+ },
1476
+ ExportNamedDeclaration(node) {
1477
+ if (node.source && typeof node.source.value === 'string')
1478
+ seen.add(node.source.value);
1479
+ },
1480
+ ExportAllDeclaration(node) {
1481
+ if (typeof node.source?.value === 'string')
1482
+ seen.add(node.source.value);
1483
+ },
1484
+ CallExpression(node) {
1485
+ if (node.callee?.type === 'Identifier' && node.callee.name === 'require'
1486
+ && node.arguments?.length >= 1
1487
+ && node.arguments[0].type === 'Literal'
1488
+ && typeof node.arguments[0].value === 'string') {
1489
+ seen.add(node.arguments[0].value);
1490
+ }
1491
+ },
1492
+ });
1493
+ }
1494
+ catch {
1495
+ const re = /(?:import|from|require\s*\()\s*['"]([^'"]+)['"]/g;
1496
+ let m;
1497
+ while ((m = re.exec(source)) !== null)
1498
+ seen.add(m[1]);
1499
+ }
1500
+ return [...seen];
1501
+ }
1502
+ /**
1503
+ * Given an absolute path inside a package, walk up to the package root
1504
+ * (the directory containing the nearest `package.json`). Returns null
1505
+ * when no `package.json` is found above `entryPath`.
1506
+ */
1507
+ function inlinePkgRoot(entryPath) {
1508
+ const found = findPackageJson(entryPath);
1509
+ return found ? found.pkgDir : null;
1510
+ }
1511
+ /**
1512
+ * If `entryPath` resolves to a `.hm` sidecar (or anything outside the
1513
+ * package's JS source tree), translate to the JS entry derived from
1514
+ * `main` / `module` so the inline-scan starts at real JavaScript.
1515
+ */
1516
+ function effectiveJsEntry(entryPath) {
1517
+ if (!entryPath.endsWith('.hm'))
1518
+ return entryPath;
1519
+ const found = findPackageJson(entryPath);
1520
+ if (!found)
1521
+ return null;
1522
+ for (const field of ['main', 'module']) {
1523
+ const v = found.pkgJson[field];
1524
+ if (typeof v === 'string') {
1525
+ const resolved = resolveWithExtensions(path.resolve(found.pkgDir, v));
1526
+ if (resolved)
1527
+ return resolved;
1528
+ }
1529
+ }
1530
+ // Fallback: index.{js,mjs,cjs}
1531
+ return resolveWithExtensions(path.join(found.pkgDir, 'index'));
1532
+ }
1533
+ /**
1534
+ * BFS the JS module graph rooted at `entryPath`, staying inside the
1535
+ * package root, collecting inline `// Name :: Type` annotations. Returns
1536
+ * `null` when nothing was found (so callers can short-circuit). Results
1537
+ * are cached by `pkgRoot + entry`.
1538
+ */
1539
+ function collectInlinePackageAnnotations(entryPath, logger = NOOP_LOGGER) {
1540
+ const effectiveEntry = effectiveJsEntry(entryPath);
1541
+ if (!effectiveEntry)
1542
+ return null;
1543
+ const pkgRoot = inlinePkgRoot(effectiveEntry);
1544
+ if (!pkgRoot)
1545
+ return null;
1546
+ const cacheKey = pkgRoot + '\0' + effectiveEntry;
1547
+ const cached = inlinePackageCache.get(cacheKey);
1548
+ if (cached !== undefined)
1549
+ return cached;
1550
+ const exportsMap = new Map();
1551
+ const methodSourceParts = [];
1552
+ const inlineRawSignatures = new Map();
1553
+ const nameToSource = new Map();
1554
+ const visited = new Set();
1555
+ const queue = [effectiveEntry];
1556
+ let hadAnyAnnotation = false;
1557
+ const { mergeOverloadSchemes } = require('../hm/env');
1558
+ const { extractAnnotations, extractTypeDirectives, extractAliasExtensions } = require('../commentParser');
1559
+ // Merge another scan (reached via `::types <bare-pkg>`) into the current
1560
+ // accumulators. First writer wins on name collisions so the directly-
1561
+ // scanned package's exports take precedence over chained sources.
1562
+ const mergeChainedScan = (other) => {
1563
+ for (const [n, s] of other.exports)
1564
+ if (!exportsMap.has(n))
1565
+ exportsMap.set(n, s);
1566
+ if (other.methodSource)
1567
+ methodSourceParts.push(other.methodSource);
1568
+ for (const [n, raw] of other.inlineRawSignatures) {
1569
+ if (!inlineRawSignatures.has(n))
1570
+ inlineRawSignatures.set(n, raw);
1571
+ }
1572
+ for (const [n, p] of other.nameToSource) {
1573
+ if (!nameToSource.has(n))
1574
+ nameToSource.set(n, p);
1575
+ }
1576
+ for (const f of other.visitedFiles)
1577
+ visited.add(f);
1578
+ if (other.exports.size > 0 || other.inlineRawSignatures.size > 0 || other.methodSource.length > 0) {
1579
+ hadAnyAnnotation = true;
1580
+ }
1581
+ };
1582
+ // Process a `.hm` file reached explicitly via `// ::types ./file.hm`.
1583
+ // Inline scans normally only walk JS, but an explicit `::types` directive
1584
+ // is the library author's opt-in to pull in a sidecar's signatures.
1585
+ const mergeHmFile = (hmPath) => {
1586
+ if (visited.has(hmPath))
1587
+ return;
1588
+ visited.add(hmPath);
1589
+ let hmSrc;
1590
+ try {
1591
+ hmSrc = fs.readFileSync(hmPath, 'utf-8');
1592
+ }
1593
+ catch (e) {
1594
+ logger.warn(`[hinmil] inline scan failed to read '${hmPath}': ${e instanceof Error ? e.message : String(e)}`);
1595
+ return;
1596
+ }
1597
+ for (const [n, s] of parseHmSource(hmSrc, { wrap: true })) {
1598
+ if (!exportsMap.has(n))
1599
+ exportsMap.set(n, s);
1600
+ }
1601
+ methodSourceParts.push(wrapHmSource(hmSrc));
1602
+ for (const [n, raw] of parseHmSourceRaw(hmSrc)) {
1603
+ if (!inlineRawSignatures.has(n))
1604
+ inlineRawSignatures.set(n, raw);
1605
+ if (!nameToSource.has(n))
1606
+ nameToSource.set(n, hmPath);
1607
+ hadAnyAnnotation = true;
1608
+ }
1609
+ };
1610
+ while (queue.length > 0 && visited.size < exports.INLINE_PACKAGE_MAX_FILES) {
1611
+ const cur = queue.shift();
1612
+ if (visited.has(cur))
1613
+ continue;
1614
+ visited.add(cur);
1615
+ let source;
1616
+ try {
1617
+ source = fs.readFileSync(cur, 'utf-8');
1618
+ }
1619
+ catch (e) {
1620
+ logger.warn(`[hinmil] inline scan failed to read '${cur}': ${e instanceof Error ? e.message : String(e)}`);
1621
+ continue;
1622
+ }
1623
+ methodSourceParts.push(source);
1624
+ // Top-level `Name :: Type` annotations (JS source, no wrap) — used to
1625
+ // resolve consumer-side imports of this package.
1626
+ for (const [name, scheme] of parseHmSource(source, { wrap: false })) {
1627
+ const existing = exportsMap.get(name);
1628
+ if (existing && !name.includes('#') && !name.includes('.')) {
1629
+ exportsMap.set(name, mergeOverloadSchemes(existing, scheme));
1630
+ }
1631
+ else {
1632
+ exportsMap.set(name, scheme);
1633
+ }
1634
+ }
1635
+ // Capture verbatim raw signature text for hover and origin file for
1636
+ // type-definition navigation. Raw JS source is already inside `// `
1637
+ // comments, so `extractAnnotations` runs directly.
1638
+ for (const ann of extractAnnotations(source)) {
1639
+ if (!ann.name || !ann.raw)
1640
+ continue;
1641
+ hadAnyAnnotation = true;
1642
+ if (ann.name.includes('#') || ann.name.includes('.'))
1643
+ continue;
1644
+ const prev = inlineRawSignatures.get(ann.name);
1645
+ inlineRawSignatures.set(ann.name, prev ? `${prev}\n${ann.name} :: ${ann.raw}` : ann.raw);
1646
+ if (!nameToSource.has(ann.name))
1647
+ nameToSource.set(ann.name, cur);
1648
+ }
1649
+ if (!hadAnyAnnotation && extractAliasExtensions(source).length > 0) {
1650
+ hadAnyAnnotation = true;
1651
+ }
1652
+ // Follow re-export / import / require edges, restricted to pkgRoot.
1653
+ for (const spec of extractAllModuleSpecifiers(source)) {
1654
+ // Skip bare specifiers — only follow same-package paths.
1655
+ if (!spec.startsWith('.') && !spec.startsWith('/'))
1656
+ continue;
1657
+ const next = resolveWithExtensions(path.resolve(path.dirname(cur), spec));
1658
+ if (!next)
1659
+ continue;
1660
+ const nextAbs = path.resolve(next);
1661
+ // Containment check: stay inside the package root.
1662
+ if (!nextAbs.startsWith(pkgRoot + path.sep) && nextAbs !== pkgRoot)
1663
+ continue;
1664
+ if (visited.has(nextAbs))
1665
+ continue;
1666
+ queue.push(nextAbs);
1667
+ }
1668
+ // Follow `// ::types <specifier>` directives. These are an explicit
1669
+ // opt-in by the library author, so containment is relaxed: relative
1670
+ // paths may point at sibling `.hm` files, and bare specifiers chain
1671
+ // into other packages' inline scans (or their sidecars, transitively).
1672
+ for (const spec of extractTypeDirectives(source)) {
1673
+ if (spec.startsWith('.') || spec.startsWith('/')) {
1674
+ const resolved = resolveWithExtensions(path.resolve(path.dirname(cur), spec));
1675
+ if (!resolved)
1676
+ continue;
1677
+ const resolvedAbs = path.resolve(resolved);
1678
+ if (visited.has(resolvedAbs))
1679
+ continue;
1680
+ if (resolvedAbs.endsWith('.hm')) {
1681
+ mergeHmFile(resolvedAbs);
1682
+ }
1683
+ else {
1684
+ queue.push(resolvedAbs);
1685
+ }
1686
+ }
1687
+ else {
1688
+ // Bare package: recurse into its inline scan (cached) and merge.
1689
+ const otherEntry = resolveNodeModulePackage(spec, path.dirname(cur));
1690
+ if (!otherEntry)
1691
+ continue;
1692
+ const otherScan = collectInlinePackageAnnotations(otherEntry, logger);
1693
+ if (otherScan)
1694
+ mergeChainedScan(otherScan);
1695
+ }
1696
+ }
1697
+ }
1698
+ if (!hadAnyAnnotation) {
1699
+ inlinePackageCache.set(cacheKey, null);
1700
+ return null;
1701
+ }
1702
+ const scan = {
1703
+ exports: exportsMap,
1704
+ methodSource: methodSourceParts.join('\n'),
1705
+ inlineRawSignatures,
1706
+ nameToSource,
1707
+ visitedFiles: [...visited],
1708
+ };
1709
+ inlinePackageCache.set(cacheKey, scan);
1710
+ return scan;
1711
+ }
1712
+ //# sourceMappingURL=files.js.map