@orkestrel/guide 0.0.17 → 0.0.18

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.
@@ -0,0 +1,3867 @@
1
+ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
+ //#region \0rolldown/runtime.js
3
+ var __create = Object.create;
4
+ var __defProp = Object.defineProperty;
5
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
6
+ var __getOwnPropNames = Object.getOwnPropertyNames;
7
+ var __getProtoOf = Object.getPrototypeOf;
8
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
9
+ var __copyProps = (to, from, except, desc) => {
10
+ if (from && typeof from === "object" || typeof from === "function") for (var keys = __getOwnPropNames(from), i = 0, n = keys.length, key; i < n; i++) {
11
+ key = keys[i];
12
+ if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, {
13
+ get: ((k) => from[k]).bind(null, key),
14
+ enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
15
+ });
16
+ }
17
+ return to;
18
+ };
19
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule || !__hasOwnProp.call(mod, "default") ? __defProp(target, "default", {
20
+ value: mod,
21
+ enumerable: true
22
+ }) : target, mod));
23
+ //#endregion
24
+ let _orkestrel_contract = require("@orkestrel/contract");
25
+ let node_path = require("node:path");
26
+ let node_url = require("node:url");
27
+ let node_fs = require("node:fs");
28
+ let node_process = require("node:process");
29
+ node_process = __toESM(node_process, 1);
30
+ let _orkestrel_markdown = require("@orkestrel/markdown");
31
+ //#region src/server/constants.ts
32
+ /** Names the workspace-relative guide concept index. */
33
+ var GUIDE_INDEX = "guides/README.md";
34
+ /** Names the package manifest read for native pitch selection. */
35
+ var GUIDE_MANIFEST = "package.json";
36
+ /** Names the package README paired with its indexed guide pitch. */
37
+ var GUIDE_README = "README.md";
38
+ /** Holds the native command usage text written for unsupported arguments. */
39
+ var GUIDE_USAGE = "usage: npm run test:guides [-- --to guide|--to source]";
40
+ //#endregion
41
+ //#region src/server/helpers.ts
42
+ /**
43
+ * Formats one finding with its guide prefix when needed.
44
+ *
45
+ * @param finding - The finding to format
46
+ * @returns The finding text with its spec prefix when the text does not already carry it
47
+ *
48
+ * @example
49
+ * ```ts
50
+ * formatGuideFinding({ spec: 'guides/widget.md', text: 'missing export' })
51
+ * ```
52
+ */
53
+ function formatGuideFinding(finding) {
54
+ const spec = finding.spec;
55
+ return `${spec === void 0 || finding.text.startsWith(spec) ? "" : `${spec} `}${finding.text}`;
56
+ }
57
+ /**
58
+ * Reads an owned foreign result view and accepts passed modules without unhandled errors.
59
+ *
60
+ * @param result - The unknown external runner result to inspect
61
+ * @returns True if a module is present, every module passed, and no unhandled error exists; false otherwise
62
+ *
63
+ * @example
64
+ * ```ts
65
+ * matchesGuideResult({ testModules: [{ state: () => 'passed' }], unhandledErrors: [] })
66
+ * ```
67
+ */
68
+ function matchesGuideResult(result) {
69
+ if (!(0, _orkestrel_contract.isObject)(result)) return false;
70
+ const testModules = Reflect.get(result, "testModules");
71
+ const unhandledErrors = Reflect.get(result, "unhandledErrors");
72
+ if (!(0, _orkestrel_contract.isArray)(testModules) || !(0, _orkestrel_contract.isArray)(unhandledErrors)) return false;
73
+ const modules = [...testModules];
74
+ const errors = [...unhandledErrors];
75
+ if (modules.length === 0 || errors.length > 0) return false;
76
+ for (const module of modules) {
77
+ if (!(0, _orkestrel_contract.isObject)(module)) return false;
78
+ const state = Reflect.get(module, "state");
79
+ if (!(0, _orkestrel_contract.isFunction)(state) || Reflect.apply(state, module, []) !== "passed") return false;
80
+ }
81
+ return true;
82
+ }
83
+ /**
84
+ * Resolves a command root to a native absolute path.
85
+ *
86
+ * @param root - The workspace root as a file URL or native path
87
+ * @returns The native absolute workspace path
88
+ *
89
+ * @example
90
+ * ```ts
91
+ * resolveGuideRoot('/workspace')
92
+ * ```
93
+ */
94
+ function resolveGuideRoot(root) {
95
+ return (0, node_path.resolve)(root instanceof URL ? (0, node_url.fileURLToPath)(root) : root);
96
+ }
97
+ /**
98
+ * Selects the indexed guide matching a package's bare name.
99
+ *
100
+ * @param entries - The concept-index entries to search
101
+ * @param name - The package's bare name, or `undefined` when none was parsed
102
+ * @returns The indexed own-guide path, or `undefined` when the index carries none
103
+ *
104
+ * @example
105
+ * ```ts
106
+ * selectGuidePitch([{ concept: 'Widget', spec: 'guides/widget.md', source: 'src', tests: 'tests' }], 'widget')
107
+ * ```
108
+ */
109
+ function selectGuidePitch(entries, name) {
110
+ if (name === void 0) return void 0;
111
+ const spec = `guides/${name}.md`;
112
+ return entries.some((entry) => entry.spec === spec) ? spec : void 0;
113
+ }
114
+ //#endregion
115
+ //#region src/server/parsers.ts
116
+ /**
117
+ * Maps the supported `--to guide` and `--to source` arguments to an explicit rewrite destination.
118
+ *
119
+ * @param args - The arguments after the native command entry
120
+ * @returns The requested destination, or `undefined` when the shape is unsupported
121
+ *
122
+ * @example
123
+ * ```ts
124
+ * parseGuideDirection(['--to', 'guide'])
125
+ * ```
126
+ */
127
+ function parseGuideDirection(args) {
128
+ if (args.length !== 2 || args[0] !== "--to") return void 0;
129
+ const direction = args[1];
130
+ return direction === "guide" || direction === "source" ? direction : void 0;
131
+ }
132
+ /**
133
+ * Reads the bare package name from package manifest JSON.
134
+ *
135
+ * @param manifest - The package manifest JSON text
136
+ * @returns The name after its final scope separator, or `undefined` when no name is declared
137
+ *
138
+ * @example
139
+ * ```ts
140
+ * parsePackageName('{"name":"@scope/widget"}')
141
+ * ```
142
+ */
143
+ function parsePackageName(manifest) {
144
+ const parsed = (0, _orkestrel_contract.parseJSON)(manifest);
145
+ if (!(0, _orkestrel_contract.isRecord)(parsed)) return void 0;
146
+ const name = parsed.name;
147
+ if (typeof name !== "string" || name.length === 0) return void 0;
148
+ return name.slice(name.lastIndexOf("/") + 1);
149
+ }
150
+ //#endregion
151
+ //#region src/core/constants.ts
152
+ /**
153
+ * Lists the declaration keywords a documented or exported symbol carries, in the order the
154
+ * reflection grammar names them — the frozen population `ExportKeyword`, `isExportKeyword`, and
155
+ * `surfaceSymbolShape` all derive from.
156
+ *
157
+ * @remarks
158
+ * One frozen list feeds the type, the guard, and the shape, so a keyword cannot be admitted by one
159
+ * and refused by another. Comment and template payload is excluded before reflection, and `enum`
160
+ * is outside this population rather than forbidden by general package policy.
161
+ */
162
+ var EXPORT_KEYWORDS = Object.freeze([
163
+ "type",
164
+ "interface",
165
+ "const",
166
+ "function",
167
+ "class"
168
+ ]);
169
+ /**
170
+ * Lists the compared sites a {@link Drift} can describe.
171
+ */
172
+ var DRIFT_CATEGORIES = Object.freeze(["summary", "example"]);
173
+ /**
174
+ * Names the `## Surface` heading text a guide's documented exports section is keyed on.
175
+ */
176
+ var SURFACE = "Surface";
177
+ /**
178
+ * Names the `## Methods` heading text a guide's documented interface-methods section is keyed on.
179
+ */
180
+ var METHODS = "Methods";
181
+ /**
182
+ * Names the `## Tests` heading text a guide's documented test-link section is keyed on.
183
+ */
184
+ var TESTS = "Tests";
185
+ /**
186
+ * Names the header text of the column a `## Surface` table's declaration keyword is read from.
187
+ */
188
+ var KIND = "Kind";
189
+ /**
190
+ * Names the header text of the column a `## Surface` or `## Methods` table's compared
191
+ * description paragraph is read from.
192
+ */
193
+ var SUMMARY = "Summary";
194
+ /**
195
+ * Names the `## By concept` heading text the manifest's run-map table is keyed on.
196
+ */
197
+ var MANIFEST = "By concept";
198
+ /**
199
+ * Lists the link `href` schemes a guides-parity link check skips as external — a link
200
+ * with one of these prefixes (or a bare `#` anchor, handled separately in
201
+ * `isExternalLink`) is never resolved against the filesystem.
202
+ */
203
+ var EXTERNAL_SCHEMES = Object.freeze([
204
+ "http:",
205
+ "https:",
206
+ "mailto:",
207
+ "tel:"
208
+ ]);
209
+ //#endregion
210
+ //#region src/core/validators.ts
211
+ /**
212
+ * Checks whether `value` is one of the documented {@link ExportKeyword}
213
+ * literals — the guard behind extracting a Surface table's `Kind` cell into a
214
+ * typed symbol.
215
+ *
216
+ * @param value - The candidate value
217
+ * @returns True if `value` is a valid {@link ExportKeyword}; false otherwise
218
+ *
219
+ * @example
220
+ * ```ts
221
+ * isExportKeyword('class') // true
222
+ * isExportKeyword('enum') // false
223
+ * ```
224
+ */
225
+ var isExportKeyword = (0, _orkestrel_contract.literalOf)(EXPORT_KEYWORDS);
226
+ /** Checks whether `value` names a supported drift category. */
227
+ var isDriftCategory = (0, _orkestrel_contract.literalOf)(DRIFT_CATEGORIES);
228
+ (0, _orkestrel_contract.recordOf)({
229
+ name: _orkestrel_contract.isString,
230
+ keyword: isExportKeyword,
231
+ summary: _orkestrel_contract.isString
232
+ }, ["summary"]);
233
+ /**
234
+ * Checks whether `value` is a well-formed {@link MethodEntry} — a `name` string with an
235
+ * optional `summary`.
236
+ *
237
+ * @param value - The value to test
238
+ * @returns True if `value` is a well-formed {@link MethodEntry}; false otherwise
239
+ *
240
+ * @example
241
+ * ```ts
242
+ * isMethodEntry({ name: 'walk' }) // true
243
+ * isMethodEntry({ name: 1 }) // false
244
+ * ```
245
+ */
246
+ var isMethodEntry = (0, _orkestrel_contract.recordOf)({
247
+ name: _orkestrel_contract.isString,
248
+ summary: _orkestrel_contract.isString
249
+ }, ["summary"]);
250
+ (0, _orkestrel_contract.recordOf)({
251
+ name: _orkestrel_contract.isString,
252
+ title: _orkestrel_contract.isString,
253
+ code: _orkestrel_contract.isString,
254
+ language: _orkestrel_contract.isString
255
+ }, ["title", "language"]);
256
+ (0, _orkestrel_contract.recordOf)({
257
+ key: _orkestrel_contract.isString,
258
+ category: isDriftCategory,
259
+ guide: _orkestrel_contract.isString,
260
+ source: _orkestrel_contract.isString
261
+ }, ["guide", "source"]);
262
+ (0, _orkestrel_contract.recordOf)({
263
+ interface: _orkestrel_contract.isString,
264
+ methods: (0, _orkestrel_contract.arrayOf)(isMethodEntry)
265
+ });
266
+ (0, _orkestrel_contract.recordOf)({
267
+ concept: _orkestrel_contract.isString,
268
+ spec: _orkestrel_contract.isString,
269
+ source: (0, _orkestrel_contract.unionOf)(_orkestrel_contract.isString, (0, _orkestrel_contract.arrayOf)(_orkestrel_contract.isString)),
270
+ tests: _orkestrel_contract.isString
271
+ });
272
+ //#endregion
273
+ //#region src/core/helpers.ts
274
+ /**
275
+ * Extracts aligned physical source-line records in one character traversal.
276
+ * Real line and block comments and complete template tokens become spaces in
277
+ * {@link SourceLine.code}, while ordinary code, quoted strings, and recognized
278
+ * regex literals retain their columns. Genuine JSDoc opened from reflection
279
+ * code is retained span by span at its exact physical column in
280
+ * {@link SourceLine.jsdoc}; faux openers in comments and templates are
281
+ * excluded. Membership remains each consumer's separate anchored grammar.
282
+ *
283
+ * @remarks
284
+ * Regex recognition is a bounded lexical goal rather than TypeScript parser
285
+ * grammar. Literal ECMAScript Unicode identifiers participate in slash-state
286
+ * recognition, including private identifiers, without decoding escaped
287
+ * identifier spellings. Slash after bare `}` is division, and a post-brace
288
+ * regex statement requires an explicit `;`. General semicolonless
289
+ * declaration/ASI classification is outside this finite projector, so callers
290
+ * place an explicit `;` before a slash-leading statement after such a
291
+ * declaration.
292
+ *
293
+ * @param source - The TypeScript source text to project
294
+ * @returns One aligned terminator-free record per LF or CRLF physical line, including the final line
295
+ *
296
+ * @example Project source into physical code lines
297
+ * ```ts
298
+ * import { extractSourceLines } from '@orkestrel/guide'
299
+ *
300
+ * extractSourceLines('export const visible = true // note\n')
301
+ * // [{ source: 'export const visible = true // note', code: 'export const visible = true ', jsdoc: undefined }]
302
+ * // … one record per remaining line
303
+ * ```
304
+ */
305
+ function extractSourceLines(source) {
306
+ const lines = [];
307
+ let characters = [];
308
+ let jsdocCharacters = [];
309
+ const identifier = /#?[$_\p{ID_Start}][$_\u200C\u200D\p{ID_Continue}]*/uy;
310
+ const templates = [];
311
+ const parentheses = [];
312
+ let start = 0;
313
+ let mode = "code";
314
+ let escaped = false;
315
+ let regexClass = false;
316
+ let operandExpected = true;
317
+ let memberExpected = false;
318
+ let pendingRole;
319
+ let restricted;
320
+ let separated = false;
321
+ let blockTemplate = false;
322
+ let lineTemplate = false;
323
+ let jsdoc = false;
324
+ let jsdocPresent = false;
325
+ for (let offset = 0; offset < source.length; offset += 1) {
326
+ const character = source[offset];
327
+ if (character === void 0) continue;
328
+ const next = source[offset + 1];
329
+ const crlf = character === "\r" && next === "\n";
330
+ if (character === "\n" || crlf) {
331
+ const code = characters.join("");
332
+ const present = jsdocPresent || jsdoc;
333
+ lines.push({
334
+ source: source.slice(start, offset),
335
+ code,
336
+ jsdoc: present ? jsdocCharacters.join("").padEnd(code.length, " ") : void 0
337
+ });
338
+ characters = [];
339
+ jsdocCharacters = [];
340
+ jsdocPresent = jsdoc;
341
+ if (mode !== "template") separated = true;
342
+ if (restricted !== void 0) {
343
+ operandExpected = true;
344
+ memberExpected = false;
345
+ pendingRole = void 0;
346
+ restricted = void 0;
347
+ }
348
+ if (crlf) offset += 1;
349
+ start = offset + 1;
350
+ if (mode === "line") mode = lineTemplate ? "templateCode" : "code";
351
+ else if (mode === "regex") {
352
+ mode = "code";
353
+ operandExpected = true;
354
+ regexClass = false;
355
+ } else if (mode === "templateLine" || mode === "templateRegex") {
356
+ mode = "templateCode";
357
+ operandExpected = true;
358
+ regexClass = false;
359
+ } else if (mode === "single" || mode === "double") {
360
+ if (!escaped) {
361
+ mode = "code";
362
+ operandExpected = true;
363
+ }
364
+ } else if (mode === "templateSingle" || mode === "templateDouble") {
365
+ if (!escaped) {
366
+ mode = "templateCode";
367
+ operandExpected = true;
368
+ }
369
+ }
370
+ escaped = false;
371
+ continue;
372
+ }
373
+ if (mode === "line" || mode === "templateLine") {
374
+ characters.push(" ");
375
+ continue;
376
+ }
377
+ if (mode === "block" || mode === "templateBlock") {
378
+ characters.push(" ");
379
+ if (jsdoc) jsdocCharacters.push(character);
380
+ if (character === "*" && next === "/") {
381
+ characters.push(" ");
382
+ if (jsdoc) {
383
+ jsdocCharacters.push("/");
384
+ jsdoc = false;
385
+ }
386
+ offset += 1;
387
+ mode = blockTemplate ? "templateCode" : "code";
388
+ }
389
+ continue;
390
+ }
391
+ if (mode === "single" || mode === "double") {
392
+ characters.push(character);
393
+ if (escaped) {
394
+ escaped = false;
395
+ continue;
396
+ }
397
+ if (character === "\\") {
398
+ escaped = true;
399
+ continue;
400
+ }
401
+ if (mode === "single" && character === "'" || mode === "double" && character === "\"") {
402
+ mode = "code";
403
+ operandExpected = false;
404
+ }
405
+ continue;
406
+ }
407
+ if (mode === "regex") {
408
+ characters.push(character);
409
+ if (escaped) {
410
+ escaped = false;
411
+ continue;
412
+ }
413
+ if (character === "\\") {
414
+ escaped = true;
415
+ continue;
416
+ }
417
+ if (character === "[") regexClass = true;
418
+ else if (character === "]") regexClass = false;
419
+ else if (character === "/" && !regexClass) {
420
+ mode = "code";
421
+ operandExpected = false;
422
+ }
423
+ continue;
424
+ }
425
+ if (mode === "templateSingle" || mode === "templateDouble") {
426
+ characters.push(" ");
427
+ if (escaped) {
428
+ escaped = false;
429
+ continue;
430
+ }
431
+ if (character === "\\") {
432
+ escaped = true;
433
+ continue;
434
+ }
435
+ if (mode === "templateSingle" && character === "'" || mode === "templateDouble" && character === "\"") {
436
+ mode = "templateCode";
437
+ operandExpected = false;
438
+ }
439
+ continue;
440
+ }
441
+ if (mode === "templateRegex") {
442
+ characters.push(" ");
443
+ if (escaped) {
444
+ escaped = false;
445
+ continue;
446
+ }
447
+ if (character === "\\") {
448
+ escaped = true;
449
+ continue;
450
+ }
451
+ if (character === "[") regexClass = true;
452
+ else if (character === "]") regexClass = false;
453
+ else if (character === "/" && !regexClass) {
454
+ mode = "templateCode";
455
+ operandExpected = false;
456
+ }
457
+ continue;
458
+ }
459
+ if (mode === "template") {
460
+ characters.push(" ");
461
+ if (escaped) {
462
+ escaped = false;
463
+ continue;
464
+ }
465
+ if (character === "\\") {
466
+ escaped = true;
467
+ continue;
468
+ }
469
+ if (character === "$" && next === "{") {
470
+ characters.push(" ");
471
+ offset += 1;
472
+ const index = templates.length - 1;
473
+ if (index >= 0) templates[index] = 1;
474
+ mode = "templateCode";
475
+ operandExpected = true;
476
+ memberExpected = false;
477
+ pendingRole = void 0;
478
+ continue;
479
+ }
480
+ if (character === "`") {
481
+ templates.pop();
482
+ mode = templates.length === 0 ? "code" : "templateCode";
483
+ operandExpected = false;
484
+ }
485
+ continue;
486
+ }
487
+ const templateCode = mode === "templateCode";
488
+ if (character === "/" && next === "/") {
489
+ characters.push(" ", " ");
490
+ offset += 1;
491
+ lineTemplate = templateCode;
492
+ mode = templateCode ? "templateLine" : "line";
493
+ continue;
494
+ }
495
+ if (character === "/" && next === "*") {
496
+ characters.push(" ", " ");
497
+ if (!templateCode && source[offset + 2] === "*") {
498
+ const column = offset - start;
499
+ const width = jsdocCharacters.join("").length;
500
+ jsdocCharacters.push(" ".repeat(column - width), "/", "*");
501
+ jsdoc = true;
502
+ jsdocPresent = true;
503
+ }
504
+ offset += 1;
505
+ blockTemplate = templateCode;
506
+ mode = templateCode ? "templateBlock" : "block";
507
+ continue;
508
+ }
509
+ if (character === "'") {
510
+ characters.push(templateCode ? " " : character);
511
+ mode = templateCode ? "templateSingle" : "single";
512
+ escaped = false;
513
+ separated = false;
514
+ restricted = void 0;
515
+ continue;
516
+ }
517
+ if (character === "\"") {
518
+ characters.push(templateCode ? " " : character);
519
+ mode = templateCode ? "templateDouble" : "double";
520
+ escaped = false;
521
+ separated = false;
522
+ restricted = void 0;
523
+ continue;
524
+ }
525
+ if (character === "`") {
526
+ characters.push(" ");
527
+ templates.push(0);
528
+ mode = "template";
529
+ escaped = false;
530
+ separated = false;
531
+ restricted = void 0;
532
+ continue;
533
+ }
534
+ const visible = templateCode ? " " : character;
535
+ if (character === "/" && next === "=" && !operandExpected) {
536
+ characters.push(visible, templateCode ? " " : "=");
537
+ offset += 1;
538
+ operandExpected = true;
539
+ memberExpected = false;
540
+ pendingRole = void 0;
541
+ separated = false;
542
+ restricted = void 0;
543
+ continue;
544
+ }
545
+ if (character === "/") {
546
+ characters.push(visible);
547
+ if (operandExpected) {
548
+ mode = templateCode ? "templateRegex" : "regex";
549
+ escaped = false;
550
+ regexClass = false;
551
+ } else {
552
+ operandExpected = true;
553
+ memberExpected = false;
554
+ pendingRole = void 0;
555
+ }
556
+ separated = false;
557
+ restricted = void 0;
558
+ continue;
559
+ }
560
+ identifier.lastIndex = offset;
561
+ const identifierMatch = identifier.exec(source);
562
+ if (identifierMatch !== null) {
563
+ const token = identifierMatch[0];
564
+ characters.push(templateCode ? " ".repeat(token.length) : token);
565
+ if (token.startsWith("#")) {
566
+ operandExpected = false;
567
+ memberExpected = false;
568
+ pendingRole = void 0;
569
+ restricted = void 0;
570
+ separated = false;
571
+ offset += token.length - 1;
572
+ continue;
573
+ }
574
+ const frame = parentheses[parentheses.length - 1];
575
+ const label = restricted === "label";
576
+ restricted = void 0;
577
+ separated = false;
578
+ if (memberExpected) {
579
+ memberExpected = false;
580
+ operandExpected = false;
581
+ pendingRole = void 0;
582
+ } else if (label) {
583
+ operandExpected = false;
584
+ pendingRole = void 0;
585
+ restricted = "complete";
586
+ } else if (/^(?:if|while|with)$/.test(token)) {
587
+ pendingRole = "statement";
588
+ operandExpected = true;
589
+ } else if (token === "for") {
590
+ pendingRole = "for";
591
+ operandExpected = true;
592
+ } else if (token === "export") {
593
+ pendingRole = "export";
594
+ operandExpected = true;
595
+ } else if (token === "default" && pendingRole === "export") {
596
+ pendingRole = void 0;
597
+ operandExpected = true;
598
+ } else if (/^(?:switch|catch)$/.test(token)) {
599
+ pendingRole = "block";
600
+ operandExpected = true;
601
+ } else if (token === "await" && pendingRole === "for") operandExpected = true;
602
+ else if (/^(?:return|throw|case|delete|void|typeof|new|await|yield|else|do|extends)$/.test(token)) {
603
+ pendingRole = void 0;
604
+ operandExpected = true;
605
+ } else if (/^(?:in|instanceof)$/.test(token)) {
606
+ pendingRole = void 0;
607
+ operandExpected = true;
608
+ } else if (/^(?:break|continue)$/.test(token)) {
609
+ pendingRole = void 0;
610
+ operandExpected = false;
611
+ restricted = "label";
612
+ } else if (token === "debugger") {
613
+ pendingRole = void 0;
614
+ operandExpected = false;
615
+ restricted = "complete";
616
+ } else if (token === "of" && frame?.role === "for" && frame.phase === "left" && !frame.binding && !operandExpected) {
617
+ frame.phase = "right";
618
+ operandExpected = true;
619
+ pendingRole = void 0;
620
+ } else if (/^(?:const|let|var)$/.test(token) && frame?.role === "for" && frame.phase === "left") {
621
+ frame.binding = true;
622
+ operandExpected = true;
623
+ pendingRole = void 0;
624
+ } else {
625
+ if (frame?.binding === true) frame.binding = false;
626
+ operandExpected = false;
627
+ pendingRole = void 0;
628
+ }
629
+ offset += token.length - 1;
630
+ continue;
631
+ }
632
+ if (/[0-9]/.test(character)) {
633
+ let end = offset + 1;
634
+ while (end < source.length) {
635
+ const part = source[end];
636
+ if (part === void 0 || !/[A-Za-z0-9_$.]/.test(part)) break;
637
+ end += 1;
638
+ }
639
+ const token = source.slice(offset, end);
640
+ characters.push(templateCode ? " ".repeat(token.length) : token);
641
+ operandExpected = false;
642
+ memberExpected = false;
643
+ pendingRole = void 0;
644
+ restricted = void 0;
645
+ separated = false;
646
+ offset = end - 1;
647
+ continue;
648
+ }
649
+ if (character === "!" && next === "=" && source[offset + 2] === "=" || character === "=" && next === "=" && source[offset + 2] === "=") {
650
+ characters.push(visible, templateCode ? " " : source.slice(offset + 1, offset + 3));
651
+ offset += 2;
652
+ operandExpected = true;
653
+ memberExpected = false;
654
+ pendingRole = void 0;
655
+ restricted = void 0;
656
+ separated = false;
657
+ continue;
658
+ }
659
+ if ((character === "!" || character === "=") && next === "=") {
660
+ characters.push(visible, templateCode ? " " : "=");
661
+ offset += 1;
662
+ operandExpected = true;
663
+ memberExpected = false;
664
+ pendingRole = void 0;
665
+ restricted = void 0;
666
+ separated = false;
667
+ continue;
668
+ }
669
+ if (character === "+" && next === "+" || character === "-" && next === "-") {
670
+ characters.push(visible, templateCode ? " " : next);
671
+ offset += 1;
672
+ if (separated) operandExpected = true;
673
+ memberExpected = false;
674
+ pendingRole = void 0;
675
+ restricted = void 0;
676
+ separated = false;
677
+ continue;
678
+ }
679
+ if (character === "." && next === "." && source[offset + 2] === ".") {
680
+ characters.push(visible, templateCode ? " " : "..");
681
+ offset += 2;
682
+ operandExpected = true;
683
+ memberExpected = false;
684
+ pendingRole = void 0;
685
+ restricted = void 0;
686
+ separated = false;
687
+ continue;
688
+ }
689
+ if (character === "?" && next === ".") {
690
+ characters.push(visible, templateCode ? " " : ".");
691
+ offset += 1;
692
+ operandExpected = false;
693
+ memberExpected = true;
694
+ pendingRole = void 0;
695
+ restricted = void 0;
696
+ separated = false;
697
+ continue;
698
+ }
699
+ characters.push(visible);
700
+ if (/\s/.test(character)) continue;
701
+ separated = false;
702
+ restricted = void 0;
703
+ if (character === "(") {
704
+ parentheses.push({
705
+ role: pendingRole ?? "plain",
706
+ phase: "left",
707
+ binding: false
708
+ });
709
+ operandExpected = true;
710
+ memberExpected = false;
711
+ pendingRole = void 0;
712
+ continue;
713
+ }
714
+ if (character === ")") {
715
+ const frame = parentheses.pop();
716
+ operandExpected = frame?.role === "statement" || frame?.role === "for";
717
+ memberExpected = false;
718
+ pendingRole = void 0;
719
+ continue;
720
+ }
721
+ if (character === ";") {
722
+ const frame = parentheses[parentheses.length - 1];
723
+ if (frame?.role === "for" && frame.phase === "left") frame.phase = "classic";
724
+ operandExpected = true;
725
+ memberExpected = false;
726
+ pendingRole = void 0;
727
+ continue;
728
+ }
729
+ if (character === ".") {
730
+ operandExpected = false;
731
+ memberExpected = true;
732
+ pendingRole = void 0;
733
+ continue;
734
+ }
735
+ if (character === "]" || character === "}") {
736
+ const frame = parentheses[parentheses.length - 1];
737
+ if (frame?.role === "for" && frame.phase === "left" && frame.binding) frame.binding = false;
738
+ }
739
+ if (character === "]") operandExpected = false;
740
+ else if (character === "}") {
741
+ const index = templates.length - 1;
742
+ const depth = templates[index];
743
+ if (templateCode && index >= 0 && depth !== void 0) {
744
+ templates[index] = depth - 1;
745
+ if (depth === 1) mode = "template";
746
+ }
747
+ operandExpected = false;
748
+ } else if (character === "{") {
749
+ const index = templates.length - 1;
750
+ const depth = templates[index];
751
+ if (templateCode && index >= 0 && depth !== void 0) templates[index] = depth + 1;
752
+ operandExpected = true;
753
+ } else if (character !== "!") operandExpected = true;
754
+ memberExpected = false;
755
+ pendingRole = void 0;
756
+ }
757
+ const code = characters.join("");
758
+ const present = jsdocPresent || jsdoc;
759
+ lines.push({
760
+ source: source.slice(start),
761
+ code,
762
+ jsdoc: present ? jsdocCharacters.join("").padEnd(code.length, " ") : void 0
763
+ });
764
+ return lines;
765
+ }
766
+ /**
767
+ * Checks whether an opaque inventory key contains only canonical slash-separated
768
+ * segments. Empty, `.` and `..` segments are rejected without rewriting the
769
+ * key; ordinary dotfile segments remain valid.
770
+ *
771
+ * @param key - The opaque inventory key to inspect
772
+ * @returns True if every segment is canonical; false otherwise
773
+ *
774
+ * @example
775
+ * ```ts
776
+ * hasCanonicalSegments('src/.hidden.ts') // true
777
+ * hasCanonicalSegments('src/../alias.ts') // false
778
+ * ```
779
+ */
780
+ function hasCanonicalSegments(key) {
781
+ return key.split("/").every((segment) => segment !== "" && segment !== "." && segment !== "..");
782
+ }
783
+ /**
784
+ * Normalizes a module scope to its canonical directory list. `'.'` represents
785
+ * workspace root; empty, trailing, and dot-segment spellings reduce through
786
+ * {@link resolvePath}, and duplicates are removed in first-seen order.
787
+ *
788
+ * @param module - The module scope to normalize
789
+ * @returns The directory list `module` denotes
790
+ *
791
+ * @example
792
+ * ```ts
793
+ * normalizeDirectories('src/core') // ['src/core']
794
+ * normalizeDirectories(['src/core', 'src/browser']) // ['src/core', 'src/browser']
795
+ * ```
796
+ */
797
+ function normalizeDirectories(module) {
798
+ const directories = [];
799
+ const seen = /* @__PURE__ */ new Set();
800
+ for (const value of typeof module === "string" ? [module] : module) {
801
+ const directory = resolvePath(".", value);
802
+ if (seen.has(directory)) continue;
803
+ seen.add(directory);
804
+ directories.push(directory);
805
+ }
806
+ return directories;
807
+ }
808
+ /**
809
+ * Computes the stable cache key for a {@link GuideModule}. Directories normalize before
810
+ * joining, so equivalent module spellings share one key. The NUL separator
811
+ * cannot occur in filesystem-backed canonical-segment inventory keys, so no
812
+ * directory boundary can collide with directory text.
813
+ *
814
+ * @param module - The module scope to key
815
+ * @returns The normalized directories joined by NUL
816
+ *
817
+ * @example
818
+ * ```ts
819
+ * computeModuleKey(['src/core', 'src/browser']) // 'src/core\0src/browser'
820
+ * ```
821
+ */
822
+ function computeModuleKey(module) {
823
+ return normalizeDirectories(module).join("\0");
824
+ }
825
+ /**
826
+ * Selects the exact opaque file-inventory keys belonging under any canonical
827
+ * {@link GuideModule} directory, sorted. `'.'` selects canonical root-relative
828
+ * keys without accepting `/`, `./`, or `../` aliases. Every selected exact
829
+ * `index.ts` and every `.test.ts` key is excluded independent of scope order.
830
+ *
831
+ * @param files - The workspace file inventory, root-relative path → file text
832
+ * @param module - The module scope to filter to
833
+ * @returns The scope's file keys, root-relative and sorted
834
+ *
835
+ * @example
836
+ * ```ts
837
+ * selectModuleKeys({ 'src/core/Guide.ts': '', 'src/core/index.ts': '' }, 'src/core') // ['src/core/Guide.ts']
838
+ * ```
839
+ */
840
+ function selectModuleKeys(files, module) {
841
+ const dirs = normalizeDirectories(module);
842
+ const indexes = new Set(dirs.map((directory) => resolvePath(directory, "index.ts")));
843
+ const keys = [];
844
+ for (const key of Object.keys(files)) {
845
+ if (!hasCanonicalSegments(key)) continue;
846
+ if (!key.endsWith(".ts")) continue;
847
+ if (key.endsWith(".test.ts")) continue;
848
+ if (!dirs.some((directory) => directory === "." || key.startsWith(`${directory}/`)) || indexes.has(key)) continue;
849
+ keys.push(key);
850
+ }
851
+ return keys.sort();
852
+ }
853
+ /**
854
+ * Computes the bijection key for a surface symbol — `${keyword} ${name}` — so a symbol-set
855
+ * comparison diffs (name, keyword) pairs rather than names alone.
856
+ *
857
+ * @param symbol - The symbol to key
858
+ * @returns The `${keyword} ${name}` key
859
+ *
860
+ * @example
861
+ * ```ts
862
+ * computeSymbolKey({ name: 'Markdown', keyword: 'class' }) // 'class Markdown'
863
+ * ```
864
+ */
865
+ function computeSymbolKey(symbol) {
866
+ return `${symbol.keyword} ${symbol.name}`;
867
+ }
868
+ /**
869
+ * Finds the names present in `names` but absent from `source` — the set-difference
870
+ * behind a both-directions bijection assertion.
871
+ *
872
+ * @param names - The candidate names
873
+ * @param source - The names to compare against
874
+ * @returns The names in `names` that are not in `source`
875
+ *
876
+ * @example
877
+ * ```ts
878
+ * findMissing(['a', 'b'], ['a']) // ['b']
879
+ * ```
880
+ */
881
+ function findMissing(names, source) {
882
+ const existing = new Set(source);
883
+ return names.filter((name) => !existing.has(name));
884
+ }
885
+ /**
886
+ * Finds the fences whose language is absent from the caller's listed languages.
887
+ * Untagged fences are always returned because they have no language to list.
888
+ *
889
+ * @param fences - The guide fences to check
890
+ * @param languages - The listed language tags
891
+ * @returns The unlisted fences in input order
892
+ *
893
+ * @example
894
+ * ```ts
895
+ * findUnlisted([{ language: 'typescript', code: 'walk()' }], ['ts'])
896
+ * // [{ language: 'typescript', code: 'walk()' }]
897
+ * ```
898
+ */
899
+ function findUnlisted(fences, languages) {
900
+ const listed = new Set(languages);
901
+ return fences.filter((fence) => fence.language === void 0 || !listed.has(fence.language));
902
+ }
903
+ /**
904
+ * Finds the symbol-key set-difference between two symbol lists — `symbols` present but
905
+ * absent from `source`, compared by {@link computeSymbolKey} so a symbol can drift in
906
+ * neither name nor keyword.
907
+ *
908
+ * @param symbols - The candidate symbols
909
+ * @param source - The symbols to compare against
910
+ * @returns The symbol keys in `symbols` that are not in `source`
911
+ *
912
+ * @example
913
+ * ```ts
914
+ * findMissingSymbols([{ name: 'X', keyword: 'class' }], []) // ['class X']
915
+ * ```
916
+ */
917
+ function findMissingSymbols(symbols, source) {
918
+ return findMissing(symbols.map(computeSymbolKey), source.map(computeSymbolKey));
919
+ }
920
+ /**
921
+ * Finds the names in `names` that have no example — a fence containing the name at a
922
+ * word boundary in `fences`, or a membership in `examples`, both count as
923
+ * "has an example"; presence-only, fence and JSDoc content are never checked.
924
+ *
925
+ * @param names - The candidate symbol/member names to check
926
+ * @param fences - The guide's ```ts Patterns fence bodies to search
927
+ * @param examples - The names already known to carry an `@example` JSDoc block
928
+ * @returns The names in `names` with no fence mention and no `@example`
929
+ *
930
+ * @example
931
+ * ```ts
932
+ * findUnexampled(['walk', 'fold'], ['walk()'], []) // ['fold']
933
+ * findUnexampled(['walk'], [], ['walk']) // []
934
+ * ```
935
+ */
936
+ function findUnexampled(names, fences, examples) {
937
+ const exampled = new Set(examples);
938
+ return names.filter((name) => {
939
+ if (exampled.has(name)) return false;
940
+ const boundary = new RegExp(`\\b${escapeRegExp(name)}\\b`);
941
+ return !fences.some((fence) => boundary.test(fence));
942
+ });
943
+ }
944
+ /**
945
+ * Parses a fence's brace `import` statements into per-specifier imported identifier names —
946
+ * `import type`, mixed multiline braces, and `x as y` aliases all count, each alias resolved to
947
+ * the exported name `x` because that is the name the checked barrel surface must hold. Brace
948
+ * bindings only: a default, namespace, side-effect, or mixed `import Default, { named }`
949
+ * statement is not surfaced.
950
+ *
951
+ * @param fence - A ```ts Patterns fence's verbatim body text
952
+ * @returns One entry per `import ... from 'specifier'` statement, in fence order
953
+ *
954
+ * @example
955
+ * ```ts
956
+ * extractFenceImports("import { a, b as c } from 'x'\n") // [{ specifier: 'x', names: ['a', 'b'] }]
957
+ * ```
958
+ */
959
+ function extractFenceImports(fence) {
960
+ const results = [];
961
+ const pattern = /import\s+(?:type\s+)?\{([^}]*)\}\s*from\s*['"]([^'"]+)['"]/gs;
962
+ let match;
963
+ while ((match = pattern.exec(fence)) !== null) {
964
+ const body = match[1];
965
+ const specifier = match[2];
966
+ if (body === void 0 || specifier === void 0) continue;
967
+ const names = body.split(",").map((part) => part.trim()).filter((part) => part.length > 0).map((part) => part.replace(/^type\s+/, "")).map((part) => {
968
+ return part.match(/^(\w+)\s+as\s+\w+$/)?.[1] ?? part;
969
+ }).filter((part) => /^\w+$/.test(part));
970
+ results.push({
971
+ specifier,
972
+ names
973
+ });
974
+ }
975
+ return results;
976
+ }
977
+ /**
978
+ * Checks whether a guides-parity link check skips a link `href` — an external
979
+ * scheme ({@link EXTERNAL_SCHEMES}) or a bare in-document `#` anchor.
980
+ *
981
+ * @param href - The link destination
982
+ * @returns True if a link check leaves the href unresolved against the filesystem; false otherwise
983
+ *
984
+ * @example
985
+ * ```ts
986
+ * isExternalLink('https://example.com') // true
987
+ * isExternalLink('../helpers.ts') // false
988
+ * ```
989
+ */
990
+ function isExternalLink(href) {
991
+ if (href.startsWith("#")) return true;
992
+ return EXTERNAL_SCHEMES.some((scheme) => href.startsWith(scheme));
993
+ }
994
+ /**
995
+ * Resolves a relative `target` from a root-relative `directory`, normalizing
996
+ * forward-slash dot segments without filesystem or extension inference. A
997
+ * parent pops only a retained real component; every excess leading parent is
998
+ * preserved.
999
+ *
1000
+ * @param directory - The root-relative directory to resolve from
1001
+ * @param target - The relative target to resolve
1002
+ * @returns The normalized path, or `'.'` when no segment remains, retaining every excess parent
1003
+ *
1004
+ * @example
1005
+ * ```ts
1006
+ * resolvePath('guides/src', '../../src/core/helpers.ts') // 'src/core/helpers.ts'
1007
+ * resolvePath('.', '../../outside.ts') // '../../outside.ts'
1008
+ * ```
1009
+ */
1010
+ function resolvePath(directory, target) {
1011
+ const combined = `${directory}/${target}`;
1012
+ const segments = [];
1013
+ for (const segment of combined.split("/")) {
1014
+ if (segment === "" || segment === ".") continue;
1015
+ if (segment === "..") {
1016
+ const previous = segments[segments.length - 1];
1017
+ if (previous !== void 0 && previous !== "..") segments.pop();
1018
+ else segments.push(segment);
1019
+ continue;
1020
+ }
1021
+ segments.push(segment);
1022
+ }
1023
+ return segments.length === 0 ? "." : segments.join("/");
1024
+ }
1025
+ /**
1026
+ * Resolves a relative `target` from the directory containing a root-relative
1027
+ * declaring `file`. A slashless file belongs to the workspace root; path
1028
+ * reduction is delegated to {@link resolvePath}.
1029
+ *
1030
+ * @param file - The root-relative declaring file
1031
+ * @param target - The relative link destination to resolve
1032
+ * @returns The normalized path, retaining every excess leading parent
1033
+ *
1034
+ * @example
1035
+ * ```ts
1036
+ * resolveLink('guides/src/guide.md', '../../src/core/helpers.ts') // 'src/core/helpers.ts'
1037
+ * resolveLink('index.ts', './root.ts') // 'root.ts'
1038
+ * ```
1039
+ */
1040
+ function resolveLink(file, target) {
1041
+ const index = file.lastIndexOf("/");
1042
+ return resolvePath(index < 0 ? "." : file.slice(0, index), target);
1043
+ }
1044
+ /**
1045
+ * Finds the first code-span value by descending an inline node list, following
1046
+ * into `emphasis` / `link` / `image` children — the extraction rule behind a
1047
+ * Surface or Methods table row's first-column identifier.
1048
+ *
1049
+ * @param nodes - The inline nodes to search
1050
+ * @returns The first code span's literal text, or `undefined` when none is found
1051
+ *
1052
+ * @example
1053
+ * ```ts
1054
+ * findFirstCode([{ element: 'codeSpan', value: 'Markdown' }]) // 'Markdown'
1055
+ * ```
1056
+ */
1057
+ function findFirstCode(nodes) {
1058
+ for (const node of nodes) {
1059
+ if ((0, _orkestrel_markdown.isCodeSpanNode)(node)) return node.value;
1060
+ if ((0, _orkestrel_markdown.isEmphasisNode)(node) || (0, _orkestrel_markdown.isLinkNode)(node) || (0, _orkestrel_markdown.isImageNode)(node)) {
1061
+ const value = findFirstCode(node.children);
1062
+ if (value !== void 0) return value;
1063
+ }
1064
+ }
1065
+ }
1066
+ /**
1067
+ * Extracts the link hrefs within one table cell's inline content, in walk order.
1068
+ *
1069
+ * @param cell - The cell's inline nodes
1070
+ * @returns The cell's link hrefs, in walk order
1071
+ *
1072
+ * @example
1073
+ * ```ts
1074
+ * extractCellLinks([{ element: 'link', href: 'x.ts', children: [] }]) // ['x.ts']
1075
+ * ```
1076
+ */
1077
+ function extractCellLinks(cell) {
1078
+ const links = [];
1079
+ for (const node of (0, _orkestrel_markdown.walkNodes)({
1080
+ element: "paragraph",
1081
+ children: cell
1082
+ })) if ((0, _orkestrel_markdown.isLinkNode)(node)) links.push(node.href);
1083
+ return links;
1084
+ }
1085
+ /**
1086
+ * Returns the identifier prefix of a code-span text — everything before its first `<`,
1087
+ * trimmed. Guide cells and headings may annotate a generic-parameterized name
1088
+ * (`MarkdownHandler<TNode, T>`) for readability, but the bijection key is the
1089
+ * bare identifier the source scanner captures, so both sides must normalize
1090
+ * the same way.
1091
+ *
1092
+ * @param code - A code span's literal text
1093
+ * @returns The identifier prefix, or an empty string when `code` is empty
1094
+ *
1095
+ * @example
1096
+ * ```ts
1097
+ * normalizeIdentifier('MarkdownHandler<TNode, T>') // 'MarkdownHandler'
1098
+ * normalizeIdentifier('fold') // 'fold'
1099
+ * ```
1100
+ */
1101
+ function normalizeIdentifier(code) {
1102
+ const index = code.indexOf("<");
1103
+ return (index < 0 ? code : code.slice(0, index)).trim();
1104
+ }
1105
+ /**
1106
+ * Extracts compared inline content — the text of a table cell or candidate entity heading
1107
+ * flattened with every code span kept as a code span, so `` `Widget` `` reads the same wherever
1108
+ * the parity reader compares it. Emphasis drops to its text, a link drops to its text, an image
1109
+ * drops to its alternative text, and the markdown parser has already unescaped `\|`.
1110
+ *
1111
+ * @param cell - The inline nodes to flatten
1112
+ * @returns The compared text, code spans included
1113
+ *
1114
+ * @example
1115
+ * ```ts
1116
+ * extractCellText([{ element: 'codeSpan', value: 'Widget' }]) // '`Widget`'
1117
+ * ```
1118
+ */
1119
+ function extractCellText(cell) {
1120
+ let text = "";
1121
+ for (const node of cell) if ((0, _orkestrel_markdown.isCodeSpanNode)(node)) text += `\`${node.value}\``;
1122
+ else if ((0, _orkestrel_markdown.isEmphasisNode)(node) || (0, _orkestrel_markdown.isLinkNode)(node) || (0, _orkestrel_markdown.isImageNode)(node)) text += extractCellText(node.children);
1123
+ else text += (0, _orkestrel_markdown.flattenText)(node);
1124
+ return text;
1125
+ }
1126
+ /**
1127
+ * Builds one table cell's inline content from its compared text — the inverse of
1128
+ * {@link extractCellText}. A single-backtick run whose text carries no inner backtick and
1129
+ * neither a leading nor a trailing space becomes a code span; every other character, a backtick
1130
+ * included, becomes literal text, which `renderMarkdown` escapes so the rendered cell parses back
1131
+ * to the text this function was given.
1132
+ *
1133
+ * @remarks
1134
+ * The compared form spells every code span with one backtick per side, because
1135
+ * {@link extractCellText} emits `` `${value}` `` whatever delimiter the source used. A run this
1136
+ * function refuses is therefore a run no parsed cell produced, and emitting it as text is what
1137
+ * keeps the projection total: reading the rendered cell back through {@link extractCellText}
1138
+ * returns the text, so a rendered row and a hand-written row compare the same. A code span whose
1139
+ * own text carries a backtick or a boundary space is outside the compared form's fidelity in
1140
+ * either direction, and this function writes it as text rather than guessing a delimiter.
1141
+ *
1142
+ * @param text - The cell's compared text, as {@link extractCellText} returns it
1143
+ * @returns The cell's inline nodes, in text order
1144
+ *
1145
+ * @example
1146
+ * ```ts
1147
+ * buildCell('Holds a `Widget`.')
1148
+ * // [{ element: 'text', value: 'Holds a ' }, { element: 'codeSpan', value: 'Widget' }, { element: 'text', value: '.' }]
1149
+ * ```
1150
+ */
1151
+ function buildCell(text) {
1152
+ const nodes = [];
1153
+ const spans = /`([^`]+)`/g;
1154
+ let cursor = 0;
1155
+ let span;
1156
+ while ((span = spans.exec(text)) !== null) {
1157
+ const value = span[1];
1158
+ if (value === void 0) continue;
1159
+ if (span.index > cursor) nodes.push({
1160
+ element: "text",
1161
+ value: text.slice(cursor, span.index)
1162
+ });
1163
+ if (value.trim() === value) nodes.push({
1164
+ element: "codeSpan",
1165
+ value
1166
+ });
1167
+ else nodes.push({
1168
+ element: "text",
1169
+ value: span[0]
1170
+ });
1171
+ cursor = span.index + span[0].length;
1172
+ }
1173
+ if (cursor < text.length) nodes.push({
1174
+ element: "text",
1175
+ value: text.slice(cursor)
1176
+ });
1177
+ return (0, _orkestrel_markdown.coalesceText)(nodes);
1178
+ }
1179
+ /**
1180
+ * Finds the index of the column whose header text is `header` so a table's columns survive
1181
+ * reordering. The match is exact and case-sensitive — a table without that exact header
1182
+ * contributes nothing to the projection reading it, so a `## Surface` table with no
1183
+ * {@link SUMMARY} column leaves every row's summary absent and {@link findDrift} reports each
1184
+ * of those rows, never agreement.
1185
+ *
1186
+ * @param table - The table to inspect
1187
+ * @param header - The exact header text to locate, for example `Kind`
1188
+ * @returns The column's index, or `undefined` when the table has no such header
1189
+ *
1190
+ * @example
1191
+ * ```ts
1192
+ * findColumnIndex(table, 'Kind') // 1, or undefined
1193
+ * ```
1194
+ */
1195
+ function findColumnIndex(table, header) {
1196
+ for (let index = 0; index < table.header.length; index += 1) {
1197
+ const cell = table.header[index];
1198
+ if (cell !== void 0 && (0, _orkestrel_markdown.flattenText)({
1199
+ element: "paragraph",
1200
+ children: cell
1201
+ }).trim() === header) return index;
1202
+ }
1203
+ }
1204
+ /**
1205
+ * Extracts the module-scope exports declared in one file's source text — the declaration keys
1206
+ * {@link collectKeys} reports, each split back into the keyword and name that built it, deduped by
1207
+ * (keyword, name).
1208
+ *
1209
+ * @remarks
1210
+ * That one grammar matches `export (async)? (function(\*)?|class|const|interface|type) Name`; a
1211
+ * generator export (`export function* walk`) keys as the `function` keyword, its trailing `*`
1212
+ * stripped before the {@link ExportKeyword} check. Scanning uses {@link extractSourceLines}, so
1213
+ * comment and template payload is excluded while its uninterrupted column-zero head remains
1214
+ * required; preserved columns do not grant membership to leading/interrupted comment forms. The
1215
+ * population is exactly `type`, `interface`, `const`, `function`, and `class`; `enum` is outside
1216
+ * this reflection contract, not forbidden by general package policy.
1217
+ *
1218
+ * @param source - The file's source text
1219
+ * @returns The file's exported symbols, in file order
1220
+ *
1221
+ * @example
1222
+ * ```ts
1223
+ * extractExports('export class Markdown {}\n') // [{ name: 'Markdown', keyword: 'class' }]
1224
+ * extractExports('export function* walk() {}\n') // [{ name: 'walk', keyword: 'function' }]
1225
+ * ```
1226
+ */
1227
+ function extractExports(source) {
1228
+ const symbols = [];
1229
+ const seen = /* @__PURE__ */ new Set();
1230
+ const lines = extractSourceLines(source);
1231
+ const summaries = collectSummaries(lines);
1232
+ const keys = collectKeys(lines);
1233
+ for (const line of lines) {
1234
+ const key = keys.get(line);
1235
+ if (key === void 0 || seen.has(key)) continue;
1236
+ const space = key.indexOf(" ");
1237
+ const keyword = key.slice(0, Math.max(space, 0));
1238
+ if (!isExportKeyword(keyword)) continue;
1239
+ seen.add(key);
1240
+ const name = key.slice(space + 1);
1241
+ const summary = summaries.get(line);
1242
+ symbols.push({
1243
+ name,
1244
+ keyword,
1245
+ ...summary === void 0 ? {} : { summary }
1246
+ });
1247
+ }
1248
+ return symbols;
1249
+ }
1250
+ /**
1251
+ * Extracts the module-scope declarations lacking the `export` keyword in one file's source text —
1252
+ * the mirror image of {@link extractExports}'s grammar, anchored the same way (column 0, so an
1253
+ * indented inner declaration never matches).
1254
+ *
1255
+ * @remarks
1256
+ * Scans only the {@link ExportKeyword} keywords (`function` / `class` / `const` / `interface` /
1257
+ * `type`) — a module-scope `let` or `var` is outside this scanner's declaration-keyword grammar
1258
+ * and out of this check's contract. Scanning uses {@link extractSourceLines}, so comment and
1259
+ * template payload is excluded while its uninterrupted column-zero head remains required;
1260
+ * preserved columns do not widen membership. `enum` is likewise outside this reflection
1261
+ * population, not forbidden by general package policy.
1262
+ *
1263
+ * @param source - The file's source text
1264
+ * @returns The file's hidden (non-exported) symbols, in file order
1265
+ *
1266
+ * @example
1267
+ * ```ts
1268
+ * extractHidden('function secretHelper() {}\n') // [{ name: 'secretHelper', keyword: 'function' }]
1269
+ * extractHidden('export class X {}\n') // []
1270
+ * ```
1271
+ */
1272
+ function extractHidden(source) {
1273
+ const symbols = [];
1274
+ const seen = /* @__PURE__ */ new Set();
1275
+ const lines = extractSourceLines(source);
1276
+ const summaries = collectSummaries(lines);
1277
+ for (const line of lines) {
1278
+ if (line.code.startsWith("export ")) continue;
1279
+ const match = line.code.match(/^(?:async )?(function\*?|class|const|interface|type) (\w+)/);
1280
+ const rawKeyword = match?.[1];
1281
+ const name = match?.[2];
1282
+ const keyword = rawKeyword === void 0 ? void 0 : rawKeyword.replace(/\*$/, "");
1283
+ if (!(0, _orkestrel_contract.isNonEmptyString)(keyword) || !(0, _orkestrel_contract.isNonEmptyString)(name) || !isExportKeyword(keyword)) continue;
1284
+ const key = `${keyword} ${name}`;
1285
+ if (seen.has(key)) continue;
1286
+ seen.add(key);
1287
+ const summary = summaries.get(line);
1288
+ symbols.push({
1289
+ name,
1290
+ keyword,
1291
+ ...summary === void 0 ? {} : { summary }
1292
+ });
1293
+ }
1294
+ return symbols;
1295
+ }
1296
+ /**
1297
+ * Joins the declaration head starting at `start` into one space-separated
1298
+ * line, consuming lines until the first that ends with `{`.
1299
+ *
1300
+ * @param lines - The file's source lines
1301
+ * @param start - The index of the head's first line
1302
+ * @returns The joined head, or `undefined` when no line opens a body
1303
+ *
1304
+ * @example
1305
+ * ```ts
1306
+ * joinHead(['export class X {'], 0) // { text: 'export class X {', end: 0 }
1307
+ * ```
1308
+ */
1309
+ function joinHead(lines, start) {
1310
+ const parts = [];
1311
+ for (let index = start; index < lines.length; index += 1) {
1312
+ const line = lines[index];
1313
+ if (line === void 0) break;
1314
+ parts.push(index === start ? line.trimEnd() : line.trim());
1315
+ if (line.trimEnd().endsWith("{")) return {
1316
+ text: parts.join(" "),
1317
+ end: index
1318
+ };
1319
+ }
1320
+ }
1321
+ /**
1322
+ * Escapes every regex metacharacter in a literal string so it reads as text
1323
+ * inside a larger `RegExp` source rather than as syntax.
1324
+ *
1325
+ * @remarks
1326
+ * A caller-supplied name reaches a `RegExp` through this: {@link
1327
+ * findUnexampled} splices it into a word-boundary search, so a name carrying
1328
+ * `$`, `(`, `[`, or `.` matches that character literally instead of throwing or
1329
+ * matching text it does not name. Pure and total; never throws.
1330
+ *
1331
+ * @param value - The literal string to escape
1332
+ * @returns `value` with every regex metacharacter backslash-escaped
1333
+ *
1334
+ * @example
1335
+ * ```ts
1336
+ * escapeRegExp('A.B') // 'A\\.B'
1337
+ * new RegExp(`^${escapeRegExp('A.B')}$`).test('AxB') // false
1338
+ * ```
1339
+ */
1340
+ function escapeRegExp(value) {
1341
+ return value.replace(/[\\^$.*+?()[\]{}|]/g, "\\$&");
1342
+ }
1343
+ /**
1344
+ * Collects every `export class` / `export interface` declaration one file's source text declares,
1345
+ * each keyed `${keyword} ${name}` and carrying the body lines and the base identifiers read from
1346
+ * its own head, so a body and a heritage clause always come from the same declaration.
1347
+ *
1348
+ * @remarks
1349
+ * The whole file is projected once through {@link extractSourceLines} and every head is read from
1350
+ * that one projection, so a scope resolving many names reads each file once rather than once per
1351
+ * name. A head is a column-zero `export class` / `export interface` line, an oxfmt-wrapped
1352
+ * signature joined through {@link joinHead}, with an optional generic parameter list and an
1353
+ * optional heritage clause between the identifier and the opening `{`; the identifier is the head's
1354
+ * own run up to that list or clause, so it enters the key as literal text and no name reaches a
1355
+ * `RegExp`. Body lines are the raw source between the head and the first projected column-zero `}`,
1356
+ * keeping JSDoc evidence intact. Every balanced `<...>` span is removed from the head before its
1357
+ * `extends` clause is read, so a `T extends Base` type parameter is never a base and `Base<T>`
1358
+ * reads as `Base`; a class's `implements` clause and everything after it is excluded, and a
1359
+ * qualified base such as `namespace.Base` is returned verbatim. The first head of a key that opens
1360
+ * a column-zero close answers for that key: a head that opens none records nothing, and a later
1361
+ * head of a key already collected adds nothing.
1362
+ *
1363
+ * @param source - The file's source text to read
1364
+ * @returns One entry per collected declaration, keyed `${keyword} ${name}`
1365
+ *
1366
+ * @example
1367
+ * ```ts
1368
+ * collectDeclarations('export interface X extends Y {\n\twalk(): void\n}\n').get('interface X')
1369
+ * // { body: ['\twalk(): void'], bases: ['Y'] }
1370
+ * ```
1371
+ */
1372
+ function collectDeclarations(source) {
1373
+ const declarations = /* @__PURE__ */ new Map();
1374
+ const opener = /^export (?:class|interface) /;
1375
+ const grammar = /^export (class|interface) ([^\s<]+)(?:<.*>)?(?: .*)? \{$/;
1376
+ const lines = extractSourceLines(source);
1377
+ const projected = lines.map((line) => line.code);
1378
+ for (let index = 0; index < projected.length; index += 1) {
1379
+ const line = projected[index];
1380
+ if (line === void 0 || !opener.test(line)) continue;
1381
+ const head = joinHead(projected, index);
1382
+ if (head === void 0) continue;
1383
+ const declared = grammar.exec(head.text);
1384
+ const keyword = declared?.[1];
1385
+ const name = declared?.[2];
1386
+ if (keyword === void 0 || name === void 0) continue;
1387
+ const key = `${keyword} ${name}`;
1388
+ if (declarations.has(key)) continue;
1389
+ let depth = 0;
1390
+ let flat = "";
1391
+ for (const character of head.text.slice(`export ${key}`.length, -1)) if (character === "<") depth += 1;
1392
+ else if (character === ">") depth = Math.max(0, depth - 1);
1393
+ else if (depth === 0) flat += character;
1394
+ const clause = flat.replace(/\bimplements\b[\s\S]*$/, "").match(/\bextends\b([\s\S]*)$/)?.[1];
1395
+ const bases = clause === void 0 ? [] : clause.split(",").map((base) => base.trim()).filter(_orkestrel_contract.isNonEmptyString);
1396
+ for (let close = head.end + 1; close < projected.length; close += 1) {
1397
+ if (projected[close] !== "}") continue;
1398
+ declarations.set(key, {
1399
+ body: lines.slice(head.end + 1, close).map((record) => record.source),
1400
+ bases
1401
+ });
1402
+ break;
1403
+ }
1404
+ }
1405
+ return declarations;
1406
+ }
1407
+ /**
1408
+ * Selects the member lines declaring a callable member: plain, `async`, generator
1409
+ * (`*`), and optional (`records?(`) methods all count; getters, setters,
1410
+ * `static` members, and `#` privates never do (their keyword or `#` breaks
1411
+ * the `name(` shape). The grammar is {@link collectKeys}'s, read once over
1412
+ * {@link extractBodyLines}'s projection of the body, so commented method-like payload never
1413
+ * becomes eligible and each member keys to the owner head that projection supplies. Each member
1414
+ * carries its own doc block's description paragraph, read through {@link collectSummaries}; the
1415
+ * first declaration of a name answers for it.
1416
+ *
1417
+ * @param lines - A declaration's body lines
1418
+ * @returns The declared members, deduplicated by name and sorted by name
1419
+ *
1420
+ * @example
1421
+ * ```ts
1422
+ * extractMemberMethods(['\tmap(): void', '\tfilter(): void']) // [{ name: 'filter' }, { name: 'map' }]
1423
+ * ```
1424
+ */
1425
+ function extractMemberMethods(lines) {
1426
+ const methods = /* @__PURE__ */ new Map();
1427
+ const projected = extractBodyLines(lines);
1428
+ const summaries = collectSummaries(projected);
1429
+ const keys = collectKeys(projected);
1430
+ for (const line of projected) {
1431
+ const key = keys.get(line) ?? "";
1432
+ const dot = key.indexOf(".");
1433
+ if (dot < 0) continue;
1434
+ const name = key.slice(dot + 1);
1435
+ if (methods.has(name)) continue;
1436
+ const summary = summaries.get(line);
1437
+ methods.set(name, {
1438
+ name,
1439
+ ...summary === void 0 ? {} : { summary }
1440
+ });
1441
+ }
1442
+ return Array.from(methods.values()).sort((a, b) => a.name === b.name ? 0 : a.name < b.name ? -1 : 1);
1443
+ }
1444
+ /**
1445
+ * Selects the block nodes under the named `##` heading, up to the next `##`-or-higher
1446
+ * heading (or the document's end) — the section-scoping window `extractSurface` /
1447
+ * `extractMethods` walk over.
1448
+ *
1449
+ * @param document - The parsed guide document
1450
+ * @param heading - The `##` heading text to scope to, for example `Surface`
1451
+ * @returns The blocks belonging to that section, in document order
1452
+ *
1453
+ * @example
1454
+ * ```ts
1455
+ * selectSectionBlocks(document, 'Surface') // the blocks between `## Surface` and the next `##`
1456
+ * ```
1457
+ */
1458
+ function selectSectionBlocks(document, heading) {
1459
+ const blocks = [];
1460
+ let active = false;
1461
+ for (const block of document.children) {
1462
+ if ((0, _orkestrel_markdown.isHeadingNode)(block) && block.level <= 2) {
1463
+ if (block.level === 2 && (0, _orkestrel_markdown.flattenText)(block).trim() === heading) {
1464
+ active = true;
1465
+ continue;
1466
+ }
1467
+ if (active) break;
1468
+ }
1469
+ if (active) blocks.push(block);
1470
+ }
1471
+ return blocks;
1472
+ }
1473
+ /**
1474
+ * Extracts one `## Surface` table row's symbol — its column 0 code span as the name, its
1475
+ * {@link KIND} column as the keyword, and its {@link SUMMARY} column as the compared summary
1476
+ * when the table has that column. A row with no code-span name and a row whose `Kind` text is
1477
+ * no {@link ExportKeyword} have no symbol to key, so each returns `undefined`.
1478
+ *
1479
+ * @param table - The table to read
1480
+ * @param row - The index of the row within {@link TableNode.rows}
1481
+ * @returns The row's symbol, or `undefined` when the row keys none
1482
+ *
1483
+ * @example
1484
+ * ```ts
1485
+ * extractRowSymbol(table, 0) // { name: 'walk', keyword: 'function', summary: 'Walks the tree.' }
1486
+ * ```
1487
+ */
1488
+ function extractRowSymbol(table, row) {
1489
+ const cells = table.rows[row];
1490
+ if (cells === void 0) return void 0;
1491
+ const nameCell = cells[0];
1492
+ const rawName = nameCell === void 0 ? void 0 : findFirstCode(nameCell);
1493
+ const name = rawName === void 0 ? void 0 : normalizeIdentifier(rawName);
1494
+ if (name === void 0) return void 0;
1495
+ const column = findColumnIndex(table, KIND);
1496
+ const kindCell = column === void 0 ? void 0 : cells[column];
1497
+ const keyword = kindCell === void 0 ? "" : (0, _orkestrel_markdown.flattenText)({
1498
+ element: "paragraph",
1499
+ children: kindCell
1500
+ }).trim();
1501
+ if (!isExportKeyword(keyword)) return void 0;
1502
+ const summary = extractRowSummary(table, row);
1503
+ return {
1504
+ name,
1505
+ keyword,
1506
+ ...summary === void 0 ? {} : { summary }
1507
+ };
1508
+ }
1509
+ /**
1510
+ * Extracts one `## Methods` table row's entry — its column 0 code span as the name and its
1511
+ * {@link SUMMARY} column as the compared summary when the table has that column. A row with no
1512
+ * code-span name has no member to key, so it returns `undefined`.
1513
+ *
1514
+ * @param table - The table to read
1515
+ * @param row - The index of the row within {@link TableNode.rows}
1516
+ * @returns The row's entry, or `undefined` when the row keys none
1517
+ *
1518
+ * @example
1519
+ * ```ts
1520
+ * extractRowEntry(table, 0) // { name: 'walk', summary: 'Walks the tree.' }
1521
+ * ```
1522
+ */
1523
+ function extractRowEntry(table, row) {
1524
+ const cells = table.rows[row];
1525
+ if (cells === void 0) return void 0;
1526
+ const cell = cells[0];
1527
+ const rawName = cell === void 0 ? void 0 : findFirstCode(cell);
1528
+ const name = rawName === void 0 ? void 0 : normalizeIdentifier(rawName);
1529
+ if (name === void 0) return void 0;
1530
+ const summary = extractRowSummary(table, row);
1531
+ return {
1532
+ name,
1533
+ ...summary === void 0 ? {} : { summary }
1534
+ };
1535
+ }
1536
+ /**
1537
+ * Extracts one row's compared summary — its {@link SUMMARY} column read through
1538
+ * {@link extractCellText} and {@link normalizeSummary}. A table with no such column and a row
1539
+ * whose cell is empty each carry no summary and return `undefined` rather than an empty string,
1540
+ * so {@link findDrift} reports the absence.
1541
+ *
1542
+ * @param table - The table to read
1543
+ * @param row - The index of the row within {@link TableNode.rows}
1544
+ * @returns The row's compared summary, or `undefined` when it carries none
1545
+ *
1546
+ * @example
1547
+ * ```ts
1548
+ * extractRowSummary(table, 0) // 'Walks the tree.'
1549
+ * ```
1550
+ */
1551
+ function extractRowSummary(table, row) {
1552
+ const described = findColumnIndex(table, SUMMARY);
1553
+ const cells = table.rows[row];
1554
+ const cell = described === void 0 || cells === void 0 ? void 0 : cells[described];
1555
+ const summary = cell === void 0 ? "" : normalizeSummary(extractCellText(cell));
1556
+ return summary.length === 0 ? void 0 : summary;
1557
+ }
1558
+ /**
1559
+ * Extracts every `## Surface` identifier the guide documents — each table row's column 0
1560
+ * code span (the name) paired with its `Kind` column (located by header text), unioned with every
1561
+ * H3 entity heading whose trimmed compared inline content is exactly its backticked code-span
1562
+ * name, deduped by {@link computeSymbolKey}. A row with no code-span name has no name to key a
1563
+ * symbol on, so this reader skips it and {@link extractUnnamed} reports it; a row with an
1564
+ * unrecognized `Kind` text is skipped. A row also carries its {@link SUMMARY} column's compared
1565
+ * text when the table has that column; a table without it leaves every row's summary absent,
1566
+ * which {@link findDrift} reports.
1567
+ *
1568
+ * @remarks
1569
+ * The heading boundary compares {@link extractCellText} with the raw value from
1570
+ * {@link findFirstCode} before {@link normalizeIdentifier} strips a generic annotation.
1571
+ * Surrounding spaces, emphasis, and links preserve that identity. This reader refuses a heading
1572
+ * carrying any other visible text or an additional code span. Entries retain encounter order, and
1573
+ * the first-seen name + keyword wins: a genuine heading before its table row keeps the heading's
1574
+ * summary-less class entry, while a table row before that heading keeps its `Summary`.
1575
+ *
1576
+ * @param document - The parsed guide document
1577
+ * @returns The documented surface, in encounter order
1578
+ *
1579
+ * @example
1580
+ * ```ts
1581
+ * extractSurface(document) // [{ name: 'Markdown', keyword: 'class' }, ...]
1582
+ * ```
1583
+ */
1584
+ function extractSurface(document) {
1585
+ const symbols = [];
1586
+ const seen = /* @__PURE__ */ new Set();
1587
+ for (const block of selectSectionBlocks(document, SURFACE)) {
1588
+ if ((0, _orkestrel_markdown.isTableNode)(block)) {
1589
+ for (let row = 0; row < block.rows.length; row += 1) {
1590
+ const symbol = extractRowSymbol(block, row);
1591
+ if (symbol === void 0) continue;
1592
+ const key = computeSymbolKey(symbol);
1593
+ if (seen.has(key)) continue;
1594
+ seen.add(key);
1595
+ symbols.push(symbol);
1596
+ }
1597
+ continue;
1598
+ }
1599
+ if ((0, _orkestrel_markdown.isHeadingNode)(block) && block.level === 3) {
1600
+ const rawName = findFirstCode(block.children);
1601
+ if (rawName === void 0 || extractCellText(block.children).trim() !== `\`${rawName}\``) continue;
1602
+ const symbol = {
1603
+ name: normalizeIdentifier(rawName),
1604
+ keyword: "class"
1605
+ };
1606
+ const key = computeSymbolKey(symbol);
1607
+ if (seen.has(key)) continue;
1608
+ seen.add(key);
1609
+ symbols.push(symbol);
1610
+ }
1611
+ }
1612
+ return symbols;
1613
+ }
1614
+ /**
1615
+ * Extracts one {@link MethodGroup} per documented behavioral interface in `## Methods` —
1616
+ * an H4 with a code span sets the current interface, and the table immediately
1617
+ * following becomes its documented methods. A row with no code-span name has no name to key a
1618
+ * member on, so this reader skips it and {@link extractUnnamed} reports it. Each row carries its
1619
+ * {@link SUMMARY} column's compared text when the table has that column.
1620
+ *
1621
+ * @param document - The parsed guide document
1622
+ * @returns The documented method groups, in document order
1623
+ *
1624
+ * @example
1625
+ * ```ts
1626
+ * extractMethods(document) // [{ interface: 'MarkdownInterface', methods: [{ name: 'walk' }] }]
1627
+ * ```
1628
+ */
1629
+ function extractMethods(document) {
1630
+ const groups = [];
1631
+ for (const [table, name] of collectGroups(document)) {
1632
+ const methods = [];
1633
+ for (let row = 0; row < table.rows.length; row += 1) {
1634
+ const entry = extractRowEntry(table, row);
1635
+ if (entry !== void 0) methods.push(entry);
1636
+ }
1637
+ groups.push({
1638
+ interface: name,
1639
+ methods
1640
+ });
1641
+ }
1642
+ return groups;
1643
+ }
1644
+ /**
1645
+ * Collects each `## Methods` table keyed to the interface its `####` heading names — an H4
1646
+ * carrying a code span sets the current interface and the table immediately following claims it,
1647
+ * so a heading with no table and a table with no heading before it contribute nothing. The map
1648
+ * iterates in document order and a node keys itself, so a repeated identical table keeps its own
1649
+ * entry.
1650
+ *
1651
+ * @param document - The parsed guide document
1652
+ * @returns One entry per documented `## Methods` table, in document order
1653
+ *
1654
+ * @example
1655
+ * ```ts
1656
+ * collectGroups(document).values().next().value // 'GuideInterface'
1657
+ * ```
1658
+ */
1659
+ function collectGroups(document) {
1660
+ const groups = /* @__PURE__ */ new Map();
1661
+ let current;
1662
+ for (const block of selectSectionBlocks(document, METHODS)) {
1663
+ if ((0, _orkestrel_markdown.isHeadingNode)(block) && block.level === 4) {
1664
+ const rawInterface = findFirstCode(block.children);
1665
+ current = rawInterface === void 0 ? void 0 : normalizeIdentifier(rawInterface);
1666
+ continue;
1667
+ }
1668
+ if ((0, _orkestrel_markdown.isTableNode)(block) && current !== void 0) {
1669
+ groups.set(block, current);
1670
+ current = void 0;
1671
+ }
1672
+ }
1673
+ return groups;
1674
+ }
1675
+ /**
1676
+ * Extracts every `## Surface` or `## Methods` table row whose first cell carries no code span.
1677
+ * {@link extractSurface} and {@link extractMethods} skip such a row, because a row with no
1678
+ * name gives them nothing to key a symbol or a member on, and this projection is what reports
1679
+ * the skip. Each entry is the row's cells read through {@link extractCellText} and joined
1680
+ * by ` | `, so a reader can locate the row in the guide; the `## Surface` rows come first,
1681
+ * then the `## Methods` rows, each in document order. {@link GuideInterface.unnamed} caches it.
1682
+ *
1683
+ * @param document - The parsed guide document
1684
+ * @returns One entry per row carrying no code-span name
1685
+ *
1686
+ * @example
1687
+ * ```ts
1688
+ * extractUnnamed(document) // ['Widget | class | Represents a widget.']
1689
+ * ```
1690
+ */
1691
+ function extractUnnamed(document) {
1692
+ const unnamed = [];
1693
+ for (const heading of [SURFACE, METHODS]) for (const block of selectSectionBlocks(document, heading)) {
1694
+ if (!(0, _orkestrel_markdown.isTableNode)(block)) continue;
1695
+ for (const row of block.rows) {
1696
+ const cell = row[0];
1697
+ if (cell !== void 0 && findFirstCode(cell) !== void 0) continue;
1698
+ unnamed.push(row.map((content) => extractCellText(content)).join(" | "));
1699
+ }
1700
+ }
1701
+ return unnamed;
1702
+ }
1703
+ /**
1704
+ * Extracts every link href in the guide document, including table cells — a full,
1705
+ * depth-first walk of the whole AST.
1706
+ *
1707
+ * @param document - The parsed guide document
1708
+ * @returns Every link's href, in walk order
1709
+ *
1710
+ * @example
1711
+ * ```ts
1712
+ * extractLinks(document) // ['../../src/core/helpers.ts', 'https://example.com']
1713
+ * ```
1714
+ */
1715
+ function extractLinks(document) {
1716
+ const links = [];
1717
+ for (const node of (0, _orkestrel_markdown.walkNodes)(document)) if ((0, _orkestrel_markdown.isLinkNode)(node)) links.push(node.href);
1718
+ return links;
1719
+ }
1720
+ /**
1721
+ * Extracts the relative test links declared under `## Tests` — every link href found
1722
+ * within that section only.
1723
+ *
1724
+ * @param document - The parsed guide document
1725
+ * @returns The `## Tests` section's link hrefs, in walk order
1726
+ *
1727
+ * @example
1728
+ * ```ts
1729
+ * extractTests(document) // ['../../tests/src/core/Markdown.test.ts', ...]
1730
+ * ```
1731
+ */
1732
+ function extractTests(document) {
1733
+ const links = [];
1734
+ for (const block of selectSectionBlocks(document, TESTS)) for (const node of (0, _orkestrel_markdown.walkNodes)(block)) if ((0, _orkestrel_markdown.isLinkNode)(node)) links.push(node.href);
1735
+ return links;
1736
+ }
1737
+ /**
1738
+ * Returns the canonical body of one genuine JSDoc span — the `/**` opener, the closing
1739
+ * marker, each line's continuation marker, and the block's leading indentation removed,
1740
+ * with per-line trailing whitespace trimmed and the surrounding blank lines dropped. A
1741
+ * line's own indentation beyond the marker is kept, so an `@example` fence body keeps the
1742
+ * shape it was written in.
1743
+ *
1744
+ * @param comment - One complete genuine JSDoc span's raw text
1745
+ * @returns The span's unwrapped body
1746
+ *
1747
+ * @example
1748
+ * ```ts
1749
+ * normalizeComment('/**' + ' Creates a widget. *' + '/') // 'Creates a widget.'
1750
+ * ```
1751
+ */
1752
+ function normalizeComment(comment) {
1753
+ return unwrapComment(comment).join("\n").replace(/^\n+/, "").replace(/\n+$/, "");
1754
+ }
1755
+ /**
1756
+ * Unwraps one genuine JSDoc span into one content line per physical line — the `/**` opener,
1757
+ * the closing marker, each line's continuation marker, and per-line trailing whitespace removed,
1758
+ * with a line's own indentation past the marker kept. The result is aligned with
1759
+ * `comment.split('\n')`, so an index found in it addresses the same physical line of the span it
1760
+ * was built from, which is what lets a rewrite keep every line it does not replace.
1761
+ * {@link normalizeComment} is this projection joined and trimmed at its ends.
1762
+ *
1763
+ * @param comment - One complete genuine JSDoc span's raw text
1764
+ * @returns One content line per physical line of the span
1765
+ *
1766
+ * @example
1767
+ * ```ts
1768
+ * unwrapComment('/**' + '\n * Walks.\n *' + '/') // ['', 'Walks.', '']
1769
+ * ```
1770
+ */
1771
+ function unwrapComment(comment) {
1772
+ return (/^[ \t]*\/\*([\s\S]*?)\*\/[ \t]*$/.exec(comment)?.[1] ?? comment).split("\n").map((line) => line.replace(/^[ \t]*\*[ \t]?/, "").replace(/[ \t]+$/, ""));
1773
+ }
1774
+ /**
1775
+ * Returns the canonical compared form of a description paragraph. `{@link Target}` and
1776
+ * `{@link Target | label}` become the code token of the target text, or of the label where one is
1777
+ * written; a target's module part — the inline import form `import('./module.js').` and TSDoc's
1778
+ * package-qualified form `@scope/pkg#` — is dropped first. Every run of whitespace, including a
1779
+ * collapsed continuation marker and a line break, becomes one space, the ends trim, and a code
1780
+ * span keeps its delimiters while its own boundary whitespace goes. The guide's side and the
1781
+ * source's side read through this one form.
1782
+ *
1783
+ * @remarks
1784
+ * The clauses land in a fixed order, because each one decides what the next one sees. Every
1785
+ * single-backtick code span — one backtick per side, no inner backtick, no adjacent backtick —
1786
+ * is located first, so a delimiter the `{@link}` expansion inserts afterwards is never mistaken
1787
+ * for an authored one. The expansion then runs outside those spans
1788
+ * only, so a `{@link}` written inside a code span stays literal on both sides. Whitespace
1789
+ * collapses next, which is what makes a span wrapped across two physical lines comparable at
1790
+ * all. The boundary trim runs last, inside each located span: the markdown parser strips one
1791
+ * space from each end of a code span it reads, and this trim is the symmetric rule that meets
1792
+ * it, so `` ` | ` ``, `` ` |` ``, and `` `|` `` all reach `` `|` `` from either side. A span
1793
+ * whose content is all whitespace keeps one space, because a parser strips nothing from that
1794
+ * one.
1795
+ *
1796
+ * A target's module part is the inline import form `import('./module.js').` or TSDoc's
1797
+ * package-qualified form `@scope/pkg#`, and the expansion drops it, so a cross-file link and the
1798
+ * code token a guide cell documents it with reach the same text. A package qualifier carries `@`
1799
+ * or `/`; text before a `#` carrying neither is JSDoc's member reference, so `{@link Owner#member}`
1800
+ * and `{@link #member}` travel whole and a guide cell documents each as written. An unscoped
1801
+ * package name is spelled like an owner, so `{@link pkg#Name}` travels whole too — write the
1802
+ * scoped or the path form where a cell must drop the package. Everything after a module part
1803
+ * travels: `Owner.member` keeps its owner, and a dotted target no module part precedes is
1804
+ * untouched. A label is text rather than a target, so `{@link Target | label}` renders its label
1805
+ * whole.
1806
+ *
1807
+ * A code span delimited by more than one backtick is outside the compared form's representable
1808
+ * set and travels untouched, as does a code span whose own text carries a backtick: the form
1809
+ * spells every span with one backtick per side, so neither can be written back. A summary that
1810
+ * needs one of those constructs takes another shape: name the construct in prose rather than
1811
+ * expecting the comparison to converge it.
1812
+ *
1813
+ * @param text - A doc block's description paragraph, or a guide cell's flattened text
1814
+ * @returns The compared form of that text
1815
+ *
1816
+ * @example
1817
+ * ```ts
1818
+ * normalizeSummary('Creates a\n{@link Widget}.') // 'Creates a `Widget`.'
1819
+ * normalizeSummary("Reads {@link import('./widgets.js').Widget}.") // 'Reads `Widget`.'
1820
+ * normalizeSummary('Reads {@link @scope/widgets#Widget}.') // 'Reads `Widget`.'
1821
+ * normalizeSummary('Reads {@link Widget#render}.') // 'Reads `Widget#render`.'
1822
+ * normalizeSummary('cells joined by ` | `.') // 'cells joined by `|`.'
1823
+ * ```
1824
+ */
1825
+ function normalizeSummary(text) {
1826
+ const parts = text.split(/((?<!`)`[^`]+`(?!`))/);
1827
+ let normalized = "";
1828
+ for (let index = 0; index < parts.length; index += 1) {
1829
+ const part = parts[index] ?? "";
1830
+ if (index % 2 === 0) {
1831
+ normalized += part.replace(/\{@link\s+[^}|]*\|\s*([^}]*?)\s*\}/g, "`$1`").replace(/\{@link\s+(?:import\([^)]*\)\.|[^}|#\s]*[@/][^}|#\s]*#)?([^}|]*?)\s*\}/g, "`$1`");
1832
+ continue;
1833
+ }
1834
+ const value = part.slice(1, -1).replace(/\s+/g, " ").trim();
1835
+ normalized += `\`${value.length === 0 ? " " : value}\``;
1836
+ }
1837
+ return normalized.replace(/\s+/g, " ").trim();
1838
+ }
1839
+ /**
1840
+ * Wraps one paragraph into greedy lines no longer than `width` characters. Every run of
1841
+ * whitespace separates words, and a word longer than `width` takes its own line rather than
1842
+ * being split, so a long code token or URL survives the wrap intact.
1843
+ *
1844
+ * @param text - The paragraph to wrap
1845
+ * @param width - The greatest length a returned line may reach
1846
+ * @returns The wrapped lines, in order, or an empty list when `text` carries no word
1847
+ *
1848
+ * @example
1849
+ * ```ts
1850
+ * wrapText('one two three', 8) // ['one two', 'three']
1851
+ * ```
1852
+ */
1853
+ function wrapText(text, width) {
1854
+ const lines = [];
1855
+ let current = "";
1856
+ for (const word of text.split(/\s+/)) {
1857
+ if (word.length === 0) continue;
1858
+ if (current.length === 0) current = word;
1859
+ else if (current.length + 1 + word.length <= width) current += ` ${word}`;
1860
+ else {
1861
+ lines.push(current);
1862
+ current = word;
1863
+ }
1864
+ }
1865
+ if (current.length > 0) lines.push(current);
1866
+ return lines;
1867
+ }
1868
+ /**
1869
+ * Builds one genuine JSDoc span from its content lines — the inverse of {@link unwrapComment}.
1870
+ * Each line is emitted at `indent` behind a continuation marker, an empty line as the bare
1871
+ * marker so no line carries trailing whitespace, and the leading and trailing empty lines are
1872
+ * dropped because the opener and the closer take those physical lines.
1873
+ *
1874
+ * @param lines - The span's content lines, as {@link unwrapComment} returns them
1875
+ * @param indent - The whitespace the span opens at
1876
+ * @returns The span's raw text, opener and closer included
1877
+ *
1878
+ * @example
1879
+ * ```ts
1880
+ * buildComment(['Walks.'], '') // '/**\n * Walks.\n *' + '/'
1881
+ * ```
1882
+ */
1883
+ function buildComment(lines, indent) {
1884
+ const content = [...lines];
1885
+ while (content[0] === "") content.shift();
1886
+ while (content[content.length - 1] === "") content.pop();
1887
+ const raw = [`${indent}/**`];
1888
+ for (const line of content) raw.push(line.length === 0 ? `${indent} *` : `${indent} * ${line}`);
1889
+ raw.push(`${indent} */`);
1890
+ return raw.join("\n");
1891
+ }
1892
+ /**
1893
+ * Returns one doc block's unwrapped text with every fenced body replaced by aligned spaces,
1894
+ * so a tag search reads the block's structure and never its example code. A line opening with
1895
+ * three or more backticks or tildes opens a body, the first line opening with a run of the same
1896
+ * character at least as long closes it, an unclosed body runs to the end, and the marker lines
1897
+ * themselves stay. The projection preserves every line and every column, so an index found in
1898
+ * it addresses the same character of the text it was built from.
1899
+ *
1900
+ * @param text - One doc block's unwrapped text, as {@link normalizeComment} returns it
1901
+ * @returns The same text with each fenced body's characters replaced by spaces
1902
+ *
1903
+ * @example
1904
+ * ```ts
1905
+ * maskFences('@example\n~~~\n@decorator()\n~~~').split('\n')[2] // ' '
1906
+ * ```
1907
+ */
1908
+ function maskFences(text) {
1909
+ const masked = [];
1910
+ let marker;
1911
+ for (const line of text.split("\n")) {
1912
+ const fence = /^[ \t]*(`{3,}|~{3,})/.exec(line)?.[1];
1913
+ if (marker === void 0) {
1914
+ masked.push(line);
1915
+ marker = fence;
1916
+ continue;
1917
+ }
1918
+ const closing = fence !== void 0 && fence.startsWith(marker);
1919
+ masked.push(closing ? line : " ".repeat(line.length));
1920
+ if (closing) marker = void 0;
1921
+ }
1922
+ return masked.join("\n");
1923
+ }
1924
+ /**
1925
+ * Extracts every eligible genuine JSDoc block paired with the physical record it documents.
1926
+ *
1927
+ * @remarks
1928
+ * An opener is eligible only when it is the first non-whitespace source material of its record; a
1929
+ * leading whitespace-separated span chain is last-span authoritative; intervening source material
1930
+ * severs association, while a leading JSDoc on the next record replaces pending state. Any other
1931
+ * next physical record is returned once and consumes it. This parser walks aligned records without
1932
+ * rescanning source syntax or applying declaration/member grammar, and every reader of a doc
1933
+ * block's text — the description paragraph, the `@example` blocks, the member summaries — reads it
1934
+ * through this one walk.
1935
+ *
1936
+ * @param lines - Aligned physical source-line records
1937
+ * @returns One record per documented physical line, in source order
1938
+ *
1939
+ * @example
1940
+ * ```ts
1941
+ * extractSourceComments(extractSourceLines('/**' + ' Walks. *' + '/\nexport function walk() {}'))
1942
+ * // [{ text: 'Walks.', line: the `export function walk() {}` SourceLine }]
1943
+ * ```
1944
+ */
1945
+ function extractSourceComments(lines) {
1946
+ const comments = [];
1947
+ let block = false;
1948
+ let eligible = false;
1949
+ let span = [];
1950
+ let pending;
1951
+ for (const line of lines) {
1952
+ const projection = line.jsdoc;
1953
+ const first = projection?.indexOf("/**") ?? -1;
1954
+ if (pending !== void 0) {
1955
+ if (!block && first >= 0 && line.source.slice(0, first).trim() === "") pending = void 0;
1956
+ else {
1957
+ comments.push({
1958
+ text: pending,
1959
+ line
1960
+ });
1961
+ pending = void 0;
1962
+ }
1963
+ }
1964
+ if (projection === void 0) continue;
1965
+ let cursor = 0;
1966
+ if (block) {
1967
+ const close = projection.indexOf("*/");
1968
+ const end = close < 0 ? projection.length : close + 2;
1969
+ span.push(projection.slice(0, end));
1970
+ if (close < 0) continue;
1971
+ block = false;
1972
+ const opener = projection.indexOf("/**", close + 2);
1973
+ const endOfGap = opener < 0 ? line.source.length : opener;
1974
+ const whitespace = line.source.slice(close + 2, endOfGap).trim() === "";
1975
+ if (opener < 0) {
1976
+ pending = eligible && whitespace ? normalizeComment(span.join("\n")) : void 0;
1977
+ continue;
1978
+ }
1979
+ eligible = eligible && whitespace;
1980
+ span = [];
1981
+ cursor = opener;
1982
+ } else {
1983
+ if (first < 0) continue;
1984
+ eligible = line.source.slice(0, first).trim() === "";
1985
+ span = [];
1986
+ cursor = first;
1987
+ }
1988
+ while (cursor < projection.length) {
1989
+ const close = projection.indexOf("*/", cursor + 2);
1990
+ const end = close < 0 ? projection.length : close + 2;
1991
+ span.push(projection.slice(cursor, end));
1992
+ if (close < 0) {
1993
+ block = true;
1994
+ break;
1995
+ }
1996
+ const opener = projection.indexOf("/**", close + 2);
1997
+ const endOfGap = opener < 0 ? line.source.length : opener;
1998
+ const whitespace = line.source.slice(close + 2, endOfGap).trim() === "";
1999
+ if (opener < 0) {
2000
+ pending = eligible && whitespace ? normalizeComment(span.join("\n")) : void 0;
2001
+ break;
2002
+ }
2003
+ eligible = eligible && whitespace;
2004
+ span = [];
2005
+ cursor = opener;
2006
+ }
2007
+ }
2008
+ return comments;
2009
+ }
2010
+ /**
2011
+ * Collects the description paragraph of every documented physical record — a doc block's
2012
+ * text before its first block tag, in {@link normalizeSummary}'s compared form — keyed by the
2013
+ * record it documents. A record whose block carries no description contributes no entry, so
2014
+ * an absent summary stays absent rather than becoming an empty string.
2015
+ *
2016
+ * @param lines - Aligned physical source-line records
2017
+ * @returns One entry per documented record carrying a description paragraph
2018
+ *
2019
+ * @example
2020
+ * ```ts
2021
+ * collectSummaries(extractSourceLines('/**' + ' Walks. *' + '/\nexport function walk() {}')).size // 1
2022
+ * ```
2023
+ */
2024
+ function collectSummaries(lines) {
2025
+ const summaries = /* @__PURE__ */ new Map();
2026
+ for (const comment of extractSourceComments(lines)) {
2027
+ const tag = maskFences(comment.text).search(/^[ \t]*@\w/m);
2028
+ const summary = normalizeSummary(tag < 0 ? comment.text : comment.text.slice(0, tag));
2029
+ if (summary.length > 0) summaries.set(comment.line, summary);
2030
+ }
2031
+ return summaries;
2032
+ }
2033
+ /**
2034
+ * Extracts the aligned physical records of a declaration's body, read inside an owner head this
2035
+ * function supplies, so a callable member in the body carries the `Owner.member` key
2036
+ * {@link collectKeys} reports for it, and that head's own record opens the projection. A body
2037
+ * read on its own carries no head, and the member grammar attaches a member to the head
2038
+ * enclosing it.
2039
+ *
2040
+ * @remarks
2041
+ * The supplied head is an `export interface` line, so the projection opens with that head's own
2042
+ * record and every body line follows it in order. A column-zero `}` among the body lines closes
2043
+ * the supplied head and leaves every later member unkeyed; a body {@link extractDeclaration}
2044
+ * returns carries none, because that reader ends a body at the first one.
2045
+ *
2046
+ * @param lines - A declaration's body lines
2047
+ * @returns The supplied head's record, then one record per body line
2048
+ *
2049
+ * @example
2050
+ * ```ts
2051
+ * extractBodyLines(['\twalk(): void'])[1]?.code // '\twalk(): void'
2052
+ * ```
2053
+ */
2054
+ function extractBodyLines(lines) {
2055
+ return extractSourceLines(["export interface Owner {", ...lines].join("\n"));
2056
+ }
2057
+ /**
2058
+ * Collects the compared key of every physical record a key names — a {@link computeSymbolKey}
2059
+ * symbol key for a column-zero `export` declaration head, an `Owner.member` key for a one-tab
2060
+ * callable member inside one — keyed by the record itself. The owner closes at the first
2061
+ * column-zero `}` or at a column-zero `export` declaration carrying another keyword, and a
2062
+ * record no key names contributes no entry.
2063
+ *
2064
+ * @remarks
2065
+ * This is the package's one key grammar, and each keyed reader projects its own part back out of
2066
+ * it: {@link extractExports} splits a declaration key at its one space,
2067
+ * {@link extractMemberMethods} and {@link extractExampleMethods} split a member key at its dot,
2068
+ * and {@link locateComment} matches a caller's key against the whole map. A change to the head
2069
+ * shape or to the member shape reaches every one of them at once.
2070
+ *
2071
+ * An owner opens at a column-zero `export class` or `export interface` head and closes at the
2072
+ * 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,
2073
+ * because a member belongs to the head enclosing it. Reading runs over {@link extractSourceLines}'s
2074
+ * projection, so a head or
2075
+ * a member written inside a comment or a template literal keys nothing.
2076
+ *
2077
+ * @param lines - Aligned physical source-line records
2078
+ * @returns One entry per record a key names, in file order
2079
+ *
2080
+ * @example
2081
+ * ```ts
2082
+ * const keys = collectKeys(extractSourceLines('export class Widget {\n\twalk(): void\n}'))
2083
+ * Array.from(keys.values()) // ['class Widget', 'Widget.walk']
2084
+ * ```
2085
+ */
2086
+ function collectKeys(lines) {
2087
+ const keys = /* @__PURE__ */ new Map();
2088
+ let owner;
2089
+ for (const line of lines) {
2090
+ const head = /^export (?:async )?(function\*?|class|const|interface|type) (\w+)/.exec(line.code);
2091
+ const keyword = head?.[1]?.replace(/\*$/, "");
2092
+ const name = head?.[2];
2093
+ if ((0, _orkestrel_contract.isNonEmptyString)(keyword) && (0, _orkestrel_contract.isNonEmptyString)(name) && isExportKeyword(keyword)) {
2094
+ keys.set(line, computeSymbolKey({
2095
+ name,
2096
+ keyword
2097
+ }));
2098
+ owner = keyword === "class" || keyword === "interface" ? name : void 0;
2099
+ continue;
2100
+ }
2101
+ if (line.code === "}") {
2102
+ owner = void 0;
2103
+ continue;
2104
+ }
2105
+ const member = /^\t(?:async )?\*?(\w+)\??(?:<.*>)?\(/.exec(line.code)?.[1];
2106
+ if (owner !== void 0 && (0, _orkestrel_contract.isNonEmptyString)(member)) keys.set(line, `${owner}.${member}`);
2107
+ }
2108
+ return keys;
2109
+ }
2110
+ /**
2111
+ * Collects the `@example` blocks one doc block's unwrapped text carries, each named for the
2112
+ * declaration or member the block documents. The text after the tag becomes the block's
2113
+ * `title`; a body opening with a fence contributes that fence's language and its verbatim
2114
+ * body, and a body with no fence contributes its own trimmed text as the code.
2115
+ *
2116
+ * @param comment - One doc block's unwrapped text, as {@link normalizeComment} returns it
2117
+ * @param name - The declaration or member the block documents
2118
+ * @returns The block's `@example` entries, in block order
2119
+ *
2120
+ * @example
2121
+ * ```ts
2122
+ * collectExamples('@example Walking\n```ts\nwalk()\n```', 'walk')
2123
+ * // [{ name: 'walk', title: 'Walking', code: 'walk()', language: 'ts' }]
2124
+ * ```
2125
+ */
2126
+ function collectExamples(comment, name) {
2127
+ const examples = [];
2128
+ const masked = maskFences(comment);
2129
+ const tags = /^[ \t]*@example(?=[ \t]|$)[ \t]*(.*)$/gm;
2130
+ let tag;
2131
+ while ((tag = tags.exec(masked)) !== null) {
2132
+ const title = (tag[1] ?? "").trim();
2133
+ const start = tag.index + tag[0].length;
2134
+ const rest = comment.slice(start).replace(/^\n/, "");
2135
+ const next = masked.slice(start).replace(/^\n/, "").search(/^[ \t]*@\w+/m);
2136
+ const body = (next < 0 ? rest : rest.slice(0, next)).replace(/^\n+/, "").replace(/\n+$/, "");
2137
+ const fence = /^```(\S*)\n([\s\S]*?)\n?```/.exec(body);
2138
+ const language = fence?.[1] ?? "";
2139
+ const code = fence?.[2] ?? body;
2140
+ examples.push({
2141
+ name,
2142
+ ...title.length === 0 ? {} : { title },
2143
+ code,
2144
+ ...language.length === 0 ? {} : { language }
2145
+ });
2146
+ }
2147
+ return examples;
2148
+ }
2149
+ /**
2150
+ * Extracts the `@example` blocks carried by the exported declaration heads in one file's source
2151
+ * text, each named for the declaration its block documents. Shared adjacency comes from
2152
+ * {@link extractSourceComments} and each block is read by {@link collectExamples}; head
2153
+ * membership is the {@link collectKeys} key of the documented record under every keyword that
2154
+ * grammar admits at column zero, so comment and template payload cannot qualify and the head
2155
+ * grammar stays the one every reader here shares. A member key carries a dot and a head key
2156
+ * does not, so a member's block belongs to {@link extractExampleMethods} instead. A head
2157
+ * carrying several blocks contributes each.
2158
+ *
2159
+ * @param source - The file's source text
2160
+ * @returns The exported declaration heads' `@example` blocks, in file order, deduplicated by name and title
2161
+ *
2162
+ * @example
2163
+ * ```ts
2164
+ * const block = ['/**', ' * @example', ' * new Widget()', ' *' + '/', 'export class Widget {}', ''].join('\n')
2165
+ * extractExamples(block) // [{ name: 'Widget', code: 'new Widget()' }]
2166
+ * extractExamples('export class Widget {}\n') // []
2167
+ * ```
2168
+ */
2169
+ function extractExamples(source) {
2170
+ const examples = [];
2171
+ const seen = /* @__PURE__ */ new Set();
2172
+ const lines = extractSourceLines(source);
2173
+ const keys = collectKeys(lines);
2174
+ for (const comment of extractSourceComments(lines)) {
2175
+ const key = keys.get(comment.line);
2176
+ if (key === void 0 || key.includes(".")) continue;
2177
+ const name = key.slice(key.indexOf(" ") + 1);
2178
+ for (const example of collectExamples(comment.text, name)) {
2179
+ const entry = `${name}\n${example.title ?? ""}`;
2180
+ if (seen.has(entry)) continue;
2181
+ seen.add(entry);
2182
+ examples.push(example);
2183
+ }
2184
+ }
2185
+ return examples;
2186
+ }
2187
+ /**
2188
+ * Extracts the `@example` blocks carried by the callable members of a declaration body (per
2189
+ * {@link collectKeys}' grammar, the same one {@link extractMemberMethods} reads), each named for
2190
+ * the member its block documents. Shared adjacency comes from {@link extractSourceComments} and
2191
+ * each block is read by {@link collectExamples}; member membership is the key
2192
+ * {@link extractBodyLines}'s projection gives the documented record.
2193
+ *
2194
+ * @param lines - A declaration's body lines
2195
+ * @returns The members' `@example` blocks, deduplicated by name and title and sorted by name
2196
+ *
2197
+ * @example
2198
+ * ```ts
2199
+ * extractExampleMethods(['\t/**', '\t * @example', '\t * walk()', '\t *' + '/', '\twalk(): void'])
2200
+ * // [{ name: 'walk', code: 'walk()' }]
2201
+ * ```
2202
+ */
2203
+ function extractExampleMethods(lines) {
2204
+ const examples = [];
2205
+ const seen = /* @__PURE__ */ new Set();
2206
+ const projected = extractBodyLines(lines);
2207
+ const keys = collectKeys(projected);
2208
+ for (const comment of extractSourceComments(projected)) {
2209
+ const key = keys.get(comment.line) ?? "";
2210
+ const dot = key.indexOf(".");
2211
+ if (dot < 0) continue;
2212
+ const name = key.slice(dot + 1);
2213
+ for (const example of collectExamples(comment.text, name)) {
2214
+ const entry = `${name}\n${example.title ?? ""}`;
2215
+ if (seen.has(entry)) continue;
2216
+ seen.add(entry);
2217
+ examples.push(example);
2218
+ }
2219
+ }
2220
+ return examples.sort((a, b) => a.name === b.name ? 0 : a.name < b.name ? -1 : 1);
2221
+ }
2222
+ /**
2223
+ * Extracts every fenced code block anywhere in the guide document. A full AST walk
2224
+ * includes fences nested inside blockquotes and lists, and the same walk carries each
2225
+ * fence's nearest preceding heading as its `title` — the key an `@example` block pairs on.
2226
+ * A heading's text is flattened, so a title written with a code span pairs with a plain
2227
+ * `@example` title.
2228
+ *
2229
+ * @param document - The parsed guide document
2230
+ * @returns Every fence's language, verbatim code, and title, in document order
2231
+ *
2232
+ * @example
2233
+ * ```ts
2234
+ * extractFences(document) // [{ language: 'ts', code: "import { X } from './x.js'\nX()" }]
2235
+ * ```
2236
+ */
2237
+ function extractFences(document) {
2238
+ return Array.from(collectFences(document).values());
2239
+ }
2240
+ /**
2241
+ * Collects each fenced code block keyed by its own node, paired with the {@link GuideFence}
2242
+ * {@link extractFences} reports for it — the node-addressed form a rewrite needs, so a caller
2243
+ * that located a fence by title can read that node's source region back from the parser. The map
2244
+ * iterates in document order and a node keys itself, so a repeated identical fence keeps its own
2245
+ * entry.
2246
+ *
2247
+ * @param document - The parsed guide document
2248
+ * @returns One entry per fenced code block, in document order
2249
+ *
2250
+ * @example
2251
+ * ```ts
2252
+ * Array.from(collectFences(document).values()) // [{ language: 'ts', code: 'walk()' }]
2253
+ * ```
2254
+ */
2255
+ function collectFences(document) {
2256
+ const fences = /* @__PURE__ */ new Map();
2257
+ let title = "";
2258
+ for (const node of (0, _orkestrel_markdown.walkNodes)(document)) {
2259
+ if ((0, _orkestrel_markdown.isHeadingNode)(node)) {
2260
+ title = (0, _orkestrel_markdown.flattenText)(node).trim();
2261
+ continue;
2262
+ }
2263
+ if ((0, _orkestrel_markdown.isCodeBlockNode)(node)) fences.set(node, {
2264
+ language: node.lang,
2265
+ code: node.code,
2266
+ ...title.length === 0 ? {} : { title }
2267
+ });
2268
+ }
2269
+ return fences;
2270
+ }
2271
+ /**
2272
+ * Extracts the guide's tagline — the text of the blockquote following the document's H1,
2273
+ * with every code span kept as a code span and whitespace collapsed. A heading before the
2274
+ * blockquote ends the window, so a blockquote elsewhere in the document is not the tagline.
2275
+ *
2276
+ * @param document - The parsed guide document
2277
+ * @returns The tagline, or `undefined` when no blockquote follows an H1 before the next heading
2278
+ *
2279
+ * @example
2280
+ * ```ts
2281
+ * extractTagline(document) // 'A pure, I/O-free guides-parity toolkit'
2282
+ * ```
2283
+ */
2284
+ function extractTagline(document) {
2285
+ let opened = false;
2286
+ for (const block of document.children) {
2287
+ if ((0, _orkestrel_markdown.isHeadingNode)(block)) {
2288
+ if (opened) return void 0;
2289
+ opened = block.level === 1;
2290
+ continue;
2291
+ }
2292
+ if (!opened || !(0, _orkestrel_markdown.isBlockquoteNode)(block)) continue;
2293
+ const text = normalizeSummary(block.children.filter(_orkestrel_markdown.isParagraphNode).map((paragraph) => extractCellText(paragraph.children)).join(" "));
2294
+ return text.length === 0 ? void 0 : text;
2295
+ }
2296
+ }
2297
+ /**
2298
+ * Computes the drift between one compared key's guide text and source text. A pair agrees
2299
+ * only when both sides carry the same text, and every other state is a drift: guide text
2300
+ * alone reports the guide's side, source text alone reports the source's, and neither side
2301
+ * carrying text reports the key by itself. A side carrying no text is absent from the result,
2302
+ * so a documented symbol with no doc block reports as a drift naming the guide's text alone,
2303
+ * and a row a table has no `Summary` column for against a declaration with no doc block
2304
+ * reports as `{ key }`.
2305
+ *
2306
+ * @param key - The compared pair's key
2307
+ * @param category - The compared site the drift came from
2308
+ * @param guide - The guide's text there, or `undefined` when it carries none
2309
+ * @param source - The source's text there, or `undefined` when it carries none
2310
+ * @returns The drift, or `undefined` when both sides carry the same text
2311
+ *
2312
+ * @example
2313
+ * ```ts
2314
+ * computeDrift('function walk', 'summary', 'Walks the tree.', 'Walks a tree.')
2315
+ * // { key: 'function walk', category: 'summary', guide: 'Walks the tree.', source: 'Walks a tree.' }
2316
+ * ```
2317
+ */
2318
+ function computeDrift(key, category, guide, source) {
2319
+ if (guide !== void 0 && guide === source) return void 0;
2320
+ return {
2321
+ key,
2322
+ category,
2323
+ ...guide === void 0 ? {} : { guide },
2324
+ ...source === void 0 ? {} : { source }
2325
+ };
2326
+ }
2327
+ /**
2328
+ * Compares documented and declared membership exactly after sorting copies, preserving duplicates.
2329
+ *
2330
+ * @param spec - The guide inventory key the finding belongs to
2331
+ * @param name - The declaration whose membership is compared
2332
+ * @param documented - The documented member names
2333
+ * @param declared - The declared member names
2334
+ * @returns The membership finding, or `undefined` when the sorted populations match
2335
+ *
2336
+ * @example Compare declaration membership
2337
+ * ```ts
2338
+ * import { compareMembership } from '@orkestrel/guide'
2339
+ *
2340
+ * compareMembership('guides/widget.md', 'WidgetInterface', ['open'], ['open']) // undefined
2341
+ * ```
2342
+ */
2343
+ function compareMembership(spec, name, documented, declared) {
2344
+ const left = [...documented].sort();
2345
+ const right = [...declared].sort();
2346
+ if (JSON.stringify(left) === JSON.stringify(right)) return void 0;
2347
+ return {
2348
+ spec,
2349
+ text: `${spec} ${name} documents ${JSON.stringify(left)} and declares ${JSON.stringify(right)}.`
2350
+ };
2351
+ }
2352
+ /**
2353
+ * Computes a category-separated identity for a guide finding.
2354
+ *
2355
+ * @param spec - The guide inventory key the drift belongs to
2356
+ * @param drift - The categorized disagreement
2357
+ * @returns The inventory key, category, and compared key separated by line feeds
2358
+ *
2359
+ * @example Identify categorized drift
2360
+ * ```ts
2361
+ * import { identifyDrift } from '@orkestrel/guide'
2362
+ *
2363
+ * identifyDrift('guides/widget.md', { category: 'summary', key: 'function open' })
2364
+ * // 'guides/widget.md\nsummary\nfunction open'
2365
+ * ```
2366
+ */
2367
+ function identifyDrift(spec, drift) {
2368
+ return `${spec}\n${drift.category}\n${drift.key}`;
2369
+ }
2370
+ /**
2371
+ * Formats present parity text as a JSON string and absent text as `absent`.
2372
+ *
2373
+ * @param value - The compared side's text, or `undefined` when absent
2374
+ * @returns The developer-facing side text
2375
+ *
2376
+ * @example Format a parity side
2377
+ * ```ts
2378
+ * import { formatSide } from '@orkestrel/guide'
2379
+ *
2380
+ * formatSide('Walks.') // '"Walks."'
2381
+ * formatSide(undefined) // 'absent'
2382
+ * ```
2383
+ */
2384
+ function formatSide(value) {
2385
+ return value === void 0 ? "absent" : JSON.stringify(value);
2386
+ }
2387
+ /**
2388
+ * Formats a categorized drift with its guide and source sides.
2389
+ *
2390
+ * @param drift - The categorized disagreement to format
2391
+ * @returns The complete developer-facing drift text
2392
+ *
2393
+ * @example Format categorized drift
2394
+ * ```ts
2395
+ * import { formatDrift } from '@orkestrel/guide'
2396
+ *
2397
+ * formatDrift({ category: 'summary', key: 'function walk', guide: 'Walks.', source: 'Walks a tree.' })
2398
+ * // 'summary function walk: guide "Walks." source "Walks a tree."'
2399
+ * ```
2400
+ */
2401
+ function formatDrift(drift) {
2402
+ return `${drift.category} ${drift.key}: guide ${formatSide(drift.guide)} source ${formatSide(drift.source)}`;
2403
+ }
2404
+ /**
2405
+ * Finds every disagreement between a guide and the source it documents, naming both sites:
2406
+ * each `## Surface` row against its declaration's description paragraph, each `## Methods`
2407
+ * row against its member's, and the first titled guide fence of a heading against the
2408
+ * `@example` block of the same title. An example's compared text is its language on the first
2409
+ * line and its body beneath, so a fence that names another language drifts on its own.
2410
+ *
2411
+ * @remarks
2412
+ * Only a pair present on both sides is compared, so a symbol, a member, or a title one side
2413
+ * lacks entirely is left to the bijection checks that own it and is never reported twice.
2414
+ * {@link computeDrift} rules each compared pair, so a pair whose sides carry different text, a
2415
+ * pair where one side carries none, and a pair where neither side carries text are all drift.
2416
+ * The pairing is per title across the whole document, not per heading: the first fence a title
2417
+ * reaches is the compared one, and every later fence of that title is outside the comparison,
2418
+ * whether it sits under the same heading or under a second heading of the same text.
2419
+ *
2420
+ * @param guide - The parsed guide
2421
+ * @param source - The reflected source the guide documents
2422
+ * @returns One entry per disagreement: Surface rows, then Methods rows, then examples
2423
+ *
2424
+ * @example
2425
+ * ```ts
2426
+ * findDrift(guide, source) // [{ key: 'function walk', category: 'summary', guide: 'Walks.', source: 'Walks a tree.' }]
2427
+ * ```
2428
+ */
2429
+ function findDrift(guide, source) {
2430
+ const drifts = [];
2431
+ const declared = new Map(source.surface().map((symbol) => [computeSymbolKey(symbol), symbol]));
2432
+ for (const symbol of guide.surface()) {
2433
+ const key = computeSymbolKey(symbol);
2434
+ const match = declared.get(key);
2435
+ if (match === void 0) continue;
2436
+ const drift = computeDrift(key, "summary", symbol.summary, match.summary);
2437
+ if (drift !== void 0) drifts.push(drift);
2438
+ }
2439
+ for (const group of guide.methods()) {
2440
+ const members = new Map(source.methods(group.interface).map((entry) => [entry.name, entry]));
2441
+ for (const entry of group.methods) {
2442
+ const member = members.get(entry.name);
2443
+ if (member === void 0) continue;
2444
+ const drift = computeDrift(`${group.interface}.${entry.name}`, "summary", entry.summary, member.summary);
2445
+ if (drift !== void 0) drifts.push(drift);
2446
+ }
2447
+ }
2448
+ const examples = collectTitles(guide, source);
2449
+ const compared = /* @__PURE__ */ new Set();
2450
+ for (const fence of guide.fences()) {
2451
+ if (fence.title === void 0 || compared.has(fence.title)) continue;
2452
+ compared.add(fence.title);
2453
+ const example = examples.get(fence.title);
2454
+ if (example === void 0) continue;
2455
+ const drift = computeDrift(fence.title, "example", `${fence.language ?? ""}\n${fence.code}`, `${example.language ?? ""}\n${example.code}`);
2456
+ if (drift !== void 0) drifts.push(drift);
2457
+ }
2458
+ return drifts;
2459
+ }
2460
+ /**
2461
+ * Collects the titled `@example` blocks a guide's documented surface reaches — the module's
2462
+ * exported declaration heads, plus the own members of every documented `class` and `interface` —
2463
+ * keyed by title, the first block of a title answering for it.
2464
+ *
2465
+ * @param guide - The parsed guide naming the documented declarations
2466
+ * @param source - The reflected source to read the blocks from
2467
+ * @returns One entry per distinct `@example` title
2468
+ *
2469
+ * @example
2470
+ * ```ts
2471
+ * collectTitles(guide, source).get('Walk a tree') // { name: 'walk', title: 'Walk a tree', code: 'walk()' }
2472
+ * ```
2473
+ */
2474
+ function collectTitles(guide, source) {
2475
+ const titled = /* @__PURE__ */ new Map();
2476
+ const owners = guide.surface().filter((symbol) => symbol.keyword === "class" || symbol.keyword === "interface");
2477
+ const examples = [...source.examples(), ...owners.flatMap((symbol) => source.examples(symbol.name))];
2478
+ for (const example of examples) {
2479
+ if (example.title === void 0 || titled.has(example.title)) continue;
2480
+ titled.set(example.title, example);
2481
+ }
2482
+ return titled;
2483
+ }
2484
+ /**
2485
+ * Builds a copy of `table` with one cell's inline content rebuilt from `text` through
2486
+ * {@link buildCell}. Every other cell keeps its own nodes, so a rewrite touches the one cell it
2487
+ * names and the header and the alignment row travel unchanged.
2488
+ *
2489
+ * @param table - The table to copy
2490
+ * @param row - The index of the row to rewrite within {@link TableNode.rows}
2491
+ * @param column - The index of the cell to rewrite within that row
2492
+ * @param text - The cell's new compared text
2493
+ * @returns The rewritten table
2494
+ *
2495
+ * @example
2496
+ * ```ts
2497
+ * buildTable(table, 0, 2, 'Walks the tree.').rows[0]?.[2] // [{ element: 'text', value: 'Walks the tree.' }]
2498
+ * ```
2499
+ */
2500
+ function buildTable(table, row, column, text) {
2501
+ return {
2502
+ element: "table",
2503
+ header: table.header,
2504
+ rows: table.rows.map((cells, index) => index === row ? cells.map((cell, position) => position === column ? buildCell(text) : cell) : cells),
2505
+ align: table.align
2506
+ };
2507
+ }
2508
+ /**
2509
+ * Builds the fenced code block one `@example` block renders as — its code inside a fence
2510
+ * carrying its language, and an untagged fence when the block names none.
2511
+ *
2512
+ * @param example - The block to render
2513
+ * @returns The fence node
2514
+ *
2515
+ * @example
2516
+ * ```ts
2517
+ * buildFence({ name: 'walk', code: 'walk()', language: 'ts' }) // { element: 'codeBlock', code: 'walk()', lang: 'ts' }
2518
+ * ```
2519
+ */
2520
+ function buildFence(example) {
2521
+ return {
2522
+ element: "codeBlock",
2523
+ code: example.code,
2524
+ ...example.language === void 0 ? {} : { lang: example.language }
2525
+ };
2526
+ }
2527
+ /**
2528
+ * Splices `replacement` into `source` over the region `span` addresses, and returns the result.
2529
+ * The text before the region and the text after it travel byte for byte, so a rewrite that
2530
+ * addresses one node's region changes nothing else in the document.
2531
+ *
2532
+ * @param source - The text to rewrite
2533
+ * @param span - The half-open region to replace: the region `MarkdownInterface.span` reports
2534
+ * for a markdown node, or the one {@link locateComment} reports for a doc block
2535
+ * @param replacement - The text to write over that region
2536
+ * @returns The rewritten text
2537
+ *
2538
+ * @example
2539
+ * ```ts
2540
+ * spliceSpan('one two three', { start: 4, end: 7 }, 'TWO') // 'one TWO three'
2541
+ * ```
2542
+ */
2543
+ function spliceSpan(source, span, replacement) {
2544
+ return source.slice(0, span.start) + replacement + source.slice(span.end);
2545
+ }
2546
+ /**
2547
+ * Replaces one compared cell in a guide's text and returns the whole guide back. `key` names the
2548
+ * row the way {@link findDrift} names it — a {@link computeSymbolKey} key for a `## Surface` row,
2549
+ * an `Owner.member` key for a `## Methods` row — and the row's {@link SUMMARY} cell becomes
2550
+ * `summary`. Only the table's own source region is rewritten, so every byte outside it travels
2551
+ * unchanged; a key reaching no cell returns `undefined`, and a row already carrying the summary
2552
+ * returns the guide byte for byte.
2553
+ *
2554
+ * @remarks
2555
+ * A row the key does not reach, a table carrying no {@link SUMMARY} column, and a document whose
2556
+ * parse recorded no region for the table are each a miss, and a miss returns `undefined` rather
2557
+ * than throwing, so a caller reports the key it could not place — the one meaning `undefined`
2558
+ * carries in every replacer here. A row already carrying `summary` returns the guide byte for
2559
+ * byte, because a rewrite would re-pad the whole table for no change; that identity reads both
2560
+ * sides through {@link normalizeSummary}, so a caller passing text the compared form still moves
2561
+ * is a fixed point on the second run rather than a row rewritten forever. The rewritten table
2562
+ * renders one-space padded whatever padding it carried, so the checkout's formatter re-aligns it.
2563
+ *
2564
+ * @param guide - The guide's markdown source
2565
+ * @param key - The compared key naming the row
2566
+ * @param summary - The row's new compared text
2567
+ * @returns The guide's text with that cell replaced, or `undefined` when the key reaches no cell
2568
+ *
2569
+ * @example
2570
+ * ```ts
2571
+ * replaceCell('## Surface\n\n| Name | Kind | Summary |\n| --- | --- | --- |\n| `walk` | function | Walks. |', 'function walk', 'Walks a tree.')
2572
+ * // '## Surface\n\n| Name | Kind | Summary |\n| --- | --- | --- |\n| `walk` | function | Walks a tree. |'
2573
+ * ```
2574
+ */
2575
+ function replaceCell(guide, key, summary) {
2576
+ const markdown = (0, _orkestrel_markdown.createMarkdown)(guide);
2577
+ const document = markdown.document;
2578
+ let located;
2579
+ let index = -1;
2580
+ for (const block of selectSectionBlocks(document, SURFACE)) {
2581
+ if (located !== void 0 || !(0, _orkestrel_markdown.isTableNode)(block)) continue;
2582
+ for (let row = 0; row < block.rows.length && located === void 0; row += 1) {
2583
+ const symbol = extractRowSymbol(block, row);
2584
+ if (symbol === void 0 || computeSymbolKey(symbol) !== key) continue;
2585
+ located = block;
2586
+ index = row;
2587
+ }
2588
+ }
2589
+ for (const [table, owner] of collectGroups(document)) {
2590
+ if (located !== void 0) break;
2591
+ for (let row = 0; row < table.rows.length && located === void 0; row += 1) {
2592
+ const entry = extractRowEntry(table, row);
2593
+ if (entry === void 0 || `${owner}.${entry.name}` !== key) continue;
2594
+ located = table;
2595
+ index = row;
2596
+ }
2597
+ }
2598
+ if (located === void 0) return void 0;
2599
+ const column = findColumnIndex(located, SUMMARY);
2600
+ if (column === void 0) return void 0;
2601
+ if ((extractRowSummary(located, index) ?? "") === normalizeSummary(summary)) return guide;
2602
+ const span = markdown.span(located);
2603
+ if (span === void 0) return void 0;
2604
+ return spliceSpan(guide, span, (0, _orkestrel_markdown.renderMarkdown)(buildTable(located, index, column, summary)));
2605
+ }
2606
+ /**
2607
+ * Replaces one titled fence in a guide's text and returns the whole guide back. The first fence
2608
+ * carrying `title` — the pairing {@link findDrift} compares on — takes `example`'s language and
2609
+ * code. Only the fence's own source region is rewritten, so every byte outside it travels
2610
+ * unchanged; a title no fence carries returns `undefined`, and a fence already carrying that
2611
+ * body returns the guide byte for byte.
2612
+ *
2613
+ * @remarks
2614
+ * A title no fence carries and a document whose parse recorded no region for the fence are each a
2615
+ * miss, and a miss returns `undefined` rather than throwing — the one meaning `undefined` carries
2616
+ * in every replacer here. A fence already carrying that language and code returns the guide
2617
+ * byte for byte. A later fence of the same title is outside the pairing and is never rewritten,
2618
+ * which is the rule {@link findDrift} compares under.
2619
+ *
2620
+ * @param guide - The guide's markdown source
2621
+ * @param title - The heading text the fence pairs on
2622
+ * @param example - The block whose language and code the fence takes
2623
+ * @returns The guide's text with that fence replaced, or `undefined` when no fence carries the title
2624
+ *
2625
+ * @example
2626
+ * ```ts
2627
+ * replaceFence(guide, 'Walk', { name: 'walk', title: 'Walk', code: 'walk()', language: 'ts' })
2628
+ * // the guide's text with the fence under its `### Walk` heading carrying `walk()`
2629
+ * ```
2630
+ */
2631
+ function replaceFence(guide, title, example) {
2632
+ const markdown = (0, _orkestrel_markdown.createMarkdown)(guide);
2633
+ let located;
2634
+ let current;
2635
+ for (const [node, fence] of collectFences(markdown.document)) {
2636
+ if (located !== void 0 || fence.title !== title) continue;
2637
+ located = node;
2638
+ current = fence;
2639
+ }
2640
+ if (located === void 0 || current === void 0) return void 0;
2641
+ if (current.code === example.code && current.language === example.language) return guide;
2642
+ const span = markdown.span(located);
2643
+ if (span === void 0) return void 0;
2644
+ return spliceSpan(guide, span, (0, _orkestrel_markdown.renderMarkdown)(buildFence(example)));
2645
+ }
2646
+ /**
2647
+ * Replaces one doc block's description paragraph with `summary` and returns the whole block back.
2648
+ * The paragraph is the block's text before its first block tag, and it re-wraps inside `width`;
2649
+ * the blank line before the first tag, every tag line, the block's indentation, and its
2650
+ * continuation markers all survive. A block already carrying the summary returns byte for byte,
2651
+ * and a text that is no doc block and a summary carrying no word each return `undefined`.
2652
+ *
2653
+ * @remarks
2654
+ * A miss returns `undefined`, the one meaning `undefined` carries in every replacer here, so a
2655
+ * caller reports the block it could not rewrite. Text that opens with no
2656
+ * `/**` is no doc block: a single-star `/*` comment reaches this function only by a caller's
2657
+ * mistake, and reshaping it into a doc block would be a silent edit. A `summary` carrying no word
2658
+ * names no paragraph to write, and deleting the block's description on that argument would erase
2659
+ * documentation on the strength of an absent value — a caller with nothing to write writes
2660
+ * nothing.
2661
+ *
2662
+ * A block already carrying `summary` returns byte for byte, which is what keeps a propagation
2663
+ * that finds no drift from rewriting the file: a doc block's own wrapping is not recoverable from
2664
+ * its text, so re-wrapping an unchanged paragraph would move most blocks this package's source
2665
+ * carries. That identity reads both sides through {@link normalizeSummary}, and it holds for a
2666
+ * block carrying no tag as much as for a block carrying several. A block written on one physical
2667
+ * line stays on one line while `summary` still fits inside `width`, and expands otherwise.
2668
+ *
2669
+ * `width` counts characters from the line's first, a tab counting as one, so a wrapped line reads
2670
+ * `${indent} * ${text}` and never passes that count. A caller whose formatter measures a tab as
2671
+ * more than one column passes a smaller width rather than taking the default.
2672
+ *
2673
+ * @param comment - One complete genuine JSDoc span's raw text, as it sits in the file
2674
+ * @param summary - The block's new description paragraph
2675
+ * @param width - The character budget a re-wrapped line stays inside. Default: {@link WRAP_WIDTH}
2676
+ * @returns The block's raw text with that paragraph replaced, or `undefined` for a text that is
2677
+ * no doc block and for a `summary` carrying no word
2678
+ *
2679
+ * @example
2680
+ * ```ts
2681
+ * replaceSummary('/**' + ' Walks. *' + '/', 'Walks a tree.') // '/**' + ' Walks a tree. *' + '/'
2682
+ * ```
2683
+ */
2684
+ function replaceSummary(comment, summary, width = 100) {
2685
+ if (!/^[ \t]*\/\*\*/.test(comment)) return void 0;
2686
+ const content = unwrapComment(comment);
2687
+ const indent = /^[ \t]*/.exec(comment)?.[0] ?? "";
2688
+ const wrapped = wrapText(summary, width - indent.length - 3);
2689
+ if (wrapped.length === 0) return void 0;
2690
+ const masked = maskFences(content.join("\n")).split("\n");
2691
+ let tag = -1;
2692
+ for (let index = 0; index < masked.length && tag < 0; index += 1) if (/^[ \t]*@\w/.test(masked[index] ?? "")) tag = index;
2693
+ if (normalizeSummary(content.slice(0, tag < 0 ? content.length : tag).join("\n")) === normalizeSummary(summary)) return comment;
2694
+ const tail = tag < 0 ? [] : content.slice(tag);
2695
+ if (tail.length === 0 && wrapped.length === 1 && content.length === 1) {
2696
+ const single = `${indent}/** ${wrapped[0] ?? ""} */`;
2697
+ if (single.length <= width) return single;
2698
+ }
2699
+ const lines = [...wrapped];
2700
+ if (tail.length > 0) lines.push("");
2701
+ return buildComment([...lines, ...tail], indent);
2702
+ }
2703
+ /**
2704
+ * Replaces the body of one titled `@example` tag in a doc block's raw text and returns the whole
2705
+ * block back. The tag carrying `example`'s title takes a fence of its language and its code;
2706
+ * every other tag, the description paragraph, the block's indentation, and its continuation
2707
+ * markers all survive. A text that is no doc block, a title no tag carries, and a language or
2708
+ * code the emitted three-backtick fence cannot enclose or the doc block cannot hold each return
2709
+ * `undefined`.
2710
+ *
2711
+ * @remarks
2712
+ * A miss returns `undefined`, the one meaning `undefined` carries in every replacer here, so a
2713
+ * caller reports the block it could not rewrite. Text that opens with no
2714
+ * `/**` is no doc block, for the reason {@link replaceSummary} states. A block carrying no
2715
+ * `@example` tag of that title has nowhere to write, so an untitled tag and a tag carrying
2716
+ * another title are each left alone, and an `example` naming no title misses a block whose tags
2717
+ * all carry one. Code carrying a run of three or more backticks is a body the emitted fence
2718
+ * cannot enclose: the fence is three backticks, {@link maskFences} ends a body at the first line
2719
+ * opening a run at least as long, and {@link collectExamples} reads to the first such run
2720
+ * whatever column it sits at, so writing that body would truncate it and turn a following
2721
+ * `@`-line into a tag. A language or code carrying the doc-comment terminator is a body the
2722
+ * block itself cannot hold: the terminator closes the block where it lands and the file stops
2723
+ * parsing there. Refusing keeps the rewrite total over the bodies it can spell.
2724
+ *
2725
+ * A tag already carrying that language and code returns byte for byte. {@link maskFences} keeps
2726
+ * the current body's own lines out of the tag search, so a fenced body carrying a tag-shaped line
2727
+ * does not end the body early. The body ends at its last line carrying text, so the blank line
2728
+ * separating it from the next tag survives.
2729
+ *
2730
+ * @param comment - One complete genuine JSDoc span's raw text, as it sits in the file
2731
+ * @param example - The block whose language and code the tag's body takes
2732
+ * @returns The block's raw text with that body replaced, or `undefined` for a text that is no
2733
+ * doc block, for a title no `@example` tag carries, and for a language or code the emitted
2734
+ * fence cannot enclose or the doc block cannot hold — a body carrying the doc-comment terminator
2735
+ *
2736
+ * @example
2737
+ * ```ts
2738
+ * replaceExample('/**' + '\n * @example Walk\n * old()\n *' + '/', { name: 'walk', title: 'Walk', code: 'walk()', language: 'ts' })
2739
+ * // the same block, its `@example Walk` body now a fence tagged `ts` carrying `walk()`
2740
+ * ```
2741
+ */
2742
+ function replaceExample(comment, example) {
2743
+ if (!/^[ \t]*\/\*\*/.test(comment)) return void 0;
2744
+ if ([example.language ?? "", ...example.code.split("\n")].some((line) => line.includes("```") || line.includes("*/"))) return void 0;
2745
+ const content = unwrapComment(comment);
2746
+ const masked = maskFences(content.join("\n")).split("\n");
2747
+ const title = example.title ?? "";
2748
+ let start = -1;
2749
+ for (let index = 0; index < masked.length && start < 0; index += 1) {
2750
+ const tag = /^[ \t]*@example(?=[ \t]|$)[ \t]*(.*)$/.exec(masked[index] ?? "");
2751
+ if (tag !== null && (tag[1] ?? "").trim() === title) start = index;
2752
+ }
2753
+ if (start < 0) return void 0;
2754
+ const current = collectExamples(content.join("\n"), example.name).find((entry) => (entry.title ?? "") === title);
2755
+ if (current !== void 0 && current.code === example.code && current.language === example.language) return comment;
2756
+ let end = content.length;
2757
+ for (let index = start + 1; index < masked.length && end === content.length; index += 1) if (/^[ \t]*@\w/.test(masked[index] ?? "")) end = index;
2758
+ while (end > start + 1 && (content[end - 1] ?? "").length === 0) end -= 1;
2759
+ const indent = /^[ \t]*/.exec(comment)?.[0] ?? "";
2760
+ const body = [
2761
+ `\`\`\`${example.language ?? ""}`,
2762
+ ...example.code.split("\n"),
2763
+ "```"
2764
+ ];
2765
+ return buildComment([
2766
+ ...content.slice(0, start + 1),
2767
+ ...body,
2768
+ ...content.slice(end)
2769
+ ], indent);
2770
+ }
2771
+ /**
2772
+ * Locates the doc block a compared key attaches to inside one file's text and returns the block's
2773
+ * own character region, so a caller can `slice` the block, rewrite it through
2774
+ * {@link replaceSummary} or {@link replaceExample}, and write the result back through
2775
+ * {@link spliceSpan}. `key` names the pair the way {@link findDrift} names it — a
2776
+ * {@link computeSymbolKey} key for a declaration, an `Owner.member` key for an interface or class
2777
+ * member; the region covers the block's own indentation, and no block carrying the key returns
2778
+ * `undefined`.
2779
+ *
2780
+ * @remarks
2781
+ * Attachment is {@link extractSourceComments}'s, not a second reading of the file: that walk
2782
+ * pairs each eligible block with the physical record it documents, and this function keeps the
2783
+ * record {@link collectKeys} gives `key`. The keys are that one grammar's — the map
2784
+ * {@link extractExports} and {@link extractMemberMethods} each read their own part out of — so
2785
+ * this function runs no head pattern, no member pattern, and no owner-close rule of its own, and
2786
+ * a change to any of them reaches the locator too. Every block {@link collectSummaries} reports
2787
+ * a summary for is reachable by its key, and a block carrying only block tags is reachable too although it carries no summary.
2788
+ * A block it misses is one the comparison never had: a block a blank line separates from its
2789
+ * declaration attaches to the blank line, and a block written inside a template literal or a
2790
+ * string is no genuine span at all. The first block whose record carries the key answers for it,
2791
+ * as the first declaration of a name does everywhere else.
2792
+ *
2793
+ * The region runs from the start of the opener's line, the block's indentation included, to the
2794
+ * character past its closing marker — the raw text {@link replaceSummary} and
2795
+ * {@link replaceExample} each document as the span "as it sits in the file", so a caller slices,
2796
+ * rewrites, and splices with no adjustment and the rewrite keeps the indentation it found. A
2797
+ * block that source material precedes on its own line starts at the opener instead. The region
2798
+ * is read off the aligned JSDoc projection rather than searched for in the text, so an opener
2799
+ * written inside a string never yields one, and line offsets come from
2800
+ * {@link extractSourceLines}'s own records under its stated LF-or-CRLF terminator rule, so a
2801
+ * CRLF file reports the offsets its own bytes carry.
2802
+ *
2803
+ * @param text - One file's whole source text
2804
+ * @param key - The compared key naming the declaration or the member
2805
+ * @returns The block's half-open character region, or `undefined` when no block carries the key
2806
+ *
2807
+ * @example
2808
+ * ```ts
2809
+ * const text = '/**' + ' Walks. *' + '/\nexport function walk(): void {}\n'
2810
+ * locateComment(text, 'function walk') // { start: 0, end: 13 }
2811
+ * ```
2812
+ */
2813
+ function locateComment(text, key) {
2814
+ const lines = extractSourceLines(text);
2815
+ const keys = collectKeys(lines);
2816
+ const offsets = [];
2817
+ const positions = /* @__PURE__ */ new Map();
2818
+ let offset = 0;
2819
+ for (let index = 0; index < lines.length; index += 1) {
2820
+ const line = lines[index];
2821
+ if (line === void 0) continue;
2822
+ offsets.push(offset);
2823
+ positions.set(line, index);
2824
+ const after = offset + line.source.length;
2825
+ offset = after + (text.startsWith("\r\n", after) ? 2 : 1);
2826
+ }
2827
+ for (const comment of extractSourceComments(lines)) {
2828
+ if (keys.get(comment.line) !== key) continue;
2829
+ const close = (positions.get(comment.line) ?? 0) - 1;
2830
+ const closing = lines[close]?.jsdoc;
2831
+ const end = closing === void 0 ? -1 : closing.lastIndexOf("*/");
2832
+ if (end < 0) continue;
2833
+ let first = close;
2834
+ while (first > 0 && lines[first - 1]?.jsdoc !== void 0) first -= 1;
2835
+ let inside = false;
2836
+ let line = -1;
2837
+ let column = -1;
2838
+ for (let index = first; index <= close; index += 1) {
2839
+ const projection = lines[index]?.jsdoc ?? "";
2840
+ let cursor = 0;
2841
+ while (cursor < projection.length) {
2842
+ const at = projection.indexOf(inside ? "*/" : "/**", cursor);
2843
+ if (at < 0) break;
2844
+ if (!inside) {
2845
+ line = index;
2846
+ column = at;
2847
+ }
2848
+ cursor = at + (inside ? 2 : 3);
2849
+ inside = !inside;
2850
+ }
2851
+ }
2852
+ if (line < 0) continue;
2853
+ const start = (lines[line]?.source ?? "").slice(0, column).trim() === "" ? 0 : column;
2854
+ return {
2855
+ start: (offsets[line] ?? 0) + start,
2856
+ end: (offsets[close] ?? 0) + end + 2
2857
+ };
2858
+ }
2859
+ }
2860
+ //#endregion
2861
+ //#region src/core/Guide.ts
2862
+ /**
2863
+ * Presents a pure, structured view over one parsed guide — the documented
2864
+ * projections (`sections` / `tagline` / `surface` / `methods` / `unnamed` / `links` /
2865
+ * `tests` / `fences`) are extracted once at construction and cached.
2866
+ *
2867
+ * @remarks
2868
+ * Parses `source` once through `@orkestrel/markdown` and never touches the
2869
+ * filesystem — `Guide` reads only the markdown text it is given and records
2870
+ * nothing about where the guide came from. Every accessor returns the same
2871
+ * cached, readonly array on every call.
2872
+ *
2873
+ * @example
2874
+ * ```ts
2875
+ * import { Guide } from '@orkestrel/guide'
2876
+ *
2877
+ * const guide = new Guide('## Surface\n\n| Name | Kind |\n| --- | --- |\n| `X` | class |')
2878
+ * guide.surface() // [{ name: 'X', keyword: 'class' }]
2879
+ * ```
2880
+ */
2881
+ var Guide = class {
2882
+ #sections;
2883
+ #tagline;
2884
+ #surface;
2885
+ #methods;
2886
+ #unnamed;
2887
+ #links;
2888
+ #tests;
2889
+ #fences;
2890
+ constructor(source) {
2891
+ const document = (0, _orkestrel_markdown.createMarkdown)(source).document;
2892
+ this.#sections = document.children.filter(_orkestrel_markdown.isHeadingNode).filter((heading) => heading.level === 2).map((heading) => (0, _orkestrel_markdown.flattenText)(heading).trim());
2893
+ this.#tagline = extractTagline(document);
2894
+ this.#surface = extractSurface(document);
2895
+ this.#methods = extractMethods(document);
2896
+ this.#unnamed = extractUnnamed(document);
2897
+ this.#links = extractLinks(document);
2898
+ this.#tests = extractTests(document);
2899
+ this.#fences = extractFences(document);
2900
+ }
2901
+ sections() {
2902
+ return this.#sections;
2903
+ }
2904
+ tagline() {
2905
+ return this.#tagline;
2906
+ }
2907
+ surface() {
2908
+ return this.#surface;
2909
+ }
2910
+ methods() {
2911
+ return this.#methods;
2912
+ }
2913
+ unnamed() {
2914
+ return this.#unnamed;
2915
+ }
2916
+ links() {
2917
+ return this.#links;
2918
+ }
2919
+ tests() {
2920
+ return this.#tests;
2921
+ }
2922
+ fences() {
2923
+ return this.#fences;
2924
+ }
2925
+ };
2926
+ //#endregion
2927
+ //#region src/core/sources/Source.ts
2928
+ /**
2929
+ * Reflects, as a pure `SourceInterface`, a module scope's intentional direct declarations,
2930
+ * conventional barrel-reachable surface, and member methods over a consumer-supplied file
2931
+ * inventory, using text-only line scanners rather than the TypeScript compiler API or the
2932
+ * filesystem. `Source` never touches disk:
2933
+ * the consumer gathers the inventory however their environment allows
2934
+ * (`node:fs` in a Node script, `import.meta.glob` in a browser/vitest run) and
2935
+ * passes it in as `files`.
2936
+ *
2937
+ * @remarks
2938
+ * Conventional barrel traversal recurses through both
2939
+ * exact workspace-root `index.ts` and nested `/index.ts` targets. `'.'` is the
2940
+ * canonical workspace-root module, module spellings normalize once at
2941
+ * construction, and exact opaque inventory keys are never rewritten; keys with
2942
+ * empty, `.` or `..` segments stay outside both initial and resolved barrel
2943
+ * inventory entrances after relative-row reduction; canonical parent hops
2944
+ * remain valid. `methods` resolves a declaration's members through its
2945
+ * `extends` chain within the same module scope, keeping the keyword it started
2946
+ * from; a base the scope does not declare contributes nothing. One declaration
2947
+ * answers for a name: the first file in sorted key order that declares the head
2948
+ * supplies its members and its bases, and a second file declaring the same name
2949
+ * adds nothing. Every reading derives once per instance from the immutable
2950
+ * inventory and is reused — the scope's declaration map on the first `methods`
2951
+ * or `examples` lookup, then each name's members and each example collection
2952
+ * under the name asked for — so a reader asking twice reads the files once and
2953
+ * receives the same records, and a second instance over the same inventory
2954
+ * derives the same readings of its own. Source projection preserves columns
2955
+ * without widening direct/hidden column-zero heads. Literal ECMAScript Unicode
2956
+ * identifiers participate in bounded slash-state recognition without escape
2957
+ * decoding. Regex recognition is bounded: slash after bare `}` is division, so
2958
+ * a post-brace regex statement requires an explicit `;`. General semicolonless
2959
+ * declaration/ASI classification is also outside the finite projector, so a
2960
+ * slash-leading statement after such a declaration requires an explicit `;`.
2961
+ *
2962
+ * @example
2963
+ * ```ts
2964
+ * import { Source } from '@orkestrel/guide'
2965
+ *
2966
+ * const source = new Source({
2967
+ * files: {
2968
+ * 'src/core/index.ts': "export * from './Guide.js'\nexport * from './types.js'\n",
2969
+ * 'src/core/Guide.ts': 'export class Guide {}\n',
2970
+ * 'src/core/types.ts': 'export interface GuideInterface {\n\tsections(): void\n}\n',
2971
+ * },
2972
+ * module: 'src/core',
2973
+ * })
2974
+ * source.exports() // [{ name: 'Guide', keyword: 'class' }, { name: 'GuideInterface', keyword: 'interface' }]
2975
+ * source.surface() // [{ name: 'Guide', keyword: 'class' }, { name: 'GuideInterface', keyword: 'interface' }]
2976
+ * source.methods('GuideInterface') // [{ name: 'sections' }]
2977
+ * source.exists('src/core/Guide.ts') // true
2978
+ * ```
2979
+ */
2980
+ var Source = class {
2981
+ #files;
2982
+ #directories;
2983
+ #methods = /* @__PURE__ */ new Map();
2984
+ #examples = /* @__PURE__ */ new Map();
2985
+ #exports;
2986
+ #surface;
2987
+ #hidden;
2988
+ #declarations;
2989
+ constructor(options) {
2990
+ this.#files = options.files;
2991
+ this.#directories = normalizeDirectories(options.module);
2992
+ }
2993
+ exports() {
2994
+ if (this.#exports === void 0) this.#exports = this.#scanSymbols(extractExports);
2995
+ return this.#exports;
2996
+ }
2997
+ surface() {
2998
+ if (this.#surface === void 0) this.#surface = this.#scanSurface();
2999
+ return this.#surface;
3000
+ }
3001
+ methods(name) {
3002
+ const cached = this.#methods.get(name);
3003
+ if (cached !== void 0) return cached;
3004
+ const members = this.#scanMethods(name);
3005
+ this.#methods.set(name, members);
3006
+ return members;
3007
+ }
3008
+ exists(relative) {
3009
+ return Object.keys(this.#files).some((key) => key === relative || key.startsWith(`${relative}/`));
3010
+ }
3011
+ hidden() {
3012
+ if (this.#hidden === void 0) this.#hidden = this.#scanSymbols(extractHidden);
3013
+ return this.#hidden;
3014
+ }
3015
+ examples(name) {
3016
+ const cached = this.#examples.get(name);
3017
+ if (cached !== void 0) return cached;
3018
+ const examples = name === void 0 ? this.#scanExamples() : this.#exampleMembers(name);
3019
+ this.#examples.set(name, examples);
3020
+ return examples;
3021
+ }
3022
+ #scanMethods(name) {
3023
+ const declared = this.#members("interface", name, /* @__PURE__ */ new Set());
3024
+ if (declared !== void 0) return declared;
3025
+ const inherited = this.#members("class", name, /* @__PURE__ */ new Set());
3026
+ return inherited === void 0 ? [] : inherited.filter((entry) => entry.name !== "constructor");
3027
+ }
3028
+ #scanExamples() {
3029
+ const examples = [];
3030
+ const seen = /* @__PURE__ */ new Set();
3031
+ for (const key of selectModuleKeys(this.#files, this.#directories)) {
3032
+ const text = this.#files[key];
3033
+ if (text === void 0) continue;
3034
+ for (const example of extractExamples(text)) {
3035
+ const identity = `${example.name}\n${example.title ?? ""}`;
3036
+ if (seen.has(identity)) continue;
3037
+ seen.add(identity);
3038
+ examples.push(example);
3039
+ }
3040
+ }
3041
+ return examples;
3042
+ }
3043
+ #scanSurface() {
3044
+ const symbols = [];
3045
+ const seen = /* @__PURE__ */ new Set();
3046
+ const visited = /* @__PURE__ */ new Set();
3047
+ for (const directory of this.#directories) this.#collectSurface(resolvePath(directory, "index.ts"), visited, symbols, seen);
3048
+ return symbols.sort((a, b) => a.name === b.name ? 0 : a.name < b.name ? -1 : 1);
3049
+ }
3050
+ #collectSurface(index, visited, symbols, seen) {
3051
+ if (!hasCanonicalSegments(index)) return;
3052
+ if (visited.has(index)) return;
3053
+ visited.add(index);
3054
+ const source = this.#files[index];
3055
+ if (source === void 0) return;
3056
+ for (const line of extractSourceLines(source)) {
3057
+ const row = line.code.match(/^\s*export\s+\*\s+from\s+(?:'(\.\.?\/[^']+\.js)'|"(\.\.?\/[^"]+\.js)")\s*;?\s*(?:\/\/.*)?$/);
3058
+ const target = row?.[1] ?? row?.[2];
3059
+ if (target === void 0) continue;
3060
+ const path = resolveLink(index, `${target.slice(0, -3)}.ts`);
3061
+ if (!hasCanonicalSegments(path)) continue;
3062
+ if (path === "index.ts" || path.endsWith("/index.ts")) {
3063
+ this.#collectSurface(path, visited, symbols, seen);
3064
+ continue;
3065
+ }
3066
+ if (visited.has(path)) continue;
3067
+ visited.add(path);
3068
+ const text = this.#files[path];
3069
+ if (text === void 0) continue;
3070
+ for (const symbol of extractExports(text)) {
3071
+ const identity = computeSymbolKey(symbol);
3072
+ if (seen.has(identity)) continue;
3073
+ seen.add(identity);
3074
+ symbols.push(symbol);
3075
+ }
3076
+ }
3077
+ }
3078
+ #exampleMembers(name) {
3079
+ const members = /* @__PURE__ */ new Map();
3080
+ for (const example of [...extractExampleMethods(this.#locate("interface", name)?.body ?? []), ...extractExampleMethods(this.#locate("class", name)?.body ?? [])]) {
3081
+ const identity = `${example.name}\n${example.title ?? ""}`;
3082
+ if (members.has(identity)) continue;
3083
+ members.set(identity, example);
3084
+ }
3085
+ return Array.from(members.values()).sort((a, b) => a.name === b.name ? 0 : a.name < b.name ? -1 : 1);
3086
+ }
3087
+ #scanSymbols(scan) {
3088
+ const symbols = [];
3089
+ const seen = /* @__PURE__ */ new Set();
3090
+ for (const key of selectModuleKeys(this.#files, this.#directories)) {
3091
+ const text = this.#files[key];
3092
+ if (text === void 0) continue;
3093
+ for (const symbol of scan(text)) {
3094
+ const identity = computeSymbolKey(symbol);
3095
+ if (seen.has(identity)) continue;
3096
+ seen.add(identity);
3097
+ symbols.push(symbol);
3098
+ }
3099
+ }
3100
+ return symbols.sort((a, b) => a.name === b.name ? 0 : a.name < b.name ? -1 : 1);
3101
+ }
3102
+ #members(keyword, name, visited) {
3103
+ if (visited.has(name)) return [];
3104
+ visited.add(name);
3105
+ const declaration = this.#locate(keyword, name);
3106
+ if (declaration === void 0) return void 0;
3107
+ const methods = /* @__PURE__ */ new Map();
3108
+ for (const entry of extractMemberMethods(declaration.body)) methods.set(entry.name, entry);
3109
+ 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);
3110
+ return Array.from(methods.values()).sort((a, b) => a.name === b.name ? 0 : a.name < b.name ? -1 : 1);
3111
+ }
3112
+ #locate(keyword, name) {
3113
+ if (this.#declarations === void 0) this.#declarations = this.#scanDeclarations();
3114
+ return this.#declarations.get(`${keyword} ${name}`);
3115
+ }
3116
+ #scanDeclarations() {
3117
+ const declarations = /* @__PURE__ */ new Map();
3118
+ for (const key of selectModuleKeys(this.#files, this.#directories)) {
3119
+ const text = this.#files[key];
3120
+ if (text === void 0) continue;
3121
+ for (const [identity, declaration] of collectDeclarations(text)) {
3122
+ if (declarations.has(identity)) continue;
3123
+ if (declaration.body.length === 0 && declaration.bases.length === 0) continue;
3124
+ declarations.set(identity, declaration);
3125
+ }
3126
+ }
3127
+ return declarations;
3128
+ }
3129
+ };
3130
+ //#endregion
3131
+ //#region src/core/sources/SourceManager.ts
3132
+ /**
3133
+ * Resolves a consumer-owned import-specifier policy into pure source views and
3134
+ * caches those views by module, so aliases for one module share one entity.
3135
+ * Unmapped specifiers remain foreign to the consumer and return `undefined`.
3136
+ * `sources()` enumerates the same shared views, one per distinct module the
3137
+ * policy maps.
3138
+ *
3139
+ * @example
3140
+ * ```ts
3141
+ * import { SourceManager } from '@orkestrel/guide'
3142
+ *
3143
+ * const sources = new SourceManager({
3144
+ * files: { 'src/core/index.ts': "export * from './types.js'" },
3145
+ * modules: { '@scope/package': 'src/core' },
3146
+ * })
3147
+ * sources.source('@scope/package')?.surface()
3148
+ * sources.sources() // [the same shared view]
3149
+ * ```
3150
+ */
3151
+ var SourceManager = class {
3152
+ #files;
3153
+ #modules;
3154
+ #sources = /* @__PURE__ */ new Map();
3155
+ constructor(options) {
3156
+ this.#files = options.files;
3157
+ this.#modules = options.modules;
3158
+ }
3159
+ source(specifier) {
3160
+ if (!Object.hasOwn(this.#modules, specifier)) return void 0;
3161
+ const module = this.#modules[specifier];
3162
+ if (module === void 0) return void 0;
3163
+ const key = computeModuleKey(module);
3164
+ const existing = this.#sources.get(key);
3165
+ if (existing !== void 0) return existing;
3166
+ const source = new Source({
3167
+ files: this.#files,
3168
+ module
3169
+ });
3170
+ this.#sources.set(key, source);
3171
+ return source;
3172
+ }
3173
+ sources() {
3174
+ const views = [];
3175
+ const seen = /* @__PURE__ */ new Set();
3176
+ for (const specifier of Object.keys(this.#modules)) {
3177
+ const view = this.source(specifier);
3178
+ if (view === void 0 || seen.has(view)) continue;
3179
+ seen.add(view);
3180
+ views.push(view);
3181
+ }
3182
+ return views;
3183
+ }
3184
+ };
3185
+ //#endregion
3186
+ //#region src/core/Parity.ts
3187
+ /**
3188
+ * Composes generic guide-parity inspection and explicit in-memory rewrites over a caller inventory.
3189
+ */
3190
+ var Parity = class Parity {
3191
+ #options;
3192
+ #rows;
3193
+ constructor(options) {
3194
+ this.#options = {
3195
+ files: { ...options.files },
3196
+ entries: options.entries.map((entry) => ({ ...entry })),
3197
+ modules: { ...options.modules },
3198
+ languages: [...options.languages],
3199
+ language: options.language,
3200
+ ...options.pitch === void 0 ? {} : { pitch: { ...options.pitch } }
3201
+ };
3202
+ this.#rows = this.#createRows(this.#options.files);
3203
+ }
3204
+ rows() {
3205
+ return this.#rows;
3206
+ }
3207
+ inspect() {
3208
+ const input = [];
3209
+ const sections = [];
3210
+ const surface = [];
3211
+ const methods = [];
3212
+ const declarations = [];
3213
+ const links = [];
3214
+ const tests = [];
3215
+ const fences = [];
3216
+ const exampleFences = [];
3217
+ const exampleFunctions = [];
3218
+ const exampleMethods = [];
3219
+ const exampleTitles = [];
3220
+ const examples = {
3221
+ fences: exampleFences,
3222
+ functions: exampleFunctions,
3223
+ methods: exampleMethods,
3224
+ titles: exampleTitles
3225
+ };
3226
+ const imports = [];
3227
+ const drift = [];
3228
+ const pitch = [];
3229
+ this.#inspectInput(input);
3230
+ for (const row of this.#rows) {
3231
+ this.#inspectSections(row, sections);
3232
+ this.#inspectSurface(row, surface);
3233
+ this.#inspectMethods(row, methods);
3234
+ this.#inspectDeclarations(row, declarations);
3235
+ this.#inspectLinks(row, links, tests);
3236
+ this.#inspectFences(row, fences);
3237
+ this.#inspectExamples(row, exampleFences, exampleFunctions, exampleMethods, exampleTitles);
3238
+ this.#inspectImports(row, imports);
3239
+ this.#inspectDrift(row, drift);
3240
+ }
3241
+ this.#inspectPitch(pitch);
3242
+ return {
3243
+ input,
3244
+ sections,
3245
+ surface,
3246
+ methods,
3247
+ declarations,
3248
+ links,
3249
+ tests,
3250
+ fences,
3251
+ examples,
3252
+ imports,
3253
+ drift,
3254
+ pitch
3255
+ };
3256
+ }
3257
+ document() {
3258
+ return this.#rewrite((row, drift, files) => this.#rewriteGuide(row, drift, files));
3259
+ }
3260
+ annotate() {
3261
+ return this.#rewrite((row, drift, files) => this.#rewriteSource(row, drift, files));
3262
+ }
3263
+ #rewrite(apply) {
3264
+ const files = new Map(Object.entries(this.#options.files));
3265
+ const reasons = /* @__PURE__ */ new Map();
3266
+ const requested = /* @__PURE__ */ new Set();
3267
+ for (const row of this.#rows) for (const drift of findDrift(row.guide, row.source)) {
3268
+ const identity = identifyDrift(row.entry.spec, drift);
3269
+ requested.add(identity);
3270
+ const reason = apply(row, drift, files);
3271
+ if (reason !== void 0) reasons.set(identity, reason);
3272
+ }
3273
+ const inventory = Object.fromEntries(files);
3274
+ const remaining = [];
3275
+ const result = new Parity({
3276
+ ...this.#options,
3277
+ files: inventory
3278
+ });
3279
+ remaining.push(...result.inspect().input);
3280
+ for (const row of result.rows()) for (const drift of findDrift(row.guide, row.source)) {
3281
+ const identity = identifyDrift(row.entry.spec, drift);
3282
+ if (!requested.has(identity)) continue;
3283
+ remaining.push({
3284
+ spec: row.entry.spec,
3285
+ text: `${formatDrift(drift)}; ${reasons.get(identity) ?? "the requested destination still disagrees"}`
3286
+ });
3287
+ }
3288
+ return {
3289
+ changes: Array.from(files.entries()).filter(([path, content]) => this.#options.files[path] !== content).sort(([left], [right]) => left.localeCompare(right)).map(([path, content]) => ({
3290
+ path,
3291
+ content
3292
+ })),
3293
+ findings: remaining
3294
+ };
3295
+ }
3296
+ #createRows(files) {
3297
+ const rows = [];
3298
+ for (const entry of this.#options.entries) {
3299
+ const text = files[entry.spec];
3300
+ if (text === void 0) continue;
3301
+ rows.push({
3302
+ entry,
3303
+ guide: new Guide(text),
3304
+ source: new Source({
3305
+ files,
3306
+ module: entry.source
3307
+ })
3308
+ });
3309
+ }
3310
+ return rows;
3311
+ }
3312
+ #inspectInput(findings) {
3313
+ if (this.#options.entries.length === 0) findings.push({ text: "The manifest has no guide entries." });
3314
+ for (const entry of this.#options.entries) {
3315
+ if (this.#options.files[entry.spec] !== void 0) continue;
3316
+ findings.push({
3317
+ spec: entry.spec,
3318
+ text: `${entry.spec} is absent from the inventory.`
3319
+ });
3320
+ }
3321
+ }
3322
+ #inspectSections(row, findings) {
3323
+ const sections = row.guide.sections();
3324
+ for (const heading of [
3325
+ SURFACE,
3326
+ METHODS,
3327
+ TESTS
3328
+ ]) {
3329
+ if (sections.includes(heading)) continue;
3330
+ findings.push({
3331
+ spec: row.entry.spec,
3332
+ text: `${row.entry.spec} has no ## ${heading} section.`
3333
+ });
3334
+ }
3335
+ if (row.guide.methods().length === 0) findings.push({
3336
+ spec: row.entry.spec,
3337
+ text: `${row.entry.spec} has no documented method groups.`
3338
+ });
3339
+ }
3340
+ #inspectSurface(row, findings) {
3341
+ if (row.guide.surface().length === 0) findings.push({
3342
+ spec: row.entry.spec,
3343
+ text: `${row.entry.spec} has no documented surface.`
3344
+ });
3345
+ for (const unnamed of row.guide.unnamed()) findings.push({
3346
+ spec: row.entry.spec,
3347
+ text: `${row.entry.spec} has an unnamed row: ${unnamed}`
3348
+ });
3349
+ for (const key of findMissingSymbols(row.source.exports(), row.source.surface())) findings.push({
3350
+ spec: row.entry.spec,
3351
+ text: `${row.entry.spec} does not re-export ${key}.`
3352
+ });
3353
+ for (const key of findMissingSymbols(row.source.surface(), row.source.exports())) findings.push({
3354
+ spec: row.entry.spec,
3355
+ text: `${row.entry.spec} barrel exposes no direct ${key}.`
3356
+ });
3357
+ for (const key of findMissingSymbols(row.source.surface(), row.guide.surface())) findings.push({
3358
+ spec: row.entry.spec,
3359
+ text: `${row.entry.spec} does not document ${key}.`
3360
+ });
3361
+ for (const key of findMissingSymbols(row.guide.surface(), row.source.surface())) findings.push({
3362
+ spec: row.entry.spec,
3363
+ text: `${row.entry.spec} documents no barrel ${key}.`
3364
+ });
3365
+ for (const symbol of row.source.hidden()) findings.push({
3366
+ spec: row.entry.spec,
3367
+ text: `${row.entry.spec} source hides ${computeSymbolKey(symbol)}.`
3368
+ });
3369
+ }
3370
+ #inspectMethods(row, findings) {
3371
+ for (const group of row.guide.methods()) {
3372
+ const documented = group.methods.map((entry) => entry.name);
3373
+ const declared = row.source.methods(group.interface).map((entry) => entry.name);
3374
+ if (documented.length === 0) findings.push({
3375
+ spec: row.entry.spec,
3376
+ text: `${row.entry.spec} ${group.interface} has no documented methods.`
3377
+ });
3378
+ for (const name of findMissing(declared, documented)) findings.push({
3379
+ spec: row.entry.spec,
3380
+ text: `${row.entry.spec} does not document ${group.interface}.${name}.`
3381
+ });
3382
+ for (const name of findMissing(documented, declared)) findings.push({
3383
+ spec: row.entry.spec,
3384
+ text: `${row.entry.spec} documents no source ${group.interface}.${name}.`
3385
+ });
3386
+ const entity = group.interface.replace(/Interface$/, "");
3387
+ if (entity === group.interface) continue;
3388
+ for (const name of findMissing(row.source.methods(entity).map((entry) => entry.name), documented)) findings.push({
3389
+ spec: row.entry.spec,
3390
+ text: `${row.entry.spec} ${entity}.${name} is outside the ${group.interface} contract.`
3391
+ });
3392
+ }
3393
+ }
3394
+ #inspectDeclarations(row, findings) {
3395
+ const groups = row.guide.methods();
3396
+ const documented = groups.map((group) => group.interface);
3397
+ const declared = new Set(row.source.surface().map((symbol) => symbol.name));
3398
+ for (const group of groups) {
3399
+ const finding = compareMembership(row.entry.spec, group.interface, group.methods.map((entry) => entry.name), row.source.methods(group.interface).map((entry) => entry.name));
3400
+ if (finding !== void 0) findings.push(finding);
3401
+ }
3402
+ for (const symbol of row.source.surface()) {
3403
+ if (symbol.keyword !== "interface" && symbol.keyword !== "class") continue;
3404
+ const members = row.source.methods(symbol.name).map((entry) => entry.name);
3405
+ if (members.length === 0) continue;
3406
+ const contract = `${symbol.name}Interface`;
3407
+ if (symbol.keyword === "class" && declared.has(contract)) {
3408
+ const finding = compareMembership(row.entry.spec, symbol.name, row.source.methods(contract).map((entry) => entry.name), members);
3409
+ if (finding !== void 0) findings.push(finding);
3410
+ continue;
3411
+ }
3412
+ if (documented.includes(symbol.name)) continue;
3413
+ findings.push({
3414
+ spec: row.entry.spec,
3415
+ text: `${row.entry.spec} ${symbol.name} declares members and carries no method table.`
3416
+ });
3417
+ }
3418
+ }
3419
+ #inspectLinks(row, links, tests) {
3420
+ if (row.guide.links().length === 0) links.push({
3421
+ spec: row.entry.spec,
3422
+ text: `${row.entry.spec} has no links.`
3423
+ });
3424
+ for (const href of row.guide.links()) {
3425
+ if (isExternalLink(href)) continue;
3426
+ const path = resolveLink(row.entry.spec, href);
3427
+ if (row.source.exists(path)) continue;
3428
+ links.push({
3429
+ spec: row.entry.spec,
3430
+ text: `${row.entry.spec} has a broken link: ${href}.`
3431
+ });
3432
+ }
3433
+ if (row.guide.tests().length === 0) tests.push({
3434
+ spec: row.entry.spec,
3435
+ text: `${row.entry.spec} has no test links.`
3436
+ });
3437
+ for (const href of row.guide.tests()) {
3438
+ const path = resolveLink(row.entry.spec, href);
3439
+ if (row.source.exists(path)) continue;
3440
+ tests.push({
3441
+ spec: row.entry.spec,
3442
+ text: `${row.entry.spec} has a missing test: ${href}.`
3443
+ });
3444
+ }
3445
+ }
3446
+ #inspectFences(row, findings) {
3447
+ for (const fence of findUnlisted(row.guide.fences(), this.#options.languages)) findings.push({
3448
+ spec: row.entry.spec,
3449
+ text: `${row.entry.spec} has an unlisted fence language under ${fence.title ?? "no heading"}: ${fence.language ?? "absent"}.`
3450
+ });
3451
+ }
3452
+ #inspectExamples(row, fencesFindings, functionFindings, methodFindings, titleFindings) {
3453
+ const fences = row.guide.fences().filter((fence) => fence.language === this.#options.language).map((fence) => fence.code);
3454
+ if (fences.length === 0) fencesFindings.push({
3455
+ spec: row.entry.spec,
3456
+ text: `${row.entry.spec} has no ${this.#options.language} example fence.`
3457
+ });
3458
+ const functions = row.guide.surface().filter((symbol) => symbol.keyword === "function").map((symbol) => symbol.name);
3459
+ for (const name of findUnexampled(functions, fences, row.source.examples().map((example) => example.name))) functionFindings.push({
3460
+ spec: row.entry.spec,
3461
+ text: `${row.entry.spec} has no example for ${name}.`
3462
+ });
3463
+ for (const group of row.guide.methods()) {
3464
+ const entity = group.interface.replace(/Interface$/, "");
3465
+ const examples = row.source.examples(group.interface).map((example) => example.name);
3466
+ if (entity !== group.interface) examples.push(...row.source.examples(entity).map((example) => example.name));
3467
+ for (const name of findUnexampled(group.methods.map((entry) => entry.name), fences, examples)) methodFindings.push({
3468
+ spec: row.entry.spec,
3469
+ text: `${row.entry.spec} has no example for ${group.interface}.${name}.`
3470
+ });
3471
+ }
3472
+ const guide = row.guide.fences().map((fence) => fence.title).filter(_orkestrel_contract.isNonEmptyString);
3473
+ const source = row.source.examples().map((example) => example.title).filter(_orkestrel_contract.isNonEmptyString);
3474
+ if (!guide.some((title) => source.includes(title))) titleFindings.push({
3475
+ spec: row.entry.spec,
3476
+ text: `${row.entry.spec} has no top-level example-title pair: guide ${JSON.stringify(guide)} source ${JSON.stringify(source)}.`
3477
+ });
3478
+ }
3479
+ #inspectImports(row, findings) {
3480
+ const sources = new SourceManager({
3481
+ files: this.#options.files,
3482
+ modules: this.#options.modules
3483
+ });
3484
+ let compared = false;
3485
+ for (const fence of row.guide.fences()) {
3486
+ if (fence.language !== this.#options.language) continue;
3487
+ for (const imported of extractFenceImports(fence.code)) {
3488
+ const source = sources.source(imported.specifier);
3489
+ if (source === void 0) continue;
3490
+ compared = true;
3491
+ const surface = source.surface().map((symbol) => symbol.name);
3492
+ for (const name of findMissing(imported.names, surface)) findings.push({
3493
+ spec: row.entry.spec,
3494
+ text: `${row.entry.spec} imports missing ${name} from ${imported.specifier}.`
3495
+ });
3496
+ }
3497
+ }
3498
+ if (!compared) findings.push({
3499
+ spec: row.entry.spec,
3500
+ text: `${row.entry.spec} has no mapped self import.`
3501
+ });
3502
+ }
3503
+ #inspectDrift(row, findings) {
3504
+ for (const drift of findDrift(row.guide, row.source)) findings.push({
3505
+ spec: row.entry.spec,
3506
+ text: formatDrift(drift)
3507
+ });
3508
+ }
3509
+ #inspectPitch(findings) {
3510
+ const pitch = this.#options.pitch;
3511
+ if (pitch === void 0) return;
3512
+ const readme = this.#options.files[pitch.readme];
3513
+ const spec = this.#options.files[pitch.spec];
3514
+ if (readme === void 0) {
3515
+ findings.push({
3516
+ spec: pitch.readme,
3517
+ text: `${pitch.readme} is absent from the inventory.`
3518
+ });
3519
+ return;
3520
+ }
3521
+ if (spec === void 0) {
3522
+ findings.push({
3523
+ spec: pitch.spec,
3524
+ text: `${pitch.spec} is absent from the inventory.`
3525
+ });
3526
+ return;
3527
+ }
3528
+ const left = new Guide(readme).tagline();
3529
+ const right = new Guide(spec).tagline();
3530
+ if (left !== void 0 && left === right) return;
3531
+ findings.push({
3532
+ spec: pitch.spec,
3533
+ text: `${pitch.spec} pitch: README ${formatSide(left)} guide ${formatSide(right)}.`
3534
+ });
3535
+ }
3536
+ #rewriteGuide(row, drift, files) {
3537
+ if (drift.source === void 0) return "source authority is absent";
3538
+ const current = files.get(row.entry.spec);
3539
+ if (current === void 0) return "the guide inventory text is absent";
3540
+ if (drift.category === "summary") {
3541
+ const replacement = replaceCell(current, drift.key, drift.source);
3542
+ if (replacement === void 0) return "the guide summary cell or its provenance is unavailable";
3543
+ files.set(row.entry.spec, replacement);
3544
+ return;
3545
+ }
3546
+ const example = collectTitles(row.guide, row.source).get(drift.key);
3547
+ if (example === void 0) return "the paired source example is unavailable";
3548
+ const replacement = replaceFence(current, drift.key, example);
3549
+ if (replacement === void 0) return "the titled guide fence or its provenance is unavailable";
3550
+ files.set(row.entry.spec, replacement);
3551
+ }
3552
+ #rewriteSource(row, drift, files) {
3553
+ if (drift.guide === void 0) return "guide authority is absent";
3554
+ if (drift.category === "summary") {
3555
+ const located = this.#locateSource(row.entry, drift.key, files);
3556
+ if (located === void 0) return "the source doc block or its provenance is unavailable";
3557
+ const replacement = replaceSummary(located.text.slice(located.span.start, located.span.end), drift.guide);
3558
+ if (replacement === void 0) return "the source summary cannot be represented safely";
3559
+ files.set(located.path, spliceSpan(located.text, located.span, replacement));
3560
+ return;
3561
+ }
3562
+ const fence = row.guide.fences().find((entry) => entry.title === drift.key);
3563
+ const located = this.#locateExample(row, drift.key, files);
3564
+ if (fence === void 0 || located === void 0) return "the paired source example or its provenance is unavailable";
3565
+ const replacement = replaceExample(located.text.slice(located.span.start, located.span.end), {
3566
+ name: located.example.name,
3567
+ title: drift.key,
3568
+ code: fence.code,
3569
+ ...fence.language === void 0 ? {} : { language: fence.language }
3570
+ });
3571
+ if (replacement === void 0) return "the guide example cannot be represented safely";
3572
+ files.set(located.path, spliceSpan(located.text, located.span, replacement));
3573
+ }
3574
+ #locateSource(entry, key, files) {
3575
+ const inventory = Object.fromEntries(files);
3576
+ for (const path of selectModuleKeys(inventory, normalizeDirectories(entry.source))) {
3577
+ const text = files.get(path);
3578
+ if (text === void 0) continue;
3579
+ const span = locateComment(text, key);
3580
+ if (span !== void 0) return {
3581
+ path,
3582
+ text,
3583
+ span
3584
+ };
3585
+ }
3586
+ }
3587
+ #locateExample(row, title, files) {
3588
+ const target = collectTitles(row.guide, row.source).get(title);
3589
+ if (target === void 0) return void 0;
3590
+ const keys = [];
3591
+ for (const symbol of row.source.exports()) if (symbol.name === target.name) keys.push(computeSymbolKey(symbol));
3592
+ for (const owner of row.guide.surface()) {
3593
+ if (owner.keyword !== "class" && owner.keyword !== "interface") continue;
3594
+ if (row.source.examples(owner.name).some((example) => example.name === target.name && example.title === title)) keys.push(`${owner.name}.${target.name}`);
3595
+ }
3596
+ const inventory = Object.fromEntries(files);
3597
+ for (const path of selectModuleKeys(inventory, normalizeDirectories(row.entry.source))) {
3598
+ const text = files.get(path);
3599
+ if (text === void 0) continue;
3600
+ let selected;
3601
+ for (const key of keys) {
3602
+ const span = locateComment(text, key);
3603
+ if (span === void 0) continue;
3604
+ const example = collectExamples(normalizeComment(text.slice(span.start, span.end)), target.name).find((entry) => entry.title === title);
3605
+ if (example === void 0) continue;
3606
+ if (selected === void 0 || span.start < selected.span.start) selected = {
3607
+ span,
3608
+ example
3609
+ };
3610
+ }
3611
+ if (selected !== void 0) return {
3612
+ path,
3613
+ text,
3614
+ ...selected
3615
+ };
3616
+ }
3617
+ }
3618
+ };
3619
+ //#endregion
3620
+ //#region src/core/parsers.ts
3621
+ /**
3622
+ * Parses a `## By concept` manifest table into its {@link ManifestEntry} rows —
3623
+ * each row's Concept cell (flattened text), Spec / Tests cells (a single link
3624
+ * href, resolved against `directory`), and Source cell (every link href,
3625
+ * resolved against `directory`; Source links canonicalize through
3626
+ * {@link normalizeDirectories}, one directory collapses to a `string`, and several become
3627
+ * a `readonly string[]`). A row missing a concept, spec link, tests link, or
3628
+ * source link is skipped as malformed.
3629
+ *
3630
+ * @param markdown - The manifest markdown source, for example the content of `guides/README.md`
3631
+ * @param directory - The root-relative directory containing the manifest
3632
+ * @returns The manifest's entries, in row order
3633
+ *
3634
+ * @example
3635
+ * ```ts
3636
+ * parseManifest(readme, 'guides') // [{ concept: 'Markdown', spec: 'guides/src/markdown.md', ... }]
3637
+ * ```
3638
+ */
3639
+ function parseManifest(markdown, directory) {
3640
+ const document = (0, _orkestrel_markdown.createMarkdown)(markdown).document;
3641
+ const entries = [];
3642
+ for (const block of selectSectionBlocks(document, MANIFEST)) {
3643
+ if (!(0, _orkestrel_markdown.isTableNode)(block)) continue;
3644
+ for (const row of block.rows) {
3645
+ const conceptCell = row[0];
3646
+ const specCell = row[1];
3647
+ const sourceCell = row[2];
3648
+ const testsCell = row[3];
3649
+ if (conceptCell === void 0 || specCell === void 0 || sourceCell === void 0 || testsCell === void 0) continue;
3650
+ const concept = (0, _orkestrel_markdown.flattenText)({
3651
+ element: "paragraph",
3652
+ children: conceptCell
3653
+ }).trim();
3654
+ if ((0, _orkestrel_contract.isEmptyString)(concept)) continue;
3655
+ const specHref = extractCellLinks(specCell)[0];
3656
+ const testsHref = extractCellLinks(testsCell)[0];
3657
+ if (specHref === void 0 || testsHref === void 0) continue;
3658
+ const sourceHrefs = normalizeDirectories(extractCellLinks(sourceCell).map((href) => resolvePath(directory, href)));
3659
+ if (!(0, _orkestrel_contract.isNonEmptyArray)(sourceHrefs)) continue;
3660
+ const [firstSource] = sourceHrefs;
3661
+ const source = sourceHrefs.length === 1 ? firstSource : sourceHrefs;
3662
+ entries.push({
3663
+ concept,
3664
+ spec: resolvePath(directory, specHref),
3665
+ source,
3666
+ tests: resolvePath(directory, testsHref)
3667
+ });
3668
+ }
3669
+ }
3670
+ return entries;
3671
+ }
3672
+ //#endregion
3673
+ //#region src/server/GuideCommand.ts
3674
+ /**
3675
+ * Drives native checking and explicit rewrites or registers package assertions in the guides
3676
+ * worker.
3677
+ *
3678
+ * @param options - The workspace policy and direct host ports
3679
+ *
3680
+ * @example
3681
+ * ```ts
3682
+ * import { GuideCommand } from '@orkestrel/guide/server'
3683
+ * import { readInventory } from '@orkestrel/test/server'
3684
+ * import { createVitest } from 'vitest/node'
3685
+ *
3686
+ * await new GuideCommand({
3687
+ * root: new URL('../', import.meta.url),
3688
+ * patterns: ['src/**\/*.ts', 'tests/**\/*.ts', 'guides/*.md', '*.md'],
3689
+ * modules: { '@scope/widget': 'src/core' },
3690
+ * languages: ['ts'],
3691
+ * language: 'ts',
3692
+ * reader: readInventory,
3693
+ * runner: createVitest,
3694
+ * }).execute(async ({ files, report, root, rows }) => {
3695
+ * const { expect, it } = await import('vitest')
3696
+ * it('checks the documented inventory', () => {
3697
+ * expect(root.length).toBeGreaterThan(0)
3698
+ * expect(Object.keys(files).length).toBeGreaterThan(0)
3699
+ * expect(rows.length).toBeGreaterThan(0)
3700
+ * expect(report.input).toEqual([])
3701
+ * })
3702
+ * })
3703
+ * ```
3704
+ */
3705
+ var GuideCommand = class {
3706
+ #root;
3707
+ #patterns;
3708
+ #modules;
3709
+ #languages;
3710
+ #language;
3711
+ #reader;
3712
+ #runner;
3713
+ constructor(options) {
3714
+ this.#root = resolveGuideRoot(options.root);
3715
+ this.#patterns = Object.freeze([...options.patterns]);
3716
+ this.#modules = Object.freeze({ ...options.modules });
3717
+ this.#languages = Object.freeze([...options.languages]);
3718
+ this.#language = options.language;
3719
+ this.#reader = options.reader;
3720
+ this.#runner = options.runner;
3721
+ }
3722
+ /**
3723
+ * Runs the native command or registers package assertions with fresh worker inventory and parity.
3724
+ *
3725
+ * @param register - The package-owned assertion registration callback
3726
+ * @returns A promise that resolves after the selected command path finishes
3727
+ * @throws When worker inventory reading or package assertion registration fails. Native failures
3728
+ * are reported through stderr and process exit status before this promise resolves.
3729
+ */
3730
+ async execute(register) {
3731
+ if (node_process.default.env.VITEST === "true") {
3732
+ await this.#register(register);
3733
+ return;
3734
+ }
3735
+ try {
3736
+ await this.#executeNative();
3737
+ } catch (error) {
3738
+ node_process.default.stderr.write(`${error instanceof Error ? error.message : String(error)}\n`);
3739
+ this.#raise(1);
3740
+ }
3741
+ }
3742
+ #createOptions() {
3743
+ const files = this.#readInventory();
3744
+ const manifest = files[GUIDE_INDEX];
3745
+ if (manifest === void 0) return void 0;
3746
+ const entries = Object.freeze([...parseManifest(manifest, "guides")]);
3747
+ const packageManifest = Object.freeze({ ...this.#reader(this.#root, [GUIDE_MANIFEST]) })[GUIDE_MANIFEST];
3748
+ const pitch = selectGuidePitch(entries, packageManifest === void 0 ? void 0 : parsePackageName(packageManifest));
3749
+ return {
3750
+ files,
3751
+ entries,
3752
+ modules: this.#modules,
3753
+ languages: this.#languages,
3754
+ language: this.#language,
3755
+ ...pitch === void 0 ? {} : { pitch: Object.freeze({
3756
+ readme: GUIDE_README,
3757
+ spec: pitch
3758
+ }) }
3759
+ };
3760
+ }
3761
+ async #executeNative() {
3762
+ const args = node_process.default.argv.slice(2);
3763
+ const direction = parseGuideDirection(args);
3764
+ if (direction === void 0 && args.length > 0) {
3765
+ node_process.default.stdout.write(`${GUIDE_USAGE}\n`);
3766
+ this.#raise(2);
3767
+ return;
3768
+ }
3769
+ if (direction === void 0) {
3770
+ if (!await this.#executeRunner()) this.#raise(1);
3771
+ return;
3772
+ }
3773
+ const options = this.#createOptions();
3774
+ if (options === void 0) {
3775
+ this.#reportMissing();
3776
+ return;
3777
+ }
3778
+ const parity = new Parity(options);
3779
+ if (this.#report(parity.inspect().input)) {
3780
+ this.#raise(2);
3781
+ return;
3782
+ }
3783
+ const rewritten = direction === "guide" ? parity.document() : parity.annotate();
3784
+ for (const change of rewritten.changes) {
3785
+ (0, node_fs.writeFileSync)((0, node_path.resolve)(this.#root, change.path), change.content);
3786
+ node_process.default.stdout.write(`wrote ${change.path}\n`);
3787
+ }
3788
+ const freshOptions = this.#createOptions();
3789
+ if (freshOptions === void 0) {
3790
+ this.#reportMissing();
3791
+ return;
3792
+ }
3793
+ const freshParity = new Parity(freshOptions);
3794
+ const freshReport = freshParity.inspect();
3795
+ if (this.#report(freshReport.input)) {
3796
+ this.#raise(2);
3797
+ return;
3798
+ }
3799
+ const remaining = direction === "guide" ? freshParity.document().findings : freshParity.annotate().findings;
3800
+ if (this.#report(remaining)) this.#raise(1);
3801
+ if (this.#report(freshReport.pitch)) this.#raise(1);
3802
+ if (rewritten.changes.length > 0) node_process.default.stdout.write("next: npm run format\n");
3803
+ if (!await this.#executeRunner()) this.#raise(1);
3804
+ }
3805
+ #readInventory() {
3806
+ const targets = (0, node_fs.globSync)([...this.#patterns], { cwd: this.#root }).map((path) => path.replaceAll("\\", "/"));
3807
+ return Object.freeze({ ...this.#reader(this.#root, targets) });
3808
+ }
3809
+ async #register(register) {
3810
+ const options = this.#createOptions();
3811
+ if (options === void 0) throw new Error("The inventory carries no guides/README.md to index from");
3812
+ const parity = new Parity(options);
3813
+ await register(Object.freeze({
3814
+ root: this.#root,
3815
+ files: options.files,
3816
+ rows: parity.rows(),
3817
+ report: parity.inspect()
3818
+ }));
3819
+ }
3820
+ #report(findings) {
3821
+ for (const finding of findings) node_process.default.stdout.write(`${formatGuideFinding(finding)}\n`);
3822
+ return findings.length > 0;
3823
+ }
3824
+ #reportMissing() {
3825
+ node_process.default.stdout.write(`${GUIDE_INDEX}: the workspace carries no concept index to read\n`);
3826
+ this.#raise(2);
3827
+ }
3828
+ async #executeRunner() {
3829
+ const runner = await this.#runner("test", {
3830
+ root: this.#root,
3831
+ config: (0, node_path.resolve)(this.#root, "vite.config.ts"),
3832
+ project: "guides",
3833
+ reporters: "dot",
3834
+ cache: false,
3835
+ watch: false
3836
+ });
3837
+ if (!(0, _orkestrel_contract.isObject)(runner)) throw new Error("The guides runner is not an object");
3838
+ const close = Reflect.get(runner, "close");
3839
+ if (!(0, _orkestrel_contract.isFunction)(close)) throw new Error("The guides runner has no callable close member");
3840
+ try {
3841
+ const start = Reflect.get(runner, "start");
3842
+ if (!(0, _orkestrel_contract.isFunction)(start)) throw new Error("The guides runner has no callable start member");
3843
+ return matchesGuideResult(await Reflect.apply(start, runner, []));
3844
+ } finally {
3845
+ await Reflect.apply(close, runner, []);
3846
+ }
3847
+ }
3848
+ #raise(code) {
3849
+ const current = node_process.default.exitCode;
3850
+ const numeric = typeof current === "string" ? Number.parseInt(current, 10) : current;
3851
+ if (typeof numeric !== "number" || !Number.isFinite(numeric) || numeric < code) node_process.default.exitCode = code;
3852
+ }
3853
+ };
3854
+ //#endregion
3855
+ exports.GUIDE_INDEX = GUIDE_INDEX;
3856
+ exports.GUIDE_MANIFEST = GUIDE_MANIFEST;
3857
+ exports.GUIDE_README = GUIDE_README;
3858
+ exports.GUIDE_USAGE = GUIDE_USAGE;
3859
+ exports.GuideCommand = GuideCommand;
3860
+ exports.formatGuideFinding = formatGuideFinding;
3861
+ exports.matchesGuideResult = matchesGuideResult;
3862
+ exports.parseGuideDirection = parseGuideDirection;
3863
+ exports.parsePackageName = parsePackageName;
3864
+ exports.resolveGuideRoot = resolveGuideRoot;
3865
+ exports.selectGuidePitch = selectGuidePitch;
3866
+
3867
+ //# sourceMappingURL=index.cjs.map