spaceforge / backend /app /main.py
2Btainment's picture
fix: replace BMC widget script with plain CSS link
2e7f3ce
Raw History Blame Contribute Delete
2.49 kB
"""SpaceForge FastAPI application — API + static frontend."""
from __future__ import annotations
import sys
from contextlib import asynccontextmanager
from pathlib import Path
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import FileResponse
from fastapi.staticfiles import StaticFiles
_ROOT = Path(__file__).resolve().parents[2]
if str(_ROOT) not in sys.path:
sys.path.insert(0, str(_ROOT))
from backend.app.api.routes import router
from backend.app.config import STATIC_DIR
from backend.app.services.builds import build_manager
@asynccontextmanager
async def lifespan(app: FastAPI):
build_manager.start_cleaner()
yield
app = FastAPI(
title="SpaceForge",
description="Package Hugging Face Spaces as widgets, PWAs, extensions, and desktop projects.",
version="0.1.0",
lifespan=lifespan,
)
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_methods=["*"],
allow_headers=["*"],
)
app.include_router(router)
_static = STATIC_DIR
if not _static.exists():
alt = _ROOT / "frontend" / "dist"
if alt.exists():
_static = alt
if _static.exists():
assets = _static / "assets"
if assets.exists():
app.mount("/assets", StaticFiles(directory=str(assets)), name="assets")
def _index_response() -> FileResponse:
return FileResponse(
_static / "index.html",
headers={
"Cache-Control": "no-cache, no-store, must-revalidate",
"Pragma": "no-cache",
"Expires": "0",
},
)
@app.get("/")
async def index() -> FileResponse:
return _index_response()
@app.get("/{full_path:path}")
async def spa_fallback(full_path: str) -> FileResponse:
# Never SPA-fallback API/docs — return real 404 JSON/HTML from FastAPI
if full_path.startswith(("api/", "api", "docs", "openapi.json", "redoc")):
from fastapi import HTTPException
raise HTTPException(status_code=404, detail="Not found")
candidate = _static / full_path
if full_path and candidate.exists() and candidate.is_file():
return FileResponse(candidate)
return _index_response()
else:
@app.get("/")
async def index_fallback() -> dict:
return {
"service": "SpaceForge",
"status": "ok",
"ui": "frontend not built — open /api/health /docs",
}