-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathvite.config.ts
More file actions
101 lines (92 loc) · 3.44 KB
/
Copy pathvite.config.ts
File metadata and controls
101 lines (92 loc) · 3.44 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
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import type { Plugin } from 'vite'
import fs from 'node:fs'
import path from 'node:path'
function tagsMiddleware(): Plugin {
return {
name: 'tags-middleware',
configureServer(server) {
const tagsDir = path.resolve(process.cwd(), 'tags')
server.middlewares.use(async (req, res, next) => {
if (!req.url) return next()
try {
if (req.url === '/tags/_list') {
if (!fs.existsSync(tagsDir)) {
res.statusCode = 404
res.setHeader('Content-Type', 'application/json; charset=utf-8')
res.end(JSON.stringify([]))
return
}
const files = fs.readdirSync(tagsDir)
.filter(f => f.toLowerCase().endsWith('.csv'))
const required = ['tag','category','post_count','aliases','is_locked','antecedent_alias']
const valid: string[] = []
// helper: split CSV line respecting quoted fields
function splitCsvLine(line: string) {
const cols: string[] = []
let cur = ''
let inQuotes = false
for (let i = 0; i < line.length; i++) {
const ch = line[i]
if (ch === '"') {
inQuotes = !inQuotes
continue
}
if (ch === ',' && !inQuotes) {
cols.push(cur)
cur = ''
continue
}
cur += ch
}
cols.push(cur)
return cols.map(s => s.trim())
}
for (const f of files) {
const p = path.join(tagsDir, f)
try {
const content = fs.readFileSync(p, 'utf-8')
const firstLine = content.split(/\r?\n/).find(l => l.trim().length > 0) || ''
const cols = splitCsvLine(firstLine)
// exact header match
let ok = required.every((k, i) => cols[i] === k)
// 如果不是表头,则尝试判断这是否为数据行(至少前三列为 tag, category, post_count)
if (!ok) {
const cat = Number(cols[1])
const pc = Number(cols[2])
if (cols.length >= 3 && Number.isFinite(cat) && Number.isFinite(pc)) {
ok = true
}
}
if (ok) valid.push(f)
} catch {}
}
res.statusCode = valid.length ? 200 : 404
res.setHeader('Content-Type', 'application/json; charset=utf-8')
res.end(JSON.stringify(valid))
return
}
// Serve raw CSV from tags dir: /tags/<name>.csv
if (req.url.startsWith('/tags/')) {
const name = decodeURIComponent(req.url.replace('/tags/', ''))
if (name.includes('..') || name.includes('/') || !name.toLowerCase().endsWith('.csv')) {
return next()
}
const filePath = path.join(tagsDir, name)
if (fs.existsSync(filePath)) {
res.statusCode = 200
res.setHeader('Content-Type', 'text/csv; charset=utf-8')
fs.createReadStream(filePath).pipe(res)
return
}
}
} catch {}
next()
})
},
}
}
export default defineConfig({
plugins: [vue(), tagsMiddleware()],
})