import { promises as fs } from 'node:fs' import path from 'node:path' import { fileURLToPath } from 'node:url' import { svelte } from '@sveltejs/vite-plugin-svelte' import { defineConfig, type Plugin } from 'vite' // @ts-expect-error Vite config 直接复用 Node ESM 构建脚本,无需单独产出 TS 类型。 import { readBooksCatalog, writeBooksCatalog } from './scripts/books-catalog.mjs' const PROJECT_ROOT = '/proj/' function readRequestBody(req: NodeJS.ReadableStream): Promise { return new Promise((resolve, reject) => { let body = '' req.setEncoding('utf8') req.on('data', (chunk) => { body += chunk }) req.on('end', () => resolve(body)) req.on('error', reject) }) } function resolvePublicTypFilePath(projectPath: string, publicRoot: string) { if (!projectPath.startsWith(PROJECT_ROOT) || !projectPath.endsWith('.typ')) { throw new Error(`不支持保存该文件:${projectPath}`) } const relativePath = projectPath.slice(PROJECT_ROOT.length) const parts = relativePath.split('/').filter(Boolean) if (parts.length === 0 || parts.some((part) => part === '.' || part === '..')) { throw new Error(`非法文件路径:${projectPath}`) } const filePath = path.resolve(publicRoot, ...parts) const normalizedPublicRoot = path.resolve(publicRoot) if (!filePath.startsWith(`${normalizedPublicRoot}${path.sep}`)) { throw new Error(`非法文件路径:${projectPath}`) } return filePath } function typstSavePlugin(): Plugin { const publicRoot = fileURLToPath(new URL('./public', import.meta.url)) const booksRoot = path.resolve(publicRoot, 'books') return { name: 'typst-save-plugin', configureServer(server) { const syncBooksCatalog = async () => { try { await writeBooksCatalog(publicRoot) } catch (error) { server.config.logger.warn( `[books] 同步 books_catalog.json 失败:${error instanceof Error ? error.message : String(error)}`, ) } } const shouldSyncCatalog = (filePath: string) => path.resolve(filePath).startsWith(`${booksRoot}${path.sep}`) void syncBooksCatalog() server.watcher.on('add', (filePath) => { if (shouldSyncCatalog(filePath)) void syncBooksCatalog() }) server.watcher.on('change', (filePath) => { if (shouldSyncCatalog(filePath)) void syncBooksCatalog() }) server.watcher.on('unlink', (filePath) => { if (shouldSyncCatalog(filePath)) void syncBooksCatalog() }) server.watcher.on('addDir', (filePath) => { if (shouldSyncCatalog(filePath)) void syncBooksCatalog() }) server.watcher.on('unlinkDir', (filePath) => { if (shouldSyncCatalog(filePath)) void syncBooksCatalog() }) server.middlewares.use('/__books_catalog', async (req, res, next) => { if (req.method !== 'GET') { next() return } try { const books = await readBooksCatalog(publicRoot) res.statusCode = 200 res.setHeader('Content-Type', 'application/json; charset=utf-8') res.end(JSON.stringify({ books })) } catch (error) { res.statusCode = 500 res.end(error instanceof Error ? error.message : String(error)) } }) server.middlewares.use('/__save_typst_file', async (req, res, next) => { if (req.method !== 'POST') { next() return } try { const body = await readRequestBody(req) const payload = JSON.parse(body) as { projectPath?: string; content?: string } const projectPath = payload.projectPath?.trim() if (!projectPath || typeof payload.content !== 'string') { res.statusCode = 400 res.end('缺少 projectPath 或 content') return } const filePath = resolvePublicTypFilePath(projectPath, publicRoot) await fs.mkdir(path.dirname(filePath), { recursive: true }) await fs.writeFile(filePath, payload.content, 'utf8') res.statusCode = 200 res.setHeader('Content-Type', 'application/json; charset=utf-8') res.end(JSON.stringify({ ok: true, filePath })) } catch (error) { res.statusCode = 500 res.end(error instanceof Error ? error.message : String(error)) } }) }, } } // https://vite.dev/config/ export default defineConfig({ plugins: [svelte(), typstSavePlugin()], })