@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,38 @@
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 const LIBRARIES = [
8
+ {
9
+ id: 'react',
10
+ label: 'Hoist React',
11
+ source: 'hoist-react',
12
+ packageName: '@xh/hoist',
13
+ installed: { npm: '@xh/hoist' },
14
+ checkout: { packageName: '@xh/hoist' }
15
+ },
16
+ {
17
+ id: 'core',
18
+ label: 'Hoist Core',
19
+ source: 'hoist-core',
20
+ packageName: 'io.xh:hoist-core',
21
+ maven: { group: 'io.xh', artifact: 'hoist-core' },
22
+ installed: { gradleProperty: 'hoistCoreVersion' },
23
+ checkout: { gradleProject: 'hoist-core', versionProperty: 'xhReleaseVersion' }
24
+ },
25
+ {
26
+ id: 'chat-kit',
27
+ label: 'Hoist Chat Kit',
28
+ source: 'hoist-chat-kit',
29
+ packageName: '@xh/hoist-chat-kit',
30
+ installed: { npm: '@xh/hoist-chat-kit' },
31
+ checkout: { packageName: '@xh/hoist-chat-kit' },
32
+ optional: true
33
+ }
34
+ ];
35
+ /** The built-in library with this id, if any. */
36
+ export function libraryDef(id) {
37
+ return LIBRARIES.find(l => l.id === id);
38
+ }
@@ -0,0 +1,25 @@
1
+ /** How long a resolved moving version (a snapshot, a dist-tag) is trusted before rechecking. */
2
+ export declare const RECHECK_MS: number;
3
+ /** What a moving version last resolved to: a cached index file, and when that was checked. */
4
+ export interface Resolution {
5
+ file: string;
6
+ checkedAt: number;
7
+ }
8
+ /**
9
+ * Where fetched indexes are kept: index files, plus `resolved.json` recording what each moving
10
+ * version (a Maven snapshot, an npm dist-tag) last resolved to.
11
+ */
12
+ export declare class IndexCache {
13
+ readonly dir: string;
14
+ constructor(dir?: string);
15
+ /** Path for a cached index file. */
16
+ path(name: string): string;
17
+ has(name: string): boolean;
18
+ write(name: string, data: Buffer): string;
19
+ /** The last resolution of `key`, if its file is still cached. */
20
+ resolution(key: string): Resolution | null;
21
+ setResolution(key: string, file: string, checkedAt: number): void;
22
+ private readResolutions;
23
+ }
24
+ /** `HOIST_DOCS_CACHE`, else the platform's user cache directory. */
25
+ export declare function defaultCacheDir(env?: Record<string, string | undefined>): string;
@@ -0,0 +1,62 @@
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 { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
8
+ import { homedir } from 'node:os';
9
+ import { join } from 'node:path';
10
+ /** How long a resolved moving version (a snapshot, a dist-tag) is trusted before rechecking. */
11
+ export const RECHECK_MS = 24 * 60 * 60 * 1000;
12
+ /**
13
+ * Where fetched indexes are kept: index files, plus `resolved.json` recording what each moving
14
+ * version (a Maven snapshot, an npm dist-tag) last resolved to.
15
+ */
16
+ export class IndexCache {
17
+ dir;
18
+ constructor(dir = defaultCacheDir()) {
19
+ this.dir = dir;
20
+ }
21
+ /** Path for a cached index file. */
22
+ path(name) {
23
+ return join(this.dir, name);
24
+ }
25
+ has(name) {
26
+ return existsSync(this.path(name));
27
+ }
28
+ write(name, data) {
29
+ mkdirSync(this.dir, { recursive: true });
30
+ const path = this.path(name);
31
+ writeFileSync(path, data);
32
+ return path;
33
+ }
34
+ /** The last resolution of `key`, if its file is still cached. */
35
+ resolution(key) {
36
+ const r = this.readResolutions()[key];
37
+ return r && this.has(r.file) ? r : null;
38
+ }
39
+ setResolution(key, file, checkedAt) {
40
+ const all = this.readResolutions();
41
+ all[key] = { file, checkedAt };
42
+ mkdirSync(this.dir, { recursive: true });
43
+ writeFileSync(join(this.dir, 'resolved.json'), JSON.stringify(all, null, 2));
44
+ }
45
+ readResolutions() {
46
+ try {
47
+ return JSON.parse(readFileSync(join(this.dir, 'resolved.json'), 'utf8'));
48
+ }
49
+ catch {
50
+ return {};
51
+ }
52
+ }
53
+ }
54
+ /** `HOIST_DOCS_CACHE`, else the platform's user cache directory. */
55
+ export function defaultCacheDir(env = process.env) {
56
+ if (env.HOIST_DOCS_CACHE)
57
+ return env.HOIST_DOCS_CACHE;
58
+ if (process.platform === 'win32' && env.LOCALAPPDATA) {
59
+ return join(env.LOCALAPPDATA, 'hoist-docs', 'cache');
60
+ }
61
+ return join(env.XDG_CACHE_HOME || join(homedir(), '.cache'), 'hoist-docs');
62
+ }
@@ -0,0 +1,6 @@
1
+ import type { DocsPayload } from '../docs/index.ts';
2
+ import { type LibraryDef } from '../libraries.ts';
3
+ /** The built-in library a checkout holds, or null if none. */
4
+ export declare function checkoutLibrary(dir: string): LibraryDef | null;
5
+ /** The docs payload of a checkout of a built-in library. */
6
+ export declare function docsFromCheckout(checkout: string): DocsPayload;
@@ -0,0 +1,178 @@
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
+ * Docs payloads read straight from a library checkout, for `hoist-docs export-docs
9
+ * --from-checkout`. The docs part of an index is only `docs/doc-registry.json` plus the markdown
10
+ * it lists, so this needs no install, no ts-morph and no JVM - it takes a second or two, which
11
+ * keeps live preview of uncommitted doc edits in a docs viewer.
12
+ *
13
+ * Applies the same rules as each library's builder (`builders/`), so the payload equals the docs
14
+ * part of an index built from the same checkout; a spec checks this against real checkouts.
15
+ */
16
+ import { execFileSync } from 'node:child_process';
17
+ import { existsSync, readFileSync, realpathSync } from 'node:fs';
18
+ import { join, resolve, sep } from 'node:path';
19
+ import { SCHEMA_VERSION } from '../index/types.js';
20
+ import { LIBRARIES } from '../libraries.js';
21
+ const CORE_DESCRIPTION = 'Server half of the Hoist toolkit: a Grails plugin providing services, controllers, caching, clustering, config, prefs, roles and monitoring.';
22
+ /** The built-in library a checkout holds, or null if none. */
23
+ export function checkoutLibrary(dir) {
24
+ const pkg = readJson(join(dir, 'package.json')), settings = join(dir, 'settings.gradle'), gradleName = existsSync(settings)
25
+ ? /rootProject\.name\s*=\s*'([^']+)'/.exec(readFileSync(settings, 'utf8'))?.[1]
26
+ : null;
27
+ return (LIBRARIES.find(l => 'packageName' in l.checkout
28
+ ? pkg?.name === l.checkout.packageName
29
+ : gradleName === l.checkout.gradleProject) ?? null);
30
+ }
31
+ /** The docs payload of a checkout of a built-in library. */
32
+ export function docsFromCheckout(checkout) {
33
+ const dir = resolve(checkout), lib = checkoutLibrary(dir);
34
+ if (!lib) {
35
+ throw new Error(`${dir} is not a checkout of ${LIBRARIES.map(l => l.source).join(', ')} (no matching package.json or settings.gradle)`);
36
+ }
37
+ const registry = readJson(join(dir, 'docs/doc-registry.json'));
38
+ if (!registry)
39
+ throw new Error(`No docs/doc-registry.json in ${dir}`);
40
+ return !lib.maven ? typescriptPayload(dir, registry, lib) : corePayload(dir, registry);
41
+ }
42
+ //------------------------
43
+ // TypeScript libraries - as builders/react (doc-registry.ts loadLibrary, cli/build-index.ts)
44
+ //------------------------
45
+ function typescriptPayload(dir, registry, lib) {
46
+ const pkg = readJson(join(dir, 'package.json')), realRoot = realpathSync(dir), entries = [];
47
+ for (const raw of array(registry.entries)) {
48
+ if (typeof raw?.id !== 'string' || !raw.id)
49
+ continue;
50
+ // Docs for the library's own maintainers, served only inside its repo.
51
+ if (raw.mcpAudience === 'maintainers')
52
+ continue;
53
+ if (raw.id.includes('..'))
54
+ continue;
55
+ const file = join(dir, raw.id);
56
+ if (!existsSync(file) || !realpathSync(file).startsWith(realRoot + sep))
57
+ continue;
58
+ entries.push({
59
+ id: raw.id,
60
+ title: str(raw.title, raw.id),
61
+ mcpCategory: str(raw.mcpCategory, 'package'),
62
+ viewerCategory: raw.viewerCategory ?? null,
63
+ description: str(raw.description, ''),
64
+ keywords: strings(raw.keywords),
65
+ aliases: strings(raw.aliases),
66
+ markdown: readFileSync(file, 'utf8')
67
+ });
68
+ }
69
+ // Categories the registry declares, then any an entry uses without declaring.
70
+ const mcpCategories = array(registry.mcpCategories)
71
+ .filter((c) => typeof c?.id === 'string' && c.id)
72
+ .map((c) => ({ id: c.id, title: str(c.title, c.id) }));
73
+ for (const id of new Set(entries.map(e => e.mcpCategory))) {
74
+ if (!mcpCategories.some(c => c.id === id)) {
75
+ mcpCategories.push({ id, title: id.charAt(0).toUpperCase() + id.slice(1) });
76
+ }
77
+ }
78
+ const instructions = lib.id === 'react' ? null : parseInstructions(registry.mcpInstructions);
79
+ return {
80
+ schemaVersion: SCHEMA_VERSION,
81
+ library: {
82
+ id: lib.id,
83
+ name: pkg?.name ?? lib.packageName,
84
+ version: pkg?.version ?? 'unknown',
85
+ language: 'typescript',
86
+ gitSha: gitSha(dir) ?? undefined,
87
+ builtAt: new Date().toISOString(),
88
+ description: pkg?.description ?? undefined,
89
+ ...(instructions ? { instructions } : {})
90
+ },
91
+ docs: { mcpCategories, viewerCategories: registry.viewerCategories ?? [], entries }
92
+ };
93
+ }
94
+ //------------------------
95
+ // hoist-core - as builders/core (IndexBuilder.build)
96
+ //------------------------
97
+ function corePayload(dir, registry) {
98
+ const entries = array(registry.entries)
99
+ .filter((e) => existsSync(join(dir, e.id)))
100
+ .map((e) => ({
101
+ id: e.id,
102
+ title: e.title,
103
+ mcpCategory: e.mcpCategory,
104
+ viewerCategory: e.viewerCategory,
105
+ description: e.description || '',
106
+ keywords: e.keywords || [],
107
+ aliases: e.aliases || [],
108
+ markdown: readFileSync(join(dir, e.id), 'utf8')
109
+ }));
110
+ const props = readFileSync(join(dir, 'gradle.properties'), 'utf8'), version = /^xhReleaseVersion=(\S+)/m.exec(props)?.[1] ?? 'unknown', sha = gitSha(dir);
111
+ return {
112
+ schemaVersion: SCHEMA_VERSION,
113
+ library: {
114
+ id: 'core',
115
+ name: 'io.xh:hoist-core',
116
+ version,
117
+ language: 'groovy',
118
+ ...(sha ? { gitSha: sha } : {}),
119
+ builtAt: new Date().toISOString(),
120
+ description: CORE_DESCRIPTION
121
+ },
122
+ docs: {
123
+ mcpCategories: registry.mcpCategories || [],
124
+ viewerCategories: registry.viewerCategories || [],
125
+ entries
126
+ }
127
+ };
128
+ }
129
+ //------------------------
130
+ // Implementation
131
+ //------------------------
132
+ /** Longest library guidance accepted, as builders/react `MAX_LIBRARY_INSTRUCTIONS_CHARS`. */
133
+ const MAX_INSTRUCTIONS_CHARS = 1500;
134
+ /** `mcpInstructions` as trimmed, non-empty lines, as builders/react `parseInstructions`. */
135
+ function parseInstructions(raw) {
136
+ const valid = typeof raw === 'string' || (Array.isArray(raw) && raw.every(it => typeof it === 'string'));
137
+ if (!valid)
138
+ return null;
139
+ const text = [raw]
140
+ .flat()
141
+ .join('\n')
142
+ .split('\n')
143
+ .map(line => line.trim())
144
+ .filter(Boolean)
145
+ .join('\n');
146
+ if (text.length <= MAX_INSTRUCTIONS_CHARS)
147
+ return text || null;
148
+ return text.slice(0, MAX_INSTRUCTIONS_CHARS - 3) + '...';
149
+ }
150
+ function readJson(path) {
151
+ try {
152
+ return JSON.parse(readFileSync(path, 'utf8'));
153
+ }
154
+ catch {
155
+ return null;
156
+ }
157
+ }
158
+ function array(v) {
159
+ return Array.isArray(v) ? v : [];
160
+ }
161
+ function str(v, dflt) {
162
+ return typeof v === 'string' ? v : dflt;
163
+ }
164
+ function strings(v) {
165
+ return Array.isArray(v) ? v.filter(s => typeof s === 'string') : [];
166
+ }
167
+ function gitSha(dir) {
168
+ try {
169
+ return execFileSync('git', ['rev-parse', 'HEAD'], {
170
+ cwd: dir,
171
+ encoding: 'utf8',
172
+ stdio: ['ignore', 'pipe', 'ignore']
173
+ }).trim();
174
+ }
175
+ catch {
176
+ return null;
177
+ }
178
+ }
@@ -0,0 +1,22 @@
1
+ /** An index shipped inside an installed npm package. */
2
+ export interface InstalledIndex {
3
+ libraryId: string;
4
+ version: string;
5
+ path: string;
6
+ packageName: string;
7
+ /** True for `@xh` packages, the only ones whose index may carry agent instructions. */
8
+ trusted: boolean;
9
+ }
10
+ /**
11
+ * Find every installed package that ships a Hoist Docs index, declared in its `package.json`:
12
+ *
13
+ * "hoistDocs": {"id": "react", "index": "hoist-docs/index.json.gz"}
14
+ *
15
+ * Looks at the direct entries of `client-app/node_modules` and `node_modules` under `root` (and
16
+ * their `@scope/` folders), the first finding of a package winning. Two packages claiming the same
17
+ * id keep the `@xh` one, else the first, with a note.
18
+ */
19
+ export declare function findInstalledIndexes(root: string): {
20
+ indexes: InstalledIndex[];
21
+ notes: string[];
22
+ };
@@ -0,0 +1,99 @@
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 { existsSync, readdirSync, readFileSync } from 'node:fs';
8
+ import { join, resolve, sep } from 'node:path';
9
+ /** The scope whose packages are trusted to give the agent instructions. */
10
+ const TRUSTED_SCOPE = '@xh/';
11
+ /**
12
+ * Find every installed package that ships a Hoist Docs index, declared in its `package.json`:
13
+ *
14
+ * "hoistDocs": {"id": "react", "index": "hoist-docs/index.json.gz"}
15
+ *
16
+ * Looks at the direct entries of `client-app/node_modules` and `node_modules` under `root` (and
17
+ * their `@scope/` folders), the first finding of a package winning. Two packages claiming the same
18
+ * id keep the `@xh` one, else the first, with a note.
19
+ */
20
+ export function findInstalledIndexes(root) {
21
+ const projectRoot = resolve(root), notes = [], byPackage = new Map();
22
+ for (const dir of [
23
+ join(projectRoot, 'client-app', 'node_modules'),
24
+ join(projectRoot, 'node_modules')
25
+ ]) {
26
+ for (const pkgDir of packageDirs(dir)) {
27
+ const pkg = readJson(join(pkgDir, 'package.json')), decl = pkg?.hoistDocs;
28
+ if (!pkg?.name || !decl || byPackage.has(pkg.name))
29
+ continue;
30
+ if (typeof decl.id !== 'string' || typeof decl.index !== 'string') {
31
+ notes.push(`${pkg.name} has a malformed "hoistDocs" entry - expected {"id", "index"}.`);
32
+ continue;
33
+ }
34
+ const path = resolve(pkgDir, decl.index);
35
+ if (!path.startsWith(resolve(pkgDir) + sep)) {
36
+ notes.push(`${pkg.name} declares a Hoist Docs index outside its package - ignored.`);
37
+ continue;
38
+ }
39
+ if (!existsSync(path)) {
40
+ notes.push(`${pkg.name} ${pkg.version} declares a Hoist Docs index at ${decl.index}, but it is missing.`);
41
+ continue;
42
+ }
43
+ byPackage.set(pkg.name, {
44
+ libraryId: decl.id,
45
+ version: pkg.version,
46
+ path,
47
+ packageName: pkg.name,
48
+ trusted: pkg.name.startsWith(TRUSTED_SCOPE)
49
+ });
50
+ }
51
+ }
52
+ const byId = new Map();
53
+ for (const idx of byPackage.values()) {
54
+ const prev = byId.get(idx.libraryId);
55
+ if (!prev) {
56
+ byId.set(idx.libraryId, idx);
57
+ continue;
58
+ }
59
+ const keep = !prev.trusted && idx.trusted ? idx : prev, drop = keep === prev ? idx : prev;
60
+ byId.set(idx.libraryId, keep);
61
+ notes.push(`${drop.packageName} and ${keep.packageName} both ship a Hoist Docs index with id '${idx.libraryId}' - serving ${keep.packageName}'s.`);
62
+ }
63
+ return { indexes: [...byId.values()], notes };
64
+ }
65
+ //------------------------
66
+ // Implementation
67
+ //------------------------
68
+ /** Package folders directly in a node_modules folder, including one level into `@scope/` folders. */
69
+ function packageDirs(nodeModules) {
70
+ const ret = [];
71
+ for (const name of list(nodeModules)) {
72
+ if (name.startsWith('.'))
73
+ continue;
74
+ if (name.startsWith('@')) {
75
+ for (const sub of list(join(nodeModules, name)))
76
+ ret.push(join(nodeModules, name, sub));
77
+ }
78
+ else {
79
+ ret.push(join(nodeModules, name));
80
+ }
81
+ }
82
+ return ret;
83
+ }
84
+ function list(dir) {
85
+ try {
86
+ return readdirSync(dir);
87
+ }
88
+ catch {
89
+ return [];
90
+ }
91
+ }
92
+ function readJson(path) {
93
+ try {
94
+ return JSON.parse(readFileSync(path, 'utf8'));
95
+ }
96
+ catch {
97
+ return null;
98
+ }
99
+ }
@@ -0,0 +1,49 @@
1
+ import { IndexCache } from './cache.ts';
2
+ /** Classifier and extension a Grails library's index is published under, beside its jar. */
3
+ export declare const DOCS_INDEX_CLASSIFIER = "docs-index";
4
+ export declare const DOCS_INDEX_EXTENSION = "json.gz";
5
+ /** Fetch a URL's body, or null when it does not exist (404, or no such file). Injectable for tests. */
6
+ export type Fetcher = (url: string) => Promise<Buffer | null>;
7
+ export interface MavenOptions {
8
+ /** Repository for releases. Default Maven Central. */
9
+ releaseRepo?: string;
10
+ /** Repository for snapshots. Default Sonatype's snapshot repository. */
11
+ snapshotRepo?: string;
12
+ /** Basic auth for an organization's mirror. */
13
+ user?: string;
14
+ password?: string;
15
+ cache?: IndexCache;
16
+ fetcher?: Fetcher;
17
+ now?: () => number;
18
+ }
19
+ export declare const MAVEN_CENTRAL = "https://repo1.maven.org/maven2";
20
+ export declare const SONATYPE_SNAPSHOTS = "https://central.sonatype.com/repository/maven-snapshots";
21
+ /**
22
+ * Fetches a Grails library's `docs-index` artifact from Maven, into the local cache. A release is
23
+ * fetched once. A snapshot resolves to its newest timestamped build through the version's
24
+ * `maven-metadata.xml`, rechecked at most daily, as Gradle treats a changing snapshot; when the
25
+ * repository cannot be reached, the cached build is used.
26
+ *
27
+ * `file:` repository URLs work too, including a local Maven repository (`~/.m2/repository`), whose
28
+ * snapshots are not timestamped.
29
+ */
30
+ export declare class MavenSource {
31
+ readonly releaseRepo: string;
32
+ readonly snapshotRepo: string;
33
+ private readonly cache;
34
+ private readonly fetcher;
35
+ private readonly now;
36
+ constructor(opts?: MavenOptions);
37
+ /** Settings from the environment: see the Configuration table in docs/design.md. */
38
+ static fromEnv(env: Record<string, string | undefined>, cache?: IndexCache): MavenSource;
39
+ /** Local path of the docs index for `version` of `group:artifact`, fetching it if needed. */
40
+ resolve(group: string, artifact: string, version: string): Promise<string>;
41
+ /** The newest release, from the artifact's `maven-metadata.xml`. */
42
+ latestRelease(group: string, artifact: string): Promise<string>;
43
+ /** The newest snapshot version (e.g. `45.0-SNAPSHOT`) in the snapshot repository. */
44
+ latestSnapshot(group: string, artifact: string): Promise<string>;
45
+ private resolveRelease;
46
+ private resolveSnapshot;
47
+ private metadata;
48
+ }
49
+ export declare function isSnapshot(version: string): boolean;
@@ -0,0 +1,184 @@
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 { readFile } from 'node:fs/promises';
8
+ import { fileURLToPath } from 'node:url';
9
+ import { compareVersions } from '../IndexStore.js';
10
+ import { log } from '../log.js';
11
+ import { IndexCache, RECHECK_MS } from './cache.js';
12
+ /** Classifier and extension a Grails library's index is published under, beside its jar. */
13
+ export const DOCS_INDEX_CLASSIFIER = 'docs-index';
14
+ export const DOCS_INDEX_EXTENSION = 'json.gz';
15
+ export const MAVEN_CENTRAL = 'https://repo1.maven.org/maven2';
16
+ export const SONATYPE_SNAPSHOTS = 'https://central.sonatype.com/repository/maven-snapshots';
17
+ /**
18
+ * Fetches a Grails library's `docs-index` artifact from Maven, into the local cache. A release is
19
+ * fetched once. A snapshot resolves to its newest timestamped build through the version's
20
+ * `maven-metadata.xml`, rechecked at most daily, as Gradle treats a changing snapshot; when the
21
+ * repository cannot be reached, the cached build is used.
22
+ *
23
+ * `file:` repository URLs work too, including a local Maven repository (`~/.m2/repository`), whose
24
+ * snapshots are not timestamped.
25
+ */
26
+ export class MavenSource {
27
+ releaseRepo;
28
+ snapshotRepo;
29
+ cache;
30
+ fetcher;
31
+ now;
32
+ constructor(opts = {}) {
33
+ this.releaseRepo = trimSlash(opts.releaseRepo || MAVEN_CENTRAL);
34
+ this.snapshotRepo = trimSlash(opts.snapshotRepo || SONATYPE_SNAPSHOTS);
35
+ this.cache = opts.cache ?? new IndexCache();
36
+ this.fetcher = opts.fetcher ?? httpFetcher(opts.user, opts.password);
37
+ this.now = opts.now ?? Date.now;
38
+ }
39
+ /** Settings from the environment: see the Configuration table in docs/design.md. */
40
+ static fromEnv(env, cache) {
41
+ return new MavenSource({
42
+ releaseRepo: env.HOIST_DOCS_MAVEN_REPO,
43
+ snapshotRepo: env.HOIST_DOCS_MAVEN_SNAPSHOT_REPO,
44
+ user: env.HOIST_DOCS_MAVEN_USER,
45
+ password: env.HOIST_DOCS_MAVEN_PASSWORD,
46
+ cache
47
+ });
48
+ }
49
+ /** Local path of the docs index for `version` of `group:artifact`, fetching it if needed. */
50
+ async resolve(group, artifact, version) {
51
+ return isSnapshot(version)
52
+ ? this.resolveSnapshot(group, artifact, version)
53
+ : this.resolveRelease(group, artifact, version);
54
+ }
55
+ /** The newest release, from the artifact's `maven-metadata.xml`. */
56
+ async latestRelease(group, artifact) {
57
+ const xml = await this.metadata(this.releaseRepo, group, artifact), release = xml &&
58
+ (tag(xml, 'release') ??
59
+ versions(xml)
60
+ .filter(v => !isSnapshot(v))
61
+ .at(-1));
62
+ if (!release)
63
+ throw new Error(`No release of ${group}:${artifact} found in ${this.releaseRepo}`);
64
+ return release;
65
+ }
66
+ /** The newest snapshot version (e.g. `45.0-SNAPSHOT`) in the snapshot repository. */
67
+ async latestSnapshot(group, artifact) {
68
+ const xml = await this.metadata(this.snapshotRepo, group, artifact), snapshot = xml && versions(xml).filter(isSnapshot).sort(compareVersions).at(-1);
69
+ if (!snapshot) {
70
+ throw new Error(`No snapshot of ${group}:${artifact} found in ${this.snapshotRepo}`);
71
+ }
72
+ return snapshot;
73
+ }
74
+ //------------------------
75
+ // Implementation
76
+ //------------------------
77
+ async resolveRelease(group, artifact, version) {
78
+ const name = fileName(artifact, version);
79
+ if (this.cache.has(name))
80
+ return this.cache.path(name);
81
+ const data = await this.fetcher(`${artifactDir(this.releaseRepo, group, artifact)}/${version}/${name}`);
82
+ if (!data) {
83
+ throw new Error(`${group}:${artifact} ${version} has no ${DOCS_INDEX_CLASSIFIER} artifact in ${this.releaseRepo} - releases from before Hoist Docs shipped indexes carry none. Upgrade, or serve an index directory (INDEX_DIR).`);
84
+ }
85
+ const path = this.cache.write(name, data);
86
+ log.info('Fetched index', {
87
+ artifact: `${group}:${artifact}:${version}`,
88
+ from: this.releaseRepo
89
+ });
90
+ return path;
91
+ }
92
+ async resolveSnapshot(group, artifact, version) {
93
+ const key = `maven:${group}:${artifact}:${version}`, cached = this.cache.resolution(key);
94
+ if (cached && this.now() - cached.checkedAt < RECHECK_MS)
95
+ return this.cache.path(cached.file);
96
+ try {
97
+ const dir = `${artifactDir(this.snapshotRepo, group, artifact)}/${version}`, meta = await this.fetcher(`${dir}/maven-metadata.xml`),
98
+ // A remote repository timestamps each build; a local one (~/.m2) does not.
99
+ build = (meta && snapshotBuild(meta.toString('utf8'))) ?? version, name = fileName(artifact, build);
100
+ if (!this.cache.has(name)) {
101
+ const data = await this.fetcher(`${dir}/${name}`);
102
+ if (!data) {
103
+ throw new Error(`${group}:${artifact} ${version} has no ${DOCS_INDEX_CLASSIFIER} artifact in ${this.snapshotRepo}.`);
104
+ }
105
+ this.cache.write(name, data);
106
+ log.info('Fetched index', {
107
+ artifact: `${group}:${artifact}:${build}`,
108
+ from: this.snapshotRepo
109
+ });
110
+ }
111
+ this.cache.setResolution(key, name, this.now());
112
+ return this.cache.path(name);
113
+ }
114
+ catch (e) {
115
+ if (cached) {
116
+ log.warn('Maven repository unreachable - using cached index', {
117
+ artifact: `${group}:${artifact}:${version}`,
118
+ error: String(e)
119
+ });
120
+ return this.cache.path(cached.file);
121
+ }
122
+ throw e;
123
+ }
124
+ }
125
+ async metadata(repo, group, artifact) {
126
+ const data = await this.fetcher(`${artifactDir(repo, group, artifact)}/maven-metadata.xml`);
127
+ return data?.toString('utf8') ?? null;
128
+ }
129
+ }
130
+ export function isSnapshot(version) {
131
+ return /-SNAPSHOT$/i.test(version);
132
+ }
133
+ //------------------------
134
+ // Implementation
135
+ //------------------------
136
+ function fileName(artifact, version) {
137
+ return `${artifact}-${version}-${DOCS_INDEX_CLASSIFIER}.${DOCS_INDEX_EXTENSION}`;
138
+ }
139
+ function artifactDir(repo, group, artifact) {
140
+ return `${repo}/${group.replace(/\./g, '/')}/${artifact}`;
141
+ }
142
+ /** The timestamped build (`45.0-20261110.120000-3`) of the docs index, from a version's metadata. */
143
+ function snapshotBuild(xml) {
144
+ for (const m of xml.matchAll(/<snapshotVersion>([\s\S]*?)<\/snapshotVersion>/g)) {
145
+ const block = m[1];
146
+ if (tag(block, 'classifier') === DOCS_INDEX_CLASSIFIER &&
147
+ tag(block, 'extension') === DOCS_INDEX_EXTENSION) {
148
+ return tag(block, 'value');
149
+ }
150
+ }
151
+ return null;
152
+ }
153
+ function versions(xml) {
154
+ return [...xml.matchAll(/<version>([^<]+)<\/version>/g)].map(m => m[1].trim());
155
+ }
156
+ function tag(xml, name) {
157
+ return new RegExp(`<${name}>([^<]*)</${name}>`).exec(xml)?.[1].trim() || null;
158
+ }
159
+ function trimSlash(url) {
160
+ return url.replace(/\/+$/, '');
161
+ }
162
+ function httpFetcher(user, password) {
163
+ const headers = user
164
+ ? { Authorization: 'Basic ' + Buffer.from(`${user}:${password ?? ''}`).toString('base64') }
165
+ : {};
166
+ return async (url) => {
167
+ if (url.startsWith('file:')) {
168
+ try {
169
+ return await readFile(fileURLToPath(url));
170
+ }
171
+ catch (e) {
172
+ if (e.code === 'ENOENT')
173
+ return null;
174
+ throw e;
175
+ }
176
+ }
177
+ const res = await fetch(url, { headers });
178
+ if (res.status === 404)
179
+ return null;
180
+ if (!res.ok)
181
+ throw new Error(`GET ${url} failed: HTTP ${res.status}`);
182
+ return Buffer.from(await res.arrayBuffer());
183
+ };
184
+ }