Skip to content

Commit 3d2d022

Browse files
committed
chore: improve mdx to md conversion
1 parent 196f0a7 commit 3d2d022

5 files changed

Lines changed: 59 additions & 61 deletions

File tree

mdx-to-md-converter/src/index.ts

Lines changed: 5 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -234,24 +234,14 @@ async function main() {
234234
fs.mkdirSync(outputFileDir, { recursive: true });
235235
}
236236

237-
let aiProcessedContent: string | null = null;
238-
try {
239-
console.log(`Processing with AI: ${displayPath}`);
240-
const aiResult = await overviewByAI(mdContent);
241-
if (aiResult && aiResult.trim().length >= 50) {
242-
aiProcessedContent = aiResult.trim();
243-
} else {
244-
console.warn(`⚠️ AI returned empty/short result for ${displayPath}, skipping write`);
245-
}
246-
} catch (aiErr) {
247-
console.warn(`⚠️ AI failed for ${displayPath}, skipping write`, aiErr);
248-
}
249-
250-
if (!aiProcessedContent) {
251-
console.warn(`⏭️ Skipping MD write for ${displayPath} due to AI unavailability`);
237+
console.log(`Processing with AI: ${displayPath}`);
238+
const aiRes = await overviewByAI(mdContent);
239+
if (aiRes.status !== 'SUCCESS') {
240+
console.warn(`⏭️ Skipping MD write for ${displayPath} due to AI status: ${aiRes.status}`);
252241
skippedAiCount++;
253242
continue;
254243
}
244+
const aiProcessedContent = aiRes.text;
255245

256246
let originalPath = relativePath.replace(/\.mdx$/, '');
257247
if (originalPath.endsWith('/index')) {

mdx-to-md-converter/src/modules/overviewByAI.ts

Lines changed: 28 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,11 @@
11
import { createOpenAICompatible } from '@ai-sdk/openai-compatible';
22
import { generateText } from 'ai';
33
import dotenv from 'dotenv';
4+
import path from 'path';
45

56
dotenv.config();
7+
dotenv.config({ path: path.join(__dirname, '../..', '.env') });
8+
dotenv.config({ path: path.join(__dirname, '../../..', '.env') });
69

710
const MAX_CHUNK_SIZE = 50000;
811

@@ -57,17 +60,25 @@ considaring:
5760
return text;
5861
}
5962

60-
export async function overviewByAI(informal_md: string): Promise<string> {
61-
try {
62-
const baseURL = process.env.MY_BASE_URL;
63-
const apiKey = process.env.MY_API_KEY;
63+
export type AIResultStatus = 'SUCCESS' | 'SKIPPED' | 'FAILED';
6464

65-
if (!baseURL || !apiKey) {
66-
throw new Error('MY_BASE_URL and MY_API_KEY environment variables must be set');
67-
}
65+
export interface AIResult {
66+
status: AIResultStatus;
67+
text: string;
68+
}
69+
70+
export async function overviewByAI(informal_md: string): Promise<AIResult> {
71+
const baseURL = process.env.MY_BASE_URL;
72+
const apiKey = process.env.MY_API_KEY;
73+
74+
if (!baseURL || !apiKey) {
75+
console.warn('AI disabled/unavailable: MY_BASE_URL or MY_API_KEY not set; skipping AI conversion');
76+
return { status: 'SKIPPED', text: '' };
77+
}
6878

79+
try {
6980
const chunks = splitIntoChunks(informal_md, MAX_CHUNK_SIZE);
70-
81+
7182
if (chunks.length > 1) {
7283
console.log(`Content split into ${chunks.length} chunks`);
7384
}
@@ -78,23 +89,26 @@ export async function overviewByAI(informal_md: string): Promise<string> {
7889
if (chunks.length > 1) {
7990
console.log(`Processing chunk ${i + 1}/${chunks.length}...`);
8091
}
81-
92+
8293
const processed = await processChunk(chunks[i], baseURL, apiKey, i, chunks.length);
8394
processedChunks.push(processed);
84-
95+
8596
if (i < chunks.length - 1) {
8697
await new Promise(resolve => setTimeout(resolve, 1000));
8798
}
8899
} catch (chunkError: any) {
89100
console.error(`Error processing chunk ${i + 1}/${chunks.length}:`, chunkError.message);
90-
processedChunks.push(chunks[i]);
101+
return { status: 'FAILED', text: '' };
91102
}
92103
}
93104

94-
return processedChunks.join('\n\n');
95-
105+
const text = processedChunks.join('\n\n').trim();
106+
if (text.length < 50) {
107+
return { status: 'FAILED', text: '' };
108+
}
109+
return { status: 'SUCCESS', text };
96110
} catch (error: any) {
97111
console.error('Error in overviewByAI:', error.message || error);
98-
return informal_md;
112+
return { status: 'FAILED', text: '' };
99113
}
100114
}

mdx-to-md-converter/src/pre-commit.ts

Lines changed: 25 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -121,28 +121,35 @@ async function main() {
121121
console.log(`📝 Found ${stagedChanges.modified.length} staged modified/added MDX files`);
122122
console.log(`🗑️ Found ${stagedChanges.deleted.length} staged deleted MDX files`);
123123

124+
const args = new Set(process.argv.slice(2));
125+
const onlyStaged = args.has('--only-staged') || !args.has('--all');
126+
const repairMissing = args.has('--repair-missing') || args.has('--repair-missing=1');
127+
const aiEnabled = !!(process.env.MY_BASE_URL && process.env.MY_API_KEY);
128+
129+
console.log(`⚙️ Options -> mode: ${onlyStaged ? 'only-staged' : 'all'}, repair-missing: ${repairMissing ? 'on' : 'off'}`);
130+
console.log(`🤖 AI enabled: ${aiEnabled ? 'yes' : 'no (will skip MD writes)'}`);
124131
if (stagedChanges.deleted.length > 0) {
125132
console.log('🗑️ Deleting corresponding MD files for deleted MDX files...');
126133
deleteCorrespondingMdFiles(stagedChanges.deleted);
127134
}
128135

129136
console.log('🔍 Checking for MDX files without corresponding MD files...');
130-
const missingMdFiles = findMdxFilesWithoutMd(srcPagesPath, outputDir);
137+
const missingMdFiles = repairMissing ? findMdxFilesWithoutMd(srcPagesPath, outputDir) : [];
131138

132139
let filesToProcess: string[] = [];
133-
134-
if (missingMdFiles.length > 0) {
135-
console.log(`📝 Found ${missingMdFiles.length} MDX files without corresponding MD files`);
136-
137-
const missingMdFilesFullPaths = missingMdFiles.map(relPath =>
138-
`src/pages/${relPath}`
139-
);
140-
141-
const allFilesToProcess = [...new Set([...stagedChanges.modified, ...missingMdFilesFullPaths])];
142-
filesToProcess = getAbsolutePaths(allFilesToProcess, projectRoot);
143-
} else {
144-
filesToProcess = getAbsolutePaths(stagedChanges.modified, projectRoot);
140+
const relPaths: string[] = [];
141+
142+
relPaths.push(...stagedChanges.modified);
143+
144+
if (repairMissing && missingMdFiles.length > 0) {
145+
console.log(`📝 Found ${missingMdFiles.length} MDX files without corresponding MD files (repair requested)`);
146+
const missingMdFilesFullPaths = missingMdFiles.map(relPath => `src/pages/${relPath}`);
147+
for (const p of missingMdFilesFullPaths) {
148+
if (!relPaths.includes(p)) relPaths.push(p);
149+
}
145150
}
151+
152+
filesToProcess = getAbsolutePaths(relPaths, projectRoot);
146153

147154
if (filesToProcess.length === 0 && stagedChanges.deleted.length === 0) {
148155
console.log('ℹ️ No MDX files to process');
@@ -185,24 +192,14 @@ async function main() {
185192
fs.mkdirSync(outputFileDir, { recursive: true });
186193
}
187194

188-
let aiProcessedContent: string | null = null;
189-
try {
190-
console.log(`🤖 Processing with AI: ${displayPath}`);
191-
const aiResult = await overviewByAI(mdContent);
192-
if (aiResult && aiResult.trim().length >= 50) {
193-
aiProcessedContent = aiResult.trim();
194-
} else {
195-
console.warn(`⚠️ AI returned empty/short result for ${displayPath}, skipping write`);
196-
}
197-
} catch (aiErr) {
198-
console.warn(`⚠️ AI failed for ${displayPath}, skipping write`, aiErr);
199-
}
200-
201-
if (!aiProcessedContent) {
202-
console.warn(`⏭️ Skipping MD write for ${displayPath} due to AI unavailability`);
195+
console.log(`🤖 Processing with AI: ${displayPath}`);
196+
const aiRes = await overviewByAI(mdContent);
197+
if (aiRes.status !== 'SUCCESS') {
198+
console.warn(`⏭️ Skipping MD write for ${displayPath} due to AI status: ${aiRes.status}`);
203199
skippedAiCount++;
204200
continue;
205201
}
202+
const aiProcessedContent = aiRes.text;
206203

207204
let originalPath = relativePath.replace(/\.mdx$/, '');
208205
if (originalPath.endsWith('/index')) {

src/pages/iaas/about.mdx

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@ import Highlight from "@/components/Common/highlight";
1010
import Link from "next/link";
1111
import PlatformIcon from "@/components/Common/icons";
1212

13-
import {
13+
import {
1414
GoContainer,
1515
GoDatabase,
1616
GoRocket,

src/pages/tmp/ai-skip-test.mdx

Lines changed: 0 additions & 3 deletions
This file was deleted.

0 commit comments

Comments
 (0)