-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbuild.js
More file actions
375 lines (317 loc) Β· 11 KB
/
build.js
File metadata and controls
375 lines (317 loc) Β· 11 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
/**
* Static Site Generator for arnav.log
*
* Converts markdown posts in content/posts/ to HTML using the post template.
* Also generates the blog listing data.
*
* Usage:
* node build.js # Build once
* node build.js --watch # Watch for changes
*/
import fs from 'fs';
import path from 'path';
import { fileURLToPath } from 'url';
import matter from 'gray-matter';
import { marked } from 'marked';
import hljs from 'highlight.js';
import Mustache from 'mustache';
// ESM __dirname equivalent
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
// Paths
const CONTENT_DIR = path.join(__dirname, 'content', 'posts');
const OUTPUT_DIR = path.join(__dirname, 'posts');
const TEMPLATE_PATH = path.join(__dirname, 'templates', 'post.html');
const BLOG_DATA_PATH = path.join(__dirname, 'blog', 'posts.json');
const CONTENT_IMAGES_DIR = path.join(__dirname, 'content', 'images');
const OUTPUT_IMAGES_DIR = path.join(__dirname, 'images');
// Configure marked with syntax highlighting
marked.setOptions({
highlight: function(code, lang) {
if (lang && hljs.getLanguage(lang)) {
try {
return hljs.highlight(code, { language: lang }).value;
} catch (err) {
console.warn(`Highlight error for language ${lang}:`, err.message);
}
}
return hljs.highlightAuto(code).value;
},
gfm: true,
breaks: false,
pedantic: false,
smartLists: true,
smartypants: true
});
// Custom renderer for additional styling
const renderer = new marked.Renderer();
// Code blocks - clean terminal style without copy button
renderer.code = function(code, language) {
const validLang = language && hljs.getLanguage(language) ? language : 'plaintext';
let highlighted;
try {
highlighted = hljs.highlight(code, { language: validLang }).value;
} catch {
highlighted = hljs.highlightAuto(code).value;
}
return `<div class="code-block">
<div class="code-block-header">
<span class="code-dot red"></span>
<span class="code-dot yellow"></span>
<span class="code-dot green"></span>
<span class="code-lang">${validLang}</span>
</div>
<pre class="code-body"><code class="hljs language-${validLang}">${highlighted}</code></pre>
</div>`;
};
// Add IDs to headings for TOC linking
renderer.heading = function(text, level) {
const slug = slugify(text);
return `<h${level} id="${slug}">${text}</h${level}>`;
};
// Add target="_blank" to external links
renderer.link = function(href, title, text) {
const isExternal = href && (href.startsWith('http://') || href.startsWith('https://'));
const titleAttr = title ? ` title="${title}"` : '';
const externalAttrs = isExternal ? ' target="_blank" rel="noopener noreferrer"' : '';
return `<a href="${href}"${titleAttr}${externalAttrs}>${text}</a>`;
};
marked.use({ renderer });
// Utilities
function slugify(text) {
return text
.toLowerCase()
.replace(/<[^>]*>/g, '') // Remove HTML tags
.replace(/[^\w\s-]/g, '') // Remove special chars
.replace(/\s+/g, '-') // Replace spaces with hyphens
.replace(/-+/g, '-') // Collapse multiple hyphens
.trim();
}
function escapeHtml(text) {
return text
.replace(/&/g, '&')
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/"/g, '"')
.replace(/'/g, ''');
}
function calculateReadingTime(text) {
const wordsPerMinute = 200;
const words = text.trim().split(/\s+/).length;
return Math.ceil(words / wordsPerMinute);
}
function countWords(text) {
return text.trim().split(/\s+/).length;
}
function formatDate(date) {
const d = new Date(date);
const months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
return `${d.getDate().toString().padStart(2, '0')} ${months[d.getMonth()]} ${d.getFullYear()}`;
}
function getISODate(date) {
return new Date(date).toISOString().split('T')[0];
}
// Copy images from content/images to root images directory
function copyImages() {
if (!fs.existsSync(CONTENT_IMAGES_DIR)) {
return 0;
}
if (!fs.existsSync(OUTPUT_IMAGES_DIR)) {
fs.mkdirSync(OUTPUT_IMAGES_DIR, { recursive: true });
}
const images = fs.readdirSync(CONTENT_IMAGES_DIR);
let copied = 0;
for (const image of images) {
const src = path.join(CONTENT_IMAGES_DIR, image);
const dest = path.join(OUTPUT_IMAGES_DIR, image);
// Only copy files, not directories
if (fs.statSync(src).isFile()) {
fs.copyFileSync(src, dest);
copied++;
}
}
return copied;
}
// Read all markdown files
function getMarkdownFiles() {
if (!fs.existsSync(CONTENT_DIR)) {
console.log(`Creating content directory: ${CONTENT_DIR}`);
fs.mkdirSync(CONTENT_DIR, { recursive: true });
return [];
}
return fs.readdirSync(CONTENT_DIR)
.filter(file => file.endsWith('.md'))
.map(file => path.join(CONTENT_DIR, file));
}
// Parse a markdown file
function parseMarkdownFile(filePath) {
const fileContent = fs.readFileSync(filePath, 'utf-8');
const { data: frontmatter, content } = matter(fileContent);
// Extract plain text for word count (strip markdown)
const plainText = content
.replace(/```[\s\S]*?```/g, '') // Remove code blocks
.replace(/`[^`]*`/g, '') // Remove inline code
.replace(/\[([^\]]*)\]\([^)]*\)/g, '$1') // Replace links with text
.replace(/[#*_~`]/g, ''); // Remove markdown chars
const wordCount = countWords(plainText);
const readingTime = calculateReadingTime(plainText);
// Convert markdown to HTML
const htmlContent = marked(content);
// Generate slug from filename
const slug = path.basename(filePath, '.md');
return {
slug,
filePath,
frontmatter,
content: htmlContent,
rawContent: content,
wordCount,
readingTime,
// Normalize frontmatter fields
title: frontmatter.title || 'Untitled',
description: frontmatter.description || frontmatter.summary || '',
date: frontmatter.date || new Date(),
tags: frontmatter.tags || frontmatter.categories || [],
draft: frontmatter.draft || false
};
}
// Generate HTML for a single post
function generatePostHtml(post, allPosts, template) {
const siteUrl = 'https://arnav.dev'; // Replace with actual URL
const postUrl = `${siteUrl}/posts/${post.slug}.html`;
// Find prev/next posts
const publishedPosts = allPosts
.filter(p => !p.draft)
.sort((a, b) => new Date(b.date) - new Date(a.date));
const currentIndex = publishedPosts.findIndex(p => p.slug === post.slug);
const prevPost = currentIndex < publishedPosts.length - 1 ? publishedPosts[currentIndex + 1] : null;
const nextPost = currentIndex > 0 ? publishedPosts[currentIndex - 1] : null;
const templateData = {
title: post.title,
description: post.description,
date: formatDate(post.date),
isoDate: getISODate(post.date),
tags: post.tags,
readingTime: post.readingTime,
wordCount: post.wordCount.toLocaleString(),
content: post.content,
url: postUrl,
encodedUrl: encodeURIComponent(postUrl),
encodedTitle: encodeURIComponent(post.title),
navigation: (prevPost || nextPost) ? {
prev: prevPost ? {
url: `${prevPost.slug}.html`,
title: prevPost.title
} : null,
next: nextPost ? {
url: `${nextPost.slug}.html`,
title: nextPost.title
} : null
} : null
};
return Mustache.render(template, templateData);
}
// Generate blog listing JSON data
function generateBlogListingData(posts) {
const publishedPosts = posts
.filter(p => !p.draft)
.sort((a, b) => new Date(b.date) - new Date(a.date));
return publishedPosts.map(post => ({
slug: post.slug,
url: `../posts/${post.slug}.html`,
title: post.title,
description: post.description,
date: formatDate(post.date),
isoDate: getISODate(post.date),
tags: post.tags,
readingTime: post.readingTime,
wordCount: post.wordCount
}));
}
// Main build function
async function build() {
console.log('\nπ§ Building arnav.log...\n');
// Ensure output directory exists
if (!fs.existsSync(OUTPUT_DIR)) {
fs.mkdirSync(OUTPUT_DIR, { recursive: true });
}
// Ensure blog directory exists
const blogDir = path.dirname(BLOG_DATA_PATH);
if (!fs.existsSync(blogDir)) {
fs.mkdirSync(blogDir, { recursive: true });
}
// Copy images from content/images to root images/
const imagesCopied = copyImages();
if (imagesCopied > 0) {
console.log(`π· Copied ${imagesCopied} image(s) to images/\n`);
}
// Read template
if (!fs.existsSync(TEMPLATE_PATH)) {
console.error(`β Template not found: ${TEMPLATE_PATH}`);
process.exit(1);
}
const template = fs.readFileSync(TEMPLATE_PATH, 'utf-8');
// Get all markdown files
const markdownFiles = getMarkdownFiles();
if (markdownFiles.length === 0) {
console.log('π No markdown files found in content/posts/');
console.log(' Create .md files with YAML frontmatter to get started.\n');
return;
}
console.log(`π Found ${markdownFiles.length} markdown file(s)\n`);
// Parse all posts
const posts = markdownFiles.map(parseMarkdownFile);
// Filter out drafts for listing, but still generate them
const publishedCount = posts.filter(p => !p.draft).length;
const draftCount = posts.filter(p => p.draft).length;
// Generate HTML for each post
let generatedCount = 0;
for (const post of posts) {
const html = generatePostHtml(post, posts, template);
const outputPath = path.join(OUTPUT_DIR, `${post.slug}.html`);
fs.writeFileSync(outputPath, html, 'utf-8');
const status = post.draft ? '(draft)' : '';
console.log(` β ${post.slug}.html ${status}`);
generatedCount++;
}
// Generate blog listing data
const listingData = generateBlogListingData(posts);
fs.writeFileSync(BLOG_DATA_PATH, JSON.stringify(listingData, null, 2), 'utf-8');
console.log(`\n β blog/posts.json (${listingData.length} posts)`);
// Summary
console.log('\nβββββββββββββββββββββββββββββββββββββ');
console.log(`β
Build complete!`);
console.log(` ${publishedCount} published, ${draftCount} drafts`);
console.log(` Output: ${OUTPUT_DIR}/`);
console.log('βββββββββββββββββββββββββββββββββββββ\n');
}
// Watch mode
function watch() {
console.log('π Watching for changes in content/posts/...\n');
console.log(' Press Ctrl+C to stop.\n');
// Initial build
build();
// Watch content directory
if (fs.existsSync(CONTENT_DIR)) {
fs.watch(CONTENT_DIR, { recursive: true }, (eventType, filename) => {
if (filename && filename.endsWith('.md')) {
console.log(`\nπ Change detected: ${filename}`);
build();
}
});
}
// Watch template
if (fs.existsSync(TEMPLATE_PATH)) {
fs.watch(TEMPLATE_PATH, () => {
console.log('\nπ Template changed');
build();
});
}
}
// CLI
const args = process.argv.slice(2);
if (args.includes('--watch') || args.includes('-w')) {
watch();
} else {
build();
}