@nifrajs/cli 5.0.0 → 5.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 (296) hide show
  1. package/CHANGELOG.md +3211 -0
  2. package/README.md +10 -2
  3. package/dist/agent-files.d.ts +19 -11
  4. package/dist/agent-files.d.ts.map +1 -1
  5. package/dist/agent-files.js +26 -18
  6. package/dist/agent-files.js.map +1 -1
  7. package/dist/assure-hydration.d.ts.map +1 -1
  8. package/dist/assure-hydration.js +5 -2
  9. package/dist/assure-hydration.js.map +1 -1
  10. package/dist/assure.d.ts +12 -2
  11. package/dist/assure.d.ts.map +1 -1
  12. package/dist/assure.js +73 -9
  13. package/dist/assure.js.map +1 -1
  14. package/dist/capabilities-tool.d.ts.map +1 -1
  15. package/dist/capabilities-tool.js +152 -49
  16. package/dist/capabilities-tool.js.map +1 -1
  17. package/dist/check-diagnostics.d.ts +7 -0
  18. package/dist/check-diagnostics.d.ts.map +1 -1
  19. package/dist/check-diagnostics.js +3 -0
  20. package/dist/check-diagnostics.js.map +1 -1
  21. package/dist/check-scan.d.ts +8 -2
  22. package/dist/check-scan.d.ts.map +1 -1
  23. package/dist/check-scan.js +49 -13
  24. package/dist/check-scan.js.map +1 -1
  25. package/dist/check.d.ts.map +1 -1
  26. package/dist/check.js +91 -45
  27. package/dist/check.js.map +1 -1
  28. package/dist/cli.d.ts +2 -0
  29. package/dist/cli.d.ts.map +1 -1
  30. package/dist/cli.js +128 -59
  31. package/dist/cli.js.map +1 -1
  32. package/dist/client-module.d.ts +5 -3
  33. package/dist/client-module.d.ts.map +1 -1
  34. package/dist/client-module.js +34 -10
  35. package/dist/client-module.js.map +1 -1
  36. package/dist/command-catalog.d.ts +9 -1
  37. package/dist/command-catalog.d.ts.map +1 -1
  38. package/dist/command-catalog.js +75 -26
  39. package/dist/command-catalog.js.map +1 -1
  40. package/dist/dev-bun-config.d.ts +6 -3
  41. package/dist/dev-bun-config.d.ts.map +1 -1
  42. package/dist/dev-bun-config.js +13 -10
  43. package/dist/dev-bun-config.js.map +1 -1
  44. package/dist/dev-feed-tool.d.ts +19 -1
  45. package/dist/dev-feed-tool.d.ts.map +1 -1
  46. package/dist/dev-feed-tool.js +114 -0
  47. package/dist/dev-feed-tool.js.map +1 -1
  48. package/dist/doctor.d.ts +15 -1
  49. package/dist/doctor.d.ts.map +1 -1
  50. package/dist/doctor.js +79 -61
  51. package/dist/doctor.js.map +1 -1
  52. package/dist/fix-recipes.d.ts +2 -0
  53. package/dist/fix-recipes.d.ts.map +1 -1
  54. package/dist/fix-recipes.js +93 -12
  55. package/dist/fix-recipes.js.map +1 -1
  56. package/dist/i18n-check.d.ts +11 -1
  57. package/dist/i18n-check.d.ts.map +1 -1
  58. package/dist/i18n-check.js +170 -17
  59. package/dist/i18n-check.js.map +1 -1
  60. package/dist/init-agents.d.ts +60 -4
  61. package/dist/init-agents.d.ts.map +1 -1
  62. package/dist/init-agents.js +196 -33
  63. package/dist/init-agents.js.map +1 -1
  64. package/dist/internal/config-paths.d.ts +16 -0
  65. package/dist/internal/config-paths.d.ts.map +1 -0
  66. package/dist/internal/config-paths.js +124 -0
  67. package/dist/internal/config-paths.js.map +1 -0
  68. package/dist/internal/installed-package.d.ts +4 -0
  69. package/dist/internal/installed-package.d.ts.map +1 -0
  70. package/dist/internal/installed-package.js +17 -0
  71. package/dist/internal/installed-package.js.map +1 -0
  72. package/dist/internal/project-specifiers.d.ts +14 -1
  73. package/dist/internal/project-specifiers.d.ts.map +1 -1
  74. package/dist/internal/project-specifiers.js +63 -16
  75. package/dist/internal/project-specifiers.js.map +1 -1
  76. package/dist/internal/source-facts.d.ts +12 -1
  77. package/dist/internal/source-facts.d.ts.map +1 -1
  78. package/dist/internal/source-facts.js +117 -5
  79. package/dist/internal/source-facts.js.map +1 -1
  80. package/dist/internal/typescript-import.d.ts.map +1 -1
  81. package/dist/internal/typescript-import.js +5 -3
  82. package/dist/internal/typescript-import.js.map +1 -1
  83. package/dist/internal/workspace-packages.d.ts +22 -0
  84. package/dist/internal/workspace-packages.d.ts.map +1 -0
  85. package/dist/internal/workspace-packages.js +215 -0
  86. package/dist/internal/workspace-packages.js.map +1 -0
  87. package/dist/introspect.d.ts +9 -0
  88. package/dist/introspect.d.ts.map +1 -1
  89. package/dist/introspect.js +32 -1
  90. package/dist/introspect.js.map +1 -1
  91. package/dist/levels-tool.d.ts.map +1 -1
  92. package/dist/levels-tool.js +5 -8
  93. package/dist/levels-tool.js.map +1 -1
  94. package/dist/load.d.ts +9 -4
  95. package/dist/load.d.ts.map +1 -1
  96. package/dist/load.js +32 -3
  97. package/dist/load.js.map +1 -1
  98. package/dist/lock-links.d.ts +42 -0
  99. package/dist/lock-links.d.ts.map +1 -0
  100. package/dist/lock-links.js +144 -0
  101. package/dist/lock-links.js.map +1 -0
  102. package/dist/mcp-context.d.ts.map +1 -1
  103. package/dist/mcp-context.js +6 -21
  104. package/dist/mcp-context.js.map +1 -1
  105. package/dist/mcp-delegate.d.ts +2 -2
  106. package/dist/mcp-delegate.d.ts.map +1 -1
  107. package/dist/mcp-delegate.js +19 -7
  108. package/dist/mcp-delegate.js.map +1 -1
  109. package/dist/mcp-exec.d.ts +1 -0
  110. package/dist/mcp-exec.d.ts.map +1 -1
  111. package/dist/mcp-exec.js +13 -5
  112. package/dist/mcp-exec.js.map +1 -1
  113. package/dist/mcp-http.js +1 -1
  114. package/dist/mcp-io.d.ts +13 -0
  115. package/dist/mcp-io.d.ts.map +1 -1
  116. package/dist/mcp-io.js +23 -0
  117. package/dist/mcp-io.js.map +1 -1
  118. package/dist/mcp-path.d.ts +2 -1
  119. package/dist/mcp-path.d.ts.map +1 -1
  120. package/dist/mcp-path.js +9 -24
  121. package/dist/mcp-path.js.map +1 -1
  122. package/dist/mcp-root.d.ts +6 -4
  123. package/dist/mcp-root.d.ts.map +1 -1
  124. package/dist/mcp-root.js +12 -8
  125. package/dist/mcp-root.js.map +1 -1
  126. package/dist/mcp.d.ts.map +1 -1
  127. package/dist/mcp.js +40 -17
  128. package/dist/mcp.js.map +1 -1
  129. package/dist/migrate-layout.d.ts +41 -1
  130. package/dist/migrate-layout.d.ts.map +1 -1
  131. package/dist/migrate-layout.js +1729 -236
  132. package/dist/migrate-layout.js.map +1 -1
  133. package/dist/output-schemas.d.ts +34 -0
  134. package/dist/output-schemas.d.ts.map +1 -1
  135. package/dist/output-schemas.js +132 -21
  136. package/dist/output-schemas.js.map +1 -1
  137. package/dist/project-path.d.ts +6 -0
  138. package/dist/project-path.d.ts.map +1 -1
  139. package/dist/project-path.js +48 -14
  140. package/dist/project-path.js.map +1 -1
  141. package/dist/project-site.d.ts +7 -0
  142. package/dist/project-site.d.ts.map +1 -0
  143. package/dist/project-site.js +19 -0
  144. package/dist/project-site.js.map +1 -0
  145. package/dist/recipes/4.0.0.d.ts.map +1 -1
  146. package/dist/recipes/4.0.0.js +2 -0
  147. package/dist/recipes/4.0.0.js.map +1 -1
  148. package/dist/recipes/5.1.0.d.ts +9 -0
  149. package/dist/recipes/5.1.0.d.ts.map +1 -0
  150. package/dist/recipes/5.1.0.js +22 -0
  151. package/dist/recipes/5.1.0.js.map +1 -0
  152. package/dist/recipes/5.2.0.d.ts +10 -0
  153. package/dist/recipes/5.2.0.d.ts.map +1 -0
  154. package/dist/recipes/5.2.0.js +32 -0
  155. package/dist/recipes/5.2.0.js.map +1 -0
  156. package/dist/recipes/index.d.ts +3 -0
  157. package/dist/recipes/index.d.ts.map +1 -1
  158. package/dist/recipes/index.js +7 -0
  159. package/dist/recipes/index.js.map +1 -1
  160. package/dist/release-verification.d.ts +5 -0
  161. package/dist/release-verification.d.ts.map +1 -1
  162. package/dist/release-verification.js +14 -0
  163. package/dist/release-verification.js.map +1 -1
  164. package/dist/review.d.ts.map +1 -1
  165. package/dist/review.js +7 -0
  166. package/dist/review.js.map +1 -1
  167. package/dist/rule-explain.d.ts +26 -0
  168. package/dist/rule-explain.d.ts.map +1 -0
  169. package/dist/rule-explain.js +49 -0
  170. package/dist/rule-explain.js.map +1 -0
  171. package/dist/rules/codes.d.ts +5 -1
  172. package/dist/rules/codes.d.ts.map +1 -1
  173. package/dist/rules/codes.js +5 -1
  174. package/dist/rules/codes.js.map +1 -1
  175. package/dist/rules/contract-visibility.d.ts.map +1 -1
  176. package/dist/rules/contract-visibility.js +93 -21
  177. package/dist/rules/contract-visibility.js.map +1 -1
  178. package/dist/rules/data-guard.d.ts +6 -0
  179. package/dist/rules/data-guard.d.ts.map +1 -1
  180. package/dist/rules/data-guard.js +37 -0
  181. package/dist/rules/data-guard.js.map +1 -1
  182. package/dist/rules/explanations.d.ts +14 -0
  183. package/dist/rules/explanations.d.ts.map +1 -0
  184. package/dist/rules/explanations.js +316 -0
  185. package/dist/rules/explanations.js.map +1 -0
  186. package/dist/rules/legacy.d.ts.map +1 -1
  187. package/dist/rules/legacy.js +44 -2
  188. package/dist/rules/legacy.js.map +1 -1
  189. package/dist/rules/merge-auth.d.ts +12 -0
  190. package/dist/rules/merge-auth.d.ts.map +1 -0
  191. package/dist/rules/merge-auth.js +52 -0
  192. package/dist/rules/merge-auth.js.map +1 -0
  193. package/dist/rules/pages.d.ts +56 -3
  194. package/dist/rules/pages.d.ts.map +1 -1
  195. package/dist/rules/pages.js +412 -23
  196. package/dist/rules/pages.js.map +1 -1
  197. package/dist/rules/routes.d.ts +3 -2
  198. package/dist/rules/routes.d.ts.map +1 -1
  199. package/dist/rules/routes.js +4 -3
  200. package/dist/rules/routes.js.map +1 -1
  201. package/dist/rules/security.d.ts +3 -2
  202. package/dist/rules/security.d.ts.map +1 -1
  203. package/dist/rules/security.js +42 -11
  204. package/dist/rules/security.js.map +1 -1
  205. package/dist/rules/zones.d.ts.map +1 -1
  206. package/dist/rules/zones.js +34 -11
  207. package/dist/rules/zones.js.map +1 -1
  208. package/dist/stylex-migrate.d.ts.map +1 -1
  209. package/dist/stylex-migrate.js +127 -17
  210. package/dist/stylex-migrate.js.map +1 -1
  211. package/dist/test-tool.d.ts.map +1 -1
  212. package/dist/test-tool.js +3 -9
  213. package/dist/test-tool.js.map +1 -1
  214. package/dist/typecheck-coverage.d.ts +11 -0
  215. package/dist/typecheck-coverage.d.ts.map +1 -1
  216. package/dist/typecheck-coverage.js +50 -7
  217. package/dist/typecheck-coverage.js.map +1 -1
  218. package/dist/upgrade.d.ts +57 -6
  219. package/dist/upgrade.d.ts.map +1 -1
  220. package/dist/upgrade.js +247 -19
  221. package/dist/upgrade.js.map +1 -1
  222. package/dist/verification-plan.d.ts.map +1 -1
  223. package/dist/verification-plan.js +7 -2
  224. package/dist/verification-plan.js.map +1 -1
  225. package/dist/version-drift.d.ts.map +1 -1
  226. package/dist/version-drift.js +66 -3
  227. package/dist/version-drift.js.map +1 -1
  228. package/dist/web-app-options.d.ts +1 -1
  229. package/dist/web-app-options.d.ts.map +1 -1
  230. package/dist/web-app-options.js.map +1 -1
  231. package/docs/examples.json +21 -3
  232. package/docs/llms-full.txt +1083 -168
  233. package/docs/types.json +535 -112
  234. package/package.json +13 -12
  235. package/src/agent-files.ts +27 -17
  236. package/src/assure-hydration.ts +5 -1
  237. package/src/assure.ts +99 -11
  238. package/src/capabilities-tool.ts +188 -53
  239. package/src/check-diagnostics.ts +10 -0
  240. package/src/check-scan.ts +65 -12
  241. package/src/check.ts +122 -51
  242. package/src/cli.ts +127 -45
  243. package/src/client-module.ts +45 -9
  244. package/src/command-catalog.ts +92 -28
  245. package/src/dev-bun-config.ts +13 -9
  246. package/src/dev-feed-tool.ts +146 -1
  247. package/src/doctor.ts +102 -66
  248. package/src/fix-recipes.ts +101 -10
  249. package/src/i18n-check.ts +254 -18
  250. package/src/init-agents.ts +225 -44
  251. package/src/internal/config-paths.ts +154 -0
  252. package/src/internal/installed-package.ts +15 -0
  253. package/src/internal/project-specifiers.ts +78 -17
  254. package/src/internal/source-facts.ts +147 -5
  255. package/src/internal/typescript-import.ts +5 -3
  256. package/src/internal/workspace-packages.ts +218 -0
  257. package/src/introspect.ts +39 -1
  258. package/src/levels-tool.ts +7 -9
  259. package/src/load.ts +46 -4
  260. package/src/lock-links.ts +173 -0
  261. package/src/mcp-context.ts +5 -18
  262. package/src/mcp-delegate.ts +22 -10
  263. package/src/mcp-exec.ts +14 -4
  264. package/src/mcp-http.ts +1 -1
  265. package/src/mcp-io.ts +33 -0
  266. package/src/mcp-path.ts +8 -22
  267. package/src/mcp-root.ts +14 -8
  268. package/src/mcp.ts +48 -19
  269. package/src/migrate-layout.ts +1968 -245
  270. package/src/output-schemas.ts +179 -23
  271. package/src/project-path.ts +44 -13
  272. package/src/project-site.ts +18 -0
  273. package/src/recipes/4.0.0.ts +2 -0
  274. package/src/recipes/5.1.0.ts +23 -0
  275. package/src/recipes/5.2.0.ts +33 -0
  276. package/src/recipes/index.ts +7 -0
  277. package/src/release-verification.ts +20 -0
  278. package/src/review.ts +7 -0
  279. package/src/rule-explain.ts +75 -0
  280. package/src/rules/codes.ts +5 -1
  281. package/src/rules/contract-visibility.ts +118 -20
  282. package/src/rules/data-guard.ts +40 -0
  283. package/src/rules/explanations.ts +329 -0
  284. package/src/rules/legacy.ts +46 -2
  285. package/src/rules/merge-auth.ts +55 -0
  286. package/src/rules/pages.ts +486 -25
  287. package/src/rules/routes.ts +4 -3
  288. package/src/rules/security.ts +49 -11
  289. package/src/rules/zones.ts +33 -9
  290. package/src/stylex-migrate.ts +117 -17
  291. package/src/test-tool.ts +3 -9
  292. package/src/typecheck-coverage.ts +51 -6
  293. package/src/upgrade.ts +312 -19
  294. package/src/verification-plan.ts +15 -2
  295. package/src/version-drift.ts +68 -2
  296. package/src/web-app-options.ts +9 -1
@@ -22,6 +22,12 @@ export interface ProjectResolver extends SpecifierResolver {
22
22
  readonly respell: (fromFile: string, specifier: string, file: string) => string | undefined
23
23
  /** The `paths` patterns of the nearest tsconfig at or above `dir`, after its `extends` chain. */
24
24
  readonly pathPatterns: (dir: string) => readonly string[]
25
+ /**
26
+ * Whether the compiler settings for `file` keep an import whose named specifiers are all
27
+ * type-only, as `import {} from "x"` (`verbatimModuleSyntax`). `true` when its tsconfig chain
28
+ * cannot be read, so a scan that trusts the answer keeps the edge.
29
+ */
30
+ readonly keepsTypeOnlyImports: (file: string) => boolean
25
31
  }
26
32
 
27
33
  /** How an alias specifier reached its file: what a rewrite through the same alias has to fit. */
@@ -59,6 +65,25 @@ interface PathsConfig {
59
65
  readonly pathsBase: string
60
66
  readonly paths: ReadonlyArray<readonly [string, readonly string[]]>
61
67
  readonly baseUrl: string | undefined
68
+ /** The {@link IMPORT_EMIT_OPTIONS} the chain sets, later configs winning; `undefined` when part of
69
+ * the chain could not be read. */
70
+ readonly importEmit: Readonly<Record<string, unknown>> | undefined
71
+ }
72
+
73
+ // The options that decide whether an import left with only type specifiers is emitted. The last two
74
+ // are removed in TypeScript 6 but still read by older compilers and bundlers.
75
+ const IMPORT_EMIT_OPTIONS = [
76
+ "verbatimModuleSyntax",
77
+ "importsNotUsedAsValues",
78
+ "preserveValueImports",
79
+ ]
80
+
81
+ /** Whether the next character after whitespace closes an object or array: a scan, not a slice, so a
82
+ * large file with many commas stays linear. */
83
+ function closesNext(code: string, from: number): boolean {
84
+ let at = from
85
+ while (at < code.length && /\s/.test(code.charAt(at))) at += 1
86
+ return code[at] === "}" || code[at] === "]"
62
87
  }
63
88
 
64
89
  /** JSON with comments and trailing commas, as tsconfig files are written. Throws on anything else. */
@@ -90,7 +115,7 @@ export function parseJsonc(text: string): unknown {
90
115
  while (end < code.length && code[end] !== '"') end += code[end] === "\\" ? 2 : 1
91
116
  json += code.slice(i, end + 1)
92
117
  i = end
93
- } else if (ch === "," && /^\s*[}\]]/.test(code.slice(i + 1))) {
118
+ } else if (ch === "," && closesNext(code, i + 1)) {
94
119
  } else json += ch
95
120
  }
96
121
  return JSON.parse(json.replace(/^\uFEFF/, ""))
@@ -101,8 +126,14 @@ const record = (value: unknown): Readonly<Record<string, unknown>> | undefined =
101
126
  ? Object.fromEntries(Object.entries(value))
102
127
  : undefined
103
128
 
104
- const isFile = (path: string): boolean =>
105
- statSync(path, { throwIfNoEntry: false })?.isFile() ?? false
129
+ /** Whether `path` is a file. A path through a file (`a.ts/index.ts`) is none, not an error. */
130
+ export const isFile = (path: string): boolean => {
131
+ try {
132
+ return statSync(path, { throwIfNoEntry: false })?.isFile() ?? false
133
+ } catch {
134
+ return false
135
+ }
136
+ }
106
137
 
107
138
  const real = (path: string): string => {
108
139
  try {
@@ -113,18 +144,18 @@ const real = (path: string): string => {
113
144
  }
114
145
 
115
146
  /** The file a path names: as written, its source for a `.js` name, with an extension, or an index. */
116
- function probe(base: string): string | undefined {
117
- if (isFile(base)) return base
147
+ function probe(base: string, exists: (path: string) => boolean): string | undefined {
148
+ if (exists(base)) return base
118
149
  const ext = extname(base)
119
150
  for (const source of SOURCE_FOR[ext] ?? []) {
120
151
  const candidate = `${base.slice(0, -ext.length)}${source}`
121
- if (isFile(candidate)) return candidate
152
+ if (exists(candidate)) return candidate
122
153
  }
123
154
  for (const extension of EXTENSIONS)
124
- if (isFile(`${base}${extension}`)) return `${base}${extension}`
155
+ if (exists(`${base}${extension}`)) return `${base}${extension}`
125
156
  for (const extension of EXTENSIONS) {
126
157
  const index = join(base, `index${extension}`)
127
- if (isFile(index)) return index
158
+ if (exists(index)) return index
128
159
  }
129
160
  return undefined
130
161
  }
@@ -164,7 +195,14 @@ function matchPattern(
164
195
  return best
165
196
  }
166
197
 
167
- export function createSpecifierResolver(): ProjectResolver {
198
+ export interface SpecifierResolverOptions {
199
+ /** Whether a module file exists, for resolving against a planned layout rather than the disk.
200
+ * Config files (tsconfig, package.json) are still read from the disk. */
201
+ readonly moduleExists?: (path: string) => boolean
202
+ }
203
+
204
+ export function createSpecifierResolver(options: SpecifierResolverOptions = {}): ProjectResolver {
205
+ const exists = options.moduleExists ?? isFile
168
206
  const configs = new Map<string, PathsConfig | undefined>()
169
207
  const tsconfigByDir = new Map<string, string | undefined>()
170
208
  const manifests = new Map<string, Readonly<Record<string, unknown>> | undefined>()
@@ -209,7 +247,7 @@ export function createSpecifierResolver(): ProjectResolver {
209
247
  }
210
248
  }
211
249
 
212
- /** The `paths` and `baseUrl` a config ends up with after its `extends` chain. */
250
+ /** The `paths`, `baseUrl` and import-emit options a config ends up with after its `extends` chain. */
213
251
  const pathsConfig = (
214
252
  file: string,
215
253
  seen: ReadonlySet<string> = new Set(),
@@ -218,6 +256,7 @@ export function createSpecifierResolver(): ProjectResolver {
218
256
  if (seen.has(file) || seen.size >= MAX_EXTENDS) return undefined
219
257
  const config = readJsonc(file)
220
258
  let inherited: PathsConfig | undefined
259
+ let importEmit: Record<string, unknown> | undefined = {}
221
260
  const extended = config?.extends
222
261
  for (const name of typeof extended === "string"
223
262
  ? [extended]
@@ -227,15 +266,24 @@ export function createSpecifierResolver(): ProjectResolver {
227
266
  if (typeof name !== "string") continue
228
267
  const base = extendedConfig(file, name)
229
268
  const parent = base === undefined ? undefined : pathsConfig(base, new Set([...seen, file]))
269
+ importEmit =
270
+ importEmit === undefined || parent?.importEmit === undefined
271
+ ? undefined
272
+ : { ...importEmit, ...parent.importEmit }
230
273
  if (parent === undefined) continue
231
274
  inherited = {
232
275
  paths: parent.paths.length > 0 ? parent.paths : (inherited?.paths ?? []),
233
276
  baseUrl: parent.baseUrl ?? inherited?.baseUrl,
234
277
  pathsBase:
235
278
  parent.paths.length > 0 ? parent.pathsBase : (inherited?.pathsBase ?? parent.pathsBase),
279
+ importEmit,
236
280
  }
237
281
  }
238
282
  const options = record(config?.compilerOptions)
283
+ if (importEmit !== undefined) {
284
+ for (const key of IMPORT_EMIT_OPTIONS)
285
+ if (options?.[key] !== undefined) importEmit = { ...importEmit, [key]: options[key] }
286
+ }
239
287
  const baseUrl =
240
288
  typeof options?.baseUrl === "string"
241
289
  ? join(dirname(file), options.baseUrl)
@@ -255,7 +303,7 @@ export function createSpecifierResolver(): ProjectResolver {
255
303
  )
256
304
  const pathsBase =
257
305
  baseUrl ?? (ownPaths === undefined ? (inherited?.pathsBase ?? dirname(file)) : dirname(file))
258
- const resolved = config === undefined ? undefined : { paths, baseUrl, pathsBase }
306
+ const resolved = config === undefined ? undefined : { paths, baseUrl, pathsBase, importEmit }
259
307
  configs.set(file, resolved)
260
308
  return resolved
261
309
  }
@@ -315,7 +363,7 @@ export function createSpecifierResolver(): ProjectResolver {
315
363
  if (template === undefined) return undefined
316
364
  const base = dirname(manifestPath)
317
365
  const written = join(base, template.replaceAll(STAR, match.star ?? ""))
318
- const found = probe(written)
366
+ const found = probe(written, exists)
319
367
  return found === undefined
320
368
  ? undefined
321
369
  : { key: match.pattern, keys, base, templates: [template], written, found }
@@ -335,7 +383,7 @@ export function createSpecifierResolver(): ProjectResolver {
335
383
  if (match === undefined) {
336
384
  if (config.baseUrl === undefined) return undefined
337
385
  const written = join(config.baseUrl, specifier)
338
- const found = probe(written)
386
+ const found = probe(written, exists)
339
387
  return found === undefined
340
388
  ? undefined
341
389
  : { key: undefined, keys, base: config.baseUrl, templates: [STAR], written, found }
@@ -346,7 +394,7 @@ export function createSpecifierResolver(): ProjectResolver {
346
394
  )
347
395
  for (const target of targets) {
348
396
  const written = join(config.pathsBase, target.replaceAll("*", match.star ?? ""))
349
- const found = probe(written)
397
+ const found = probe(written, exists)
350
398
  if (found === undefined) continue
351
399
  const templates = targets.map((t) => t.replaceAll("*", STAR))
352
400
  return { key: match.pattern, keys, base: config.pathsBase, templates, written, found }
@@ -401,7 +449,20 @@ export function createSpecifierResolver(): ProjectResolver {
401
449
  return (config?.paths ?? []).map(([pattern]) => pattern)
402
450
  }
403
451
 
404
- return Object.assign(resolve, { respell, pathPatterns })
452
+ const keepsTypeOnlyImports = (file: string): boolean => {
453
+ const tsconfig = tsconfigFor(dirname(file))
454
+ if (tsconfig === undefined) return false
455
+ const emit = pathsConfig(tsconfig)?.importEmit
456
+ if (emit === undefined) return true
457
+ return (
458
+ emit.verbatimModuleSyntax === true ||
459
+ emit.preserveValueImports === true ||
460
+ emit.importsNotUsedAsValues === "preserve" ||
461
+ emit.importsNotUsedAsValues === "error"
462
+ )
463
+ }
464
+
465
+ return Object.assign(resolve, { respell, pathPatterns, keepsTypeOnlyImports })
405
466
 
406
467
  function resolveFrom(fromFile: string, specifier: string): string | undefined {
407
468
  let found: string | undefined
@@ -411,8 +472,8 @@ export function createSpecifierResolver(): ProjectResolver {
411
472
  specifier === "." ||
412
473
  specifier === ".."
413
474
  )
414
- found = probe(join(dirname(fromFile), specifier))
415
- else if (isAbsolute(specifier)) found = probe(specifier)
475
+ found = probe(join(dirname(fromFile), specifier), exists)
476
+ else if (isAbsolute(specifier)) found = probe(specifier, exists)
416
477
  // A `#` name is a package.json import first; a tsconfig may still map it.
417
478
  else if (specifier.startsWith("#"))
418
479
  found = viaImports(fromFile, specifier) ?? viaTsconfig(fromFile, specifier)
@@ -36,6 +36,12 @@ export interface SourceFacts {
36
36
  path: string,
37
37
  ): boolean | undefined
38
38
  isResponseSyntaxAt(source: TSApi.SourceFile, position: number): boolean | undefined
39
+ /**
40
+ * Whether `position` lies in a route handler: a function passed to `.get("/path", …)` and the
41
+ * other method registrations, a function value of an `implement(contract, {...})` map, a local
42
+ * function either one names, or a local function a handler returns a call to (one hop).
43
+ */
44
+ isRouteHandlerAt(source: TSApi.SourceFile, position: number): boolean
39
45
  /** Whether the `import` keyword at `position` starts a runtime `import(specifier)` call (true) or a
40
46
  * type-position `import("…")` such as `typeof import("x")` (false); undefined when neither. */
41
47
  isDynamicImportAt(
@@ -82,8 +88,130 @@ function rawResponseExpression(ts: TypeScriptApi, node: TSApi.Expression): boole
82
88
  )
83
89
  }
84
90
 
85
- export function createSourceFacts(ts: TypeScriptApi): SourceFacts {
91
+ const REGISTRATION_METHODS: ReadonlySet<string> = new Set([
92
+ "get",
93
+ "post",
94
+ "put",
95
+ "patch",
96
+ "delete",
97
+ "head",
98
+ "options",
99
+ "all",
100
+ ])
101
+
102
+ function unwrapExpression(ts: TypeScriptApi, node: TSApi.Expression): TSApi.Expression {
103
+ let current = node
104
+ while (
105
+ ts.isParenthesizedExpression(current) ||
106
+ ts.isAsExpression(current) ||
107
+ ts.isSatisfiesExpression(current) ||
108
+ ts.isAwaitExpression(current)
109
+ )
110
+ current = current.expression
111
+ return current
112
+ }
113
+
114
+ type FunctionNode =
115
+ | TSApi.ArrowFunction
116
+ | TSApi.FunctionExpression
117
+ | TSApi.FunctionDeclaration
118
+ | TSApi.MethodDeclaration
119
+
120
+ /** Every route handler of `source`, by the rules {@link SourceFacts.isRouteHandlerAt} states. */
121
+ function routeHandlers(ts: TypeScriptApi, source: TSApi.SourceFile): ReadonlySet<TSApi.Node> {
122
+ const isFunctionValue = (node: TSApi.Node): node is FunctionNode =>
123
+ ts.isArrowFunction(node) || ts.isFunctionExpression(node) || ts.isMethodDeclaration(node)
124
+ // Local functions by name; a name declared twice keeps both, which only ever adds findings.
125
+ const locals = new Map<string, FunctionNode[]>()
126
+ const declare = (name: string, fn: FunctionNode): void => {
127
+ locals.set(name, [...(locals.get(name) ?? []), fn])
128
+ }
129
+ const collect = (node: TSApi.Node): void => {
130
+ if (ts.isFunctionDeclaration(node) && node.name !== undefined) declare(node.name.text, node)
131
+ else if (ts.isVariableDeclaration(node) && ts.isIdentifier(node.name) && node.initializer) {
132
+ const value = unwrapExpression(ts, node.initializer)
133
+ if (isFunctionValue(value)) declare(node.name.text, value)
134
+ }
135
+ ts.forEachChild(node, collect)
136
+ }
137
+ collect(source)
138
+
139
+ const handlers = new Set<TSApi.Node>()
140
+ const named = (expression: TSApi.Node): readonly FunctionNode[] => {
141
+ if (ts.isIdentifier(expression)) return locals.get(expression.text) ?? []
142
+ return isFunctionValue(expression) ? [expression] : []
143
+ }
144
+ const find = (node: TSApi.Node): void => {
145
+ if (ts.isCallExpression(node)) {
146
+ const callee = node.expression
147
+ const method = ts.isPropertyAccessExpression(callee) ? callee.name.text : undefined
148
+ const [first, ...rest] = node.arguments
149
+ if (
150
+ method !== undefined &&
151
+ REGISTRATION_METHODS.has(method) &&
152
+ first !== undefined &&
153
+ (ts.isStringLiteralLike(first) || ts.isTemplateExpression(first))
154
+ ) {
155
+ for (const argument of rest)
156
+ for (const fn of named(unwrapExpression(ts, argument))) handlers.add(fn)
157
+ }
158
+ const implement =
159
+ (ts.isIdentifier(callee) && callee.text === "implement") || method === "implement"
160
+ const map =
161
+ node.arguments[1] === undefined ? undefined : unwrapExpression(ts, node.arguments[1])
162
+ if (implement && map !== undefined && ts.isObjectLiteralExpression(map)) {
163
+ for (const property of map.properties) {
164
+ if (ts.isMethodDeclaration(property)) handlers.add(property)
165
+ else if (ts.isPropertyAssignment(property))
166
+ for (const fn of named(unwrapExpression(ts, property.initializer))) handlers.add(fn)
167
+ else if (ts.isShorthandPropertyAssignment(property))
168
+ for (const fn of locals.get(property.name.text) ?? []) handlers.add(fn)
169
+ }
170
+ }
171
+ }
172
+ ts.forEachChild(node, find)
173
+ }
174
+ find(source)
175
+
176
+ // One hop: a local function a handler returns a call to answers for that handler.
177
+ const returned = new Set<TSApi.Node>()
178
+ const follow = (node: TSApi.Node): void => {
179
+ const value =
180
+ ts.isReturnStatement(node) && node.expression !== undefined
181
+ ? node.expression
182
+ : ts.isArrowFunction(node) && !ts.isBlock(node.body)
183
+ ? node.body
184
+ : undefined
185
+ const call = value === undefined ? undefined : unwrapExpression(ts, value)
186
+ if (call !== undefined && ts.isCallExpression(call))
187
+ for (const fn of named(call.expression)) returned.add(fn)
188
+ ts.forEachChild(node, follow)
189
+ }
190
+ for (const handler of handlers) follow(handler)
191
+ for (const fn of returned) handlers.add(fn)
192
+ return handlers
193
+ }
194
+
195
+ export interface SourceFactsOptions {
196
+ /** Whether the compiler settings for a parsed file keep an import whose named specifiers are all
197
+ * type-only (`verbatimModuleSyntax`). Without it such an import is erased. */
198
+ readonly keepsTypeOnlyImports?: (file: string) => boolean
199
+ }
200
+
201
+ export function createSourceFacts(
202
+ ts: TypeScriptApi,
203
+ options: SourceFactsOptions = {},
204
+ ): SourceFacts {
86
205
  const cache = new Map<string, { content: string; source: TSApi.SourceFile | undefined }>()
206
+ // `{}` loads its module in every bundler; a list of type-only specifiers is erased unless the
207
+ // compiler keeps it as `import {} from "x"`.
208
+ const loadsModule = (
209
+ source: TSApi.SourceFile,
210
+ elements: readonly { readonly isTypeOnly: boolean }[],
211
+ ): boolean =>
212
+ elements.length === 0 ||
213
+ elements.some((element) => !element.isTypeOnly) ||
214
+ (options.keepsTypeOnlyImports?.(source.fileName) ?? false)
87
215
 
88
216
  const parse = (file: string, content: string): TSApi.SourceFile | undefined => {
89
217
  const cached = cache.get(file)
@@ -118,7 +246,7 @@ export function createSourceFacts(ts: TypeScriptApi): SourceFacts {
118
246
  if (reexport.isTypeOnly) return false
119
247
  const named = reexport.exportClause
120
248
  if (named !== undefined && ts.isNamedExports(named))
121
- return named.elements.some((element) => !element.isTypeOnly)
249
+ return loadsModule(source, named.elements)
122
250
  return true // `export *` and `export * as ns`
123
251
  }
124
252
  const declaration = ancestorAt(ts, source, position, ts.isImportDeclaration)
@@ -128,9 +256,9 @@ export function createSourceFacts(ts: TypeScriptApi): SourceFacts {
128
256
  const clause = declaration.importClause
129
257
  if (clause === undefined) return true // side-effect import
130
258
  if (clause.isTypeOnly) return false
131
- if (clause.namedBindings !== undefined && ts.isNamedImports(clause.namedBindings)) {
132
- return clause.namedBindings.elements.some((element) => !element.isTypeOnly)
133
- }
259
+ // A default binding is a runtime import whatever its named list holds.
260
+ const named = clause.name === undefined ? clause.namedBindings : undefined
261
+ if (named !== undefined && ts.isNamedImports(named)) return loadsModule(source, named.elements)
134
262
  return true // default and namespace bindings are runtime imports
135
263
  }
136
264
 
@@ -197,6 +325,19 @@ export function createSourceFacts(ts: TypeScriptApi): SourceFacts {
197
325
  return false
198
326
  }
199
327
 
328
+ const handlersBySource = new WeakMap<TSApi.SourceFile, ReadonlySet<TSApi.Node>>()
329
+ const isRouteHandlerAt = (source: TSApi.SourceFile, position: number): boolean => {
330
+ let handlers = handlersBySource.get(source)
331
+ if (handlers === undefined) {
332
+ handlers = routeHandlers(ts, source)
333
+ handlersBySource.set(source, handlers)
334
+ }
335
+ return (
336
+ ancestorAt(ts, source, position, (node): node is TSApi.Node => handlers.has(node)) !==
337
+ undefined
338
+ )
339
+ }
340
+
200
341
  const isDynamicImportAt = (
201
342
  source: TSApi.SourceFile,
202
343
  position: number,
@@ -227,6 +368,7 @@ export function createSourceFacts(ts: TypeScriptApi): SourceFacts {
227
368
  isRouteArgumentAt,
228
369
  isFunctionRouteCallAt,
229
370
  isResponseSyntaxAt,
371
+ isRouteHandlerAt,
230
372
  isDynamicImportAt,
231
373
  }
232
374
  }
@@ -323,9 +323,9 @@ function syntaxKinds(module: UnknownRecord, names: readonly string[]): ReadonlyS
323
323
 
324
324
  function createVirtualFileSystem(
325
325
  sourceFiles: ReadonlyMap<string, string>,
326
- root: string,
326
+ roots: readonly string[],
327
327
  ): UnknownRecord {
328
- const rootPaths = pathVariants(root)
328
+ const rootPaths = [...new Set(roots.flatMap(pathVariants))]
329
329
  const virtualFiles: string[] = []
330
330
  const seenFiles = new Set<string>()
331
331
  for (const file of sourceFiles.keys()) {
@@ -454,7 +454,9 @@ async function createTypeScript7Session(
454
454
 
455
455
  const api = new API({
456
456
  cwd: sessionRoot,
457
- fs: createVirtualFileSystem(files, sessionRoot),
457
+ // The root as the caller spells it too: a file not yet on disk keeps that spelling (`/var`, not
458
+ // `/private/var`), and the session reaches it through the caller's config.
459
+ fs: createVirtualFileSystem(files, [sessionRoot, root]),
458
460
  })
459
461
  let snapshot: TypeScript7Snapshot | undefined
460
462
  let configuredProject: TypeScript7Project | undefined
@@ -0,0 +1,218 @@
1
+ /**
2
+ * Bare specifiers that name a package the project owns, resolved through that package's `exports`
3
+ * the way Bun resolves them. A package is the project's when it is a workspace member, or when its
4
+ * `node_modules` entry links to a directory outside every `node_modules`; one installed from a
5
+ * registry is never read, because its source is not the project's to check.
6
+ */
7
+ import { existsSync, readFileSync, realpathSync, statSync } from "node:fs"
8
+ import { dirname, join, relative, sep } from "node:path"
9
+ import { workspaceMemberDirs } from "../mcp-root.ts"
10
+
11
+ /** Bun's runtime conditions, in the order a conditions object is read; `types` is taken only when it
12
+ * names a TypeScript source, which is what Bun would run. */
13
+ const CONDITIONS: ReadonlySet<string> = new Set(["bun", "import", "default"])
14
+ const TS_SOURCE = /\.[cm]?tsx?$/
15
+ const DECLARATION = /\.d\.[cm]?tsx?$/
16
+ /** Tried in order when a package without `exports` names a file without its extension. */
17
+ const EXTENSIONS: readonly string[] = ["", ".ts", ".tsx", ".mts", ".js", ".mjs", ".jsx"]
18
+ const PACKAGE_NAME = /^(?:@[a-z0-9][\w.~-]*\/)?[a-z0-9][\w.~-]*$/i
19
+
20
+ /** The file a specifier names, or why a package the project owns does not export it. */
21
+ export type ExportedFile =
22
+ | { readonly path: string }
23
+ | { readonly package: string; readonly reason: string }
24
+
25
+ const record = (value: unknown): Readonly<Record<string, unknown>> | undefined =>
26
+ typeof value === "object" && value !== null && !Array.isArray(value)
27
+ ? Object.fromEntries(Object.entries(value))
28
+ : undefined
29
+
30
+ const isFile = (path: string): boolean => {
31
+ try {
32
+ return statSync(path).isFile()
33
+ } catch {
34
+ return false
35
+ }
36
+ }
37
+
38
+ const manifestOf = (dir: string): Readonly<Record<string, unknown>> | undefined => {
39
+ try {
40
+ return record(JSON.parse(readFileSync(join(dir, "package.json"), "utf8")))
41
+ } catch {
42
+ return undefined
43
+ }
44
+ }
45
+
46
+ /** `@scope/name/sub/path` -> `["@scope/name", "./sub/path"]`; `undefined` for a relative, absolute,
47
+ * `#` or `scheme:` specifier. */
48
+ export function splitBareSpecifier(specifier: string): [string, string] | undefined {
49
+ if (/^[./#]/.test(specifier) || specifier.includes(":")) return undefined
50
+ const parts = specifier.split("/")
51
+ const take = specifier.startsWith("@") ? 2 : 1
52
+ const name = parts.slice(0, take).join("/")
53
+ if (!PACKAGE_NAME.test(name)) return undefined
54
+ const rest = parts.slice(take)
55
+ return [name, rest.length === 0 ? "." : `./${rest.join("/")}`]
56
+ }
57
+
58
+ /** The target a conditions value selects, with `*` replaced; `null` when the package excludes it. */
59
+ function conditionTarget(value: unknown, match: string): string | null | undefined {
60
+ if (value === null) return null
61
+ if (typeof value === "string") {
62
+ // As Node and Bun refuse them: a target leaves the package only through `..` or `node_modules`.
63
+ const segments = value.split("/")
64
+ if (segments[0] !== "." || segments.some((part) => part === ".." || part === "node_modules"))
65
+ return undefined
66
+ return value.replaceAll("*", match)
67
+ }
68
+ if (Array.isArray(value)) {
69
+ for (const item of value) {
70
+ const target = conditionTarget(item, match)
71
+ if (target !== undefined) return target
72
+ }
73
+ return undefined
74
+ }
75
+ const conditions = record(value)
76
+ if (conditions === undefined) return undefined
77
+ for (const [key, inner] of Object.entries(conditions)) {
78
+ if (CONDITIONS.has(key)) {
79
+ const target = conditionTarget(inner, match)
80
+ if (target !== undefined) return target
81
+ } else if (key === "types") {
82
+ const target = conditionTarget(inner, match)
83
+ if (typeof target === "string" && TS_SOURCE.test(target) && !DECLARATION.test(target))
84
+ return target
85
+ }
86
+ }
87
+ return undefined
88
+ }
89
+
90
+ /** What `exports` maps `subpath` to: an exact key first, then the `*` pattern with the longest
91
+ * prefix, as Node and Bun match them. */
92
+ export function exportsTarget(exports: unknown, subpath: string): string | null | undefined {
93
+ const map = record(exports)
94
+ const subpaths =
95
+ map !== undefined && Object.keys(map).some((key) => key.startsWith("."))
96
+ ? map
97
+ : { ".": exports }
98
+ if (Object.hasOwn(subpaths, subpath)) return conditionTarget(subpaths[subpath], "")
99
+ let best: { readonly key: string; readonly match: string } | undefined
100
+ for (const key of Object.keys(subpaths)) {
101
+ const star = key.indexOf("*")
102
+ if (star === -1 || key.indexOf("*", star + 1) !== -1) continue
103
+ const prefix = key.slice(0, star)
104
+ const suffix = key.slice(star + 1)
105
+ if (
106
+ subpath.length < key.length ||
107
+ !subpath.startsWith(prefix) ||
108
+ !subpath.endsWith(suffix) ||
109
+ (best !== undefined && prefix.length <= best.key.indexOf("*"))
110
+ )
111
+ continue
112
+ best = { key, match: subpath.slice(prefix.length, subpath.length - suffix.length) }
113
+ }
114
+ if (best === undefined) return undefined
115
+ if (best.match.split("/").includes("..")) return undefined
116
+ return conditionTarget(subpaths[best.key], best.match)
117
+ }
118
+
119
+ const inside = (dir: string, path: string): boolean => {
120
+ const rel = relative(dir, path)
121
+ return rel !== "" && !rel.startsWith("..") && !rel.split(sep).includes("node_modules")
122
+ }
123
+
124
+ /** The file `subpath` names in the package at `dir`, or why it names none. */
125
+ function entryIn(dir: string, name: string, subpath: string): ExportedFile {
126
+ const manifest = manifestOf(dir)
127
+ const shown = subpath === "." ? name : `${name}/${subpath.slice(2)}`
128
+ const exported =
129
+ manifest?.exports !== undefined
130
+ ? exportsTarget(manifest.exports, subpath)
131
+ : subpath === "."
132
+ ? typeof manifest?.module === "string"
133
+ ? manifest.module
134
+ : typeof manifest?.main === "string"
135
+ ? manifest.main
136
+ : "./index"
137
+ : subpath
138
+ if (exported === null || exported === undefined)
139
+ return { package: name, reason: `${name} does not export "${subpath}"` }
140
+ // An `exports` target is a file; a package without `exports` is probed the way Bun probes it.
141
+ const base = join(dir, exported)
142
+ const probes =
143
+ manifest?.exports !== undefined
144
+ ? [base]
145
+ : [
146
+ ...EXTENSIONS.map((extension) => `${base}${extension}`),
147
+ ...EXTENSIONS.slice(1).map((extension) => join(base, `index${extension}`)),
148
+ ]
149
+ const found = probes.find(isFile)
150
+ if (found === undefined)
151
+ return { package: name, reason: `${shown} resolves to ${exported}, which does not exist` }
152
+ let real: string
153
+ try {
154
+ real = realpathSync(found)
155
+ } catch {
156
+ return { package: name, reason: `${shown} resolves to ${exported}, which cannot be read` }
157
+ }
158
+ return inside(realpathSync(dir), real)
159
+ ? { path: real }
160
+ : { package: name, reason: `${shown} resolves outside the package` }
161
+ }
162
+
163
+ /** The nearest directory at or above `start`, up to the repository root, whose package.json declares
164
+ * `workspaces`. */
165
+ function workspaceRoot(start: string): string | undefined {
166
+ for (let dir = start; ; ) {
167
+ const workspaces = manifestOf(dir)?.workspaces
168
+ if (workspaces !== undefined) return dir
169
+ const parent = dirname(dir)
170
+ if (parent === dir || existsSync(join(dir, ".git"))) return undefined
171
+ dir = parent
172
+ }
173
+ }
174
+
175
+ /** Resolves a bare specifier from an absolute importing file; `undefined` when it is not bare. */
176
+ export type ExportedFileResolver = (from: string, specifier: string) => ExportedFile | undefined
177
+
178
+ /**
179
+ * A resolver over the workspace `root` belongs to. Workspace members are read from their manifests
180
+ * once; any other package is looked up in the `node_modules` above the importing file and read only
181
+ * when that entry links outside every `node_modules`.
182
+ */
183
+ export async function createExportedFileResolver(root: string): Promise<ExportedFileResolver> {
184
+ const members = new Map<string, string>()
185
+ const top = workspaceRoot(root)
186
+ for (const dir of top === undefined ? [] : ((await workspaceMemberDirs(top)) ?? [])) {
187
+ const name = manifestOf(dir)?.name
188
+ if (typeof name === "string" && !members.has(name)) members.set(name, dir)
189
+ }
190
+ return (from, specifier) => {
191
+ const split = splitBareSpecifier(specifier)
192
+ if (split === undefined) return undefined
193
+ const [name, subpath] = split
194
+ const member = members.get(name)
195
+ if (member !== undefined) return entryIn(member, name, subpath)
196
+ for (let dir = dirname(from); ; ) {
197
+ const linked = join(dir, "node_modules", name)
198
+ if (existsSync(linked)) {
199
+ let real: string
200
+ try {
201
+ real = realpathSync(linked)
202
+ } catch {
203
+ break
204
+ }
205
+ return real.split(sep).includes("node_modules")
206
+ ? {
207
+ package: name,
208
+ reason: `${name} is installed from a registry, not a workspace package`,
209
+ }
210
+ : entryIn(real, name, subpath)
211
+ }
212
+ const parent = dirname(dir)
213
+ if (parent === dir) break
214
+ dir = parent
215
+ }
216
+ return { package: name, reason: `${name} is not a workspace package and is not installed` }
217
+ }
218
+ }