@statewalker/site-api-reference 0.0.0-stage → 0.1.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.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Mikhail Kotelnikov
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,26 @@
1
- # Temporary Holding Version
1
+ # @statewalker/site-api-reference
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ API reference pages for project sites. A package's exported types, read by TypeDoc, become page
4
+ models: the package README first, then one page per exported class, interface, type, enum,
5
+ function, variable and namespace, with signatures, comments and links between the pages.
6
+
7
+ ```ts
8
+ import { apiPages } from "@statewalker/site-api-reference";
9
+ import { runTypedoc } from "@statewalker/site-api-reference/typedoc"; // Node only
10
+
11
+ const pages = apiPages(await runTypedoc("packages/vcs-core"), { base: "api/vcs-core" });
12
+ // [{ slug: "api/vcs-core", kind: "package", title, html }, { slug: "api/vcs-core/...", ... }]
13
+ ```
14
+
15
+ `apiPages()` is isomorphic (no Node import), so the site generator runs it in a browser tab too;
16
+ it takes any TypeDoc JSON (`typedoc --json`). `runTypedoc()` runs TypeDoc over one package folder:
17
+ entry points from its `exports` map (the `source` condition first), its `tsconfig.build.json` or
18
+ `tsconfig.json`, its README. A package that does not type-check fails.
19
+
20
+ TypeDoc 0.28 supports TypeScript up to 6.0 and the projects use TypeScript 7, so this package
21
+ depends on its own `typescript@6.0.3` (the `typedoc` catalog in `pnpm-workspace.yaml`), never the
22
+ projects' (statewalker-root `subjects/sites/research/api-reference-generation.md`).
23
+
24
+ ## Tests
25
+
26
+ `pnpm test` runs TypeDoc over a fixture package written to a temporary folder.
@@ -0,0 +1,25 @@
1
+ import { JSONOutput } from "typedoc";
2
+ //#region src/index.d.ts
3
+ /** TypeDoc's JSON model of one package (`runTypedoc()`, or `typedoc --json`). */
4
+ export type TypedocJson = JSONOutput.ProjectReflection;
5
+ export type ApiPageKind = "package" | "module" | "namespace" | "class" | "interface" | "type" | "enum" | "function" | "variable";
6
+ /** One page of a package's API reference. The README page comes first. */
7
+ export interface ApiPage {
8
+ slug: string;
9
+ title: string;
10
+ kind: ApiPageKind;
11
+ /** The first paragraph of the comment, as plain text. */
12
+ description?: string;
13
+ /** Body HTML: signatures, members and rendered comments. */
14
+ html: string;
15
+ }
16
+ export interface ApiPagesOptions {
17
+ /** Slug of the package's README page; symbol pages go below it. */
18
+ base: string;
19
+ }
20
+ /**
21
+ * The pages of one package's reference: its README first, then one page per exported class,
22
+ * interface, type, enum, function, variable and namespace, in TypeDoc's group order.
23
+ */
24
+ export declare function apiPages(project: JSONOutput.ProjectReflection, opts: ApiPagesOptions): ApiPage[];
25
+ //#endregion
package/dist/index.mjs ADDED
@@ -0,0 +1,266 @@
1
+ import MarkdownIt from "markdown-it";
2
+ //#region src/index.ts
3
+ const K = {
4
+ Project: 1,
5
+ Module: 2,
6
+ Namespace: 4,
7
+ Enum: 8,
8
+ EnumMember: 16,
9
+ Variable: 32,
10
+ Function: 64,
11
+ Class: 128,
12
+ Interface: 256,
13
+ Constructor: 512,
14
+ Property: 1024,
15
+ Method: 2048,
16
+ Accessor: 262144,
17
+ TypeAlias: 2097152,
18
+ Reference: 4194304
19
+ };
20
+ const PAGE_KINDS = {
21
+ [K.Namespace]: "namespace",
22
+ [K.Enum]: "enum",
23
+ [K.Variable]: "variable",
24
+ [K.Function]: "function",
25
+ [K.Class]: "class",
26
+ [K.Interface]: "interface",
27
+ [K.TypeAlias]: "type"
28
+ };
29
+ const md = new MarkdownIt({
30
+ html: false,
31
+ linkify: true
32
+ });
33
+ const esc = (s) => s.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;");
34
+ const href = (slug) => `/${slug}${slug ? "/" : ""}`;
35
+ /**
36
+ * The pages of one package's reference: its README first, then one page per exported class,
37
+ * interface, type, enum, function, variable and namespace, in TypeDoc's group order.
38
+ */
39
+ function apiPages(project, opts) {
40
+ const slugOf = /* @__PURE__ */ new Map();
41
+ const entries = [];
42
+ const modules = [];
43
+ const place = (container, base) => {
44
+ const taken = /* @__PURE__ */ new Set();
45
+ for (const decl of ordered(container)) {
46
+ if (decl.kind === K.Module) {
47
+ const name = decl.name.replace(/^\.?\/?/, "");
48
+ const slug = name && name !== "index" ? `${base}/${slugPart(name)}` : base;
49
+ if (slug !== base) {
50
+ slugOf.set(decl.id, slug);
51
+ modules.push({
52
+ decl,
53
+ slug
54
+ });
55
+ }
56
+ place(decl, slug);
57
+ continue;
58
+ }
59
+ const kind = PAGE_KINDS[decl.kind];
60
+ if (!kind) continue;
61
+ let part = slugPart(decl.name);
62
+ if (taken.has(part)) part = `${part}-${kind}`;
63
+ taken.add(part);
64
+ const slug = `${base}/${part}`;
65
+ slugOf.set(decl.id, slug);
66
+ entries.push({
67
+ decl,
68
+ slug,
69
+ kind
70
+ });
71
+ if (decl.kind === K.Namespace) place(decl, slug);
72
+ }
73
+ };
74
+ place(project, opts.base);
75
+ const r = new Renderer(slugOf);
76
+ const pkgName = project.packageName ?? project.name;
77
+ const pages = [{
78
+ slug: opts.base,
79
+ title: pkgName,
80
+ kind: "package",
81
+ description: firstParagraph(project.readme),
82
+ html: [project.readme ? `<div class="api-readme">${r.markdown(project.readme)}</div>` : "", r.index(project, entries)].join("\n")
83
+ }];
84
+ for (const m of modules) pages.push({
85
+ slug: m.slug,
86
+ title: `${pkgName}/${m.decl.name}`,
87
+ kind: "module",
88
+ description: firstParagraph(m.decl.comment?.summary),
89
+ html: [r.comment(m.decl.comment), r.index(m.decl, entries)].join("\n")
90
+ });
91
+ for (const e of entries) pages.push({
92
+ slug: e.slug,
93
+ title: e.decl.name,
94
+ kind: e.kind,
95
+ description: firstParagraph(e.decl.comment?.summary ?? e.decl.signatures?.[0]?.comment?.summary),
96
+ html: r.declaration(e.decl, e.kind)
97
+ });
98
+ return pages;
99
+ }
100
+ /** Children in TypeDoc's group order (Classes, Interfaces, Type Aliases, …), then the rest. */
101
+ function ordered(container) {
102
+ const children = container.children ?? [];
103
+ const byId = new Map(children.map((c) => [c.id, c]));
104
+ const out = [];
105
+ const seen = /* @__PURE__ */ new Set();
106
+ for (const g of container.groups ?? []) for (const id of g.children ?? []) {
107
+ const c = byId.get(id);
108
+ if (c && !seen.has(id)) {
109
+ seen.add(id);
110
+ out.push(c);
111
+ }
112
+ }
113
+ for (const c of children) if (!seen.has(c.id)) out.push(c);
114
+ return out;
115
+ }
116
+ const slugPart = (name) => name.toLowerCase().replace(/[^a-z0-9_$-]+/g, "-").replace(/^-+|-+$/g, "") || "_";
117
+ function partsToText(parts) {
118
+ return (parts ?? []).map((p) => p.text).join("");
119
+ }
120
+ function firstParagraph(parts) {
121
+ const text = partsToText(parts).split(/\n\s*\n/).map((s) => s.trim()).find((s) => s && !s.startsWith("#"));
122
+ return text ? text.replace(/`/g, "").replace(/\s+/g, " ") : void 0;
123
+ }
124
+ var Renderer = class {
125
+ slugOf;
126
+ constructor(slugOf) {
127
+ this.slugOf = slugOf;
128
+ }
129
+ link(name, target) {
130
+ const slug = typeof target === "number" ? this.slugOf.get(target) : void 0;
131
+ return slug !== void 0 ? `<a href="${href(slug)}">${esc(name)}</a>` : esc(name);
132
+ }
133
+ /** Comment parts as Markdown (links resolved to page URLs), rendered to HTML. */
134
+ markdown(parts) {
135
+ if (!parts?.length) return "";
136
+ const text = parts.map((p) => {
137
+ if (p.kind !== "inline-tag") return p.text;
138
+ const slug = typeof p.target === "number" ? this.slugOf.get(p.target) : void 0;
139
+ const label = `\`${p.text.replace(/`/g, "")}\``;
140
+ if (slug !== void 0) return `[${label}](${href(slug)})`;
141
+ if (typeof p.target === "string") return `[${p.text}](${p.target})`;
142
+ return label;
143
+ }).join("");
144
+ return md.render(text);
145
+ }
146
+ comment(c) {
147
+ if (!c) return "";
148
+ const blocks = (c.blockTags ?? []).filter((t) => t.tag !== "@param" && t.tag !== "@typeParam").map((t) => `<div class="api-tag"><h4>${esc(t.tag.slice(1))}</h4>${this.markdown(t.content)}</div>`);
149
+ return [`<div class="api-comment">${this.markdown(c.summary)}</div>`, ...blocks].join("\n");
150
+ }
151
+ index(container, entries) {
152
+ const ids = new Set(entries.map((e) => e.decl.id));
153
+ const sections = [];
154
+ for (const g of container.groups ?? []) {
155
+ const items = (g.children ?? []).map((id) => container.children?.find((c) => c.id === id)).filter((c) => !!c && ids.has(c.id));
156
+ if (!items.length) continue;
157
+ sections.push(`<h2>${esc(g.title)}</h2>\n<ul class="api-index">${items.map((c) => {
158
+ const d = firstParagraph(c.comment?.summary ?? c.signatures?.[0]?.comment?.summary);
159
+ return `<li>${this.link(c.name, c.id)}${d ? ` — ${esc(d)}` : ""}</li>`;
160
+ }).join("")}</ul>`);
161
+ }
162
+ return sections.join("\n");
163
+ }
164
+ declaration(decl, kind) {
165
+ const out = [];
166
+ if (kind === "function") {
167
+ for (const s of decl.signatures ?? []) out.push(this.signatureBlock(s, decl.name));
168
+ return out.join("\n");
169
+ }
170
+ out.push(this.comment(decl.comment));
171
+ if (kind === "type") out.push(`<pre class="api-signature"><code>type ${esc(decl.name)}${this.typeParams(decl.typeParameters)} = ${this.type(decl.type)}</code></pre>`);
172
+ else if (kind === "variable") out.push(`<pre class="api-signature"><code>${decl.flags.isConst ? "const" : "let"} ${esc(decl.name)}: ${this.type(decl.type)}</code></pre>`);
173
+ else if (kind === "class" || kind === "interface") {
174
+ const ext = (decl.extendedTypes ?? []).map((t) => this.type(t));
175
+ const impl = (decl.implementedTypes ?? []).map((t) => this.type(t));
176
+ out.push(`<pre class="api-signature"><code>${kind} ${esc(decl.name)}${this.typeParams(decl.typeParameters)}${ext.length ? ` extends ${ext.join(", ")}` : ""}${impl.length ? ` implements ${impl.join(", ")}` : ""}</code></pre>`);
177
+ }
178
+ if (kind !== "namespace") out.push(this.members(decl));
179
+ return out.filter(Boolean).join("\n");
180
+ }
181
+ members(decl) {
182
+ const out = [];
183
+ for (const m of ordered(decl)) {
184
+ if (m.flags.isPrivate || m.name.startsWith("#")) continue;
185
+ const head = `<h3 id="${esc(slugPart(m.name))}">${esc(m.name)}</h3>`;
186
+ if (m.signatures?.length) {
187
+ const name = m.kind === K.Constructor ? `new ${decl.name}` : m.name;
188
+ out.push(head, ...m.signatures.map((s) => this.signatureBlock(s, name)));
189
+ } else if (m.kind === K.Accessor) {
190
+ const get = m.getSignature;
191
+ out.push(head, `<pre class="api-signature"><code>${get ? "get" : "set"} ${esc(m.name)}: ${this.type(get?.type ?? m.setSignature?.parameters?.[0]?.type)}</code></pre>`, this.comment(get?.comment ?? m.setSignature?.comment));
192
+ } else {
193
+ const flags = `${m.flags.isStatic ? "static " : ""}${m.flags.isReadonly ? "readonly " : ""}`;
194
+ const value = m.kind === K.EnumMember ? ` = ${this.type(m.type)}` : `${m.flags.isOptional ? "?" : ""}: ${this.type(m.type)}`;
195
+ out.push(head, `<pre class="api-signature"><code>${flags}${esc(m.name)}${value}</code></pre>`, this.comment(m.comment));
196
+ }
197
+ }
198
+ return out.length ? `<h2>Members</h2>\n${out.filter(Boolean).join("\n")}` : "";
199
+ }
200
+ signature(s, name) {
201
+ const params = (s.parameters ?? []).map((p) => `${p.flags.isRest ? "..." : ""}${esc(p.name)}${p.flags.isOptional || p.defaultValue ? "?" : ""}: ${this.type(p.type)}`);
202
+ return `${esc(name)}${this.typeParams(s.typeParameters)}(${params.join(", ")}): ${this.type(s.type)}`;
203
+ }
204
+ signatureBlock(s, name) {
205
+ const params = (s.parameters ?? []).filter((p) => p.comment?.summary?.length);
206
+ const ret = s.comment?.blockTags?.find((t) => t.tag === "@returns");
207
+ return [
208
+ `<pre class="api-signature"><code>${this.signature(s, name)}</code></pre>`,
209
+ this.comment(s.comment && {
210
+ ...s.comment,
211
+ blockTags: s.comment.blockTags?.filter((t) => t.tag !== "@returns")
212
+ }),
213
+ params.length ? `<h4>Parameters</h4>\n<dl class="api-params">${params.map((p) => `<dt><code>${esc(p.name)}</code></dt><dd>${this.markdown(p.comment?.summary)}</dd>`).join("")}</dl>` : "",
214
+ ret ? `<h4>Returns</h4>\n${this.markdown(ret.content)}` : ""
215
+ ].filter(Boolean).join("\n");
216
+ }
217
+ typeParams(tps) {
218
+ if (!tps?.length) return "";
219
+ return `&lt;${tps.map((t) => `${esc(t.name)}${t.type ? ` extends ${this.type(t.type)}` : ""}${t.default ? ` = ${this.type(t.default)}` : ""}`).join(", ")}&gt;`;
220
+ }
221
+ /** A type as HTML, references linked to their pages. */
222
+ type(t) {
223
+ if (!t) return "unknown";
224
+ switch (t.type) {
225
+ case "intrinsic": return esc(t.name);
226
+ case "reference": {
227
+ const args = t.typeArguments?.length ? `&lt;${t.typeArguments.map((a) => this.type(a)).join(", ")}&gt;` : "";
228
+ return `${this.link(t.name, t.target)}${args}`;
229
+ }
230
+ case "literal": return esc(t.value === null ? "null" : typeof t.value === "object" ? `${t.value.negative ? "-" : ""}${t.value.value}n` : JSON.stringify(t.value));
231
+ case "union": return t.types.map((x) => this.type(x)).join(" | ");
232
+ case "intersection": return t.types.map((x) => this.type(x)).join(" &amp; ");
233
+ case "array": {
234
+ const inner = this.type(t.elementType);
235
+ return `${[
236
+ "union",
237
+ "intersection",
238
+ "conditional"
239
+ ].includes(t.elementType.type) ? `(${inner})` : inner}[]`;
240
+ }
241
+ case "tuple": return `[${(t.elements ?? []).map((x) => this.type(x)).join(", ")}]`;
242
+ case "namedTupleMember": return `${esc(t.name)}${t.isOptional ? "?" : ""}: ${this.type(t.element)}`;
243
+ case "optional": return `${this.type(t.elementType)}?`;
244
+ case "rest": return `...${this.type(t.elementType)}`;
245
+ case "typeOperator": return `${t.operator} ${this.type(t.target)}`;
246
+ case "indexedAccess": return `${this.type(t.objectType)}[${this.type(t.indexType)}]`;
247
+ case "query": return `typeof ${this.type(t.queryType)}`;
248
+ case "predicate": return `${t.asserts ? "asserts " : ""}${esc(t.name)}${t.targetType ? ` is ${this.type(t.targetType)}` : ""}`;
249
+ case "conditional": return `${this.type(t.checkType)} extends ${this.type(t.extendsType)} ? ${this.type(t.trueType)} : ${this.type(t.falseType)}`;
250
+ case "inferred": return `infer ${esc(t.name)}`;
251
+ case "templateLiteral": return esc(`\`${t.head}${t.tail.map(([x, s]) => `\${${stripTags(this.type(x))}}${s}`).join("")}\``);
252
+ case "mapped": return `{ [${esc(t.parameter)} in ${this.type(t.parameterType)}]: ${this.type(t.templateType)} }`;
253
+ case "reflection": {
254
+ const d = t.declaration;
255
+ const only = d.signatures?.length === 1 && !d.children?.length ? d.signatures[0] : void 0;
256
+ if (only) return this.signature(only, "").replace(/\): /, ") =&gt; ");
257
+ return `{ ${(d.children ?? []).map((c) => `${esc(c.name)}${c.flags.isOptional ? "?" : ""}: ${this.type(c.type)}`).join("; ")} }`;
258
+ }
259
+ case "unknown": return esc(t.name);
260
+ default: return "unknown";
261
+ }
262
+ }
263
+ };
264
+ const stripTags = (html) => html.replace(/<[^>]+>/g, "").replace(/&lt;/g, "<").replace(/&gt;/g, ">").replace(/&amp;/g, "&").replace(/&quot;/g, "\"");
265
+ //#endregion
266
+ export { apiPages };
@@ -0,0 +1,22 @@
1
+ import { JSONOutput } from "typedoc";
2
+ //#region src/typedoc.d.ts
3
+ export interface RunTypedocOptions {
4
+ /** The tsconfig, relative to the package folder. Default: `tsconfig.build.json` if present, else `tsconfig.json`. */
5
+ tsconfig?: string;
6
+ /** Problems TypeDoc reports (warnings and errors). */
7
+ log?: (level: "warn" | "error", message: string) => void;
8
+ /**
9
+ * When given, an import of a package that cannot be resolved (nothing installed) does not fail
10
+ * the package: its types are shown unresolved and this is told the import, as
11
+ * `unresolved import '<name>' (<file>:<line>)`, the file relative to the package (a missing
12
+ * `types` library as `unresolved type library '<name>'`). Without it such
13
+ * an import is an error, as any other type error.
14
+ */
15
+ unresolvedImport?: (warning: string) => void;
16
+ }
17
+ /**
18
+ * TypeDoc's JSON for one package: entry points from its `exports` map (the `source` condition
19
+ * first), its README included.
20
+ */
21
+ export declare function runTypedoc(packageDir: string, options?: RunTypedocOptions): Promise<JSONOutput.ProjectReflection>;
22
+ //#endregion
@@ -0,0 +1,94 @@
1
+ import { existsSync, readFileSync } from "node:fs";
2
+ import { join, relative } from "node:path";
3
+ import { Application, Converter, LogLevel, normalizePath } from "typedoc";
4
+ import ts from "typescript";
5
+ //#region src/typedoc.ts
6
+ /**
7
+ * "Cannot find module" (2307, 2792), "Could not find a declaration file" (7016) and "Cannot find
8
+ * name 'node:…'. Do you need to install type definitions for node?" (2591): an import of types
9
+ * that are not installed.
10
+ */
11
+ const UNRESOLVED_MODULE_CODES = /* @__PURE__ */ new Set([
12
+ 2307,
13
+ 2792,
14
+ 7016,
15
+ 2591
16
+ ]);
17
+ /** "Cannot find type definition file for '<name>'": a `types` library that is not installed. */
18
+ const MISSING_TYPE_LIBRARY = 2688;
19
+ /** The type library a diagnostic says is not installed, if it is one. */
20
+ function missingTypeLibrary(d) {
21
+ if (d.code !== MISSING_TYPE_LIBRARY) return void 0;
22
+ return /'([^']+)'/.exec(ts.flattenDiagnosticMessageText(d.messageText, "\n"))?.[1];
23
+ }
24
+ /** The bare specifier a diagnostic says cannot be resolved, if it is one (never a relative path). */
25
+ function unresolvedSpecifier(d) {
26
+ if (!UNRESOLVED_MODULE_CODES.has(d.code) || !d.file || d.start === void 0) return void 0;
27
+ const literal = d.file.text.slice(d.start, d.start + (d.length ?? 0));
28
+ const name = literal.replace(/^(['"])(.*)\1$/s, "$2");
29
+ return name === literal || name.startsWith(".") || name.startsWith("/") ? void 0 : name;
30
+ }
31
+ /**
32
+ * TypeDoc's JSON for one package: entry points from its `exports` map (the `source` condition
33
+ * first), its README included.
34
+ */
35
+ async function runTypedoc(packageDir, options = {}) {
36
+ const tsconfig = options.tsconfig ?? (existsSync(join(packageDir, "tsconfig.build.json")) ? "tsconfig.build.json" : "tsconfig.json");
37
+ const app = await Application.bootstrapWithPlugins({
38
+ entryPoints: [packageDir],
39
+ entryPointStrategy: "packages",
40
+ packageOptions: {
41
+ tsconfig: join(packageDir, tsconfig),
42
+ compilerOptions: { customConditions: ["source"] },
43
+ readme: join(packageDir, "README.md"),
44
+ skipErrorChecking: true
45
+ },
46
+ ...existsSync(join(packageDir, "README.md")) ? { readme: join(packageDir, "README.md") } : {},
47
+ plugin: [],
48
+ logLevel: LogLevel.Warn,
49
+ skipErrorChecking: true
50
+ });
51
+ const failures = [];
52
+ app.logger.log = (message, level) => {
53
+ if (level === LogLevel.Error) failures.push(message);
54
+ if (level >= LogLevel.Warn) options.log?.(level === LogLevel.Error ? "error" : "warn", message);
55
+ };
56
+ let checkFailed = false;
57
+ const report = options.unresolvedImport;
58
+ app.converter.on(Converter.EVENT_BEGIN, (context) => {
59
+ const errors = [];
60
+ for (const d of context.programs.flatMap((p) => ts.getPreEmitDiagnostics(p))) {
61
+ if (d.file && /[\\/]node_modules[\\/]/.test(d.file.fileName)) continue;
62
+ if (!report) {
63
+ if (d.category === ts.DiagnosticCategory.Error) errors.push(d);
64
+ continue;
65
+ }
66
+ const library = missingTypeLibrary(d);
67
+ if (library !== void 0) {
68
+ report(`unresolved type library '${library}'`);
69
+ continue;
70
+ }
71
+ const name = unresolvedSpecifier(d);
72
+ if (name === void 0) {
73
+ if (d.category === ts.DiagnosticCategory.Error) errors.push(d);
74
+ continue;
75
+ }
76
+ const file = d.file;
77
+ const line = file.getLineAndCharacterOfPosition(d.start ?? 0).line + 1;
78
+ report(`unresolved import '${name}' (${relative(packageDir, file.fileName).split("\\").join("/")}:${line})`);
79
+ }
80
+ if (errors.length === 0) return;
81
+ checkFailed = true;
82
+ app.logger.log(ts.formatDiagnosticsWithColorAndContext(errors, {
83
+ getCanonicalFileName: (f) => f,
84
+ getCurrentDirectory: () => process.cwd(),
85
+ getNewLine: () => ts.sys.newLine
86
+ }), LogLevel.Error);
87
+ });
88
+ const project = await app.convert();
89
+ if (!project || checkFailed) throw new Error(`TypeDoc failed on ${packageDir}: ${failures.join("; ")}`);
90
+ project.packageName = JSON.parse(readFileSync(join(packageDir, "package.json"), "utf8")).name;
91
+ return app.serializer.projectToObject(project, normalizePath(packageDir));
92
+ }
93
+ //#endregion
94
+ export { runTypedoc };
package/package.json CHANGED
@@ -1,6 +1,50 @@
1
1
  {
2
2
  "name": "@statewalker/site-api-reference",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "0.1.0",
4
+ "private": false,
5
+ "type": "module",
6
+ "description": "API reference pages for project sites: TypeDoc JSON of a package in, page models out.",
7
+ "repository": {
8
+ "type": "git",
9
+ "url": "git+https://github.com/statewalker/statewalker-knowledge.git",
10
+ "directory": "packages/site-api-reference"
11
+ },
12
+ "bugs": {
13
+ "url": "https://github.com/statewalker/statewalker-knowledge/issues"
14
+ },
15
+ "homepage": "https://github.com/statewalker/statewalker-knowledge/tree/main/packages/site-api-reference#readme",
16
+ "license": "MIT",
17
+ "exports": {
18
+ ".": {
19
+ "source": "./src/index.ts",
20
+ "types": "./dist/index.d.mts",
21
+ "import": "./dist/index.mjs"
22
+ },
23
+ "./typedoc": {
24
+ "source": "./src/typedoc.ts",
25
+ "types": "./dist/typedoc.d.mts",
26
+ "import": "./dist/typedoc.mjs"
27
+ },
28
+ "./package.json": "./package.json"
29
+ },
30
+ "files": [
31
+ "dist",
32
+ "src"
33
+ ],
34
+ "dependencies": {
35
+ "markdown-it": "^15.0.2",
36
+ "typedoc": "0.28.20",
37
+ "typescript": "6.0.3"
38
+ },
39
+ "devDependencies": {
40
+ "@types/markdown-it": "^14.2.0",
41
+ "@types/node": "^26.6.4",
42
+ "vitest": "^5.0.3",
43
+ "tsdown": "^0.23.0"
44
+ },
45
+ "scripts": {
46
+ "build": "tsdown",
47
+ "test": "pnpm run build && vitest run",
48
+ "typecheck": "tsc --noEmit"
49
+ }
6
50
  }
package/src/index.ts ADDED
@@ -0,0 +1,424 @@
1
+ // TypeDoc JSON of one package in, API reference page models out. Isomorphic: imports nothing from
2
+ // Node and only TypeDoc's types, so a site generator can run it in a browser tab too. Running
3
+ // TypeDoc itself is `./typedoc.ts` (Node).
4
+ import MarkdownIt from "markdown-it";
5
+ import type { JSONOutput } from "typedoc";
6
+
7
+ /** TypeDoc's JSON model of one package (`runTypedoc()`, or `typedoc --json`). */
8
+ export type TypedocJson = JSONOutput.ProjectReflection;
9
+
10
+ export type ApiPageKind =
11
+ | "package"
12
+ | "module"
13
+ | "namespace"
14
+ | "class"
15
+ | "interface"
16
+ | "type"
17
+ | "enum"
18
+ | "function"
19
+ | "variable";
20
+
21
+ /** One page of a package's API reference. The README page comes first. */
22
+ export interface ApiPage {
23
+ slug: string;
24
+ title: string;
25
+ kind: ApiPageKind;
26
+ /** The first paragraph of the comment, as plain text. */
27
+ description?: string;
28
+ /** Body HTML: signatures, members and rendered comments. */
29
+ html: string;
30
+ }
31
+
32
+ export interface ApiPagesOptions {
33
+ /** Slug of the package's README page; symbol pages go below it. */
34
+ base: string;
35
+ }
36
+
37
+ // TypeDoc's ReflectionKind values (stable across 0.2x).
38
+ const K = {
39
+ Project: 1,
40
+ Module: 2,
41
+ Namespace: 4,
42
+ Enum: 8,
43
+ EnumMember: 16,
44
+ Variable: 32,
45
+ Function: 64,
46
+ Class: 128,
47
+ Interface: 256,
48
+ Constructor: 512,
49
+ Property: 1024,
50
+ Method: 2048,
51
+ Accessor: 262144,
52
+ TypeAlias: 2097152,
53
+ Reference: 4194304,
54
+ } as const;
55
+
56
+ const PAGE_KINDS: Record<number, ApiPageKind> = {
57
+ [K.Namespace]: "namespace",
58
+ [K.Enum]: "enum",
59
+ [K.Variable]: "variable",
60
+ [K.Function]: "function",
61
+ [K.Class]: "class",
62
+ [K.Interface]: "interface",
63
+ [K.TypeAlias]: "type",
64
+ };
65
+
66
+ type Decl = JSONOutput.DeclarationReflection;
67
+ type Sig = JSONOutput.SignatureReflection;
68
+ type Part = JSONOutput.CommentDisplayPart;
69
+ type SomeType = JSONOutput.SomeType;
70
+
71
+ const md = new MarkdownIt({ html: false, linkify: true });
72
+
73
+ const esc = (s: string) =>
74
+ s.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;");
75
+
76
+ const href = (slug: string) => `/${slug}${slug ? "/" : ""}`;
77
+
78
+ /**
79
+ * The pages of one package's reference: its README first, then one page per exported class,
80
+ * interface, type, enum, function, variable and namespace, in TypeDoc's group order.
81
+ */
82
+ export function apiPages(project: JSONOutput.ProjectReflection, opts: ApiPagesOptions): ApiPage[] {
83
+ // 1. Which declaration gets which page, so types and {@link}s can point at it.
84
+ const slugOf = new Map<number, string>();
85
+ const entries: { decl: Decl; slug: string; kind: ApiPageKind }[] = [];
86
+ const modules: { decl: Decl; slug: string }[] = [];
87
+ const place = (container: Decl | JSONOutput.ProjectReflection, base: string) => {
88
+ const taken = new Set<string>();
89
+ for (const decl of ordered(container)) {
90
+ if (decl.kind === K.Module) {
91
+ const name = decl.name.replace(/^\.?\/?/, "");
92
+ const slug = name && name !== "index" ? `${base}/${slugPart(name)}` : base;
93
+ if (slug !== base) {
94
+ slugOf.set(decl.id, slug);
95
+ modules.push({ decl, slug });
96
+ }
97
+ place(decl, slug);
98
+ continue;
99
+ }
100
+ const kind = PAGE_KINDS[decl.kind];
101
+ if (!kind) continue;
102
+ let part = slugPart(decl.name);
103
+ if (taken.has(part)) part = `${part}-${kind}`;
104
+ taken.add(part);
105
+ const slug = `${base}/${part}`;
106
+ slugOf.set(decl.id, slug);
107
+ entries.push({ decl, slug, kind });
108
+ if (decl.kind === K.Namespace) place(decl, slug);
109
+ }
110
+ };
111
+ place(project, opts.base);
112
+
113
+ const r = new Renderer(slugOf);
114
+ const pkgName = project.packageName ?? project.name;
115
+ const pages: ApiPage[] = [
116
+ {
117
+ slug: opts.base,
118
+ title: pkgName,
119
+ kind: "package",
120
+ description: firstParagraph(project.readme),
121
+ html: [
122
+ project.readme ? `<div class="api-readme">${r.markdown(project.readme)}</div>` : "",
123
+ r.index(project, entries),
124
+ ].join("\n"),
125
+ },
126
+ ];
127
+ for (const m of modules) {
128
+ pages.push({
129
+ slug: m.slug,
130
+ title: `${pkgName}/${m.decl.name}`,
131
+ kind: "module",
132
+ description: firstParagraph(m.decl.comment?.summary),
133
+ html: [r.comment(m.decl.comment), r.index(m.decl, entries)].join("\n"),
134
+ });
135
+ }
136
+ for (const e of entries) {
137
+ pages.push({
138
+ slug: e.slug,
139
+ title: e.decl.name,
140
+ kind: e.kind,
141
+ description: firstParagraph(
142
+ e.decl.comment?.summary ?? e.decl.signatures?.[0]?.comment?.summary,
143
+ ),
144
+ html: r.declaration(e.decl, e.kind),
145
+ });
146
+ }
147
+ return pages;
148
+ }
149
+
150
+ /** Children in TypeDoc's group order (Classes, Interfaces, Type Aliases, …), then the rest. */
151
+ function ordered(container: Decl | JSONOutput.ProjectReflection): Decl[] {
152
+ const children = container.children ?? [];
153
+ const byId = new Map(children.map((c) => [c.id, c]));
154
+ const out: Decl[] = [];
155
+ const seen = new Set<number>();
156
+ for (const g of container.groups ?? []) {
157
+ for (const id of g.children ?? []) {
158
+ const c = byId.get(id);
159
+ if (c && !seen.has(id)) {
160
+ seen.add(id);
161
+ out.push(c);
162
+ }
163
+ }
164
+ }
165
+ for (const c of children) if (!seen.has(c.id)) out.push(c);
166
+ return out;
167
+ }
168
+
169
+ const slugPart = (name: string) =>
170
+ name
171
+ .toLowerCase()
172
+ .replace(/[^a-z0-9_$-]+/g, "-")
173
+ .replace(/^-+|-+$/g, "") || "_";
174
+
175
+ function partsToText(parts: Part[] | undefined): string {
176
+ return (parts ?? []).map((p) => p.text).join("");
177
+ }
178
+
179
+ function firstParagraph(parts: Part[] | undefined): string | undefined {
180
+ const text = partsToText(parts)
181
+ .split(/\n\s*\n/)
182
+ .map((s) => s.trim())
183
+ .find((s) => s && !s.startsWith("#"));
184
+ return text ? text.replace(/`/g, "").replace(/\s+/g, " ") : undefined;
185
+ }
186
+
187
+ class Renderer {
188
+ private slugOf: Map<number, string>;
189
+ constructor(slugOf: Map<number, string>) {
190
+ this.slugOf = slugOf;
191
+ }
192
+
193
+ link(name: string, target: unknown): string {
194
+ const slug = typeof target === "number" ? this.slugOf.get(target) : undefined;
195
+ return slug !== undefined ? `<a href="${href(slug)}">${esc(name)}</a>` : esc(name);
196
+ }
197
+
198
+ /** Comment parts as Markdown (links resolved to page URLs), rendered to HTML. */
199
+ markdown(parts: Part[] | undefined): string {
200
+ if (!parts?.length) return "";
201
+ const text = parts
202
+ .map((p) => {
203
+ if (p.kind !== "inline-tag") return p.text;
204
+ const slug = typeof p.target === "number" ? this.slugOf.get(p.target) : undefined;
205
+ const label = `\`${p.text.replace(/`/g, "")}\``;
206
+ if (slug !== undefined) return `[${label}](${href(slug)})`;
207
+ if (typeof p.target === "string") return `[${p.text}](${p.target})`;
208
+ return label;
209
+ })
210
+ .join("");
211
+ return md.render(text);
212
+ }
213
+
214
+ comment(c: JSONOutput.Comment | undefined): string {
215
+ if (!c) return "";
216
+ const blocks = (c.blockTags ?? [])
217
+ .filter((t) => t.tag !== "@param" && t.tag !== "@typeParam")
218
+ .map(
219
+ (t) =>
220
+ `<div class="api-tag"><h4>${esc(t.tag.slice(1))}</h4>${this.markdown(t.content)}</div>`,
221
+ );
222
+ return [`<div class="api-comment">${this.markdown(c.summary)}</div>`, ...blocks].join("\n");
223
+ }
224
+
225
+ index(container: Decl | JSONOutput.ProjectReflection, entries: { decl: Decl }[]): string {
226
+ const ids = new Set(entries.map((e) => e.decl.id));
227
+ const sections: string[] = [];
228
+ for (const g of container.groups ?? []) {
229
+ const items = (g.children ?? [])
230
+ .map((id) => container.children?.find((c) => c.id === id))
231
+ .filter((c): c is Decl => !!c && ids.has(c.id));
232
+ if (!items.length) continue;
233
+ sections.push(
234
+ `<h2>${esc(g.title)}</h2>\n<ul class="api-index">${items
235
+ .map((c) => {
236
+ const d = firstParagraph(c.comment?.summary ?? c.signatures?.[0]?.comment?.summary);
237
+ return `<li>${this.link(c.name, c.id)}${d ? ` — ${esc(d)}` : ""}</li>`;
238
+ })
239
+ .join("")}</ul>`,
240
+ );
241
+ }
242
+ return sections.join("\n");
243
+ }
244
+
245
+ declaration(decl: Decl, kind: ApiPageKind): string {
246
+ const out: string[] = [];
247
+ if (kind === "function") {
248
+ for (const s of decl.signatures ?? []) out.push(this.signatureBlock(s, decl.name));
249
+ return out.join("\n");
250
+ }
251
+ out.push(this.comment(decl.comment));
252
+ if (kind === "type") {
253
+ out.push(
254
+ `<pre class="api-signature"><code>type ${esc(decl.name)}${this.typeParams(decl.typeParameters)} = ${this.type(decl.type)}</code></pre>`,
255
+ );
256
+ } else if (kind === "variable") {
257
+ out.push(
258
+ `<pre class="api-signature"><code>${decl.flags.isConst ? "const" : "let"} ${esc(decl.name)}: ${this.type(decl.type)}</code></pre>`,
259
+ );
260
+ } else if (kind === "class" || kind === "interface") {
261
+ const ext = (decl.extendedTypes ?? []).map((t) => this.type(t));
262
+ const impl = (decl.implementedTypes ?? []).map((t) => this.type(t));
263
+ out.push(
264
+ `<pre class="api-signature"><code>${kind} ${esc(decl.name)}${this.typeParams(decl.typeParameters)}${ext.length ? ` extends ${ext.join(", ")}` : ""}${impl.length ? ` implements ${impl.join(", ")}` : ""}</code></pre>`,
265
+ );
266
+ }
267
+ if (kind !== "namespace") out.push(this.members(decl));
268
+ return out.filter(Boolean).join("\n");
269
+ }
270
+
271
+ members(decl: Decl): string {
272
+ const out: string[] = [];
273
+ for (const m of ordered(decl)) {
274
+ if (m.flags.isPrivate || m.name.startsWith("#")) continue;
275
+ const head = `<h3 id="${esc(slugPart(m.name))}">${esc(m.name)}</h3>`;
276
+ if (m.signatures?.length) {
277
+ const name = m.kind === K.Constructor ? `new ${decl.name}` : m.name;
278
+ out.push(head, ...m.signatures.map((s) => this.signatureBlock(s, name)));
279
+ } else if (m.kind === K.Accessor) {
280
+ const get = m.getSignature;
281
+ out.push(
282
+ head,
283
+ `<pre class="api-signature"><code>${get ? "get" : "set"} ${esc(m.name)}: ${this.type(get?.type ?? m.setSignature?.parameters?.[0]?.type)}</code></pre>`,
284
+ this.comment(get?.comment ?? m.setSignature?.comment),
285
+ );
286
+ } else {
287
+ const flags = `${m.flags.isStatic ? "static " : ""}${m.flags.isReadonly ? "readonly " : ""}`;
288
+ const value =
289
+ m.kind === K.EnumMember
290
+ ? ` = ${this.type(m.type)}`
291
+ : `${m.flags.isOptional ? "?" : ""}: ${this.type(m.type)}`;
292
+ out.push(
293
+ head,
294
+ `<pre class="api-signature"><code>${flags}${esc(m.name)}${value}</code></pre>`,
295
+ this.comment(m.comment),
296
+ );
297
+ }
298
+ }
299
+ return out.length ? `<h2>Members</h2>\n${out.filter(Boolean).join("\n")}` : "";
300
+ }
301
+
302
+ signature(s: Sig, name: string): string {
303
+ const params = (s.parameters ?? []).map(
304
+ (p) =>
305
+ `${p.flags.isRest ? "..." : ""}${esc(p.name)}${p.flags.isOptional || p.defaultValue ? "?" : ""}: ${this.type(p.type)}`,
306
+ );
307
+ return `${esc(name)}${this.typeParams(s.typeParameters)}(${params.join(", ")}): ${this.type(s.type)}`;
308
+ }
309
+
310
+ signatureBlock(s: Sig, name: string): string {
311
+ const params = (s.parameters ?? []).filter((p) => p.comment?.summary?.length);
312
+ const ret = s.comment?.blockTags?.find((t) => t.tag === "@returns");
313
+ return [
314
+ `<pre class="api-signature"><code>${this.signature(s, name)}</code></pre>`,
315
+ this.comment(
316
+ s.comment && {
317
+ ...s.comment,
318
+ blockTags: s.comment.blockTags?.filter((t) => t.tag !== "@returns"),
319
+ },
320
+ ),
321
+ params.length
322
+ ? `<h4>Parameters</h4>\n<dl class="api-params">${params
323
+ .map(
324
+ (p) =>
325
+ `<dt><code>${esc(p.name)}</code></dt><dd>${this.markdown(p.comment?.summary)}</dd>`,
326
+ )
327
+ .join("")}</dl>`
328
+ : "",
329
+ ret ? `<h4>Returns</h4>\n${this.markdown(ret.content)}` : "",
330
+ ]
331
+ .filter(Boolean)
332
+ .join("\n");
333
+ }
334
+
335
+ typeParams(tps: JSONOutput.TypeParameterReflection[] | undefined): string {
336
+ if (!tps?.length) return "";
337
+ return `&lt;${tps
338
+ .map(
339
+ (t) =>
340
+ `${esc(t.name)}${t.type ? ` extends ${this.type(t.type)}` : ""}${t.default ? ` = ${this.type(t.default)}` : ""}`,
341
+ )
342
+ .join(", ")}&gt;`;
343
+ }
344
+
345
+ /** A type as HTML, references linked to their pages. */
346
+ type(t: SomeType | undefined): string {
347
+ if (!t) return "unknown";
348
+ switch (t.type) {
349
+ case "intrinsic":
350
+ return esc(t.name);
351
+ case "reference": {
352
+ const args = t.typeArguments?.length
353
+ ? `&lt;${t.typeArguments.map((a) => this.type(a)).join(", ")}&gt;`
354
+ : "";
355
+ return `${this.link(t.name, t.target)}${args}`;
356
+ }
357
+ case "literal":
358
+ return esc(
359
+ t.value === null
360
+ ? "null"
361
+ : typeof t.value === "object"
362
+ ? `${t.value.negative ? "-" : ""}${t.value.value}n`
363
+ : JSON.stringify(t.value),
364
+ );
365
+ case "union":
366
+ return t.types.map((x) => this.type(x)).join(" | ");
367
+ case "intersection":
368
+ return t.types.map((x) => this.type(x)).join(" &amp; ");
369
+ case "array": {
370
+ const inner = this.type(t.elementType);
371
+ const wrap = ["union", "intersection", "conditional"].includes(t.elementType.type);
372
+ return `${wrap ? `(${inner})` : inner}[]`;
373
+ }
374
+ case "tuple":
375
+ return `[${(t.elements ?? []).map((x) => this.type(x)).join(", ")}]`;
376
+ case "namedTupleMember":
377
+ return `${esc(t.name)}${t.isOptional ? "?" : ""}: ${this.type(t.element)}`;
378
+ case "optional":
379
+ return `${this.type(t.elementType)}?`;
380
+ case "rest":
381
+ return `...${this.type(t.elementType)}`;
382
+ case "typeOperator":
383
+ return `${t.operator} ${this.type(t.target)}`;
384
+ case "indexedAccess":
385
+ return `${this.type(t.objectType)}[${this.type(t.indexType)}]`;
386
+ case "query":
387
+ return `typeof ${this.type(t.queryType)}`;
388
+ case "predicate":
389
+ return `${t.asserts ? "asserts " : ""}${esc(t.name)}${t.targetType ? ` is ${this.type(t.targetType)}` : ""}`;
390
+ case "conditional":
391
+ return `${this.type(t.checkType)} extends ${this.type(t.extendsType)} ? ${this.type(t.trueType)} : ${this.type(t.falseType)}`;
392
+ case "inferred":
393
+ return `infer ${esc(t.name)}`;
394
+ case "templateLiteral":
395
+ return esc(
396
+ `\`${t.head}${t.tail.map(([x, s]) => `\${${stripTags(this.type(x))}}${s}`).join("")}\``,
397
+ );
398
+ case "mapped":
399
+ return `{ [${esc(t.parameter)} in ${this.type(t.parameterType)}]: ${this.type(t.templateType)} }`;
400
+ case "reflection": {
401
+ const d = t.declaration;
402
+ const only =
403
+ d.signatures?.length === 1 && !d.children?.length ? d.signatures[0] : undefined;
404
+ if (only) return this.signature(only, "").replace(/\): /, ") =&gt; ");
405
+ const members = (d.children ?? []).map(
406
+ (c) => `${esc(c.name)}${c.flags.isOptional ? "?" : ""}: ${this.type(c.type)}`,
407
+ );
408
+ return `{ ${members.join("; ")} }`;
409
+ }
410
+ case "unknown":
411
+ return esc(t.name);
412
+ default:
413
+ return "unknown";
414
+ }
415
+ }
416
+ }
417
+
418
+ const stripTags = (html: string) =>
419
+ html
420
+ .replace(/<[^>]+>/g, "")
421
+ .replace(/&lt;/g, "<")
422
+ .replace(/&gt;/g, ">")
423
+ .replace(/&amp;/g, "&")
424
+ .replace(/&quot;/g, '"');
package/src/typedoc.ts ADDED
@@ -0,0 +1,128 @@
1
+ // Node only: runs TypeDoc (with its own TypeScript 6.0.3, never the projects' TypeScript 7) over
2
+ // one package folder and returns the JSON model `apiPages()` reads.
3
+ import { existsSync, readFileSync } from "node:fs";
4
+ import { join, relative } from "node:path";
5
+ import { Application, Converter, type JSONOutput, LogLevel, normalizePath } from "typedoc";
6
+ import ts from "typescript";
7
+
8
+ export interface RunTypedocOptions {
9
+ /** The tsconfig, relative to the package folder. Default: `tsconfig.build.json` if present, else `tsconfig.json`. */
10
+ tsconfig?: string;
11
+ /** Problems TypeDoc reports (warnings and errors). */
12
+ log?: (level: "warn" | "error", message: string) => void;
13
+ /**
14
+ * When given, an import of a package that cannot be resolved (nothing installed) does not fail
15
+ * the package: its types are shown unresolved and this is told the import, as
16
+ * `unresolved import '<name>' (<file>:<line>)`, the file relative to the package (a missing
17
+ * `types` library as `unresolved type library '<name>'`). Without it such
18
+ * an import is an error, as any other type error.
19
+ */
20
+ unresolvedImport?: (warning: string) => void;
21
+ }
22
+
23
+ /**
24
+ * "Cannot find module" (2307, 2792), "Could not find a declaration file" (7016) and "Cannot find
25
+ * name 'node:…'. Do you need to install type definitions for node?" (2591): an import of types
26
+ * that are not installed.
27
+ */
28
+ const UNRESOLVED_MODULE_CODES = new Set([2307, 2792, 7016, 2591]);
29
+ /** "Cannot find type definition file for '<name>'": a `types` library that is not installed. */
30
+ const MISSING_TYPE_LIBRARY = 2688;
31
+
32
+ /** The type library a diagnostic says is not installed, if it is one. */
33
+ function missingTypeLibrary(d: ts.Diagnostic): string | undefined {
34
+ if (d.code !== MISSING_TYPE_LIBRARY) return undefined;
35
+ return /'([^']+)'/.exec(ts.flattenDiagnosticMessageText(d.messageText, "\n"))?.[1];
36
+ }
37
+
38
+ /** The bare specifier a diagnostic says cannot be resolved, if it is one (never a relative path). */
39
+ function unresolvedSpecifier(d: ts.Diagnostic): string | undefined {
40
+ if (!UNRESOLVED_MODULE_CODES.has(d.code) || !d.file || d.start === undefined) return undefined;
41
+ const literal = d.file.text.slice(d.start, d.start + (d.length ?? 0));
42
+ const name = literal.replace(/^(['"])(.*)\1$/s, "$2");
43
+ return name === literal || name.startsWith(".") || name.startsWith("/") ? undefined : name;
44
+ }
45
+
46
+ /**
47
+ * TypeDoc's JSON for one package: entry points from its `exports` map (the `source` condition
48
+ * first), its README included.
49
+ */
50
+ export async function runTypedoc(
51
+ packageDir: string,
52
+ options: RunTypedocOptions = {},
53
+ ): Promise<JSONOutput.ProjectReflection> {
54
+ const tsconfig =
55
+ options.tsconfig ??
56
+ (existsSync(join(packageDir, "tsconfig.build.json")) ? "tsconfig.build.json" : "tsconfig.json");
57
+ const app = await Application.bootstrapWithPlugins({
58
+ entryPoints: [packageDir],
59
+ entryPointStrategy: "packages",
60
+ packageOptions: {
61
+ tsconfig: join(packageDir, tsconfig),
62
+ compilerOptions: { customConditions: ["source"] },
63
+ readme: join(packageDir, "README.md"),
64
+ // TypeDoc's own check is replaced by the one below (each package is checked with its own
65
+ // options, not the root's): it skips installed dependencies' sources and, when asked,
66
+ // tells unresolved imports apart from other errors.
67
+ skipErrorChecking: true,
68
+ },
69
+ // The merged project's README; its package name is set after conversion (below).
70
+ ...(existsSync(join(packageDir, "README.md")) ? { readme: join(packageDir, "README.md") } : {}),
71
+ plugin: [],
72
+ logLevel: LogLevel.Warn,
73
+ skipErrorChecking: true,
74
+ });
75
+ const failures: string[] = [];
76
+ app.logger.log = (message, level) => {
77
+ if (level === LogLevel.Error) failures.push(message);
78
+ if (level >= LogLevel.Warn) options.log?.(level === LogLevel.Error ? "error" : "warn", message);
79
+ };
80
+ let checkFailed = false;
81
+ const report = options.unresolvedImport;
82
+ // TypeDoc's check, except that a diagnostic in an installed package's file is not the
83
+ // package's (the `source` condition reaches the TypeScript sources some dependencies ship,
84
+ // checked against types they do not install), and, with `unresolvedImport`, an unresolved bare
85
+ // import is a warning.
86
+ app.converter.on(Converter.EVENT_BEGIN, (context) => {
87
+ const errors: ts.Diagnostic[] = [];
88
+ for (const d of context.programs.flatMap((p) => ts.getPreEmitDiagnostics(p))) {
89
+ if (d.file && /[\\/]node_modules[\\/]/.test(d.file.fileName)) continue;
90
+ if (!report) {
91
+ if (d.category === ts.DiagnosticCategory.Error) errors.push(d);
92
+ continue;
93
+ }
94
+ const library = missingTypeLibrary(d);
95
+ if (library !== undefined) {
96
+ report(`unresolved type library '${library}'`);
97
+ continue;
98
+ }
99
+ const name = unresolvedSpecifier(d);
100
+ if (name === undefined) {
101
+ if (d.category === ts.DiagnosticCategory.Error) errors.push(d);
102
+ continue;
103
+ }
104
+ const file = d.file as ts.SourceFile;
105
+ const line = file.getLineAndCharacterOfPosition(d.start ?? 0).line + 1;
106
+ report(
107
+ `unresolved import '${name}' (${relative(packageDir, file.fileName).split("\\").join("/")}:${line})`,
108
+ );
109
+ }
110
+ if (errors.length === 0) return;
111
+ checkFailed = true;
112
+ app.logger.log(
113
+ ts.formatDiagnosticsWithColorAndContext(errors, {
114
+ getCanonicalFileName: (f) => f,
115
+ getCurrentDirectory: () => process.cwd(),
116
+ getNewLine: () => ts.sys.newLine,
117
+ }),
118
+ LogLevel.Error,
119
+ );
120
+ });
121
+ const project = await app.convert();
122
+ if (!project || checkFailed)
123
+ throw new Error(`TypeDoc failed on ${packageDir}: ${failures.join("; ")}`);
124
+ // TypeDoc names the merged project after the package.json it finds above the entry points: in
125
+ // a monorepo that is the repository's root, not the package's.
126
+ project.packageName = JSON.parse(readFileSync(join(packageDir, "package.json"), "utf8")).name;
127
+ return app.serializer.projectToObject(project, normalizePath(packageDir));
128
+ }