@xh/hoist-docs 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.
Files changed (62) hide show
  1. package/LICENSE.md +190 -0
  2. package/README.md +145 -2
  3. package/bin/hoist-docs.mjs +16 -0
  4. package/dist/IndexStore.d.ts +78 -0
  5. package/dist/IndexStore.js +249 -0
  6. package/dist/cli.d.ts +11 -0
  7. package/dist/cli.js +258 -0
  8. package/dist/config.d.ts +17 -0
  9. package/dist/config.js +18 -0
  10. package/dist/docs/index.d.ts +70 -0
  11. package/dist/docs/index.js +101 -0
  12. package/dist/index/DocEntry.d.ts +16 -0
  13. package/dist/index/DocEntry.js +32 -0
  14. package/dist/index/DocIdResolver.d.ts +31 -0
  15. package/dist/index/DocIdResolver.js +159 -0
  16. package/dist/index/DocSearch.d.ts +41 -0
  17. package/dist/index/DocSearch.js +180 -0
  18. package/dist/index/LibraryIndex.d.ts +62 -0
  19. package/dist/index/LibraryIndex.js +153 -0
  20. package/dist/index/SymbolSearch.d.ts +52 -0
  21. package/dist/index/SymbolSearch.js +249 -0
  22. package/dist/index/doc-sections.d.ts +94 -0
  23. package/dist/index/doc-sections.js +260 -0
  24. package/dist/index/search-text.d.ts +78 -0
  25. package/dist/index/search-text.js +140 -0
  26. package/dist/index/types.d.ts +115 -0
  27. package/dist/index/types.js +11 -0
  28. package/dist/libraries.d.ts +57 -0
  29. package/dist/libraries.js +38 -0
  30. package/dist/local/cache.d.ts +25 -0
  31. package/dist/local/cache.js +62 -0
  32. package/dist/local/checkout.d.ts +6 -0
  33. package/dist/local/checkout.js +178 -0
  34. package/dist/local/installed.d.ts +22 -0
  35. package/dist/local/installed.js +99 -0
  36. package/dist/local/maven.d.ts +49 -0
  37. package/dist/local/maven.js +184 -0
  38. package/dist/local/npm.d.ts +24 -0
  39. package/dist/local/npm.js +66 -0
  40. package/dist/local/project.d.ts +26 -0
  41. package/dist/local/project.js +103 -0
  42. package/dist/local/registry.d.ts +15 -0
  43. package/dist/local/registry.js +67 -0
  44. package/dist/local/sources.d.ts +30 -0
  45. package/dist/local/sources.js +50 -0
  46. package/dist/local/tar.d.ts +6 -0
  47. package/dist/local/tar.js +31 -0
  48. package/dist/log.d.ts +10 -0
  49. package/dist/log.js +31 -0
  50. package/dist/mcp.d.ts +23 -0
  51. package/dist/mcp.js +396 -0
  52. package/dist/server.d.ts +15 -0
  53. package/dist/server.js +88 -0
  54. package/dist/tools/DocTools.d.ts +19 -0
  55. package/dist/tools/DocTools.js +245 -0
  56. package/dist/tools/SymbolTools.d.ts +27 -0
  57. package/dist/tools/SymbolTools.js +572 -0
  58. package/dist/tools/types.d.ts +6 -0
  59. package/dist/tools/types.js +7 -0
  60. package/dist/usage.d.ts +10 -0
  61. package/dist/usage.js +11 -0
  62. package/package.json +62 -4
@@ -0,0 +1,249 @@
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 { readdirSync, statSync } from 'node:fs';
8
+ import { join, resolve } from 'node:path';
9
+ import { LibraryIndex } from './index/LibraryIndex.js';
10
+ import { LIBRARIES } from './libraries.js';
11
+ import { log } from './log.js';
12
+ /** Libraries in display order. hoist-react comes first, so its doc ids win when unqualified. */
13
+ const LIBRARY_ORDER = LIBRARIES.map(l => l.id);
14
+ const FILE_RE = /^([a-z][a-z0-9-]*)-(.+?)\.json(\.gz)?$/;
15
+ /** How long a directory scan is trusted before the next request rescans. */
16
+ const RESCAN_MS = 5_000;
17
+ /** On demand: how long a library's newest release is trusted before the registry is asked again. */
18
+ const LATEST_RECHECK_MS = 60 * 60 * 1000;
19
+ /** On demand: how long a failed fetch is remembered before it is tried again. */
20
+ const RETRY_MS = 5 * 60 * 1000;
21
+ /** Thrown for a library or version with no index file. */
22
+ export class NotFoundError extends Error {
23
+ }
24
+ /**
25
+ * The index files the tool serves, from one of three sources:
26
+ *
27
+ * - **A directory** of `<libraryId>-<version>.json[.gz]` files (see docs/index-schema.md), for
28
+ * HTTP deployments without registry access, and development. It may hold several versions of
29
+ * each library.
30
+ * - **Explicit files**, for the local tool: one per library, for the project's own versions.
31
+ * - **On demand**, for HTTP deployments: the built-in libraries' indexes, fetched from each
32
+ * library's own channel (its npm package, or its Maven `docs-index` artifact) and cached as
33
+ * calls ask for each library and version (see {@link ensure}), the newest release of each by
34
+ * default.
35
+ *
36
+ * Each file is parsed on first use and held in memory. Sources are rechecked at most every few
37
+ * seconds, and a file that changed on disk is reloaded, so freshly built indexes are picked up
38
+ * without a restart.
39
+ */
40
+ export class IndexStore {
41
+ /** The directory scanned, or null for explicit files. */
42
+ dir;
43
+ /** True when indexes are fetched as they are asked for. */
44
+ onDemand;
45
+ specs;
46
+ source = null;
47
+ /** On demand: `<libraryId>@<version or 'latest'>` -> the fetch, finished or in flight. */
48
+ fetches = new Map();
49
+ /** libraryId -> version -> file */
50
+ files = new Map();
51
+ loaded = new Map();
52
+ lastScan = 0;
53
+ missingDirWarned = false;
54
+ constructor(source) {
55
+ this.onDemand = false;
56
+ if (typeof source === 'string') {
57
+ this.dir = resolve(source);
58
+ this.specs = null;
59
+ }
60
+ else if (Array.isArray(source)) {
61
+ this.dir = null;
62
+ this.specs = source.map(s => ({ ...s, path: resolve(s.path) }));
63
+ }
64
+ else {
65
+ this.dir = null;
66
+ this.specs = [];
67
+ this.source = source.source;
68
+ this.onDemand = true;
69
+ }
70
+ }
71
+ /**
72
+ * On demand, fetch what a call needs: `version` of `libraryId`, else the newest release of
73
+ * `libraryId`, else the newest release of every built-in library. A no-op for the other
74
+ * sources. A library with nothing published is skipped with a warning when not asked for by
75
+ * name; asked for by name, it fails with a {@link NotFoundError}.
76
+ */
77
+ async ensure(libraryId, version) {
78
+ if (!this.source)
79
+ return;
80
+ if (!libraryId) {
81
+ await Promise.all(LIBRARIES.map(l => this.fetch(l.id, null, false)));
82
+ return;
83
+ }
84
+ if (!LIBRARY_ORDER.includes(libraryId)) {
85
+ throw new NotFoundError(`Unknown library '${libraryId}'. Libraries: ${LIBRARY_ORDER.join(', ')}`);
86
+ }
87
+ await this.fetch(libraryId, version || null, true);
88
+ }
89
+ /** Scan the directory and load the newest version of every library. */
90
+ init() {
91
+ this.scan();
92
+ this.latest();
93
+ }
94
+ /** Library ids with at least one index file, in display order. */
95
+ libraryIds() {
96
+ this.maybeRescan();
97
+ const rank = (id) => {
98
+ const i = LIBRARY_ORDER.indexOf(id);
99
+ return i < 0 ? 99 : i;
100
+ };
101
+ return [...this.files.keys()].sort((a, b) => rank(a) - rank(b) || a.localeCompare(b));
102
+ }
103
+ /** Available versions of a library, newest first. */
104
+ versions(libraryId) {
105
+ this.maybeRescan();
106
+ return [...(this.files.get(libraryId)?.keys() ?? [])].sort(compareVersions).reverse();
107
+ }
108
+ /** The index for a library at a version - the newest when no version is given. */
109
+ get(libraryId, version) {
110
+ this.maybeRescan();
111
+ const byVersion = this.files.get(libraryId);
112
+ if (!byVersion) {
113
+ throw new NotFoundError(`No index loaded for library '${libraryId}'. Available: ${this.libraryIds().join(', ')}`);
114
+ }
115
+ const v = version || this.versions(libraryId)[0], file = byVersion.get(v);
116
+ if (!file) {
117
+ throw new NotFoundError(`No index for ${libraryId} version '${v}'. Available: ${this.versions(libraryId).join(', ')}`);
118
+ }
119
+ const key = `${libraryId}@${v}`, cached = this.loaded.get(key);
120
+ if (cached && cached.mtimeMs === file.mtimeMs)
121
+ return cached.index;
122
+ const start = Date.now(), index = LibraryIndex.load(file.path, { trusted: file.trusted });
123
+ this.loaded.set(key, { index, mtimeMs: file.mtimeMs });
124
+ log.info('Loaded index', { file: file.path, elapsedMs: Date.now() - start });
125
+ return index;
126
+ }
127
+ /** Path of the index file for a library version - the newest when no version is given. */
128
+ filePath(libraryId, version) {
129
+ this.maybeRescan();
130
+ const v = version || this.versions(libraryId)[0], file = this.files.get(libraryId)?.get(v);
131
+ if (!file)
132
+ throw new NotFoundError(`No index for ${libraryId} version '${v}'`);
133
+ return file.path;
134
+ }
135
+ /** The newest index of every library, in display order. */
136
+ latest() {
137
+ return this.libraryIds().map(id => this.get(id));
138
+ }
139
+ //------------------------
140
+ // Implementation
141
+ //------------------------
142
+ async fetch(libraryId, version, required) {
143
+ const key = `${libraryId}@${version ?? 'latest'}`, now = Date.now();
144
+ let entry = this.fetches.get(key);
145
+ const maxAgeMs = entry?.failed ? RETRY_MS : version ? Infinity : LATEST_RECHECK_MS;
146
+ if (!entry || now - entry.at > maxAgeMs) {
147
+ const fresh = {
148
+ at: now,
149
+ failed: false,
150
+ done: this.resolve(libraryId, version)
151
+ };
152
+ fresh.done.then(r => (fresh.failed = 'error' in r));
153
+ this.fetches.set(key, (entry = fresh));
154
+ }
155
+ const result = await entry.done;
156
+ if ('error' in result && required)
157
+ throw new NotFoundError(result.error);
158
+ }
159
+ /** Resolve and register one index file, returning its path, or the error with a warning. */
160
+ async resolve(libraryId, version) {
161
+ const source = this.source;
162
+ try {
163
+ const v = version ?? (await source.latestRelease(libraryId)), path = resolve((await source.resolve(libraryId, v)).path), specs = this.specs;
164
+ if (!specs.some(s => s.libraryId === libraryId && s.version === v)) {
165
+ specs.push({ libraryId, version: v, path });
166
+ this.lastScan = 0;
167
+ }
168
+ return { path };
169
+ }
170
+ catch (e) {
171
+ log.warn('Could not fetch index', { libraryId, version, error: String(e) });
172
+ return { error: e.message ?? String(e) };
173
+ }
174
+ }
175
+ maybeRescan() {
176
+ if (Date.now() - this.lastScan > RESCAN_MS)
177
+ this.scan();
178
+ }
179
+ scan() {
180
+ this.lastScan = Date.now();
181
+ if (this.specs) {
182
+ const ret = new Map();
183
+ for (const { libraryId, version, path, trusted = true } of this.specs) {
184
+ let byVersion = ret.get(libraryId);
185
+ if (!byVersion)
186
+ ret.set(libraryId, (byVersion = new Map()));
187
+ byVersion.set(version, { path, mtimeMs: statSync(path).mtimeMs, trusted });
188
+ }
189
+ this.files = ret;
190
+ return;
191
+ }
192
+ const dir = this.dir, ret = new Map();
193
+ let names;
194
+ try {
195
+ names = readdirSync(dir);
196
+ }
197
+ catch {
198
+ if (!this.missingDirWarned) {
199
+ log.warn('Index directory not found - no docs will be served', { dir });
200
+ this.missingDirWarned = true;
201
+ }
202
+ this.files = ret;
203
+ return;
204
+ }
205
+ for (const name of names) {
206
+ const m = FILE_RE.exec(name);
207
+ if (!m)
208
+ continue;
209
+ const [, lib, version] = m, path = join(dir, name);
210
+ let byVersion = ret.get(lib);
211
+ if (!byVersion)
212
+ ret.set(lib, (byVersion = new Map()));
213
+ // Prefer the uncompressed file when both exist.
214
+ if (!byVersion.has(version) || !name.endsWith('.gz')) {
215
+ byVersion.set(version, { path, mtimeMs: statSync(path).mtimeMs, trusted: true });
216
+ }
217
+ }
218
+ const summary = (m) => JSON.stringify([...m].map(([k, v]) => [k, [...v.keys()].sort(compareVersions)]));
219
+ if (summary(ret) !== summary(this.files)) {
220
+ log.info('Index files found', {
221
+ dir,
222
+ libraries: Object.fromEntries([...ret].map(([k, v]) => [k, [...v.keys()].sort(compareVersions)]))
223
+ });
224
+ }
225
+ this.missingDirWarned = false;
226
+ this.files = ret;
227
+ }
228
+ }
229
+ /** Orders versions numerically by segment; a SNAPSHOT sorts before its release. */
230
+ export function compareVersions(a, b) {
231
+ const pa = parseVersion(a), pb = parseVersion(b);
232
+ for (let i = 0; i < Math.max(pa.nums.length, pb.nums.length); i++) {
233
+ const c = (pa.nums[i] ?? 0) - (pb.nums[i] ?? 0);
234
+ if (c)
235
+ return c;
236
+ }
237
+ if (pa.snapshot !== pb.snapshot)
238
+ return pa.snapshot ? -1 : 1;
239
+ return a < b ? -1 : a > b ? 1 : 0;
240
+ }
241
+ function parseVersion(v) {
242
+ return {
243
+ snapshot: /snapshot/i.test(v),
244
+ nums: v
245
+ .replace(/-SNAPSHOT.*/i, '')
246
+ .split(/[.-]/)
247
+ .map(s => (/^\d+$/.test(s) ? parseInt(s) : 0))
248
+ };
249
+ }
package/dist/cli.d.ts ADDED
@@ -0,0 +1,11 @@
1
+ import { type Fetcher } from './local/maven.ts';
2
+ import { type Registry } from './local/registry.ts';
3
+ export interface CliDeps {
4
+ registry?: Registry;
5
+ cacheDir?: string;
6
+ mavenFetcher?: Fetcher;
7
+ }
8
+ /** Run the command. Exported for tests; `bin/hoist-docs.mjs` and `pnpm start` call it. */
9
+ export declare function main(argv: string[], deps?: CliDeps): Promise<void>;
10
+ /** Entry point: report failures on stderr and exit non-zero. */
11
+ export declare function run(argv: string[]): Promise<void>;
package/dist/cli.js ADDED
@@ -0,0 +1,258 @@
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
+ * The `hoist-docs` command.
9
+ *
10
+ * hoist-docs MCP over stdio, for the project in the current directory: serves
11
+ * the indexes its installed packages ship, and hoist-core's from
12
+ * Maven.
13
+ * hoist-docs --http MCP over HTTP, fetching indexes from each library's own channel
14
+ * as asked for, or from an index directory. For MCP gateways and
15
+ * development.
16
+ * hoist-docs export-docs --out <dir> [--from-checkout <dir> ...]
17
+ * Write the docs part of the project's indexes, for a docs viewer
18
+ * such as Toolbox's (see `@xh/hoist-docs/docs`). With
19
+ * --from-checkout, read docs straight from hoist-react and
20
+ * hoist-core checkouts instead, in a second or two.
21
+ *
22
+ * Options: --project <dir> (default: current directory), --index-dir <dir> (serve or export the
23
+ * indexes in a directory instead of resolving the project's), --port <n> (HTTP), --help.
24
+ * Environment: see the Configuration table in docs/design.md.
25
+ */
26
+ import { mkdirSync, readFileSync, watch, writeFileSync } from 'node:fs';
27
+ import { dirname, join, resolve } from 'node:path';
28
+ import { serveStdio } from '@modelcontextprotocol/server/stdio';
29
+ import { loadConfig } from './config.js';
30
+ import { extractDocs } from './docs/index.js';
31
+ import { IndexStore } from './IndexStore.js';
32
+ import { LibraryIndex } from './index/LibraryIndex.js';
33
+ import { libraryDef } from './libraries.js';
34
+ import { IndexCache } from './local/cache.js';
35
+ import { docsFromCheckout } from './local/checkout.js';
36
+ import { findInstalledIndexes } from './local/installed.js';
37
+ import { MavenSource } from './local/maven.js';
38
+ import { NpmSource } from './local/npm.js';
39
+ import { detectProjectVersions, LATEST_SNAPSHOT } from './local/project.js';
40
+ import { NpmRegistry } from './local/registry.js';
41
+ import { BuiltInSource } from './local/sources.js';
42
+ import { errorData, log, logToStderr } from './log.js';
43
+ import { createMcpServer } from './mcp.js';
44
+ import { createApp } from './server.js';
45
+ const USAGE = `Usage:
46
+ hoist-docs [--project <dir>] [--index-dir <dir>]
47
+ MCP over stdio for the project's installed Hoist versions (the default; for agents).
48
+ hoist-docs --http [--index-dir <dir>] [--port <n>]
49
+ MCP over HTTP, for MCP gateways and development.
50
+ hoist-docs export-docs --out <dir> [--project <dir>] [--index-dir <dir>]
51
+ Write docs payloads for a docs viewer, from the project's own Hoist versions.
52
+ hoist-docs export-docs --out <dir> --from-checkout <dir> [--from-checkout <dir>] [--watch]
53
+ Write docs payloads straight from hoist-react and hoist-core checkouts; with --watch, again
54
+ on every doc change, for live preview.`;
55
+ /** Run the command. Exported for tests; `bin/hoist-docs.mjs` and `pnpm start` call it. */
56
+ export async function main(argv, deps = {}) {
57
+ const args = parseArgs(argv), config = loadConfig(process.env, packageVersion());
58
+ if (args.flags.has('help')) {
59
+ process.stderr.write(USAGE + '\n');
60
+ return;
61
+ }
62
+ if (args.command === 'export-docs') {
63
+ logToStderr();
64
+ await exportDocs(args, deps);
65
+ return;
66
+ }
67
+ if (args.flags.has('http')) {
68
+ if (args.values.port)
69
+ config.port = parseInt(args.values.port);
70
+ const indexDir = args.values['index-dir'] || config.indexDir, store = indexDir
71
+ ? new IndexStore(indexDir)
72
+ : new IndexStore({ source: builtInSource(deps) });
73
+ if (store.onDemand)
74
+ await store.ensure();
75
+ store.init();
76
+ createApp(config, store).listen(config.port, () => {
77
+ log.info('Hoist Docs started', {
78
+ port: config.port,
79
+ indexDir: store.dir ?? "on demand, from each library's own channel",
80
+ libraries: Object.fromEntries(store.libraryIds().map(id => [id, store.versions(id)])),
81
+ version: config.version
82
+ });
83
+ });
84
+ return;
85
+ }
86
+ logToStderr();
87
+ const store = await projectStore(args, deps);
88
+ store.init();
89
+ log.info('Hoist Docs serving over stdio', {
90
+ version: config.version,
91
+ libraries: Object.fromEntries(store.libraryIds().map(id => [id, store.versions(id)[0]]))
92
+ });
93
+ serveStdio(() => createMcpServer(store, config), {
94
+ onerror: e => log.warn('MCP stdio error', errorData(e))
95
+ });
96
+ }
97
+ /**
98
+ * The indexes to serve: an explicit directory (--index-dir, else a non-empty INDEX_DIR), else the
99
+ * project's own - every index its installed packages ship, plus hoist-core's from Maven. In a
100
+ * library checkout, libraries not installed there get their newest published snapshots.
101
+ */
102
+ async function projectStore(args, deps) {
103
+ const indexDir = args.values['index-dir'] || process.env.INDEX_DIR;
104
+ if (indexDir)
105
+ return new IndexStore(indexDir);
106
+ const root = resolve(args.values.project ?? '.'), detected = detectProjectVersions(root), installed = findInstalledIndexes(root);
107
+ [...detected.notes, ...installed.notes].forEach(note => log.warn(note));
108
+ const specs = installed.indexes.map(i => ({
109
+ libraryId: i.libraryId,
110
+ version: i.version,
111
+ path: i.path,
112
+ trusted: i.trusted
113
+ })), source = builtInSource(deps);
114
+ for (const [libraryId, version] of Object.entries(detected.versions)) {
115
+ if (specs.some(s => s.libraryId === libraryId))
116
+ continue;
117
+ const lib = libraryDef(libraryId);
118
+ try {
119
+ let wanted = version;
120
+ if (!lib.maven && version !== LATEST_SNAPSHOT) {
121
+ // An installed npm library that ships no index: a release from before indexes
122
+ // shipped. A checkout can fall back to the newest snapshot; an app cannot.
123
+ const missing = `${lib.packageName} ${version} is installed but ships no Hoist Docs index - releases from before Hoist Docs shipped indexes carry none. Upgrade it, or serve an index directory (INDEX_DIR).`;
124
+ if (!detected.checkout)
125
+ throw new Error(missing);
126
+ log.warn(`${missing} Serving its newest snapshot instead.`);
127
+ wanted = LATEST_SNAPSHOT;
128
+ }
129
+ const r = await source.resolve(libraryId, wanted);
130
+ specs.push({ libraryId, version: r.version, path: r.path });
131
+ }
132
+ catch (e) {
133
+ // hoist-react and hoist-core are what the tool is for, so their failure is fatal. An
134
+ // optional library is skipped, so it never costs the app the others.
135
+ if (!lib.optional)
136
+ throw e;
137
+ log.warn(`Skipping ${libraryId} ${version}: ${e.message}`);
138
+ }
139
+ }
140
+ if (!specs.length) {
141
+ throw new Error(`No Hoist versions found in ${root}: expected an installed @xh/hoist (client-app/node_modules) or hoistCoreVersion in gradle.properties. Run from the project root, or pass --project.`);
142
+ }
143
+ return new IndexStore(specs);
144
+ }
145
+ /** The built-in libraries' own channels: npm packages and Maven artifacts. */
146
+ function builtInSource(deps) {
147
+ const cache = new IndexCache(deps.cacheDir), maven = deps.mavenFetcher
148
+ ? new MavenSource({ cache, fetcher: deps.mavenFetcher })
149
+ : MavenSource.fromEnv(process.env, cache);
150
+ return new BuiltInSource(new NpmSource(deps.registry ?? new NpmRegistry(), cache), maven);
151
+ }
152
+ /** Write `<out>/<libraryId>.json` docs payloads, plus `<out>/index.json` listing them. */
153
+ async function exportDocs(args, deps) {
154
+ const out = args.values.out;
155
+ if (!out)
156
+ throw new Error('export-docs needs --out <dir>');
157
+ if (args.checkouts.length) {
158
+ const write = () => writePayloads(out, args.checkouts.map(dir => docsFromCheckout(dir)));
159
+ write();
160
+ if (args.flags.has('watch'))
161
+ await watchCheckouts(args.checkouts, write);
162
+ return;
163
+ }
164
+ if (args.flags.has('watch'))
165
+ throw new Error('--watch needs --from-checkout');
166
+ const store = await projectStore(args, deps);
167
+ writePayloads(out, store.libraryIds().map(id => extractDocs(LibraryIndex.readJson(store.filePath(id)))));
168
+ }
169
+ function writePayloads(out, payloads) {
170
+ mkdirSync(out, { recursive: true });
171
+ const manifest = payloads.map(payload => {
172
+ const { id, name, version } = payload.library, file = `${id}.json`;
173
+ writeFileSync(join(out, file), JSON.stringify(payload));
174
+ log.info('Exported docs', { library: id, version, file: join(out, file) });
175
+ return { id, name, version, file };
176
+ });
177
+ writeFileSync(join(out, 'index.json'), JSON.stringify(manifest, null, 2));
178
+ }
179
+ /**
180
+ * Re-export whenever a doc or the registry changes, until interrupted. Watches only the folders
181
+ * holding registered docs - not whole checkouts, whose `node_modules` would be costly to watch.
182
+ */
183
+ async function watchCheckouts(checkouts, write) {
184
+ let timer = null;
185
+ const onChange = (file) => {
186
+ if (file && !/\.md$|doc-registry\.json$/.test(file))
187
+ return;
188
+ if (timer)
189
+ clearTimeout(timer);
190
+ timer = setTimeout(() => {
191
+ try {
192
+ write();
193
+ }
194
+ catch (e) {
195
+ log.warn('Re-export failed', errorData(e));
196
+ }
197
+ }, 200);
198
+ };
199
+ const dirs = new Set();
200
+ for (const checkout of checkouts) {
201
+ const root = resolve(checkout);
202
+ dirs.add(join(root, 'docs'));
203
+ for (const e of docsFromCheckout(root).docs.entries)
204
+ dirs.add(dirname(join(root, e.id)));
205
+ }
206
+ for (const dir of dirs)
207
+ watch(dir, (_, file) => onChange(file));
208
+ log.info('Watching docs for changes', { folders: dirs.size });
209
+ await new Promise(() => { });
210
+ }
211
+ const VALUE_OPTIONS = new Set(['project', 'index-dir', 'port', 'out']);
212
+ function parseArgs(argv) {
213
+ const ret = { command: null, flags: new Set(), values: {}, checkouts: [] };
214
+ for (let i = 0; i < argv.length; i++) {
215
+ const arg = argv[i];
216
+ if (arg.startsWith('--')) {
217
+ const [name, inline] = arg.slice(2).split('=', 2);
218
+ if (name === 'from-checkout')
219
+ ret.checkouts.push(inline ?? argv[++i]);
220
+ else if (VALUE_OPTIONS.has(name))
221
+ ret.values[name] = inline ?? argv[++i];
222
+ else
223
+ ret.flags.add(name);
224
+ }
225
+ else if (!ret.command) {
226
+ ret.command = arg;
227
+ }
228
+ else {
229
+ throw new Error(`Unexpected argument: ${arg}\n${USAGE}`);
230
+ }
231
+ }
232
+ if (ret.command && ret.command !== 'export-docs') {
233
+ throw new Error(`Unknown command: ${ret.command}\n${USAGE}`);
234
+ }
235
+ return ret;
236
+ }
237
+ function packageVersion() {
238
+ try {
239
+ return JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8'))
240
+ .version;
241
+ }
242
+ catch {
243
+ return 'dev';
244
+ }
245
+ }
246
+ /** Entry point: report failures on stderr and exit non-zero. */
247
+ export async function run(argv) {
248
+ try {
249
+ await main(argv);
250
+ }
251
+ catch (e) {
252
+ log.debug('hoist-docs failed', errorData(e));
253
+ process.stderr.write(`hoist-docs: ${e?.message ?? e}\n`);
254
+ process.exitCode = 1;
255
+ }
256
+ }
257
+ if (import.meta.main)
258
+ await run(process.argv.slice(2));
@@ -0,0 +1,17 @@
1
+ /** Service configuration, from environment variables. See the Configuration table in docs/design.md. */
2
+ export interface Config {
3
+ port: number;
4
+ /**
5
+ * HTTP: a directory of index files to serve. Null to fetch the built-in libraries' indexes
6
+ * through npm as they are asked for.
7
+ */
8
+ indexDir: string | null;
9
+ logQueries: boolean;
10
+ /**
11
+ * Browser origins allowed to call the HTTP endpoint, besides localhost. Requests with no
12
+ * `Origin` header (agents, gateways - anything but a browser) are always allowed.
13
+ */
14
+ allowedOrigins: string[];
15
+ version: string;
16
+ }
17
+ export declare function loadConfig(env?: Record<string, string | undefined>, version?: string): Config;
package/dist/config.js ADDED
@@ -0,0 +1,18 @@
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
+ export function loadConfig(env = process.env, version = 'dev') {
8
+ return {
9
+ port: parseInt(env.PORT ?? '') || 8081,
10
+ indexDir: env.INDEX_DIR || null,
11
+ logQueries: env.LOG_QUERIES === 'true',
12
+ allowedOrigins: (env.ALLOWED_ORIGINS ?? '')
13
+ .split(',')
14
+ .map(s => s.trim())
15
+ .filter(Boolean),
16
+ version
17
+ };
18
+ }
@@ -0,0 +1,70 @@
1
+ /**
2
+ * Browser-safe docs library: registry, content and ranked search over the docs of one or more
3
+ * Hoist libraries, for docs viewers such as Toolbox's. Same ranking as the MCP tools, because it
4
+ * is the same code. Imports nothing from Node, so it bundles for the browser.
5
+ *
6
+ * Input is a docs payload per library: the docs part of an index file, written by
7
+ * `hoist-docs export-docs` (see {@link extractDocs}). Results keep the shapes of the former
8
+ * `docs/*` HTTP API, which Toolbox's viewer already reads.
9
+ */
10
+ import { DocEntry } from '../index/DocEntry.ts';
11
+ import { DocSearch } from '../index/DocSearch.ts';
12
+ import { type Category, type IndexFile, type LibraryInfo } from '../index/types.ts';
13
+ /** The docs part of an index file: everything a viewer needs, without the symbols. */
14
+ export interface DocsPayload {
15
+ schemaVersion: number;
16
+ library: LibraryInfo;
17
+ docs: IndexFile['docs'];
18
+ }
19
+ export interface RegistryEntry {
20
+ id: string;
21
+ source: string;
22
+ title: string;
23
+ category: string;
24
+ description: string;
25
+ keywords: string[];
26
+ }
27
+ export interface SourceInfo {
28
+ label: string;
29
+ categories: Category[];
30
+ version: string;
31
+ versions: string[];
32
+ }
33
+ export interface DocsSearchResult {
34
+ source: string;
35
+ id: string;
36
+ score: number;
37
+ /** Ref of the best-matching section, to pass when reading. */
38
+ section: string;
39
+ snippet: string;
40
+ }
41
+ /** The docs part of a full index file. */
42
+ export declare function extractDocs(index: IndexFile): DocsPayload;
43
+ /** One library's docs, searchable. */
44
+ export declare class LibraryDocs {
45
+ readonly library: LibraryInfo;
46
+ /** Source name viewers use for this library: `hoist-react`, `hoist-core`, or the library id. */
47
+ readonly source: string;
48
+ readonly categories: Category[];
49
+ readonly docs: DocEntry[];
50
+ readonly docsById: Map<string, DocEntry>;
51
+ private _search;
52
+ constructor(payload: DocsPayload);
53
+ /** Search index, built on first use. */
54
+ get docSearch(): DocSearch;
55
+ }
56
+ /** The docs of several libraries, hoist-react first. */
57
+ export declare class DocsCatalog {
58
+ readonly libraries: LibraryDocs[];
59
+ constructor(payloads: DocsPayload[]);
60
+ /** Every doc, with each source's categories and version. */
61
+ registry(): {
62
+ entries: RegistryEntry[];
63
+ sources: Record<string, SourceInfo>;
64
+ };
65
+ /** Markdown of one doc, or null if the source has no such doc. */
66
+ content(source: string, docId: string): string | null;
67
+ /** Ranked docs across every library, each once under its best-matching section. */
68
+ search(query: string, limit?: number): DocsSearchResult[];
69
+ private librarySource;
70
+ }