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