-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
363 lines (298 loc) · 15.1 KB
/
server.js
File metadata and controls
363 lines (298 loc) · 15.1 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
/**
* py.edit — meta.txt live editor + preview
* Runs on port 3005 (configurable via PORT env var).
*
* Set PORTFOLIO_ROOT env var if your portfolio repo lives elsewhere:
* PORTFOLIO_ROOT=/home/pi/repos/portfolio node server.js
*/
import express from 'express'
import multer from 'multer'
import { readFileSync, writeFileSync, mkdirSync, existsSync,
readdirSync, statSync, unlinkSync, rmSync, copyFileSync, renameSync } from 'fs'
import { join, dirname } from 'path'
import { fileURLToPath } from 'url'
import { exec } from 'child_process'
import { promisify } from 'util'
import { renderPreview, renderPanelPreview } from './lib/renderer.js'
const execAsync = promisify(exec)
const __dir = dirname(fileURLToPath(import.meta.url))
// ── Config ────────────────────────────────────────────────────────────────────
const PORT = process.env.PORT || 3005
const PORTFOLIO_ROOT = process.env.PORTFOLIO_ROOT
|| '/Users/nathan/Documents/VSCodeProjects/pyth.com/py-xxx.github.io'
const CONTENT_DIR = join(PORTFOLIO_ROOT, 'content')
const TEMPLATES_DIR = join(CONTENT_DIR, 'templates')
const SRC_DIR = join(PORTFOLIO_ROOT, 'src')
const PUBLIC_DIR = join(PORTFOLIO_ROOT, 'public')
const CATEGORIES = ['software', 'systems', 'other', 'models', 'books']
// ── App setup ─────────────────────────────────────────────────────────────────
const app = express()
app.use(express.json({ limit: '10mb' }))
app.use(express.static(join(__dir, 'public')))
// Serve portfolio CSS for preview rendering
app.use('/portfolio-src', express.static(SRC_DIR))
app.use('/portfolio-public', express.static(PUBLIC_DIR))
// Serve content folder assets for preview (models, PDFs, images)
app.use('/content-assets', express.static(CONTENT_DIR))
// ── Helpers ───────────────────────────────────────────────────────────────────
const toSlug = s => s.toLowerCase().replace(/\s+/g, '-').replace(/[^a-z0-9-]/g, '')
const projectDir = (cat, slug) => join(CONTENT_DIR, cat, slug)
// ── API: directory tree ───────────────────────────────────────────────────────
app.get('/api/tree', (req, res) => {
const tree = []
for (const cat of CATEGORIES) {
const catDir = join(CONTENT_DIR, cat)
if (!existsSync(catDir)) continue
const projects = []
for (const slug of readdirSync(catDir).sort()) {
const dir = join(catDir, slug)
if (!statSync(dir).isDirectory()) continue
const assets = readdirSync(dir).filter(f => f !== 'meta.txt' && !f.startsWith('.'))
projects.push({ slug, assets })
}
if (projects.length) tree.push({ category: cat, projects })
}
res.json(tree)
})
// ── API: read / write meta.txt ────────────────────────────────────────────────
app.get('/api/meta', (req, res) => {
const { category, slug } = req.query
const path = join(projectDir(category, slug), 'meta.txt')
if (!existsSync(path)) return res.status(404).json({ error: 'meta.txt not found' })
res.json({ content: readFileSync(path, 'utf8') })
})
app.post('/api/meta', (req, res) => {
const { category, slug, content } = req.body
const dir = projectDir(category, slug)
if (!existsSync(dir)) return res.status(404).json({ error: 'project not found' })
writeFileSync(join(dir, 'meta.txt'), content, 'utf8')
res.json({ ok: true })
})
// ── API: live preview ─────────────────────────────────────────────────────────
app.post('/api/preview', (req, res) => {
const { content, category, slug } = req.body
try {
res.send(renderPreview(content || '', category, slug))
} catch (err) {
res.send(`<body style="background:#111;color:#f87171;font-family:monospace;padding:2rem">
<strong>Preview error:</strong><br><pre>${err.message}</pre></body>`)
}
})
app.post('/api/panel-preview', (req, res) => {
const { content, category, slug } = req.body
try {
res.send(renderPanelPreview(content || '', category, slug))
} catch (err) {
res.send(`<body style="background:#111;color:#f87171;font-family:monospace;padding:2rem">
<strong>Panel preview error:</strong><br><pre>${err.message}</pre></body>`)
}
})
// ── API: guide ────────────────────────────────────────────────────────────────
app.get('/api/guide', (req, res) => {
const path = join(CONTENT_DIR, 'GUIDE.md')
if (!existsSync(path)) return res.status(404).json({ error: 'GUIDE.md not found' })
res.json({ content: readFileSync(path, 'utf8') })
})
// ── API: templates ────────────────────────────────────────────────────────────
app.get('/api/template/:type', (req, res) => {
const path = join(TEMPLATES_DIR, `${req.params.type}.meta.txt`)
if (!existsSync(path)) return res.status(404).json({ error: 'template not found' })
res.json({ content: readFileSync(path, 'utf8') })
})
// ── API: create project ───────────────────────────────────────────────────────
app.post('/api/projects', (req, res) => {
const { name, category } = req.body
if (!name || !category) return res.status(400).json({ error: 'name and category required' })
const slug = toSlug(name)
const dir = projectDir(category, slug)
if (existsSync(dir)) return res.status(409).json({ error: 'A project with that slug already exists.' })
mkdirSync(dir, { recursive: true })
const templatePath = join(TEMPLATES_DIR, `${category}.meta.txt`)
if (existsSync(templatePath)) {
copyFileSync(templatePath, join(dir, 'meta.txt'))
} else {
writeFileSync(join(dir, 'meta.txt'), `title: ${name}\n`, 'utf8')
}
res.json({ ok: true, slug, category })
})
// ── API: rename project ───────────────────────────────────────────────────────
app.post('/api/projects/rename', async (req, res) => {
const { category, oldSlug, newSlug } = req.body
if (!newSlug) return res.status(400).json({ error: 'New name is required.' })
const slug = toSlug(newSlug)
if (!slug) return res.status(400).json({ error: 'Invalid name — no valid characters.' })
const oldDir = projectDir(category, oldSlug)
const newDir = projectDir(category, slug)
if (!existsSync(oldDir)) return res.status(404).json({ error: 'Project not found.' })
if (existsSync(newDir)) return res.status(409).json({ error: `A project named "${slug}" already exists.` })
// Rename the content folder
renameSync(oldDir, newDir)
// Delete the old generated HTML so the stale page doesn't linger on the site.
const outDir = category === 'books' ? 'writing' : 'workshop'
if (['software', 'systems', 'other', 'books'].includes(category)) {
const oldHtml = join(PORTFOLIO_ROOT, outDir, `${oldSlug}.html`)
if (existsSync(oldHtml)) unlinkSync(oldHtml)
}
// Patch slug references in hand-authored HTML files (workshop.html, index.html).
// These are NOT regenerated by generate.js — they contain hardcoded project links.
const handAuthored = [
join(PORTFOLIO_ROOT, 'workshop.html'),
join(PORTFOLIO_ROOT, 'index.html'),
]
const oldPattern = new RegExp(oldSlug.replace(/-/g, '-'), 'g')
for (const filePath of handAuthored) {
if (!existsSync(filePath)) continue
const original = readFileSync(filePath, 'utf8')
const updated = original.split(oldSlug).join(slug)
if (updated !== original) writeFileSync(filePath, updated, 'utf8')
}
// Run the generator now so the new page exists immediately (not just after push)
try {
await execAsync('node scripts/generate.js', { cwd: PORTFOLIO_ROOT })
} catch (e) {
// Non-fatal — page will be generated on next push anyway
console.warn('[rename] generator warning:', e.message)
}
res.json({ ok: true, slug })
})
// ── API: delete project ───────────────────────────────────────────────────────
app.delete('/api/projects', (req, res) => {
const { category, slug } = req.query
const dir = projectDir(category, slug)
if (!existsSync(dir)) return res.status(404).json({ error: 'not found' })
rmSync(dir, { recursive: true })
res.json({ ok: true })
})
// ── API: upload assets ────────────────────────────────────────────────────────
const upload = multer({
storage: multer.diskStorage({
destination (req, file, cb) {
const dir = projectDir(req.query.category, req.query.slug)
mkdirSync(dir, { recursive: true })
cb(null, dir)
},
filename (req, file, cb) { cb(null, file.originalname) }
})
})
app.post('/api/upload', upload.array('files'), (req, res) => {
res.json({ ok: true, files: req.files.map(f => f.originalname) })
})
// ── API: delete asset ─────────────────────────────────────────────────────────
app.delete('/api/asset', (req, res) => {
const { category, slug, filename } = req.query
const path = join(projectDir(category, slug), filename)
if (!existsSync(path)) return res.status(404).json({ error: 'not found' })
unlinkSync(path)
res.json({ ok: true })
})
// ── API: git ──────────────────────────────────────────────────────────────────
const git = cmd => execAsync(cmd, { cwd: PORTFOLIO_ROOT })
// Returns { "software/warstonks": "modified", "other/closet": "new", ... }
app.get('/api/git/changes', async (req, res) => {
try {
const { stdout } = await git('git status --short content/')
const changes = {}
for (const line of stdout.split('\n')) {
if (!line.trim()) continue
// e.g. " M content/systems/stream-deck/meta.txt"
// "?? content/models/new-thing/"
const m = line.match(/^(..)[\s]+content\/([^/]+)\/([^/\n]+)/)
if (!m) continue
const [, xy, category, slug] = m
const key = `${category}/${slug.replace('/', '')}`
changes[key] = (xy[0] === '?' || xy[1] === '?') ? 'new' : 'modified'
}
res.json(changes)
} catch (e) { res.json({}) }
})
app.get('/api/git/status', async (req, res) => {
try {
const { stdout } = await git('git status --short')
res.json({ output: stdout || 'Nothing to commit.' })
} catch (e) { res.status(500).json({ error: e.message }) }
})
app.post('/api/git/pull', async (req, res) => {
try {
const { stdout } = await git('git pull')
res.json({ ok: true, output: stdout })
} catch (e) { res.status(500).json({ error: e.stderr || e.message }) }
})
app.post('/api/git/force-pull', async (req, res) => {
try {
await git('git fetch origin')
const { stdout: branch } = await git('git rev-parse --abbrev-ref HEAD')
const { stdout } = await git(`git reset --hard origin/${branch.trim()}`)
res.json({ ok: true, output: stdout })
} catch (e) { res.status(500).json({ error: e.stderr || e.message }) }
})
app.post('/api/git/revert', async (req, res) => {
const { category, slug } = req.body
try {
// Revert tracked changes
await git(`git checkout -- content/${category}/${slug}/`).catch(() => {})
// Remove untracked files (new files not yet committed)
await git(`git clean -fd content/${category}/${slug}/`).catch(() => {})
res.json({ ok: true })
} catch (e) { res.status(500).json({ error: e.stderr || e.message }) }
})
/**
* Delete any generated HTML files in workshop/ or writing/ that no longer
* have a matching content folder. This cleans up after renames and deletes
* so orphaned pages don't linger in the repo.
*/
function removeStaleGeneratedFiles() {
// workshop/*.html ← software/ + systems/ + other/
const workshopDir = join(PORTFOLIO_ROOT, 'workshop')
if (existsSync(workshopDir)) {
const liveSlugs = new Set(
['software', 'systems', 'other'].flatMap(cat => {
const d = join(CONTENT_DIR, cat)
return existsSync(d) ? readdirSync(d) : []
})
)
for (const file of readdirSync(workshopDir)) {
if (!file.endsWith('.html')) continue
const slug = file.slice(0, -5)
if (!liveSlugs.has(slug)) unlinkSync(join(workshopDir, file))
}
}
// writing/*.html ← books/
const writingDir = join(PORTFOLIO_ROOT, 'writing')
if (existsSync(writingDir)) {
const bookSlugs = new Set(
existsSync(join(CONTENT_DIR, 'books'))
? readdirSync(join(CONTENT_DIR, 'books'))
: []
)
for (const file of readdirSync(writingDir)) {
if (!file.endsWith('.html')) continue
const slug = file.slice(0, -5)
if (!bookSlugs.has(slug)) unlinkSync(join(writingDir, file))
}
}
}
app.post('/api/git/push', async (req, res) => {
const msg = (req.body.message || 'update content').replace(/"/g, "'")
try {
// Remove any orphaned generated HTML files from renames / deletes
removeStaleGeneratedFiles()
// Run the generator so all pages are up to date before committing
const { stdout: genOut } = await execAsync(
'node scripts/generate.js', { cwd: PORTFOLIO_ROOT }
).catch(e => { throw new Error(`Generator failed:\n${e.stderr || e.message}`) })
// Stage content + everything the generator touched (deletions included)
await git('git add content/ workshop/ writing/ workshop.html')
const { stdout: diff } = await git('git diff --staged --stat')
if (!diff.trim()) return res.json({ ok: true, output: 'Nothing new to commit.' })
await git(`git commit -m "${msg}"`)
const { stdout } = await git('git push')
const genSummary = genOut.trim().split('\n').pop() // last line e.g. "[generate] Done — 11 pages"
res.json({ ok: true, output: [genSummary, stdout || 'Pushed.'].filter(Boolean).join('\n') })
} catch (e) { res.status(500).json({ error: e.stderr || e.message || String(e) }) }
})
// ── Start ─────────────────────────────────────────────────────────────────────
app.listen(PORT, () => {
console.log(`\n py.edit → http://localhost:${PORT}\n`)
console.log(` Portfolio → ${PORTFOLIO_ROOT}`)
console.log(` Content → ${CONTENT_DIR}\n`)
})