@redocly/realm-plugin-asciidoc 0.8.0-next.9 → 0.9.0-next.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,1025 +0,0 @@
1
- import path from 'node:path';
2
- import Asciidoctor from '@asciidoctor/core';
3
-
4
- import type {
5
- ContentNode,
6
- InlineIcon,
7
- CodeBlockCallout,
8
- AsciidocSection,
9
- ListItemNode,
10
- DescriptionListItemNode,
11
- TableCellNode,
12
- AdmonitionNode,
13
- } from './types.js';
14
-
15
- const asciidoctor = Asciidoctor();
16
- const DIAGRAM_TYPES = ['mermaid', 'excalidraw', 'plantuml'] as const;
17
- type DiagramType = (typeof DIAGRAM_TYPES)[number];
18
-
19
- export type AsciidocLink = {
20
- href: string;
21
- text: string;
22
- type: 'xref' | 'link' | 'url';
23
- };
24
-
25
- export type ParsedAsciidoc = {
26
- title: string;
27
- attributes: Record<string, string | number | boolean>;
28
- sections: AsciidocSection[];
29
- contentNodes: ContentNode[];
30
- links: AsciidocLink[];
31
- sourceContent: string;
32
- };
33
-
34
- // We type these loosely because @asciidoctor/core doesn't ship TS types.
35
- // The actual objects come from Opal/Ruby, so we access them via duck-typing.
36
-
37
- type ADoc = {
38
- getDocumentTitle: () => { toString: () => string } | undefined;
39
- getAttributes: () => Record<string, unknown>;
40
- getSections: () => ASection[];
41
- getBlocks: () => ABlock[];
42
- findBy: (selector: { context: string }) => ABlock[];
43
- convert: () => string;
44
- };
45
-
46
- type ASection = ABlock & {
47
- getId: () => string | undefined;
48
- getTitle: () => string | undefined;
49
- getLevel: () => number;
50
- getSections: () => ASection[];
51
- };
52
-
53
- type ABlock = {
54
- getContext: () => string;
55
- getNodeName: () => string;
56
- getTitle: () => string | undefined;
57
- getId: () => string | undefined;
58
- getRole: () => string | undefined;
59
- getStyle: () => string | undefined;
60
- getSource: () => string | undefined;
61
- getContent: () => string | undefined;
62
- getBlocks: () => ABlock[];
63
- getItems: () => AListItem[];
64
- getRows: () => { head: ACell[][]; body: ACell[][]; foot: ACell[][] };
65
- getAttribute: (name: string, defaultValue?: unknown) => unknown;
66
- isOption: (name: string) => boolean;
67
- getCaption: () => string | undefined;
68
- getLevel: () => number;
69
- };
70
-
71
- type AListItem = ABlock & {
72
- getText: () => string;
73
- getBlocks: () => ABlock[];
74
- hasBlocks: () => boolean;
75
- };
76
-
77
- type ACell = {
78
- getText: () => string;
79
- getContent: () => string;
80
- getColumnSpan: () => number;
81
- getRowSpan: () => number;
82
- getStyle: () => string | undefined;
83
- getAttribute: (name: string) => unknown;
84
- };
85
-
86
- export function parseAsciidoc(
87
- content: string,
88
- relativePath: string,
89
- contentRoot: string,
90
- ): ParsedAsciidoc {
91
- const absolutePath = path.resolve(contentRoot, relativePath);
92
- const doc = asciidoctor.load(content, {
93
- safe: 'safe',
94
- base_dir: path.dirname(absolutePath),
95
- docfile: absolutePath,
96
- attributes: {
97
- showtitle: true,
98
- 'source-highlighter': 'highlight.js',
99
- icons: 'font',
100
- idprefix: '',
101
- idseparator: '-',
102
- },
103
- }) as unknown as ADoc;
104
-
105
- const title = doc.getDocumentTitle()?.toString() || '';
106
-
107
- const rawAttributes = doc.getAttributes();
108
- const attributes: Record<string, string | number | boolean> = {};
109
- for (const [key, value] of Object.entries(rawAttributes)) {
110
- if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') {
111
- attributes[key] = value;
112
- }
113
- }
114
-
115
- // Walk the AST to produce serializable content nodes
116
- const topBlocks = doc.getBlocks();
117
- const contentNodes: ContentNode[] = [];
118
-
119
- // AsciiDoc `= Title` (level 0) is the document title — asciidoctor excludes it from
120
- // getBlocks()/getSections(). Prepend it as an H1 heading so it renders on the page.
121
- if (title) {
122
- const { html: titleHtml, icons: titleIcons } = extractInlineIcons(title);
123
- contentNodes.push({
124
- type: 'section',
125
- id: '',
126
- title: stripInlineHtml(title),
127
- titleHtml,
128
- titleIcons,
129
- level: 1,
130
- children: [],
131
- });
132
- }
133
-
134
- contentNodes.push(...convertBlocks(topBlocks, relativePath));
135
-
136
- // Build section tree for TOC, search, and AI docs
137
- const sections = buildSectionTree(doc.getSections());
138
-
139
- // Extract links from converted HTML (used for sitemap / link checking)
140
- const convertedHtml = doc.convert();
141
- const links = extractLinks(convertedHtml, relativePath);
142
-
143
- return {
144
- title,
145
- attributes,
146
- sections,
147
- contentNodes,
148
- links,
149
- sourceContent: content,
150
- };
151
- }
152
-
153
- function isDiagramType(value: string | undefined | null): value is DiagramType {
154
- if (!value) return false;
155
- return DIAGRAM_TYPES.includes(value as DiagramType);
156
- }
157
-
158
- function convertBlocks(blocks: ABlock[], relativePath: string): ContentNode[] {
159
- const nodes: ContentNode[] = [];
160
-
161
- for (let i = 0; i < blocks.length; i++) {
162
- const block = blocks[i];
163
- const context = block.getContext();
164
-
165
- switch (context) {
166
- case 'section':
167
- nodes.push(convertSection(block as unknown as ASection, relativePath));
168
- break;
169
- case 'paragraph':
170
- nodes.push(convertParagraph(block));
171
- break;
172
- case 'listing': {
173
- const codeNode = convertListing(block, blocks[i + 1]);
174
- // If we consumed a colist, skip it
175
- if (
176
- codeNode.type === 'codeBlock' &&
177
- codeNode.calloutDescriptions &&
178
- codeNode.calloutDescriptions.length > 0
179
- ) {
180
- const next = blocks[i + 1];
181
- if (next && next.getContext() === 'colist') {
182
- i++;
183
- }
184
- }
185
- nodes.push(codeNode);
186
- break;
187
- }
188
- case 'literal':
189
- nodes.push(convertLiteral(block));
190
- break;
191
- case 'admonition':
192
- nodes.push(convertAdmonition(block, relativePath));
193
- break;
194
- case 'ulist':
195
- nodes.push(convertList(block, false, relativePath));
196
- break;
197
- case 'olist':
198
- nodes.push(convertList(block, true, relativePath));
199
- break;
200
- case 'dlist':
201
- nodes.push(convertDescriptionList(block, relativePath));
202
- break;
203
- case 'table':
204
- nodes.push(convertTable(block));
205
- break;
206
- case 'image':
207
- nodes.push(convertImage(block, relativePath));
208
- break;
209
- case 'quote':
210
- case 'verse':
211
- nodes.push(convertQuote(block, relativePath));
212
- break;
213
- case 'sidebar':
214
- nodes.push(convertSidebar(block, relativePath));
215
- break;
216
- case 'example':
217
- nodes.push(convertExample(block, relativePath));
218
- break;
219
- case 'open':
220
- nodes.push(convertOpen(block, relativePath));
221
- break;
222
- case 'thematic_break':
223
- nodes.push({ type: 'thematicBreak' });
224
- break;
225
- case 'pass':
226
- case 'stem':
227
- nodes.push(convertPassthrough(block));
228
- break;
229
- case 'preamble':
230
- // Preamble is a wrapper; recurse into its children
231
- nodes.push(...convertBlocks(block.getBlocks(), relativePath));
232
- break;
233
- case 'toc':
234
- // Skip generated TOC — we use our own
235
- break;
236
- case 'colist':
237
- // Colist is consumed alongside listing blocks; if orphaned, skip
238
- break;
239
- default:
240
- console.warn(`[asciidoc-plugin] Unsupported block type "${context}" — skipping.`);
241
- break;
242
- }
243
- }
244
-
245
- return nodes;
246
- }
247
-
248
- function convertSection(section: ASection, relativePath: string): ContentNode {
249
- const id = section.getId() || slugify(section.getTitle() || '');
250
- const rawTitle = section.getTitle() || '';
251
- const level = Math.min(section.getLevel() + 1, 6); // +1 because section level is 0-based in AsciiDoc
252
-
253
- // Section titles can contain inline icons (e.g. `== icon:flag[] Heading`)
254
- const { html: titleHtml, icons: titleIcons } = extractInlineIcons(rawTitle);
255
- // Plain text title (strip HTML) for TOC and search
256
- const title = stripInlineHtml(rawTitle);
257
-
258
- const children = convertBlocks(section.getBlocks(), relativePath);
259
-
260
- return {
261
- type: 'section',
262
- id,
263
- title,
264
- titleHtml,
265
- titleIcons,
266
- level,
267
- children,
268
- };
269
- }
270
-
271
- function convertParagraph(block: ABlock): ContentNode {
272
- const html = block.getContent() || '';
273
- const { html: processedHtml, icons } = extractInlineIcons(html);
274
- const role = block.getRole() || undefined;
275
-
276
- return {
277
- type: 'paragraph',
278
- contentHtml: processedHtml,
279
- icons,
280
- role,
281
- };
282
- }
283
-
284
- function convertListing(block: ABlock, nextBlock?: ABlock): ContentNode {
285
- const lang = ((block.getAttribute('language') as string) || '').toLowerCase();
286
- const style = (block.getStyle() || '').toLowerCase();
287
- const rawSource = block.getSource() || '';
288
-
289
- // Diagram type can come either from the language (e.g. `[source,plantuml]`)
290
- // or the block style (e.g. `[plantuml]` directly).
291
- const diagramType = isDiagramType(lang) ? lang : isDiagramType(style) ? style : null;
292
- if (diagramType) {
293
- return {
294
- type: 'diagram',
295
- diagramType,
296
- source: rawSource,
297
- id: block.getId() || undefined,
298
- };
299
- }
300
-
301
- const title = block.getTitle() || undefined;
302
-
303
- // Parse callout markers from source: <1>, <2>, etc.
304
- const { cleaned, callouts } = parseCallouts(rawSource);
305
-
306
- // Check if next block is a colist (callout list)
307
- let calloutDescriptions: string[] | undefined;
308
- if (nextBlock && nextBlock.getContext() === 'colist') {
309
- calloutDescriptions = extractColistDescriptions(nextBlock);
310
- }
311
-
312
- return {
313
- type: 'codeBlock',
314
- lang,
315
- source: cleaned,
316
- title,
317
- callouts: callouts.length > 0 ? callouts : undefined,
318
- calloutDescriptions:
319
- calloutDescriptions && calloutDescriptions.length > 0 ? calloutDescriptions : undefined,
320
- };
321
- }
322
-
323
- function convertLiteral(block: ABlock): ContentNode {
324
- const source = block.getSource() || '';
325
- const style = (block.getStyle() || '').toLowerCase();
326
-
327
- // Diagram styles with the literal delimiter (`....`) — e.g. `[plantuml]....`
328
- if (isDiagramType(style)) {
329
- return {
330
- type: 'diagram',
331
- diagramType: style,
332
- source,
333
- id: block.getId() || undefined,
334
- };
335
- }
336
-
337
- return {
338
- type: 'codeBlock',
339
- lang: '',
340
- source,
341
- title: block.getTitle() || undefined,
342
- };
343
- }
344
-
345
- const ADMONITION_TYPE_MAP: Record<string, AdmonitionNode['admonitionType']> = {
346
- note: 'info',
347
- tip: 'success',
348
- warning: 'warning',
349
- caution: 'warning',
350
- important: 'danger',
351
- };
352
-
353
- function convertAdmonition(block: ABlock, relativePath: string): ContentNode {
354
- const style = (block.getStyle() || 'note').toLowerCase();
355
- const admonitionType = ADMONITION_TYPE_MAP[style] || 'info';
356
- const name = style.charAt(0).toUpperCase() + style.slice(1);
357
-
358
- const innerBlocks = block.getBlocks();
359
- const children = convertBlocks(innerBlocks, relativePath);
360
-
361
- return {
362
- type: 'admonition',
363
- admonitionType,
364
- name,
365
- children,
366
- };
367
- }
368
-
369
- function convertList(block: ABlock, ordered: boolean, relativePath: string): ContentNode {
370
- const items: ListItemNode[] = [];
371
-
372
- for (const item of block.getItems()) {
373
- const textHtml = item.getText() || '';
374
- const { html: processedHtml, icons } = extractInlineIcons(textHtml);
375
-
376
- const childBlocks = item.hasBlocks() ? item.getBlocks() : [];
377
- const children = convertBlocks(childBlocks, relativePath);
378
-
379
- items.push({
380
- contentHtml: processedHtml,
381
- icons,
382
- children,
383
- });
384
- }
385
-
386
- return {
387
- type: 'list',
388
- ordered,
389
- items,
390
- };
391
- }
392
-
393
- function convertDescriptionList(block: ABlock, relativePath: string): ContentNode {
394
- const items: DescriptionListItemNode[] = [];
395
-
396
- const rawItems = block.getItems();
397
- for (const pair of rawItems) {
398
- if (!Array.isArray(pair) || pair.length < 2) continue;
399
-
400
- const [terms, definition] = pair as unknown as [AListItem[], AListItem];
401
-
402
- const termsHtml: string[] = [];
403
- if (Array.isArray(terms)) {
404
- for (const term of terms) {
405
- const text = typeof term.getText === 'function' ? term.getText() : String(term);
406
- termsHtml.push(text);
407
- }
408
- }
409
-
410
- let descriptionHtml = '';
411
- let descriptionIcons: InlineIcon[] = [];
412
- let children: ContentNode[] = [];
413
-
414
- if (definition && typeof definition.getText === 'function') {
415
- const rawHtml = definition.getText() || '';
416
- const extracted = extractInlineIcons(rawHtml);
417
- descriptionHtml = extracted.html;
418
- descriptionIcons = extracted.icons;
419
-
420
- if (typeof definition.hasBlocks === 'function' && definition.hasBlocks()) {
421
- children = convertBlocks(definition.getBlocks(), relativePath);
422
- }
423
- }
424
-
425
- items.push({
426
- termsHtml,
427
- descriptionHtml,
428
- descriptionIcons,
429
- children,
430
- });
431
- }
432
-
433
- return {
434
- type: 'descriptionList',
435
- items,
436
- };
437
- }
438
-
439
- function convertTable(block: ABlock): ContentNode {
440
- const rows = block.getRows();
441
- const title = block.getTitle() || undefined;
442
-
443
- const convertRow = (row: ACell[]): TableCellNode[] =>
444
- row.map((cell) => {
445
- const colSpan = cell.getColumnSpan();
446
- const rowSpan = cell.getRowSpan();
447
- // getContent() returns rendered HTML for asciidoc cells; getText() for plain text cells
448
- const style = cell.getStyle?.();
449
- const contentHtml = (style === 'asciidoc' ? cell.getContent() : cell.getText()) || '';
450
-
451
- return {
452
- contentHtml,
453
- ...(colSpan > 1 ? { colSpan } : {}),
454
- ...(rowSpan > 1 ? { rowSpan } : {}),
455
- };
456
- });
457
-
458
- return {
459
- type: 'table',
460
- title,
461
- head: (rows.head || []).map(convertRow),
462
- body: (rows.body || []).map(convertRow),
463
- foot: (rows.foot || []).map(convertRow),
464
- };
465
- }
466
-
467
- function convertImage(block: ABlock, relativePath: string): ContentNode {
468
- const target = (block.getAttribute('target') as string) || '';
469
- const alt = (block.getAttribute('alt') as string) || '';
470
- const width = block.getAttribute('width') as string | undefined;
471
- const height = block.getAttribute('height') as string | undefined;
472
- const title = block.getTitle() || undefined;
473
-
474
- const src = normalizeImageSrc(target, relativePath);
475
-
476
- return {
477
- type: 'image',
478
- src,
479
- alt,
480
- title,
481
- ...(width ? { width: String(width) } : {}),
482
- ...(height ? { height: String(height) } : {}),
483
- };
484
- }
485
-
486
- function convertQuote(block: ABlock, relativePath: string): ContentNode {
487
- const attribution = (block.getAttribute('attribution') as string) || undefined;
488
- const citeTitle = (block.getAttribute('citetitle') as string) || undefined;
489
-
490
- const innerBlocks = block.getBlocks();
491
- const children =
492
- innerBlocks.length > 0
493
- ? convertBlocks(innerBlocks, relativePath)
494
- : block.getContent()
495
- ? [
496
- {
497
- type: 'paragraph' as const,
498
- contentHtml: block.getContent() || '',
499
- icons: [],
500
- },
501
- ]
502
- : [];
503
-
504
- return {
505
- type: 'quote',
506
- attribution,
507
- citeTitle,
508
- children,
509
- };
510
- }
511
-
512
- function convertSidebar(block: ABlock, relativePath: string): ContentNode {
513
- return {
514
- type: 'sidebar',
515
- title: block.getTitle() || undefined,
516
- children: convertBlocks(block.getBlocks(), relativePath),
517
- };
518
- }
519
-
520
- function convertExample(block: ABlock, relativePath: string): ContentNode {
521
- const isCollapsible = block.isOption('collapsible');
522
-
523
- if (isCollapsible) {
524
- return {
525
- type: 'collapsible',
526
- title: block.getTitle() || undefined,
527
- children: convertBlocks(block.getBlocks(), relativePath),
528
- };
529
- }
530
-
531
- return {
532
- type: 'example',
533
- title: block.getTitle() || undefined,
534
- children: convertBlocks(block.getBlocks(), relativePath),
535
- };
536
- }
537
-
538
- function convertOpen(block: ABlock, relativePath: string): ContentNode {
539
- const style = (block.getStyle() || '').toLowerCase();
540
- if (isDiagramType(style)) {
541
- const source = extractSourceFromBlocks(block.getBlocks()).trim();
542
- if (source) {
543
- return {
544
- type: 'diagram',
545
- diagramType: style,
546
- source,
547
- id: block.getId() || undefined,
548
- };
549
- }
550
- }
551
-
552
- // An open block is a generic container — just recurse into children
553
- const children = convertBlocks(block.getBlocks(), relativePath);
554
- if (children.length === 1) return children[0];
555
-
556
- // Return as an example-like container if it has a role
557
- const role = block.getRole();
558
- if (role) {
559
- return {
560
- type: 'paragraph',
561
- contentHtml: block.getContent() || '',
562
- icons: [],
563
- role,
564
- };
565
- }
566
-
567
- // Just flatten open blocks
568
- return {
569
- type: 'example',
570
- title: undefined,
571
- children,
572
- };
573
- }
574
-
575
- function extractSourceFromBlocks(blocks: ABlock[]): string {
576
- const parts: string[] = [];
577
-
578
- for (const block of blocks) {
579
- const source = block.getSource?.();
580
- if (source) {
581
- parts.push(source);
582
- continue;
583
- }
584
-
585
- const childBlocks = block.getBlocks?.() || [];
586
- if (childBlocks.length > 0) {
587
- const childSource = extractSourceFromBlocks(childBlocks);
588
- if (childSource) {
589
- parts.push(childSource);
590
- }
591
- }
592
- }
593
-
594
- return parts.join('\n\n');
595
- }
596
-
597
- function convertPassthrough(block: ABlock): ContentNode {
598
- return {
599
- type: 'htmlPassthrough',
600
- html: block.getContent() || '',
601
- };
602
- }
603
-
604
- /**
605
- * Parses raw AsciiDoc source callout markers like `<1>` `<2>` from code.
606
- * Returns cleaned source and callout positions.
607
- */
608
- function parseCallouts(source: string): { cleaned: string; callouts: CodeBlockCallout[] } {
609
- const callouts: CodeBlockCallout[] = [];
610
- const calloutRegex = /(?<!\s)\s*<(\d+)>\s*$/;
611
- const lines = source.split('\n');
612
- const cleanedLines: string[] = [];
613
-
614
- for (let i = 0; i < lines.length; i++) {
615
- let line = lines[i];
616
- const match = line.match(calloutRegex);
617
- if (match) {
618
- callouts.push({ line: i + 1, number: parseInt(match[1], 10) });
619
- line = line.replace(calloutRegex, '');
620
- }
621
- cleanedLines.push(line);
622
- }
623
-
624
- return { cleaned: cleanedLines.join('\n'), callouts };
625
- }
626
-
627
- /**
628
- * Extracts callout descriptions from a colist (callout list) block.
629
- */
630
- function extractColistDescriptions(colist: ABlock): string[] {
631
- const descriptions: string[] = [];
632
- try {
633
- const items = colist.getItems();
634
- if (items && Array.isArray(items)) {
635
- for (const item of items) {
636
- if (typeof item.getText === 'function') {
637
- descriptions.push(stripInlineHtml(item.getText()));
638
- }
639
- }
640
- }
641
- } catch {
642
- // Colist may not support getItems on all versions
643
- }
644
- return descriptions;
645
- }
646
-
647
- /**
648
- * Known Font Awesome brand icon names that live under the `brands/` style.
649
- */
650
- const FA_BRAND_ICONS = new Set([
651
- 'github',
652
- 'twitter',
653
- 'facebook',
654
- 'linkedin',
655
- 'youtube',
656
- 'google',
657
- 'apple',
658
- 'android',
659
- 'windows',
660
- 'docker',
661
- 'npm',
662
- 'node-js',
663
- 'node',
664
- 'react',
665
- 'angular',
666
- 'vuejs',
667
- 'python',
668
- 'java',
669
- 'php',
670
- 'rust',
671
- 'golang',
672
- 'aws',
673
- 'slack',
674
- 'discord',
675
- 'reddit',
676
- 'stackoverflow',
677
- 'stack-overflow',
678
- 'gitlab',
679
- 'bitbucket',
680
- 'codepen',
681
- 'jsfiddle',
682
- 'bootstrap',
683
- 'sass',
684
- 'less',
685
- 'css3',
686
- 'html5',
687
- 'js',
688
- 'markdown',
689
- 'stripe',
690
- 'paypal',
691
- 'shopify',
692
- 'wordpress',
693
- 'medium',
694
- 'dev',
695
- 'figma',
696
- 'sketch',
697
- 'dribbble',
698
- 'behance',
699
- 'instagram',
700
- 'pinterest',
701
- 'tiktok',
702
- 'whatsapp',
703
- 'telegram',
704
- 'x-twitter',
705
- ]);
706
-
707
- /**
708
- * Extracts `<i class="fa fa-*">` icons from inline HTML and replaces them
709
- * with `<!--icon:N-->` placeholders. The extracted icon data is stored in
710
- * the InlineIcon array so the template can render CDNIcon components.
711
- */
712
- function extractInlineIcons(html: string): { html: string; icons: InlineIcon[] } {
713
- const icons: InlineIcon[] = [];
714
-
715
- const processed = html.replace(
716
- /<i class="fa\s+fa-([a-z0-9-]+)((?:[^"a-z0-9-][^"]*)?)"[^>]*><\/i>/gi,
717
- (_match, name: string, extraClasses: string) => {
718
- let iconName = name;
719
- let style = 'solid';
720
-
721
- if (iconName.endsWith('-o')) {
722
- iconName = iconName.slice(0, -2);
723
- style = 'regular';
724
- }
725
-
726
- if (FA_BRAND_ICONS.has(iconName)) {
727
- style = 'brands';
728
- }
729
-
730
- const size = extraClasses.includes('fa-2x') ? '2em' : undefined;
731
- const idx = icons.length;
732
- icons.push({ name: iconName, style, size });
733
- return `<!--icon:${idx}-->`;
734
- },
735
- );
736
-
737
- return { html: processed, icons };
738
- }
739
-
740
- function buildSectionTree(sections: ASection[]): AsciidocSection[] {
741
- return sections.map((section) => {
742
- const id = section.getId() || slugify(section.getTitle() || '');
743
- const title = section.getTitle() || '';
744
- const level = section.getLevel();
745
-
746
- // Extract plain text from the section's non-section blocks
747
- const textContent = extractTextFromBlocks(section.getBlocks());
748
-
749
- // Recurse into child sections
750
- const childSections = section
751
- .getBlocks()
752
- .filter((b) => b.getContext() === 'section') as unknown as ASection[];
753
-
754
- return {
755
- id,
756
- title,
757
- level,
758
- textContent,
759
- children: buildSectionTree(childSections),
760
- };
761
- });
762
- }
763
-
764
- function extractTextFromBlocks(blocks: ABlock[]): string {
765
- const parts: string[] = [];
766
-
767
- for (const block of blocks) {
768
- const context = block.getContext();
769
- if (context === 'section') continue;
770
-
771
- if (context === 'paragraph' || context === 'verse') {
772
- const html = block.getContent();
773
- if (html) parts.push(stripInlineHtml(html));
774
- } else if (context === 'literal') {
775
- const source = block.getSource();
776
- if (source) parts.push(normalizeUnicode(source));
777
- } else if (context === 'listing') {
778
- const lang = (block.getAttribute('language') as string) || '';
779
- const source = block.getSource();
780
- if (source) parts.push('```' + lang + '\n' + normalizeUnicode(source) + '\n```');
781
- } else if (context === 'open') {
782
- const text = extractOpenBlockText(block);
783
- if (text) parts.push(text);
784
- } else if (context === 'ulist' || context === 'olist') {
785
- const text = extractListText(block, context === 'olist');
786
- if (text) parts.push(text);
787
- } else if (context === 'dlist') {
788
- const text = extractDlistText(block);
789
- if (text) parts.push(text);
790
- } else if (context === 'table') {
791
- try {
792
- parts.push(tableToMarkdown(block));
793
- } catch {
794
- /* skip */
795
- }
796
- } else if (context === 'admonition') {
797
- const text = extractAdmonitionText(block);
798
- if (text) parts.push(text);
799
- } else if (
800
- context === 'quote' ||
801
- context === 'example' ||
802
- context === 'sidebar' ||
803
- context === 'preamble'
804
- ) {
805
- const text = extractContainerText(block);
806
- if (text) parts.push(text);
807
- }
808
- }
809
-
810
- return parts.filter(Boolean).join('\n\n');
811
- }
812
-
813
- function extractOpenBlockText(block: ABlock): string {
814
- const style = (block.getStyle() || '').toLowerCase();
815
- if (isDiagramType(style)) {
816
- const source = extractSourceFromBlocks(block.getBlocks());
817
- return source ? '```' + style + '\n' + normalizeUnicode(source) + '\n```' : '';
818
- }
819
-
820
- // Not a diagram — fall through to generic nested-block extraction, same as
821
- // quote/example/sidebar/preamble. (#25965: this used to be unreachable because
822
- // 'open' was matched earlier in the if/else-if chain by the diagram-only branch.)
823
- return extractContainerText(block);
824
- }
825
-
826
- function extractListText(block: ABlock, isOrdered: boolean): string {
827
- try {
828
- const items = block.getItems();
829
- if (!items || !Array.isArray(items)) return '';
830
-
831
- const lines: string[] = [];
832
- for (let idx = 0; idx < items.length; idx++) {
833
- const item = items[idx];
834
- if (typeof item.getText === 'function') {
835
- const prefix = isOrdered ? `${idx + 1}. ` : '- ';
836
- lines.push(prefix + stripInlineHtml(item.getText()));
837
- }
838
- }
839
- return lines.join('\n');
840
- } catch {
841
- return '';
842
- }
843
- }
844
-
845
- function extractDlistText(block: ABlock): string {
846
- try {
847
- const items = block.getItems();
848
- if (!items || !Array.isArray(items)) return '';
849
-
850
- const lines: string[] = [];
851
- for (const pair of items) {
852
- if (!Array.isArray(pair)) continue;
853
- const [terms, definition] = pair;
854
- if (Array.isArray(terms)) {
855
- for (const t of terms) {
856
- if (typeof t.getText === 'function') {
857
- lines.push('**' + stripInlineHtml(t.getText()) + '**');
858
- }
859
- }
860
- }
861
- if (definition && typeof definition.getText === 'function') {
862
- lines.push(': ' + stripInlineHtml(definition.getText()));
863
- }
864
- }
865
- return lines.join('\n');
866
- } catch {
867
- return '';
868
- }
869
- }
870
-
871
- function extractAdmonitionText(block: ABlock): string {
872
- const style = ((block.getStyle?.() as string) || 'note').toUpperCase();
873
- const innerBlocks = block.getBlocks();
874
- const inner = innerBlocks?.length
875
- ? extractTextFromBlocks(innerBlocks)
876
- : stripInlineHtml(block.getContent() || '');
877
- return inner ? `> [!${style}]\n> ${inner.replace(/\n/g, '\n> ')}` : '';
878
- }
879
-
880
- function extractContainerText(block: ABlock): string {
881
- const innerBlocks = block.getBlocks();
882
- if (innerBlocks && innerBlocks.length > 0) {
883
- return extractTextFromBlocks(innerBlocks);
884
- }
885
- const html = block.getContent();
886
- return html ? stripInlineHtml(html) : '';
887
- }
888
-
889
- function tableToMarkdown(block: ABlock): string {
890
- const rows = block.getRows();
891
- const headRows: string[][] = [];
892
- const bodyRows: string[][] = [];
893
- const footRows: string[][] = [];
894
-
895
- const extractRow = (row: ACell[]): string[] =>
896
- row.map((cell) => stripInlineHtml(cell.getText?.() || '').replace(/\|/g, '\\|'));
897
-
898
- for (const row of rows.head || []) {
899
- if (Array.isArray(row)) headRows.push(extractRow(row));
900
- }
901
- for (const row of rows.body || []) {
902
- if (Array.isArray(row)) bodyRows.push(extractRow(row));
903
- }
904
- for (const row of rows.foot || []) {
905
- if (Array.isArray(row)) footRows.push(extractRow(row));
906
- }
907
-
908
- const allRows = [...headRows, ...bodyRows, ...footRows];
909
- if (allRows.length === 0) return '';
910
-
911
- const colCount = Math.max(...allRows.map((r) => r.length));
912
- const pad = (row: string[]) => {
913
- while (row.length < colCount) row.push('');
914
- return row;
915
- };
916
-
917
- const lines: string[] = [];
918
-
919
- if (headRows.length > 0) {
920
- for (const row of headRows) {
921
- lines.push('| ' + pad(row).join(' | ') + ' |');
922
- }
923
- } else {
924
- // Use first body row as header if no explicit header
925
- const firstRow = bodyRows.shift();
926
- if (firstRow) {
927
- lines.push('| ' + pad(firstRow).join(' | ') + ' |');
928
- }
929
- }
930
-
931
- // Separator row
932
- lines.push('| ' + Array(colCount).fill('---').join(' | ') + ' |');
933
-
934
- for (const row of bodyRows) {
935
- lines.push('| ' + pad(row).join(' | ') + ' |');
936
- }
937
-
938
- for (const row of footRows) {
939
- lines.push('| ' + pad(row).join(' | ') + ' |');
940
- }
941
-
942
- return lines.join('\n');
943
- }
944
-
945
- function extractLinks(html: string, _relativePath: string): AsciidocLink[] {
946
- const links: AsciidocLink[] = [];
947
- const linkRegex = /<a\s[^>]*href="([^"]*)"[^>]*>([^<]*)<\/a>/gi;
948
- let match;
949
-
950
- while ((match = linkRegex.exec(html)) !== null) {
951
- const href = match[1];
952
- const text = match[2];
953
- let type: AsciidocLink['type'] = 'link';
954
-
955
- if (href.startsWith('#')) {
956
- type = 'xref';
957
- } else if (href.startsWith('http://') || href.startsWith('https://')) {
958
- type = 'url';
959
- }
960
-
961
- links.push({ href, text, type });
962
- }
963
-
964
- return links;
965
- }
966
-
967
- function normalizeImageSrc(src: string, relativePath: string): string {
968
- if (!src) return src;
969
- if (
970
- src.startsWith('/') ||
971
- src.startsWith('//') ||
972
- src.startsWith('data:') ||
973
- /^[a-z][a-z\d+\-.]*:/i.test(src)
974
- ) {
975
- return src;
976
- }
977
-
978
- const baseDir = path.posix.dirname(relativePath);
979
- const resolvedPath = path.posix.normalize(path.posix.join(baseDir, src));
980
- return `/${resolvedPath.replace(/^\/+/, '')}`;
981
- }
982
-
983
- function stripInlineHtml(text: string): string {
984
- return decodeHtmlEntities(
985
- text
986
- .replace(
987
- /<span class="icon"><i class="fa[^"]*fa-([^"\s]+)"[^>]*><\/i><\/span>/gi,
988
- (_m, name) => `:${name}:`,
989
- )
990
- .replace(/<i class="fa[^"]*fa-([^"\s]+)"[^>]*><\/i>/gi, (_m, name) => `:${name}:`)
991
- .replace(/<(?<!<[^>]*?<)[^>]+>/g, ''),
992
- );
993
- }
994
-
995
- function decodeHtmlEntities(text: string): string {
996
- return normalizeUnicode(
997
- text
998
- .replace(/&#(\d+);/g, (_m, code) => String.fromCodePoint(Number(code)))
999
- .replace(/&#x([0-9a-f]+);/gi, (_m, hex) => String.fromCodePoint(parseInt(hex, 16)))
1000
- .replace(/&amp;/g, '&')
1001
- .replace(/&lt;/g, '<')
1002
- .replace(/&gt;/g, '>')
1003
- .replace(/&quot;/g, '"')
1004
- .replace(/&apos;/g, "'"),
1005
- );
1006
- }
1007
-
1008
- function normalizeUnicode(text: string): string {
1009
- return text
1010
- .replace(/\u2014/g, '--')
1011
- .replace(/\u2013/g, '-')
1012
- .replace(/\u2018|\u2019/g, "'")
1013
- .replace(/\u201C|\u201D/g, '"')
1014
- .replace(/\u2026/g, '...')
1015
- .replace(/\u00A0/g, ' ');
1016
- }
1017
-
1018
- function slugify(text: string): string {
1019
- return text
1020
- .toLowerCase()
1021
- .replace(/[^\w\s-]/g, '')
1022
- .replace(/\s+/g, '-')
1023
- .replace(/-+/g, '-')
1024
- .replace(/^-|-$/g, '');
1025
- }