@orkestrel/guide 0.0.17 → 0.0.19

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.
@@ -1,16 +1,15 @@
1
- import { createMarkdown, flattenText, isCodeBlockNode, isCodeSpanNode, isEmphasisNode, isHeadingNode, isImageNode, isLinkNode, isTableNode, walkNodes } from "@orkestrel/markdown";
2
- import { arrayOf, arrayShape, createContract, isEmptyString, isNonEmptyArray, isNonEmptyString, isString, literalOf, literalShape, objectShape, recordOf, stringShape, unionOf, unionShape } from "@orkestrel/contract";
1
+ import { coalesceText, createMarkdown, flattenText, isBlockquoteNode, isCodeBlockNode, isCodeSpanNode, isEmphasisNode, isHeadingNode, isImageNode, isLinkNode, isParagraphNode, isTableNode, renderMarkdown, walkNodes } from "@orkestrel/markdown";
2
+ import { arrayOf, arrayShape, createContract, isEmptyString, isNonEmptyArray, isNonEmptyString, isString, literalOf, literalShape, objectShape, optionalShape, recordOf, stringShape, unionOf, unionShape } from "@orkestrel/contract";
3
3
  //#region src/core/constants.ts
4
4
  /**
5
- * Lists the declaration keywords a documented or exported symbol carries, in
6
- * the order the reflection grammar names them.
5
+ * Lists the declaration keywords a documented or exported symbol carries, in the order the
6
+ * reflection grammar names them — the frozen population `ExportKeyword`, `isExportKeyword`, and
7
+ * `surfaceSymbolShape` all derive from.
7
8
  *
8
9
  * @remarks
9
- * One frozen list feeds the `ExportKeyword` type, the `isExportKeyword` guard, and
10
- * `surfaceSymbolShape`, so a keyword cannot be admitted by one and refused by
11
- * another. Comment and template payload is excluded before reflection, and
12
- * `enum` is outside this population rather than forbidden by general package
13
- * policy.
10
+ * One frozen list feeds the type, the guard, and the shape, so a keyword cannot be admitted by one
11
+ * and refused by another. Comment and template payload is excluded before reflection, and `enum`
12
+ * is outside this population rather than forbidden by general package policy.
14
13
  */
15
14
  var EXPORT_KEYWORDS = Object.freeze([
16
15
  "type",
@@ -20,6 +19,10 @@ var EXPORT_KEYWORDS = Object.freeze([
20
19
  "class"
21
20
  ]);
22
21
  /**
22
+ * Lists the compared sites a {@link Drift} can describe.
23
+ */
24
+ var DRIFT_CATEGORIES = Object.freeze(["summary", "example"]);
25
+ /**
23
26
  * Names the `## Surface` heading text a guide's documented exports section is keyed on.
24
27
  */
25
28
  var SURFACE = "Surface";
@@ -32,10 +35,34 @@ var METHODS = "Methods";
32
35
  */
33
36
  var TESTS = "Tests";
34
37
  /**
38
+ * Names the header text of the column a `## Surface` table's declaration keyword is read from.
39
+ */
40
+ var KIND = "Kind";
41
+ /**
42
+ * Names the header text of the column a `## Surface` or `## Methods` table's compared
43
+ * description paragraph is read from.
44
+ */
45
+ var SUMMARY = "Summary";
46
+ /**
35
47
  * Names the `## By concept` heading text the manifest's run-map table is keyed on.
36
48
  */
37
49
  var MANIFEST = "By concept";
38
50
  /**
51
+ * Holds the default character budget a rewritten doc block's description paragraph wraps
52
+ * inside — the greatest number of characters a re-wrapped line may carry, counted from the
53
+ * line's first character with a tab counting as one, so a wrapped line reads
54
+ * `${indent} * ${text}` and never passes that count.
55
+ *
56
+ * @remarks
57
+ * The budget counts characters, not rendered columns. A block indented with tabs therefore
58
+ * measures each tab as one character, and a formatter that renders a tab wider reads the same
59
+ * line as longer; a caller whose formatter measures differently passes its own width instead of
60
+ * taking this default. A doc block's own wrapping is not recoverable from its text either — the
61
+ * blocks this package's own source carries are hand-wrapped, and no single greedy width
62
+ * reproduces them — so a rewrite cannot infer a per-block width and falls back to this budget.
63
+ */
64
+ var WRAP_WIDTH = 100;
65
+ /**
39
66
  * Lists the link `href` schemes a guides-parity link check skips as external — a link
40
67
  * with one of these prefixes (or a bare `#` anchor, handled separately in
41
68
  * `isExternalLink`) is never resolved against the filesystem.
@@ -63,9 +90,11 @@ var EXTERNAL_SCHEMES = Object.freeze([
63
90
  * ```
64
91
  */
65
92
  var isExportKeyword = literalOf(EXPORT_KEYWORDS);
93
+ /** Checks whether `value` names a supported drift category. */
94
+ var isDriftCategory = literalOf(DRIFT_CATEGORIES);
66
95
  /**
67
96
  * Checks whether `value` is a well-formed {@link SurfaceSymbol} — a `name`
68
- * string paired with a valid {@link ExportKeyword}.
97
+ * string paired with a valid {@link ExportKeyword}, and an optional `summary`.
69
98
  *
70
99
  * @param value - The value to test
71
100
  * @returns True if `value` is a well-formed {@link SurfaceSymbol}; false otherwise
@@ -78,24 +107,80 @@ var isExportKeyword = literalOf(EXPORT_KEYWORDS);
78
107
  */
79
108
  var isSurfaceSymbol = recordOf({
80
109
  name: isString,
81
- keyword: isExportKeyword
82
- });
110
+ keyword: isExportKeyword,
111
+ summary: isString
112
+ }, ["summary"]);
113
+ /**
114
+ * Checks whether `value` is a well-formed {@link MethodEntry} — a `name` string with an
115
+ * optional `summary`.
116
+ *
117
+ * @param value - The value to test
118
+ * @returns True if `value` is a well-formed {@link MethodEntry}; false otherwise
119
+ *
120
+ * @example
121
+ * ```ts
122
+ * isMethodEntry({ name: 'walk' }) // true
123
+ * isMethodEntry({ name: 1 }) // false
124
+ * ```
125
+ */
126
+ var isMethodEntry = recordOf({
127
+ name: isString,
128
+ summary: isString
129
+ }, ["summary"]);
130
+ /**
131
+ * Checks whether `value` is a well-formed {@link SourceExample} — a `name` and `code`
132
+ * string with an optional `title` and `language`.
133
+ *
134
+ * @param value - The value to test
135
+ * @returns True if `value` is a well-formed {@link SourceExample}; false otherwise
136
+ *
137
+ * @example
138
+ * ```ts
139
+ * isSourceExample({ name: 'walk', code: 'walk()' }) // true
140
+ * isSourceExample({ name: 'walk' }) // false
141
+ * ```
142
+ */
143
+ var isSourceExample = recordOf({
144
+ name: isString,
145
+ title: isString,
146
+ code: isString,
147
+ language: isString
148
+ }, ["title", "language"]);
149
+ /**
150
+ * Checks whether `value` is a well-formed {@link Drift} — a compared `key` with an optional
151
+ * `guide` and `source` text.
152
+ *
153
+ * @param value - The value to test
154
+ * @returns True if `value` is a well-formed {@link Drift}; false otherwise
155
+ *
156
+ * @example
157
+ * ```ts
158
+ * isDrift({ key: 'class Widget', category: 'summary', guide: 'A widget.' }) // true
159
+ * isDrift({ guide: 'A widget.' }) // false
160
+ * ```
161
+ */
162
+ var isDrift = recordOf({
163
+ key: isString,
164
+ category: isDriftCategory,
165
+ guide: isString,
166
+ source: isString
167
+ }, ["guide", "source"]);
83
168
  /**
84
169
  * Checks whether `value` is a well-formed {@link MethodGroup} — a backticked
85
- * `interface` name paired with its documented `methods`.
170
+ * `interface` name paired with its documented {@link MethodEntry} rows.
86
171
  *
87
172
  * @param value - The value to test
88
173
  * @returns True if `value` is a well-formed {@link MethodGroup}; false otherwise
89
174
  *
90
175
  * @example
91
176
  * ```ts
92
- * isMethodGroup({ interface: 'MarkdownInterface', methods: ['walk'] }) // true
93
- * isMethodGroup({ interface: 'MarkdownInterface', methods: [1] }) // false
177
+ * isMethodGroup({ interface: 'MarkdownInterface', methods: [{ name: 'walk' }] }) // true
178
+ * isMethodGroup({ interface: 'MarkdownInterface', methods: [1] }) // false
94
179
  * ```
95
180
  */
96
181
  var isMethodGroup = recordOf({
97
182
  interface: isString,
98
- methods: arrayOf(isString)
183
+ methods: arrayOf(isMethodEntry)
99
184
  });
100
185
  /**
101
186
  * Checks whether `value` is a well-formed {@link ManifestEntry} — a
@@ -141,10 +226,13 @@ var isManifestEntry = recordOf({
141
226
  * @param source - The TypeScript source text to project
142
227
  * @returns One aligned terminator-free record per LF or CRLF physical line, including the final line
143
228
  *
144
- * @example
229
+ * @example Project source into physical code lines
145
230
  * ```ts
231
+ * import { extractSourceLines } from '@orkestrel/guide'
232
+ *
146
233
  * extractSourceLines('export const visible = true // note\n')
147
- * // [{ source: 'export const visible = true // note', code: 'export const visible = true ', jsdoc: undefined }, ...]
234
+ * // [{ source: 'export const visible = true // note', code: 'export const visible = true ', jsdoc: undefined }]
235
+ * // … one record per remaining line
148
236
  * ```
149
237
  */
150
238
  function extractSourceLines(source) {
@@ -696,8 +784,8 @@ function selectModuleKeys(files, module) {
696
784
  return keys.sort();
697
785
  }
698
786
  /**
699
- * Computes the bijection key for a surface symbol — its keyword and name combined — so a
700
- * symbol-set comparison diffs (name, keyword) pairs rather than names alone.
787
+ * Computes the bijection key for a surface symbol — `${keyword} ${name}` — so a symbol-set
788
+ * comparison diffs (name, keyword) pairs rather than names alone.
701
789
  *
702
790
  * @param symbol - The symbol to key
703
791
  * @returns The `${keyword} ${name}` key
@@ -787,10 +875,11 @@ function findUnexampled(names, fences, examples) {
787
875
  });
788
876
  }
789
877
  /**
790
- * Parses a fence's `import` statements into per-specifier imported identifier
791
- * names — handles `import type`, mixed multiline braces, and `x as y` aliases,
792
- * resolving each alias to the exported name `x` because that is the name the
793
- * checked barrel surface must hold.
878
+ * Parses a fence's brace `import` statements into per-specifier imported identifier names —
879
+ * `import type`, mixed multiline braces, and `x as y` aliases all count, each alias resolved to
880
+ * the exported name `x` because that is the name the checked barrel surface must hold. Brace
881
+ * bindings only: a default, namespace, side-effect, or mixed `import Default, { named }`
882
+ * statement is not surfaced.
794
883
  *
795
884
  * @param fence - A ```ts Patterns fence's verbatim body text
796
885
  * @returns One entry per `import ... from 'specifier'` statement, in fence order
@@ -908,7 +997,7 @@ function findFirstCode(nodes) {
908
997
  }
909
998
  }
910
999
  /**
911
- * Extracts the link hrefs within one table cell's inline content.
1000
+ * Extracts the link hrefs within one table cell's inline content, in walk order.
912
1001
  *
913
1002
  * @param cell - The cell's inline nodes
914
1003
  * @returns The cell's link hrefs, in walk order
@@ -947,38 +1036,117 @@ function normalizeIdentifier(code) {
947
1036
  return (index < 0 ? code : code.slice(0, index)).trim();
948
1037
  }
949
1038
  /**
950
- * Finds the index of a table's `Kind` column by its header text so it survives
951
- * column reordering. The match is exact and case-sensitive (`'Kind'`) — a table
952
- * without that exact header contributes no symbols to the surface it feeds.
1039
+ * Extracts compared inline content — the text of a table cell or candidate entity heading
1040
+ * flattened with every code span kept as a code span, so `` `Widget` `` reads the same wherever
1041
+ * the parity reader compares it. Emphasis drops to its text, a link drops to its text, an image
1042
+ * drops to its alternative text, and the markdown parser has already unescaped `\|`.
1043
+ *
1044
+ * @param cell - The inline nodes to flatten
1045
+ * @returns The compared text, code spans included
1046
+ *
1047
+ * @example
1048
+ * ```ts
1049
+ * extractCellText([{ element: 'codeSpan', value: 'Widget' }]) // '`Widget`'
1050
+ * ```
1051
+ */
1052
+ function extractCellText(cell) {
1053
+ let text = "";
1054
+ for (const node of cell) if (isCodeSpanNode(node)) text += `\`${node.value}\``;
1055
+ else if (isEmphasisNode(node) || isLinkNode(node) || isImageNode(node)) text += extractCellText(node.children);
1056
+ else text += flattenText(node);
1057
+ return text;
1058
+ }
1059
+ /**
1060
+ * Builds one table cell's inline content from its compared text — the inverse of
1061
+ * {@link extractCellText}. A single-backtick run whose text carries no inner backtick and
1062
+ * neither a leading nor a trailing space becomes a code span; every other character, a backtick
1063
+ * included, becomes literal text, which `renderMarkdown` escapes so the rendered cell parses back
1064
+ * to the text this function was given.
1065
+ *
1066
+ * @remarks
1067
+ * The compared form spells every code span with one backtick per side, because
1068
+ * {@link extractCellText} emits `` `${value}` `` whatever delimiter the source used. A run this
1069
+ * function refuses is therefore a run no parsed cell produced, and emitting it as text is what
1070
+ * keeps the projection total: reading the rendered cell back through {@link extractCellText}
1071
+ * returns the text, so a rendered row and a hand-written row compare the same. A code span whose
1072
+ * own text carries a backtick or a boundary space is outside the compared form's fidelity in
1073
+ * either direction, and this function writes it as text rather than guessing a delimiter.
1074
+ *
1075
+ * @param text - The cell's compared text, as {@link extractCellText} returns it
1076
+ * @returns The cell's inline nodes, in text order
1077
+ *
1078
+ * @example
1079
+ * ```ts
1080
+ * buildCell('Holds a `Widget`.')
1081
+ * // [{ element: 'text', value: 'Holds a ' }, { element: 'codeSpan', value: 'Widget' }, { element: 'text', value: '.' }]
1082
+ * ```
1083
+ */
1084
+ function buildCell(text) {
1085
+ const nodes = [];
1086
+ const spans = /`([^`]+)`/g;
1087
+ let cursor = 0;
1088
+ let span;
1089
+ while ((span = spans.exec(text)) !== null) {
1090
+ const value = span[1];
1091
+ if (value === void 0) continue;
1092
+ if (span.index > cursor) nodes.push({
1093
+ element: "text",
1094
+ value: text.slice(cursor, span.index)
1095
+ });
1096
+ if (value.trim() === value) nodes.push({
1097
+ element: "codeSpan",
1098
+ value
1099
+ });
1100
+ else nodes.push({
1101
+ element: "text",
1102
+ value: span[0]
1103
+ });
1104
+ cursor = span.index + span[0].length;
1105
+ }
1106
+ if (cursor < text.length) nodes.push({
1107
+ element: "text",
1108
+ value: text.slice(cursor)
1109
+ });
1110
+ return coalesceText(nodes);
1111
+ }
1112
+ /**
1113
+ * Finds the index of the column whose header text is `header` so a table's columns survive
1114
+ * reordering. The match is exact and case-sensitive — a table without that exact header
1115
+ * contributes nothing to the projection reading it, so a `## Surface` table with no
1116
+ * {@link SUMMARY} column leaves every row's summary absent and {@link findDrift} reports each
1117
+ * of those rows, never agreement.
953
1118
  *
954
1119
  * @param table - The table to inspect
955
- * @returns The `Kind` column's index, or `undefined` when the table has no `Kind` header
1120
+ * @param header - The exact header text to locate, for example `Kind`
1121
+ * @returns The column's index, or `undefined` when the table has no such header
956
1122
  *
957
1123
  * @example
958
1124
  * ```ts
959
- * findKindIndex(table) // 1, or undefined
1125
+ * findColumnIndex(table, 'Kind') // 1, or undefined
960
1126
  * ```
961
1127
  */
962
- function findKindIndex(table) {
1128
+ function findColumnIndex(table, header) {
963
1129
  for (let index = 0; index < table.header.length; index += 1) {
964
1130
  const cell = table.header[index];
965
1131
  if (cell !== void 0 && flattenText({
966
1132
  element: "paragraph",
967
1133
  children: cell
968
- }).trim() === "Kind") return index;
1134
+ }).trim() === header) return index;
969
1135
  }
970
1136
  }
971
1137
  /**
972
- * Extracts the module-scope exports declared in one file's source text — matches
973
- * `export (async)? (function(\*)?|class|const|interface|type) Name`, deduped
974
- * by (keyword, name). A generator export (`export function* walk`) scans as the
975
- * `function` keyword — its trailing `*` is stripped before the
976
- * {@link ExportKeyword} check.
977
- * Scanning uses {@link extractSourceLines}, so comment and template payload is
978
- * excluded while its uninterrupted column-zero head remains required; preserved
979
- * columns do not grant membership to leading/interrupted comment forms. The population is
980
- * exactly `type`, `interface`, `const`, `function`, and `class`; `enum` is
981
- * outside this reflection contract, not forbidden by general package policy.
1138
+ * Extracts the module-scope exports declared in one file's source text — the declaration keys
1139
+ * {@link collectKeys} reports, each split back into the keyword and name that built it, deduped by
1140
+ * (keyword, name).
1141
+ *
1142
+ * @remarks
1143
+ * That one grammar matches `export (async)? (function(\*)?|class|const|interface|type) Name`; a
1144
+ * generator export (`export function* walk`) keys as the `function` keyword, its trailing `*`
1145
+ * stripped before the {@link ExportKeyword} check. Scanning uses {@link extractSourceLines}, so
1146
+ * comment and template payload is excluded while its uninterrupted column-zero head remains
1147
+ * required; preserved columns do not grant membership to leading/interrupted comment forms. The
1148
+ * population is exactly `type`, `interface`, `const`, `function`, and `class`; `enum` is outside
1149
+ * this reflection contract, not forbidden by general package policy.
982
1150
  *
983
1151
  * @param source - The file's source text
984
1152
  * @returns The file's exported symbols, in file order
@@ -992,33 +1160,38 @@ function findKindIndex(table) {
992
1160
  function extractExports(source) {
993
1161
  const symbols = [];
994
1162
  const seen = /* @__PURE__ */ new Set();
995
- for (const line of extractSourceLines(source)) {
996
- const match = line.code.match(/^export (?:async )?(function\*?|class|const|interface|type) (\w+)/);
997
- const rawKeyword = match?.[1];
998
- const name = match?.[2];
999
- const keyword = rawKeyword === void 0 ? void 0 : rawKeyword.replace(/\*$/, "");
1000
- if (!isNonEmptyString(keyword) || !isNonEmptyString(name) || !isExportKeyword(keyword)) continue;
1001
- const key = `${keyword} ${name}`;
1002
- if (seen.has(key)) continue;
1163
+ const lines = extractSourceLines(source);
1164
+ const summaries = collectSummaries(lines);
1165
+ const keys = collectKeys(lines);
1166
+ for (const line of lines) {
1167
+ const key = keys.get(line);
1168
+ if (key === void 0 || seen.has(key)) continue;
1169
+ const space = key.indexOf(" ");
1170
+ const keyword = key.slice(0, Math.max(space, 0));
1171
+ if (!isExportKeyword(keyword)) continue;
1003
1172
  seen.add(key);
1173
+ const name = key.slice(space + 1);
1174
+ const summary = summaries.get(line);
1004
1175
  symbols.push({
1005
1176
  name,
1006
- keyword
1177
+ keyword,
1178
+ ...summary === void 0 ? {} : { summary }
1007
1179
  });
1008
1180
  }
1009
1181
  return symbols;
1010
1182
  }
1011
1183
  /**
1012
- * Extracts the module-scope declarations lacking the `export` keyword in one file's
1013
- * source text — the mirror image of {@link extractExports}'s grammar, anchored
1014
- * the same way (column 0, so an indented inner declaration never matches).
1015
- * Scans only the {@link ExportKeyword} keywords (`function` / `class` /
1016
- * `const` / `interface` / `type`) — a module-scope `let` or `var` is outside
1017
- * this scanner's declaration-keyword grammar and out of this check's contract.
1018
- * Scanning uses {@link extractSourceLines}, so comment
1019
- * and template payload is excluded while its uninterrupted column-zero head
1020
- * remains required; preserved columns do not widen membership. `enum` is likewise outside this reflection population, not
1021
- * forbidden by general package policy.
1184
+ * Extracts the module-scope declarations lacking the `export` keyword in one file's source text —
1185
+ * the mirror image of {@link extractExports}'s grammar, anchored the same way (column 0, so an
1186
+ * indented inner declaration never matches).
1187
+ *
1188
+ * @remarks
1189
+ * Scans only the {@link ExportKeyword} keywords (`function` / `class` / `const` / `interface` /
1190
+ * `type`) — a module-scope `let` or `var` is outside this scanner's declaration-keyword grammar
1191
+ * and out of this check's contract. Scanning uses {@link extractSourceLines}, so comment and
1192
+ * template payload is excluded while its uninterrupted column-zero head remains required;
1193
+ * preserved columns do not widen membership. `enum` is likewise outside this reflection
1194
+ * population, not forbidden by general package policy.
1022
1195
  *
1023
1196
  * @param source - The file's source text
1024
1197
  * @returns The file's hidden (non-exported) symbols, in file order
@@ -1032,7 +1205,9 @@ function extractExports(source) {
1032
1205
  function extractHidden(source) {
1033
1206
  const symbols = [];
1034
1207
  const seen = /* @__PURE__ */ new Set();
1035
- for (const line of extractSourceLines(source)) {
1208
+ const lines = extractSourceLines(source);
1209
+ const summaries = collectSummaries(lines);
1210
+ for (const line of lines) {
1036
1211
  if (line.code.startsWith("export ")) continue;
1037
1212
  const match = line.code.match(/^(?:async )?(function\*?|class|const|interface|type) (\w+)/);
1038
1213
  const rawKeyword = match?.[1];
@@ -1042,9 +1217,11 @@ function extractHidden(source) {
1042
1217
  const key = `${keyword} ${name}`;
1043
1218
  if (seen.has(key)) continue;
1044
1219
  seen.add(key);
1220
+ const summary = summaries.get(line);
1045
1221
  symbols.push({
1046
1222
  name,
1047
- keyword
1223
+ keyword,
1224
+ ...summary === void 0 ? {} : { summary }
1048
1225
  });
1049
1226
  }
1050
1227
  return symbols;
@@ -1079,11 +1256,10 @@ function joinHead(lines, start) {
1079
1256
  * inside a larger `RegExp` source rather than as syntax.
1080
1257
  *
1081
1258
  * @remarks
1082
- * Every caller-supplied name reaches a `RegExp` through this: {@link
1083
- * extractDeclaration} splices it into the head grammar and {@link
1084
- * findUnexampled} into a word-boundary search, so a name carrying `$`, `(`,
1085
- * `[`, or `.` matches that character literally instead of throwing or matching
1086
- * text it does not name. Pure and total; never throws.
1259
+ * A caller-supplied name reaches a `RegExp` through this: {@link
1260
+ * findUnexampled} splices it into a word-boundary search, so a name carrying
1261
+ * `$`, `(`, `[`, or `.` matches that character literally instead of throwing or
1262
+ * matching text it does not name. Pure and total; never throws.
1087
1263
  *
1088
1264
  * @param value - The literal string to escape
1089
1265
  * @returns `value` with every regex metacharacter backslash-escaped
@@ -1098,84 +1274,134 @@ function escapeRegExp(value) {
1098
1274
  return value.replace(/[\\^$.*+?()[\]{}|]/g, "\\$&");
1099
1275
  }
1100
1276
  /**
1101
- * Locates the named `export class` / `export interface` declaration in one
1102
- * file's source text and returns its body lines and its base identifiers read
1103
- * from that one head, so a body and a heritage clause always come from the same
1104
- * declaration.
1277
+ * Collects every `export class` / `export interface` declaration one file's source text declares,
1278
+ * each keyed `${keyword} ${name}` and carrying the body lines and the base identifiers read from
1279
+ * its own head, so a body and a heritage clause always come from the same declaration.
1105
1280
  *
1106
1281
  * @remarks
1107
- * The head is matched on projected lines (column 0, an oxfmt-wrapped signature
1108
- * joined through {@link joinHead}), with an optional generic parameter list and
1109
- * an optional heritage clause between the identifier and the opening `{`; the
1110
- * identifier matches exactly and is escaped through {@link escapeRegExp}, so a
1111
- * metacharacter in `name` is literal text. The returned body lines are the raw
1112
- * source between that head and the first projected column-zero `}`, keeping
1113
- * JSDoc evidence intact. Every balanced `<...>` span is removed from the head
1114
- * before its `extends` clause is read, so a `T extends Base` type parameter is
1115
- * never a base and `Base<T>` reads as `Base`; a class's `implements` clause and
1116
- * everything after it is excluded, and a qualified base such as
1117
- * `namespace.Base` is returned verbatim. A head that opens no column-zero close
1118
- * is skipped and the scan continues, so a later real declaration still answers.
1119
- *
1120
- * @param source - The file's source text to search
1121
- * @param keyword - Whether to look for a `class` or an `interface`
1122
- * @param name - The declaration's identifier
1123
- * @returns Its body and bases, or `undefined` when `source` declares no such head
1282
+ * The whole file is projected once through {@link extractSourceLines} and every head is read from
1283
+ * that one projection, so a scope resolving many names reads each file once rather than once per
1284
+ * name. A head is a column-zero `export class` / `export interface` line, an oxfmt-wrapped
1285
+ * signature joined through {@link joinHead}, with an optional generic parameter list and an
1286
+ * optional heritage clause between the identifier and the opening `{`; the identifier is the head's
1287
+ * own run up to that list or clause, so it enters the key as literal text and no name reaches a
1288
+ * `RegExp`. Body lines are the raw source between the head and the first projected column-zero `}`,
1289
+ * keeping JSDoc evidence intact. Every balanced `<...>` span is removed from the head before its
1290
+ * `extends` clause is read, so a `T extends Base` type parameter is never a base and `Base<T>`
1291
+ * reads as `Base`; a class's `implements` clause and everything after it is excluded, and a
1292
+ * qualified base such as `namespace.Base` is returned verbatim. The first head of a key that opens
1293
+ * a column-zero close answers for that key: a head that opens none records nothing, and a later
1294
+ * head of a key already collected adds nothing.
1295
+ *
1296
+ * @param source - The file's source text to read
1297
+ * @returns One entry per collected declaration, keyed `${keyword} ${name}`
1124
1298
  *
1125
1299
  * @example
1126
1300
  * ```ts
1127
- * extractDeclaration('export interface X extends Y {\n\twalk(): void\n}\n', 'interface', 'X')
1301
+ * collectDeclarations('export interface X extends Y {\n\twalk(): void\n}\n').get('interface X')
1128
1302
  * // { body: ['\twalk(): void'], bases: ['Y'] }
1129
1303
  * ```
1130
1304
  */
1131
- function extractDeclaration(source, keyword, name) {
1132
- const opener = `export ${keyword} ${name}`;
1133
- const grammar = new RegExp(`^${escapeRegExp(opener)}(?:<.*>)?(?: .*)? \\{$`);
1305
+ function collectDeclarations(source) {
1306
+ const declarations = /* @__PURE__ */ new Map();
1307
+ const opener = /^export (?:class|interface) /;
1308
+ const grammar = /^export (class|interface) ([^\s<]+)(?:<.*>)?(?: .*)? \{$/;
1134
1309
  const lines = extractSourceLines(source);
1135
1310
  const projected = lines.map((line) => line.code);
1136
1311
  for (let index = 0; index < projected.length; index += 1) {
1137
1312
  const line = projected[index];
1138
- if (line === void 0 || !line.startsWith(opener)) continue;
1313
+ if (line === void 0 || !opener.test(line)) continue;
1139
1314
  const head = joinHead(projected, index);
1140
- if (head === void 0 || !grammar.test(head.text)) continue;
1315
+ if (head === void 0) continue;
1316
+ const declared = grammar.exec(head.text);
1317
+ const keyword = declared?.[1];
1318
+ const name = declared?.[2];
1319
+ if (keyword === void 0 || name === void 0) continue;
1320
+ const key = `${keyword} ${name}`;
1321
+ if (declarations.has(key)) continue;
1141
1322
  let depth = 0;
1142
1323
  let flat = "";
1143
- for (const character of head.text.slice(opener.length, -1)) if (character === "<") depth += 1;
1324
+ for (const character of head.text.slice(`export ${key}`.length, -1)) if (character === "<") depth += 1;
1144
1325
  else if (character === ">") depth = Math.max(0, depth - 1);
1145
1326
  else if (depth === 0) flat += character;
1146
1327
  const clause = flat.replace(/\bimplements\b[\s\S]*$/, "").match(/\bextends\b([\s\S]*)$/)?.[1];
1147
1328
  const bases = clause === void 0 ? [] : clause.split(",").map((base) => base.trim()).filter(isNonEmptyString);
1148
1329
  for (let close = head.end + 1; close < projected.length; close += 1) {
1149
1330
  if (projected[close] !== "}") continue;
1150
- return {
1331
+ declarations.set(key, {
1151
1332
  body: lines.slice(head.end + 1, close).map((record) => record.source),
1152
1333
  bases
1153
- };
1334
+ });
1335
+ break;
1154
1336
  }
1155
1337
  }
1338
+ return declarations;
1339
+ }
1340
+ /**
1341
+ * Locates the named `export class` / `export interface` declaration in one file's source text
1342
+ * and returns its body lines and its base identifiers read from that one head, so a body and a
1343
+ * heritage clause always come from the same declaration, or `undefined` when the file declares
1344
+ * no such head.
1345
+ *
1346
+ * @remarks
1347
+ * The one named lookup over {@link collectDeclarations}, which owns the head grammar, the body
1348
+ * window, and the base reading. This lookup spells the map's `${keyword} ${name}` key for its
1349
+ * caller, so a consumer reading one name never writes that convention itself. `name` is compared
1350
+ * as literal text against the identifier the head itself carries, so a metacharacter in `name`
1351
+ * names that character rather than matching text it does not name. Every call collects the whole
1352
+ * file afresh: a consumer reading many names from one file calls {@link collectDeclarations} once
1353
+ * and reads the map, and {@link Source} holds one such map per module scope.
1354
+ *
1355
+ * @param source - The file's source text to search
1356
+ * @param keyword - Whether to look for a `class` or an `interface`
1357
+ * @param name - The declaration's identifier
1358
+ * @returns Its body and bases, or `undefined` when `source` declares no such head
1359
+ *
1360
+ * @example
1361
+ * ```ts
1362
+ * extractDeclaration('export interface X extends Y {\n\twalk(): void\n}\n', 'interface', 'X')
1363
+ * // { body: ['\twalk(): void'], bases: ['Y'] }
1364
+ * ```
1365
+ */
1366
+ function extractDeclaration(source, keyword, name) {
1367
+ return collectDeclarations(source).get(`${keyword} ${name}`);
1156
1368
  }
1157
1369
  /**
1158
1370
  * Selects the member lines declaring a callable member: plain, `async`, generator
1159
1371
  * (`*`), and optional (`records?(`) methods all count; getters, setters,
1160
1372
  * `static` members, and `#` privates never do (their keyword or `#` breaks
1161
- * the `name(` shape). Matching runs once over projected lines so commented
1162
- * method-like payload never becomes eligible.
1373
+ * the `name(` shape). The grammar is {@link collectKeys}'s, read once over
1374
+ * {@link extractBodyLines}'s projection of the body, so commented method-like payload never
1375
+ * becomes eligible and each member keys to the owner head that projection supplies. Each member
1376
+ * carries its own doc block's description paragraph, read through {@link collectSummaries}; the
1377
+ * first declaration of a name answers for it.
1163
1378
  *
1164
1379
  * @param lines - A declaration's body lines
1165
- * @returns The declared method names, deduped and sorted
1380
+ * @returns The declared members, deduplicated by name and sorted by name
1166
1381
  *
1167
1382
  * @example
1168
1383
  * ```ts
1169
- * extractMemberMethods(['\tmap(): void', '\tfilter(): void']) // ['filter', 'map']
1384
+ * extractMemberMethods(['\tmap(): void', '\tfilter(): void']) // [{ name: 'filter' }, { name: 'map' }]
1170
1385
  * ```
1171
1386
  */
1172
1387
  function extractMemberMethods(lines) {
1173
- const methods = [];
1174
- for (const line of extractSourceLines(lines.join("\n"))) {
1175
- const method = line.code.match(/^\t(?:async )?\*?(\w+)\??(<.*>)?\(/);
1176
- if (method?.[1] !== void 0) methods.push(method[1]);
1388
+ const methods = /* @__PURE__ */ new Map();
1389
+ const projected = extractBodyLines(lines);
1390
+ const summaries = collectSummaries(projected);
1391
+ const keys = collectKeys(projected);
1392
+ for (const line of projected) {
1393
+ const key = keys.get(line) ?? "";
1394
+ const dot = key.indexOf(".");
1395
+ if (dot < 0) continue;
1396
+ const name = key.slice(dot + 1);
1397
+ if (methods.has(name)) continue;
1398
+ const summary = summaries.get(line);
1399
+ methods.set(name, {
1400
+ name,
1401
+ ...summary === void 0 ? {} : { summary }
1402
+ });
1177
1403
  }
1178
- return Array.from(new Set(methods)).sort();
1404
+ return Array.from(methods.values()).sort((a, b) => a.name === b.name ? 0 : a.name < b.name ? -1 : 1);
1179
1405
  }
1180
1406
  /**
1181
1407
  * Selects the block nodes under the named `##` heading, up to the next `##`-or-higher
@@ -1207,11 +1433,107 @@ function selectSectionBlocks(document, heading) {
1207
1433
  return blocks;
1208
1434
  }
1209
1435
  /**
1436
+ * Extracts one `## Surface` table row's symbol — its column 0 code span as the name, its
1437
+ * {@link KIND} column as the keyword, and its {@link SUMMARY} column as the compared summary
1438
+ * when the table has that column. A row with no code-span name and a row whose `Kind` text is
1439
+ * no {@link ExportKeyword} have no symbol to key, so each returns `undefined`.
1440
+ *
1441
+ * @param table - The table to read
1442
+ * @param row - The index of the row within {@link TableNode.rows}
1443
+ * @returns The row's symbol, or `undefined` when the row keys none
1444
+ *
1445
+ * @example
1446
+ * ```ts
1447
+ * extractRowSymbol(table, 0) // { name: 'walk', keyword: 'function', summary: 'Walks the tree.' }
1448
+ * ```
1449
+ */
1450
+ function extractRowSymbol(table, row) {
1451
+ const cells = table.rows[row];
1452
+ if (cells === void 0) return void 0;
1453
+ const nameCell = cells[0];
1454
+ const rawName = nameCell === void 0 ? void 0 : findFirstCode(nameCell);
1455
+ const name = rawName === void 0 ? void 0 : normalizeIdentifier(rawName);
1456
+ if (name === void 0) return void 0;
1457
+ const column = findColumnIndex(table, KIND);
1458
+ const kindCell = column === void 0 ? void 0 : cells[column];
1459
+ const keyword = kindCell === void 0 ? "" : flattenText({
1460
+ element: "paragraph",
1461
+ children: kindCell
1462
+ }).trim();
1463
+ if (!isExportKeyword(keyword)) return void 0;
1464
+ const summary = extractRowSummary(table, row);
1465
+ return {
1466
+ name,
1467
+ keyword,
1468
+ ...summary === void 0 ? {} : { summary }
1469
+ };
1470
+ }
1471
+ /**
1472
+ * Extracts one `## Methods` table row's entry — its column 0 code span as the name and its
1473
+ * {@link SUMMARY} column as the compared summary when the table has that column. A row with no
1474
+ * code-span name has no member to key, so it returns `undefined`.
1475
+ *
1476
+ * @param table - The table to read
1477
+ * @param row - The index of the row within {@link TableNode.rows}
1478
+ * @returns The row's entry, or `undefined` when the row keys none
1479
+ *
1480
+ * @example
1481
+ * ```ts
1482
+ * extractRowEntry(table, 0) // { name: 'walk', summary: 'Walks the tree.' }
1483
+ * ```
1484
+ */
1485
+ function extractRowEntry(table, row) {
1486
+ const cells = table.rows[row];
1487
+ if (cells === void 0) return void 0;
1488
+ const cell = cells[0];
1489
+ const rawName = cell === void 0 ? void 0 : findFirstCode(cell);
1490
+ const name = rawName === void 0 ? void 0 : normalizeIdentifier(rawName);
1491
+ if (name === void 0) return void 0;
1492
+ const summary = extractRowSummary(table, row);
1493
+ return {
1494
+ name,
1495
+ ...summary === void 0 ? {} : { summary }
1496
+ };
1497
+ }
1498
+ /**
1499
+ * Extracts one row's compared summary — its {@link SUMMARY} column read through
1500
+ * {@link extractCellText} and {@link normalizeSummary}. A table with no such column and a row
1501
+ * whose cell is empty each carry no summary and return `undefined` rather than an empty string,
1502
+ * so {@link findDrift} reports the absence.
1503
+ *
1504
+ * @param table - The table to read
1505
+ * @param row - The index of the row within {@link TableNode.rows}
1506
+ * @returns The row's compared summary, or `undefined` when it carries none
1507
+ *
1508
+ * @example
1509
+ * ```ts
1510
+ * extractRowSummary(table, 0) // 'Walks the tree.'
1511
+ * ```
1512
+ */
1513
+ function extractRowSummary(table, row) {
1514
+ const described = findColumnIndex(table, SUMMARY);
1515
+ const cells = table.rows[row];
1516
+ const cell = described === void 0 || cells === void 0 ? void 0 : cells[described];
1517
+ const summary = cell === void 0 ? "" : normalizeSummary(extractCellText(cell));
1518
+ return summary.length === 0 ? void 0 : summary;
1519
+ }
1520
+ /**
1210
1521
  * Extracts every `## Surface` identifier the guide documents — each table row's column 0
1211
- * code span (the name) paired with its `Kind` column (located by header text)
1212
- * unioned with every backticked H3 entity heading in the section
1213
- * (`{name: <codeSpan>, keyword: 'class'}`), deduped by {@link computeSymbolKey}. A row with
1214
- * no code-span name, or an unrecognized `Kind` text, is skipped.
1522
+ * code span (the name) paired with its `Kind` column (located by header text), unioned with every
1523
+ * H3 entity heading whose trimmed compared inline content is exactly its backticked code-span
1524
+ * name, deduped by {@link computeSymbolKey}. A row with no code-span name has no name to key a
1525
+ * symbol on, so this reader skips it and {@link extractUnnamed} reports it; a row with an
1526
+ * unrecognized `Kind` text is skipped. A row also carries its {@link SUMMARY} column's compared
1527
+ * text when the table has that column; a table without it leaves every row's summary absent,
1528
+ * which {@link findDrift} reports.
1529
+ *
1530
+ * @remarks
1531
+ * The heading boundary compares {@link extractCellText} with the raw value from
1532
+ * {@link findFirstCode} before {@link normalizeIdentifier} strips a generic annotation.
1533
+ * Surrounding spaces, emphasis, and links preserve that identity. This reader refuses a heading
1534
+ * carrying any other visible text or an additional code span. Entries retain encounter order, and
1535
+ * the first-seen name + keyword wins: a genuine heading before its table row keeps the heading's
1536
+ * summary-less class entry, while a table row before that heading keeps its `Summary`.
1215
1537
  *
1216
1538
  * @param document - The parsed guide document
1217
1539
  * @returns The documented surface, in encounter order
@@ -1226,22 +1548,9 @@ function extractSurface(document) {
1226
1548
  const seen = /* @__PURE__ */ new Set();
1227
1549
  for (const block of selectSectionBlocks(document, SURFACE)) {
1228
1550
  if (isTableNode(block)) {
1229
- const column = findKindIndex(block);
1230
- for (const row of block.rows) {
1231
- const nameCell = row[0];
1232
- const rawName = nameCell === void 0 ? void 0 : findFirstCode(nameCell);
1233
- const name = rawName === void 0 ? void 0 : normalizeIdentifier(rawName);
1234
- if (name === void 0) continue;
1235
- const kindCell = column === void 0 ? void 0 : row[column];
1236
- const kindText = kindCell === void 0 ? "" : flattenText({
1237
- element: "paragraph",
1238
- children: kindCell
1239
- }).trim();
1240
- if (!isExportKeyword(kindText)) continue;
1241
- const symbol = {
1242
- name,
1243
- keyword: kindText
1244
- };
1551
+ for (let row = 0; row < block.rows.length; row += 1) {
1552
+ const symbol = extractRowSymbol(block, row);
1553
+ if (symbol === void 0) continue;
1245
1554
  const key = computeSymbolKey(symbol);
1246
1555
  if (seen.has(key)) continue;
1247
1556
  seen.add(key);
@@ -1251,10 +1560,9 @@ function extractSurface(document) {
1251
1560
  }
1252
1561
  if (isHeadingNode(block) && block.level === 3) {
1253
1562
  const rawName = findFirstCode(block.children);
1254
- const name = rawName === void 0 ? void 0 : normalizeIdentifier(rawName);
1255
- if (name === void 0) continue;
1563
+ if (rawName === void 0 || extractCellText(block.children).trim() !== `\`${rawName}\``) continue;
1256
1564
  const symbol = {
1257
- name,
1565
+ name: normalizeIdentifier(rawName),
1258
1566
  keyword: "class"
1259
1567
  };
1260
1568
  const key = computeSymbolKey(symbol);
@@ -1268,18 +1576,50 @@ function extractSurface(document) {
1268
1576
  /**
1269
1577
  * Extracts one {@link MethodGroup} per documented behavioral interface in `## Methods` —
1270
1578
  * an H4 with a code span sets the current interface, and the table immediately
1271
- * following becomes its documented methods.
1579
+ * following becomes its documented methods. A row with no code-span name has no name to key a
1580
+ * member on, so this reader skips it and {@link extractUnnamed} reports it. Each row carries its
1581
+ * {@link SUMMARY} column's compared text when the table has that column.
1272
1582
  *
1273
1583
  * @param document - The parsed guide document
1274
1584
  * @returns The documented method groups, in document order
1275
1585
  *
1276
1586
  * @example
1277
1587
  * ```ts
1278
- * extractMethods(document) // [{ interface: 'MarkdownInterface', methods: ['walk', ...] }]
1588
+ * extractMethods(document) // [{ interface: 'MarkdownInterface', methods: [{ name: 'walk' }] }]
1279
1589
  * ```
1280
1590
  */
1281
1591
  function extractMethods(document) {
1282
1592
  const groups = [];
1593
+ for (const [table, name] of collectGroups(document)) {
1594
+ const methods = [];
1595
+ for (let row = 0; row < table.rows.length; row += 1) {
1596
+ const entry = extractRowEntry(table, row);
1597
+ if (entry !== void 0) methods.push(entry);
1598
+ }
1599
+ groups.push({
1600
+ interface: name,
1601
+ methods
1602
+ });
1603
+ }
1604
+ return groups;
1605
+ }
1606
+ /**
1607
+ * Collects each `## Methods` table keyed to the interface its `####` heading names — an H4
1608
+ * carrying a code span sets the current interface and the table immediately following claims it,
1609
+ * so a heading with no table and a table with no heading before it contribute nothing. The map
1610
+ * iterates in document order and a node keys itself, so a repeated identical table keeps its own
1611
+ * entry.
1612
+ *
1613
+ * @param document - The parsed guide document
1614
+ * @returns One entry per documented `## Methods` table, in document order
1615
+ *
1616
+ * @example
1617
+ * ```ts
1618
+ * collectGroups(document).values().next().value // 'GuideInterface'
1619
+ * ```
1620
+ */
1621
+ function collectGroups(document) {
1622
+ const groups = /* @__PURE__ */ new Map();
1283
1623
  let current;
1284
1624
  for (const block of selectSectionBlocks(document, METHODS)) {
1285
1625
  if (isHeadingNode(block) && block.level === 4) {
@@ -1288,23 +1628,41 @@ function extractMethods(document) {
1288
1628
  continue;
1289
1629
  }
1290
1630
  if (isTableNode(block) && current !== void 0) {
1291
- const methods = [];
1292
- for (const row of block.rows) {
1293
- const cell = row[0];
1294
- const rawName = cell === void 0 ? void 0 : findFirstCode(cell);
1295
- const name = rawName === void 0 ? void 0 : normalizeIdentifier(rawName);
1296
- if (name !== void 0) methods.push(name);
1297
- }
1298
- groups.push({
1299
- interface: current,
1300
- methods
1301
- });
1631
+ groups.set(block, current);
1302
1632
  current = void 0;
1303
1633
  }
1304
1634
  }
1305
1635
  return groups;
1306
1636
  }
1307
1637
  /**
1638
+ * Extracts every `## Surface` or `## Methods` table row whose first cell carries no code span.
1639
+ * {@link extractSurface} and {@link extractMethods} skip such a row, because a row with no
1640
+ * name gives them nothing to key a symbol or a member on, and this projection is what reports
1641
+ * the skip. Each entry is the row's cells read through {@link extractCellText} and joined
1642
+ * by ` | `, so a reader can locate the row in the guide; the `## Surface` rows come first,
1643
+ * then the `## Methods` rows, each in document order. {@link GuideInterface.unnamed} caches it.
1644
+ *
1645
+ * @param document - The parsed guide document
1646
+ * @returns One entry per row carrying no code-span name
1647
+ *
1648
+ * @example
1649
+ * ```ts
1650
+ * extractUnnamed(document) // ['Widget | class | Represents a widget.']
1651
+ * ```
1652
+ */
1653
+ function extractUnnamed(document) {
1654
+ const unnamed = [];
1655
+ for (const heading of [SURFACE, METHODS]) for (const block of selectSectionBlocks(document, heading)) {
1656
+ if (!isTableNode(block)) continue;
1657
+ for (const row of block.rows) {
1658
+ const cell = row[0];
1659
+ if (cell !== void 0 && findFirstCode(cell) !== void 0) continue;
1660
+ unnamed.push(row.map((content) => extractCellText(content)).join(" | "));
1661
+ }
1662
+ }
1663
+ return unnamed;
1664
+ }
1665
+ /**
1308
1666
  * Extracts every link href in the guide document, including table cells — a full,
1309
1667
  * depth-first walk of the whole AST.
1310
1668
  *
@@ -1339,38 +1697,230 @@ function extractTests(document) {
1339
1697
  return links;
1340
1698
  }
1341
1699
  /**
1342
- * Selects the next physical record after an eligible genuine JSDoc whose final
1343
- * authoritative span carries an exact block-position `@example` tag. Title
1344
- * text is allowed. A leading whitespace-separated span chain is last-span
1345
- * authoritative; intervening source material severs association, while a
1346
- * leading JSDoc on the next record replaces pending state. Any other next
1347
- * physical record is returned once and consumes it. This parser walks aligned
1348
- * records without rescanning source syntax or applying declaration/member
1349
- * grammar.
1700
+ * Returns the canonical body of one genuine JSDoc span — the `/**` opener, the closing
1701
+ * marker, each line's continuation marker, and the block's leading indentation removed,
1702
+ * with per-line trailing whitespace trimmed and the surrounding blank lines dropped. A
1703
+ * line's own indentation beyond the marker is kept, so an `@example` fence body keeps the
1704
+ * shape it was written in.
1705
+ *
1706
+ * @param comment - One complete genuine JSDoc span's raw text
1707
+ * @returns The span's unwrapped body
1708
+ *
1709
+ * @example
1710
+ * ```ts
1711
+ * normalizeComment('/**' + ' Creates a widget. *' + '/') // 'Creates a widget.'
1712
+ * ```
1713
+ */
1714
+ function normalizeComment(comment) {
1715
+ return unwrapComment(comment).join("\n").replace(/^\n+/, "").replace(/\n+$/, "");
1716
+ }
1717
+ /**
1718
+ * Unwraps one genuine JSDoc span into one content line per physical line — the `/**` opener,
1719
+ * the closing marker, each line's continuation marker, and per-line trailing whitespace removed,
1720
+ * with a line's own indentation past the marker kept. The result is aligned with
1721
+ * `comment.split('\n')`, so an index found in it addresses the same physical line of the span it
1722
+ * was built from, which is what lets a rewrite keep every line it does not replace.
1723
+ * {@link normalizeComment} is this projection joined and trimmed at its ends.
1724
+ *
1725
+ * @param comment - One complete genuine JSDoc span's raw text
1726
+ * @returns One content line per physical line of the span
1727
+ *
1728
+ * @example
1729
+ * ```ts
1730
+ * unwrapComment('/**' + '\n * Walks.\n *' + '/') // ['', 'Walks.', '']
1731
+ * ```
1732
+ */
1733
+ function unwrapComment(comment) {
1734
+ return (/^[ \t]*\/\*([\s\S]*?)\*\/[ \t]*$/.exec(comment)?.[1] ?? comment).split("\n").map((line) => line.replace(/^[ \t]*\*[ \t]?/, "").replace(/[ \t]+$/, ""));
1735
+ }
1736
+ /**
1737
+ * Returns the canonical compared form of a description paragraph. `{@link Target}` and
1738
+ * `{@link Target | label}` become the code token of the target text, or of the label where one is
1739
+ * written; a target's module part — the inline import form `import('./module.js').` and TSDoc's
1740
+ * package-qualified form `@scope/pkg#` — is dropped first. Every run of whitespace, including a
1741
+ * collapsed continuation marker and a line break, becomes one space, the ends trim, and a code
1742
+ * span keeps its delimiters while its own boundary whitespace goes. The guide's side and the
1743
+ * source's side read through this one form.
1744
+ *
1745
+ * @remarks
1746
+ * The clauses land in a fixed order, because each one decides what the next one sees. Every
1747
+ * single-backtick code span — one backtick per side, no inner backtick, no adjacent backtick —
1748
+ * is located first, so a delimiter the `{@link}` expansion inserts afterwards is never mistaken
1749
+ * for an authored one. The expansion then runs outside those spans
1750
+ * only, so a `{@link}` written inside a code span stays literal on both sides. Whitespace
1751
+ * collapses next, which is what makes a span wrapped across two physical lines comparable at
1752
+ * all. The boundary trim runs last, inside each located span: the markdown parser strips one
1753
+ * space from each end of a code span it reads, and this trim is the symmetric rule that meets
1754
+ * it, so `` ` | ` ``, `` ` |` ``, and `` `|` `` all reach `` `|` `` from either side. A span
1755
+ * whose content is all whitespace keeps one space, because a parser strips nothing from that
1756
+ * one.
1757
+ *
1758
+ * A target's module part is the inline import form `import('./module.js').` or TSDoc's
1759
+ * package-qualified form `@scope/pkg#`, and the expansion drops it, so a cross-file link and the
1760
+ * code token a guide cell documents it with reach the same text. A package qualifier carries `@`
1761
+ * or `/`; text before a `#` carrying neither is JSDoc's member reference, so `{@link Owner#member}`
1762
+ * and `{@link #member}` travel whole and a guide cell documents each as written. An unscoped
1763
+ * package name is spelled like an owner, so `{@link pkg#Name}` travels whole too — write the
1764
+ * scoped or the path form where a cell must drop the package. Everything after a module part
1765
+ * travels: `Owner.member` keeps its owner, and a dotted target no module part precedes is
1766
+ * untouched. A label is text rather than a target, so `{@link Target | label}` renders its label
1767
+ * whole.
1768
+ *
1769
+ * A code span delimited by more than one backtick is outside the compared form's representable
1770
+ * set and travels untouched, as does a code span whose own text carries a backtick: the form
1771
+ * spells every span with one backtick per side, so neither can be written back. A summary that
1772
+ * needs one of those constructs takes another shape: name the construct in prose rather than
1773
+ * expecting the comparison to converge it.
1774
+ *
1775
+ * @param text - A doc block's description paragraph, or a guide cell's flattened text
1776
+ * @returns The compared form of that text
1777
+ *
1778
+ * @example
1779
+ * ```ts
1780
+ * normalizeSummary('Creates a\n{@link Widget}.') // 'Creates a `Widget`.'
1781
+ * normalizeSummary("Reads {@link import('./widgets.js').Widget}.") // 'Reads `Widget`.'
1782
+ * normalizeSummary('Reads {@link @scope/widgets#Widget}.') // 'Reads `Widget`.'
1783
+ * normalizeSummary('Reads {@link Widget#render}.') // 'Reads `Widget#render`.'
1784
+ * normalizeSummary('cells joined by ` | `.') // 'cells joined by `|`.'
1785
+ * ```
1786
+ */
1787
+ function normalizeSummary(text) {
1788
+ const parts = text.split(/((?<!`)`[^`]+`(?!`))/);
1789
+ let normalized = "";
1790
+ for (let index = 0; index < parts.length; index += 1) {
1791
+ const part = parts[index] ?? "";
1792
+ if (index % 2 === 0) {
1793
+ normalized += part.replace(/\{@link\s+[^}|]*\|\s*([^}]*?)\s*\}/g, "`$1`").replace(/\{@link\s+(?:import\([^)]*\)\.|[^}|#\s]*[@/][^}|#\s]*#)?([^}|]*?)\s*\}/g, "`$1`");
1794
+ continue;
1795
+ }
1796
+ const value = part.slice(1, -1).replace(/\s+/g, " ").trim();
1797
+ normalized += `\`${value.length === 0 ? " " : value}\``;
1798
+ }
1799
+ return normalized.replace(/\s+/g, " ").trim();
1800
+ }
1801
+ /**
1802
+ * Wraps one paragraph into greedy lines no longer than `width` characters. Every run of
1803
+ * whitespace separates words, and a word longer than `width` takes its own line rather than
1804
+ * being split, so a long code token or URL survives the wrap intact.
1805
+ *
1806
+ * @param text - The paragraph to wrap
1807
+ * @param width - The greatest length a returned line may reach
1808
+ * @returns The wrapped lines, in order, or an empty list when `text` carries no word
1809
+ *
1810
+ * @example
1811
+ * ```ts
1812
+ * wrapText('one two three', 8) // ['one two', 'three']
1813
+ * ```
1814
+ */
1815
+ function wrapText(text, width) {
1816
+ const lines = [];
1817
+ let current = "";
1818
+ for (const word of text.split(/\s+/)) {
1819
+ if (word.length === 0) continue;
1820
+ if (current.length === 0) current = word;
1821
+ else if (current.length + 1 + word.length <= width) current += ` ${word}`;
1822
+ else {
1823
+ lines.push(current);
1824
+ current = word;
1825
+ }
1826
+ }
1827
+ if (current.length > 0) lines.push(current);
1828
+ return lines;
1829
+ }
1830
+ /**
1831
+ * Builds one genuine JSDoc span from its content lines — the inverse of {@link unwrapComment}.
1832
+ * Each line is emitted at `indent` behind a continuation marker, an empty line as the bare
1833
+ * marker so no line carries trailing whitespace, and the leading and trailing empty lines are
1834
+ * dropped because the opener and the closer take those physical lines.
1835
+ *
1836
+ * @param lines - The span's content lines, as {@link unwrapComment} returns them
1837
+ * @param indent - The whitespace the span opens at
1838
+ * @returns The span's raw text, opener and closer included
1839
+ *
1840
+ * @example
1841
+ * ```ts
1842
+ * buildComment(['Walks.'], '') // '/**\n * Walks.\n *' + '/'
1843
+ * ```
1844
+ */
1845
+ function buildComment(lines, indent) {
1846
+ const content = [...lines];
1847
+ while (content[0] === "") content.shift();
1848
+ while (content[content.length - 1] === "") content.pop();
1849
+ const raw = [`${indent}/**`];
1850
+ for (const line of content) raw.push(line.length === 0 ? `${indent} *` : `${indent} * ${line}`);
1851
+ raw.push(`${indent} */`);
1852
+ return raw.join("\n");
1853
+ }
1854
+ /**
1855
+ * Returns one doc block's unwrapped text with every fenced body replaced by aligned spaces,
1856
+ * so a tag search reads the block's structure and never its example code. A line opening with
1857
+ * three or more backticks or tildes opens a body, the first line opening with a run of the same
1858
+ * character at least as long closes it, an unclosed body runs to the end, and the marker lines
1859
+ * themselves stay. The projection preserves every line and every column, so an index found in
1860
+ * it addresses the same character of the text it was built from.
1861
+ *
1862
+ * @param text - One doc block's unwrapped text, as {@link normalizeComment} returns it
1863
+ * @returns The same text with each fenced body's characters replaced by spaces
1864
+ *
1865
+ * @example
1866
+ * ```ts
1867
+ * maskFences('@example\n~~~\n@decorator()\n~~~').split('\n')[2] // ' '
1868
+ * ```
1869
+ */
1870
+ function maskFences(text) {
1871
+ const masked = [];
1872
+ let marker;
1873
+ for (const line of text.split("\n")) {
1874
+ const fence = /^[ \t]*(`{3,}|~{3,})/.exec(line)?.[1];
1875
+ if (marker === void 0) {
1876
+ masked.push(line);
1877
+ marker = fence;
1878
+ continue;
1879
+ }
1880
+ const closing = fence !== void 0 && fence.startsWith(marker);
1881
+ masked.push(closing ? line : " ".repeat(line.length));
1882
+ if (closing) marker = void 0;
1883
+ }
1884
+ return masked.join("\n");
1885
+ }
1886
+ /**
1887
+ * Extracts every eligible genuine JSDoc block paired with the physical record it documents.
1888
+ *
1889
+ * @remarks
1890
+ * An opener is eligible only when it is the first non-whitespace source material of its record; a
1891
+ * leading whitespace-separated span chain is last-span authoritative; intervening source material
1892
+ * severs association, while a leading JSDoc on the next record replaces pending state. Any other
1893
+ * next physical record is returned once and consumes it. This parser walks aligned records without
1894
+ * rescanning source syntax or applying declaration/member grammar, and every reader of a doc
1895
+ * block's text — the description paragraph, the `@example` blocks, the member summaries — reads it
1896
+ * through this one walk.
1350
1897
  *
1351
1898
  * @param lines - Aligned physical source-line records
1352
- * @returns The immediately following candidate lines, in source order
1899
+ * @returns One record per documented physical line, in source order
1353
1900
  *
1354
1901
  * @example
1355
1902
  * ```ts
1356
- * extractExampleLines(extractSourceLines('/** @example *' + '/\nexport function walk() {}'))
1357
- * // the `export function walk() {}` SourceLine
1903
+ * extractSourceComments(extractSourceLines('/**' + ' Walks. *' + '/\nexport function walk() {}'))
1904
+ * // [{ text: 'Walks.', line: the `export function walk() {}` SourceLine }]
1358
1905
  * ```
1359
1906
  */
1360
- function extractExampleLines(lines) {
1361
- const examples = [];
1907
+ function extractSourceComments(lines) {
1908
+ const comments = [];
1362
1909
  let block = false;
1363
1910
  let eligible = false;
1364
- let example = false;
1365
- let pending = false;
1911
+ let span = [];
1912
+ let pending;
1366
1913
  for (const line of lines) {
1367
1914
  const projection = line.jsdoc;
1368
1915
  const first = projection?.indexOf("/**") ?? -1;
1369
- if (pending) {
1370
- if (!block && first >= 0 && line.source.slice(0, first).trim() === "") pending = false;
1916
+ if (pending !== void 0) {
1917
+ if (!block && first >= 0 && line.source.slice(0, first).trim() === "") pending = void 0;
1371
1918
  else {
1372
- examples.push(line);
1373
- pending = false;
1919
+ comments.push({
1920
+ text: pending,
1921
+ line
1922
+ });
1923
+ pending = void 0;
1374
1924
  }
1375
1925
  }
1376
1926
  if (projection === void 0) continue;
@@ -1378,29 +1928,29 @@ function extractExampleLines(lines) {
1378
1928
  if (block) {
1379
1929
  const close = projection.indexOf("*/");
1380
1930
  const end = close < 0 ? projection.length : close + 2;
1381
- if (eligible && /^\s*\*?\s*@example(?=\s|\*\/|$)/.test(projection.slice(0, end))) example = true;
1931
+ span.push(projection.slice(0, end));
1382
1932
  if (close < 0) continue;
1383
1933
  block = false;
1384
1934
  const opener = projection.indexOf("/**", close + 2);
1385
1935
  const endOfGap = opener < 0 ? line.source.length : opener;
1386
1936
  const whitespace = line.source.slice(close + 2, endOfGap).trim() === "";
1387
1937
  if (opener < 0) {
1388
- pending = eligible && example && whitespace;
1938
+ pending = eligible && whitespace ? normalizeComment(span.join("\n")) : void 0;
1389
1939
  continue;
1390
1940
  }
1391
1941
  eligible = eligible && whitespace;
1392
- example = false;
1942
+ span = [];
1393
1943
  cursor = opener;
1394
1944
  } else {
1395
1945
  if (first < 0) continue;
1396
1946
  eligible = line.source.slice(0, first).trim() === "";
1397
- example = false;
1947
+ span = [];
1398
1948
  cursor = first;
1399
1949
  }
1400
1950
  while (cursor < projection.length) {
1401
1951
  const close = projection.indexOf("*/", cursor + 2);
1402
1952
  const end = close < 0 ? projection.length : close + 2;
1403
- if (eligible && /^\s*\*?\s*@example(?=\s|\*\/|$)/.test(projection.slice(cursor + 3, end))) example = true;
1953
+ span.push(projection.slice(cursor, end));
1404
1954
  if (close < 0) {
1405
1955
  block = true;
1406
1956
  break;
@@ -1409,93 +1959,1025 @@ function extractExampleLines(lines) {
1409
1959
  const endOfGap = opener < 0 ? line.source.length : opener;
1410
1960
  const whitespace = line.source.slice(close + 2, endOfGap).trim() === "";
1411
1961
  if (opener < 0) {
1412
- pending = eligible && example && whitespace;
1962
+ pending = eligible && whitespace ? normalizeComment(span.join("\n")) : void 0;
1413
1963
  break;
1414
1964
  }
1415
1965
  eligible = eligible && whitespace;
1416
- example = false;
1966
+ span = [];
1417
1967
  cursor = opener;
1418
1968
  }
1419
1969
  }
1420
- return examples;
1970
+ return comments;
1421
1971
  }
1422
1972
  /**
1423
- * Extracts the exported functions in one file's source text whose immediately preceding
1424
- * eligible genuine JSDoc block carries `@example`. Shared adjacency comes from
1425
- * {@link extractExampleLines}; exported-function membership is matched against
1426
- * the aligned code projection, so comment and template payload cannot qualify.
1973
+ * Selects the next physical record after an eligible genuine JSDoc whose final
1974
+ * authoritative span carries an `@example` tag opening a line at its first non-blank column —
1975
+ * the {@link extractSourceComments} walk filtered to the blocks that carry one. Title
1976
+ * text is allowed, and {@link maskFences} keeps a fenced body's own lines out of the search.
1427
1977
  *
1428
- * @param source - The file's source text
1429
- * @returns The exported function names with an `@example`, in file order
1978
+ * @param lines - Aligned physical source-line records
1979
+ * @returns The immediately following candidate lines, in source order
1430
1980
  *
1431
1981
  * @example
1432
1982
  * ```ts
1433
- * const block = ['/**', ' * @example', ' *' + '/', 'export function walk() {}', ''].join('\n')
1434
- * extractExamples(block) // ['walk']
1435
- * extractExamples('export function walk() {}\n') // []
1983
+ * extractExampleLines(extractSourceLines('/**' + ' @example *' + '/\nexport function walk() {}'))
1984
+ * // the `export function walk() {}` SourceLine
1436
1985
  * ```
1437
1986
  */
1438
- function extractExamples(source) {
1439
- const names = [];
1440
- const seen = /* @__PURE__ */ new Set();
1441
- for (const line of extractExampleLines(extractSourceLines(source))) {
1442
- const name = line.code.match(/^export (?:async )?function\*? (\w+)/)?.[1];
1443
- if (isNonEmptyString(name) && !seen.has(name)) {
1444
- seen.add(name);
1445
- names.push(name);
1446
- }
1447
- }
1448
- return names;
1987
+ function extractExampleLines(lines) {
1988
+ return extractSourceComments(lines).filter((comment) => /^[ \t]*@example(?=[ \t]|$)/m.test(maskFences(comment.text))).map((comment) => comment.line);
1449
1989
  }
1450
1990
  /**
1451
- * Extracts the callable-member names in a declaration body (per {@link extractMemberMethods}'
1452
- * grammar) whose immediately preceding eligible genuine JSDoc block, within
1453
- * the same body, carries `@example`. Shared adjacency comes from
1454
- * {@link extractExampleLines}; member membership is matched against aligned
1455
- * projected code.
1991
+ * Collects the description paragraph of every documented physical record — a doc block's
1992
+ * text before its first block tag, in {@link normalizeSummary}'s compared form — keyed by the
1993
+ * record it documents. A record whose block carries no description contributes no entry, so
1994
+ * an absent summary stays absent rather than becoming an empty string.
1456
1995
  *
1457
- * @param lines - A declaration's body lines
1458
- * @returns The exemplified member names, deduped and sorted
1996
+ * @param lines - Aligned physical source-line records
1997
+ * @returns One entry per documented record carrying a description paragraph
1459
1998
  *
1460
1999
  * @example
1461
2000
  * ```ts
1462
- * extractExampleMethods(['\t/**', '\t * @example', '\t *' + '/', '\twalk(): void']) // ['walk']
2001
+ * collectSummaries(extractSourceLines('/**' + ' Walks. *' + '/\nexport function walk() {}')).size // 1
1463
2002
  * ```
1464
2003
  */
1465
- function extractExampleMethods(lines) {
1466
- const methods = [];
1467
- const seen = /* @__PURE__ */ new Set();
1468
- for (const line of extractExampleLines(extractSourceLines(lines.join("\n")))) {
1469
- const name = line.code.match(/^\t(?:async )?\*?(\w+)\??(<.*>)?\(/)?.[1];
1470
- if (isNonEmptyString(name) && !seen.has(name)) {
1471
- seen.add(name);
1472
- methods.push(name);
1473
- }
2004
+ function collectSummaries(lines) {
2005
+ const summaries = /* @__PURE__ */ new Map();
2006
+ for (const comment of extractSourceComments(lines)) {
2007
+ const tag = maskFences(comment.text).search(/^[ \t]*@\w/m);
2008
+ const summary = normalizeSummary(tag < 0 ? comment.text : comment.text.slice(0, tag));
2009
+ if (summary.length > 0) summaries.set(comment.line, summary);
1474
2010
  }
1475
- return Array.from(new Set(methods)).sort();
2011
+ return summaries;
1476
2012
  }
1477
2013
  /**
1478
- * Extracts every fenced code block anywhere in the guide document. A full AST walk
1479
- * includes fences nested inside blockquotes and lists.
2014
+ * Extracts the aligned physical records of a declaration's body, read inside an owner head this
2015
+ * function supplies, so a callable member in the body carries the `Owner.member` key
2016
+ * {@link collectKeys} reports for it, and that head's own record opens the projection. A body
2017
+ * read on its own carries no head, and the member grammar attaches a member to the head
2018
+ * enclosing it.
1480
2019
  *
1481
- * @param document - The parsed guide document
1482
- * @returns Every fence's language and verbatim code, in document order
2020
+ * @remarks
2021
+ * The supplied head is an `export interface` line, so the projection opens with that head's own
2022
+ * record and every body line follows it in order. A column-zero `}` among the body lines closes
2023
+ * the supplied head and leaves every later member unkeyed; a body {@link extractDeclaration}
2024
+ * returns carries none, because that reader ends a body at the first one.
2025
+ *
2026
+ * @param lines - A declaration's body lines
2027
+ * @returns The supplied head's record, then one record per body line
1483
2028
  *
1484
2029
  * @example
1485
2030
  * ```ts
1486
- * extractFences(document) // [{ language: 'ts', code: "import { X } from './x.js'\nX()" }]
2031
+ * extractBodyLines(['\twalk(): void'])[1]?.code // '\twalk(): void'
1487
2032
  * ```
1488
2033
  */
1489
- function extractFences(document) {
1490
- const fences = [];
1491
- for (const node of walkNodes(document)) if (isCodeBlockNode(node)) fences.push({
1492
- language: node.lang,
1493
- code: node.code
1494
- });
1495
- return fences;
2034
+ function extractBodyLines(lines) {
2035
+ return extractSourceLines(["export interface Owner {", ...lines].join("\n"));
1496
2036
  }
1497
- //#endregion
1498
- //#region src/core/parsers.ts
2037
+ /**
2038
+ * Collects the compared key of every physical record a key names — a {@link computeSymbolKey}
2039
+ * symbol key for a column-zero `export` declaration head, an `Owner.member` key for a one-tab
2040
+ * callable member inside one — keyed by the record itself. The owner closes at the first
2041
+ * column-zero `}` or at a column-zero `export` declaration carrying another keyword, and a
2042
+ * record no key names contributes no entry.
2043
+ *
2044
+ * @remarks
2045
+ * This is the package's one key grammar, and each keyed reader projects its own part back out of
2046
+ * it: {@link extractExports} splits a declaration key at its one space,
2047
+ * {@link extractMemberMethods} and {@link extractExampleMethods} split a member key at its dot,
2048
+ * and {@link locateComment} matches a caller's key against the whole map. A change to the head
2049
+ * shape or to the member shape reaches every one of them at once.
2050
+ *
2051
+ * An owner opens at a column-zero `export class`, `export abstract class`, or `export interface`
2052
+ * head and closes at the
2053
+ * first column-zero `}`, so a member declared past that brace keys nothing. A column-zero `export` declaration carrying any other keyword closes the owner it follows,
2054
+ * because a member belongs to the head enclosing it. Reading runs over {@link extractSourceLines}'s
2055
+ * projection, so a head or
2056
+ * a member written inside a comment or a template literal keys nothing.
2057
+ *
2058
+ * @param lines - Aligned physical source-line records
2059
+ * @returns One entry per record a key names, in file order
2060
+ *
2061
+ * @example
2062
+ * ```ts
2063
+ * const keys = collectKeys(extractSourceLines('export class Widget {\n\twalk(): void\n}'))
2064
+ * Array.from(keys.values()) // ['class Widget', 'Widget.walk']
2065
+ * ```
2066
+ */
2067
+ function collectKeys(lines) {
2068
+ const keys = /* @__PURE__ */ new Map();
2069
+ let owner;
2070
+ for (const line of lines) {
2071
+ const head = /^export (?:async )?(?:abstract )?(function\*?|class|const|interface|type) (\w+)/.exec(line.code);
2072
+ const keyword = head?.[1]?.replace(/\*$/, "");
2073
+ const name = head?.[2];
2074
+ if (isNonEmptyString(keyword) && isNonEmptyString(name) && isExportKeyword(keyword)) {
2075
+ keys.set(line, computeSymbolKey({
2076
+ name,
2077
+ keyword
2078
+ }));
2079
+ owner = keyword === "class" || keyword === "interface" ? name : void 0;
2080
+ continue;
2081
+ }
2082
+ if (line.code === "}") {
2083
+ owner = void 0;
2084
+ continue;
2085
+ }
2086
+ const member = /^\t(?:async )?\*?(\w+)\??(?:<.*>)?\(/.exec(line.code)?.[1];
2087
+ if (owner !== void 0 && isNonEmptyString(member)) keys.set(line, `${owner}.${member}`);
2088
+ }
2089
+ return keys;
2090
+ }
2091
+ /**
2092
+ * Collects the `@example` blocks one doc block's unwrapped text carries, each named for the
2093
+ * declaration or member the block documents. The text after the tag becomes the block's
2094
+ * `title`; a body opening with a fence contributes that fence's language and its verbatim
2095
+ * body, and a body with no fence contributes its own trimmed text as the code.
2096
+ *
2097
+ * @param comment - One doc block's unwrapped text, as {@link normalizeComment} returns it
2098
+ * @param name - The declaration or member the block documents
2099
+ * @returns The block's `@example` entries, in block order
2100
+ *
2101
+ * @example
2102
+ * ```ts
2103
+ * collectExamples('@example Walking\n```ts\nwalk()\n```', 'walk')
2104
+ * // [{ name: 'walk', title: 'Walking', code: 'walk()', language: 'ts' }]
2105
+ * ```
2106
+ */
2107
+ function collectExamples(comment, name) {
2108
+ const examples = [];
2109
+ const masked = maskFences(comment);
2110
+ const tags = /^[ \t]*@example(?=[ \t]|$)[ \t]*(.*)$/gm;
2111
+ let tag;
2112
+ while ((tag = tags.exec(masked)) !== null) {
2113
+ const title = (tag[1] ?? "").trim();
2114
+ const start = tag.index + tag[0].length;
2115
+ const rest = comment.slice(start).replace(/^\n/, "");
2116
+ const next = masked.slice(start).replace(/^\n/, "").search(/^[ \t]*@\w+/m);
2117
+ const body = (next < 0 ? rest : rest.slice(0, next)).replace(/^\n+/, "").replace(/\n+$/, "");
2118
+ const fence = /^```(\S*)\n([\s\S]*?)\n?```/.exec(body);
2119
+ const language = fence?.[1] ?? "";
2120
+ const code = fence?.[2] ?? body;
2121
+ examples.push({
2122
+ name,
2123
+ ...title.length === 0 ? {} : { title },
2124
+ code,
2125
+ ...language.length === 0 ? {} : { language }
2126
+ });
2127
+ }
2128
+ return examples;
2129
+ }
2130
+ /**
2131
+ * Extracts the `@example` blocks carried by the exported declaration heads in one file's source
2132
+ * text, each named for the declaration its block documents. Shared adjacency comes from
2133
+ * {@link extractSourceComments} and each block is read by {@link collectExamples}; head
2134
+ * membership is the {@link collectKeys} key of the documented record under every keyword that
2135
+ * grammar admits at column zero, so comment and template payload cannot qualify and the head
2136
+ * grammar stays the one every reader here shares. A member key carries a dot and a head key
2137
+ * does not, so a member's block belongs to {@link extractExampleMethods} instead. A head
2138
+ * carrying several blocks contributes each.
2139
+ *
2140
+ * @param source - The file's source text
2141
+ * @returns The exported declaration heads' `@example` blocks, in file order, deduplicated by name and title
2142
+ *
2143
+ * @example
2144
+ * ```ts
2145
+ * const block = ['/**', ' * @example', ' * new Widget()', ' *' + '/', 'export class Widget {}', ''].join('\n')
2146
+ * extractExamples(block) // [{ name: 'Widget', code: 'new Widget()' }]
2147
+ * extractExamples('export class Widget {}\n') // []
2148
+ * ```
2149
+ */
2150
+ function extractExamples(source) {
2151
+ const examples = [];
2152
+ const seen = /* @__PURE__ */ new Set();
2153
+ const lines = extractSourceLines(source);
2154
+ const keys = collectKeys(lines);
2155
+ for (const comment of extractSourceComments(lines)) {
2156
+ const key = keys.get(comment.line);
2157
+ if (key === void 0 || key.includes(".")) continue;
2158
+ const name = key.slice(key.indexOf(" ") + 1);
2159
+ for (const example of collectExamples(comment.text, name)) {
2160
+ const entry = `${name}\n${example.title ?? ""}`;
2161
+ if (seen.has(entry)) continue;
2162
+ seen.add(entry);
2163
+ examples.push(example);
2164
+ }
2165
+ }
2166
+ return examples;
2167
+ }
2168
+ /**
2169
+ * Extracts the `@example` blocks carried by the callable members of a declaration body (per
2170
+ * {@link collectKeys}' grammar, the same one {@link extractMemberMethods} reads), each named for
2171
+ * the member its block documents. Shared adjacency comes from {@link extractSourceComments} and
2172
+ * each block is read by {@link collectExamples}; member membership is the key
2173
+ * {@link extractBodyLines}'s projection gives the documented record.
2174
+ *
2175
+ * @param lines - A declaration's body lines
2176
+ * @returns The members' `@example` blocks, deduplicated by name and title and sorted by name
2177
+ *
2178
+ * @example
2179
+ * ```ts
2180
+ * extractExampleMethods(['\t/**', '\t * @example', '\t * walk()', '\t *' + '/', '\twalk(): void'])
2181
+ * // [{ name: 'walk', code: 'walk()' }]
2182
+ * ```
2183
+ */
2184
+ function extractExampleMethods(lines) {
2185
+ const examples = [];
2186
+ const seen = /* @__PURE__ */ new Set();
2187
+ const projected = extractBodyLines(lines);
2188
+ const keys = collectKeys(projected);
2189
+ for (const comment of extractSourceComments(projected)) {
2190
+ const key = keys.get(comment.line) ?? "";
2191
+ const dot = key.indexOf(".");
2192
+ if (dot < 0) continue;
2193
+ const name = key.slice(dot + 1);
2194
+ for (const example of collectExamples(comment.text, name)) {
2195
+ const entry = `${name}\n${example.title ?? ""}`;
2196
+ if (seen.has(entry)) continue;
2197
+ seen.add(entry);
2198
+ examples.push(example);
2199
+ }
2200
+ }
2201
+ return examples.sort((a, b) => a.name === b.name ? 0 : a.name < b.name ? -1 : 1);
2202
+ }
2203
+ /**
2204
+ * Extracts every fenced code block anywhere in the guide document. A full AST walk
2205
+ * includes fences nested inside blockquotes and lists, and the same walk carries each
2206
+ * fence's nearest preceding heading as its `title` — the key an `@example` block pairs on.
2207
+ * A heading's text is flattened, so a title written with a code span pairs with a plain
2208
+ * `@example` title.
2209
+ *
2210
+ * @param document - The parsed guide document
2211
+ * @returns Every fence's language, verbatim code, and title, in document order
2212
+ *
2213
+ * @example
2214
+ * ```ts
2215
+ * extractFences(document) // [{ language: 'ts', code: "import { X } from './x.js'\nX()" }]
2216
+ * ```
2217
+ */
2218
+ function extractFences(document) {
2219
+ return Array.from(collectFences(document).values());
2220
+ }
2221
+ /**
2222
+ * Collects each fenced code block keyed by its own node, paired with the {@link GuideFence}
2223
+ * {@link extractFences} reports for it — the node-addressed form a rewrite needs, so a caller
2224
+ * that located a fence by title can read that node's source region back from the parser. The map
2225
+ * iterates in document order and a node keys itself, so a repeated identical fence keeps its own
2226
+ * entry.
2227
+ *
2228
+ * @param document - The parsed guide document
2229
+ * @returns One entry per fenced code block, in document order
2230
+ *
2231
+ * @example
2232
+ * ```ts
2233
+ * Array.from(collectFences(document).values()) // [{ language: 'ts', code: 'walk()' }]
2234
+ * ```
2235
+ */
2236
+ function collectFences(document) {
2237
+ const fences = /* @__PURE__ */ new Map();
2238
+ let title = "";
2239
+ for (const node of walkNodes(document)) {
2240
+ if (isHeadingNode(node)) {
2241
+ title = flattenText(node).trim();
2242
+ continue;
2243
+ }
2244
+ if (isCodeBlockNode(node)) fences.set(node, {
2245
+ language: node.lang,
2246
+ code: node.code,
2247
+ ...title.length === 0 ? {} : { title }
2248
+ });
2249
+ }
2250
+ return fences;
2251
+ }
2252
+ /**
2253
+ * Extracts the guide's tagline — the text of the blockquote following the document's H1,
2254
+ * with every code span kept as a code span and whitespace collapsed. A heading before the
2255
+ * blockquote ends the window, so a blockquote elsewhere in the document is not the tagline.
2256
+ *
2257
+ * @param document - The parsed guide document
2258
+ * @returns The tagline, or `undefined` when no blockquote follows an H1 before the next heading
2259
+ *
2260
+ * @example
2261
+ * ```ts
2262
+ * extractTagline(document) // 'A pure, I/O-free guides-parity toolkit'
2263
+ * ```
2264
+ */
2265
+ function extractTagline(document) {
2266
+ let opened = false;
2267
+ for (const block of document.children) {
2268
+ if (isHeadingNode(block)) {
2269
+ if (opened) return void 0;
2270
+ opened = block.level === 1;
2271
+ continue;
2272
+ }
2273
+ if (!opened || !isBlockquoteNode(block)) continue;
2274
+ const text = normalizeSummary(block.children.filter(isParagraphNode).map((paragraph) => extractCellText(paragraph.children)).join(" "));
2275
+ return text.length === 0 ? void 0 : text;
2276
+ }
2277
+ }
2278
+ /**
2279
+ * Computes the drift between one compared key's guide text and source text. A pair agrees
2280
+ * only when both sides carry the same text, and every other state is a drift: guide text
2281
+ * alone reports the guide's side, source text alone reports the source's, and neither side
2282
+ * carrying text reports the key by itself. A side carrying no text is absent from the result,
2283
+ * so a documented symbol with no doc block reports as a drift naming the guide's text alone,
2284
+ * and a row a table has no `Summary` column for against a declaration with no doc block
2285
+ * reports as `{ key }`.
2286
+ *
2287
+ * @param key - The compared pair's key
2288
+ * @param category - The compared site the drift came from
2289
+ * @param guide - The guide's text there, or `undefined` when it carries none
2290
+ * @param source - The source's text there, or `undefined` when it carries none
2291
+ * @returns The drift, or `undefined` when both sides carry the same text
2292
+ *
2293
+ * @example
2294
+ * ```ts
2295
+ * computeDrift('function walk', 'summary', 'Walks the tree.', 'Walks a tree.')
2296
+ * // { key: 'function walk', category: 'summary', guide: 'Walks the tree.', source: 'Walks a tree.' }
2297
+ * ```
2298
+ */
2299
+ function computeDrift(key, category, guide, source) {
2300
+ if (guide !== void 0 && guide === source) return void 0;
2301
+ return {
2302
+ key,
2303
+ category,
2304
+ ...guide === void 0 ? {} : { guide },
2305
+ ...source === void 0 ? {} : { source }
2306
+ };
2307
+ }
2308
+ /**
2309
+ * Compares documented and declared membership exactly after sorting copies, preserving duplicates.
2310
+ *
2311
+ * @param spec - The guide inventory key the finding belongs to
2312
+ * @param name - The declaration whose membership is compared
2313
+ * @param documented - The documented member names
2314
+ * @param declared - The declared member names
2315
+ * @returns The membership finding, or `undefined` when the sorted populations match
2316
+ *
2317
+ * @example Compare declaration membership
2318
+ * ```ts
2319
+ * import { compareMembership } from '@orkestrel/guide'
2320
+ *
2321
+ * compareMembership('guides/widget.md', 'WidgetInterface', ['open'], ['open']) // undefined
2322
+ * ```
2323
+ */
2324
+ function compareMembership(spec, name, documented, declared) {
2325
+ const left = [...documented].sort();
2326
+ const right = [...declared].sort();
2327
+ if (JSON.stringify(left) === JSON.stringify(right)) return void 0;
2328
+ return {
2329
+ spec,
2330
+ text: `${spec} ${name} documents ${JSON.stringify(left)} and declares ${JSON.stringify(right)}.`
2331
+ };
2332
+ }
2333
+ /**
2334
+ * Computes a category-separated identity for a guide finding.
2335
+ *
2336
+ * @param spec - The guide inventory key the drift belongs to
2337
+ * @param drift - The categorized disagreement
2338
+ * @returns The inventory key, category, and compared key separated by line feeds
2339
+ *
2340
+ * @example Identify categorized drift
2341
+ * ```ts
2342
+ * import { identifyDrift } from '@orkestrel/guide'
2343
+ *
2344
+ * identifyDrift('guides/widget.md', { category: 'summary', key: 'function open' })
2345
+ * // 'guides/widget.md\nsummary\nfunction open'
2346
+ * ```
2347
+ */
2348
+ function identifyDrift(spec, drift) {
2349
+ return `${spec}\n${drift.category}\n${drift.key}`;
2350
+ }
2351
+ /**
2352
+ * Formats present parity text as a JSON string and absent text as `absent`.
2353
+ *
2354
+ * @param value - The compared side's text, or `undefined` when absent
2355
+ * @returns The developer-facing side text
2356
+ *
2357
+ * @example Format a parity side
2358
+ * ```ts
2359
+ * import { formatSide } from '@orkestrel/guide'
2360
+ *
2361
+ * formatSide('Walks.') // '"Walks."'
2362
+ * formatSide(undefined) // 'absent'
2363
+ * ```
2364
+ */
2365
+ function formatSide(value) {
2366
+ return value === void 0 ? "absent" : JSON.stringify(value);
2367
+ }
2368
+ /**
2369
+ * Formats a categorized drift with its guide and source sides.
2370
+ *
2371
+ * @param drift - The categorized disagreement to format
2372
+ * @returns The complete developer-facing drift text
2373
+ *
2374
+ * @example Format categorized drift
2375
+ * ```ts
2376
+ * import { formatDrift } from '@orkestrel/guide'
2377
+ *
2378
+ * formatDrift({ category: 'summary', key: 'function walk', guide: 'Walks.', source: 'Walks a tree.' })
2379
+ * // 'summary function walk: guide "Walks." source "Walks a tree."'
2380
+ * ```
2381
+ */
2382
+ function formatDrift(drift) {
2383
+ return `${drift.category} ${drift.key}: guide ${formatSide(drift.guide)} source ${formatSide(drift.source)}`;
2384
+ }
2385
+ /**
2386
+ * Finds every disagreement between a guide and the source it documents, naming both sites:
2387
+ * each `## Surface` row against its declaration's description paragraph, each `## Methods`
2388
+ * row against its member's, and the first titled guide fence of a heading against the
2389
+ * `@example` block of the same title. An example's compared text is its language on the first
2390
+ * line and its body beneath, so a fence that names another language drifts on its own.
2391
+ *
2392
+ * @remarks
2393
+ * Only a pair present on both sides is compared, so a symbol, a member, or a title one side
2394
+ * lacks entirely is left to the bijection checks that own it and is never reported twice.
2395
+ * {@link computeDrift} rules each compared pair, so a pair whose sides carry different text, a
2396
+ * pair where one side carries none, and a pair where neither side carries text are all drift.
2397
+ * The pairing is per title across the whole document, not per heading: the first fence a title
2398
+ * reaches is the compared one, and every later fence of that title is outside the comparison,
2399
+ * whether it sits under the same heading or under a second heading of the same text.
2400
+ *
2401
+ * @param guide - The parsed guide
2402
+ * @param source - The reflected source the guide documents
2403
+ * @returns One entry per disagreement: Surface rows, then Methods rows, then examples
2404
+ *
2405
+ * @example
2406
+ * ```ts
2407
+ * findDrift(guide, source) // [{ key: 'function walk', category: 'summary', guide: 'Walks.', source: 'Walks a tree.' }]
2408
+ * ```
2409
+ */
2410
+ function findDrift(guide, source) {
2411
+ const drifts = [];
2412
+ const declared = new Map(source.surface().map((symbol) => [computeSymbolKey(symbol), symbol]));
2413
+ for (const symbol of guide.surface()) {
2414
+ const key = computeSymbolKey(symbol);
2415
+ const match = declared.get(key);
2416
+ if (match === void 0) continue;
2417
+ const drift = computeDrift(key, "summary", symbol.summary, match.summary);
2418
+ if (drift !== void 0) drifts.push(drift);
2419
+ }
2420
+ for (const group of guide.methods()) {
2421
+ const members = new Map(source.methods(group.interface).map((entry) => [entry.name, entry]));
2422
+ for (const entry of group.methods) {
2423
+ const member = members.get(entry.name);
2424
+ if (member === void 0) continue;
2425
+ const drift = computeDrift(`${group.interface}.${entry.name}`, "summary", entry.summary, member.summary);
2426
+ if (drift !== void 0) drifts.push(drift);
2427
+ }
2428
+ }
2429
+ const examples = collectTitles(guide, source);
2430
+ const compared = /* @__PURE__ */ new Set();
2431
+ for (const fence of guide.fences()) {
2432
+ if (fence.title === void 0 || compared.has(fence.title)) continue;
2433
+ compared.add(fence.title);
2434
+ const example = examples.get(fence.title);
2435
+ if (example === void 0) continue;
2436
+ const drift = computeDrift(fence.title, "example", `${fence.language ?? ""}\n${fence.code}`, `${example.language ?? ""}\n${example.code}`);
2437
+ if (drift !== void 0) drifts.push(drift);
2438
+ }
2439
+ return drifts;
2440
+ }
2441
+ /**
2442
+ * Collects the titled `@example` blocks a guide's documented surface reaches — the module's
2443
+ * exported declaration heads, plus the own members of every documented `class` and `interface` —
2444
+ * keyed by title, the first block of a title answering for it.
2445
+ *
2446
+ * @param guide - The parsed guide naming the documented declarations
2447
+ * @param source - The reflected source to read the blocks from
2448
+ * @returns One entry per distinct `@example` title
2449
+ *
2450
+ * @example
2451
+ * ```ts
2452
+ * collectTitles(guide, source).get('Walk a tree') // { name: 'walk', title: 'Walk a tree', code: 'walk()' }
2453
+ * ```
2454
+ */
2455
+ function collectTitles(guide, source) {
2456
+ const titled = /* @__PURE__ */ new Map();
2457
+ const owners = guide.surface().filter((symbol) => symbol.keyword === "class" || symbol.keyword === "interface");
2458
+ const examples = [...source.examples(), ...owners.flatMap((symbol) => source.examples(symbol.name))];
2459
+ for (const example of examples) {
2460
+ if (example.title === void 0 || titled.has(example.title)) continue;
2461
+ titled.set(example.title, example);
2462
+ }
2463
+ return titled;
2464
+ }
2465
+ /**
2466
+ * Builds a copy of `table` with one cell's inline content rebuilt from `text` through
2467
+ * {@link buildCell}. Every other cell keeps its own nodes, so a rewrite touches the one cell it
2468
+ * names and the header and the alignment row travel unchanged.
2469
+ *
2470
+ * @param table - The table to copy
2471
+ * @param row - The index of the row to rewrite within {@link TableNode.rows}
2472
+ * @param column - The index of the cell to rewrite within that row
2473
+ * @param text - The cell's new compared text
2474
+ * @returns The rewritten table
2475
+ *
2476
+ * @example
2477
+ * ```ts
2478
+ * buildTable(table, 0, 2, 'Walks the tree.').rows[0]?.[2] // [{ element: 'text', value: 'Walks the tree.' }]
2479
+ * ```
2480
+ */
2481
+ function buildTable(table, row, column, text) {
2482
+ return {
2483
+ element: "table",
2484
+ header: table.header,
2485
+ rows: table.rows.map((cells, index) => index === row ? cells.map((cell, position) => position === column ? buildCell(text) : cell) : cells),
2486
+ align: table.align
2487
+ };
2488
+ }
2489
+ /**
2490
+ * Builds the fenced code block one `@example` block renders as — its code inside a fence
2491
+ * carrying its language, and an untagged fence when the block names none.
2492
+ *
2493
+ * @param example - The block to render
2494
+ * @returns The fence node
2495
+ *
2496
+ * @example
2497
+ * ```ts
2498
+ * buildFence({ name: 'walk', code: 'walk()', language: 'ts' }) // { element: 'codeBlock', code: 'walk()', lang: 'ts' }
2499
+ * ```
2500
+ */
2501
+ function buildFence(example) {
2502
+ return {
2503
+ element: "codeBlock",
2504
+ code: example.code,
2505
+ ...example.language === void 0 ? {} : { lang: example.language }
2506
+ };
2507
+ }
2508
+ /**
2509
+ * Splices `replacement` into `source` over the region `span` addresses, and returns the result.
2510
+ * The text before the region and the text after it travel byte for byte, so a rewrite that
2511
+ * addresses one node's region changes nothing else in the document.
2512
+ *
2513
+ * @param source - The text to rewrite
2514
+ * @param span - The half-open region to replace: the region `MarkdownInterface.span` reports
2515
+ * for a markdown node, or the one {@link locateComment} reports for a doc block
2516
+ * @param replacement - The text to write over that region
2517
+ * @returns The rewritten text
2518
+ *
2519
+ * @example
2520
+ * ```ts
2521
+ * spliceSpan('one two three', { start: 4, end: 7 }, 'TWO') // 'one TWO three'
2522
+ * ```
2523
+ */
2524
+ function spliceSpan(source, span, replacement) {
2525
+ return source.slice(0, span.start) + replacement + source.slice(span.end);
2526
+ }
2527
+ /**
2528
+ * Renders a `## Surface` table from the symbols a source declares — a `Name`, {@link KIND}, and
2529
+ * {@link SUMMARY} table with one row per symbol, the name as a code span, the keyword as its
2530
+ * text, and the summary through {@link buildCell}. A symbol carrying no summary renders an empty
2531
+ * cell, which {@link extractSurface} reads back as an absent summary.
2532
+ *
2533
+ * @remarks
2534
+ * The render carries no `## Surface` heading, because a guide documents its surface in several
2535
+ * tables under their own sub-headings and one of them is what this function produces. Reading the
2536
+ * render back therefore parses it under that heading. `renderMarkdown` pads every cell to one
2537
+ * space, so the render is not the committed column-aligned bytes; the checkout's formatter
2538
+ * re-aligns the table and the reader compares parsed entries rather than bytes.
2539
+ *
2540
+ * @param symbols - The symbols to document, in row order
2541
+ * @returns The table's markdown source, with no trailing newline
2542
+ *
2543
+ * @example
2544
+ * ```ts
2545
+ * renderSurface([{ name: 'walk', keyword: 'function', summary: 'Walks the tree.' }])
2546
+ * // '| Name | Kind | Summary |\n| --- | --- | --- |\n| `walk` | function | Walks the tree. |'
2547
+ * ```
2548
+ */
2549
+ function renderSurface(symbols) {
2550
+ return renderMarkdown({
2551
+ element: "table",
2552
+ header: [
2553
+ [{
2554
+ element: "text",
2555
+ value: "Name"
2556
+ }],
2557
+ [{
2558
+ element: "text",
2559
+ value: KIND
2560
+ }],
2561
+ [{
2562
+ element: "text",
2563
+ value: SUMMARY
2564
+ }]
2565
+ ],
2566
+ rows: symbols.map((symbol) => [
2567
+ [{
2568
+ element: "codeSpan",
2569
+ value: symbol.name
2570
+ }],
2571
+ [{
2572
+ element: "text",
2573
+ value: symbol.keyword
2574
+ }],
2575
+ buildCell(symbol.summary ?? "")
2576
+ ]),
2577
+ align: [
2578
+ null,
2579
+ null,
2580
+ null
2581
+ ]
2582
+ });
2583
+ }
2584
+ /**
2585
+ * Renders one `## Methods` group — the `####` heading naming the interface as a code span, then
2586
+ * a `Name` and {@link SUMMARY} table with one row per documented member. A member carrying no
2587
+ * summary renders an empty cell, which {@link extractMethods} reads back as an absent summary.
2588
+ *
2589
+ * @remarks
2590
+ * The render carries no `## Methods` heading, for the reason {@link renderSurface} states:
2591
+ * a guide documents one group per interface under that one section heading.
2592
+ *
2593
+ * @param group - The interface and its members
2594
+ * @returns The heading and table's markdown source, with no trailing newline
2595
+ *
2596
+ * @example
2597
+ * ```ts
2598
+ * renderMethods({ interface: 'WidgetInterface', methods: [{ name: 'walk', summary: 'Walks.' }] })
2599
+ * // '#### `WidgetInterface`\n\n| Name | Summary |\n| --- | --- |\n| `walk` | Walks. |'
2600
+ * ```
2601
+ */
2602
+ function renderMethods(group) {
2603
+ return renderMarkdown({
2604
+ element: "document",
2605
+ children: [{
2606
+ element: "heading",
2607
+ level: 4,
2608
+ children: [{
2609
+ element: "codeSpan",
2610
+ value: group.interface
2611
+ }]
2612
+ }, {
2613
+ element: "table",
2614
+ header: [[{
2615
+ element: "text",
2616
+ value: "Name"
2617
+ }], [{
2618
+ element: "text",
2619
+ value: SUMMARY
2620
+ }]],
2621
+ rows: group.methods.map((entry) => [[{
2622
+ element: "codeSpan",
2623
+ value: entry.name
2624
+ }], buildCell(entry.summary ?? "")]),
2625
+ align: [null, null]
2626
+ }]
2627
+ });
2628
+ }
2629
+ /**
2630
+ * Renders one `@example` block as the guide fence it pairs with — an H3 heading carrying the
2631
+ * block's title, then a fence carrying its language and its code. An untitled block renders the
2632
+ * fence alone, because a fence pairs on its nearest preceding heading and an untitled block
2633
+ * claims none.
2634
+ *
2635
+ * @remarks
2636
+ * The title renders as literal text rather than markdown, so a title carrying backticks or
2637
+ * emphasis reads back through {@link extractFences} as the text the `@example` tag carried.
2638
+ * The heading level is 3 because a guide documents its examples one level under a `##` section;
2639
+ * {@link extractFences} pairs on the nearest preceding heading of any level, so the level is
2640
+ * presentation rather than pairing.
2641
+ *
2642
+ * @param example - The block to render
2643
+ * @returns The heading and fence's markdown source, with no trailing newline
2644
+ *
2645
+ * @example
2646
+ * ```ts
2647
+ * renderExample({ name: 'walk', title: 'Walk a tree', code: 'walk()', language: 'ts' })
2648
+ * // an H3 heading of 'Walk a tree', then a fence tagged `ts` carrying `walk()`
2649
+ * ```
2650
+ */
2651
+ function renderExample(example) {
2652
+ const fence = buildFence(example);
2653
+ return renderMarkdown({
2654
+ element: "document",
2655
+ children: example.title === void 0 ? [fence] : [{
2656
+ element: "heading",
2657
+ level: 3,
2658
+ children: [{
2659
+ element: "text",
2660
+ value: example.title
2661
+ }]
2662
+ }, fence]
2663
+ });
2664
+ }
2665
+ /**
2666
+ * Replaces one compared cell in a guide's text and returns the whole guide back. `key` names the
2667
+ * row the way {@link findDrift} names it — a {@link computeSymbolKey} key for a `## Surface` row,
2668
+ * an `Owner.member` key for a `## Methods` row — and the row's {@link SUMMARY} cell becomes
2669
+ * `summary`. Only the table's own source region is rewritten, so every byte outside it travels
2670
+ * unchanged; a key reaching no cell returns `undefined`, and a row already carrying the summary
2671
+ * returns the guide byte for byte.
2672
+ *
2673
+ * @remarks
2674
+ * A row the key does not reach, a table carrying no {@link SUMMARY} column, and a document whose
2675
+ * parse recorded no region for the table are each a miss, and a miss returns `undefined` rather
2676
+ * than throwing, so a caller reports the key it could not place — the one meaning `undefined`
2677
+ * carries in every replacer here. A row already carrying `summary` returns the guide byte for
2678
+ * byte, because a rewrite would re-pad the whole table for no change; that identity reads both
2679
+ * sides through {@link normalizeSummary}, so a caller passing text the compared form still moves
2680
+ * is a fixed point on the second run rather than a row rewritten forever. The rewritten table
2681
+ * renders one-space padded whatever padding it carried, so the checkout's formatter re-aligns it.
2682
+ *
2683
+ * @param guide - The guide's markdown source
2684
+ * @param key - The compared key naming the row
2685
+ * @param summary - The row's new compared text
2686
+ * @returns The guide's text with that cell replaced, or `undefined` when the key reaches no cell
2687
+ *
2688
+ * @example
2689
+ * ```ts
2690
+ * replaceCell('## Surface\n\n| Name | Kind | Summary |\n| --- | --- | --- |\n| `walk` | function | Walks. |', 'function walk', 'Walks a tree.')
2691
+ * // '## Surface\n\n| Name | Kind | Summary |\n| --- | --- | --- |\n| `walk` | function | Walks a tree. |'
2692
+ * ```
2693
+ */
2694
+ function replaceCell(guide, key, summary) {
2695
+ const markdown = createMarkdown(guide);
2696
+ const document = markdown.document;
2697
+ let located;
2698
+ let index = -1;
2699
+ for (const block of selectSectionBlocks(document, SURFACE)) {
2700
+ if (located !== void 0 || !isTableNode(block)) continue;
2701
+ for (let row = 0; row < block.rows.length && located === void 0; row += 1) {
2702
+ const symbol = extractRowSymbol(block, row);
2703
+ if (symbol === void 0 || computeSymbolKey(symbol) !== key) continue;
2704
+ located = block;
2705
+ index = row;
2706
+ }
2707
+ }
2708
+ for (const [table, owner] of collectGroups(document)) {
2709
+ if (located !== void 0) break;
2710
+ for (let row = 0; row < table.rows.length && located === void 0; row += 1) {
2711
+ const entry = extractRowEntry(table, row);
2712
+ if (entry === void 0 || `${owner}.${entry.name}` !== key) continue;
2713
+ located = table;
2714
+ index = row;
2715
+ }
2716
+ }
2717
+ if (located === void 0) return void 0;
2718
+ const column = findColumnIndex(located, SUMMARY);
2719
+ if (column === void 0) return void 0;
2720
+ if ((extractRowSummary(located, index) ?? "") === normalizeSummary(summary)) return guide;
2721
+ const span = markdown.span(located);
2722
+ if (span === void 0) return void 0;
2723
+ return spliceSpan(guide, span, renderMarkdown(buildTable(located, index, column, summary)));
2724
+ }
2725
+ /**
2726
+ * Replaces one titled fence in a guide's text and returns the whole guide back. The first fence
2727
+ * carrying `title` — the pairing {@link findDrift} compares on — takes `example`'s language and
2728
+ * code. Only the fence's own source region is rewritten, so every byte outside it travels
2729
+ * unchanged; a title no fence carries returns `undefined`, and a fence already carrying that
2730
+ * body returns the guide byte for byte.
2731
+ *
2732
+ * @remarks
2733
+ * A title no fence carries and a document whose parse recorded no region for the fence are each a
2734
+ * miss, and a miss returns `undefined` rather than throwing — the one meaning `undefined` carries
2735
+ * in every replacer here. A fence already carrying that language and code returns the guide
2736
+ * byte for byte. A later fence of the same title is outside the pairing and is never rewritten,
2737
+ * which is the rule {@link findDrift} compares under.
2738
+ *
2739
+ * @param guide - The guide's markdown source
2740
+ * @param title - The heading text the fence pairs on
2741
+ * @param example - The block whose language and code the fence takes
2742
+ * @returns The guide's text with that fence replaced, or `undefined` when no fence carries the title
2743
+ *
2744
+ * @example
2745
+ * ```ts
2746
+ * replaceFence(guide, 'Walk', { name: 'walk', title: 'Walk', code: 'walk()', language: 'ts' })
2747
+ * // the guide's text with the fence under its `### Walk` heading carrying `walk()`
2748
+ * ```
2749
+ */
2750
+ function replaceFence(guide, title, example) {
2751
+ const markdown = createMarkdown(guide);
2752
+ let located;
2753
+ let current;
2754
+ for (const [node, fence] of collectFences(markdown.document)) {
2755
+ if (located !== void 0 || fence.title !== title) continue;
2756
+ located = node;
2757
+ current = fence;
2758
+ }
2759
+ if (located === void 0 || current === void 0) return void 0;
2760
+ if (current.code === example.code && current.language === example.language) return guide;
2761
+ const span = markdown.span(located);
2762
+ if (span === void 0) return void 0;
2763
+ return spliceSpan(guide, span, renderMarkdown(buildFence(example)));
2764
+ }
2765
+ /**
2766
+ * Replaces one doc block's description paragraph with `summary` and returns the whole block back.
2767
+ * The paragraph is the block's text before its first block tag, and it re-wraps inside `width`;
2768
+ * the blank line before the first tag, every tag line, the block's indentation, and its
2769
+ * continuation markers all survive. A block already carrying the summary returns byte for byte,
2770
+ * and a text that is no doc block and a summary carrying no word each return `undefined`.
2771
+ *
2772
+ * @remarks
2773
+ * A miss returns `undefined`, the one meaning `undefined` carries in every replacer here, so a
2774
+ * caller reports the block it could not rewrite. Text that opens with no
2775
+ * `/**` is no doc block: a single-star `/*` comment reaches this function only by a caller's
2776
+ * mistake, and reshaping it into a doc block would be a silent edit. A `summary` carrying no word
2777
+ * names no paragraph to write, and deleting the block's description on that argument would erase
2778
+ * documentation on the strength of an absent value — a caller with nothing to write writes
2779
+ * nothing.
2780
+ *
2781
+ * A block already carrying `summary` returns byte for byte, which is what keeps a propagation
2782
+ * that finds no drift from rewriting the file: a doc block's own wrapping is not recoverable from
2783
+ * its text, so re-wrapping an unchanged paragraph would move most blocks this package's source
2784
+ * carries. That identity reads both sides through {@link normalizeSummary}, and it holds for a
2785
+ * block carrying no tag as much as for a block carrying several. A block written on one physical
2786
+ * line stays on one line while `summary` still fits inside `width`, and expands otherwise.
2787
+ *
2788
+ * `width` counts characters from the line's first, a tab counting as one, so a wrapped line reads
2789
+ * `${indent} * ${text}` and never passes that count. A caller whose formatter measures a tab as
2790
+ * more than one column passes a smaller width rather than taking the default.
2791
+ *
2792
+ * @param comment - One complete genuine JSDoc span's raw text, as it sits in the file
2793
+ * @param summary - The block's new description paragraph
2794
+ * @param width - The character budget a re-wrapped line stays inside. Default: {@link WRAP_WIDTH}
2795
+ * @returns The block's raw text with that paragraph replaced, or `undefined` for a text that is
2796
+ * no doc block and for a `summary` carrying no word
2797
+ *
2798
+ * @example
2799
+ * ```ts
2800
+ * replaceSummary('/**' + ' Walks. *' + '/', 'Walks a tree.') // '/**' + ' Walks a tree. *' + '/'
2801
+ * ```
2802
+ */
2803
+ function replaceSummary(comment, summary, width = 100) {
2804
+ if (!/^[ \t]*\/\*\*/.test(comment)) return void 0;
2805
+ const content = unwrapComment(comment);
2806
+ const indent = /^[ \t]*/.exec(comment)?.[0] ?? "";
2807
+ const wrapped = wrapText(summary, width - indent.length - 3);
2808
+ if (wrapped.length === 0) return void 0;
2809
+ const masked = maskFences(content.join("\n")).split("\n");
2810
+ let tag = -1;
2811
+ for (let index = 0; index < masked.length && tag < 0; index += 1) if (/^[ \t]*@\w/.test(masked[index] ?? "")) tag = index;
2812
+ if (normalizeSummary(content.slice(0, tag < 0 ? content.length : tag).join("\n")) === normalizeSummary(summary)) return comment;
2813
+ const tail = tag < 0 ? [] : content.slice(tag);
2814
+ if (tail.length === 0 && wrapped.length === 1 && content.length === 1) {
2815
+ const single = `${indent}/** ${wrapped[0] ?? ""} */`;
2816
+ if (single.length <= width) return single;
2817
+ }
2818
+ const lines = [...wrapped];
2819
+ if (tail.length > 0) lines.push("");
2820
+ return buildComment([...lines, ...tail], indent);
2821
+ }
2822
+ /**
2823
+ * Replaces the body of one titled `@example` tag in a doc block's raw text and returns the whole
2824
+ * block back. The tag carrying `example`'s title takes a fence of its language and its code;
2825
+ * every other tag, the description paragraph, the block's indentation, and its continuation
2826
+ * markers all survive. A text that is no doc block, a title no tag carries, and a language or
2827
+ * code the emitted three-backtick fence cannot enclose or the doc block cannot hold each return
2828
+ * `undefined`.
2829
+ *
2830
+ * @remarks
2831
+ * A miss returns `undefined`, the one meaning `undefined` carries in every replacer here, so a
2832
+ * caller reports the block it could not rewrite. Text that opens with no
2833
+ * `/**` is no doc block, for the reason {@link replaceSummary} states. A block carrying no
2834
+ * `@example` tag of that title has nowhere to write, so an untitled tag and a tag carrying
2835
+ * another title are each left alone, and an `example` naming no title misses a block whose tags
2836
+ * all carry one. Code carrying a run of three or more backticks is a body the emitted fence
2837
+ * cannot enclose: the fence is three backticks, {@link maskFences} ends a body at the first line
2838
+ * opening a run at least as long, and {@link collectExamples} reads to the first such run
2839
+ * whatever column it sits at, so writing that body would truncate it and turn a following
2840
+ * `@`-line into a tag. A language or code carrying the doc-comment terminator is a body the
2841
+ * block itself cannot hold: the terminator closes the block where it lands and the file stops
2842
+ * parsing there. Refusing keeps the rewrite total over the bodies it can spell.
2843
+ *
2844
+ * A tag already carrying that language and code returns byte for byte. {@link maskFences} keeps
2845
+ * the current body's own lines out of the tag search, so a fenced body carrying a tag-shaped line
2846
+ * does not end the body early. The body ends at its last line carrying text, so the blank line
2847
+ * separating it from the next tag survives.
2848
+ *
2849
+ * @param comment - One complete genuine JSDoc span's raw text, as it sits in the file
2850
+ * @param example - The block whose language and code the tag's body takes
2851
+ * @returns The block's raw text with that body replaced, or `undefined` for a text that is no
2852
+ * doc block, for a title no `@example` tag carries, and for a language or code the emitted
2853
+ * fence cannot enclose or the doc block cannot hold — a body carrying the doc-comment terminator
2854
+ *
2855
+ * @example
2856
+ * ```ts
2857
+ * replaceExample('/**' + '\n * @example Walk\n * old()\n *' + '/', { name: 'walk', title: 'Walk', code: 'walk()', language: 'ts' })
2858
+ * // the same block, its `@example Walk` body now a fence tagged `ts` carrying `walk()`
2859
+ * ```
2860
+ */
2861
+ function replaceExample(comment, example) {
2862
+ if (!/^[ \t]*\/\*\*/.test(comment)) return void 0;
2863
+ if ([example.language ?? "", ...example.code.split("\n")].some((line) => line.includes("```") || line.includes("*/"))) return void 0;
2864
+ const content = unwrapComment(comment);
2865
+ const masked = maskFences(content.join("\n")).split("\n");
2866
+ const title = example.title ?? "";
2867
+ let start = -1;
2868
+ for (let index = 0; index < masked.length && start < 0; index += 1) {
2869
+ const tag = /^[ \t]*@example(?=[ \t]|$)[ \t]*(.*)$/.exec(masked[index] ?? "");
2870
+ if (tag !== null && (tag[1] ?? "").trim() === title) start = index;
2871
+ }
2872
+ if (start < 0) return void 0;
2873
+ const current = collectExamples(content.join("\n"), example.name).find((entry) => (entry.title ?? "") === title);
2874
+ if (current !== void 0 && current.code === example.code && current.language === example.language) return comment;
2875
+ let end = content.length;
2876
+ for (let index = start + 1; index < masked.length && end === content.length; index += 1) if (/^[ \t]*@\w/.test(masked[index] ?? "")) end = index;
2877
+ while (end > start + 1 && (content[end - 1] ?? "").length === 0) end -= 1;
2878
+ const indent = /^[ \t]*/.exec(comment)?.[0] ?? "";
2879
+ const body = [
2880
+ `\`\`\`${example.language ?? ""}`,
2881
+ ...example.code.split("\n"),
2882
+ "```"
2883
+ ];
2884
+ return buildComment([
2885
+ ...content.slice(0, start + 1),
2886
+ ...body,
2887
+ ...content.slice(end)
2888
+ ], indent);
2889
+ }
2890
+ /**
2891
+ * Locates the doc block a compared key attaches to inside one file's text and returns the block's
2892
+ * own character region, so a caller can `slice` the block, rewrite it through
2893
+ * {@link replaceSummary} or {@link replaceExample}, and write the result back through
2894
+ * {@link spliceSpan}. `key` names the pair the way {@link findDrift} names it — a
2895
+ * {@link computeSymbolKey} key for a declaration, an `Owner.member` key for an interface or class
2896
+ * member; the region covers the block's own indentation, and no block carrying the key returns
2897
+ * `undefined`.
2898
+ *
2899
+ * @remarks
2900
+ * Attachment is {@link extractSourceComments}'s, not a second reading of the file: that walk
2901
+ * pairs each eligible block with the physical record it documents, and this function keeps the
2902
+ * record {@link collectKeys} gives `key`. The keys are that one grammar's — the map
2903
+ * {@link extractExports} and {@link extractMemberMethods} each read their own part out of — so
2904
+ * this function runs no head pattern, no member pattern, and no owner-close rule of its own, and
2905
+ * a change to any of them reaches the locator too. Every block {@link collectSummaries} reports
2906
+ * a summary for is reachable by its key, and a block carrying only block tags is reachable too although it carries no summary.
2907
+ * A block it misses is one the comparison never had: a block a blank line separates from its
2908
+ * declaration attaches to the blank line, and a block written inside a template literal or a
2909
+ * string is no genuine span at all. The first block whose record carries the key answers for it,
2910
+ * as the first declaration of a name does everywhere else.
2911
+ *
2912
+ * The region runs from the start of the opener's line, the block's indentation included, to the
2913
+ * character past its closing marker — the raw text {@link replaceSummary} and
2914
+ * {@link replaceExample} each document as the span "as it sits in the file", so a caller slices,
2915
+ * rewrites, and splices with no adjustment and the rewrite keeps the indentation it found. A
2916
+ * block that source material precedes on its own line starts at the opener instead. The region
2917
+ * is read off the aligned JSDoc projection rather than searched for in the text, so an opener
2918
+ * written inside a string never yields one, and line offsets come from
2919
+ * {@link extractSourceLines}'s own records under its stated LF-or-CRLF terminator rule, so a
2920
+ * CRLF file reports the offsets its own bytes carry.
2921
+ *
2922
+ * @param text - One file's whole source text
2923
+ * @param key - The compared key naming the declaration or the member
2924
+ * @returns The block's half-open character region, or `undefined` when no block carries the key
2925
+ *
2926
+ * @example
2927
+ * ```ts
2928
+ * const text = '/**' + ' Walks. *' + '/\nexport function walk(): void {}\n'
2929
+ * locateComment(text, 'function walk') // { start: 0, end: 13 }
2930
+ * ```
2931
+ */
2932
+ function locateComment(text, key) {
2933
+ const lines = extractSourceLines(text);
2934
+ const keys = collectKeys(lines);
2935
+ const offsets = [];
2936
+ const positions = /* @__PURE__ */ new Map();
2937
+ let offset = 0;
2938
+ for (let index = 0; index < lines.length; index += 1) {
2939
+ const line = lines[index];
2940
+ if (line === void 0) continue;
2941
+ offsets.push(offset);
2942
+ positions.set(line, index);
2943
+ const after = offset + line.source.length;
2944
+ offset = after + (text.startsWith("\r\n", after) ? 2 : 1);
2945
+ }
2946
+ for (const comment of extractSourceComments(lines)) {
2947
+ if (keys.get(comment.line) !== key) continue;
2948
+ const close = (positions.get(comment.line) ?? 0) - 1;
2949
+ const closing = lines[close]?.jsdoc;
2950
+ const end = closing === void 0 ? -1 : closing.lastIndexOf("*/");
2951
+ if (end < 0) continue;
2952
+ let first = close;
2953
+ while (first > 0 && lines[first - 1]?.jsdoc !== void 0) first -= 1;
2954
+ let inside = false;
2955
+ let line = -1;
2956
+ let column = -1;
2957
+ for (let index = first; index <= close; index += 1) {
2958
+ const projection = lines[index]?.jsdoc ?? "";
2959
+ let cursor = 0;
2960
+ while (cursor < projection.length) {
2961
+ const at = projection.indexOf(inside ? "*/" : "/**", cursor);
2962
+ if (at < 0) break;
2963
+ if (!inside) {
2964
+ line = index;
2965
+ column = at;
2966
+ }
2967
+ cursor = at + (inside ? 2 : 3);
2968
+ inside = !inside;
2969
+ }
2970
+ }
2971
+ if (line < 0) continue;
2972
+ const start = (lines[line]?.source ?? "").slice(0, column).trim() === "" ? 0 : column;
2973
+ return {
2974
+ start: (offsets[line] ?? 0) + start,
2975
+ end: (offsets[close] ?? 0) + end + 2
2976
+ };
2977
+ }
2978
+ }
2979
+ //#endregion
2980
+ //#region src/core/parsers.ts
1499
2981
  /**
1500
2982
  * Parses a `## By concept` manifest table into its {@link ManifestEntry} rows —
1501
2983
  * each row's Concept cell (flattened text), Spec / Tests cells (a single link
@@ -1551,7 +3033,7 @@ function parseManifest(markdown, directory) {
1551
3033
  //#region src/core/shapers.ts
1552
3034
  /**
1553
3035
  * Shapes a {@link SurfaceSymbol} — a documented / exported symbol's `name`
1554
- * paired with its {@link ExportKeyword}.
3036
+ * paired with its {@link ExportKeyword} and its optional compared `summary`.
1555
3037
  *
1556
3038
  * @example
1557
3039
  * ```ts
@@ -1564,7 +3046,63 @@ function parseManifest(markdown, directory) {
1564
3046
  */
1565
3047
  var surfaceSymbolShape = objectShape({
1566
3048
  name: stringShape(),
1567
- keyword: literalShape(EXPORT_KEYWORDS)
3049
+ keyword: literalShape(EXPORT_KEYWORDS),
3050
+ summary: optionalShape(stringShape())
3051
+ });
3052
+ /**
3053
+ * Shapes a {@link MethodEntry} — one documented method's `name` paired with its optional
3054
+ * compared `summary`.
3055
+ *
3056
+ * @example
3057
+ * ```ts
3058
+ * import { createContract } from '@orkestrel/contract'
3059
+ * import { methodEntryShape } from '@orkestrel/guide'
3060
+ *
3061
+ * const methodEntry = createContract(methodEntryShape)
3062
+ * methodEntry.is({ name: 'walk' }) // true
3063
+ * ```
3064
+ */
3065
+ var methodEntryShape = objectShape({
3066
+ name: stringShape(),
3067
+ summary: optionalShape(stringShape())
3068
+ });
3069
+ /**
3070
+ * Shapes a {@link SourceExample} — one `@example` block's `name`, its optional pairing
3071
+ * `title`, its `code`, and its optional fence `language`.
3072
+ *
3073
+ * @example
3074
+ * ```ts
3075
+ * import { createContract } from '@orkestrel/contract'
3076
+ * import { sourceExampleShape } from '@orkestrel/guide'
3077
+ *
3078
+ * const sourceExample = createContract(sourceExampleShape)
3079
+ * sourceExample.is({ name: 'walk', code: 'walk()' }) // true
3080
+ * ```
3081
+ */
3082
+ var sourceExampleShape = objectShape({
3083
+ name: stringShape(),
3084
+ title: optionalShape(stringShape()),
3085
+ code: stringShape(),
3086
+ language: optionalShape(stringShape())
3087
+ });
3088
+ /**
3089
+ * Shapes a {@link Drift} — one disagreement's compared `key` with the optional text each
3090
+ * side carries there.
3091
+ *
3092
+ * @example
3093
+ * ```ts
3094
+ * import { createContract } from '@orkestrel/contract'
3095
+ * import { driftShape } from '@orkestrel/guide'
3096
+ *
3097
+ * const drift = createContract(driftShape)
3098
+ * drift.is({ key: 'class Widget', category: 'summary', guide: 'A widget.' }) // true
3099
+ * ```
3100
+ */
3101
+ var driftShape = objectShape({
3102
+ key: stringShape(),
3103
+ category: literalShape(DRIFT_CATEGORIES),
3104
+ guide: optionalShape(stringShape()),
3105
+ source: optionalShape(stringShape())
1568
3106
  });
1569
3107
  /**
1570
3108
  * Shapes a {@link MethodGroup} — a backticked `interface` name paired with
@@ -1581,7 +3119,7 @@ var surfaceSymbolShape = objectShape({
1581
3119
  */
1582
3120
  var methodGroupShape = objectShape({
1583
3121
  interface: stringShape(),
1584
- methods: arrayShape(stringShape())
3122
+ methods: arrayShape(methodEntryShape)
1585
3123
  });
1586
3124
  /**
1587
3125
  * Shapes a {@link ManifestEntry} — one `## By concept` manifest row, `source`
@@ -1606,8 +3144,8 @@ var manifestEntryShape = objectShape({
1606
3144
  //#region src/core/Guide.ts
1607
3145
  /**
1608
3146
  * Presents a pure, structured view over one parsed guide — the documented
1609
- * projections (`sections` / `surface` / `methods` / `links` / `tests` /
1610
- * `fences`) are extracted once at construction and cached.
3147
+ * projections (`sections` / `tagline` / `surface` / `methods` / `unnamed` / `links` /
3148
+ * `tests` / `fences`) are extracted once at construction and cached.
1611
3149
  *
1612
3150
  * @remarks
1613
3151
  * Parses `source` once through `@orkestrel/markdown` and never touches the
@@ -1625,16 +3163,20 @@ var manifestEntryShape = objectShape({
1625
3163
  */
1626
3164
  var Guide = class {
1627
3165
  #sections;
3166
+ #tagline;
1628
3167
  #surface;
1629
3168
  #methods;
3169
+ #unnamed;
1630
3170
  #links;
1631
3171
  #tests;
1632
3172
  #fences;
1633
3173
  constructor(source) {
1634
3174
  const document = createMarkdown(source).document;
1635
3175
  this.#sections = document.children.filter(isHeadingNode).filter((heading) => heading.level === 2).map((heading) => flattenText(heading).trim());
3176
+ this.#tagline = extractTagline(document);
1636
3177
  this.#surface = extractSurface(document);
1637
3178
  this.#methods = extractMethods(document);
3179
+ this.#unnamed = extractUnnamed(document);
1638
3180
  this.#links = extractLinks(document);
1639
3181
  this.#tests = extractTests(document);
1640
3182
  this.#fences = extractFences(document);
@@ -1642,12 +3184,18 @@ var Guide = class {
1642
3184
  sections() {
1643
3185
  return this.#sections;
1644
3186
  }
3187
+ tagline() {
3188
+ return this.#tagline;
3189
+ }
1645
3190
  surface() {
1646
3191
  return this.#surface;
1647
3192
  }
1648
3193
  methods() {
1649
3194
  return this.#methods;
1650
3195
  }
3196
+ unnamed() {
3197
+ return this.#unnamed;
3198
+ }
1651
3199
  links() {
1652
3200
  return this.#links;
1653
3201
  }
@@ -1667,7 +3215,10 @@ var Guide = class {
1667
3215
  * filesystem. `Source` never touches disk:
1668
3216
  * the consumer gathers the inventory however their environment allows
1669
3217
  * (`node:fs` in a Node script, `import.meta.glob` in a browser/vitest run) and
1670
- * passes it in as `files`. Conventional barrel traversal recurses through both
3218
+ * passes it in as `files`.
3219
+ *
3220
+ * @remarks
3221
+ * Conventional barrel traversal recurses through both
1671
3222
  * exact workspace-root `index.ts` and nested `/index.ts` targets. `'.'` is the
1672
3223
  * canonical workspace-root module, module spellings normalize once at
1673
3224
  * construction, and exact opaque inventory keys are never rewritten; keys with
@@ -1678,11 +3229,16 @@ var Guide = class {
1678
3229
  * from; a base the scope does not declare contributes nothing. One declaration
1679
3230
  * answers for a name: the first file in sorted key order that declares the head
1680
3231
  * supplies its members and its bases, and a second file declaring the same name
1681
- * adds nothing. Source projection preserves columns without widening
1682
- * direct/hidden column-zero heads. Literal ECMAScript Unicode identifiers
1683
- * participate in bounded slash-state recognition without escape decoding.
1684
- * Regex recognition is bounded: slash after bare `}` is division, so a
1685
- * post-brace regex statement requires an explicit `;`. General semicolonless
3232
+ * adds nothing. Every reading derives once per instance from the immutable
3233
+ * inventory and is reused — the scope's declaration map on the first `methods`
3234
+ * or `examples` lookup, then each name's members and each example collection
3235
+ * under the name asked for — so a reader asking twice reads the files once and
3236
+ * receives the same records, and a second instance over the same inventory
3237
+ * derives the same readings of its own. Source projection preserves columns
3238
+ * without widening direct/hidden column-zero heads. Literal ECMAScript Unicode
3239
+ * identifiers participate in bounded slash-state recognition without escape
3240
+ * decoding. Regex recognition is bounded: slash after bare `}` is division, so
3241
+ * a post-brace regex statement requires an explicit `;`. General semicolonless
1686
3242
  * declaration/ASI classification is also outside the finite projector, so a
1687
3243
  * slash-leading statement after such a declaration requires an explicit `;`.
1688
3244
  *
@@ -1700,17 +3256,19 @@ var Guide = class {
1700
3256
  * })
1701
3257
  * source.exports() // [{ name: 'Guide', keyword: 'class' }, { name: 'GuideInterface', keyword: 'interface' }]
1702
3258
  * source.surface() // [{ name: 'Guide', keyword: 'class' }, { name: 'GuideInterface', keyword: 'interface' }]
1703
- * source.methods('GuideInterface') // ['sections']
3259
+ * source.methods('GuideInterface') // [{ name: 'sections' }]
1704
3260
  * source.exists('src/core/Guide.ts') // true
1705
3261
  * ```
1706
3262
  */
1707
3263
  var Source = class {
1708
3264
  #files;
1709
3265
  #directories;
3266
+ #methods = /* @__PURE__ */ new Map();
3267
+ #examples = /* @__PURE__ */ new Map();
1710
3268
  #exports;
1711
3269
  #surface;
1712
3270
  #hidden;
1713
- #examples;
3271
+ #declarations;
1714
3272
  constructor(options) {
1715
3273
  this.#files = options.files;
1716
3274
  this.#directories = normalizeDirectories(options.module);
@@ -1724,10 +3282,11 @@ var Source = class {
1724
3282
  return this.#surface;
1725
3283
  }
1726
3284
  methods(name) {
1727
- const declared = this.#members("interface", name, /* @__PURE__ */ new Set());
1728
- if (declared !== void 0) return declared;
1729
- const inherited = this.#members("class", name, /* @__PURE__ */ new Set());
1730
- return inherited === void 0 ? [] : inherited.filter((method) => method !== "constructor");
3285
+ const cached = this.#methods.get(name);
3286
+ if (cached !== void 0) return cached;
3287
+ const members = this.#scanMethods(name);
3288
+ this.#methods.set(name, members);
3289
+ return members;
1731
3290
  }
1732
3291
  exists(relative) {
1733
3292
  return Object.keys(this.#files).some((key) => key === relative || key.startsWith(`${relative}/`));
@@ -1737,25 +3296,32 @@ var Source = class {
1737
3296
  return this.#hidden;
1738
3297
  }
1739
3298
  examples(name) {
1740
- if (name === void 0) {
1741
- if (this.#examples === void 0) this.#examples = this.#scanExamples();
1742
- return this.#examples;
1743
- }
1744
- return this.#exampleMembers(name);
3299
+ const cached = this.#examples.get(name);
3300
+ if (cached !== void 0) return cached;
3301
+ const examples = name === void 0 ? this.#scanExamples() : this.#exampleMembers(name);
3302
+ this.#examples.set(name, examples);
3303
+ return examples;
3304
+ }
3305
+ #scanMethods(name) {
3306
+ const declared = this.#members("interface", name, /* @__PURE__ */ new Set());
3307
+ if (declared !== void 0) return declared;
3308
+ const inherited = this.#members("class", name, /* @__PURE__ */ new Set());
3309
+ return inherited === void 0 ? [] : inherited.filter((entry) => entry.name !== "constructor");
1745
3310
  }
1746
3311
  #scanExamples() {
1747
- const names = [];
3312
+ const examples = [];
1748
3313
  const seen = /* @__PURE__ */ new Set();
1749
3314
  for (const key of selectModuleKeys(this.#files, this.#directories)) {
1750
3315
  const text = this.#files[key];
1751
3316
  if (text === void 0) continue;
1752
- for (const name of extractExamples(text)) {
1753
- if (seen.has(name)) continue;
1754
- seen.add(name);
1755
- names.push(name);
3317
+ for (const example of extractExamples(text)) {
3318
+ const identity = `${example.name}\n${example.title ?? ""}`;
3319
+ if (seen.has(identity)) continue;
3320
+ seen.add(identity);
3321
+ examples.push(example);
1756
3322
  }
1757
3323
  }
1758
- return names;
3324
+ return examples;
1759
3325
  }
1760
3326
  #scanSurface() {
1761
3327
  const symbols = [];
@@ -1793,8 +3359,13 @@ var Source = class {
1793
3359
  }
1794
3360
  }
1795
3361
  #exampleMembers(name) {
1796
- const members = /* @__PURE__ */ new Set([...extractExampleMethods(this.#locate("interface", name)?.body ?? []), ...extractExampleMethods(this.#locate("class", name)?.body ?? [])]);
1797
- return Array.from(members).sort();
3362
+ const members = /* @__PURE__ */ new Map();
3363
+ for (const example of [...extractExampleMethods(this.#locate("interface", name)?.body ?? []), ...extractExampleMethods(this.#locate("class", name)?.body ?? [])]) {
3364
+ const identity = `${example.name}\n${example.title ?? ""}`;
3365
+ if (members.has(identity)) continue;
3366
+ members.set(identity, example);
3367
+ }
3368
+ return Array.from(members.values()).sort((a, b) => a.name === b.name ? 0 : a.name < b.name ? -1 : 1);
1798
3369
  }
1799
3370
  #scanSymbols(scan) {
1800
3371
  const symbols = [];
@@ -1816,19 +3387,27 @@ var Source = class {
1816
3387
  visited.add(name);
1817
3388
  const declaration = this.#locate(keyword, name);
1818
3389
  if (declaration === void 0) return void 0;
1819
- const methods = new Set(extractMemberMethods(declaration.body));
1820
- for (const base of declaration.bases) for (const member of this.#members(keyword, base, visited) ?? []) methods.add(member);
1821
- return Array.from(methods).sort();
3390
+ const methods = /* @__PURE__ */ new Map();
3391
+ for (const entry of extractMemberMethods(declaration.body)) methods.set(entry.name, entry);
3392
+ for (const base of declaration.bases) for (const member of this.#members(keyword, base, visited) ?? []) if (!methods.has(member.name)) methods.set(member.name, member);
3393
+ return Array.from(methods.values()).sort((a, b) => a.name === b.name ? 0 : a.name < b.name ? -1 : 1);
1822
3394
  }
1823
3395
  #locate(keyword, name) {
3396
+ if (this.#declarations === void 0) this.#declarations = this.#scanDeclarations();
3397
+ return this.#declarations.get(`${keyword} ${name}`);
3398
+ }
3399
+ #scanDeclarations() {
3400
+ const declarations = /* @__PURE__ */ new Map();
1824
3401
  for (const key of selectModuleKeys(this.#files, this.#directories)) {
1825
3402
  const text = this.#files[key];
1826
3403
  if (text === void 0) continue;
1827
- const declaration = extractDeclaration(text, keyword, name);
1828
- if (declaration === void 0) continue;
1829
- if (declaration.body.length === 0 && declaration.bases.length === 0) continue;
1830
- return declaration;
3404
+ for (const [identity, declaration] of collectDeclarations(text)) {
3405
+ if (declarations.has(identity)) continue;
3406
+ if (declaration.body.length === 0 && declaration.bases.length === 0) continue;
3407
+ declarations.set(identity, declaration);
3408
+ }
1831
3409
  }
3410
+ return declarations;
1832
3411
  }
1833
3412
  };
1834
3413
  //#endregion
@@ -1887,6 +3466,440 @@ var SourceManager = class {
1887
3466
  }
1888
3467
  };
1889
3468
  //#endregion
3469
+ //#region src/core/Parity.ts
3470
+ /**
3471
+ * Composes generic guide-parity inspection and explicit in-memory rewrites over a caller inventory.
3472
+ */
3473
+ var Parity = class Parity {
3474
+ #options;
3475
+ #rows;
3476
+ constructor(options) {
3477
+ this.#options = {
3478
+ files: { ...options.files },
3479
+ entries: options.entries.map((entry) => ({ ...entry })),
3480
+ modules: { ...options.modules },
3481
+ languages: [...options.languages],
3482
+ language: options.language,
3483
+ ...options.pitch === void 0 ? {} : { pitch: { ...options.pitch } }
3484
+ };
3485
+ this.#rows = this.#createRows(this.#options.files);
3486
+ }
3487
+ rows() {
3488
+ return this.#rows;
3489
+ }
3490
+ inspect() {
3491
+ const input = [];
3492
+ const sections = [];
3493
+ const surface = [];
3494
+ const methods = [];
3495
+ const declarations = [];
3496
+ const links = [];
3497
+ const tests = [];
3498
+ const fences = [];
3499
+ const exampleFences = [];
3500
+ const exampleFunctions = [];
3501
+ const exampleMethods = [];
3502
+ const exampleTitles = [];
3503
+ const examples = {
3504
+ fences: exampleFences,
3505
+ functions: exampleFunctions,
3506
+ methods: exampleMethods,
3507
+ titles: exampleTitles
3508
+ };
3509
+ const imports = [];
3510
+ const drift = [];
3511
+ const pitch = [];
3512
+ this.#inspectInput(input);
3513
+ for (const row of this.#rows) {
3514
+ this.#inspectSections(row, sections);
3515
+ this.#inspectSurface(row, surface);
3516
+ this.#inspectMethods(row, methods);
3517
+ this.#inspectDeclarations(row, declarations);
3518
+ this.#inspectLinks(row, links, tests);
3519
+ this.#inspectFences(row, fences);
3520
+ this.#inspectExamples(row, exampleFences, exampleFunctions, exampleMethods, exampleTitles);
3521
+ this.#inspectImports(row, imports);
3522
+ this.#inspectDrift(row, drift);
3523
+ }
3524
+ this.#inspectPitch(pitch);
3525
+ return {
3526
+ input,
3527
+ sections,
3528
+ surface,
3529
+ methods,
3530
+ declarations,
3531
+ links,
3532
+ tests,
3533
+ fences,
3534
+ examples,
3535
+ imports,
3536
+ drift,
3537
+ pitch
3538
+ };
3539
+ }
3540
+ document() {
3541
+ return this.#rewrite((row, drift, files) => this.#rewriteGuide(row, drift, files));
3542
+ }
3543
+ annotate() {
3544
+ return this.#rewrite((row, drift, files) => this.#rewriteSource(row, drift, files));
3545
+ }
3546
+ #rewrite(apply) {
3547
+ const files = new Map(Object.entries(this.#options.files));
3548
+ const reasons = /* @__PURE__ */ new Map();
3549
+ const requested = /* @__PURE__ */ new Set();
3550
+ for (const row of this.#rows) for (const drift of findDrift(row.guide, row.source)) {
3551
+ const identity = identifyDrift(row.entry.spec, drift);
3552
+ requested.add(identity);
3553
+ const reason = apply(row, drift, files);
3554
+ if (reason !== void 0) reasons.set(identity, reason);
3555
+ }
3556
+ const inventory = Object.fromEntries(files);
3557
+ const remaining = [];
3558
+ const result = new Parity({
3559
+ ...this.#options,
3560
+ files: inventory
3561
+ });
3562
+ remaining.push(...result.inspect().input);
3563
+ for (const row of result.rows()) for (const drift of findDrift(row.guide, row.source)) {
3564
+ const identity = identifyDrift(row.entry.spec, drift);
3565
+ if (!requested.has(identity)) continue;
3566
+ remaining.push({
3567
+ spec: row.entry.spec,
3568
+ text: `${formatDrift(drift)}; ${reasons.get(identity) ?? "the requested destination still disagrees"}`
3569
+ });
3570
+ }
3571
+ return {
3572
+ changes: Array.from(files.entries()).filter(([path, content]) => this.#options.files[path] !== content).sort(([left], [right]) => left.localeCompare(right)).map(([path, content]) => ({
3573
+ path,
3574
+ content
3575
+ })),
3576
+ findings: remaining
3577
+ };
3578
+ }
3579
+ #createRows(files) {
3580
+ const rows = [];
3581
+ for (const entry of this.#options.entries) {
3582
+ const text = files[entry.spec];
3583
+ if (text === void 0) continue;
3584
+ rows.push({
3585
+ entry,
3586
+ guide: new Guide(text),
3587
+ source: new Source({
3588
+ files,
3589
+ module: entry.source
3590
+ })
3591
+ });
3592
+ }
3593
+ return rows;
3594
+ }
3595
+ #inspectInput(findings) {
3596
+ if (this.#options.entries.length === 0) findings.push({ text: "The manifest has no guide entries." });
3597
+ for (const entry of this.#options.entries) {
3598
+ if (this.#options.files[entry.spec] !== void 0) continue;
3599
+ findings.push({
3600
+ spec: entry.spec,
3601
+ text: `${entry.spec} is absent from the inventory.`
3602
+ });
3603
+ }
3604
+ }
3605
+ #inspectSections(row, findings) {
3606
+ const sections = row.guide.sections();
3607
+ for (const heading of [
3608
+ SURFACE,
3609
+ METHODS,
3610
+ TESTS
3611
+ ]) {
3612
+ if (sections.includes(heading)) continue;
3613
+ findings.push({
3614
+ spec: row.entry.spec,
3615
+ text: `${row.entry.spec} has no ## ${heading} section.`
3616
+ });
3617
+ }
3618
+ if (row.guide.methods().length === 0) findings.push({
3619
+ spec: row.entry.spec,
3620
+ text: `${row.entry.spec} has no documented method groups.`
3621
+ });
3622
+ }
3623
+ #inspectSurface(row, findings) {
3624
+ if (row.guide.surface().length === 0) findings.push({
3625
+ spec: row.entry.spec,
3626
+ text: `${row.entry.spec} has no documented surface.`
3627
+ });
3628
+ for (const unnamed of row.guide.unnamed()) findings.push({
3629
+ spec: row.entry.spec,
3630
+ text: `${row.entry.spec} has an unnamed row: ${unnamed}`
3631
+ });
3632
+ for (const key of findMissingSymbols(row.source.exports(), row.source.surface())) findings.push({
3633
+ spec: row.entry.spec,
3634
+ text: `${row.entry.spec} does not re-export ${key}.`
3635
+ });
3636
+ for (const key of findMissingSymbols(row.source.surface(), row.source.exports())) findings.push({
3637
+ spec: row.entry.spec,
3638
+ text: `${row.entry.spec} barrel exposes no direct ${key}.`
3639
+ });
3640
+ for (const key of findMissingSymbols(row.source.surface(), row.guide.surface())) findings.push({
3641
+ spec: row.entry.spec,
3642
+ text: `${row.entry.spec} does not document ${key}.`
3643
+ });
3644
+ for (const key of findMissingSymbols(row.guide.surface(), row.source.surface())) findings.push({
3645
+ spec: row.entry.spec,
3646
+ text: `${row.entry.spec} documents no barrel ${key}.`
3647
+ });
3648
+ for (const symbol of row.source.hidden()) findings.push({
3649
+ spec: row.entry.spec,
3650
+ text: `${row.entry.spec} source hides ${computeSymbolKey(symbol)}.`
3651
+ });
3652
+ }
3653
+ #inspectMethods(row, findings) {
3654
+ for (const group of row.guide.methods()) {
3655
+ const documented = group.methods.map((entry) => entry.name);
3656
+ const declared = row.source.methods(group.interface).map((entry) => entry.name);
3657
+ if (documented.length === 0) findings.push({
3658
+ spec: row.entry.spec,
3659
+ text: `${row.entry.spec} ${group.interface} has no documented methods.`
3660
+ });
3661
+ for (const name of findMissing(declared, documented)) findings.push({
3662
+ spec: row.entry.spec,
3663
+ text: `${row.entry.spec} does not document ${group.interface}.${name}.`
3664
+ });
3665
+ for (const name of findMissing(documented, declared)) findings.push({
3666
+ spec: row.entry.spec,
3667
+ text: `${row.entry.spec} documents no source ${group.interface}.${name}.`
3668
+ });
3669
+ const entity = group.interface.replace(/Interface$/, "");
3670
+ if (entity === group.interface) continue;
3671
+ for (const name of findMissing(row.source.methods(entity).map((entry) => entry.name), documented)) findings.push({
3672
+ spec: row.entry.spec,
3673
+ text: `${row.entry.spec} ${entity}.${name} is outside the ${group.interface} contract.`
3674
+ });
3675
+ }
3676
+ }
3677
+ #inspectDeclarations(row, findings) {
3678
+ const groups = row.guide.methods();
3679
+ const documented = groups.map((group) => group.interface);
3680
+ const declared = new Set(row.source.surface().map((symbol) => symbol.name));
3681
+ for (const group of groups) {
3682
+ const finding = compareMembership(row.entry.spec, group.interface, group.methods.map((entry) => entry.name), row.source.methods(group.interface).map((entry) => entry.name));
3683
+ if (finding !== void 0) findings.push(finding);
3684
+ }
3685
+ for (const symbol of row.source.surface()) {
3686
+ if (symbol.keyword !== "interface" && symbol.keyword !== "class") continue;
3687
+ const members = row.source.methods(symbol.name).map((entry) => entry.name);
3688
+ if (members.length === 0) continue;
3689
+ const contract = `${symbol.name}Interface`;
3690
+ if (symbol.keyword === "class" && declared.has(contract)) {
3691
+ const finding = compareMembership(row.entry.spec, symbol.name, row.source.methods(contract).map((entry) => entry.name), members);
3692
+ if (finding !== void 0) findings.push(finding);
3693
+ continue;
3694
+ }
3695
+ if (documented.includes(symbol.name)) continue;
3696
+ findings.push({
3697
+ spec: row.entry.spec,
3698
+ text: `${row.entry.spec} ${symbol.name} declares members and carries no method table.`
3699
+ });
3700
+ }
3701
+ }
3702
+ #inspectLinks(row, links, tests) {
3703
+ if (row.guide.links().length === 0) links.push({
3704
+ spec: row.entry.spec,
3705
+ text: `${row.entry.spec} has no links.`
3706
+ });
3707
+ for (const href of row.guide.links()) {
3708
+ if (isExternalLink(href)) continue;
3709
+ const path = resolveLink(row.entry.spec, href);
3710
+ if (row.source.exists(path)) continue;
3711
+ links.push({
3712
+ spec: row.entry.spec,
3713
+ text: `${row.entry.spec} has a broken link: ${href}.`
3714
+ });
3715
+ }
3716
+ if (row.guide.tests().length === 0) tests.push({
3717
+ spec: row.entry.spec,
3718
+ text: `${row.entry.spec} has no test links.`
3719
+ });
3720
+ for (const href of row.guide.tests()) {
3721
+ const path = resolveLink(row.entry.spec, href);
3722
+ if (row.source.exists(path)) continue;
3723
+ tests.push({
3724
+ spec: row.entry.spec,
3725
+ text: `${row.entry.spec} has a missing test: ${href}.`
3726
+ });
3727
+ }
3728
+ }
3729
+ #inspectFences(row, findings) {
3730
+ for (const fence of findUnlisted(row.guide.fences(), this.#options.languages)) findings.push({
3731
+ spec: row.entry.spec,
3732
+ text: `${row.entry.spec} has an unlisted fence language under ${fence.title ?? "no heading"}: ${fence.language ?? "absent"}.`
3733
+ });
3734
+ }
3735
+ #inspectExamples(row, fencesFindings, functionFindings, methodFindings, titleFindings) {
3736
+ const fences = row.guide.fences().filter((fence) => fence.language === this.#options.language).map((fence) => fence.code);
3737
+ if (fences.length === 0) fencesFindings.push({
3738
+ spec: row.entry.spec,
3739
+ text: `${row.entry.spec} has no ${this.#options.language} example fence.`
3740
+ });
3741
+ const functions = row.guide.surface().filter((symbol) => symbol.keyword === "function").map((symbol) => symbol.name);
3742
+ for (const name of findUnexampled(functions, fences, row.source.examples().map((example) => example.name))) functionFindings.push({
3743
+ spec: row.entry.spec,
3744
+ text: `${row.entry.spec} has no example for ${name}.`
3745
+ });
3746
+ for (const group of row.guide.methods()) {
3747
+ const entity = group.interface.replace(/Interface$/, "");
3748
+ const examples = row.source.examples(group.interface).map((example) => example.name);
3749
+ if (entity !== group.interface) examples.push(...row.source.examples(entity).map((example) => example.name));
3750
+ for (const name of findUnexampled(group.methods.map((entry) => entry.name), fences, examples)) methodFindings.push({
3751
+ spec: row.entry.spec,
3752
+ text: `${row.entry.spec} has no example for ${group.interface}.${name}.`
3753
+ });
3754
+ }
3755
+ const guide = row.guide.fences().map((fence) => fence.title).filter(isNonEmptyString);
3756
+ const source = row.source.examples().map((example) => example.title).filter(isNonEmptyString);
3757
+ if (!guide.some((title) => source.includes(title))) titleFindings.push({
3758
+ spec: row.entry.spec,
3759
+ text: `${row.entry.spec} has no top-level example-title pair: guide ${JSON.stringify(guide)} source ${JSON.stringify(source)}.`
3760
+ });
3761
+ }
3762
+ #inspectImports(row, findings) {
3763
+ const sources = new SourceManager({
3764
+ files: this.#options.files,
3765
+ modules: this.#options.modules
3766
+ });
3767
+ let compared = false;
3768
+ for (const fence of row.guide.fences()) {
3769
+ if (fence.language !== this.#options.language) continue;
3770
+ for (const imported of extractFenceImports(fence.code)) {
3771
+ const source = sources.source(imported.specifier);
3772
+ if (source === void 0) continue;
3773
+ compared = true;
3774
+ const surface = source.surface().map((symbol) => symbol.name);
3775
+ for (const name of findMissing(imported.names, surface)) findings.push({
3776
+ spec: row.entry.spec,
3777
+ text: `${row.entry.spec} imports missing ${name} from ${imported.specifier}.`
3778
+ });
3779
+ }
3780
+ }
3781
+ if (!compared) findings.push({
3782
+ spec: row.entry.spec,
3783
+ text: `${row.entry.spec} has no mapped self import.`
3784
+ });
3785
+ }
3786
+ #inspectDrift(row, findings) {
3787
+ for (const drift of findDrift(row.guide, row.source)) findings.push({
3788
+ spec: row.entry.spec,
3789
+ text: formatDrift(drift)
3790
+ });
3791
+ }
3792
+ #inspectPitch(findings) {
3793
+ const pitch = this.#options.pitch;
3794
+ if (pitch === void 0) return;
3795
+ const readme = this.#options.files[pitch.readme];
3796
+ const spec = this.#options.files[pitch.spec];
3797
+ if (readme === void 0) {
3798
+ findings.push({
3799
+ spec: pitch.readme,
3800
+ text: `${pitch.readme} is absent from the inventory.`
3801
+ });
3802
+ return;
3803
+ }
3804
+ if (spec === void 0) {
3805
+ findings.push({
3806
+ spec: pitch.spec,
3807
+ text: `${pitch.spec} is absent from the inventory.`
3808
+ });
3809
+ return;
3810
+ }
3811
+ const left = new Guide(readme).tagline();
3812
+ const right = new Guide(spec).tagline();
3813
+ if (left !== void 0 && left === right) return;
3814
+ findings.push({
3815
+ spec: pitch.spec,
3816
+ text: `${pitch.spec} pitch: README ${formatSide(left)} guide ${formatSide(right)}.`
3817
+ });
3818
+ }
3819
+ #rewriteGuide(row, drift, files) {
3820
+ if (drift.source === void 0) return "source authority is absent";
3821
+ const current = files.get(row.entry.spec);
3822
+ if (current === void 0) return "the guide inventory text is absent";
3823
+ if (drift.category === "summary") {
3824
+ const replacement = replaceCell(current, drift.key, drift.source);
3825
+ if (replacement === void 0) return "the guide summary cell or its provenance is unavailable";
3826
+ files.set(row.entry.spec, replacement);
3827
+ return;
3828
+ }
3829
+ const example = collectTitles(row.guide, row.source).get(drift.key);
3830
+ if (example === void 0) return "the paired source example is unavailable";
3831
+ const replacement = replaceFence(current, drift.key, example);
3832
+ if (replacement === void 0) return "the titled guide fence or its provenance is unavailable";
3833
+ files.set(row.entry.spec, replacement);
3834
+ }
3835
+ #rewriteSource(row, drift, files) {
3836
+ if (drift.guide === void 0) return "guide authority is absent";
3837
+ if (drift.category === "summary") {
3838
+ const located = this.#locateSource(row.entry, drift.key, files);
3839
+ if (located === void 0) return "the source doc block or its provenance is unavailable";
3840
+ const replacement = replaceSummary(located.text.slice(located.span.start, located.span.end), drift.guide);
3841
+ if (replacement === void 0) return "the source summary cannot be represented safely";
3842
+ files.set(located.path, spliceSpan(located.text, located.span, replacement));
3843
+ return;
3844
+ }
3845
+ const fence = row.guide.fences().find((entry) => entry.title === drift.key);
3846
+ const located = this.#locateExample(row, drift.key, files);
3847
+ if (fence === void 0 || located === void 0) return "the paired source example or its provenance is unavailable";
3848
+ const replacement = replaceExample(located.text.slice(located.span.start, located.span.end), {
3849
+ name: located.example.name,
3850
+ title: drift.key,
3851
+ code: fence.code,
3852
+ ...fence.language === void 0 ? {} : { language: fence.language }
3853
+ });
3854
+ if (replacement === void 0) return "the guide example cannot be represented safely";
3855
+ files.set(located.path, spliceSpan(located.text, located.span, replacement));
3856
+ }
3857
+ #locateSource(entry, key, files) {
3858
+ const inventory = Object.fromEntries(files);
3859
+ for (const path of selectModuleKeys(inventory, normalizeDirectories(entry.source))) {
3860
+ const text = files.get(path);
3861
+ if (text === void 0) continue;
3862
+ const span = locateComment(text, key);
3863
+ if (span !== void 0) return {
3864
+ path,
3865
+ text,
3866
+ span
3867
+ };
3868
+ }
3869
+ }
3870
+ #locateExample(row, title, files) {
3871
+ const target = collectTitles(row.guide, row.source).get(title);
3872
+ if (target === void 0) return void 0;
3873
+ const keys = [];
3874
+ for (const symbol of row.source.exports()) if (symbol.name === target.name) keys.push(computeSymbolKey(symbol));
3875
+ for (const owner of row.guide.surface()) {
3876
+ if (owner.keyword !== "class" && owner.keyword !== "interface") continue;
3877
+ if (row.source.examples(owner.name).some((example) => example.name === target.name && example.title === title)) keys.push(`${owner.name}.${target.name}`);
3878
+ }
3879
+ const inventory = Object.fromEntries(files);
3880
+ for (const path of selectModuleKeys(inventory, normalizeDirectories(row.entry.source))) {
3881
+ const text = files.get(path);
3882
+ if (text === void 0) continue;
3883
+ let selected;
3884
+ for (const key of keys) {
3885
+ const span = locateComment(text, key);
3886
+ if (span === void 0) continue;
3887
+ const example = collectExamples(normalizeComment(text.slice(span.start, span.end)), target.name).find((entry) => entry.title === title);
3888
+ if (example === void 0) continue;
3889
+ if (selected === void 0 || span.start < selected.span.start) selected = {
3890
+ span,
3891
+ example
3892
+ };
3893
+ }
3894
+ if (selected !== void 0) return {
3895
+ path,
3896
+ text,
3897
+ ...selected
3898
+ };
3899
+ }
3900
+ }
3901
+ };
3902
+ //#endregion
1890
3903
  //#region src/core/factories.ts
1891
3904
  /**
1892
3905
  * Creates a structured {@link GuideInterface} view over one guide's markdown
@@ -1896,12 +3909,13 @@ var SourceManager = class {
1896
3909
  * @param source - The guide's markdown source text
1897
3910
  * @returns A working {@link GuideInterface}
1898
3911
  *
1899
- * @example
3912
+ * @example Construct a Guide from markdown text
1900
3913
  * ```ts
1901
3914
  * import { createGuide } from '@orkestrel/guide'
1902
3915
  *
1903
3916
  * const guide = createGuide('## Surface\n\n| Name | Kind |\n| --- | --- |\n| `X` | class |')
1904
3917
  * guide.surface() // [{ name: 'X', keyword: 'class' }]
3918
+ * guide.sections() // ['Surface']
1905
3919
  * ```
1906
3920
  */
1907
3921
  function createGuide(source) {
@@ -1914,15 +3928,23 @@ function createGuide(source) {
1914
3928
  * @param options - The file inventory and module scope to reflect
1915
3929
  * @returns A `SourceInterface` reflecting the given module scope
1916
3930
  *
1917
- * @example
3931
+ * @example Construct a Source from an inline files record
1918
3932
  * ```ts
1919
3933
  * import { createSource } from '@orkestrel/guide'
1920
3934
  *
1921
3935
  * const source = createSource({
1922
- * files: { 'src/core/Guide.ts': 'export class Guide {}\n' },
3936
+ * files: {
3937
+ * 'src/core/index.ts': "export * from './Guide.js'\nexport * from './types.js'\n",
3938
+ * 'src/core/Guide.ts': 'export class Guide {}\n',
3939
+ * 'src/core/types.ts': 'export interface GuideInterface {\n\tsections(): void\n}\n',
3940
+ * },
1923
3941
  * module: 'src/core',
1924
3942
  * })
1925
- * source.exports() // [{ name: 'Guide', keyword: 'class' }]
3943
+ * source.exports() // [{ name: 'Guide', keyword: 'class' }, { name: 'GuideInterface', keyword: 'interface' }]
3944
+ * source.surface() // [{ name: 'Guide', keyword: 'class' }, { name: 'GuideInterface', keyword: 'interface' }]
3945
+ * source.methods('GuideInterface') // [{ name: 'sections' }]
3946
+ * source.exists('src/core/Guide.ts') // true
3947
+ * source.exists('src/core') // true — a directory any inventory key sits beneath
1926
3948
  * ```
1927
3949
  */
1928
3950
  function createSource(options) {
@@ -1935,15 +3957,22 @@ function createSource(options) {
1935
3957
  * @param options - The shared file inventory and specifier-to-module policy
1936
3958
  * @returns A source manager over the supplied policy
1937
3959
  *
1938
- * @example
3960
+ * @example Resolve a fence's import specifier to the right Source
1939
3961
  * ```ts
1940
3962
  * import { createSourceManager } from '@orkestrel/guide'
1941
3963
  *
1942
3964
  * const sources = createSourceManager({
1943
- * files: { 'src/core/index.ts': "export * from './types.js'" },
1944
- * modules: { '@scope/package': 'src/core' },
3965
+ * files: {
3966
+ * 'src/core/index.ts': "export * from './Guide.js'\n",
3967
+ * 'src/core/Guide.ts': 'export class Guide {}\n',
3968
+ * },
3969
+ * modules: { '@scope/package': 'src/core', '@scope/package/core': 'src/core' },
1945
3970
  * })
1946
- * sources.source('@scope/package')?.surface()
3971
+ *
3972
+ * sources.source('@scope/package')?.surface() // [{ name: 'Guide', keyword: 'class' }]
3973
+ * sources.source('node:fs') // undefined — a foreign import, which a fence check skips
3974
+ * sources.source('@scope/package') === sources.source('@scope/package/core') // true
3975
+ * sources.sources() // [the one shared view both specifiers name]
1947
3976
  * ```
1948
3977
  */
1949
3978
  function createSourceManager(options) {
@@ -1968,6 +3997,60 @@ function createSurfaceSymbolContract() {
1968
3997
  return createContract(surfaceSymbolShape);
1969
3998
  }
1970
3999
  /**
4000
+ * Compiles the {@link methodEntryShape} into a {@link ContractInterface} for
4001
+ * {@link MethodEntry} — a guard, coercing parser, JSON Schema, and seeded
4002
+ * generator from one shape declaration (AGENTS.md § Design laws).
4003
+ *
4004
+ * @returns A `MethodEntry` contract bundling `schema` / `is` / `parse` / `generate`
4005
+ *
4006
+ * @example
4007
+ * ```ts
4008
+ * import { createMethodEntryContract } from '@orkestrel/guide'
4009
+ *
4010
+ * const methodEntry = createMethodEntryContract()
4011
+ * methodEntry.is({ name: 'walk' }) // true
4012
+ * ```
4013
+ */
4014
+ function createMethodEntryContract() {
4015
+ return createContract(methodEntryShape);
4016
+ }
4017
+ /**
4018
+ * Compiles the {@link sourceExampleShape} into a {@link ContractInterface} for
4019
+ * {@link SourceExample} — a guard, coercing parser, JSON Schema, and seeded
4020
+ * generator from one shape declaration (AGENTS.md § Design laws).
4021
+ *
4022
+ * @returns A `SourceExample` contract bundling `schema` / `is` / `parse` / `generate`
4023
+ *
4024
+ * @example
4025
+ * ```ts
4026
+ * import { createSourceExampleContract } from '@orkestrel/guide'
4027
+ *
4028
+ * const sourceExample = createSourceExampleContract()
4029
+ * sourceExample.is({ name: 'walk', code: 'walk()' }) // true
4030
+ * ```
4031
+ */
4032
+ function createSourceExampleContract() {
4033
+ return createContract(sourceExampleShape);
4034
+ }
4035
+ /**
4036
+ * Compiles the {@link driftShape} into a {@link ContractInterface} for
4037
+ * {@link Drift} — a guard, coercing parser, JSON Schema, and seeded
4038
+ * generator from one shape declaration (AGENTS.md § Design laws).
4039
+ *
4040
+ * @returns A `Drift` contract bundling `schema` / `is` / `parse` / `generate`
4041
+ *
4042
+ * @example
4043
+ * ```ts
4044
+ * import { createDriftContract } from '@orkestrel/guide'
4045
+ *
4046
+ * const drift = createDriftContract()
4047
+ * drift.is({ key: 'class Widget', category: 'summary', guide: 'A widget.' }) // true
4048
+ * ```
4049
+ */
4050
+ function createDriftContract() {
4051
+ return createContract(driftShape);
4052
+ }
4053
+ /**
1971
4054
  * Compiles the {@link methodGroupShape} into a {@link ContractInterface} for
1972
4055
  * {@link MethodGroup} — a guard, coercing parser, JSON Schema, and seeded
1973
4056
  * generator from one shape declaration (AGENTS.md § Design laws).
@@ -1979,7 +4062,7 @@ function createSurfaceSymbolContract() {
1979
4062
  * import { createMethodGroupContract } from '@orkestrel/guide'
1980
4063
  *
1981
4064
  * const methodGroup = createMethodGroupContract()
1982
- * methodGroup.is({ interface: 'MarkdownInterface', methods: ['walk'] }) // true
4065
+ * methodGroup.is({ interface: 'MarkdownInterface', methods: [{ name: 'walk' }] }) // true
1983
4066
  * ```
1984
4067
  */
1985
4068
  function createMethodGroupContract() {
@@ -2004,6 +4087,6 @@ function createManifestEntryContract() {
2004
4087
  return createContract(manifestEntryShape);
2005
4088
  }
2006
4089
  //#endregion
2007
- export { EXPORT_KEYWORDS, EXTERNAL_SCHEMES, Guide, MANIFEST, METHODS, SURFACE, Source, SourceManager, TESTS, computeModuleKey, computeSymbolKey, createGuide, createManifestEntryContract, createMethodGroupContract, createSource, createSourceManager, createSurfaceSymbolContract, escapeRegExp, extractCellLinks, extractDeclaration, extractExampleLines, extractExampleMethods, extractExamples, extractExports, extractFenceImports, extractFences, extractHidden, extractLinks, extractMemberMethods, extractMethods, extractSourceLines, extractSurface, extractTests, findFirstCode, findKindIndex, findMissing, findMissingSymbols, findUnexampled, findUnlisted, hasCanonicalSegments, isExportKeyword, isExternalLink, isManifestEntry, isMethodGroup, isSurfaceSymbol, joinHead, manifestEntryShape, methodGroupShape, normalizeDirectories, normalizeIdentifier, parseManifest, resolveLink, resolvePath, selectModuleKeys, selectSectionBlocks, surfaceSymbolShape };
4090
+ export { DRIFT_CATEGORIES, EXPORT_KEYWORDS, EXTERNAL_SCHEMES, Guide, KIND, MANIFEST, METHODS, Parity, SUMMARY, SURFACE, Source, SourceManager, TESTS, WRAP_WIDTH, buildCell, buildComment, buildFence, buildTable, collectDeclarations, collectExamples, collectFences, collectGroups, collectKeys, collectSummaries, collectTitles, compareMembership, computeDrift, computeModuleKey, computeSymbolKey, createDriftContract, createGuide, createManifestEntryContract, createMethodEntryContract, createMethodGroupContract, createSource, createSourceExampleContract, createSourceManager, createSurfaceSymbolContract, driftShape, escapeRegExp, extractBodyLines, extractCellLinks, extractCellText, extractDeclaration, extractExampleLines, extractExampleMethods, extractExamples, extractExports, extractFenceImports, extractFences, extractHidden, extractLinks, extractMemberMethods, extractMethods, extractRowEntry, extractRowSummary, extractRowSymbol, extractSourceComments, extractSourceLines, extractSurface, extractTagline, extractTests, extractUnnamed, findColumnIndex, findDrift, findFirstCode, findMissing, findMissingSymbols, findUnexampled, findUnlisted, formatDrift, formatSide, hasCanonicalSegments, identifyDrift, isDrift, isDriftCategory, isExportKeyword, isExternalLink, isManifestEntry, isMethodEntry, isMethodGroup, isSourceExample, isSurfaceSymbol, joinHead, locateComment, manifestEntryShape, maskFences, methodEntryShape, methodGroupShape, normalizeComment, normalizeDirectories, normalizeIdentifier, normalizeSummary, parseManifest, renderExample, renderMethods, renderSurface, replaceCell, replaceExample, replaceFence, replaceSummary, resolveLink, resolvePath, selectModuleKeys, selectSectionBlocks, sourceExampleShape, spliceSpan, surfaceSymbolShape, unwrapComment, wrapText };
2008
4091
 
2009
4092
  //# sourceMappingURL=index.js.map