potree_build/index.ts
Georgy Shive dd09f80472 реорганизация статических файлов и маршрутизации
- Перенес статические файлы из public/build в два места:
  - /public/libs - библиотеки и зависимости
  - /protected/examples - защищенные примеры и демо
2025-05-21 20:14:18 +07:00

148 lines
5.1 KiB
TypeScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import { Elysia } from 'elysia'
import { staticPlugin } from '@elysiajs/static'
import { cookie } from '@elysiajs/cookie'
import { randomUUID } from 'crypto'
import { createServer } from 'vite'
const sessions = new Set<string>()
// Инициализация Vite в режиме разработки
async function createViteServer() {
const vite = await createServer({
server: { middlewareMode: true },
appType: 'spa',
})
return vite
}
async function startServer() {
// Создаем Vite сервер в режиме разработки
const viteServer = process.env.NODE_ENV !== 'production'
? await createViteServer()
: null
const app = new Elysia()
.use(cookie())
// Лог запросов
.onRequest(({ request }) => {
console.log(`→ ${request.method} ${new URL(request.url).pathname}`)
})
// Публичная зона
.get('/', ({ redirect }) => redirect('/login'))
// API для авторизации (старый маршрут для совместимости)
.post('/login', async (ctx) => {
const { username = '', password = '' } = await ctx.request.json()
if (username === 'admin' && password === 'secret') {
const sid = randomUUID()
sessions.add(sid)
return new Response(null, {
status: 302,
headers: {
Location: '/examples/copc.html',
'Set-Cookie': `session=${sid}; Path=/; HttpOnly; SameSite=Lax; Max-Age=86400`
}
})
}
return new Response(JSON.stringify({ message: 'Неверные учётные данные' }), {
status: 401,
headers: { 'Content-Type': 'application/json; charset=utf-8' }
})
})
// API для авторизации (новый маршрут)
.post('/api/login', async (ctx) => {
const { username = '', password = '' } = await ctx.request.json()
if (username === 'admin' && password === 'secret') {
const sid = randomUUID()
sessions.add(sid)
return new Response(null, {
status: 302,
headers: {
Location: '/examples/copc.html',
'Set-Cookie': `session=${sid}; Path=/; HttpOnly; SameSite=Lax; Max-Age=86400`
}
})
}
return new Response(JSON.stringify({ message: 'Неверные учётные данные' }), {
status: 401,
headers: { 'Content-Type': 'application/json; charset=utf-8' }
})
})
.get('/logout', ({ cookie, redirect }) => {
const sid = cookie.session?.value
if (sid) sessions.delete(sid)
return redirect('/login')
})
// Всё что лежит в ./build (CSS/JS/картинки) /build/*
.use(staticPlugin({
assets: './build',
prefix: '/build',
indexHTML: false
}))
// Раздача статики из dist (собранные React-файлы) в продакшн
.use(staticPlugin({
assets: './dist',
prefix: '/',
alwaysStatic: process.env.NODE_ENV === 'production'
}))
// Ручная отдача HTML из ./build/examples с проверкой сессии
.get('/examples/:page', async ({ params, cookie, redirect }) => {
const sid = cookie.session?.value
if (!sid || !sessions.has(sid)) {
return redirect('/login')
}
try {
const html = await Bun.file(`./build/examples/${params.page}`).text()
return new Response(html, {
headers: { 'Content-Type': 'text/html; charset=utf-8' }
})
} catch {
return new Response('Not Found', { status: 404 })
}
})
// Если мы в режиме разработки, используем Vite как middleware для React-приложения
if (viteServer) {
app.all('*', async ({ request }) => {
// Исключаем запросы к API и статике
const url = new URL(request.url)
if (url.pathname.startsWith('/api') || url.pathname.startsWith('/build') || url.pathname.startsWith('/examples')) {
return; // Пропускаем и позволяем обработать другим обработчикам
}
// Для остальных запросов используем Vite
try {
// Создаем новый запрос, который будет передан в vite middleware
const viteRequest = new Request(request.url, {
method: request.method,
headers: request.headers,
body: request.method !== 'GET' && request.method !== 'HEAD' ? request.body : undefined
})
// Применяем middleware Vite
return await viteServer.middlewares.apply(
viteRequest,
// @ts-ignore ограничения типизации
{ locals: {} }
)
} catch (error) {
console.error('Ошибка при обработке запроса через Vite:', error)
return new Response('Internal Server Error', { status: 500 })
}
})
}
app.listen(1234)
console.log('🚀 Server running: http://localhost:1234')
}
startServer().catch(console.error)