@cubicecho/agent-docs 0.0.0-stage → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (54) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +52 -2
  3. package/_agents/docs/01-install.md +55 -0
  4. package/_agents/docs/checks.md +16 -0
  5. package/_agents/docs/ci.md +71 -0
  6. package/_agents/docs/cli.md +39 -0
  7. package/_agents/docs/common-mistakes.md +54 -0
  8. package/_agents/docs/config.md +25 -0
  9. package/dist/bin.d.ts +7 -0
  10. package/dist/bin.js +11 -0
  11. package/dist/check/check-agent-docs.d.ts +23 -0
  12. package/dist/check/check-agent-docs.js +314 -0
  13. package/dist/check/generation.d.ts +37 -0
  14. package/dist/check/generation.js +86 -0
  15. package/dist/cli/run.d.ts +24 -0
  16. package/dist/cli/run.js +131 -0
  17. package/dist/consts.d.ts +16 -0
  18. package/dist/consts.js +16 -0
  19. package/dist/core/config.d.ts +31 -0
  20. package/dist/core/config.js +69 -0
  21. package/dist/core/errors.d.ts +17 -0
  22. package/dist/core/errors.js +21 -0
  23. package/dist/core/files.d.ts +28 -0
  24. package/dist/core/files.js +67 -0
  25. package/dist/core/json.d.ts +26 -0
  26. package/dist/core/json.js +44 -0
  27. package/dist/core/package-manifest.d.ts +38 -0
  28. package/dist/core/package-manifest.js +58 -0
  29. package/dist/defaults.d.ts +26 -0
  30. package/dist/defaults.js +14 -0
  31. package/dist/exports/entry-points.d.ts +30 -0
  32. package/dist/exports/entry-points.js +119 -0
  33. package/dist/exports/export-index.d.ts +44 -0
  34. package/dist/exports/export-index.js +233 -0
  35. package/dist/exports/module-source.d.ts +74 -0
  36. package/dist/exports/module-source.js +161 -0
  37. package/dist/exports/scan.d.ts +29 -0
  38. package/dist/exports/scan.js +156 -0
  39. package/dist/exports/summary.d.ts +36 -0
  40. package/dist/exports/summary.js +84 -0
  41. package/dist/index.d.ts +16 -0
  42. package/dist/index.js +16 -0
  43. package/dist/llms/identity.d.ts +21 -0
  44. package/dist/llms/identity.js +67 -0
  45. package/dist/llms/plan.d.ts +53 -0
  46. package/dist/llms/plan.js +318 -0
  47. package/dist/llms/sync.d.ts +16 -0
  48. package/dist/llms/sync.js +36 -0
  49. package/dist/markdown/anchors.d.ts +35 -0
  50. package/dist/markdown/anchors.js +66 -0
  51. package/dist/markdown/page.d.ts +20 -0
  52. package/dist/markdown/page.js +57 -0
  53. package/llms.txt +42 -0
  54. package/package.json +64 -4
@@ -0,0 +1,233 @@
1
+ import { existsSync, readFileSync } from 'node:fs';
2
+ import { join, posix } from 'node:path';
3
+ import { AgentDocsError } from '../core/errors.js';
4
+ import { ExportForm, parseModule } from './module-source.js';
5
+ import { plainText } from './summary.js';
6
+ const SOURCE_CANDIDATES = ['', '.ts', '.tsx', '.mts', '/index.ts'];
7
+ const BUILT_TO_SOURCE = { '.js': '.ts', '.mjs': '.mts', '.jsx': '.tsx' };
8
+ /** How many re-export hops a name is followed through before it is given up as a cycle. */
9
+ const MAX_HOPS = 32;
10
+ /**
11
+ * Lists what each entry point exports, each name with the first sentence of its doc comment.
12
+ *
13
+ * @param root - Package root.
14
+ * @param entries - The entry points, as {@link findEntryPoints} traces them.
15
+ * @returns One index per entry, in the same order.
16
+ * @throws {@link AgentDocsError} If a re-exported module is missing or an `export` statement can't be read.
17
+ *
18
+ * @remarks
19
+ * A re-exported name is followed through `export … from`, `export *` and imports to the declaration that
20
+ * documents it. Where a name is declared twice (a vocabulary's const and its union type), the first doc comment
21
+ * wins.
22
+ */
23
+ export function buildExportIndex(root, entries) {
24
+ const reader = new ModuleReader(root);
25
+ const indexes = entries.map((entry) => {
26
+ const module = reader.read(entry.source);
27
+ const listed = reader.listExports(entry.source, 0);
28
+ return {
29
+ importPath: entry.importPath,
30
+ source: entry.source,
31
+ summary: plainText(module?.moduleDoc[0] ?? ''),
32
+ exports: dedupe(listed.exports),
33
+ foreign: [...listed.foreign].map(([specifier, names]) => ({ specifier, names: [...new Set(names)] })),
34
+ };
35
+ });
36
+ if (reader.problems.length > 0) {
37
+ throw new AgentDocsError([...new Set(reader.problems)]);
38
+ }
39
+ return indexes;
40
+ }
41
+ /**
42
+ * Keeps the first entry per name, merging what a later one adds.
43
+ *
44
+ * @param listed - Exports in source order, possibly repeating a name.
45
+ * @returns One entry per name; a value wins over a type, and the first summary found is kept.
46
+ */
47
+ function dedupe(listed) {
48
+ const byName = new Map();
49
+ for (const entry of listed) {
50
+ const known = byName.get(entry.name);
51
+ if (known === undefined) {
52
+ byName.set(entry.name, { ...entry });
53
+ }
54
+ else {
55
+ known.isType = known.isType && entry.isType;
56
+ known.summary = known.summary === '' ? entry.summary : known.summary;
57
+ }
58
+ }
59
+ return [...byName.values()];
60
+ }
61
+ /** Reads and caches the modules an entry reaches, collecting what it can't read. */
62
+ class ModuleReader {
63
+ /** One line per module or statement that could not be read. */
64
+ problems = [];
65
+ #root;
66
+ #cache = new Map();
67
+ /**
68
+ * Starts a reader for one package.
69
+ *
70
+ * @param root - Package root.
71
+ */
72
+ constructor(root) {
73
+ this.#root = root;
74
+ }
75
+ /**
76
+ * Parses a module once.
77
+ *
78
+ * @param file - Path relative to the root.
79
+ * @returns The module, or undefined when the file is missing.
80
+ */
81
+ read(file) {
82
+ if (this.#cache.has(file)) {
83
+ return this.#cache.get(file);
84
+ }
85
+ const full = join(this.#root, file);
86
+ const module = existsSync(full) ? parseModule(file, readFileSync(full, 'utf8')) : undefined;
87
+ this.#cache.set(file, module);
88
+ for (const line of module?.unreadLines ?? []) {
89
+ this.problems.push(`${file}:${line} has an export this index can't read: write it as a declaration or an "export { … } from" list.`);
90
+ }
91
+ return module;
92
+ }
93
+ /**
94
+ * Resolves a relative specifier to a source file.
95
+ *
96
+ * @param from - The importing file, relative to the root.
97
+ * @param specifier - The specifier as written.
98
+ * @returns The file relative to the root, or undefined when nothing matches (also reported as a problem).
99
+ */
100
+ resolve(from, specifier) {
101
+ const base = posix.join(posix.dirname(from), specifier);
102
+ const builtExtension = Object.keys(BUILT_TO_SOURCE).find((extension) => base.endsWith(extension));
103
+ const stem = builtExtension ? base.slice(0, -builtExtension.length) : base;
104
+ const mapped = builtExtension ? [`${stem}${BUILT_TO_SOURCE[builtExtension]}`] : [];
105
+ const candidates = [...mapped, ...SOURCE_CANDIDATES.map((suffix) => `${stem}${suffix}`)];
106
+ const found = candidates.find((candidate) => this.#isFile(candidate));
107
+ if (found === undefined) {
108
+ this.problems.push(`${from} imports "${specifier}", which has no source file: fix the path.`);
109
+ }
110
+ return found;
111
+ }
112
+ /**
113
+ * Whether a path is an existing file with a source extension.
114
+ *
115
+ * @param path - Path relative to the root.
116
+ * @returns true for an existing `.ts`, `.tsx` or `.mts` file.
117
+ */
118
+ #isFile(path) {
119
+ return /\.(ts|tsx|mts)$/.test(path) && existsSync(join(this.#root, path));
120
+ }
121
+ /**
122
+ * Everything a module exports, in source order.
123
+ *
124
+ * @param file - Path relative to the root.
125
+ * @param hops - Re-export hops taken so far.
126
+ * @returns Its own and re-exported names, and the names it takes from other packages.
127
+ */
128
+ listExports(file, hops) {
129
+ const exports = [];
130
+ const foreign = new Map();
131
+ const module = this.read(file);
132
+ if (module === undefined || hops > MAX_HOPS) {
133
+ return { exports, foreign };
134
+ }
135
+ const addForeign = (specifier, names) => {
136
+ foreign.set(specifier, [...(foreign.get(specifier) ?? []), ...names]);
137
+ };
138
+ const items = [
139
+ ...module.declarations.filter((d) => d.isExported).map((d) => ({ offset: d.offset, declaration: d })),
140
+ ...module.statements.map((s) => ({ offset: s.offset, statement: s })),
141
+ ].sort((a, b) => a.offset - b.offset);
142
+ for (const item of items) {
143
+ if ('declaration' in item) {
144
+ const { name, isType, summary } = item.declaration;
145
+ exports.push({ name, isType, summary });
146
+ continue;
147
+ }
148
+ const { form, names, specifier } = item.statement;
149
+ const isForeign = specifier !== null && specifier.startsWith('.') === false;
150
+ if (isForeign) {
151
+ addForeign(specifier, form === ExportForm.All ? ['*'] : names.map((n) => n.exported));
152
+ continue;
153
+ }
154
+ const target = specifier === null ? file : this.resolve(file, specifier);
155
+ if (target === undefined) {
156
+ continue;
157
+ }
158
+ if (form === ExportForm.All) {
159
+ const inner = this.listExports(target, hops + 1);
160
+ exports.push(...inner.exports);
161
+ for (const [innerSpecifier, innerNames] of inner.foreign) {
162
+ addForeign(innerSpecifier, innerNames);
163
+ }
164
+ continue;
165
+ }
166
+ if (form === ExportForm.Namespace) {
167
+ const summary = plainText(this.read(target)?.moduleDoc[0] ?? '');
168
+ exports.push(...names.map((n) => ({ name: n.exported, isType: n.isType, summary })));
169
+ continue;
170
+ }
171
+ for (const name of names) {
172
+ const described = this.describe(target, name.local, hops + 1);
173
+ const isType = name.isType || (described?.isType ?? false);
174
+ exports.push({ name: name.exported, isType, summary: described?.summary ?? '' });
175
+ }
176
+ }
177
+ return { exports, foreign };
178
+ }
179
+ /**
180
+ * Follows a name to the declaration that documents it.
181
+ *
182
+ * @param file - The module the name is looked up in.
183
+ * @param name - The name inside that module.
184
+ * @param hops - Re-export hops taken so far.
185
+ * @returns Whether it is a type and its summary; undefined when it leaves the package or can't be found.
186
+ */
187
+ describe(file, name, hops) {
188
+ const module = this.read(file);
189
+ if (module === undefined || hops > MAX_HOPS) {
190
+ return undefined;
191
+ }
192
+ const declared = module.declarations.filter((d) => d.name === name);
193
+ if (declared.length > 0) {
194
+ const summary = declared.find((d) => d.summary !== '')?.summary ?? '';
195
+ return { isType: declared.every((d) => d.isType), summary };
196
+ }
197
+ const imported = module.imports.get(name);
198
+ if (imported !== undefined) {
199
+ return this.#follow(file, imported.specifier, imported.imported, hops);
200
+ }
201
+ for (const statement of module.statements) {
202
+ const listed = statement.names.find((n) => n.exported === name);
203
+ const isListed = listed !== undefined && statement.form === ExportForm.List && statement.specifier !== null;
204
+ if (isListed) {
205
+ return this.#follow(file, statement.specifier ?? '', listed.local, hops);
206
+ }
207
+ if (statement.form === ExportForm.All && statement.specifier?.startsWith('.')) {
208
+ const target = this.resolve(file, statement.specifier);
209
+ const found = target === undefined ? undefined : this.describe(target, name, hops + 1);
210
+ if (found !== undefined) {
211
+ return found;
212
+ }
213
+ }
214
+ }
215
+ return undefined;
216
+ }
217
+ /**
218
+ * Describes a name in the module a specifier names, when it is in this package.
219
+ *
220
+ * @param from - The file the specifier is written in.
221
+ * @param specifier - The specifier.
222
+ * @param name - The name inside the target module.
223
+ * @param hops - Re-export hops taken so far.
224
+ * @returns What {@link ModuleReader.describe} finds there; undefined for another package.
225
+ */
226
+ #follow(from, specifier, name, hops) {
227
+ if (specifier.startsWith('.') === false) {
228
+ return undefined;
229
+ }
230
+ const target = this.resolve(from, specifier);
231
+ return target === undefined ? undefined : this.describe(target, name, hops + 1);
232
+ }
233
+ }
@@ -0,0 +1,74 @@
1
+ /** A top-level declaration and what its doc comment says. */
2
+ export interface Declaration {
3
+ /** The declared name; `default` for an `export default` with no name of its own. */
4
+ name: string;
5
+ /** An interface or type alias. */
6
+ isType: boolean;
7
+ /** Declared with `export`. */
8
+ isExported: boolean;
9
+ /** The first sentence of its doc comment; empty when it has none. */
10
+ summary: string;
11
+ /** Offset of the declaration in the file. */
12
+ offset: number;
13
+ }
14
+ /** One name in an `export { … }` or `import { … }` list. */
15
+ export interface ListedName {
16
+ /** The name inside the module it comes from. */
17
+ local: string;
18
+ /** The name it goes by after `as`, or `local`. */
19
+ exported: string;
20
+ /** Marked `type`, on the name or the whole list. */
21
+ isType: boolean;
22
+ }
23
+ /** The shapes of export statement this reader understands, beside declarations. */
24
+ export declare const ExportForm: {
25
+ /** `export { a, type B } from '…'`, or the same list without `from`. */
26
+ readonly List: 'list';
27
+ /** `export * from '…'`. */
28
+ readonly All: 'all';
29
+ /** `export * as ns from '…'`. */
30
+ readonly Namespace: 'namespace';
31
+ };
32
+ export type ExportForm = (typeof ExportForm)[keyof typeof ExportForm];
33
+ /** An export statement that is not a declaration. */
34
+ export interface ExportStatement {
35
+ /** Which shape it has. */
36
+ form: ExportForm;
37
+ /** The names it exports: the list, or the one namespace name. Empty for `export *`. */
38
+ names: ListedName[];
39
+ /** The module it re-exports from; null for a list of the file's own names. */
40
+ specifier: string | null;
41
+ /** Offset of the statement in the file. */
42
+ offset: number;
43
+ }
44
+ /** What one TypeScript file declares, exports and imports. */
45
+ export interface ModuleSource {
46
+ /** The file's path relative to the package root. */
47
+ file: string;
48
+ /** Paragraphs of the file's own doc comment (a doc comment followed by a blank line); empty when absent. */
49
+ moduleDoc: string[];
50
+ /** Top-level declarations in order, overloads and merged declarations each listed. */
51
+ declarations: Declaration[];
52
+ /** Export statements in order. */
53
+ statements: ExportStatement[];
54
+ /** Named imports by local name. */
55
+ imports: Map<string, {
56
+ imported: string;
57
+ specifier: string;
58
+ }>;
59
+ /** Line numbers of `export` statements none of the patterns read. */
60
+ unreadLines: number[];
61
+ }
62
+ /**
63
+ * Reads the shape of one TypeScript module.
64
+ *
65
+ * @param file - The file's path relative to the package root, for messages.
66
+ * @param source - The file's text.
67
+ * @returns Its declarations, exports, imports and own doc comment.
68
+ * @throws {@link AgentDocsError} If a block comment never closes.
69
+ *
70
+ * @remarks
71
+ * Only top-level code at the start of a line is read, as a formatter leaves it. An `export` statement that no
72
+ * pattern reads is reported in `unreadLines` rather than skipped, so the index never quietly drops an export.
73
+ */
74
+ export declare function parseModule(file: string, source: string): ModuleSource;
@@ -0,0 +1,161 @@
1
+ import { scanSource } from './scan.js';
2
+ import { paragraphs, summarize } from './summary.js';
3
+ /** The shapes of export statement this reader understands, beside declarations. */
4
+ export const ExportForm = {
5
+ /** `export { a, type B } from '…'`, or the same list without `from`. */
6
+ List: 'list',
7
+ /** `export * from '…'`. */
8
+ All: 'all',
9
+ /** `export * as ns from '…'`. */
10
+ Namespace: 'namespace',
11
+ };
12
+ const DECLARATION = /^(export[ \t]+)?(?:declare[ \t]+)?(default[ \t]+)?(?:abstract[ \t]+)?(?:async[ \t]+)?(function[ \t]*\*?|const|let|var|class|interface|type|enum|namespace)[ \t]+([A-Za-z_$][\w$]*)/gm;
13
+ const DEFAULT_EXPRESSION = /^export[ \t]+default\b/gm;
14
+ const LIST = /^export[ \t]+(type[ \t]+)?\{([^}]*)\}(?:\s*from\s*(['"])([^'"\n]+)\3)?/gm;
15
+ const ALL = /^export[ \t]+(?:type[ \t]+)?\*(?:\s+as\s+([\w$]+))?\s+from\s*(['"])([^'"\n]+)\2/gm;
16
+ const IMPORT = /^import[ \t]+(type[ \t]+)?\{([^}]*)\}\s*from\s*(['"])([^'"\n]+)\3/gm;
17
+ const EXPORT_KEYWORD = /^export\b/gm;
18
+ const TYPE_KINDS = new Set(['interface', 'type']);
19
+ /**
20
+ * Reads the shape of one TypeScript module.
21
+ *
22
+ * @param file - The file's path relative to the package root, for messages.
23
+ * @param source - The file's text.
24
+ * @returns Its declarations, exports, imports and own doc comment.
25
+ * @throws {@link AgentDocsError} If a block comment never closes.
26
+ *
27
+ * @remarks
28
+ * Only top-level code at the start of a line is read, as a formatter leaves it. An `export` statement that no
29
+ * pattern reads is reported in `unreadLines` rather than skipped, so the index never quietly drops an export.
30
+ */
31
+ export function parseModule(file, source) {
32
+ const { code, docBlocks } = scanSource(file, source);
33
+ const declarations = [];
34
+ for (const match of code.matchAll(DECLARATION)) {
35
+ const [, exportKeyword, defaultKeyword, kind, name] = match;
36
+ const block = attachedBlock(source, docBlocks, match.index);
37
+ declarations.push({
38
+ name: defaultKeyword ? 'default' : name,
39
+ isType: TYPE_KINDS.has(kind),
40
+ isExported: Boolean(exportKeyword),
41
+ summary: block ? summarize(block.body) : '',
42
+ offset: match.index,
43
+ });
44
+ }
45
+ const statements = exportStatements(code);
46
+ const read = new Set([...declarations.map((d) => d.offset), ...statements.map((s) => s.offset)]);
47
+ for (const match of code.matchAll(DEFAULT_EXPRESSION)) {
48
+ const isUnread = read.has(match.index) === false;
49
+ if (isUnread) {
50
+ const block = attachedBlock(source, docBlocks, match.index);
51
+ const summary = block ? summarize(block.body) : '';
52
+ declarations.push({ name: 'default', isType: false, isExported: true, summary, offset: match.index });
53
+ read.add(match.index);
54
+ }
55
+ }
56
+ const unreadLines = [...code.matchAll(EXPORT_KEYWORD)]
57
+ .filter((match) => read.has(match.index) === false)
58
+ .map((match) => lineNumber(code, match.index));
59
+ const moduleBlock = docBlocks.find((block) => isFollowedByBlankLine(source, block));
60
+ return {
61
+ file,
62
+ moduleDoc: moduleBlock ? paragraphs(moduleBlock.body) : [],
63
+ declarations: declarations.sort((a, b) => a.offset - b.offset),
64
+ statements,
65
+ imports: namedImports(code),
66
+ unreadLines,
67
+ };
68
+ }
69
+ /**
70
+ * The `export { … }` and `export *` statements of a file.
71
+ *
72
+ * @param code - The file with comments blanked.
73
+ * @returns The statements, in order.
74
+ */
75
+ function exportStatements(code) {
76
+ const statements = [];
77
+ for (const match of code.matchAll(LIST)) {
78
+ const [, typeKeyword, inner, , specifier] = match;
79
+ const names = listedNames(inner, Boolean(typeKeyword));
80
+ statements.push({ form: ExportForm.List, names, specifier: specifier ?? null, offset: match.index });
81
+ }
82
+ for (const match of code.matchAll(ALL)) {
83
+ const [, namespace, , specifier] = match;
84
+ const names = namespace ? [{ local: namespace, exported: namespace, isType: false }] : [];
85
+ const form = namespace ? ExportForm.Namespace : ExportForm.All;
86
+ statements.push({ form, names, specifier, offset: match.index });
87
+ }
88
+ return statements.sort((a, b) => a.offset - b.offset);
89
+ }
90
+ /**
91
+ * The names in the braces of an import or export list.
92
+ *
93
+ * @param inner - The text between the braces.
94
+ * @param isTypeList - Whether the whole list is marked `type`.
95
+ * @returns One entry per name, with its `as` rename applied.
96
+ */
97
+ function listedNames(inner, isTypeList) {
98
+ return inner
99
+ .split(',')
100
+ .map((entry) => entry.trim())
101
+ .filter((entry) => entry !== '')
102
+ .map((entry) => {
103
+ const isType = isTypeList || entry.startsWith('type ');
104
+ const [local, exported = local] = entry.replace(/^type\s+/, '').split(/\s+as\s+/);
105
+ return { local, exported, isType };
106
+ });
107
+ }
108
+ /**
109
+ * The named imports of a file.
110
+ *
111
+ * @param code - The file with comments blanked.
112
+ * @returns The imported name and module per local name.
113
+ */
114
+ function namedImports(code) {
115
+ const imports = new Map();
116
+ for (const [, typeKeyword, inner, , specifier] of code.matchAll(IMPORT)) {
117
+ for (const { local, exported } of listedNames(inner, Boolean(typeKeyword))) {
118
+ imports.set(exported, { imported: local, specifier });
119
+ }
120
+ }
121
+ return imports;
122
+ }
123
+ /**
124
+ * The doc comment directly above a position, with no blank line between.
125
+ *
126
+ * @param source - The file's text.
127
+ * @param blocks - The file's doc comments.
128
+ * @param offset - Where the declaration starts.
129
+ * @returns The comment, or undefined when the nearest one is separated by a blank line or by code.
130
+ */
131
+ function attachedBlock(source, blocks, offset) {
132
+ const block = blocks.findLast((candidate) => candidate.end <= offset);
133
+ if (block === undefined) {
134
+ return undefined;
135
+ }
136
+ const between = source.slice(block.end, offset).split('\n');
137
+ const isAttached = between.slice(1, -1).every((line) => line.trim().startsWith('//') || line.trim().startsWith('@'));
138
+ const isOnlySpace = between[0].trim() === '' && between[between.length - 1].trim() === '';
139
+ return isAttached && isOnlySpace ? block : undefined;
140
+ }
141
+ /**
142
+ * Whether a doc comment is the file's own: followed by a blank line, or by nothing.
143
+ *
144
+ * @param source - The file's text.
145
+ * @param block - One of its doc comments.
146
+ * @returns true when the line after the comment is blank or the file ends.
147
+ */
148
+ function isFollowedByBlankLine(source, block) {
149
+ const [rest = '', next] = source.slice(block.end).split('\n', 2);
150
+ return rest.trim() === '' && (next === undefined || next.trim() === '');
151
+ }
152
+ /**
153
+ * The 1-based line number of an offset.
154
+ *
155
+ * @param text - The file's text.
156
+ * @param offset - A position in it.
157
+ * @returns The line it is on.
158
+ */
159
+ function lineNumber(text, offset) {
160
+ return text.slice(0, offset).split('\n').length;
161
+ }
@@ -0,0 +1,29 @@
1
+ /** One `/** … *\/` comment. */
2
+ export interface DocBlock {
3
+ /** Offset of the opening `/**`. */
4
+ start: number;
5
+ /** Offset just past the closing delimiter. */
6
+ end: number;
7
+ /** The comment's lines, `*` margin stripped. */
8
+ body: string[];
9
+ }
10
+ /** A source file with its comments found. */
11
+ export interface ScannedSource {
12
+ /** The source with every comment replaced by spaces, newlines and offsets kept, so patterns never match inside one. */
13
+ code: string;
14
+ /** Every doc comment, in order. */
15
+ docBlocks: DocBlock[];
16
+ }
17
+ /**
18
+ * Finds the comments in a TypeScript file.
19
+ *
20
+ * @param file - The file's path, for messages.
21
+ * @param source - The file's text.
22
+ * @returns The source with comments blanked, and its doc comments.
23
+ * @throws {@link AgentDocsError} If a block comment is never closed.
24
+ *
25
+ * @remarks
26
+ * Strings, template literals and regex literals are stepped over, so a `//` in a URL or a `/*` in a pattern is
27
+ * not taken for a comment.
28
+ */
29
+ export declare function scanSource(file: string, source: string): ScannedSource;
@@ -0,0 +1,156 @@
1
+ import { AgentDocsError } from '../core/errors.js';
2
+ const DOC_OPEN = '/**';
3
+ const COMMENT_CLOSE = '*/';
4
+ const QUOTES = new Set(['"', "'", '`']);
5
+ /** A `/` after one of these (or at the start) opens a regex literal rather than dividing. */
6
+ const BEFORE_REGEX = /[(,=:[!&|?{};+\-*%<>~^]$|(?:^|[^\w$])(?:return|typeof|case|of|in)$/;
7
+ const MARGIN = /^\s*\* ?/;
8
+ /** How many characters before a `/` are enough to see the keyword or operator in front of it. */
9
+ const REGEX_LOOKBEHIND = 8;
10
+ /**
11
+ * Finds the comments in a TypeScript file.
12
+ *
13
+ * @param file - The file's path, for messages.
14
+ * @param source - The file's text.
15
+ * @returns The source with comments blanked, and its doc comments.
16
+ * @throws {@link AgentDocsError} If a block comment is never closed.
17
+ *
18
+ * @remarks
19
+ * Strings, template literals and regex literals are stepped over, so a `//` in a URL or a `/*` in a pattern is
20
+ * not taken for a comment.
21
+ */
22
+ export function scanSource(file, source) {
23
+ const parts = [];
24
+ const docBlocks = [];
25
+ let copiedTo = 0;
26
+ let i = 0;
27
+ while (i < source.length) {
28
+ const char = source[i];
29
+ const next = source[i + 1];
30
+ if (QUOTES.has(char)) {
31
+ i = skipQuoted(source, i);
32
+ continue;
33
+ }
34
+ const isLineComment = char === '/' && next === '/';
35
+ const isBlockComment = char === '/' && next === '*';
36
+ if (isLineComment || isBlockComment) {
37
+ const end = isLineComment ? lineEnd(source, i) : blockEnd(file, source, i);
38
+ const isDoc = isBlockComment && source.startsWith(DOC_OPEN, i) && end - i > DOC_OPEN.length + 1;
39
+ if (isDoc) {
40
+ docBlocks.push({ start: i, end, body: docBody(source.slice(i + DOC_OPEN.length, end - COMMENT_CLOSE.length)) });
41
+ }
42
+ parts.push(source.slice(copiedTo, i), source.slice(i, end).replace(/[^\n]/g, ' '));
43
+ copiedTo = end;
44
+ i = end;
45
+ continue;
46
+ }
47
+ const opensRegex = char === '/' && BEFORE_REGEX.test(source.slice(Math.max(0, i - REGEX_LOOKBEHIND), i).trimEnd());
48
+ if (opensRegex) {
49
+ i = skipRegex(source, i);
50
+ continue;
51
+ }
52
+ i += 1;
53
+ }
54
+ parts.push(source.slice(copiedTo));
55
+ return { code: parts.join(''), docBlocks };
56
+ }
57
+ /**
58
+ * Offset of the end of the line a position is on.
59
+ *
60
+ * @param source - The text.
61
+ * @param from - A position on the line.
62
+ * @returns The offset of its newline, or the text's length on the last line.
63
+ */
64
+ function lineEnd(source, from) {
65
+ const newline = source.indexOf('\n', from);
66
+ return newline === -1 ? source.length : newline;
67
+ }
68
+ /**
69
+ * Offset just past the block comment that opens at a position.
70
+ *
71
+ * @param file - The file's path, for messages.
72
+ * @param source - The text.
73
+ * @param from - Offset of the opening `/*`.
74
+ * @returns Offset just past its `*\/`.
75
+ * @throws {@link AgentDocsError} If the comment is never closed.
76
+ */
77
+ function blockEnd(file, source, from) {
78
+ const close = source.indexOf(COMMENT_CLOSE, from + 2);
79
+ if (close === -1) {
80
+ const line = source.slice(0, from).split('\n').length;
81
+ throw new AgentDocsError([`${file}:${line} opens a comment that never closes: add the closing "*/".`]);
82
+ }
83
+ return close + COMMENT_CLOSE.length;
84
+ }
85
+ /**
86
+ * Offset just past the string or template literal that opens at a position.
87
+ *
88
+ * @param source - The text.
89
+ * @param from - Offset of the opening quote.
90
+ * @returns Offset just past the closing quote; a plain string also ends at its line's end.
91
+ */
92
+ function skipQuoted(source, from) {
93
+ const quote = source[from];
94
+ let i = from + 1;
95
+ while (i < source.length) {
96
+ const char = source[i];
97
+ if (char === '\\') {
98
+ i += 2;
99
+ continue;
100
+ }
101
+ if (char === quote) {
102
+ return i + 1;
103
+ }
104
+ const isUnterminatedLine = char === '\n' && quote !== '`';
105
+ if (isUnterminatedLine) {
106
+ return i;
107
+ }
108
+ i += 1;
109
+ }
110
+ return i;
111
+ }
112
+ /**
113
+ * Offset just past the regex literal that opens at a position.
114
+ *
115
+ * @param source - The text.
116
+ * @param from - Offset of the opening `/`.
117
+ * @returns Offset just past the closing `/`, or the line's end when there is none.
118
+ */
119
+ function skipRegex(source, from) {
120
+ let inClass = false;
121
+ for (let i = from + 1; i < source.length; i++) {
122
+ const char = source[i];
123
+ if (char === '\\') {
124
+ i += 1;
125
+ }
126
+ else if (char === '\n') {
127
+ return i;
128
+ }
129
+ else if (char === '[') {
130
+ inClass = true;
131
+ }
132
+ else if (char === ']') {
133
+ inClass = false;
134
+ }
135
+ else if (char === '/' && inClass === false) {
136
+ return i + 1;
137
+ }
138
+ }
139
+ return source.length;
140
+ }
141
+ /**
142
+ * The lines of a doc comment's inside, `*` margin stripped.
143
+ *
144
+ * @param inner - The text between `/**` and `*\/`.
145
+ * @returns The lines, with the empty first and last lines of the block form dropped.
146
+ */
147
+ function docBody(inner) {
148
+ const lines = inner.split('\n').map((line, index) => (index === 0 ? line : line.replace(MARGIN, '')).trimEnd());
149
+ while (lines.length > 0 && lines[0].trim() === '') {
150
+ lines.shift();
151
+ }
152
+ while (lines.length > 0 && lines[lines.length - 1].trim() === '') {
153
+ lines.pop();
154
+ }
155
+ return lines;
156
+ }
@@ -0,0 +1,36 @@
1
+ /**
2
+ * The paragraphs of a doc comment ahead of its first tag, each on one line.
3
+ *
4
+ * @param body - The comment's lines, `*` margin stripped.
5
+ * @returns The paragraphs, blank-line separated in the comment.
6
+ *
7
+ * @remarks
8
+ * Tags, and the `@remarks` prose under them, are not the summary's; a block written without the blank line above
9
+ * its tags would otherwise run its summary on into them.
10
+ */
11
+ export declare function paragraphs(body: readonly string[]): string[];
12
+ /**
13
+ * Reduces TSDoc and markdown links to their text.
14
+ *
15
+ * @param text - One paragraph of a doc comment.
16
+ * @returns `{@link X | label}` as `label`, `{@link X}` as `X`, and `[text](url)` as `text`.
17
+ */
18
+ export declare function plainText(text: string): string;
19
+ /**
20
+ * The first sentence of a paragraph.
21
+ *
22
+ * @param text - One paragraph, on one line.
23
+ * @returns Its text up to the first sentence end, or all of it when it has none.
24
+ *
25
+ * @remarks
26
+ * A period inside a code span, or after an abbreviation such as `e.g.` or `i.e.` (also after a bracket, as in
27
+ * `(e.g. a host)`), does not end the sentence.
28
+ */
29
+ export declare function firstSentence(text: string): string;
30
+ /**
31
+ * The one-line summary a doc comment gives the index.
32
+ *
33
+ * @param body - The comment's lines, `*` margin stripped.
34
+ * @returns The first sentence of its first paragraph, links reduced to text; empty when it has no prose.
35
+ */
36
+ export declare function summarize(body: readonly string[]): string;