-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathedit-server.js
More file actions
212 lines (181 loc) · 6.4 KB
/
Copy pathedit-server.js
File metadata and controls
212 lines (181 loc) · 6.4 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
const http = require('http');
const fs = require('fs');
const path = require('path');
const { spawn, execSync } = require('child_process');
const PORT = 3002; // Different port from wfs-site
const ROOT_DIR = __dirname;
// Directories to skip when scanning for markdown files
const SKIP_DIRS = ['_site', 'node_modules', '.git', 'img', 'data'];
// Get last git commit date for a file
function getGitModifiedDate(filePath) {
try {
const result = execSync(
`git log -1 --format="%aI" -- "${filePath}"`,
{ cwd: ROOT_DIR, encoding: 'utf8', stdio: ['pipe', 'pipe', 'ignore'] }
).trim();
if (result) {
return result;
}
} catch (e) {
// Fall back to filesystem mtime if git fails
}
return fs.statSync(filePath).mtime.toISOString();
}
// Parse YAML front matter from markdown content
function parseFrontMatter(content) {
const match = content.match(/^---\n([\s\S]*?)\n---/);
if (!match) return { title: null, body: content };
const frontMatter = match[1];
const body = content.slice(match[0].length).trim();
// Simple YAML parsing for title
const titleMatch = frontMatter.match(/^title:\s*["']?(.+?)["']?\s*$/m);
const title = titleMatch ? titleMatch[1] : null;
return { title, body };
}
// Get excerpt from body (first ~100 chars of actual content)
function getExcerpt(body, maxLength = 100) {
// Remove markdown and HTML elements
let text = body
.replace(/^#+\s+.*/gm, '') // markdown headers
.replace(/!\[.*?\]\(.*?\)/g, '') // markdown images
.replace(/\[(.+?)\]\(.*?\)/g, '$1') // markdown links (keep text)
.replace(/\*\*(.+?)\*\*/g, '$1') // bold
.replace(/\*(.+?)\*/g, '$1') // italic
.replace(/`(.+?)`/g, '$1') // inline code
.replace(/```[\s\S]*?```/g, '') // code blocks
.replace(/<img[^>]*>/gi, '') // HTML img tags
.replace(/<[^>]+>/g, ' ') // all other HTML tags
.replace(/\{%[\s\S]*?%\}/g, '') // Nunjucks tags
.replace(/\{\{[\s\S]*?\}\}/g, '') // Nunjucks variables
.replace(/\s+/g, ' ') // collapse whitespace
.trim();
if (text.length <= maxLength) return text;
return text.slice(0, maxLength).trim() + '...';
}
// Recursively find all markdown files
function findMarkdownFiles(dir, category = null) {
const files = [];
let entries;
try {
entries = fs.readdirSync(dir, { withFileTypes: true });
} catch (e) {
return files;
}
for (const entry of entries) {
const fullPath = path.join(dir, entry.name);
const relativePath = path.relative(ROOT_DIR, fullPath);
if (entry.isDirectory()) {
// Skip certain directories
if (SKIP_DIRS.includes(entry.name) || entry.name.startsWith('.') || entry.name.startsWith('_')) continue;
// The first-level directory becomes the category
const newCategory = category || entry.name;
files.push(...findMarkdownFiles(fullPath, newCategory));
} else if (entry.isFile() && entry.name.endsWith('.md')) {
const content = fs.readFileSync(fullPath, 'utf8');
const { title, body } = parseFrontMatter(content);
const parentDir = path.relative(ROOT_DIR, dir);
files.push({
path: fullPath,
relativePath,
parentDir,
category: category || 'root',
title: title || entry.name.replace(/\.md$/, ''),
excerpt: getExcerpt(body),
body: body,
modified: getGitModifiedDate(fullPath)
});
}
}
return files;
}
// Group files by category
function getFilesGroupedByCategory() {
const files = findMarkdownFiles(ROOT_DIR);
const grouped = {};
for (const file of files) {
if (!grouped[file.category]) {
grouped[file.category] = [];
}
grouped[file.category].push(file);
}
// Sort each category's files by modified date (newest first)
for (const category of Object.keys(grouped)) {
grouped[category].sort((a, b) => new Date(b.modified) - new Date(a.modified));
}
return grouped;
}
// HTTP server
const server = http.createServer((req, res) => {
// CORS headers for local development
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS');
res.setHeader('Access-Control-Allow-Headers', 'Content-Type');
if (req.method === 'OPTIONS') {
res.writeHead(200);
res.end();
return;
}
const url = new URL(req.url, `http://localhost:${PORT}`);
// Serve dashboard
if (url.pathname === '/' && req.method === 'GET') {
const dashboardPath = path.join(__dirname, 'edit-dashboard.html');
fs.readFile(dashboardPath, 'utf8', (err, content) => {
if (err) {
res.writeHead(500, { 'Content-Type': 'text/plain' });
res.end('Error loading dashboard');
return;
}
res.writeHead(200, { 'Content-Type': 'text/html' });
res.end(content);
});
return;
}
// API: List files
if (url.pathname === '/api/files' && req.method === 'GET') {
try {
const files = getFilesGroupedByCategory();
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify(files));
} catch (err) {
res.writeHead(500, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ error: err.message }));
}
return;
}
// API: Open file in gedit
if (url.pathname === '/api/open' && req.method === 'POST') {
let body = '';
req.on('data', chunk => body += chunk);
req.on('end', () => {
try {
const { filePath } = JSON.parse(body);
// Security: ensure path is within project directory
const resolved = path.resolve(filePath);
if (!resolved.startsWith(ROOT_DIR)) {
res.writeHead(403, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ error: 'Access denied' }));
return;
}
// Open in gedit
const child = spawn('gedit', [resolved], {
detached: true,
stdio: 'ignore'
});
child.unref();
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ success: true, path: resolved }));
} catch (err) {
res.writeHead(400, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ error: err.message }));
}
});
return;
}
// 404 for everything else
res.writeHead(404, { 'Content-Type': 'text/plain' });
res.end('Not found');
});
server.listen(PORT, () => {
console.log(`Edge Blog Quick Edit Dashboard running at http://localhost:${PORT}`);
console.log('Press Ctrl+C to stop');
});