-
Notifications
You must be signed in to change notification settings - Fork 11
Expand file tree
/
Copy pathmigrate.js
More file actions
3341 lines (2909 loc) · 115 KB
/
migrate.js
File metadata and controls
3341 lines (2909 loc) · 115 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env node
/**
* @fileoverview Docusaurus to Mintlify Migration Script
* @description Converts Docusaurus documentation to Mintlify format with proper MDX syntax,
* code formatting, and navigation structure. Supports multi-version migration with intelligent
* content caching and validation.
*
* @example
* // Interactive mode
* node migrate-docusaurus.js
*
* @example
* // Non-interactive mode (all versions)
* node migrate-docusaurus.js ~/repos/cosmos-sdk-docs ./tmp sdk
* node migrate-docusaurus.js ~/repos/cosmos-sdk-docs ./tmp sdk --update-nav
*
* @requires gray-matter - Parse and generate YAML frontmatter
* @requires unified - Unified text processing framework
* @requires remark-parse - Markdown parser for unified
* @requires remark-gfm - GitHub Flavored Markdown support
* @requires remark-stringify - Markdown stringifier for unified
* @requires unist-util-visit - Tree visitor for unified AST
*
* @author Cosmos SDK Team
* @version 2.0.0
* @since 2024
*/
import fs from 'fs';
import path from 'path';
import { fileURLToPath } from 'url';
import readline from 'readline';
import crypto from 'crypto';
import matter from 'gray-matter';
import { unified } from 'unified';
import remarkParse from 'remark-parse';
import remarkGfm from 'remark-gfm';
import remarkStringify from 'remark-stringify';
import { visit } from 'unist-util-visit';
import { execSync } from 'child_process';
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
// Create readline interface for prompts
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
const prompt = (question) => new Promise((resolve) => rl.question(question, resolve));
/**
* Safely process content while preserving code blocks and inline code.
* This is the foundation of our text transformation system, ensuring code is never
* accidentally modified by markdown transformations.
*
* @function safeProcessContent
* @param {string} content - The markdown content to process
* @param {Function} processor - Function to process non-code content
* @returns {string} Processed content with code blocks preserved
*
* @description
* Pipeline steps:
* 1. Extract and replace fenced code blocks with placeholders
* 2. Extract and replace inline code with placeholders
* 3. Apply processor function to remaining content
* 4. Restore inline code from placeholders
* 5. Restore fenced code blocks from placeholders
*
* This ensures transformations like escaping underscores or fixing JSX
* comments never affect actual code content.
*
* @example
* const result = safeProcessContent(content, (text) => {
* return text.replace(/_/g, '\\_'); // Escapes underscores in text only
* });
*/
function safeProcessContent(content, processor) {
// STEP 1: Extract all code blocks and inline code to protect them from processing
const codeBlocks = [];
const inlineCode = [];
let processed = content;
// STEP 2: Replace triple-backtick code blocks with placeholders
// This prevents code blocks from being modified by subsequent processing
processed = processed.replace(/```[\s\S]*?```/g, (match) => {
const index = codeBlocks.length;
codeBlocks.push(match); // Store original code block
return `__CODE_BLOCK_${index}__`; // Replace with placeholder
});
// STEP 3: Replace inline code spans of ANY tick length with placeholders
// This handles `, ``, ```, etc. to protect all code spans from processing
// The regex (`+)([^`\n]*?)\1 matches any number of backticks, content, then same number of backticks
processed = processed.replace(/(`+)([^`\n]*?)\1/g, (match) => {
const index = inlineCode.length;
inlineCode.push(match); // Store original inline code (e.g., `{groupId}` or ``{groupId}``)
return `__INLINE_CODE_${index}__`; // Replace with placeholder
});
// STEP 4: Process the content (with code replaced by placeholders)
// The processor function won't see any backtick-wrapped content
processed = processor(processed);
// STEP 5: Restore inline code first
// This puts back the original inline code (e.g., `{groupId}`) exactly as it was
// Handle both escaped and non-escaped versions (in case underscores were escaped in tables)
for (let i = 0; i < inlineCode.length; i++) {
// Try escaped version first (if underscores were escaped in table processing)
const escapedPlaceholder = `__INLINE\\_CODE_${i}__`;
const normalPlaceholder = `__INLINE_CODE_${i}__`;
if (processed.includes(escapedPlaceholder)) {
processed = processed.replace(escapedPlaceholder, inlineCode[i]);
} else {
processed = processed.replace(normalPlaceholder, inlineCode[i]);
}
}
// STEP 6: Restore code blocks last
for (let i = 0; i < codeBlocks.length; i++) {
// Try escaped version first
const escapedPlaceholder = `__CODE\\_BLOCK_${i}__`;
const normalPlaceholder = `__CODE_BLOCK_${i}__`;
if (processed.includes(escapedPlaceholder)) {
processed = processed.replace(escapedPlaceholder, codeBlocks[i]);
} else {
processed = processed.replace(normalPlaceholder, codeBlocks[i]);
}
}
return processed;
}
/**
* Parse Docusaurus frontmatter using battle-tested gray-matter library.
* Extracts YAML frontmatter and returns parsed metadata.
*
* @function parseDocusaurusFrontmatter
* @param {string} content - Raw markdown content with potential frontmatter
* @returns {Object} Parsed result
* @returns {Object} result.frontmatter - Parsed YAML frontmatter as object
* @returns {string} result.content - Content with frontmatter removed
*
* @description
* Uses gray-matter to parse YAML frontmatter from markdown.
* Handles missing frontmatter gracefully by returning empty object.
*
* Common Docusaurus frontmatter fields:
* - title: Page title
* - sidebar_label: Navigation label
* - sidebar_position: Sort order in navigation
* - description: Page description
* - slug: Custom URL slug
*
* @example
* const { frontmatter, content } = parseDocusaurusFrontmatter(
* '---\ntitle: My Page\n---\n# Content'
* );
* // frontmatter = { title: 'My Page' }
* // content = '# Content'
*/
function parseDocusaurusFrontmatter(content) {
const parsed = matter(content);
return {
frontmatter: parsed.data,
content: parsed.content
};
}
/**
* Extract title from content (first H1 heading).
* Removes the H1 from content to avoid duplication.
*
* @function extractTitleFromContent
* @param {string} content - Markdown content potentially containing H1
* @returns {Object} Extraction result
* @returns {string|null} result.title - Extracted title or null if no H1
* @returns {string} result.content - Content with H1 removed
*
* @description
* Looks for H1 heading at the start of content (after any blank lines).
* Supports both # syntax and underline (===) syntax.
* Returns the title text and content without the H1.
*
* @example
* const { title, content } = extractTitleFromContent('# My Title\n\nContent here');
* // title = 'My Title'
* // content = 'Content here'
*/
function extractTitleFromContent(content) {
const match = content.match(/^#\s+(.+)$/m);
if (match) {
return {
title: match[1].trim(),
content: content.replace(/^#\s+.+\n?/m, '').trim() // Only remove the heading line, not random content
};
}
return { title: null, content };
}
/**
* Convert Docusaurus admonitions to Mintlify callouts.
* Only processes non-code content, preserving code blocks.
*
* @function convertAdmonitions
* @param {string} content - Markdown content with Docusaurus admonitions
* @returns {string} Content with Mintlify callout components
*
* @description
* Converts Docusaurus triple-colon syntax to Mintlify components:
* - note admonitions to Note components
* - warning admonitions to Warning components
* - tip admonitions to Tip components
* - info admonitions to Info components
* - caution admonitions to Warning components
* - danger admonitions to Warning components
*
* Features:
* - Supports custom titles after the admonition type
* - Handles nested admonitions with a stack
* - Cleans up malformed syntax
* - Ensures proper tag pairing
* - Processes only non-code content
*
* @example
* // Converts Docusaurus admonition with title
* // to Mintlify Note component with bold title
*/
function convertAdmonitions(content) {
return safeProcessContent(content, (nonCodeContent) => {
const admonitionMap = {
'note': 'Note',
'tip': 'Tip',
'info': 'Info',
'warning': 'Warning',
'danger': 'Warning',
'caution': 'Warning',
'important': 'Info',
'success': 'Check',
'details': 'Accordion' // For expandable sections
};
// Use line-by-line processing to handle complex nested cases
const lines = nonCodeContent.split('\n');
const result = [];
const admonitionStack = [];
for (let i = 0; i < lines.length; i++) {
const line = lines[i];
// Check for opening admonition
const openMatch = line.match(/^:::(\w+)(?:\s+(.+))?$/);
if (openMatch) {
const type = openMatch[1].toLowerCase();
const title = openMatch[2];
const component = admonitionMap[type] || 'Note';
admonitionStack.push(component);
if (title) {
result.push(`<${component}>`);
result.push(`**${title}**`);
} else {
result.push(`<${component}>`);
}
continue;
}
// Check for closing admonition
if (line.trim() === ':::') {
if (admonitionStack.length > 0) {
const component = admonitionStack.pop();
result.push(`</${component}>`);
}
continue;
}
// Regular line
result.push(line);
}
let finalResult = result.join('\n');
// Clean up any remaining ::: artifacts and malformed syntax
finalResult = finalResult.replace(/:::\s*\n/g, '\n');
finalResult = finalResult.replace(/:::\./g, ''); // Handle malformed :::.
finalResult = finalResult.replace(/^\s*:::\s*$/gm, '');
// Fix unclosed tags by ensuring proper pairing
// If we find an opening tag without a closing tag, add the closing tag
const tagPattern = /<(Note|Warning|Tip|Info|Check)\b[^>]*>/g;
const openTags = finalResult.match(tagPattern) || [];
for (const openTag of openTags) {
const tagName = openTag.match(/<(\w+)/)[1];
const closeTag = `</${tagName}>`;
// Check if this opening tag has a corresponding closing tag
const openIndex = finalResult.indexOf(openTag);
const nextOpenIndex = finalResult.indexOf(`<${tagName}`, openIndex + openTag.length);
const closeIndex = finalResult.indexOf(closeTag, openIndex);
// If no closing tag found, or closing tag is after the next opening tag, add one
if (closeIndex === -1 || (nextOpenIndex !== -1 && closeIndex > nextOpenIndex)) {
const insertPoint = nextOpenIndex !== -1 ? nextOpenIndex : finalResult.length;
finalResult = finalResult.slice(0, insertPoint) + `\n${closeTag}\n` + finalResult.slice(insertPoint);
}
}
return finalResult;
});
}
/**
* Format Go code
*/
function formatGoCode(code) {
return code
// Fix imports
.replace(/import \(/g, 'import (\n ')
.replace(/"\s+"/g, '"\n "')
.replace(/\)\s*([a-zA-Z])/g, ')\n\n$1')
// Fix braces and structure
.replace(/\{\s*([a-zA-Z])/g, '{\n $1')
.replace(/([^}\n])\s*\}/g, '$1\n}')
.replace(/\)\s*\{/g, ') {')
.replace(/\}\s*([a-zA-Z])/g, '}\n\n$1')
// Fix struct declarations
.replace(/\{\s*([A-Z][a-zA-Z]*:)/g, '{\n $1')
.replace(/,\s*([A-Z][a-zA-Z]*:)/g, ',\n $1')
// Basic indentation
.replace(/^(\s*)([a-z][a-zA-Z]*\s*:=)/gm, ' $2')
.replace(/^(\s*)(if|for|switch|case)/gm, ' $2')
.replace(/\n{3,}/g, '\n\n')
.trim();
}
/**
* Format JavaScript/TypeScript code
*/
function formatJavaScriptCode(code) {
return code
// Fix imports
.replace(/import\s*\{([^}]+)\}\s*from/g, (match, imports) => {
const cleanImports = imports.split(',').map(imp => imp.trim()).join(',\n ');
return `import {\n ${cleanImports}\n} from`;
})
// Fix object/function braces
.replace(/\{\s*([a-zA-Z])/g, '{\n $1')
.replace(/([^}\n])\s*\}/g, '$1\n}')
.replace(/\)\s*=>\s*\{/g, ') => {')
// Fix function declarations
.replace(/function\s+([a-zA-Z_$][a-zA-Z0-9_$]*)\s*\(/g, 'function $1(')
.replace(/\)\s*\{/g, ') {')
.replace(/\n{3,}/g, '\n\n')
.trim();
}
/**
* Format Rust code
*/
function formatRustCode(code) {
return code
// Fix use statements
.replace(/use\s+([^;]+);/g, (match, usePath) => {
if (usePath.includes('{')) {
return match.replace(/\{\s*([^}]+)\s*\}/g, (m, items) => {
const cleanItems = items.split(',').map(item => item.trim()).join(',\n ');
return `{\n ${cleanItems}\n}`;
});
}
return match;
})
// Fix function formatting
.replace(/fn\s+([a-zA-Z_][a-zA-Z0-9_]*)\s*\(/g, 'fn $1(')
.replace(/\)\s*->\s*([^{]+)\s*\{/g, ') -> $1 {')
// Fix struct/impl blocks
.replace(/\{\s*([a-zA-Z])/g, '{\n $1')
.replace(/([^}\n])\s*\}/g, '$1\n}')
.replace(/\n{3,}/g, '\n\n')
.trim();
}
/**
* Format JSON code
*/
function formatJsonCode(code) {
try {
// Try to parse and reformat JSON
const parsed = JSON.parse(code);
return JSON.stringify(parsed, null, 2);
} catch {
// If not valid JSON, just clean up basic formatting
return code
.replace(/\{\s*"/g, '{\n "')
.replace(/",\s*"/g, '",\n "')
.replace(/\}\s*,/g, '\n},')
.replace(/\n{3,}/g, '\n\n')
.trim();
}
}
/**
* Generic code formatting for other languages.
* Applies basic formatting rules for unrecognized languages.
*
* @function formatGenericCode
* @param {string} code - Raw code in any language
* @returns {string} Formatted code with basic improvements
*
* @description
* Applies minimal formatting:
* - Basic brace positioning
* - Removes excessive blank lines
* - Trims whitespace
*
* Used as fallback when language-specific formatter unavailable.
*
* @example
* const formatted = formatGenericCode('function() {return true}');
* // Returns code with improved brace positioning
*/
function formatGenericCode(code) {
return code
// Basic brace formatting
.replace(/\{\s*([a-zA-Z])/g, '{\n $1')
.replace(/([^}\n])\s*\}/g, '$1\n}')
// Basic function-like patterns
.replace(/\)\s*\{/g, ') {')
// Clean up spacing
.replace(/\n{3,}/g, '\n\n')
.trim();
}
/**
* Fix internal documentation links for Mintlify's product-based structure.
* Only processes non-code content, preserving links in code blocks.
*
* @function fixInternalLinks
* @param {string} content - Markdown content with internal links
* @param {string} version - Target version (e.g., 'next', 'v0.50')
* @param {string} [product='generic'] - Product name for namespacing
* @returns {string} Content with updated internal links
*
* @description
* Cleans up Docusaurus-specific patterns:
* - Removes Docusaurus-specific "Direct link" anchor links
* - Removes heading ID anchors (e.g., {#my-anchor})
*
* Note: All relative link resolution (../, ./, implicit paths) is handled by
* the AST-based createLinkFixerPlugin which properly resolves paths using the
* source file location. File extension removal and product/version prefixing
* are also handled by the AST plugin.
*
* Link transformation examples:
* - [](#heading "Direct link to Heading") → (removed)
* - # Heading {#my-anchor} → # Heading
*
* @example
* const fixed = fixInternalLinks(
* 'markdown with relative link',
* 'v0.50',
* 'sdk'
* );
* // Returns markdown with absolute versioned link
*/
function fixInternalLinks(content, version, product = 'generic') {
return safeProcessContent(content, (nonCodeContent) => {
let result = nonCodeContent;
// Remove Docusaurus-specific "Direct link" anchors
result = result.replace(/\[\]\(#[^)]+\s+"Direct link to[^"]+"\)/g, '');
// Remove heading anchors {#anchor}
result = result.replace(/^(#+\s+.+?)\s*\{#[^}]+\}\s*$/gm, '$1');
// Note: Relative link resolution (../, ./, implicit paths) is handled by
// the AST-based createLinkFixerPlugin which properly resolves paths using
// the source file location. No need for regex-based link fixing here.
return result;
});
}
/**
* Copy static assets (images) from source to target directory.
* Recursively copies all image files while preserving directory structure.
*
* @function copyStaticAssets
* @param {string} staticPath - Source directory containing static assets
* @param {string} targetImagesDir - Target directory for images
*
* @description
* Copies image assets with the following features:
* - Recursively traverses source directory
* - Preserves directory structure in target
* - Copies common image formats: png, jpg, jpeg, gif, svg, webp
* - Creates target directories as needed
* - Skips non-image files
*
* @example
* copyStaticAssets(
* '/source/static',
* './assets/product/images'
* );
* // Copies all images from /source/static to ./assets/product/images
*/
function copyStaticAssets(staticPath, targetImagesDir) {
if (!fs.existsSync(targetImagesDir)) {
fs.mkdirSync(targetImagesDir, { recursive: true });
}
function copyImages(dir, targetSubDir = '') {
const items = fs.readdirSync(dir);
for (const item of items) {
const sourcePath = path.join(dir, item);
const stat = fs.statSync(sourcePath);
if (stat.isDirectory()) {
// Recursively copy subdirectories
const newTargetSubDir = path.join(targetSubDir, item);
copyImages(sourcePath, newTargetSubDir);
} else if (item.match(/\.(png|jpg|jpeg|gif|svg|webp)$/i)) {
// Copy image files
const targetPath = path.join(targetImagesDir, 'static', targetSubDir, item);
const targetDir = path.dirname(targetPath);
if (!fs.existsSync(targetDir)) {
fs.mkdirSync(targetDir, { recursive: true });
}
fs.copyFileSync(sourcePath, targetPath);
console.log(` Copied: static/${targetSubDir}/${item}`);
}
}
}
copyImages(staticPath);
}
/**
* Update image paths to use centralized images folder.
* Moves images from versioned directories to shared location.
*
* @function updateImagePaths
* @param {string} content - Content with image references
* @param {string} sourceRelativePath - Relative path of source file
* @param {string} version - Version directory name
* @returns {string} Content with updated image paths
*
* @description
* Updates image references to point to centralized images directory:
* - Removes version from image paths
* - Handles both markdown and HTML image syntax
* - Preserves relative path structure within images folder
*
* Path transformation:
* - Local images to centralized dirname path
* - Parent directory images to root images path
*
* @example
* const updated = updateImagePaths(
* 'markdown with local image reference',
* 'learn/intro.md',
* 'v0.50'
* );
* // Returns markdown with centralized image path
*/
function updateImagePaths(content, sourceRelativePath, version) {
let result = content;
// Calculate the depth of the source file to determine relative path to images
const sourceDepth = sourceRelativePath.split('/').length - 1;
const pathToRoot = sourceDepth > 0 ? '../'.repeat(sourceDepth) : './';
// Images are at the same level as version directories (e.g., sdk/images/)
const pathToImages = `${pathToRoot}../images/`;
// Update local image references (./image.png or ../image.png)
// Match both markdown images  and HTML img tags
result = result.replace(/(!\[[^\]]*\]\()(\.\.\/|\.\/)([^)]+\.(png|jpg|jpeg|gif|svg|webp))/gi,
(match, prefix, relative, imagePath) => {
const imageName = path.basename(imagePath);
const imageDir = path.dirname(imagePath);
const sourceDir = path.dirname(sourceRelativePath);
// Strip numbered prefixes from source directory for clean image paths
const cleanSourceDir = sourceDir.replace(/\/(\d+-)/g, '/').replace(/^(\d+-)/, '');
if (relative === './' && imageDir === '.') {
// Image in same directory as markdown
return `${prefix}${pathToImages}${cleanSourceDir}/${imageName}`;
} else if (relative === '../') {
// Image in parent directory
const parentSourceDir = path.dirname(cleanSourceDir);
return `${prefix}${pathToImages}${parentSourceDir}/${imagePath}`;
} else {
// Image in subdirectory
return `${prefix}${pathToImages}${cleanSourceDir}/${imagePath}`;
}
});
// Update HTML img tags
result = result.replace(/(<img[^>]+src=")(\.\.\/|\.\/)([^"]+\.(png|jpg|jpeg|gif|svg|webp))/gi,
(match, prefix, relative, imagePath) => {
const imageName = path.basename(imagePath);
const imageDir = path.dirname(imagePath);
if (imageDir === '.') {
const sourceDir = path.dirname(sourceRelativePath);
// Strip numbered prefixes from source directory for clean image paths
const cleanSourceDir = sourceDir.replace(/\/(\d+-)/g, '/').replace(/^(\d+-)/, '');
return `${prefix}${pathToImages}${cleanSourceDir}/${imageName}`;
} else {
return `${prefix}${pathToImages}${imagePath}`;
}
});
// Handle references to /img/ or /static/ folders (from Docusaurus static folder)
result = result.replace(/(!\[[^\]]*\]\()(\/(img|static)\/[^)]+\.(png|jpg|jpeg|gif|svg|webp))/gi,
(match, prefix, imagePath) => {
// Convert /img/file.png to images/static/img/file.png
// Convert /static/file.png to images/static/file.png
const cleanPath = imagePath.startsWith('/') ? imagePath.slice(1) : imagePath;
return `${prefix}${pathToImages}static/${cleanPath.replace(/^static\//, '')}`;
});
// Handle HTML img tags with /img/ or /static/ paths
result = result.replace(/(<img[^>]+src=")(\/(img|static)\/[^"]+\.(png|jpg|jpeg|gif|svg|webp))/gi,
(match, prefix, imagePath) => {
const cleanPath = imagePath.startsWith('/') ? imagePath.slice(1) : imagePath;
return `${prefix}${pathToImages}static/${cleanPath.replace(/^static\//, '')}`;
});
// Handle GitHub raw content URLs (keep them as-is)
// These don't need updating as they're external URLs
return result;
}
/**
* Content-based migration cache system.
* Implements SHA-256 checksumming to detect duplicate content across versions,
* significantly improving performance by processing identical content only once.
*
* @namespace migrationCache
* @description
* The cache system tracks:
* - Content checksums to detect duplicates
* - Transformation results to reuse for identical content
* - Validation errors per unique content block
* - File paths mapped to their content checksums
*
* This enables efficient processing where identical files across versions
* (e.g., v0.47, v0.50, v0.53) are transformed only once but written to
* all appropriate locations.
*
* @example
* // Process flow with caching:
* // 1. File A in v0.47: Full processing, cached
* // 2. File A in v0.50 (identical): Cache hit, skip processing
* // 3. File A in v0.53 (modified): Different checksum, full processing
*/
const migrationCache = {
// Map of content checksum → migration result
contentCache: new Map(),
// Map of content checksum → validation errors
validationCache: new Map(),
// Map of file path → content checksum
fileChecksums: new Map(),
/**
* Calculate SHA-256 checksum of content
*/
getChecksum(content) {
return crypto.createHash('sha256').update(content, 'utf8').digest('hex');
},
/**
* Check if content has been processed before
*/
hasProcessed(checksum) {
return this.contentCache.has(checksum);
},
/**
* Get cached migration result
*/
getCachedResult(checksum) {
return this.contentCache.get(checksum);
},
/**
* Cache migration result
*/
cacheResult(checksum, result) {
this.contentCache.set(checksum, result);
},
/**
* Get cached validation errors
*/
getCachedValidation(checksum) {
return this.validationCache.get(checksum) || [];
},
/**
* Cache validation errors
*/
cacheValidation(checksum, errors) {
this.validationCache.set(checksum, errors);
},
/**
* Track file checksum
*/
trackFile(filepath, checksum) {
this.fileChecksums.set(filepath, checksum);
},
/**
* Get statistics
*/
getStats() {
return {
uniqueContent: this.contentCache.size,
totalFiles: this.fileChecksums.size,
duplicates: this.fileChecksums.size - this.contentCache.size
};
},
/**
* Clear cache
*/
clear() {
this.contentCache.clear();
this.validationCache.clear();
this.fileChecksums.clear();
}
};
// Global issue tracker for reporting
const migrationIssues = {
warnings: [],
errors: [],
info: [],
currentFile: '',
processedFiles: new Set(),
addWarning(line, issue, suggestion = '') {
this.warnings.push({
file: this.currentFile,
line,
issue,
suggestion
});
},
addRemoval(message, details) {
this.info.push({
file: this.currentFile,
message,
details
});
},
addError(line, issue, suggestion = '') {
this.errors.push({
file: this.currentFile,
line,
issue,
suggestion
});
},
setCurrentFile(filepath) {
this.currentFile = filepath;
},
reset() {
this.warnings = [];
this.errors = [];
this.currentFile = '';
this.processedFiles.clear();
},
generateReport() {
const totalIssues = this.warnings.length + this.errors.length;
if (totalIssues === 0) return '';
let report = '\n' + '='.repeat(80) + '\n';
report += ' MIGRATION REPORT\n';
report += '='.repeat(80) + '\n\n';
if (this.errors.length > 0) {
report += ` ERRORS (${this.errors.length}) - These need manual fixes:\n`;
report += '-'.repeat(40) + '\n';
const errorsByFile = {};
this.errors.forEach(err => {
if (!errorsByFile[err.file]) errorsByFile[err.file] = [];
errorsByFile[err.file].push(err);
});
Object.entries(errorsByFile).forEach(([file, errors]) => {
report += `\n ${file}:\n`;
errors.forEach(err => {
report += ` Line ${err.line}: ${err.issue}\n`;
if (err.suggestion) {
report += ` Suggestion: ${err.suggestion}\n`;
}
});
});
report += '\n';
}
if (this.warnings.length > 0) {
report += ` WARNINGS (${this.warnings.length}) - Automatically handled but please verify:\n`;
report += '-'.repeat(40) + '\n';
const warningsByFile = {};
this.warnings.forEach(warn => {
if (!warningsByFile[warn.file]) warningsByFile[warn.file] = [];
warningsByFile[warn.file].push(warn);
});
Object.entries(warningsByFile).forEach(([file, warnings]) => {
report += `\n ${file}:\n`;
warnings.forEach(warn => {
report += ` Line ${warn.line}: ${warn.issue}\n`;
if (warn.suggestion) {
report += ` Applied: ${warn.suggestion}\n`;
}
});
});
}
// Report removed content that couldn't be safely converted
if (this.info.length > 0) {
report += `REMOVED CONTENT (${this.info.length}) - Content that was removed:\n`;
report += '-'.repeat(40) + '\n';
const infoByFile = {};
this.info.forEach(info => {
if (!infoByFile[info.file]) infoByFile[info.file] = [];
infoByFile[info.file].push(info);
});
Object.entries(infoByFile).forEach(([file, infos]) => {
report += `\n${file}:\n`;
infos.forEach(info => {
report += ` ${info.message}: ${info.details}\n`;
});
});
report += '\n';
}
report += '\n' + '='.repeat(80) + '\n';
report += `Summary: ${this.errors.length} errors, ${this.warnings.length} warnings`;
if (this.info.length > 0) {
report += `, ${this.info.length} removals`;
}
report += '\n';
report += '='.repeat(80) + '\n';
return report;
}
};
/**
* Fix common MDX parsing issues while preserving all code content.
* Applies automatic fixes for known Docusaurus to Mintlify incompatibilities.
*
* @function fixMDXIssues
* @param {string} content - The markdown content to fix
* @param {string} [filepath=''] - Path to file being processed (for error context)
* @returns {string} Fixed content with MDX issues resolved
*
* @description
* Automatic fixes applied (in order):
* 1. Escape underscores in table cells for proper rendering
* 2. Fix invalid JSX comment escaping
* 3. Fix expressions with hyphens that break JSX parsing
* 4. Convert double backticks to single backticks
* 5. Convert HTML comments to JSX comments
* 6. Escape template variables outside code to inline code
* 7. Fix unclosed braces in expressions
* 8. Convert <details> to <Expandable> for Mintlify
* 9. Fix backticks in link text for proper MDX rendering
*
* All transformations use safeProcessContent() to preserve code blocks.
* Error reporting is handled separately in validateMDXContent().
*
* @see {@link safeProcessContent} - For code block preservation
* @see {@link validateMDXContent} - For error reporting
*/
function fixMDXIssues(content, filepath = '') {
// No error reporting in this function - only fixes
// Error reporting is done in validateMDXContent()
// ALL transformations happen inside safeProcessContent
// This ensures code blocks are completely untouched
return safeProcessContent(content, (nonCodeContent) => {
// CRITICAL FIX 1: Escape underscores in table cells (epochs_number -> epochs\\_number)
// This must be done FIRST before any other processing
nonCodeContent = nonCodeContent.replace(/(\|[^|]*?)([a-zA-Z]+)_([a-zA-Z]+)([^|]*?\|)/g, (match, before, word1, word2, after) => {
// Escape underscores within table cells (including placeholders - we handle them later)
return `${before}${word1}\\_${word2}${after}`;
});
// CRITICAL FIX 1b: Escape template variables and JSON objects in table cells
// This prevents acorn parsing errors for content like {"denom":"uatom"}
nonCodeContent = nonCodeContent.replace(/(\|[^|\n]*)(\{[^}|\n]+\})([^|\n]*\|)/g, (match, before, templateVar, after) => {
// Wrap template variables and JSON in backticks within table cells
return `${before}\`${templateVar}\`${after}`;
});
// Fix invalid JSX comments with escaped characters
// Handle complete escaped comments: {/\*...\*/}
nonCodeContent = nonCodeContent.replace(/\{\/\\\*([^}]*)\\\*\/\}/g, (match, content) => {
return '{/* ' + content.trim() + ' */}';
});
// Handle partial escaped comment starts: {/\*
nonCodeContent = nonCodeContent.replace(/\{\/\\\*/g, '{/*');
// Handle partial escaped comment ends: \*/}
nonCodeContent = nonCodeContent.replace(/\\\*\/\}/g, '*/}');
// Fix unclosed JSX comments - ensure all {/* have matching */}
nonCodeContent = nonCodeContent.replace(/\{\/\*([^*]|\*(?!\/))*$/gm, (match) => {
// Add closing */} if missing
return match + ' */}';
});
// Fix orphaned comment closings */} without opening {/*
nonCodeContent = nonCodeContent.replace(/^[^{]*\*\/\}/gm, (match) => {
// Add opening {/* if missing
return '{/* ' + match;
});
// Fix HTML elements with hyphens in tag names (e.g., <custom-element>)
// Convert to PascalCase for JSX compatibility
nonCodeContent = nonCodeContent.replace(/<([a-z]+(?:-[a-z]+)+)([^>]*>)/gi, (match, tagName, rest) => {
// Skip if already in backticks
if (match.includes('`')) return match;
// Convert kebab-case to PascalCase
const pascalCase = tagName.split('-')
.map(part => part.charAt(0).toUpperCase() + part.slice(1))
.join('');
return `<${pascalCase}${rest}`;
});
// Also convert closing tags
nonCodeContent = nonCodeContent.replace(/<\/([a-z]+(?:-[a-z]+)+)>/gi, (match, tagName) => {
const pascalCase = tagName.split('-')
.map(part => part.charAt(0).toUpperCase() + part.slice(1))
.join('');
return `</${pascalCase}>`;
});
// Fix expressions with hyphens that break JSX parsing
nonCodeContent = nonCodeContent.replace(/`([^`]*<[^>]*-[^>]*>[^`]*)`/g, (match, content) => {
if (content.match(/<-+>/)) {
return '`' + content + '`';
}
return match;
});
// Fix double backticks to single backticks
nonCodeContent = nonCodeContent.replace(/``([^`]+)``/g, (match, content) => {
return '`' + content + '`';
});
// Convert HTML comments to JSX comments, handling incomplete ones
nonCodeContent = nonCodeContent.replace(/<!--\s*(.*?)\s*-->/gs, '{/* $1 */}');
// Handle incomplete HTML comments that never close
nonCodeContent = nonCodeContent.replace(/<!--([^]*?)(?!-->)(?=\n|$)/g, '{/* $1 */}');