-
Notifications
You must be signed in to change notification settings - Fork 46
Expand file tree
/
Copy pathbuild.blogs.featured.mjs
More file actions
281 lines (236 loc) · 8.13 KB
/
build.blogs.featured.mjs
File metadata and controls
281 lines (236 loc) · 8.13 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
import chalk from 'chalk';
import fs from 'fs/promises';
import path from 'path';
import { fileURLToPath } from 'url';
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const BLOG_DIR = path.join(__dirname, 'blog');
const OUTPUT_DIR = path.join(__dirname, 'static/content');
const OUTPUT_FILE = path.join(OUTPUT_DIR, 'featuredblogs.json');
const FEATURED_IMAGES_DIR = path.join(__dirname, 'static/assets/blog/featured');
// Parse frontmatter from markdown content
const parseFrontmatter = (content) => {
const frontmatterRegex = /^---\n([\s\S]*?)\n---/;
const match = content.match(frontmatterRegex);
if (!match) return null;
const frontmatter = {};
const lines = match[1].split('\n');
let currentKey = null;
let currentValue = '';
let inArray = false;
for (const line of lines) {
// Check if line starts a new key-value pair
if (line.includes(':') && !inArray) {
// Save previous key-value if exists
if (currentKey) {
frontmatter[currentKey] = currentValue.trim();
}
const colonIndex = line.indexOf(':');
currentKey = line.substring(0, colonIndex).trim();
let value = line.substring(colonIndex + 1).trim();
// Check if value starts and ends with array on same line
if (value.startsWith('[') && value.endsWith(']')) {
currentValue = value;
inArray = false;
} else if (value.startsWith('[')) {
// Array spans multiple lines
inArray = true;
currentValue = value;
} else {
currentValue = value;
inArray = false;
}
} else if (inArray) {
// Continue building array value
currentValue += ' ' + line.trim();
if (line.includes(']')) {
inArray = false;
}
}
}
// Save last key-value
if (currentKey) {
frontmatter[currentKey] = currentValue.trim();
}
// Clean up values
Object.keys(frontmatter).forEach((key) => {
let value = frontmatter[key];
// Remove quotes
if (
(value.startsWith("'") && value.endsWith("'")) ||
(value.startsWith('"') && value.endsWith('"'))
) {
value = value.slice(1, -1);
}
// Parse arrays
if (value.startsWith('[') && value.endsWith(']')) {
value = value
.slice(1, -1)
.split(',')
.map((item) => item.trim().replace(/^['"]|['"]$/g, ''));
}
frontmatter[key] = value;
});
return frontmatter;
};
// Calculate reading time
const calculateReadingTime = (content) => {
const text = content.replace(/<[^>]*>/g, '').replace(/[#*`]/g, '');
const wordCount = text.split(/\s+/).filter((word) => word.length > 0).length;
return Math.max(1, Math.ceil(wordCount / 200));
};
// Get all blog directories sorted by date (newest first)
const getBlogDirectories = async () => {
try {
const items = await fs.readdir(BLOG_DIR, { withFileTypes: true });
const blogDirs = items
.filter(
(item) =>
item.isDirectory() &&
!item.name.startsWith('.') &&
item.name !== 'authors.yml'
)
.map((item) => item.name)
.filter((name) => /^\d{4}-\d{2}-\d{2}-/.test(name)) // Only date-prefixed directories
.sort((a, b) => b.localeCompare(a)); // Sort newest first
return blogDirs;
} catch (error) {
console.error(chalk.red('Error reading blog directory:'), error.message);
return [];
}
};
// Process a single blog post
const processBlogPost = async (blogDir) => {
const blogPath = path.join(BLOG_DIR, blogDir);
const indexPath = path.join(blogPath, 'index.md');
try {
const content = await fs.readFile(indexPath, 'utf-8');
const frontmatter = parseFrontmatter(content);
if (!frontmatter) {
console.log(chalk.yellow(` ⚠️ No frontmatter found in ${blogDir}`));
return null;
}
// Check if blog has "Featured" tag
const tags = Array.isArray(frontmatter.tags) ? frontmatter.tags : [];
if (!tags.some((tag) => tag.toLowerCase() === 'featured')) {
return null;
}
// Extract blog slug from directory name (or use frontmatter slug if available)
const slug = frontmatter.slug || blogDir.replace(/^\d{4}-\d{2}-\d{2}-/, '');
const link = `/blog/${slug}/`;
// Use text field from frontmatter for content
const contentText = frontmatter.text || frontmatter.description || '';
// Calculate reading time based on text field
const readingTime = calculateReadingTime(contentText);
// Copy image to featured folder and build flattened image URL
let imageUrl = null;
if (frontmatter.image) {
const imageName = frontmatter.image.replace(/^\.\//, '');
const sourceImagePath = path.join(blogPath, imageName);
// Create flattened filename: blog--slug--image.webp
const flattenedImageName = `blog--${slug}--${imageName}`;
const destImagePath = path.join(FEATURED_IMAGES_DIR, flattenedImageName);
try {
// Ensure featured images directory exists
await fs.mkdir(FEATURED_IMAGES_DIR, { recursive: true });
// Copy image to featured folder
await fs.copyFile(sourceImagePath, destImagePath);
// Set image URL to reference the copied image
imageUrl = `/assets/blog/featured/${flattenedImageName}`;
} catch (error) {
console.error(
chalk.yellow(` ⚠️ Failed to copy image for ${blogDir}:`),
error.message
);
// Fallback to original path if copy fails
imageUrl = `/blog/${slug}/${imageName}`;
}
}
// Format pubDate to match RSS format
const dateMatch = blogDir.match(/^(\d{4})-(\d{2})-(\d{2})/);
let pubDate = 'Unknown Date';
if (dateMatch) {
const [, year, month, day] = dateMatch;
const date = new Date(`${year}-${month}-${day}`);
pubDate = date.toUTCString();
}
return {
title: frontmatter.title || 'Untitled Post',
link,
slug,
pubDate,
description: contentText || frontmatter.description || '',
readingTime,
imageUrl,
tags,
authors: frontmatter.authors || [],
showcase:
frontmatter.showcase === true || frontmatter.showcase === 'true',
};
} catch (error) {
console.error(
chalk.red(` ❌ Error processing ${blogDir}:`),
error.message
);
return null;
}
};
// Main function
const buildFeaturedBlogs = async () => {
console.log(chalk.blue('🔍 Scanning blog directory for featured posts...'));
try {
// Get all blog directories
const blogDirs = await getBlogDirectories();
if (blogDirs.length === 0) {
console.log(chalk.yellow('📂 No blog posts found'));
return;
}
console.log(chalk.cyan(`📦 Found ${blogDirs.length} total blog posts`));
// Process all blogs and filter for featured ones
const featuredBlogs = [];
for (const blogDir of blogDirs) {
const blog = await processBlogPost(blogDir);
if (blog) {
featuredBlogs.push(blog);
console.log(chalk.green(` ✅ Featured: ${blog.title}`));
}
}
if (featuredBlogs.length === 0) {
console.log(chalk.yellow('⚠️ No featured blog posts found'));
return;
}
// Sort featured blogs: showcase:true first, then by date
featuredBlogs.sort((a, b) => {
// Showcase blogs come first
if (a.showcase && !b.showcase) return -1;
if (!a.showcase && b.showcase) return 1;
// If both have same showcase status, maintain date order (already sorted newest first)
return 0;
});
// Ensure output directory exists
await fs.mkdir(OUTPUT_DIR, { recursive: true });
// Write to JSON file
await fs.writeFile(
OUTPUT_FILE,
JSON.stringify(featuredBlogs, null, 2),
'utf-8'
);
console.log(
chalk.green(
`\n✅ Successfully generated featuredblogs.json with ${featuredBlogs.length} featured posts`
)
);
console.log(chalk.blue(`📄 Output: ${OUTPUT_FILE}`));
} catch (error) {
console.error(
chalk.red('❌ Error building featured blogs:'),
error.message
);
process.exit(1);
}
};
// Run if called directly
if (import.meta.url === `file://${process.argv[1]}`) {
buildFeaturedBlogs();
}
export { buildFeaturedBlogs };