@xh/hoist-docs-builder 0.0.0-stage → 0.0.1
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.
- package/bin/hoist-docs-build.mjs +12 -0
- package/dist/cli/build-index.d.ts +15 -0
- package/dist/cli/build-index.js +199 -0
- package/dist/data/doc-registry.d.ts +148 -0
- package/dist/data/doc-registry.js +378 -0
- package/dist/data/import-paths.d.ts +28 -0
- package/dist/data/import-paths.js +107 -0
- package/dist/data/index-cache.d.ts +30 -0
- package/dist/data/index-cache.js +210 -0
- package/dist/data/ts-registry.d.ts +251 -0
- package/dist/data/ts-registry.js +1845 -0
- package/dist/util/logger.d.ts +6 -0
- package/dist/util/logger.js +31 -0
- package/dist/util/paths.d.ts +103 -0
- package/dist/util/paths.js +200 -0
- package/package.json +34 -4
- package/README.md +0 -3
|
@@ -0,0 +1,378 @@
|
|
|
1
|
+
/*
|
|
2
|
+
* This file belongs to Hoist, an application development toolkit
|
|
3
|
+
* developed by Extremely Heavy Industries (www.xh.io | info@xh.io)
|
|
4
|
+
*
|
|
5
|
+
* Copyright © 2026 Extremely Heavy Industries Inc.
|
|
6
|
+
*/
|
|
7
|
+
/**
|
|
8
|
+
* Document registry for the Hoist MCP server.
|
|
9
|
+
*
|
|
10
|
+
* Loads documentation inventory from `docs/doc-registry.json` -- the single
|
|
11
|
+
* source of truth for hoist-react's documentation catalog. The same file is
|
|
12
|
+
* also read by the toolbox doc viewer (toolbox's Grails `DocsService` resolves
|
|
13
|
+
* it from a sibling checkout in local development or from a GitHub tarball in
|
|
14
|
+
* production, then serves entries to the toolbox client).
|
|
15
|
+
*
|
|
16
|
+
* Companion libraries - packages that build on Hoist, such as `@xh/hoist-chat-kit` or a client
|
|
17
|
+
* firm's own shared Hoist package - can add their docs to the same tools. A library opts in with
|
|
18
|
+
* `"hoist": {"docRegistry": "<path>"}` in its package.json, pointing at a registry file in the
|
|
19
|
+
* same JSON schema. {@link loadRegistry} finds opted-in packages among the direct dependencies of
|
|
20
|
+
* the consuming app (see `resolveAppRoot()` in `util/paths.ts`) and merges their entries in,
|
|
21
|
+
* with each id prefixed by the package name. See `docs/companion-library-docs.md`.
|
|
22
|
+
*
|
|
23
|
+
* Hoist-core maintains a *separate* registry of server-side docs at its own
|
|
24
|
+
* `docs/doc-registry.json`, consumed by its own (Groovy) MCP server. The two
|
|
25
|
+
* registries use the same JSON schema, but the files and entries are
|
|
26
|
+
* independent -- changes here do not propagate there and vice versa.
|
|
27
|
+
*
|
|
28
|
+
* Provides metadata and file loading. Search lives in `doc-search.ts`, and the section model
|
|
29
|
+
* used for search and targeted reads lives in `doc-sections.ts`.
|
|
30
|
+
*/
|
|
31
|
+
import { existsSync, readFileSync, realpathSync } from 'node:fs';
|
|
32
|
+
import { isAbsolute, posix, relative, resolve, sep } from 'node:path';
|
|
33
|
+
import { log } from '../util/logger.js';
|
|
34
|
+
import { findInstalledPackage, readPackageJson, resolveDocPath, resolveRepoRoot } from '../util/paths.js';
|
|
35
|
+
/** Load and parse a registry file, or return null (and warn) if missing or invalid. */
|
|
36
|
+
function loadRegistryJson(jsonPath, warn) {
|
|
37
|
+
if (!existsSync(jsonPath)) {
|
|
38
|
+
warn(`doc registry not found at ${jsonPath}`);
|
|
39
|
+
return null;
|
|
40
|
+
}
|
|
41
|
+
try {
|
|
42
|
+
return JSON.parse(readFileSync(jsonPath, 'utf-8'));
|
|
43
|
+
}
|
|
44
|
+
catch (e) {
|
|
45
|
+
warn(`doc registry at ${jsonPath} is not valid JSON: ${e}`);
|
|
46
|
+
return null;
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
//------------------------------------------------------------------
|
|
50
|
+
// Registry builder
|
|
51
|
+
//------------------------------------------------------------------
|
|
52
|
+
/** Package name of hoist-react, which owns the primary docs. */
|
|
53
|
+
export const HOIST_PACKAGE = '@xh/hoist';
|
|
54
|
+
/**
|
|
55
|
+
* Build the complete document registry: hoist-react's docs, plus those of any companion
|
|
56
|
+
* libraries discovered from `appRoot`. Omit `appRoot` to load hoist-react's docs alone.
|
|
57
|
+
*
|
|
58
|
+
* Each entry's file path is validated at build time; missing files are
|
|
59
|
+
* logged and skipped.
|
|
60
|
+
*/
|
|
61
|
+
export function buildRegistry(repoRoot, { appRoot } = {}) {
|
|
62
|
+
const warnings = [], hoistPkg = readPackageJson(repoRoot), isAppRoot = (root) => appRoot != null && samePath(root, appRoot), primary = loadLibrary(repoRoot, hoistPkg ?? { name: HOIST_PACKAGE }, 'docs/doc-registry.json', { primary: true, isAppRoot: isAppRoot(repoRoot), sourcePath: displayPath(repoRoot) }, msg => log.warn(msg));
|
|
63
|
+
const libraries = [primary.library], entries = [...primary.entries], mcpCategories = [...primary.mcpCategories];
|
|
64
|
+
for (const { path, pkg } of appRoot ? discoverCompanionPackages(appRoot) : []) {
|
|
65
|
+
const name = pkg.name, warn = (msg) => {
|
|
66
|
+
warnings.push(`${name}: ${msg}`);
|
|
67
|
+
log.warn(`Companion library ${name}: ${msg}`);
|
|
68
|
+
}, loaded = loadCompanion(path, pkg, isAppRoot(path), warn);
|
|
69
|
+
if (!loaded)
|
|
70
|
+
continue;
|
|
71
|
+
// An unscoped package named like a hoist-react folder (e.g. `core`) could produce an id
|
|
72
|
+
// that is already taken. Ids must be unique, so the first claimant keeps it.
|
|
73
|
+
const taken = new Set(entries.map(e => e.id)), kept = loaded.entries.filter(e => {
|
|
74
|
+
if (!taken.has(e.id))
|
|
75
|
+
return true;
|
|
76
|
+
warn(`skipped "${e.path}": id "${e.id}" is already registered`);
|
|
77
|
+
return false;
|
|
78
|
+
});
|
|
79
|
+
const links = {
|
|
80
|
+
library: name,
|
|
81
|
+
docPaths: new Set(kept.map(e => e.path)),
|
|
82
|
+
sourcePath: loaded.library.sourcePath
|
|
83
|
+
};
|
|
84
|
+
libraries.push({ ...loaded.library, docCount: kept.length });
|
|
85
|
+
entries.push(...kept.map(e => ({ ...e, links })));
|
|
86
|
+
for (const cat of loaded.mcpCategories) {
|
|
87
|
+
if (!mcpCategories.some(c => c.id === cat.id))
|
|
88
|
+
mcpCategories.push(cat);
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
const companions = libraries.length - 1;
|
|
92
|
+
log.info(`Document registry built: ${entries.length} entries across ${new Set(entries.map(e => e.mcpCategory)).size} categories` +
|
|
93
|
+
(companions
|
|
94
|
+
? `, including ${companions} companion librar${companions > 1 ? 'ies' : 'y'}`
|
|
95
|
+
: ''));
|
|
96
|
+
return { entries, mcpCategories, libraries, warnings };
|
|
97
|
+
}
|
|
98
|
+
/**
|
|
99
|
+
* Load a companion library, or return null. A library's files must never stop Hoist's own docs
|
|
100
|
+
* from loading, so any error it causes becomes a warning.
|
|
101
|
+
*/
|
|
102
|
+
function loadCompanion(path, pkg, isAppRoot, warn) {
|
|
103
|
+
try {
|
|
104
|
+
return loadLibrary(realpathSync(path), pkg, pkg.hoist.docRegistry, { primary: false, isAppRoot, sourcePath: displayPath(path) }, warn);
|
|
105
|
+
}
|
|
106
|
+
catch (e) {
|
|
107
|
+
warn(`failed to load: ${e.message}`);
|
|
108
|
+
return null;
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
/** `path` relative to the working directory when inside it, else absolute. */
|
|
112
|
+
function displayPath(path) {
|
|
113
|
+
const rel = relative(process.cwd(), path);
|
|
114
|
+
if (!rel)
|
|
115
|
+
return '.';
|
|
116
|
+
return rel.startsWith('..') || isAbsolute(rel) ? path : rel;
|
|
117
|
+
}
|
|
118
|
+
/** True if two paths name the same folder, following symlinks. */
|
|
119
|
+
function samePath(a, b) {
|
|
120
|
+
try {
|
|
121
|
+
return realpathSync(a) === realpathSync(b);
|
|
122
|
+
}
|
|
123
|
+
catch {
|
|
124
|
+
return resolve(a) === resolve(b);
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
/**
|
|
128
|
+
* Load one library's registry, resolving each entry against the library's own root. Returns
|
|
129
|
+
* null for a companion library whose registry cannot be read. hoist-react's own registry always
|
|
130
|
+
* loads, if only as an empty one.
|
|
131
|
+
*
|
|
132
|
+
* Entries with `mcpAudience: 'maintainers'` load only when the library is the app root - that
|
|
133
|
+
* is, when an agent works in the library's own repo.
|
|
134
|
+
*/
|
|
135
|
+
function loadLibrary(root, pkg, registryPath, { primary, isAppRoot, sourcePath }, warn) {
|
|
136
|
+
const name = pkg.name ?? HOIST_PACKAGE;
|
|
137
|
+
let json = null;
|
|
138
|
+
try {
|
|
139
|
+
json = loadRegistryJson(resolveDocPath(root, registryPath), warn);
|
|
140
|
+
}
|
|
141
|
+
catch (e) {
|
|
142
|
+
warn(`invalid docRegistry path "${registryPath}": ${e.message}`);
|
|
143
|
+
}
|
|
144
|
+
if (!json) {
|
|
145
|
+
if (!primary)
|
|
146
|
+
return null;
|
|
147
|
+
json = {};
|
|
148
|
+
}
|
|
149
|
+
const entries = [], realRoot = realpathSync(root);
|
|
150
|
+
for (const raw of arrayField(json.entries, 'entries', warn)) {
|
|
151
|
+
if (typeof raw?.id !== 'string' || !raw.id) {
|
|
152
|
+
warn('skipped an entry with no id');
|
|
153
|
+
continue;
|
|
154
|
+
}
|
|
155
|
+
if (raw.mcpAudience != null && raw.mcpAudience !== 'maintainers') {
|
|
156
|
+
warn(`ignored mcpAudience "${raw.mcpAudience}" on "${raw.id}": expected "maintainers"`);
|
|
157
|
+
}
|
|
158
|
+
if (raw.mcpAudience === 'maintainers' && !isAppRoot)
|
|
159
|
+
continue;
|
|
160
|
+
let filePath;
|
|
161
|
+
try {
|
|
162
|
+
filePath = resolveDocPath(root, raw.id);
|
|
163
|
+
}
|
|
164
|
+
catch (e) {
|
|
165
|
+
warn(`skipped "${raw.id}": ${e.message}`);
|
|
166
|
+
continue;
|
|
167
|
+
}
|
|
168
|
+
if (!existsSync(filePath)) {
|
|
169
|
+
warn(`skipped doc entry "${raw.id}": file not found at ${filePath}`);
|
|
170
|
+
continue;
|
|
171
|
+
}
|
|
172
|
+
if (!realpathSync(filePath).startsWith(realRoot + sep)) {
|
|
173
|
+
warn(`skipped "${raw.id}": it links to a file outside the package root`);
|
|
174
|
+
continue;
|
|
175
|
+
}
|
|
176
|
+
entries.push({
|
|
177
|
+
id: primary ? raw.id : `${name}/${raw.id}`,
|
|
178
|
+
path: raw.id,
|
|
179
|
+
library: primary ? null : name,
|
|
180
|
+
title: stringField(raw.title, raw.id),
|
|
181
|
+
filePath,
|
|
182
|
+
mcpCategory: stringField(raw.mcpCategory, 'package'),
|
|
183
|
+
description: stringField(raw.description, ''),
|
|
184
|
+
keywords: stringsField(raw.keywords),
|
|
185
|
+
aliases: stringsField(raw.aliases)
|
|
186
|
+
});
|
|
187
|
+
}
|
|
188
|
+
// Categories the registry declares, then any an entry uses without declaring.
|
|
189
|
+
const mcpCategories = arrayField(json.mcpCategories, 'mcpCategories', warn)
|
|
190
|
+
.filter(c => typeof c?.id === 'string' && c.id)
|
|
191
|
+
.map(c => ({ id: c.id, title: stringField(c.title, c.id) }));
|
|
192
|
+
for (const id of new Set(entries.map(e => e.mcpCategory))) {
|
|
193
|
+
if (!mcpCategories.some(c => c.id === id)) {
|
|
194
|
+
mcpCategories.push({ id, title: id.charAt(0).toUpperCase() + id.slice(1) });
|
|
195
|
+
}
|
|
196
|
+
}
|
|
197
|
+
const index = entries.find(e => e.path === 'docs/README.md');
|
|
198
|
+
return {
|
|
199
|
+
library: {
|
|
200
|
+
name,
|
|
201
|
+
version: stringField(pkg.version, 'unknown'),
|
|
202
|
+
description: stringField(pkg.description, ''),
|
|
203
|
+
root,
|
|
204
|
+
sourcePath,
|
|
205
|
+
primary,
|
|
206
|
+
indexId: index?.id ?? null,
|
|
207
|
+
docCount: entries.length,
|
|
208
|
+
instructions: primary ? null : parseInstructions(json.mcpInstructions, warn)
|
|
209
|
+
},
|
|
210
|
+
entries,
|
|
211
|
+
mcpCategories
|
|
212
|
+
};
|
|
213
|
+
}
|
|
214
|
+
/*
|
|
215
|
+
* Field readers for registry and package.json values. Companion files come from any dependency,
|
|
216
|
+
* so a field of the wrong type falls back to its default rather than throwing later.
|
|
217
|
+
*/
|
|
218
|
+
function stringField(value, fallback) {
|
|
219
|
+
return typeof value === 'string' ? value : fallback;
|
|
220
|
+
}
|
|
221
|
+
function stringsField(value) {
|
|
222
|
+
return Array.isArray(value) ? value.filter(it => typeof it === 'string') : [];
|
|
223
|
+
}
|
|
224
|
+
function arrayField(value, field, warn) {
|
|
225
|
+
if (value == null)
|
|
226
|
+
return [];
|
|
227
|
+
if (Array.isArray(value))
|
|
228
|
+
return value;
|
|
229
|
+
warn(`ignored ${field}: expected an array`);
|
|
230
|
+
return [];
|
|
231
|
+
}
|
|
232
|
+
/** Longest library guidance accepted, in characters. Longer guidance is cut, with a warning. */
|
|
233
|
+
export const MAX_LIBRARY_INSTRUCTIONS_CHARS = 1500;
|
|
234
|
+
/** Normalize `mcpInstructions` to trimmed, non-empty lines, or null if absent or invalid. */
|
|
235
|
+
export function parseInstructions(raw, warn) {
|
|
236
|
+
if (raw == null)
|
|
237
|
+
return null;
|
|
238
|
+
const valid = typeof raw === 'string' || (Array.isArray(raw) && raw.every(it => typeof it === 'string'));
|
|
239
|
+
if (!valid) {
|
|
240
|
+
warn('ignored mcpInstructions: expected a string or an array of strings');
|
|
241
|
+
return null;
|
|
242
|
+
}
|
|
243
|
+
const text = [raw]
|
|
244
|
+
.flat()
|
|
245
|
+
.join('\n')
|
|
246
|
+
.split('\n')
|
|
247
|
+
.map(line => line.trim())
|
|
248
|
+
.filter(Boolean)
|
|
249
|
+
.join('\n');
|
|
250
|
+
if (text.length <= MAX_LIBRARY_INSTRUCTIONS_CHARS)
|
|
251
|
+
return text || null;
|
|
252
|
+
warn(`mcpInstructions cut to ${MAX_LIBRARY_INSTRUCTIONS_CHARS} of ${text.length} characters`);
|
|
253
|
+
return text.slice(0, MAX_LIBRARY_INSTRUCTIONS_CHARS - 3) + '...';
|
|
254
|
+
}
|
|
255
|
+
/**
|
|
256
|
+
* Find opted-in companion packages: the app package itself, then its direct `dependencies` and
|
|
257
|
+
* `devDependencies`. Transitive dependencies are not walked. `@xh/hoist` is skipped - its docs
|
|
258
|
+
* are always loaded as the primary library.
|
|
259
|
+
*/
|
|
260
|
+
function discoverCompanionPackages(appRoot) {
|
|
261
|
+
const appPkg = readPackageJson(appRoot);
|
|
262
|
+
if (!appPkg)
|
|
263
|
+
return [];
|
|
264
|
+
const candidates = [{ path: appRoot, pkg: appPkg }], depNames = new Set([
|
|
265
|
+
...Object.keys(appPkg.dependencies ?? {}),
|
|
266
|
+
...Object.keys(appPkg.devDependencies ?? {})
|
|
267
|
+
]);
|
|
268
|
+
for (const depName of depNames) {
|
|
269
|
+
const path = findInstalledPackage(appRoot, depName), pkg = path ? readPackageJson(path) : null;
|
|
270
|
+
if (path && pkg)
|
|
271
|
+
candidates.push({ path, pkg });
|
|
272
|
+
}
|
|
273
|
+
const seen = new Set();
|
|
274
|
+
return candidates.filter(({ pkg }) => {
|
|
275
|
+
if (typeof pkg.name !== 'string' || !pkg.name)
|
|
276
|
+
return false;
|
|
277
|
+
if (pkg.name === HOIST_PACKAGE || seen.has(pkg.name))
|
|
278
|
+
return false;
|
|
279
|
+
if (typeof pkg.hoist?.docRegistry !== 'string')
|
|
280
|
+
return false;
|
|
281
|
+
seen.add(pkg.name);
|
|
282
|
+
return true;
|
|
283
|
+
});
|
|
284
|
+
}
|
|
285
|
+
/** Memoized registry for the checkout being indexed. */
|
|
286
|
+
let cachedRegistry;
|
|
287
|
+
/**
|
|
288
|
+
* Load hoist-react's own doc registry for the checkout being indexed. Companion libraries build
|
|
289
|
+
* their own indexes, so none are discovered here.
|
|
290
|
+
*/
|
|
291
|
+
export function loadRegistry() {
|
|
292
|
+
cachedRegistry ??= buildRegistry(resolveRepoRoot());
|
|
293
|
+
return cachedRegistry;
|
|
294
|
+
}
|
|
295
|
+
//------------------------------------------------------------------
|
|
296
|
+
// File loading
|
|
297
|
+
//------------------------------------------------------------------
|
|
298
|
+
/**
|
|
299
|
+
* Read and return the full content of a document. A companion library doc has its relative links
|
|
300
|
+
* rewritten to full ids - see {@link rewriteRelativeLinks}.
|
|
301
|
+
*
|
|
302
|
+
* @throws Error if the file does not exist.
|
|
303
|
+
*/
|
|
304
|
+
export function loadDocContent(entry) {
|
|
305
|
+
if (!existsSync(entry.filePath)) {
|
|
306
|
+
throw new Error(`Document file not found: "${entry.id}" at ${entry.filePath}`);
|
|
307
|
+
}
|
|
308
|
+
const content = readFileSync(entry.filePath, 'utf-8');
|
|
309
|
+
return entry.links ? rewriteRelativeLinks(content, entry.path, entry.links) : content;
|
|
310
|
+
}
|
|
311
|
+
/** Inline link or image `](target`, capturing the lead and the target. */
|
|
312
|
+
const INLINE_LINK_RE = /(\]\(\s*<?)([^\s)>]+)/g;
|
|
313
|
+
/**
|
|
314
|
+
* A whole line that is a link reference definition, `[label]: target` with an optional title.
|
|
315
|
+
* Captures the lead, the target, and the rest. Excludes footnotes (`[^1]: text`) and prose such as
|
|
316
|
+
* `[Note]: remember this`, whose text after the target is not a title.
|
|
317
|
+
*/
|
|
318
|
+
const REF_DEF_RE = /^(\s{0,3}\[(?!\^)[^\]]+\]:\s*<?)([^\s>]+)(>?(?:\s+(?:"[^"]*"|'[^']*'|\([^)]*\)))?\s*)$/;
|
|
319
|
+
/**
|
|
320
|
+
* Fence that opens or closes a markdown code block. Any indent, so a fence nested in a list
|
|
321
|
+
* item counts too.
|
|
322
|
+
*/
|
|
323
|
+
const FENCE_RE = /^\s*(`{3,}|~{3,})/;
|
|
324
|
+
/**
|
|
325
|
+
* Rewrite relative links in a companion library doc so an agent can follow them. Read as
|
|
326
|
+
* written, `../core/README.md` in `@xh/hoist-chat-kit/docs/architecture.md` sends an agent to
|
|
327
|
+
* hoist-react's `core/README.md`, with no error to tell it the doc is the wrong one.
|
|
328
|
+
*
|
|
329
|
+
* A link to a served doc becomes its full id, prefixed with the package name. A link to any other
|
|
330
|
+
* file in the package, such as source or a doc not served here, becomes a file path under
|
|
331
|
+
* {@link DocLinkContext.sourcePath}. Leaves anchors, absolute paths, URLs, links that leave the
|
|
332
|
+
* package root, and code as they are. Keeps line numbers unchanged, so section line ranges still
|
|
333
|
+
* match the file.
|
|
334
|
+
*/
|
|
335
|
+
export function rewriteRelativeLinks(content, docPath, { library, docPaths, sourcePath }) {
|
|
336
|
+
const docDir = posix.dirname(docPath);
|
|
337
|
+
// The open fence, if inside a code block. It closes on a fence of the same character, at
|
|
338
|
+
// least as long.
|
|
339
|
+
let openFence = null;
|
|
340
|
+
return content
|
|
341
|
+
.split('\n')
|
|
342
|
+
.map(line => {
|
|
343
|
+
const fence = FENCE_RE.exec(line)?.[1];
|
|
344
|
+
if (fence) {
|
|
345
|
+
if (!openFence) {
|
|
346
|
+
openFence = fence;
|
|
347
|
+
}
|
|
348
|
+
else if (fence[0] === openFence[0] && fence.length >= openFence.length) {
|
|
349
|
+
openFence = null;
|
|
350
|
+
}
|
|
351
|
+
return line;
|
|
352
|
+
}
|
|
353
|
+
if (openFence)
|
|
354
|
+
return line;
|
|
355
|
+
const def = REF_DEF_RE.exec(line);
|
|
356
|
+
if (def)
|
|
357
|
+
return def[1] + rewrite(def[2]) + def[3];
|
|
358
|
+
// Odd segments are inline code spans, left as written.
|
|
359
|
+
return line
|
|
360
|
+
.split(/(`+[^`]*`+)/)
|
|
361
|
+
.map((seg, i) => i % 2 ? seg : seg.replace(INLINE_LINK_RE, (_, lead, t) => lead + rewrite(t)))
|
|
362
|
+
.join('');
|
|
363
|
+
})
|
|
364
|
+
.join('\n');
|
|
365
|
+
function rewrite(target) {
|
|
366
|
+
if (/^([a-z][a-z0-9+.-]*:|[#/])/i.test(target))
|
|
367
|
+
return target;
|
|
368
|
+
const hashAt = target.indexOf('#'), path = hashAt < 0 ? target : target.slice(0, hashAt), anchor = hashAt < 0 ? '' : target.slice(hashAt), resolved = posix.normalize(posix.join(docDir, path));
|
|
369
|
+
if (resolved === '..' || resolved.startsWith('../'))
|
|
370
|
+
return target;
|
|
371
|
+
if (resolved === '.')
|
|
372
|
+
return library + anchor;
|
|
373
|
+
const rewritten = docPaths.has(resolved)
|
|
374
|
+
? `${library}/${resolved}`
|
|
375
|
+
: posix.join(sourcePath.split(sep).join('/'), resolved);
|
|
376
|
+
return rewritten + anchor;
|
|
377
|
+
}
|
|
378
|
+
}
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Import path resolution for indexed symbols.
|
|
3
|
+
*
|
|
4
|
+
* The package barrel (`@xh/hoist/cmp/grid`) is the preferred import: apps use barrels far more
|
|
5
|
+
* than deep imports, and barrels are the curated API surface. The resolver finds it when one
|
|
6
|
+
* exists: `@xh/hoist/` plus the shallowest directory whose `index.ts` re-exports the symbol,
|
|
7
|
+
* walking from the declaring file upward and following any chain of `export * from` /
|
|
8
|
+
* `export {name} from` statements between barrels. When no barrel reaches an exported symbol,
|
|
9
|
+
* the file itself still imports - the package has no `exports` map - and the tools show
|
|
10
|
+
* {@link fileImportPath} instead.
|
|
11
|
+
*
|
|
12
|
+
* The barrel path is computed once per index build and stored on each `SymbolEntry`, so the
|
|
13
|
+
* disk cache carries it. The file path is derived at output time.
|
|
14
|
+
*/
|
|
15
|
+
import type { Project } from 'ts-morph';
|
|
16
|
+
/** Resolve the barrel import path of `name` declared in `filePath` (POSIX, absolute). */
|
|
17
|
+
export type ImportPathResolver = (filePath: string, name: string) => string | null;
|
|
18
|
+
/**
|
|
19
|
+
* Build a resolver over every `index.ts` barrel in the repo. Barrel reachability is computed
|
|
20
|
+
* lazily per barrel and memoized, since most barrels are only consulted for their own subtree.
|
|
21
|
+
*/
|
|
22
|
+
export declare function createImportPathResolver(project: Project, repoRoot: string): ImportPathResolver;
|
|
23
|
+
/**
|
|
24
|
+
* Import path of a declaring file (`@xh/hoist/data/cube/row/LeafRow`): `@xh/hoist/` plus the
|
|
25
|
+
* repo-relative file path without its extension. The import to show when no barrel re-exports
|
|
26
|
+
* a symbol - the package has no `exports` map, so a deep import always resolves.
|
|
27
|
+
*/
|
|
28
|
+
export declare function fileImportPath(relPath: string): string;
|
|
@@ -0,0 +1,107 @@
|
|
|
1
|
+
/*
|
|
2
|
+
* This file belongs to Hoist, an application development toolkit
|
|
3
|
+
* developed by Extremely Heavy Industries (www.xh.io | info@xh.io)
|
|
4
|
+
*
|
|
5
|
+
* Copyright © 2026 Extremely Heavy Industries Inc.
|
|
6
|
+
*/
|
|
7
|
+
import { getLibraryOptions, isLibrarySource } from '../util/paths.js';
|
|
8
|
+
/**
|
|
9
|
+
* Build a resolver over every `index.ts` barrel in the repo. Barrel reachability is computed
|
|
10
|
+
* lazily per barrel and memoized, since most barrels are only consulted for their own subtree.
|
|
11
|
+
*/
|
|
12
|
+
export function createImportPathResolver(project, repoRoot) {
|
|
13
|
+
const prefix = repoRoot + '/';
|
|
14
|
+
// Barrel file path keyed by its directory, relative to the repo root (`cmp/grid`).
|
|
15
|
+
const barrels = new Map();
|
|
16
|
+
for (const sf of project.getSourceFiles()) {
|
|
17
|
+
const path = sf.getFilePath();
|
|
18
|
+
if (!isLibrarySource(path, repoRoot) || !path.endsWith('/index.ts'))
|
|
19
|
+
continue;
|
|
20
|
+
barrels.set(path.slice(prefix.length, -'/index.ts'.length), sf);
|
|
21
|
+
}
|
|
22
|
+
const edgeCache = new Map(), reachCache = new Map();
|
|
23
|
+
/** Re-export statements of a file, resolved to their target source files. */
|
|
24
|
+
function edgesOf(sf) {
|
|
25
|
+
const path = sf.getFilePath();
|
|
26
|
+
let edges = edgeCache.get(path);
|
|
27
|
+
if (edges)
|
|
28
|
+
return edges;
|
|
29
|
+
edges = [];
|
|
30
|
+
for (const decl of sf.getExportDeclarations()) {
|
|
31
|
+
// `export * as ns from` exposes members as `ns.X`, not as direct imports.
|
|
32
|
+
if (!decl.hasModuleSpecifier() || decl.getNamespaceExport())
|
|
33
|
+
continue;
|
|
34
|
+
const target = decl.getModuleSpecifierSourceFile();
|
|
35
|
+
if (!target)
|
|
36
|
+
continue;
|
|
37
|
+
const named = decl.getNamedExports();
|
|
38
|
+
edges.push({
|
|
39
|
+
target: target.getFilePath(),
|
|
40
|
+
names: named.length ? new Set(named.map(n => n.getName())) : 'all'
|
|
41
|
+
});
|
|
42
|
+
}
|
|
43
|
+
edgeCache.set(path, edges);
|
|
44
|
+
return edges;
|
|
45
|
+
}
|
|
46
|
+
/** Every file a barrel reaches, with the names it re-exports from each. */
|
|
47
|
+
function reachOf(barrel) {
|
|
48
|
+
const start = barrel.getFilePath();
|
|
49
|
+
let reach = reachCache.get(start);
|
|
50
|
+
if (reach)
|
|
51
|
+
return reach;
|
|
52
|
+
reach = new Map();
|
|
53
|
+
const visit = (sf, allowed) => {
|
|
54
|
+
const path = sf.getFilePath(), prior = reach.get(path);
|
|
55
|
+
if (prior === 'all')
|
|
56
|
+
return;
|
|
57
|
+
if (allowed === 'all') {
|
|
58
|
+
reach.set(path, 'all');
|
|
59
|
+
}
|
|
60
|
+
else {
|
|
61
|
+
const merged = new Set(prior ?? []), before = merged.size;
|
|
62
|
+
allowed.forEach(n => merged.add(n));
|
|
63
|
+
if (prior && merged.size === before)
|
|
64
|
+
return;
|
|
65
|
+
reach.set(path, merged);
|
|
66
|
+
}
|
|
67
|
+
for (const edge of edgesOf(sf)) {
|
|
68
|
+
const names = edge.names, next = allowed === 'all'
|
|
69
|
+
? names
|
|
70
|
+
: names === 'all'
|
|
71
|
+
? allowed
|
|
72
|
+
: new Set([...allowed].filter(n => names.has(n)));
|
|
73
|
+
if (next !== 'all' && next.size === 0)
|
|
74
|
+
continue;
|
|
75
|
+
const target = project.getSourceFile(edge.target);
|
|
76
|
+
if (target)
|
|
77
|
+
visit(target, next);
|
|
78
|
+
}
|
|
79
|
+
};
|
|
80
|
+
visit(barrel, 'all');
|
|
81
|
+
reachCache.set(start, reach);
|
|
82
|
+
return reach;
|
|
83
|
+
}
|
|
84
|
+
return (filePath, name) => {
|
|
85
|
+
if (!isLibrarySource(filePath, repoRoot))
|
|
86
|
+
return null;
|
|
87
|
+
const segments = filePath.slice(prefix.length).split('/').slice(0, -1);
|
|
88
|
+
for (let depth = 1; depth <= segments.length; depth++) {
|
|
89
|
+
const dir = segments.slice(0, depth).join('/'), barrel = barrels.get(dir);
|
|
90
|
+
if (!barrel)
|
|
91
|
+
continue;
|
|
92
|
+
const exported = reachOf(barrel).get(filePath);
|
|
93
|
+
if (exported === 'all' || (exported != null && exported.has(name))) {
|
|
94
|
+
return `${getLibraryOptions().importPrefix}/${dir}`;
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
return null;
|
|
98
|
+
};
|
|
99
|
+
}
|
|
100
|
+
/**
|
|
101
|
+
* Import path of a declaring file (`@xh/hoist/data/cube/row/LeafRow`): `@xh/hoist/` plus the
|
|
102
|
+
* repo-relative file path without its extension. The import to show when no barrel re-exports
|
|
103
|
+
* a symbol - the package has no `exports` map, so a deep import always resolves.
|
|
104
|
+
*/
|
|
105
|
+
export function fileImportPath(relPath) {
|
|
106
|
+
return `${getLibraryOptions().importPrefix}/${relPath.replace(/\.tsx?$/, '')}`;
|
|
107
|
+
}
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
import type { SymbolEntry, MemberIndexEntry, SymbolDetail } from './ts-registry.ts';
|
|
2
|
+
export interface CachedIndexes {
|
|
3
|
+
symbols: Map<string, SymbolEntry[]>;
|
|
4
|
+
members: Map<string, MemberIndexEntry[]>;
|
|
5
|
+
promiseExtensions: Map<string, SymbolDetail>;
|
|
6
|
+
}
|
|
7
|
+
/**
|
|
8
|
+
* Hash all candidate source files (path + mtime + size) plus `package.json`,
|
|
9
|
+
* yielding a fingerprint that changes whenever any indexable file or the
|
|
10
|
+
* package version changes. Mirrors the file-set filter applied in
|
|
11
|
+
* `buildSymbolIndex` so the fingerprint and the indexed file set stay in sync.
|
|
12
|
+
*
|
|
13
|
+
* Walks the repo tree once, one stat per `.ts`/`.tsx` file outside the excluded
|
|
14
|
+
* directories. Sub-100ms on a fast disk.
|
|
15
|
+
*/
|
|
16
|
+
export declare function computeFingerprint(repoRoot: string): string;
|
|
17
|
+
/**
|
|
18
|
+
* Try to load cached indexes for the given repo. Returns `null` if the cache
|
|
19
|
+
* is missing, malformed, schema-mismatched, or fingerprint-stale - in any of
|
|
20
|
+
* those cases the caller should fall back to a fresh build.
|
|
21
|
+
*
|
|
22
|
+
* Set `HOIST_MCP_NO_CACHE=1` in the environment to bypass cache reads (useful
|
|
23
|
+
* for debugging).
|
|
24
|
+
*/
|
|
25
|
+
export declare function loadCache(repoRoot: string): CachedIndexes | null;
|
|
26
|
+
/**
|
|
27
|
+
* Write index data to disk atomically (write-to-tmp then rename). Failures
|
|
28
|
+
* are logged but non-fatal - the next invocation just rebuilds.
|
|
29
|
+
*/
|
|
30
|
+
export declare function writeCache(repoRoot: string, fingerprint: string, indexes: CachedIndexes): void;
|