Add browser Python editor with Pyodide, user auth, and workspace API
- FastAPI serves static UI, file CRUD under code/ and read-only lib/ - Pyodide worker runs Python and Jedi completions in the browser - SQLite accounts: login/register, session cookies, superuser user management - Optional EDITOR_API_KEY, AUTH_* env vars, .env.example - Pipenv, pytest, Selenium smoke test, README Made-with: Cursor
This commit is contained in:
1 parent
d245ecd353
commit
f204109a84
40 files changed
+4950
-2
No files matched your search
@@ -0,0 +1,7 @@
|
||||
from editor_app.main import app
|
||||
|
||||
|
||||
if __name__ == "__main__": # pragma: no cover
|
||||
import uvicorn
|
||||
|
||||
uvicorn.run(app, host="0.0.0.0", port=8080)
|
||||
Whitespace-only changes.
@@ -0,0 +1,30 @@
|
||||
import os
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
# Application package lives under `src/`; repo root is one level up (for `.env`, default workspace).
|
||||
BASE_DIR = Path(__file__).resolve().parent.parent
|
||||
PROJECT_ROOT = BASE_DIR.parent
|
||||
STATIC_DIR = BASE_DIR / "static"
|
||||
|
||||
|
||||
def load_env_file(env_path: Path) -> None:
|
||||
"""Load KEY=VALUE entries from a local .env file (does not override existing os.environ)."""
|
||||
if not env_path.exists():
|
||||
return
|
||||
|
||||
for line in env_path.read_text(encoding="utf-8").splitlines():
|
||||
stripped = line.strip()
|
||||
if not stripped or stripped.startswith("#") or "=" not in stripped:
|
||||
continue
|
||||
key, value = stripped.split("=", 1)
|
||||
key = key.strip()
|
||||
value = value.strip().strip('"').strip("'")
|
||||
if key and key not in os.environ:
|
||||
os.environ[key] = value
|
||||
|
||||
|
||||
load_env_file(PROJECT_ROOT / ".env")
|
||||
|
||||
_default_workspace = PROJECT_ROOT / "workspace"
|
||||
WORKSPACE_ROOT = Path(os.environ.get("WORKSPACE_ROOT", str(_default_workspace))).resolve()
|
||||
Whitespace-only changes.
@@ -0,0 +1,40 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import datetime as dt
|
||||
|
||||
from sqlalchemy import Boolean, DateTime, ForeignKey, Integer, String
|
||||
from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column, relationship
|
||||
|
||||
|
||||
def _utc_naive() -> dt.datetime:
|
||||
return dt.datetime.now(dt.UTC).replace(tzinfo=None)
|
||||
|
||||
|
||||
class Base(DeclarativeBase):
|
||||
pass
|
||||
|
||||
|
||||
class User(Base):
|
||||
__tablename__ = "users"
|
||||
|
||||
id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True)
|
||||
username: Mapped[str] = mapped_column(String(64), unique=True, index=True)
|
||||
password_hash: Mapped[str] = mapped_column(String(256))
|
||||
is_superuser: Mapped[bool] = mapped_column(Boolean, default=False)
|
||||
created_at: Mapped[dt.datetime] = mapped_column(DateTime, default=_utc_naive)
|
||||
|
||||
sessions: Mapped[list[AuthSession]] = relationship(
|
||||
"AuthSession", back_populates="user", cascade="all, delete-orphan"
|
||||
)
|
||||
|
||||
|
||||
class AuthSession(Base):
|
||||
__tablename__ = "auth_sessions"
|
||||
|
||||
id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True)
|
||||
user_id: Mapped[int] = mapped_column(ForeignKey("users.id", ondelete="CASCADE"), index=True)
|
||||
token: Mapped[str] = mapped_column(String(128), unique=True, index=True)
|
||||
expires_at: Mapped[dt.datetime] = mapped_column(DateTime)
|
||||
created_at: Mapped[dt.datetime] = mapped_column(DateTime, default=_utc_naive)
|
||||
|
||||
user: Mapped[User] = relationship("User", back_populates="sessions")
|
||||
@@ -0,0 +1,55 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
from collections.abc import Generator
|
||||
from pathlib import Path
|
||||
|
||||
from sqlalchemy import create_engine
|
||||
from sqlalchemy.orm import Session, sessionmaker
|
||||
|
||||
from editor_app.config import PROJECT_ROOT
|
||||
|
||||
_engine = None
|
||||
_SessionLocal: sessionmaker[Session] | None = None
|
||||
|
||||
|
||||
def _database_url() -> str:
|
||||
path = os.environ.get("AUTH_DATABASE_PATH", str(PROJECT_ROOT / "data" / "editor.db"))
|
||||
Path(path).parent.mkdir(parents=True, exist_ok=True)
|
||||
return f"sqlite:///{path}"
|
||||
|
||||
|
||||
def reset_engine() -> None:
|
||||
"""Test helper: clear cached engine after env change."""
|
||||
global _engine, _SessionLocal
|
||||
if _engine is not None:
|
||||
_engine.dispose()
|
||||
_engine = None
|
||||
_SessionLocal = None
|
||||
|
||||
|
||||
def get_engine():
|
||||
global _engine, _SessionLocal
|
||||
if _engine is None:
|
||||
_engine = create_engine(
|
||||
_database_url(),
|
||||
connect_args={"check_same_thread": False},
|
||||
pool_pre_ping=True,
|
||||
)
|
||||
_SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=_engine)
|
||||
return _engine
|
||||
|
||||
|
||||
def get_session_factory() -> sessionmaker[Session]:
|
||||
get_engine()
|
||||
assert _SessionLocal is not None
|
||||
return _SessionLocal
|
||||
|
||||
|
||||
def get_db() -> Generator[Session, None, None]:
|
||||
factory = get_session_factory()
|
||||
db = factory()
|
||||
try:
|
||||
yield db
|
||||
finally:
|
||||
db.close()
|
||||
@@ -0,0 +1,63 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
|
||||
from fastapi import Cookie, Depends, Header, HTTPException
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from editor_app.db.session import get_db
|
||||
from editor_app.db.models import User
|
||||
from editor_app.services import accounts
|
||||
|
||||
|
||||
def api_key_valid(authorization: str | None) -> bool:
|
||||
expected = (os.environ.get("EDITOR_API_KEY") or "").strip()
|
||||
if not expected:
|
||||
return False
|
||||
return (authorization or "").strip() == f"Bearer {expected}"
|
||||
|
||||
|
||||
async def require_api_access(
|
||||
db: Session = Depends(get_db),
|
||||
authorization: str | None = Header(None),
|
||||
editor_session: str | None = Cookie(None),
|
||||
) -> None:
|
||||
"""API key, or (when auth off) open access, or (when auth on) valid session — see README."""
|
||||
if api_key_valid(authorization):
|
||||
return
|
||||
key_configured = bool((os.environ.get("EDITOR_API_KEY") or "").strip())
|
||||
if key_configured:
|
||||
if accounts.auth_enabled():
|
||||
user = accounts.get_session_user(db, editor_session)
|
||||
if user:
|
||||
return
|
||||
raise HTTPException(status_code=401, detail="Invalid or missing API key")
|
||||
if not accounts.auth_enabled():
|
||||
return
|
||||
user = accounts.get_session_user(db, editor_session)
|
||||
if user is None:
|
||||
raise HTTPException(status_code=401, detail="Not authenticated")
|
||||
|
||||
|
||||
async def get_current_user_optional(
|
||||
db: Session = Depends(get_db),
|
||||
authorization: str | None = Header(None),
|
||||
editor_session: str | None = Cookie(None),
|
||||
) -> User | None:
|
||||
if api_key_valid(authorization):
|
||||
return None
|
||||
if not accounts.auth_enabled():
|
||||
return None
|
||||
return accounts.get_session_user(db, editor_session)
|
||||
|
||||
|
||||
async def require_superuser(
|
||||
user: User | None = Depends(get_current_user_optional),
|
||||
) -> User:
|
||||
if not accounts.auth_enabled():
|
||||
raise HTTPException(status_code=400, detail="User management requires AUTH_ENABLED=true")
|
||||
if user is None:
|
||||
raise HTTPException(status_code=401, detail="Not authenticated")
|
||||
if not user.is_superuser:
|
||||
raise HTTPException(status_code=403, detail="Superuser required")
|
||||
return user
|
||||
@@ -0,0 +1,47 @@
|
||||
import os
|
||||
from contextlib import asynccontextmanager
|
||||
|
||||
from fastapi import Depends, FastAPI
|
||||
from fastapi.staticfiles import StaticFiles
|
||||
from sqlalchemy.orm import sessionmaker
|
||||
|
||||
from editor_app.config import STATIC_DIR, WORKSPACE_ROOT
|
||||
from editor_app.db.models import Base
|
||||
from editor_app.db.session import get_engine
|
||||
from editor_app.deps import require_api_access
|
||||
from editor_app.routers.auth_routes import router as auth_router
|
||||
from editor_app.routers.files import router as files_router
|
||||
from editor_app.routers.frontend import router as frontend_router
|
||||
from editor_app.routers.users_admin import router as users_admin_router
|
||||
from editor_app.services import accounts
|
||||
|
||||
|
||||
@asynccontextmanager
|
||||
async def lifespan(_app: FastAPI):
|
||||
(WORKSPACE_ROOT / "lib").mkdir(parents=True, exist_ok=True)
|
||||
engine = get_engine()
|
||||
Base.metadata.create_all(bind=engine)
|
||||
factory = sessionmaker(autocommit=False, autoflush=False, bind=engine)
|
||||
db = factory()
|
||||
try:
|
||||
if accounts.auth_enabled():
|
||||
bu = os.environ.get("BOOTSTRAP_ADMIN_USERNAME", "").strip()
|
||||
bp = os.environ.get("BOOTSTRAP_ADMIN_PASSWORD", "").strip()
|
||||
if bu and bp and accounts.count_users(db) == 0:
|
||||
accounts.create_user(db, bu, bp, is_superuser=True)
|
||||
finally:
|
||||
db.close()
|
||||
yield
|
||||
|
||||
|
||||
def create_app() -> FastAPI:
|
||||
app = FastAPI(lifespan=lifespan)
|
||||
app.mount("/static", StaticFiles(directory=str(STATIC_DIR)), name="static")
|
||||
app.include_router(frontend_router)
|
||||
app.include_router(auth_router)
|
||||
app.include_router(users_admin_router)
|
||||
app.include_router(files_router, dependencies=[Depends(require_api_access)])
|
||||
return app
|
||||
|
||||
|
||||
app = create_app()
|
||||
@@ -0,0 +1,22 @@
|
||||
from typing import Optional
|
||||
|
||||
from pydantic import BaseModel
|
||||
|
||||
|
||||
class FileContent(BaseModel):
|
||||
content: str
|
||||
|
||||
|
||||
class FileInfo(BaseModel):
|
||||
name: str
|
||||
is_directory: bool
|
||||
size: Optional[int] = None
|
||||
|
||||
|
||||
class FolderOperation(BaseModel):
|
||||
path: str
|
||||
|
||||
|
||||
class MoveFileRequest(BaseModel):
|
||||
source_path: str
|
||||
destination_folder: str = ""
|
||||
Whitespace-only changes.
@@ -0,0 +1,95 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException, Request, Response
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from editor_app.db.session import get_db
|
||||
from editor_app.schemas.users import AuthStatusResponse, LoginRequest, RegisterRequest, UserPublic
|
||||
from editor_app.services import accounts
|
||||
|
||||
router = APIRouter(prefix="/api/auth", tags=["auth"])
|
||||
|
||||
|
||||
def _set_session_cookie(response: Response, request: Request, token: str) -> None:
|
||||
max_age = accounts.session_ttl_days() * 86400
|
||||
secure = request.url.scheme == "https"
|
||||
response.set_cookie(
|
||||
key=accounts.SESSION_COOKIE_NAME,
|
||||
value=token,
|
||||
max_age=max_age,
|
||||
httponly=True,
|
||||
samesite="lax",
|
||||
secure=secure,
|
||||
path="/",
|
||||
)
|
||||
|
||||
|
||||
def _clear_session_cookie(response: Response, request: Request) -> None:
|
||||
secure = request.url.scheme == "https"
|
||||
response.delete_cookie(accounts.SESSION_COOKIE_NAME, path="/", samesite="lax", secure=secure)
|
||||
|
||||
|
||||
@router.get("/status", response_model=AuthStatusResponse)
|
||||
async def auth_status() -> AuthStatusResponse:
|
||||
return AuthStatusResponse(auth_enabled=accounts.auth_enabled(), register_open=accounts.register_open())
|
||||
|
||||
|
||||
@router.get("/me")
|
||||
async def auth_me(
|
||||
request: Request,
|
||||
db: Session = Depends(get_db),
|
||||
) -> dict:
|
||||
if not accounts.auth_enabled():
|
||||
return {"auth_enabled": False, "user": None}
|
||||
token = request.cookies.get(accounts.SESSION_COOKIE_NAME)
|
||||
user = accounts.get_session_user(db, token)
|
||||
if user is None:
|
||||
raise HTTPException(status_code=401, detail="Not authenticated")
|
||||
return {"auth_enabled": True, "user": UserPublic.model_validate(user).model_dump()}
|
||||
|
||||
|
||||
@router.post("/register", response_model=UserPublic)
|
||||
async def register(
|
||||
body: RegisterRequest,
|
||||
db: Session = Depends(get_db),
|
||||
) -> UserPublic:
|
||||
if not accounts.auth_enabled():
|
||||
raise HTTPException(status_code=400, detail="Set AUTH_ENABLED=true to use accounts")
|
||||
if not accounts.register_open():
|
||||
raise HTTPException(status_code=403, detail="Registration is disabled (AUTH_REGISTER_OPEN=false)")
|
||||
try:
|
||||
user = accounts.register_user(db, body.username, body.password)
|
||||
except ValueError as exc:
|
||||
raise HTTPException(status_code=409, detail=str(exc)) from exc
|
||||
return UserPublic.model_validate(user)
|
||||
|
||||
|
||||
@router.post("/login")
|
||||
async def login(
|
||||
request: Request,
|
||||
response: Response,
|
||||
body: LoginRequest,
|
||||
db: Session = Depends(get_db),
|
||||
) -> UserPublic:
|
||||
if not accounts.auth_enabled():
|
||||
raise HTTPException(status_code=400, detail="Set AUTH_ENABLED=true to use accounts")
|
||||
user = accounts.authenticate(db, body.username, body.password)
|
||||
if not user:
|
||||
raise HTTPException(status_code=401, detail="Invalid username or password")
|
||||
sess = accounts.create_session(db, user)
|
||||
_set_session_cookie(response, request, sess.token)
|
||||
return UserPublic.model_validate(user)
|
||||
|
||||
|
||||
@router.post("/logout")
|
||||
async def logout(
|
||||
request: Request,
|
||||
response: Response,
|
||||
db: Session = Depends(get_db),
|
||||
) -> dict:
|
||||
token = request.cookies.get(accounts.SESSION_COOKIE_NAME)
|
||||
accounts.delete_session(db, token)
|
||||
_clear_session_cookie(response, request)
|
||||
return {"message": "Logged out"}
|
||||
@@ -0,0 +1,56 @@
|
||||
from fastapi import APIRouter
|
||||
|
||||
from editor_app.models import FileContent, FolderOperation, MoveFileRequest
|
||||
from editor_app.services import filesystem
|
||||
|
||||
router = APIRouter(prefix="/api")
|
||||
|
||||
|
||||
@router.get("/files")
|
||||
async def list_files(path: str = ""):
|
||||
files = filesystem.list_files(path)
|
||||
return {"files": files}
|
||||
|
||||
|
||||
@router.get("/workspace/py-sources")
|
||||
async def workspace_python_sources():
|
||||
return {"files": filesystem.collect_python_sources()}
|
||||
|
||||
|
||||
@router.get("/file/{file_path:path}")
|
||||
async def read_file(file_path: str):
|
||||
content, filename = filesystem.read_text_file(file_path)
|
||||
return {"content": content, "filename": filename}
|
||||
|
||||
|
||||
@router.post("/file/{file_path:path}")
|
||||
async def save_file(file_path: str, file_data: FileContent):
|
||||
filename = filesystem.save_text_file(file_path, file_data.content)
|
||||
return {"message": "File saved successfully", "filename": filename}
|
||||
|
||||
|
||||
@router.post("/file-move")
|
||||
async def move_file(move_data: MoveFileRequest):
|
||||
new_path, moved_type = filesystem.move_path(
|
||||
source_path=move_data.source_path,
|
||||
destination_folder=move_data.destination_folder,
|
||||
)
|
||||
return {"message": "Path moved successfully", "new_path": new_path, "moved_type": moved_type}
|
||||
|
||||
|
||||
@router.delete("/file/{file_path:path}")
|
||||
async def delete_file(file_path: str):
|
||||
filesystem.delete_file(file_path)
|
||||
return {"message": "File deleted successfully"}
|
||||
|
||||
|
||||
@router.post("/folder/new/{folder_path:path}")
|
||||
async def create_folder(folder_path: str, folder_data: FolderOperation):
|
||||
folder_name = filesystem.create_folder(folder_path)
|
||||
return {"message": "Folder created successfully", "folder": folder_name}
|
||||
|
||||
|
||||
@router.delete("/folder/{folder_path:path}")
|
||||
async def delete_folder(folder_path: str):
|
||||
filesystem.delete_folder(folder_path)
|
||||
return {"message": "Folder deleted successfully"}
|
||||
@@ -0,0 +1,26 @@
|
||||
from fastapi import APIRouter
|
||||
from fastapi.responses import FileResponse
|
||||
|
||||
from editor_app.config import STATIC_DIR
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
|
||||
@router.get("/")
|
||||
async def serve_home():
|
||||
return FileResponse(STATIC_DIR / "home.html")
|
||||
|
||||
|
||||
@router.get("/editor")
|
||||
async def serve_frontend():
|
||||
return FileResponse(STATIC_DIR / "index.html")
|
||||
|
||||
|
||||
@router.get("/login")
|
||||
async def serve_login():
|
||||
return FileResponse(STATIC_DIR / "login.html")
|
||||
|
||||
|
||||
@router.get("/register")
|
||||
async def serve_register():
|
||||
return FileResponse(STATIC_DIR / "register.html")
|
||||
@@ -0,0 +1,50 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from editor_app.db.session import get_db
|
||||
from editor_app.db.models import User
|
||||
from editor_app.deps import require_superuser
|
||||
from editor_app.schemas.users import UserCreateAdmin, UserPublic
|
||||
from editor_app.services import accounts
|
||||
|
||||
router = APIRouter(prefix="/api/users", tags=["users"])
|
||||
|
||||
|
||||
@router.get("", response_model=list[UserPublic])
|
||||
async def list_users(
|
||||
_admin: User = Depends(require_superuser),
|
||||
db: Session = Depends(get_db),
|
||||
) -> list[UserPublic]:
|
||||
return [UserPublic.model_validate(u) for u in accounts.list_users(db)]
|
||||
|
||||
|
||||
@router.post("", response_model=UserPublic)
|
||||
async def create_user_admin(
|
||||
body: UserCreateAdmin,
|
||||
admin: User = Depends(require_superuser),
|
||||
db: Session = Depends(get_db),
|
||||
) -> UserPublic:
|
||||
if accounts.get_user_by_username(db, body.username):
|
||||
raise HTTPException(status_code=409, detail="Username already taken")
|
||||
user = accounts.create_user(
|
||||
db,
|
||||
body.username,
|
||||
body.password,
|
||||
is_superuser=body.is_superuser,
|
||||
)
|
||||
return UserPublic.model_validate(user)
|
||||
|
||||
|
||||
@router.delete("/{user_id}")
|
||||
async def delete_user_admin(
|
||||
user_id: int,
|
||||
admin: User = Depends(require_superuser),
|
||||
db: Session = Depends(get_db),
|
||||
) -> dict:
|
||||
if user_id == admin.id:
|
||||
raise HTTPException(status_code=400, detail="Cannot delete your own account")
|
||||
if not accounts.delete_user(db, user_id):
|
||||
raise HTTPException(status_code=404, detail="User not found")
|
||||
return {"message": "User deleted"}
|
||||
@@ -0,0 +1,46 @@
|
||||
from pydantic import BaseModel, Field, field_validator
|
||||
|
||||
|
||||
class RegisterRequest(BaseModel):
|
||||
username: str = Field(min_length=3, max_length=64)
|
||||
password: str = Field(min_length=8, max_length=128)
|
||||
|
||||
@field_validator("username")
|
||||
@classmethod
|
||||
def username_chars(cls, v: str) -> str:
|
||||
s = v.strip()
|
||||
if not s.replace("_", "").isalnum():
|
||||
raise ValueError("Username may only contain letters, numbers, and underscores")
|
||||
return s
|
||||
|
||||
|
||||
class LoginRequest(BaseModel):
|
||||
username: str
|
||||
password: str
|
||||
|
||||
|
||||
class UserPublic(BaseModel):
|
||||
id: int
|
||||
username: str
|
||||
is_superuser: bool
|
||||
|
||||
model_config = {"from_attributes": True}
|
||||
|
||||
|
||||
class UserCreateAdmin(BaseModel):
|
||||
username: str = Field(min_length=3, max_length=64)
|
||||
password: str = Field(min_length=8, max_length=128)
|
||||
is_superuser: bool = False
|
||||
|
||||
@field_validator("username")
|
||||
@classmethod
|
||||
def username_chars(cls, v: str) -> str:
|
||||
s = v.strip()
|
||||
if not s.replace("_", "").isalnum():
|
||||
raise ValueError("Username may only contain letters, numbers, and underscores")
|
||||
return s
|
||||
|
||||
|
||||
class AuthStatusResponse(BaseModel):
|
||||
auth_enabled: bool
|
||||
register_open: bool
|
||||
Whitespace-only changes.
@@ -0,0 +1,128 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import datetime as dt
|
||||
import os
|
||||
import secrets
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
import bcrypt
|
||||
from sqlalchemy import func, select
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from editor_app.db.models import AuthSession, User
|
||||
|
||||
if TYPE_CHECKING:
|
||||
pass
|
||||
|
||||
SESSION_COOKIE_NAME = "editor_session"
|
||||
SESSION_DAYS_DEFAULT = 14
|
||||
|
||||
|
||||
def auth_enabled() -> bool:
|
||||
return os.environ.get("AUTH_ENABLED", "false").strip().lower() in ("1", "true", "yes", "on")
|
||||
|
||||
|
||||
def register_open() -> bool:
|
||||
return os.environ.get("AUTH_REGISTER_OPEN", "true").strip().lower() in ("1", "true", "yes", "on")
|
||||
|
||||
|
||||
def session_ttl_days() -> int:
|
||||
try:
|
||||
return max(1, min(365, int(os.environ.get("AUTH_SESSION_DAYS", str(SESSION_DAYS_DEFAULT)))))
|
||||
except ValueError:
|
||||
return SESSION_DAYS_DEFAULT
|
||||
|
||||
|
||||
def hash_password(password: str) -> str:
|
||||
return bcrypt.hashpw(password.encode("utf-8"), bcrypt.gensalt()).decode("ascii")
|
||||
|
||||
|
||||
def verify_password(plain: str, hashed: str) -> bool:
|
||||
try:
|
||||
return bcrypt.checkpw(plain.encode("utf-8"), hashed.encode("ascii"))
|
||||
except (ValueError, TypeError):
|
||||
return False
|
||||
|
||||
|
||||
def get_user_by_username(db: Session, username: str) -> User | None:
|
||||
return db.scalars(select(User).where(User.username == username)).one_or_none()
|
||||
|
||||
|
||||
def get_user_by_id(db: Session, user_id: int) -> User | None:
|
||||
return db.scalars(select(User).where(User.id == user_id)).one_or_none()
|
||||
|
||||
|
||||
def count_users(db: Session) -> int:
|
||||
return int(db.scalar(select(func.count()).select_from(User)) or 0)
|
||||
|
||||
|
||||
def create_user(db: Session, username: str, password: str, *, is_superuser: bool = False) -> User:
|
||||
user = User(
|
||||
username=username,
|
||||
password_hash=hash_password(password),
|
||||
is_superuser=is_superuser,
|
||||
)
|
||||
db.add(user)
|
||||
db.commit()
|
||||
db.refresh(user)
|
||||
return user
|
||||
|
||||
|
||||
def register_user(db: Session, username: str, password: str) -> User:
|
||||
if get_user_by_username(db, username):
|
||||
raise ValueError("Username already taken")
|
||||
first = count_users(db) == 0
|
||||
return create_user(db, username, password, is_superuser=first)
|
||||
|
||||
|
||||
def authenticate(db: Session, username: str, password: str) -> User | None:
|
||||
user = get_user_by_username(db, username.strip())
|
||||
if not user or not verify_password(password, user.password_hash):
|
||||
return None
|
||||
return user
|
||||
|
||||
|
||||
def _utc_naive() -> dt.datetime:
|
||||
return dt.datetime.now(dt.UTC).replace(tzinfo=None)
|
||||
|
||||
|
||||
def create_session(db: Session, user: User) -> AuthSession:
|
||||
token = secrets.token_urlsafe(48)
|
||||
expires = _utc_naive() + dt.timedelta(days=session_ttl_days())
|
||||
row = AuthSession(user_id=user.id, token=token, expires_at=expires)
|
||||
db.add(row)
|
||||
db.commit()
|
||||
db.refresh(row)
|
||||
return row
|
||||
|
||||
|
||||
def get_session_user(db: Session, token: str | None) -> User | None:
|
||||
if not token:
|
||||
return None
|
||||
now = _utc_naive()
|
||||
row = db.scalars(select(AuthSession).where(AuthSession.token == token)).one_or_none()
|
||||
if not row or row.expires_at < now:
|
||||
return None
|
||||
return get_user_by_id(db, row.user_id)
|
||||
|
||||
|
||||
def delete_session(db: Session, token: str | None) -> None:
|
||||
if not token:
|
||||
return
|
||||
row = db.scalars(select(AuthSession).where(AuthSession.token == token)).one_or_none()
|
||||
if row:
|
||||
db.delete(row)
|
||||
db.commit()
|
||||
|
||||
|
||||
def list_users(db: Session) -> list[User]:
|
||||
return list(db.scalars(select(User).order_by(User.username)).all())
|
||||
|
||||
|
||||
def delete_user(db: Session, user_id: int) -> bool:
|
||||
user = get_user_by_id(db, user_id)
|
||||
if not user:
|
||||
return False
|
||||
db.delete(user)
|
||||
db.commit()
|
||||
return True
|
||||
@@ -0,0 +1,202 @@
|
||||
import shutil
|
||||
from pathlib import Path
|
||||
|
||||
from fastapi import HTTPException
|
||||
|
||||
from editor_app import config
|
||||
from editor_app.models import FileInfo
|
||||
|
||||
LIB_DIR_NAME = "lib"
|
||||
WRITABLE_ROOTS = {"code"}
|
||||
|
||||
|
||||
def normalize_relative_path(relative_path: str) -> str:
|
||||
cleaned = (relative_path or "").strip().lstrip("/")
|
||||
if not cleaned:
|
||||
return ""
|
||||
|
||||
parts = [segment for segment in cleaned.split("/") if segment]
|
||||
if len(parts) >= 2 and parts[0] == "code":
|
||||
while len(parts) >= 2 and parts[0] == parts[1] == "code":
|
||||
parts.pop(1)
|
||||
return "/".join(parts)
|
||||
|
||||
|
||||
def resolve_workspace_path(relative_path: str) -> Path:
|
||||
relative_path = normalize_relative_path(relative_path)
|
||||
target_path = (config.WORKSPACE_ROOT / relative_path).resolve()
|
||||
try:
|
||||
target_path.relative_to(config.WORKSPACE_ROOT.resolve())
|
||||
except ValueError as exc:
|
||||
raise HTTPException(status_code=400, detail="Path escapes workspace") from exc
|
||||
return target_path
|
||||
|
||||
|
||||
def _is_path_in_lib(target_path: Path) -> bool:
|
||||
workspace = config.WORKSPACE_ROOT.resolve()
|
||||
lib_root = (workspace / LIB_DIR_NAME).resolve()
|
||||
try:
|
||||
target_path.resolve().relative_to(lib_root)
|
||||
return True
|
||||
except ValueError:
|
||||
return False
|
||||
|
||||
|
||||
def _ensure_not_lib_path(target_path: Path) -> None:
|
||||
if _is_path_in_lib(target_path):
|
||||
raise HTTPException(status_code=403, detail="lib is read-only")
|
||||
|
||||
|
||||
def _is_writable_path(target_path: Path) -> bool:
|
||||
workspace = config.WORKSPACE_ROOT.resolve()
|
||||
resolved = target_path.resolve()
|
||||
try:
|
||||
relative = resolved.relative_to(workspace)
|
||||
except ValueError:
|
||||
return False
|
||||
if not relative.parts:
|
||||
return False
|
||||
return relative.parts[0] in WRITABLE_ROOTS
|
||||
|
||||
|
||||
def _ensure_writable_path(target_path: Path) -> None:
|
||||
if not _is_writable_path(target_path):
|
||||
raise HTTPException(
|
||||
status_code=403,
|
||||
detail="Only code/ is writable (lib is read-only)",
|
||||
)
|
||||
|
||||
|
||||
def list_files(path: str = "") -> list[FileInfo]:
|
||||
path = normalize_relative_path(path)
|
||||
target_path = config.WORKSPACE_ROOT / path if path else config.WORKSPACE_ROOT
|
||||
if not target_path.exists() or not target_path.is_dir():
|
||||
raise HTTPException(status_code=404, detail="Directory not found")
|
||||
|
||||
files = []
|
||||
for item in sorted(target_path.iterdir()):
|
||||
if item.name.startswith("."):
|
||||
continue
|
||||
files.append(
|
||||
FileInfo(
|
||||
name=item.name,
|
||||
is_directory=item.is_dir(),
|
||||
size=item.stat().st_size if item.is_file() else None,
|
||||
)
|
||||
)
|
||||
return files
|
||||
|
||||
|
||||
def read_text_file(file_path: str) -> tuple[str, str]:
|
||||
target_path = resolve_workspace_path(file_path)
|
||||
if not target_path.exists():
|
||||
raise HTTPException(status_code=404, detail="File not found")
|
||||
if target_path.is_dir():
|
||||
raise HTTPException(status_code=400, detail="Path is a directory")
|
||||
try:
|
||||
content = target_path.read_text(encoding="utf-8")
|
||||
except UnicodeDecodeError as exc:
|
||||
raise HTTPException(status_code=400, detail="File is not a text file") from exc
|
||||
return content, target_path.name
|
||||
|
||||
|
||||
def save_text_file(file_path: str, content: str) -> str:
|
||||
target_path = resolve_workspace_path(file_path)
|
||||
_ensure_not_lib_path(target_path)
|
||||
_ensure_writable_path(target_path)
|
||||
target_path.parent.mkdir(parents=True, exist_ok=True)
|
||||
target_path.write_text(content, encoding="utf-8")
|
||||
return target_path.name
|
||||
|
||||
|
||||
def delete_file(file_path: str) -> None:
|
||||
target_path = resolve_workspace_path(file_path)
|
||||
_ensure_not_lib_path(target_path)
|
||||
_ensure_writable_path(target_path)
|
||||
if not target_path.exists():
|
||||
raise HTTPException(status_code=404, detail="File not found")
|
||||
if target_path.is_dir():
|
||||
raise HTTPException(status_code=400, detail="Cannot delete directories")
|
||||
target_path.unlink()
|
||||
|
||||
|
||||
def move_path(source_path: str, destination_folder: str) -> tuple[str, str]:
|
||||
source = resolve_workspace_path(source_path)
|
||||
_ensure_not_lib_path(source)
|
||||
_ensure_writable_path(source)
|
||||
if not source.exists():
|
||||
raise HTTPException(status_code=404, detail="Source path not found")
|
||||
|
||||
destination_dir = (
|
||||
resolve_workspace_path(destination_folder)
|
||||
if destination_folder
|
||||
else config.WORKSPACE_ROOT
|
||||
)
|
||||
_ensure_not_lib_path(destination_dir)
|
||||
_ensure_writable_path(destination_dir)
|
||||
if not destination_dir.exists() or not destination_dir.is_dir():
|
||||
raise HTTPException(status_code=404, detail="Destination folder not found")
|
||||
|
||||
destination = destination_dir / source.name
|
||||
source_resolved = source.resolve()
|
||||
destination_resolved = destination.resolve()
|
||||
if destination_resolved == source_resolved:
|
||||
raise HTTPException(status_code=400, detail="Path is already in that folder")
|
||||
if source.is_dir():
|
||||
source_prefix = str(source_resolved) + "/"
|
||||
if str(destination_dir.resolve()).startswith(source_prefix):
|
||||
raise HTTPException(
|
||||
status_code=400, detail="Cannot move a folder into itself or its child"
|
||||
)
|
||||
if destination.exists():
|
||||
raise HTTPException(
|
||||
status_code=409,
|
||||
detail="A path with that name already exists in destination",
|
||||
)
|
||||
|
||||
destination.parent.mkdir(parents=True, exist_ok=True)
|
||||
source.rename(destination)
|
||||
moved_type = "folder" if destination.is_dir() else "file"
|
||||
return str(destination.relative_to(config.WORKSPACE_ROOT)), moved_type
|
||||
|
||||
|
||||
def create_folder(folder_path: str) -> str:
|
||||
target_path = resolve_workspace_path(folder_path)
|
||||
_ensure_not_lib_path(target_path)
|
||||
_ensure_writable_path(target_path)
|
||||
if target_path.exists():
|
||||
raise HTTPException(status_code=400, detail="Folder already exists")
|
||||
target_path.mkdir(parents=True, exist_ok=False)
|
||||
return target_path.name
|
||||
|
||||
|
||||
def delete_folder(folder_path: str) -> None:
|
||||
target_path = resolve_workspace_path(folder_path)
|
||||
_ensure_not_lib_path(target_path)
|
||||
_ensure_writable_path(target_path)
|
||||
if not target_path.exists():
|
||||
raise HTTPException(status_code=404, detail="Folder not found")
|
||||
if not target_path.is_dir():
|
||||
raise HTTPException(status_code=400, detail="Path is not a directory")
|
||||
shutil.rmtree(target_path)
|
||||
|
||||
|
||||
def collect_python_sources() -> dict[str, str]:
|
||||
"""Return all UTF-8 .py files under the workspace for browser-side Pyodide sync."""
|
||||
result: dict[str, str] = {}
|
||||
workspace = config.WORKSPACE_ROOT.resolve()
|
||||
if not workspace.exists():
|
||||
return result
|
||||
for path in workspace.rglob("*.py"):
|
||||
try:
|
||||
rel = path.relative_to(workspace)
|
||||
except ValueError:
|
||||
continue
|
||||
if any(part.startswith(".") for part in rel.parts):
|
||||
continue
|
||||
try:
|
||||
key = str(rel).replace("\\", "/")
|
||||
result[key] = path.read_text(encoding="utf-8")
|
||||
except (UnicodeDecodeError, OSError):
|
||||
continue
|
||||
return result
|
||||
@@ -0,0 +1,14 @@
|
||||
/* esm.sh - codemirror@6.0.2 */
|
||||
var js=[],Bl=[];(()=>{let n="lc,34,7n,7,7b,19,,,,2,,2,,,20,b,1c,l,g,,2t,7,2,6,2,2,,4,z,,u,r,2j,b,1m,9,9,,o,4,,9,,3,,5,17,3,3b,f,,w,1j,,,,4,8,4,,3,7,a,2,t,,1m,,,,2,4,8,,9,,a,2,q,,2,2,1l,,4,2,4,2,2,3,3,,u,2,3,,b,2,1l,,4,5,,2,4,,k,2,m,6,,,1m,,,2,,4,8,,7,3,a,2,u,,1n,,,,c,,9,,14,,3,,1l,3,5,3,,4,7,2,b,2,t,,1m,,2,,2,,3,,5,2,7,2,b,2,s,2,1l,2,,,2,4,8,,9,,a,2,t,,20,,4,,2,3,,,8,,29,,2,7,c,8,2q,,2,9,b,6,22,2,r,,,,,,1j,e,,5,,2,5,b,,10,9,,2u,4,,6,,2,2,2,p,2,4,3,g,4,d,,2,2,6,,f,,jj,3,qa,3,t,3,t,2,u,2,1s,2,,7,8,,2,b,9,,19,3,3b,2,y,,3a,3,4,2,9,,6,3,63,2,2,,1m,,,7,,,,,2,8,6,a,2,,1c,h,1r,4,1c,7,,,5,,14,9,c,2,w,4,2,2,,3,1k,,,2,3,,,3,1m,8,2,2,48,3,,d,,7,4,,6,,3,2,5i,1m,,5,ek,,5f,x,2da,3,3x,,2o,w,fe,6,2x,2,n9w,4,,a,w,2,28,2,7k,,3,,4,,p,2,5,,47,2,q,i,d,,12,8,p,b,1a,3,1c,,2,4,2,2,13,,1v,6,2,2,2,2,c,,8,,1b,,1f,,,3,2,2,5,2,,,16,2,8,,6m,,2,,4,,fn4,,kh,g,g,g,a6,2,gt,,6a,,45,5,1ae,3,,2,5,4,14,3,4,,4l,2,fx,4,ar,2,49,b,4w,,1i,f,1k,3,1d,4,2,2,1x,3,10,5,,8,1q,,c,2,1g,9,a,4,2,,2n,3,2,,,2,6,,4g,,3,8,l,2,1l,2,,,,,m,,e,7,3,5,5f,8,2,3,,,n,,29,,2,6,,,2,,,2,,2,6j,,2,4,6,2,,2,r,2,2d,8,2,,,2,2y,,,,2,6,,,2t,3,2,4,,5,77,9,,2,6t,,a,2,,,4,,40,4,2,2,4,,w,a,14,6,2,4,8,,9,6,2,3,1a,d,,2,ba,7,,6,,,2a,m,2,7,,2,,2,3e,6,3,,,2,,7,,,20,2,3,,,,9n,2,f0b,5,1n,7,t4,,1r,4,29,,f5k,2,43q,,,3,4,5,8,8,2,7,u,4,44,3,1iz,1j,4,1e,8,,e,,m,5,,f,11s,7,,h,2,7,,2,,5,79,7,c5,4,15s,7,31,7,240,5,gx7k,2o,3k,6o".split(",").map(e=>e?parseInt(e,36):1);for(let e=0,t=0;e<n.length;e++)(e%2?Bl:js).push(t=t+n[e])})();function iu(n){if(n<768)return!1;for(let e=0,t=js.length;;){let i=e+t>>1;if(n<js[i])t=i;else if(n>=Bl[i])e=i+1;else return!0;if(e==t)return!1}}function Tl(n){return n>=127462&&n<=127487}var Dl=8205;function El(n,e,t=!0,i=!0){return(t?Pl:nu)(n,e,i)}function Pl(n,e,t){if(e==n.length)return e;e&&Ll(n.charCodeAt(e))&&Rl(n.charCodeAt(e-1))&&e--;let i=$s(n,e);for(e+=Ol(i);e<n.length;){let s=$s(n,e);if(i==Dl||s==Dl||t&&iu(s))e+=Ol(s),i=s;else if(Tl(s)){let r=0,o=e-2;for(;o>=0&&Tl($s(n,o));)r++,o-=2;if(r%2==0)break;e+=2}else break}return e}function nu(n,e,t){for(;e>0;){let i=Pl(n,e-2,t);if(i<e)return i;e--}return 0}function $s(n,e){let t=n.charCodeAt(e);if(!Rl(t)||e+1==n.length)return t;let i=n.charCodeAt(e+1);return Ll(i)?(t-55296<<10)+(i-56320)+65536:t}function Ll(n){return n>=56320&&n<57344}function Rl(n){return n>=55296&&n<56320}function Ol(n){return n<65536?1:2}var N=class n{lineAt(e){if(e<0||e>this.length)throw new RangeError(`Invalid position ${e} in document of length ${this.length}`);return this.lineInner(e,!1,1,0)}line(e){if(e<1||e>this.lines)throw new RangeError(`Invalid line number ${e} in ${this.lines}-line document`);return this.lineInner(e,!0,1,0)}replace(e,t,i){[e,t]=Yt(this,e,t);let s=[];return this.decompose(0,e,s,2),i.length&&i.decompose(0,i.length,s,3),this.decompose(t,this.length,s,1),Ut.from(s,this.length-(t-e)+i.length)}append(e){return this.replace(this.length,this.length,e)}slice(e,t=this.length){[e,t]=Yt(this,e,t);let i=[];return this.decompose(e,t,i,0),Ut.from(i,t-e)}eq(e){if(e==this)return!0;if(e.length!=this.length||e.lines!=this.lines)return!1;let t=this.scanIdentical(e,1),i=this.length-this.scanIdentical(e,-1),s=new Mt(this),r=new Mt(e);for(let o=t,l=t;;){if(s.next(o),r.next(o),o=0,s.lineBreak!=r.lineBreak||s.done!=r.done||s.value!=r.value)return!1;if(l+=s.value.length,s.done||l>=i)return!0}}iter(e=1){return new Mt(this,e)}iterRange(e,t=this.length){return new mn(this,e,t)}iterLines(e,t){let i;if(e==null)i=this.iter();else{t==null&&(t=this.lines+1);let s=this.line(e).from;i=this.iterRange(s,Math.max(s,t==this.lines+1?this.length:t<=1?0:this.line(t-1).to))}return new gn(i)}toString(){return this.sliceString(0)}toJSON(){let e=[];return this.flatten(e),e}constructor(){}static of(e){if(e.length==0)throw new RangeError("A document must have at least one line");return e.length==1&&!e[0]?n.empty:e.length<=32?new ve(e):Ut.from(ve.split(e,[]))}},ve=class n extends N{constructor(e,t=su(e)){super(),this.text=e,this.length=t}get lines(){return this.text.length}get children(){return null}lineInner(e,t,i,s){for(let r=0;;r++){let o=this.text[r],l=s+o.length;if((t?i:l)>=e)return new Gs(s,l,i,o);s=l+1,i++}}decompose(e,t,i,s){let r=e<=0&&t>=this.length?this:new n(Il(this.text,e,t),Math.min(t,this.length)-Math.max(0,e));if(s&1){let o=i.pop(),l=pn(r.text,o.text.slice(),0,r.length);if(l.length<=32)i.push(new n(l,o.length+r.length));else{let a=l.length>>1;i.push(new n(l.slice(0,a)),new n(l.slice(a)))}}else i.push(r)}replace(e,t,i){if(!(i instanceof n))return super.replace(e,t,i);[e,t]=Yt(this,e,t);let s=pn(this.text,pn(i.text,Il(this.text,0,e)),t),r=this.length+i.length-(t-e);return s.length<=32?new n(s,r):Ut.from(n.split(s,[]),r)}sliceString(e,t=this.length,i=`
|
||||
`){[e,t]=Yt(this,e,t);let s="";for(let r=0,o=0;r<=t&&o<this.text.length;o++){let l=this.text[o],a=r+l.length;r>e&&o&&(s+=i),e<a&&t>r&&(s+=l.slice(Math.max(0,e-r),t-r)),r=a+1}return s}flatten(e){for(let t of this.text)e.push(t)}scanIdentical(){return 0}static split(e,t){let i=[],s=-1;for(let r of e)i.push(r),s+=r.length+1,i.length==32&&(t.push(new n(i,s)),i=[],s=-1);return s>-1&&t.push(new n(i,s)),t}},Ut=class n extends N{constructor(e,t){super(),this.children=e,this.length=t,this.lines=0;for(let i of e)this.lines+=i.lines}lineInner(e,t,i,s){for(let r=0;;r++){let o=this.children[r],l=s+o.length,a=i+o.lines-1;if((t?a:l)>=e)return o.lineInner(e,t,i,s);s=l+1,i=a+1}}decompose(e,t,i,s){for(let r=0,o=0;o<=t&&r<this.children.length;r++){let l=this.children[r],a=o+l.length;if(e<=a&&t>=o){let f=s&((o<=e?1:0)|(a>=t?2:0));o>=e&&a<=t&&!f?i.push(l):l.decompose(e-o,t-o,i,f)}o=a+1}}replace(e,t,i){if([e,t]=Yt(this,e,t),i.lines<this.lines)for(let s=0,r=0;s<this.children.length;s++){let o=this.children[s],l=r+o.length;if(e>=r&&t<=l){let a=o.replace(e-r,t-r,i),f=this.lines-o.lines+a.lines;if(a.lines<f>>4&&a.lines>f>>6){let h=this.children.slice();return h[s]=a,new n(h,this.length-(t-e)+i.length)}return super.replace(r,l,a)}r=l+1}return super.replace(e,t,i)}sliceString(e,t=this.length,i=`
|
||||
`){[e,t]=Yt(this,e,t);let s="";for(let r=0,o=0;r<this.children.length&&o<=t;r++){let l=this.children[r],a=o+l.length;o>e&&r&&(s+=i),e<a&&t>o&&(s+=l.sliceString(e-o,t-o,i)),o=a+1}return s}flatten(e){for(let t of this.children)t.flatten(e)}scanIdentical(e,t){if(!(e instanceof n))return 0;let i=0,[s,r,o,l]=t>0?[0,0,this.children.length,e.children.length]:[this.children.length-1,e.children.length-1,-1,-1];for(;;s+=t,r+=t){if(s==o||r==l)return i;let a=this.children[s],f=e.children[r];if(a!=f)return i+a.scanIdentical(f,t);i+=a.length+1}}static from(e,t=e.reduce((i,s)=>i+s.length+1,-1)){let i=0;for(let d of e)i+=d.lines;if(i<32){let d=[];for(let p of e)p.flatten(d);return new ve(d,t)}let s=Math.max(32,i>>5),r=s<<1,o=s>>1,l=[],a=0,f=-1,h=[];function c(d){let p;if(d.lines>r&&d instanceof n)for(let m of d.children)c(m);else d.lines>o&&(a>o||!a)?(u(),l.push(d)):d instanceof ve&&a&&(p=h[h.length-1])instanceof ve&&d.lines+p.lines<=32?(a+=d.lines,f+=d.length+1,h[h.length-1]=new ve(p.text.concat(d.text),p.length+1+d.length)):(a+d.lines>s&&u(),a+=d.lines,f+=d.length+1,h.push(d))}function u(){a!=0&&(l.push(h.length==1?h[0]:n.from(h,f)),f=-1,a=h.length=0)}for(let d of e)c(d);return u(),l.length==1?l[0]:new n(l,t)}};N.empty=new ve([""],0);function su(n){let e=-1;for(let t of n)e+=t.length+1;return e}function pn(n,e,t=0,i=1e9){for(let s=0,r=0,o=!0;r<n.length&&s<=i;r++){let l=n[r],a=s+l.length;a>=t&&(a>i&&(l=l.slice(0,i-s)),s<t&&(l=l.slice(t-s)),o?(e[e.length-1]+=l,o=!1):e.push(l)),s=a+1}return e}function Il(n,e,t){return pn(n,[""],e,t)}var Mt=class{constructor(e,t=1){this.dir=t,this.done=!1,this.lineBreak=!1,this.value="",this.nodes=[e],this.offsets=[t>0?1:(e instanceof ve?e.text.length:e.children.length)<<1]}nextInner(e,t){for(this.done=this.lineBreak=!1;;){let i=this.nodes.length-1,s=this.nodes[i],r=this.offsets[i],o=r>>1,l=s instanceof ve?s.text.length:s.children.length;if(o==(t>0?l:0)){if(i==0)return this.done=!0,this.value="",this;t>0&&this.offsets[i-1]++,this.nodes.pop(),this.offsets.pop()}else if((r&1)==(t>0?0:1)){if(this.offsets[i]+=t,e==0)return this.lineBreak=!0,this.value=`
|
||||
`,this;e--}else if(s instanceof ve){let a=s.text[o+(t<0?-1:0)];if(this.offsets[i]+=t,a.length>Math.max(0,e))return this.value=e==0?a:t>0?a.slice(e):a.slice(0,a.length-e),this;e-=a.length}else{let a=s.children[o+(t<0?-1:0)];e>a.length?(e-=a.length,this.offsets[i]+=t):(t<0&&this.offsets[i]--,this.nodes.push(a),this.offsets.push(t>0?1:(a instanceof ve?a.text.length:a.children.length)<<1))}}}next(e=0){return e<0&&(this.nextInner(-e,-this.dir),e=this.value.length),this.nextInner(e,this.dir)}},mn=class{constructor(e,t,i){this.value="",this.done=!1,this.cursor=new Mt(e,t>i?-1:1),this.pos=t>i?e.length:0,this.from=Math.min(t,i),this.to=Math.max(t,i)}nextInner(e,t){if(t<0?this.pos<=this.from:this.pos>=this.to)return this.value="",this.done=!0,this;e+=Math.max(0,t<0?this.pos-this.to:this.from-this.pos);let i=t<0?this.pos-this.from:this.to-this.pos;e>i&&(e=i),i-=e;let{value:s}=this.cursor.next(e);return this.pos+=(s.length+e)*t,this.value=s.length<=i?s:t<0?s.slice(s.length-i):s.slice(0,i),this.done=!this.value,this}next(e=0){return e<0?e=Math.max(e,this.from-this.pos):e>0&&(e=Math.min(e,this.to-this.pos)),this.nextInner(e,this.cursor.dir)}get lineBreak(){return this.cursor.lineBreak&&this.value!=""}},gn=class{constructor(e){this.inner=e,this.afterBreak=!0,this.value="",this.done=!1}next(e=0){let{done:t,lineBreak:i,value:s}=this.inner.next(e);return t&&this.afterBreak?(this.value="",this.afterBreak=!1):t?(this.done=!0,this.value=""):i?this.afterBreak?this.value="":(this.afterBreak=!0,this.next()):(this.value=s,this.afterBreak=!1),this}get lineBreak(){return!1}};typeof Symbol<"u"&&(N.prototype[Symbol.iterator]=function(){return this.iter()},Mt.prototype[Symbol.iterator]=mn.prototype[Symbol.iterator]=gn.prototype[Symbol.iterator]=function(){return this});var Gs=class{constructor(e,t,i,s){this.from=e,this.to=t,this.number=i,this.text=s}get length(){return this.to-this.from}};function Yt(n,e,t){return e=Math.max(0,Math.min(n.length,e)),[e,Math.max(e,Math.min(n.length,t))]}function Q(n,e,t=!0,i=!0){return El(n,e,t,i)}function ru(n){return n>=56320&&n<57344}function ou(n){return n>=55296&&n<56320}function oe(n,e){let t=n.charCodeAt(e);if(!ou(t)||e+1==n.length)return t;let i=n.charCodeAt(e+1);return ru(i)?(t-55296<<10)+(i-56320)+65536:t}function yi(n){return n<=65535?String.fromCharCode(n):(n-=65536,String.fromCharCode((n>>10)+55296,(n&1023)+56320))}function Se(n){return n<65536?1:2}var _s=/\r\n?|\n/,re=(function(n){return n[n.Simple=0]="Simple",n[n.TrackDel=1]="TrackDel",n[n.TrackBefore=2]="TrackBefore",n[n.TrackAfter=3]="TrackAfter",n})(re||(re={})),rt=class n{constructor(e){this.sections=e}get length(){let e=0;for(let t=0;t<this.sections.length;t+=2)e+=this.sections[t];return e}get newLength(){let e=0;for(let t=0;t<this.sections.length;t+=2){let i=this.sections[t+1];e+=i<0?this.sections[t]:i}return e}get empty(){return this.sections.length==0||this.sections.length==2&&this.sections[1]<0}iterGaps(e){for(let t=0,i=0,s=0;t<this.sections.length;){let r=this.sections[t++],o=this.sections[t++];o<0?(e(i,s,r),s+=r):s+=o,i+=r}}iterChangedRanges(e,t=!1){Ys(this,e,t)}get invertedDesc(){let e=[];for(let t=0;t<this.sections.length;){let i=this.sections[t++],s=this.sections[t++];s<0?e.push(i,s):e.push(s,i)}return new n(e)}composeDesc(e){return this.empty?e:e.empty?this:Wl(this,e)}mapDesc(e,t=!1){return e.empty?this:Js(this,e,t)}mapPos(e,t=-1,i=re.Simple){let s=0,r=0;for(let o=0;o<this.sections.length;){let l=this.sections[o++],a=this.sections[o++],f=s+l;if(a<0){if(f>e)return r+(e-s);r+=l}else{if(i!=re.Simple&&f>=e&&(i==re.TrackDel&&s<e&&f>e||i==re.TrackBefore&&s<e||i==re.TrackAfter&&f>e))return null;if(f>e||f==e&&t<0&&!l)return e==s||t<0?r:r+a;r+=a}s=f}if(e>s)throw new RangeError(`Position ${e} is out of range for changeset of length ${s}`);return r}touchesRange(e,t=e){for(let i=0,s=0;i<this.sections.length&&s<=t;){let r=this.sections[i++],o=this.sections[i++],l=s+r;if(o>=0&&s<=t&&l>=e)return s<e&&l>t?"cover":!0;s=l}return!1}toString(){let e="";for(let t=0;t<this.sections.length;){let i=this.sections[t++],s=this.sections[t++];e+=(e?" ":"")+i+(s>=0?":"+s:"")}return e}toJSON(){return this.sections}static fromJSON(e){if(!Array.isArray(e)||e.length%2||e.some(t=>typeof t!="number"))throw new RangeError("Invalid JSON representation of ChangeDesc");return new n(e)}static create(e){return new n(e)}},pe=class n extends rt{constructor(e,t){super(e),this.inserted=t}apply(e){if(this.length!=e.length)throw new RangeError("Applying change set to a document with the wrong length");return Ys(this,(t,i,s,r,o)=>e=e.replace(s,s+(i-t),o),!1),e}mapDesc(e,t=!1){return Js(this,e,t,!0)}invert(e){let t=this.sections.slice(),i=[];for(let s=0,r=0;s<t.length;s+=2){let o=t[s],l=t[s+1];if(l>=0){t[s]=l,t[s+1]=o;let a=s>>1;for(;i.length<a;)i.push(N.empty);i.push(o?e.slice(r,r+o):N.empty)}r+=o}return new n(t,i)}compose(e){return this.empty?e:e.empty?this:Wl(this,e,!0)}map(e,t=!1){return e.empty?this:Js(this,e,t,!0)}iterChanges(e,t=!1){Ys(this,e,t)}get desc(){return rt.
Line truncated
|
||||
`}get readOnly(){return this.facet(Gl)}phrase(e,...t){for(let i of this.facet(n.phrases))if(Object.prototype.hasOwnProperty.call(i,e)){e=i[e];break}return t.length&&(e=e.replace(/\$(\$|\d*)/g,(i,s)=>{if(s=="$")return"$";let r=+(s||1);return!r||r>t.length?i:t[r-1]})),e}languageDataAt(e,t,i=-1){let s=[];for(let r of this.facet(ql))for(let o of r(this,t,i))Object.prototype.hasOwnProperty.call(o,e)&&s.push(o[e]);return s}charCategorizer(e){return mu(this.languageDataAt("wordChars",e).join(""))}wordAt(e){let{text:t,from:i,length:s}=this.doc.lineAt(e),r=this.charCategorizer(e),o=e-i,l=e-i;for(;o>0;){let a=Q(t,o,!1);if(r(t.slice(a,o))!=q.Word)break;o=a}for(;l<s;){let a=Q(t,l);if(r(t.slice(l,a))!=q.Word)break;l=a}return o==l?null:b.range(o+i,l+i)}};j.allowMultipleSelections=Qs;j.tabSize=T.define({combine:n=>n.length?n[0]:4});j.lineSeparator=Kl;j.readOnly=Gl;j.phrases=T.define({compare(n,e){let t=Object.keys(n),i=Object.keys(e);return t.length==i.length&&t.every(s=>n[s]==e[s])}});j.languageData=ql;j.changeFilter=$l;j.transactionFilter=jl;j.transactionExtender=Ul;bn.reconfigure=P.define();function fe(n,e,t={}){let i={};for(let s of n)for(let r of Object.keys(s)){let o=s[r],l=i[r];if(l===void 0)i[r]=o;else if(!(l===o||o===void 0))if(Object.hasOwnProperty.call(t,r))i[r]=t[r](l,o);else throw new Error("Config merge conflict for field "+r)}for(let s in e)i[s]===void 0&&(i[s]=e[s]);return i}var He=class{eq(e){return this==e}range(e,t=e){return mi.create(e,t,this)}};He.prototype.startSide=He.prototype.endSide=0;He.prototype.point=!1;He.prototype.mapMode=re.TrackDel;var mi=class n{constructor(e,t,i){this.from=e,this.to=t,this.value=i}static create(e,t,i){return new n(e,t,i)}};function nr(n,e){return n.from-e.from||n.value.startSide-e.value.startSide}var sr=class n{constructor(e,t,i,s){this.from=e,this.to=t,this.value=i,this.maxPoint=s}get length(){return this.to[this.to.length-1]}findIndex(e,t,i,s=0){let r=i?this.to:this.from;for(let o=s,l=r.length;;){if(o==l)return o;let a=o+l>>1,f=r[a]-e||(i?this.value[a].endSide:this.value[a].startSide)-t;if(a==o)return f>=0?o:l;f>=0?l=a:o=a+1}}between(e,t,i,s){for(let r=this.findIndex(t,-1e9,!0),o=this.findIndex(i,1e9,!1,r);r<o;r++)if(s(this.from[r]+e,this.to[r]+e,this.value[r])===!1)return!1}map(e,t){let i=[],s=[],r=[],o=-1,l=-1;for(let a=0;a<this.value.length;a++){let f=this.value[a],h=this.from[a]+e,c=this.to[a]+e,u,d;if(h==c){let p=t.mapPos(h,f.startSide,f.mapMode);if(p==null||(u=d=p,f.startSide!=f.endSide&&(d=t.mapPos(h,f.endSide),d<u)))continue}else if(u=t.mapPos(h,f.startSide),d=t.mapPos(c,f.endSide),u>d||u==d&&f.startSide>0&&f.endSide<=0)continue;(d-u||f.endSide-f.startSide)<0||(o<0&&(o=u),f.point&&(l=Math.max(l,d-u)),i.push(f),s.push(u-o),r.push(d-o))}return{mapped:i.length?new n(s,r,i,l):null,pos:o}}},W=class n{constructor(e,t,i,s){this.chunkPos=e,this.chunk=t,this.nextLayer=i,this.maxPoint=s}static create(e,t,i,s){return new n(e,t,i,s)}get length(){let e=this.chunk.length-1;return e<0?0:Math.max(this.chunkEnd(e),this.nextLayer.length)}get size(){if(this.isEmpty)return 0;let e=this.nextLayer.size;for(let t of this.chunk)e+=t.value.length;return e}chunkEnd(e){return this.chunkPos[e]+this.chunk[e].length}update(e){let{add:t=[],sort:i=!1,filterFrom:s=0,filterTo:r=this.length}=e,o=e.filter;if(t.length==0&&!o)return this;if(i&&(t=t.slice().sort(nr)),this.isEmpty)return t.length?n.of(t):this;let l=new vn(this,null,-1).goto(0),a=0,f=[],h=new ke;for(;l.value||a<t.length;)if(a<t.length&&(l.from-t[a].from||l.startSide-t[a].value.startSide)>=0){let c=t[a++];h.addInner(c.from,c.to,c.value)||f.push(c)}else l.rangeIndex==1&&l.chunkIndex<this.chunk.length&&(a==t.length||this.chunkEnd(l.chunkIndex)<t[a].from)&&(!o||s>this.chunkEnd(l.chunkIndex)||r<this.chunkPos[l.chunkIndex])&&h.addChunk(this.chunkPos[l.chunkIndex],this.chunk[l.chunkIndex])?l.nextChunk():((!o||s>l.to||r<l.from||o(l.from,l.to,l.value))&&(h.addInner(l.from,l.to,l.value)||f.push(mi.create(l.from,l.to,l.value))),l.next());return h.finishInner(this.nextLayer.isEmpty&&!f.length?n.empty:this.nextLayer.update({add:f,filter:o,filterFrom:s,filterTo:r}))}map(e){if(e.empty||this.isEmpty)return this;let t=[],i=[],s=-1;for(let o=0;o<this.chunk.length;o++){let l=this.chunkPos[o],a=this.chunk[o],f=e.touchesRange(l,l+a.length);if(f===!1)s=Math.max(s,a.maxPoint),t.push(a),i.push(e.mapPos(l));else if(f===!0){let{mapped:h,pos:c}=a.map(l,e);h&&(s=Math.max(s,h.maxPoint),t.push(h),i.push(c))}}let r=this.nextLayer.map(e);return t.length==0?r:new n(i,t,r||n.empty,s)}between(e,t,i){if(!this.isEmpty){for(let s=0;s<this.chunk.length;s++){let r=this.chunkPos[s],o=this.chunk[s];if(t>=r&&e<=r+o.length&&o.between(r,e-r,t-r,i)===!1)return}this.nextLayer.between(e,t,i)}}iter(e=0){return gi.from([this]).goto(e)}get isEmpty(){return this.nextLayer==this}static iter(e,t=0){return gi.from(e).goto(t)}static compare(e,t,i,s,r=-1){let o=e.filter(c=>c.maxPoint>0||!c.isEmpty&&c.maxPoint>=r),l=t.filter(c=>c.maxPoint>0||!c.isEmpty&&c.maxPoint>=r),a=Fl(o,l,i),f=new At(o
Line truncated
|
||||
`)}static newName(){let e=Xl[Jl]||1;return Xl[Jl]=e+1,"\u037C"+e.toString(36)}static mount(e,t,i){let s=e[ar],r=i&&i.nonce;s?r&&s.setNonce(r):s=new hr(e,r),s.mount(Array.isArray(t)?t:[t],e)}},Ql=new Map,hr=class{constructor(e,t){let i=e.ownerDocument||e,s=i.defaultView;if(!e.head&&e.adoptedStyleSheets&&s.CSSStyleSheet){let r=Ql.get(i);if(r)return e[ar]=r;this.sheet=new s.CSSStyleSheet,Ql.set(i,this)}else this.styleTag=i.createElement("style"),t&&this.styleTag.setAttribute("nonce",t);this.modules=[],e[ar]=this}mount(e,t){let i=this.sheet,s=0,r=0;for(let o=0;o<e.length;o++){let l=e[o],a=this.modules.indexOf(l);if(a<r&&a>-1&&(this.modules.splice(a,1),r--,a=-1),a==-1){if(this.modules.splice(r++,0,l),i)for(let f=0;f<l.rules.length;f++)i.insertRule(l.rules[f],s++)}else{for(;r<a;)s+=this.modules[r++].rules.length;s+=l.rules.length,r++}}if(i)t.adoptedStyleSheets.indexOf(this.sheet)<0&&(t.adoptedStyleSheets=[this.sheet,...t.adoptedStyleSheets]);else{let o="";for(let a=0;a<this.modules.length;a++)o+=this.modules[a].getRules()+`
|
||||
`;this.styleTag.textContent=o;let l=t.head||t;this.styleTag.parentNode!=l&&l.insertBefore(this.styleTag,l.firstChild)}}setNonce(e){this.styleTag&&this.styleTag.getAttribute("nonce")!=e&&this.styleTag.setAttribute("nonce",e)}};var lt={8:"Backspace",9:"Tab",10:"Enter",12:"NumLock",13:"Enter",16:"Shift",17:"Control",18:"Alt",20:"CapsLock",27:"Escape",32:" ",33:"PageUp",34:"PageDown",35:"End",36:"Home",37:"ArrowLeft",38:"ArrowUp",39:"ArrowRight",40:"ArrowDown",44:"PrintScreen",45:"Insert",46:"Delete",59:";",61:"=",91:"Meta",92:"Meta",106:"*",107:"+",108:",",109:"-",110:".",111:"/",144:"NumLock",145:"ScrollLock",160:"Shift",161:"Shift",162:"Control",163:"Control",164:"Alt",165:"Alt",173:"-",186:";",187:"=",188:",",189:"-",190:".",191:"/",192:"`",219:"[",220:"\\",221:"]",222:"'"},Jt={48:")",49:"!",50:"@",51:"#",52:"$",53:"%",54:"^",55:"&",56:"*",57:"(",59:":",61:"+",173:"_",186:":",187:"+",188:"<",189:"_",190:">",191:"?",192:"~",219:"{",220:"|",221:"}",222:'"'},yu=typeof navigator<"u"&&/Mac/.test(navigator.platform),bu=typeof navigator<"u"&&/MSIE \d|Trident\/(?:[7-9]|\d{2,})\..*rv:(\d+)/.exec(navigator.userAgent);for(Z=0;Z<10;Z++)lt[48+Z]=lt[96+Z]=String(Z);var Z;for(Z=1;Z<=24;Z++)lt[Z+111]="F"+Z;var Z;for(Z=65;Z<=90;Z++)lt[Z]=String.fromCharCode(Z+32),Jt[Z]=String.fromCharCode(Z);var Z;for(Sn in lt)Jt.hasOwnProperty(Sn)||(Jt[Sn]=lt[Sn]);var Sn;function Zl(n){var e=yu&&n.metaKey&&n.shiftKey&&!n.ctrlKey&&!n.altKey||bu&&n.shiftKey&&n.key&&n.key.length==1||n.key=="Unidentified",t=!e&&n.key||(n.shiftKey?Jt:lt)[n.keyCode]||n.key||"Unidentified";return t=="Esc"&&(t="Escape"),t=="Del"&&(t="Delete"),t=="Left"&&(t="ArrowLeft"),t=="Up"&&(t="ArrowUp"),t=="Right"&&(t="ArrowRight"),t=="Down"&&(t="ArrowDown"),t}function V(){var n=arguments[0];typeof n=="string"&&(n=document.createElement(n));var e=1,t=arguments[1];if(t&&typeof t=="object"&&t.nodeType==null&&!Array.isArray(t)){for(var i in t)if(Object.prototype.hasOwnProperty.call(t,i)){var s=t[i];typeof s=="string"?n.setAttribute(i,s):s!=null&&(n[i]=s)}e++}for(;e<arguments.length;e++)ea(n,arguments[e]);return n}function ea(n,e){if(typeof e=="string")n.appendChild(document.createTextNode(e));else if(e!=null)if(e.nodeType!=null)n.appendChild(e);else if(Array.isArray(e))for(var t=0;t<e.length;t++)ea(n,e[t]);else throw new RangeError("Unsupported child node: "+e)}var me=typeof navigator<"u"?navigator:{userAgent:"",vendor:"",platform:""},yr=typeof document<"u"?document:{documentElement:{style:{}}},br=/Edge\/(\d+)/.exec(me.userAgent),Ka=/MSIE \d/.test(me.userAgent),xr=/Trident\/(?:[7-9]|\d{2,})\..*rv:(\d+)/.exec(me.userAgent),ts=!!(Ka||xr||br),ta=!ts&&/gecko\/(\d+)/i.test(me.userAgent),fr=!ts&&/Chrome\/(\d+)/.exec(me.userAgent),ia="webkitFontSmoothing"in yr.documentElement.style,wr=!ts&&/Apple Computer/.test(me.vendor),na=wr&&(/Mobile\/\w+/.test(me.userAgent)||me.maxTouchPoints>2),D={mac:na||/Mac/.test(me.platform),windows:/Win/.test(me.platform),linux:/Linux|X11/.test(me.platform),ie:ts,ie_version:Ka?yr.documentMode||6:xr?+xr[1]:br?+br[1]:0,gecko:ta,gecko_version:ta?+(/Firefox\/(\d+)/.exec(me.userAgent)||[0,0])[1]:0,chrome:!!fr,chrome_version:fr?+fr[1]:0,ios:na,android:/Android\b/.test(me.userAgent),webkit:ia,webkit_version:ia?+(/\bAppleWebKit\/(\d+)/.exec(me.userAgent)||[0,0])[1]:0,safari:wr,safari_version:wr?+(/\bVersion\/(\d+(\.\d+)?)/.exec(me.userAgent)||[0,0])[1]:0,tabSize:yr.documentElement.style.tabSize!=null?"tab-size":"-moz-tab-size"};function Bi(n){let e;return n.nodeType==11?e=n.getSelection?n:n.ownerDocument:e=n,e.getSelection()}function vr(n,e){return e?n==e||n.contains(e.nodeType!=1?e.parentNode:e):!1}function Rn(n,e){if(!e.anchorNode)return!1;try{return vr(n,e.anchorNode)}catch{return!1}}function Ei(n){return n.nodeType==3?Et(n,0,n.nodeValue.length).getClientRects():n.nodeType==1?n.getClientRects():[]}function ki(n,e,t,i){return t?sa(n,e,t,i,-1)||sa(n,e,t,i,1):!1}function Bt(n){for(var e=0;;e++)if(n=n.previousSibling,!n)return e}function Wn(n){return n.nodeType==1&&/^(DIV|P|LI|UL|OL|BLOCKQUOTE|DD|DT|H\d|SECTION|PRE)$/.test(n.nodeName)}function sa(n,e,t,i,s){for(;;){if(n==t&&e==i)return!0;if(e==(s<0?0:Qe(n))){if(n.nodeName=="DIV")return!1;let r=n.parentNode;if(!r||r.nodeType!=1)return!1;e=Bt(n)+(s<0?0:1),n=r}else if(n.nodeType==1){if(n=n.childNodes[e+(s<0?-1:0)],n.nodeType==1&&n.contentEditable=="false")return!1;e=s<0?Qe(n):0}else return!1}}function Qe(n){return n.nodeType==3?n.nodeValue.length:n.childNodes.length}function is(n,e){let t=e?n.left:n.right;return{left:t,right:t,top:n.top,bottom:n.bottom}}function xu(n){let e=n.visualViewport;return e?{left:0,right:e.width,top:0,bottom:e.height}:{left:0,right:n.innerWidth,top:0,bottom:n.innerHeight}}function $a(n,e){let t=e.width/n.offsetWidth,i=e.height/n.offsetHeight;return(t>.995&&t<1.005||!isFinite(t)||Math.abs(e.width-n.offsetWidth)<1)&&(t=1),(i>.995&&i<1.005||!isFinite(i)||Math.abs(e.height-n.offsetHeight)<1)&&(i=1),{scaleX:t,scaleY:i}}function wu(n,e,t,i,s,r,o,l){let a=n.ownerDocument,f=a.defaultView||window;for(lLine truncated
|
||||
`,s=n.state.doc.line(s.number+(t?1:-1)),r=n.bidiSpans(s),f=n.visualLineSide(s,!t)}if(a){if(!a(h))return l}else{if(!i)return f;a=i(h)}l=f}}function Zu(n,e,t){let i=n.state.charCategorizer(e),s=i(t);return r=>{let o=i(r);return s==q.Space&&(s=o),s==o}}function ed(n,e,t,i){let s=e.head,r=t?1:-1;if(s==(t?n.state.doc.length:0))return b.cursor(s,e.assoc);let o=e.goalColumn,l,a=n.contentDOM.getBoundingClientRect(),f=n.coordsAtPos(s,e.assoc||-1),h=n.documentTop;if(f)o==null&&(o=f.left-a.left),l=r<0?f.top:f.bottom;else{let d=n.viewState.lineBlockAt(s);o==null&&(o=Math.min(a.right-a.left,n.defaultCharacterWidth*(s-d.from))),l=(r<0?d.top:d.bottom)+h}let c=a.left+o,u=i??n.viewState.heightOracle.textHeight>>1;for(let d=0;;d+=10){let p=l+(u+d)*r,m=kh(n,{x:c,y:p},!1,r);if(p<a.top||p>a.bottom||(r<0?m<s:m>s)){let g=n.docView.coordsForChar(m),y=!g||p<g.top?-1:1;return b.cursor(m,y,void 0,o)}}}function Mi(n,e,t){for(;;){let i=0;for(let s of n)s.between(e-1,e+1,(r,o,l)=>{if(e>r&&e<o){let a=i||t||(e-r<o-e?-1:1);e=a<0?r:o,i=a}});if(!i)return e}}function Ch(n,e){let t=null;for(let i=0;i<e.ranges.length;i++){let s=e.ranges[i],r=null;if(s.empty){let o=Mi(n,s.from,0);o!=s.from&&(r=b.cursor(o,-1))}else{let o=Mi(n,s.from,-1),l=Mi(n,s.to,1);(o!=s.from||l!=s.to)&&(r=b.range(s.from==s.anchor?o:l,s.from==s.head?o:l))}r&&(t||(t=e.ranges.slice()),t[i]=r)}return t?b.create(t,e.mainIndex):e}function ur(n,e,t){let i=Mi(n.state.facet(Vi).map(s=>s(n)),t.from,e.head>t.from?-1:1);return i==t.from?t:b.cursor(i,i<t.from?1:-1)}var xi="\uFFFF",Er=class{constructor(e,t){this.points=e,this.text="",this.lineSeparator=t.facet(j.lineSeparator)}append(e){this.text+=e}lineBreak(){this.text+=xi}readRange(e,t){if(!e)return this;let i=e.parentNode;for(let s=e;;){this.findPointBefore(i,s);let r=this.text.length;this.readNode(s);let o=s.nextSibling;if(o==t)break;let l=G.get(s),a=G.get(o);(l&&a?l.breakAfter:(l?l.breakAfter:Wn(s))||Wn(o)&&(s.nodeName!="BR"||s.cmIgnore)&&this.text.length>r)&&!id(o,t)&&this.lineBreak(),s=o}return this.findPointBefore(i,t),this}readTextNode(e){let t=e.nodeValue;for(let i of this.points)i.node==e&&(i.pos=this.text.length+Math.min(i.offset,t.length));for(let i=0,s=this.lineSeparator?null:/\r\n?|\n/g;;){let r=-1,o=1,l;if(this.lineSeparator?(r=t.indexOf(this.lineSeparator,i),o=this.lineSeparator.length):(l=s.exec(t))&&(r=l.index,o=l[0].length),this.append(t.slice(i,r<0?t.length:r)),r<0)break;if(this.lineBreak(),o>1)for(let a of this.points)a.node==e&&a.pos>this.text.length&&(a.pos-=o-1);i=r+o}}readNode(e){if(e.cmIgnore)return;let t=G.get(e),i=t&&t.overrideDOMText;if(i!=null){this.findPointInside(e,i.length);for(let s=i.iter();!s.next().done;)s.lineBreak?this.lineBreak():this.append(s.value)}else e.nodeType==3?this.readTextNode(e):e.nodeName=="BR"?e.nextSibling&&this.lineBreak():e.nodeType==1&&this.readRange(e.firstChild,null)}findPointBefore(e,t){for(let i of this.points)i.node==e&&e.childNodes[i.offset]==t&&(i.pos=this.text.length)}findPointInside(e,t){for(let i of this.points)(e.nodeType==3?i.node==e:e.contains(i.node))&&(i.pos=this.text.length+(td(e,i.node,i.offset)?t:0))}};function td(n,e,t){for(;;){if(!e||t<Qe(e))return!1;if(e==n)return!0;t=Bt(e)+1,e=e.parentNode}}function id(n,e){let t;for(;!(n==e||!n);n=n.nextSibling){let i=G.get(n);if(!(i?.isWidget||n.cmIgnore))return!1;i&&(t||(t=[])).push(i)}if(t)for(let i of t){let s=i.overrideDOMText;if(s?.length)return!1}return!0}var jn=class{constructor(e,t){this.node=e,this.offset=t,this.pos=-1}},Pr=class{constructor(e,t,i,s){this.typeOver=s,this.bounds=null,this.text="",this.domChanged=t>-1;let{impreciseHead:r,impreciseAnchor:o}=e.docView;if(e.state.readOnly&&t>-1)this.newSel=null;else if(t>-1&&(this.bounds=e.docView.domBoundsAround(t,i,0))){let l=r||o?[]:sd(e),a=new Er(l,e.state);a.readRange(this.bounds.startDOM,this.bounds.endDOM),this.text=a.text,this.newSel=rd(l,this.bounds.from)}else{let l=e.observer.selectionRange,a=r&&r.node==l.focusNode&&r.offset==l.focusOffset||!vr(e.contentDOM,l.focusNode)?e.state.selection.main.head:e.docView.posFromDOM(l.focusNode,l.focusOffset),f=o&&o.node==l.anchorNode&&o.offset==l.anchorOffset||!vr(e.contentDOM,l.anchorNode)?e.state.selection.main.anchor:e.docView.posFromDOM(l.anchorNode,l.anchorOffset),h=e.viewport;if((D.ios||D.chrome)&&e.state.selection.main.empty&&a!=f&&(h.from>0||h.to<e.state.doc.length)){let c=Math.min(a,f),u=Math.max(a,f),d=h.from-c,p=h.to-u;(d==0||d==1||c==0)&&(p==0||p==-1||u==e.state.doc.length)&&(a=0,f=e.state.doc.length)}e.inputState.composing>-1&&e.state.selection.ranges.length>1?this.newSel=e.state.selection.replaceRange(b.range(f,a)):this.newSel=b.single(f,a)}}};function Ah(n,e){let t,{newSel:i}=e,s=n.state.selection.main,r=n.inputState.lastKeyTime>Date.now()-100?n.inputState.lastKeyCode:-1;if(e.bounds){let{from:o,to:l}=e.bounds,a=s.from,f=null;(r===8||D.android&&e.text.length<l-o)&&(a=s.to,f="end");let h=Mh(n.state.doc.sliceString(o,l,xi),e.text,a-o,f);h&&(D.chrome&&r==13&&h.toB==h.from+2&&e.text.slice(h.from,h.toB)==xi+xi&&h.t
Line truncated
|
||||
`&&n.lineWrapping&&(i&&(i=b.single(i.main.anchor-1,i.main.head-1)),t={from:s.from,to:s.to,insert:N.of([" "])}),t)return co(n,t,i,r);if(i&&!i.main.eq(s)){let o=!1,l="select";return n.inputState.lastSelectionTime>Date.now()-50&&(n.inputState.lastSelectionOrigin=="select"&&(o=!0),l=n.inputState.lastSelectionOrigin,l=="select.pointer"&&(i=Ch(n.state.facet(Vi).map(a=>a(n)),i))),n.dispatch({selection:i,scrollIntoView:o,userEvent:l}),!0}else return!1}function co(n,e,t,i=-1){if(D.ios&&n.inputState.flushIOSKey(e))return!0;let s=n.state.selection.main;if(D.android&&(e.to==s.to&&(e.from==s.from||e.from==s.from-1&&n.state.sliceDoc(e.from,s.from)==" ")&&e.insert.length==1&&e.insert.lines==2&&ti(n.contentDOM,"Enter",13)||(e.from==s.from-1&&e.to==s.to&&e.insert.length==0||i==8&&e.insert.length<e.to-e.from&&e.to>s.head)&&ti(n.contentDOM,"Backspace",8)||e.from==s.from&&e.to==s.to+1&&e.insert.length==0&&ti(n.contentDOM,"Delete",46)))return!0;let r=e.insert.toString();n.inputState.composing>=0&&n.inputState.composing++;let o,l=()=>o||(o=nd(n,e,t));return n.state.facet(ch).some(a=>a(n,e.from,e.to,r,l))||n.dispatch(l()),!0}function nd(n,e,t){let i,s=n.state,r=s.selection.main,o=-1;if(e.from==e.to&&e.from<r.from||e.from>r.to){let a=e.from<r.from?-1:1,f=a<0?r.from:r.to,h=Mi(s.facet(Vi).map(c=>c(n)),f,a);e.from==h&&(o=h)}if(o>-1)i={changes:e,selection:b.cursor(e.from+e.insert.length,-1)};else if(e.from>=r.from&&e.to<=r.to&&e.to-e.from>=(r.to-r.from)/3&&(!t||t.main.empty&&t.main.from==e.from+e.insert.length)&&n.inputState.composing<0){let a=r.from<e.from?s.sliceDoc(r.from,e.from):"",f=r.to>e.to?s.sliceDoc(e.to,r.to):"";i=s.replaceSelection(n.state.toText(a+e.insert.sliceString(0,void 0,n.state.lineBreak)+f))}else{let a=s.changes(e),f=t&&t.main.to<=a.newLength?t.main:void 0;if(s.selection.ranges.length>1&&(n.inputState.composing>=0||n.inputState.compositionPendingChange)&&e.to<=r.to+10&&e.to>=r.to-10){let h=n.state.sliceDoc(e.from,e.to),c,u=t&&vh(n,t.main.head);if(u){let p=e.insert.length-(e.to-e.from);c={from:u.from,to:u.to-p}}else c=n.state.doc.lineAt(r.head);let d=r.to-e.to;i=s.changeByRange(p=>{if(p.from==r.from&&p.to==r.to)return{changes:a,range:f||p.map(a)};let m=p.to-d,g=m-h.length;if(n.state.sliceDoc(g,m)!=h||m>=c.from&&g<=c.to)return{range:p};let y=s.changes({from:g,to:m,insert:e.insert}),x=p.to-r.to;return{changes:y,range:f?b.range(Math.max(0,f.anchor+x),Math.max(0,f.head+x)):p.map(y)}})}else i={changes:a,selection:f&&s.selection.replaceRange(f)}}let l="input.type";return(n.composing||n.inputState.compositionPendingChange&&n.inputState.compositionEndedAt>Date.now()-50)&&(n.inputState.compositionPendingChange=!1,l+=".compose",n.inputState.compositionFirstChange&&(l+=".start",n.inputState.compositionFirstChange=!1)),s.update(i,{userEvent:l,scrollIntoView:!0})}function Mh(n,e,t,i){let s=Math.min(n.length,e.length),r=0;for(;r<s&&n.charCodeAt(r)==e.charCodeAt(r);)r++;if(r==s&&n.length==e.length)return null;let o=n.length,l=e.length;for(;o>0&&l>0&&n.charCodeAt(o-1)==e.charCodeAt(l-1);)o--,l--;if(i=="end"){let a=Math.max(0,r-Math.min(o,l));t-=o+a-r}if(o<r&&n.length<e.length){let a=t<=r&&t>=o?r-t:0;r-=a,l=r+(l-o),o=r}else if(l<r){let a=t<=r&&t>=l?r-t:0;r-=a,o=r+(o-l),l=r}return{from:r,toA:o,toB:l}}function sd(n){let e=[];if(n.root.activeElement!=n.contentDOM)return e;let{anchorNode:t,anchorOffset:i,focusNode:s,focusOffset:r}=n.observer.selectionRange;return t&&(e.push(new jn(t,i)),(s!=t||r!=i)&&e.push(new jn(s,r))),e}function rd(n,e){if(n.length==0)return null;let t=n[0].pos,i=n.length==2?n[1].pos:t;return t>-1&&i>-1?b.single(t+e,i+e):null}var Lr=class{setSelectionOrigin(e){this.lastSelectionOrigin=e,this.lastSelectionTime=Date.now()}constructor(e){this.view=e,this.lastKeyCode=0,this.lastKeyTime=0,this.lastTouchTime=0,this.lastFocusTime=0,this.lastScrollTop=0,this.lastScrollLeft=0,this.pendingIOSKey=void 0,this.tabFocusMode=-1,this.lastSelectionOrigin=null,this.lastSelectionTime=0,this.lastContextMenu=0,this.scrollHandlers=[],this.handlers=Object.create(null),this.composing=-1,this.compositionFirstChange=null,this.compositionEndedAt=0,this.compositionPendingKey=!1,this.compositionPendingChange=!1,this.insertingText="",this.insertingTextAt=0,this.mouseSelection=null,this.draggedContent=null,this.handleEvent=this.handleEvent.bind(this),this.notifiedFocused=e.hasFocus,D.safari&&e.contentDOM.addEventListener("input",()=>null),D.gecko&&wd(e.contentDOM.ownerDocument)}handleEvent(e){!ud(this.view,e)||this.ignoreDuringComposition(e)||e.type=="keydown"&&this.keydown(e)||(this.view.updateState!=0?Promise.resolve().then(()=>this.runHandlers(e.type,e)):this.runHandlers(e.type,e))}runHandlers(e,t){let i=this.handlers[e];if(i){for(let s of i.observers)s(this.view,t);for(let s of i.handlers){if(t.defaultPrevented)break;if(s(this.view,t)){t.preventDefault();break}}}}ensureHandlers(e){let t=od(e),i=this.handlers,s=this.view.contentDOM;for(let r in t)if(r!="scroll"){let o=!t[r].handlers.length,l=i[r];l&&o!=!l.handlers.length&&(s.removeEventListen
Line truncated
|
||||
`))};if((D.mac||D.android)&&c.from==o-1&&/^\. ?$/.test(i.text)&&e.contentDOM.getAttribute("autocorrect")=="off"&&(c={from:l,to:a,insert:N.of([i.text.replace("."," ")])}),this.pendingContextChange=c,!e.state.readOnly){let u=this.to-this.from+(c.to-c.from+c.insert.length);co(e,c,b.single(this.toEditorPos(i.selectionStart,u),this.toEditorPos(i.selectionEnd,u)))}this.pendingContextChange&&(this.revertPending(e.state),this.setSelection(e.state)),c.from<c.to&&!c.insert.length&&e.inputState.composing>=0&&!/[\\p{Alphabetic}\\p{Number}_]/.test(t.text.slice(Math.max(0,i.updateRangeStart-1),Math.min(t.text.length,i.updateRangeStart+1)))&&this.handlers.compositionend(i)},this.handlers.characterboundsupdate=i=>{let s=[],r=null;for(let o=this.toEditorPos(i.rangeStart),l=this.toEditorPos(i.rangeEnd);o<l;o++){let a=e.coordsForChar(o);r=a&&new DOMRect(a.left,a.top,a.right-a.left,a.bottom-a.top)||r||new DOMRect,s.push(r)}t.updateCharacterBounds(i.rangeStart,s)},this.handlers.textformatupdate=i=>{let s=[];for(let r of i.getTextFormats()){let o=r.underlineStyle,l=r.underlineThickness;if(!/none/i.test(o)&&!/none/i.test(l)){let a=this.toEditorPos(r.rangeStart),f=this.toEditorPos(r.rangeEnd);if(a<f){let h=`text-decoration: underline ${/^[a-z]/.test(o)?o+" ":o=="Dashed"?"dashed ":o=="Squiggle"?"wavy ":""}${/thin/i.test(l)?1:2}px`;s.push(B.mark({attributes:{style:h}}).range(a,f))}}}e.dispatch({effects:gh.of(B.set(s))})},this.handlers.compositionstart=()=>{e.inputState.composing<0&&(e.inputState.composing=0,e.inputState.compositionFirstChange=!0)},this.handlers.compositionend=()=>{if(e.inputState.composing=-1,e.inputState.compositionFirstChange=null,this.composing){let{drifted:i}=this.composing;this.composing=null,i&&this.reset(e.state)}};for(let i in this.handlers)t.addEventListener(i,this.handlers[i]);this.measureReq={read:i=>{this.editContext.updateControlBounds(i.contentDOM.getBoundingClientRect());let s=Bi(i.root);s&&s.rangeCount&&this.editContext.updateSelectionBounds(s.getRangeAt(0).getBoundingClientRect())}}}applyEdits(e){let t=0,i=!1,s=this.pendingContextChange;return e.changes.iterChanges((r,o,l,a,f)=>{if(i)return;let h=f.length-(o-r);if(s&&o>=s.to)if(s.from==r&&s.to==o&&s.insert.eq(f)){s=this.pendingContextChange=null,t+=h,this.to+=h;return}else s=null,this.revertPending(e.state);if(r+=t,o+=t,o<=this.from)this.from+=h,this.to+=h;else if(r<this.to){if(r<this.from||o>this.to||this.to-this.from+f.length>3e4){i=!0;return}this.editContext.updateText(this.toContextPos(r),this.toContextPos(o),f.toString()),this.to+=h}t+=h}),s&&!i&&this.revertPending(e.state),!i}update(e){let t=this.pendingContextChange,i=e.startState.selection.main;this.composing&&(this.composing.drifted||!e.changes.touchesRange(i.from,i.to)&&e.transactions.some(s=>!s.isUserEvent("input.type")&&s.changes.touchesRange(this.from,this.to)))?(this.composing.drifted=!0,this.composing.editorBase=e.changes.mapPos(this.composing.editorBase)):!this.applyEdits(e)||!this.rangeIsValid(e.state)?(this.pendingContextChange=null,this.reset(e.state)):(e.docChanged||e.selectionSet||t)&&this.setSelection(e.state),(e.geometryChanged||e.docChanged||e.selectionSet)&&e.view.requestMeasure(this.measureReq)}resetRange(e){let{head:t}=e.selection.main;this.from=Math.max(0,t-1e4),this.to=Math.min(e.doc.length,t+1e4)}reset(e){this.resetRange(e),this.editContext.updateText(0,this.editContext.text.length,e.doc.sliceString(this.from,this.to)),this.setSelection(e)}revertPending(e){let t=this.pendingContextChange;this.pendingContextChange=null,this.editContext.updateText(this.toContextPos(t.from),this.toContextPos(t.from+t.insert.length),e.doc.sliceString(t.from,t.to))}setSelection(e){let{main:t}=e.selection,i=this.toContextPos(Math.max(this.from,Math.min(this.to,t.anchor))),s=this.toContextPos(t.head);(this.editContext.selectionStart!=i||this.editContext.selectionEnd!=s)&&this.editContext.updateSelection(i,s)}rangeIsValid(e){let{head:t}=e.selection.main;return!(this.from>0&&t-this.from<500||this.to<e.doc.length&&this.to-t<500||this.to-this.from>1e4*3)}toEditorPos(e,t=this.to-this.from){e=Math.min(e,t);let i=this.composing;return i&&i.drifted?i.editorBase+(e-i.contextBase):e+this.from}toContextPos(e){let t=this.composing;return t&&t.drifted?t.contextBase+(e-t.editorBase):e-this.from}destroy(){for(let e in this.handlers)this.editContext.removeEventListener(e,this.handlers[e])}},O=class n{get state(){return this.viewState.state}get viewport(){return this.viewState.viewport}get visibleRanges(){return this.viewState.visibleRanges}get inView(){return this.viewState.inView}get composing(){return!!this.inputState&&this.inputState.composing>0}get compositionStarted(){return!!this.inputState&&this.inputState.composing>=0}get root(){return this._root}get win(){return this.dom.ownerDocument.defaultView||window}constructor(e={}){var t;this.plugins=[],this.pluginMap=new Map,this.editorAttrs={},this.contentAttrs={},this.bidiCache=[],this.destroyed=!1,this.updateState=2,this.measureScheduled=-1,this.measureRe
Line truncated
|
||||
-\x7F-\x9F\xAD\u061C\u200B\u200E\u200F\u2028\u2029\u202D\u202E\u2066\u2067\u2069\uFEFF\uFFF9-\uFFFC]`,Xr),jd={0:"null",7:"bell",8:"backspace",10:"newline",11:"vertical tab",13:"carriage return",27:"escape",8203:"zero width space",8204:"zero width non-joiner",8205:"zero width joiner",8206:"left-to-right mark",8207:"right-to-left mark",8232:"line separator",8237:"left-to-right override",8238:"right-to-left override",8294:"left-to-right isolate",8295:"right-to-left isolate",8297:"pop directional isolate",8233:"paragraph separator",65279:"zero width no-break space",65532:"object replacement"},pr=null;function Ud(){var n;if(pr==null&&typeof document<"u"&&document.body){let e=document.body.style;pr=((n=e.tabSize)!==null&&n!==void 0?n:e.MozTabSize)!=null}return pr||!1}var Hn=T.define({combine(n){let e=fe(n,{render:null,specialChars:$d,addSpecialChars:null});return(e.replaceTabs=!Ud())&&(e.specialChars=new RegExp(" |"+e.specialChars.source,Xr)),e.addSpecialChars&&(e.specialChars=new RegExp(e.specialChars.source+"|"+e.addSpecialChars.source,Xr)),e}});function po(n={}){return[Hn.of(n),Gd()]}var Ia=null;function Gd(){return Ia||(Ia=X.fromClass(class{constructor(n){this.view=n,this.decorations=B.none,this.decorationCache=Object.create(null),this.decorator=this.makeDecorator(n.state.facet(Hn)),this.decorations=this.decorator.createDeco(n)}makeDecorator(n){return new Jr({regexp:n.specialChars,decoration:(e,t,i)=>{let{doc:s}=t.state,r=oe(e[0],0);if(r==9){let o=s.lineAt(i),l=t.state.tabSize,a=ot(o.text,l,i-o.from);return B.replace({widget:new Zr((l-a%l)*this.view.defaultCharacterWidth/this.view.scaleX)})}return this.decorationCache[r]||(this.decorationCache[r]=B.replace({widget:new Qr(n,r)}))},boundary:n.replaceTabs?void 0:/[^]/})}update(n){let e=n.state.facet(Hn);n.startState.facet(Hn)!=e?(this.decorator=this.makeDecorator(e),this.decorations=this.decorator.createDeco(n.view)):this.decorations=this.decorator.updateDeco(n,this.decorations)}},{decorations:n=>n.decorations}))}var _d="\u2022";function Yd(n){return n>=32?_d:n==10?"\u2424":String.fromCharCode(9216+n)}var Qr=class extends Ae{constructor(e,t){super(),this.options=e,this.code=t}eq(e){return e.code==this.code}toDOM(e){let t=Yd(this.code),i=e.state.phrase("Control character")+" "+(jd[this.code]||"0x"+this.code.toString(16)),s=this.options.render&&this.options.render(this.code,i,t);if(s)return s;let r=document.createElement("span");return r.textContent=t,r.title=i,r.setAttribute("aria-label",i),r.className="cm-specialChar",r}ignoreEvent(){return!1}},Zr=class extends Ae{constructor(e){super(),this.width=e}eq(e){return e.width==this.width}toDOM(){let e=document.createElement("span");return e.textContent=" ",e.className="cm-tab",e.style.width=this.width+"px",e}ignoreEvent(){return!1}};function Uh(){return Xd}var Jd=B.line({class:"cm-activeLine"}),Xd=X.fromClass(class{constructor(n){this.decorations=this.getDeco(n)}update(n){(n.docChanged||n.selectionSet)&&(this.decorations=this.getDeco(n.view))}getDeco(n){let e=-1,t=[];for(let i of n.state.selection.ranges){let s=n.lineBlockAt(i.head);s.from>e&&(t.push(Jd.range(s.from)),e=s.from)}return B.set(t)}},{decorations:n=>n.decorations});var eo=2e3;function Qd(n,e,t){let i=Math.min(e.line,t.line),s=Math.max(e.line,t.line),r=[];if(e.off>eo||t.off>eo||e.col<0||t.col<0){let o=Math.min(e.off,t.off),l=Math.max(e.off,t.off);for(let a=i;a<=s;a++){let f=n.doc.line(a);f.length<=l&&r.push(b.range(f.from+o,f.to+l))}}else{let o=Math.min(e.col,t.col),l=Math.max(e.col,t.col);for(let a=i;a<=s;a++){let f=n.doc.line(a),h=kn(f.text,o,n.tabSize,!0);if(h<0)r.push(b.cursor(f.to));else{let c=kn(f.text,l,n.tabSize);r.push(b.range(f.from+h,f.from+c))}}}return r}function Zd(n,e){let t=n.coordsAtPos(n.viewport.from);return t?Math.round(Math.abs((t.left-e)/n.defaultCharacterWidth)):-1}function Na(n,e){let t=n.posAtCoords({x:e.clientX,y:e.clientY},!1),i=n.state.doc.lineAt(t),s=t-i.from,r=s>eo?-1:s==i.length?Zd(n,e.clientX):ot(i.text,n.state.tabSize,t-i.from);return{line:i.number,col:r,off:s}}function ep(n,e){let t=Na(n,e),i=n.state.selection;return t?{update(s){if(s.docChanged){let r=s.changes.mapPos(s.startState.doc.line(t.line).from),o=s.state.doc.lineAt(r);t={line:o.number,col:t.col,off:Math.min(t.off,o.length)},i=i.map(s.changes)}},get(s,r,o){let l=Na(n,s);if(!l)return i;let a=Qd(n.state,t,l);return a.length?o?b.create(a.concat(i.ranges)):b.create(a):i}}:null}function Gh(n){let e=n?.eventFilter||(t=>t.altKey&&t.button==0);return O.mouseSelectionStyle.of((t,i)=>e(i)?ep(t,i):null)}var tp={Alt:[18,n=>!!n.altKey],Control:[17,n=>!!n.ctrlKey],Shift:[16,n=>!!n.shiftKey],Meta:[91,n=>!!n.metaKey]},ip={style:"cursor: crosshair"};function _h(n={}){let[e,t]=tp[n.key||"Alt"],i=X.fromClass(class{constructor(s){this.view=s,this.isDown=!1}set(s){this.isDown!=s&&(this.isDown=s,this.view.update([]))}},{eventObservers:{keydown(s){this.set(s.keyCode==e||t(s))},keyup(s){(s.keyCode==e||!t(s))&&this.set(!1)},mousemove(s){this.set(t(s))}}});return[i,O.contentAttributes.of(s
Line truncated
|
||||
`:i=="r"?"\r":i=="t"?" ":"\\")}eq(e){return this.search==e.search&&this.replace==e.replace&&this.caseSensitive==e.caseSensitive&&this.regexp==e.regexp&&this.wholeWord==e.wholeWord}create(){return this.regexp?new sl(this):new nl(this)}getCursor(e,t=0,i){let s=e.doc?e:j.create({doc:e});return i==null&&(i=s.doc.length),this.regexp?hi(this,s,t,i):ai(this,s,t,i)}},Bs=class{constructor(e){this.spec=e}};function ai(n,e,t,i){return new kt(e.doc,n.unquoted,t,i,n.caseSensitive?void 0:s=>s.toLowerCase(),n.wholeWord?Ig(e.doc,e.charCategorizer(e.selection.main.head)):void 0)}function Ig(n,e){return(t,i,s,r)=>((r>t||r+s.length<i)&&(r=Math.max(0,t-2),s=n.sliceString(r,Math.min(n.length,i+2))),(e(Es(s,t-r))!=q.Word||e(Ps(s,t-r))!=q.Word)&&(e(Ps(s,i-r))!=q.Word||e(Es(s,i-r))!=q.Word))}var nl=class extends Bs{constructor(e){super(e)}nextMatch(e,t,i){let s=ai(this.spec,e,i,e.doc.length).nextOverlapping();if(s.done){let r=Math.min(e.doc.length,t+this.spec.unquoted.length);s=ai(this.spec,e,0,r).nextOverlapping()}return s.done||s.value.from==t&&s.value.to==i?null:s.value}prevMatchInRange(e,t,i){for(let s=i;;){let r=Math.max(t,s-1e4-this.spec.unquoted.length),o=ai(this.spec,e,r,s),l=null;for(;!o.nextOverlapping().done;)l=o.value;if(l)return l;if(r==t)return null;s-=1e4}}prevMatch(e,t,i){let s=this.prevMatchInRange(e,0,t);return s||(s=this.prevMatchInRange(e,Math.max(0,i-this.spec.unquoted.length),e.doc.length)),s&&(s.from!=t||s.to!=i)?s:null}getReplacement(e){return this.spec.unquote(this.spec.replace)}matchAll(e,t){let i=ai(this.spec,e,0,e.doc.length),s=[];for(;!i.next().done;){if(s.length>=t)return null;s.push(i.value)}return s}highlight(e,t,i,s){let r=ai(this.spec,e,Math.max(0,t-this.spec.unquoted.length),Math.min(i+this.spec.unquoted.length,e.doc.length));for(;!r.next().done;)s(r.value.from,r.value.to)}};function hi(n,e,t,i){return new As(e.doc,n.search,{ignoreCase:!n.caseSensitive,test:n.wholeWord?Ng(e.charCategorizer(e.selection.main.head)):void 0},t,i)}function Es(n,e){return n.slice(Q(n,e,!1),e)}function Ps(n,e){return n.slice(e,Q(n,e))}function Ng(n){return(e,t,i)=>!i[0].length||(n(Es(i.input,i.index))!=q.Word||n(Ps(i.input,i.index))!=q.Word)&&(n(Ps(i.input,i.index+i[0].length))!=q.Word||n(Es(i.input,i.index+i[0].length))!=q.Word)}var sl=class extends Bs{nextMatch(e,t,i){let s=hi(this.spec,e,i,e.doc.length).next();return s.done&&(s=hi(this.spec,e,0,t).next()),s.done?null:s.value}prevMatchInRange(e,t,i){for(let s=1;;s++){let r=Math.max(t,i-s*1e4),o=hi(this.spec,e,r,i),l=null;for(;!o.next().done;)l=o.value;if(l&&(r==t||l.from>r+10))return l;if(r==t)return null}}prevMatch(e,t,i){return this.prevMatchInRange(e,0,t)||this.prevMatchInRange(e,i,e.doc.length)}getReplacement(e){return this.spec.unquote(this.spec.replace).replace(/\$([$&]|\d+)/g,(t,i)=>{if(i=="&")return e.match[0];if(i=="$")return"$";for(let s=i.length;s>0;s--){let r=+i.slice(0,s);if(r>0&&r<e.match.length)return e.match[r]+i.slice(s)}return t})}matchAll(e,t){let i=hi(this.spec,e,0,e.doc.length),s=[];for(;!i.next().done;){if(s.length>=t)return null;s.push(i.value)}return s}highlight(e,t,i,s){let r=hi(this.spec,e,Math.max(0,t-250),Math.min(i+250,e.doc.length));for(;!r.next().done;)s(r.value.from,r.value.to)}},sn=P.define(),al=P.define(),vt=J.define({create(n){return new nn(rl(n).create(),null)},update(n,e){for(let t of e.effects)t.is(sn)?n=new nn(t.value.create(),n.panel):t.is(al)&&(n=new nn(n.query,t.value?hl:null));return n},provide:n=>Lt.from(n,e=>e.panel)});var nn=class{constructor(e,t){this.query=e,this.panel=t}},Fg=B.mark({class:"cm-searchMatch"}),Hg=B.mark({class:"cm-searchMatch cm-searchMatch-selected"}),Vg=X.fromClass(class{constructor(n){this.view=n,this.decorations=this.highlight(n.state.field(vt))}update(n){let e=n.state.field(vt);(e!=n.startState.field(vt)||n.docChanged||n.selectionSet||n.viewportChanged)&&(this.decorations=this.highlight(e))}highlight({query:n,panel:e}){if(!e||!n.spec.valid)return B.none;let{view:t}=this,i=new ke;for(let s=0,r=t.visibleRanges,o=r.length;s<o;s++){let{from:l,to:a}=r[s];for(;s<o-1&&a>r[s+1].from-500;)a=r[++s].to;n.highlight(t.state,l,a,(f,h)=>{let c=t.state.selection.ranges.some(u=>u.from==f&&u.to==h);i.add(f,h,c?Hg:Fg)})}return i.finish()}},{decorations:n=>n.decorations});function rn(n){return e=>{let t=e.state.field(vt,!1);return t&&t.query.spec.valid?n(e,t):Dc(e)}}var Ls=rn((n,{query:e})=>{let{to:t}=n.state.selection.main,i=e.nextMatch(n.state,t,t);if(!i)return!1;let s=b.single(i.from,i.to),r=n.state.facet(fi);return n.dispatch({selection:s,effects:[fl(n,i),r.scrollToMatch(s.main,n)],userEvent:"select.search"}),Tc(n),!0}),Rs=rn((n,{query:e})=>{let{state:t}=n,{from:i}=t.selection.main,s=e.prevMatch(t,i,i);if(!s)return!1;let r=b.single(s.from,s.to),o=n.state.facet(fi);return n.dispatch({selection:r,effects:[fl(n,s),o.scrollToMatch(r.main,n)],userEvent:"select.search"}),Tc(n),!0}),Wg=rn((n,{query:e})=>{let t=e.matchAll(n.state,1e3);return!t||!t.length?!1:(n.dispatch({selection:b.create(t.map(i=>b.range(i.from,i.to))),use
Line truncated
|
||||
//# sourceMappingURL=codemirror.bundle.mjs.map
|
||||
@@ -0,0 +1,143 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>Python Editor</title>
|
||||
<link rel="icon" href="data:,">
|
||||
<style>
|
||||
* { box-sizing: border-box; }
|
||||
body {
|
||||
margin: 0;
|
||||
min-height: 100vh;
|
||||
display: grid;
|
||||
place-items: center;
|
||||
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;
|
||||
background: linear-gradient(135deg, #0f172a, #1e293b);
|
||||
color: #e2e8f0;
|
||||
}
|
||||
.home-card {
|
||||
width: min(560px, 92vw);
|
||||
background: rgba(15, 23, 42, 0.78);
|
||||
border: 1px solid rgba(148, 163, 184, 0.25);
|
||||
border-radius: 14px;
|
||||
padding: 2rem;
|
||||
box-shadow: 0 20px 45px rgba(0, 0, 0, 0.35);
|
||||
}
|
||||
h1 { margin: 0 0 0.75rem 0; font-size: 1.8rem; color: #f8fafc; }
|
||||
p { margin: 0 0 1rem 0; color: #cbd5e1; line-height: 1.5; }
|
||||
.btn {
|
||||
display: inline-block;
|
||||
text-decoration: none;
|
||||
border-radius: 8px;
|
||||
padding: 0.65rem 1rem;
|
||||
font-weight: 600;
|
||||
border: 1px solid transparent;
|
||||
cursor: pointer;
|
||||
font-size: 1rem;
|
||||
}
|
||||
.btn-primary { background: #3b82f6; color: #ffffff; }
|
||||
.btn-ghost { background: transparent; border-color: #64748b; color: #e2e8f0; }
|
||||
label { display: block; font-size: 0.85rem; color: #94a3b8; margin-bottom: 0.35rem; }
|
||||
input[type="password"] {
|
||||
width: 100%;
|
||||
padding: 0.5rem 0.65rem;
|
||||
border-radius: 8px;
|
||||
border: 1px solid #64748b;
|
||||
background: #0f172a;
|
||||
color: #e2e8f0;
|
||||
margin-bottom: 0.75rem;
|
||||
}
|
||||
.note { font-size: 0.8rem; color: #94a3b8; margin-top: 1rem; }
|
||||
.nav { display: flex; flex-wrap: wrap; gap: 0.5rem; margin-bottom: 1rem; align-items: center; }
|
||||
.nav span { color: #94a3b8; font-size: 0.9rem; }
|
||||
.hidden { display: none !important; }
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<main class="home-card">
|
||||
<h1>Python Editor</h1>
|
||||
<div id="auth-nav" class="nav">
|
||||
<span id="auth-greeting" class="hidden"></span>
|
||||
<a class="btn btn-ghost hidden" id="link-login" href="/login">Sign in</a>
|
||||
<a class="btn btn-ghost hidden" id="link-register" href="/register">Register</a>
|
||||
<button type="button" class="btn btn-ghost hidden" id="btn-logout">Sign out</button>
|
||||
</div>
|
||||
<p>Edit and store files on the server. Python runs in your browser with <a href="https://pyodide.org/" style="color:#93c5fd">Pyodide</a>.</p>
|
||||
<div id="optional-api-key">
|
||||
<p>If you use <code style="color:#fcd34d">EDITOR_API_KEY</code> (without user login), store it here for API calls from this browser tab:</p>
|
||||
<label for="api-key">API key (optional)</label>
|
||||
<input id="api-key" type="password" autocomplete="off" placeholder="Leave blank if not used" />
|
||||
<p class="note">The key is kept in <code>sessionStorage</code>. You can also use <code>?api_key=…</code> on the editor URL.</p>
|
||||
</div>
|
||||
<a class="btn btn-primary" href="/editor" id="open-editor">Open Editor</a>
|
||||
</main>
|
||||
<script>
|
||||
const storageKey = 'python-editor.api_key';
|
||||
const input = document.getElementById('api-key');
|
||||
const openLink = document.getElementById('open-editor');
|
||||
|
||||
async function refreshAuthNav() {
|
||||
const st = await fetch('/api/auth/status');
|
||||
const status = await st.json();
|
||||
const loginEl = document.getElementById('link-login');
|
||||
const regEl = document.getElementById('link-register');
|
||||
const outEl = document.getElementById('btn-logout');
|
||||
const greet = document.getElementById('auth-greeting');
|
||||
const optionalKey = document.getElementById('optional-api-key');
|
||||
if (!status.auth_enabled) {
|
||||
loginEl.classList.add('hidden');
|
||||
regEl.classList.add('hidden');
|
||||
outEl.classList.add('hidden');
|
||||
greet.classList.add('hidden');
|
||||
return;
|
||||
}
|
||||
loginEl.classList.remove('hidden');
|
||||
if (status.register_open) {
|
||||
regEl.classList.remove('hidden');
|
||||
}
|
||||
const me = await fetch('/api/auth/me', { credentials: 'include' });
|
||||
if (me.ok) {
|
||||
const j = await me.json();
|
||||
greet.textContent = `Signed in as ${j.user.username}`;
|
||||
greet.classList.remove('hidden');
|
||||
loginEl.classList.add('hidden');
|
||||
regEl.classList.add('hidden');
|
||||
outEl.classList.remove('hidden');
|
||||
if (optionalKey) optionalKey.classList.add('hidden');
|
||||
} else {
|
||||
outEl.classList.add('hidden');
|
||||
greet.classList.add('hidden');
|
||||
}
|
||||
}
|
||||
|
||||
document.getElementById('btn-logout').addEventListener('click', async () => {
|
||||
await fetch('/api/auth/logout', { method: 'POST', credentials: 'include' });
|
||||
window.location.reload();
|
||||
});
|
||||
|
||||
try {
|
||||
const params = new URLSearchParams(window.location.search);
|
||||
const fromQuery = params.get('api_key');
|
||||
if (fromQuery) {
|
||||
sessionStorage.setItem(storageKey, fromQuery);
|
||||
}
|
||||
const existing = sessionStorage.getItem(storageKey);
|
||||
if (existing) {
|
||||
input.value = existing;
|
||||
}
|
||||
} catch (_e) {}
|
||||
openLink.addEventListener('click', () => {
|
||||
try {
|
||||
const v = input.value.trim();
|
||||
if (v) {
|
||||
sessionStorage.setItem(storageKey, v);
|
||||
} else {
|
||||
sessionStorage.removeItem(storageKey);
|
||||
}
|
||||
} catch (_e) {}
|
||||
});
|
||||
refreshAuthNav();
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,72 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>Python Editor</title>
|
||||
<link rel="icon" href="data:,">
|
||||
<link rel="stylesheet" href="/static/styles.css?v=6">
|
||||
</head>
|
||||
<body>
|
||||
<div class="container">
|
||||
<div class="sidebar">
|
||||
<div class="sidebar-header">
|
||||
<h3>Files</h3>
|
||||
<div class="sidebar-actions">
|
||||
<button id="new-file-btn" title="New File">📄</button>
|
||||
<button id="new-folder-btn" title="New Folder">📁+</button>
|
||||
<button id="delete-selected-btn" title="Delete Selected">🗑️</button>
|
||||
<button id="refresh-btn" title="Refresh">🔄</button>
|
||||
</div>
|
||||
</div>
|
||||
<div class="file-tree" id="file-tree">
|
||||
<div class="loading">Loading files...</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="main-content">
|
||||
<div class="editor-header">
|
||||
<div class="file-info">
|
||||
<span id="save-status" class="save-status"></span>
|
||||
<span class="runtime-hint" title="Python runs locally in your browser via Pyodide; completions use Jedi in the same runtime.">Browser · Pyodide</span>
|
||||
</div>
|
||||
<div class="mode-toggle">
|
||||
<a id="home-btn" class="mode-btn active" href="/">Home</a>
|
||||
</div>
|
||||
<div class="editor-actions">
|
||||
<button id="run-btn" disabled>Run Python</button>
|
||||
<button id="stop-btn" disabled>Stop</button>
|
||||
<select id="run-file-select" title="Script to run">
|
||||
<option value="">Run active file</option>
|
||||
</select>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div id="tabs" class="tabs"></div>
|
||||
|
||||
<div class="editor-container">
|
||||
<div id="editor"></div>
|
||||
<div id="completion-dropdown" class="completion-dropdown"></div>
|
||||
</div>
|
||||
|
||||
<div class="console-container">
|
||||
<div class="console-header">Console Output</div>
|
||||
<pre id="console-output" class="console-output"></pre>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div id="new-file-modal" class="modal">
|
||||
<div class="modal-content">
|
||||
<h3>Create New File</h3>
|
||||
<input type="text" id="new-filename" placeholder="Enter filename (e.g., example.txt)" />
|
||||
<div class="modal-actions">
|
||||
<button id="create-file-btn">Create</button>
|
||||
<button id="cancel-create-btn">Cancel</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<script type="module" src="/static/script.js?v=10"></script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,120 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>Sign in — Python Editor</title>
|
||||
<link rel="icon" href="data:,">
|
||||
<style>
|
||||
* { box-sizing: border-box; }
|
||||
body {
|
||||
margin: 0;
|
||||
min-height: 100vh;
|
||||
display: grid;
|
||||
place-items: center;
|
||||
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;
|
||||
background: linear-gradient(135deg, #0f172a, #1e293b);
|
||||
color: #e2e8f0;
|
||||
}
|
||||
.card {
|
||||
width: min(400px, 92vw);
|
||||
background: rgba(15, 23, 42, 0.85);
|
||||
border: 1px solid rgba(148, 163, 184, 0.25);
|
||||
border-radius: 14px;
|
||||
padding: 2rem;
|
||||
}
|
||||
h1 { margin: 0 0 1rem 0; font-size: 1.4rem; }
|
||||
label { display: block; font-size: 0.85rem; color: #94a3b8; margin-bottom: 0.35rem; }
|
||||
input {
|
||||
width: 100%;
|
||||
padding: 0.55rem 0.65rem;
|
||||
border-radius: 8px;
|
||||
border: 1px solid #64748b;
|
||||
background: #0f172a;
|
||||
color: #e2e8f0;
|
||||
margin-bottom: 1rem;
|
||||
}
|
||||
button {
|
||||
width: 100%;
|
||||
padding: 0.65rem;
|
||||
border: none;
|
||||
border-radius: 8px;
|
||||
background: #3b82f6;
|
||||
color: #fff;
|
||||
font-weight: 600;
|
||||
cursor: pointer;
|
||||
margin-bottom: 0.75rem;
|
||||
}
|
||||
button:disabled { opacity: 0.6; cursor: not-allowed; }
|
||||
.err { color: #fca5a5; font-size: 0.9rem; margin-bottom: 0.75rem; min-height: 1.2em; }
|
||||
a { color: #93c5fd; }
|
||||
.links { font-size: 0.9rem; margin-top: 1rem; }
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<main class="card">
|
||||
<h1>Sign in</h1>
|
||||
<div id="err" class="err"></div>
|
||||
<form id="form">
|
||||
<label for="username">Username</label>
|
||||
<input id="username" name="username" autocomplete="username" required />
|
||||
<label for="password">Password</label>
|
||||
<input id="password" type="password" name="password" autocomplete="current-password" required />
|
||||
<button type="submit" id="submit">Sign in</button>
|
||||
</form>
|
||||
<div class="links">
|
||||
<a href="/">Home</a>
|
||||
· <a id="register-link" href="/register">Create account</a>
|
||||
</div>
|
||||
</main>
|
||||
<script>
|
||||
const params = new URLSearchParams(window.location.search);
|
||||
const next = params.get("next") || "/editor";
|
||||
|
||||
(async function checkStatus() {
|
||||
try {
|
||||
const r = await fetch("/api/auth/status");
|
||||
const s = await r.json();
|
||||
if (!s.auth_enabled) {
|
||||
document.getElementById("err").textContent = "Sign-in is disabled (AUTH_ENABLED is not set).";
|
||||
document.getElementById("form").style.display = "none";
|
||||
}
|
||||
if (!s.register_open) {
|
||||
const link = document.getElementById("register-link");
|
||||
link.style.display = "none";
|
||||
}
|
||||
} catch (_e) {}
|
||||
})();
|
||||
|
||||
document.getElementById("form").addEventListener("submit", async (e) => {
|
||||
e.preventDefault();
|
||||
const err = document.getElementById("err");
|
||||
const btn = document.getElementById("submit");
|
||||
err.textContent = "";
|
||||
btn.disabled = true;
|
||||
try {
|
||||
const body = {
|
||||
username: document.getElementById("username").value.trim(),
|
||||
password: document.getElementById("password").value,
|
||||
};
|
||||
const res = await fetch("/api/auth/login", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
credentials: "include",
|
||||
body: JSON.stringify(body),
|
||||
});
|
||||
if (!res.ok) {
|
||||
const j = await res.json().catch(() => ({}));
|
||||
err.textContent = j.detail || res.statusText || "Login failed";
|
||||
return;
|
||||
}
|
||||
window.location.href = next.startsWith("/") ? next : "/editor";
|
||||
} catch (ex) {
|
||||
err.textContent = String(ex.message || ex);
|
||||
} finally {
|
||||
btn.disabled = false;
|
||||
}
|
||||
});
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,122 @@
|
||||
/* global importScripts, loadPyodide, self */
|
||||
importScripts('https://cdn.jsdelivr.net/pyodide/v0.26.4/full/pyodide.js');
|
||||
|
||||
const PYODIDE_INDEX_URL = 'https://cdn.jsdelivr.net/pyodide/v0.26.4/full/';
|
||||
|
||||
let pyodide = null;
|
||||
let loadingPromise = null;
|
||||
|
||||
async function ensurePyodide() {
|
||||
if (pyodide) {
|
||||
return pyodide;
|
||||
}
|
||||
if (!loadingPromise) {
|
||||
loadingPromise = (async () => {
|
||||
const p = await loadPyodide({ indexURL: PYODIDE_INDEX_URL });
|
||||
p.setStdout({
|
||||
batched: (txt) => self.postMessage({ type: 'io', stream: 'stdout', text: txt }),
|
||||
});
|
||||
p.setStderr({
|
||||
batched: (txt) => self.postMessage({ type: 'io', stream: 'stderr', text: txt }),
|
||||
});
|
||||
await p.loadPackage('micropip');
|
||||
await p.runPythonAsync(`
|
||||
import micropip
|
||||
await micropip.install("jedi")
|
||||
`);
|
||||
return p;
|
||||
})();
|
||||
}
|
||||
pyodide = await loadingPromise;
|
||||
return pyodide;
|
||||
}
|
||||
|
||||
self.onmessage = async (event) => {
|
||||
const { id, type, payload } = event.data || {};
|
||||
try {
|
||||
if (type === 'init') {
|
||||
await ensurePyodide();
|
||||
self.postMessage({ id, type: 'init', ok: true });
|
||||
return;
|
||||
}
|
||||
|
||||
const p = await ensurePyodide();
|
||||
|
||||
if (type === 'complete') {
|
||||
const rel = String(payload.path || 'scratch.py').replace(/^\/+/, '');
|
||||
const vpath = `/workspace/${rel}`;
|
||||
p.globals.set('__cm_code', String(payload.content ?? ''));
|
||||
p.globals.set('__cm_path', vpath);
|
||||
p.globals.set('__cm_line', Number(payload.line) || 1);
|
||||
p.globals.set('__cm_col', Number(payload.column) || 0);
|
||||
p.globals.set('__cm_max', Math.min(100, Math.max(1, Number(payload.max_results) || 20)));
|
||||
p.globals.set('__cm_extra_json', JSON.stringify(payload.extra_files || {}));
|
||||
const raw = p.runPython(`
|
||||
import json, os
|
||||
import jedi
|
||||
|
||||
extra = json.loads(__cm_extra_json)
|
||||
os.makedirs("/workspace", exist_ok=True)
|
||||
for rel_path, body in extra.items():
|
||||
rel_path = str(rel_path).lstrip("/")
|
||||
full = os.path.join("/workspace", rel_path)
|
||||
os.makedirs(os.path.dirname(full), exist_ok=True)
|
||||
with open(full, "w", encoding="utf-8") as fh:
|
||||
fh.write(str(body))
|
||||
os.makedirs(os.path.dirname(__cm_path), exist_ok=True)
|
||||
with open(__cm_path, "w", encoding="utf-8") as fh:
|
||||
fh.write(__cm_code)
|
||||
proj = jedi.Project("/workspace")
|
||||
s = jedi.Script(code=__cm_code, path=__cm_path, project=proj)
|
||||
items = s.complete(line=__cm_line, column=__cm_col)
|
||||
out = [{"name": i.name, "type": i.type, "complete": i.complete} for i in items[:__cm_max]]
|
||||
json.dumps(out)
|
||||
`);
|
||||
const completions = JSON.parse(String(raw));
|
||||
self.postMessage({ id, type: 'complete', ok: true, completions });
|
||||
return;
|
||||
}
|
||||
|
||||
if (type === 'run') {
|
||||
const files = payload.files && typeof payload.files === 'object' ? payload.files : {};
|
||||
const mainRel = String(payload.mainPath || '').replace(/^\/+/, '');
|
||||
const argsList = Array.isArray(payload.args) ? payload.args.map(String) : [];
|
||||
p.globals.set('__run_files_json', JSON.stringify(files));
|
||||
p.globals.set('__run_main', `/workspace/${mainRel}`);
|
||||
p.globals.set('__run_args', p.toPy(argsList));
|
||||
await p.runPythonAsync(`
|
||||
import json, os, shutil, sys, runpy
|
||||
|
||||
files = json.loads(__run_files_json)
|
||||
shutil.rmtree('/workspace', ignore_errors=True)
|
||||
os.makedirs('/workspace', exist_ok=True)
|
||||
for rel, body in files.items():
|
||||
rel = str(rel).lstrip("/")
|
||||
full = os.path.join("/workspace", rel)
|
||||
os.makedirs(os.path.dirname(full), exist_ok=True)
|
||||
with open(full, "w", encoding="utf-8") as fh:
|
||||
fh.write(str(body))
|
||||
|
||||
for entry in ("/workspace/lib", "/workspace"):
|
||||
if entry not in sys.path:
|
||||
sys.path.insert(0, entry)
|
||||
|
||||
os.chdir("/workspace")
|
||||
main = __run_main
|
||||
sys.argv = [main] + list(__run_args)
|
||||
runpy.run_path(main, run_name="__main__")
|
||||
`);
|
||||
self.postMessage({ id, type: 'run', ok: true });
|
||||
return;
|
||||
}
|
||||
|
||||
self.postMessage({ id, type, ok: false, error: `Unknown message type: ${type}` });
|
||||
} catch (err) {
|
||||
self.postMessage({
|
||||
id,
|
||||
type,
|
||||
ok: false,
|
||||
error: err && err.message ? String(err.message) : String(err),
|
||||
});
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,113 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>Register — Python Editor</title>
|
||||
<link rel="icon" href="data:,">
|
||||
<style>
|
||||
* { box-sizing: border-box; }
|
||||
body {
|
||||
margin: 0;
|
||||
min-height: 100vh;
|
||||
display: grid;
|
||||
place-items: center;
|
||||
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;
|
||||
background: linear-gradient(135deg, #0f172a, #1e293b);
|
||||
color: #e2e8f0;
|
||||
}
|
||||
.card {
|
||||
width: min(400px, 92vw);
|
||||
background: rgba(15, 23, 42, 0.85);
|
||||
border: 1px solid rgba(148, 163, 184, 0.25);
|
||||
border-radius: 14px;
|
||||
padding: 2rem;
|
||||
}
|
||||
h1 { margin: 0 0 1rem 0; font-size: 1.4rem; }
|
||||
label { display: block; font-size: 0.85rem; color: #94a3b8; margin-bottom: 0.35rem; }
|
||||
input {
|
||||
width: 100%;
|
||||
padding: 0.55rem 0.65rem;
|
||||
border-radius: 8px;
|
||||
border: 1px solid #64748b;
|
||||
background: #0f172a;
|
||||
color: #e2e8f0;
|
||||
margin-bottom: 1rem;
|
||||
}
|
||||
button {
|
||||
width: 100%;
|
||||
padding: 0.65rem;
|
||||
border: none;
|
||||
border-radius: 8px;
|
||||
background: #3b82f6;
|
||||
color: #fff;
|
||||
font-weight: 600;
|
||||
cursor: pointer;
|
||||
margin-bottom: 0.75rem;
|
||||
}
|
||||
button:disabled { opacity: 0.6; cursor: not-allowed; }
|
||||
.err { color: #fca5a5; font-size: 0.9rem; margin-bottom: 0.75rem; min-height: 1.2em; }
|
||||
.hint { font-size: 0.8rem; color: #94a3b8; margin-bottom: 1rem; }
|
||||
a { color: #93c5fd; }
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<main class="card">
|
||||
<h1>Create account</h1>
|
||||
<p class="hint">Username: letters, numbers, underscore (3–64). Password: at least 8 characters.</p>
|
||||
<div id="err" class="err"></div>
|
||||
<form id="form">
|
||||
<label for="username">Username</label>
|
||||
<input id="username" name="username" autocomplete="username" required />
|
||||
<label for="password">Password</label>
|
||||
<input id="password" type="password" name="password" autocomplete="new-password" required />
|
||||
<button type="submit" id="submit">Register</button>
|
||||
</form>
|
||||
<p><a href="/login">Sign in</a> · <a href="/">Home</a></p>
|
||||
</main>
|
||||
<script>
|
||||
(async function checkStatus() {
|
||||
try {
|
||||
const r = await fetch("/api/auth/status");
|
||||
const s = await r.json();
|
||||
if (!s.auth_enabled) {
|
||||
document.getElementById("err").textContent = "Registration is disabled (AUTH_ENABLED is not set).";
|
||||
document.getElementById("form").style.display = "none";
|
||||
} else if (!s.register_open) {
|
||||
document.getElementById("err").textContent = "Public registration is closed. Ask an administrator.";
|
||||
document.getElementById("form").style.display = "none";
|
||||
}
|
||||
} catch (_e) {}
|
||||
})();
|
||||
|
||||
document.getElementById("form").addEventListener("submit", async (e) => {
|
||||
e.preventDefault();
|
||||
const err = document.getElementById("err");
|
||||
const btn = document.getElementById("submit");
|
||||
err.textContent = "";
|
||||
btn.disabled = true;
|
||||
try {
|
||||
const body = {
|
||||
username: document.getElementById("username").value.trim(),
|
||||
password: document.getElementById("password").value,
|
||||
};
|
||||
const res = await fetch("/api/auth/register", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify(body),
|
||||
});
|
||||
if (!res.ok) {
|
||||
const j = await res.json().catch(() => ({}));
|
||||
err.textContent = typeof j.detail === "string" ? j.detail : JSON.stringify(j.detail) || res.statusText;
|
||||
return;
|
||||
}
|
||||
window.location.href = "/login?next=/editor";
|
||||
} catch (ex) {
|
||||
err.textContent = String(ex.message || ex);
|
||||
} finally {
|
||||
btn.disabled = false;
|
||||
}
|
||||
});
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,475 @@
|
||||
* {
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
box-sizing: border-box;
|
||||
}
|
||||
|
||||
body {
|
||||
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
|
||||
background-color: #f5f5f5;
|
||||
height: 100vh;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.container {
|
||||
display: flex;
|
||||
height: 100vh;
|
||||
}
|
||||
|
||||
/* Sidebar */
|
||||
.sidebar {
|
||||
width: 300px;
|
||||
background-color: #2d3748;
|
||||
color: white;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
}
|
||||
|
||||
.sidebar-header {
|
||||
padding: 1rem;
|
||||
border-bottom: 1px solid #4a5568;
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
}
|
||||
|
||||
.sidebar-header h3 {
|
||||
font-size: 1.1rem;
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.sidebar-actions {
|
||||
display: flex;
|
||||
gap: 0.5rem;
|
||||
}
|
||||
|
||||
.sidebar-actions button {
|
||||
background: none;
|
||||
border: none;
|
||||
color: white;
|
||||
cursor: pointer;
|
||||
padding: 0.25rem;
|
||||
border-radius: 4px;
|
||||
font-size: 1rem;
|
||||
transition: background-color 0.2s;
|
||||
}
|
||||
|
||||
.sidebar-actions button:hover {
|
||||
background-color: #4a5568;
|
||||
}
|
||||
|
||||
.file-tree {
|
||||
flex: 1;
|
||||
overflow-y: auto;
|
||||
padding: 0.5rem;
|
||||
}
|
||||
|
||||
.file-item {
|
||||
padding: 0.5rem;
|
||||
cursor: pointer;
|
||||
border-radius: 4px;
|
||||
margin-bottom: 2px;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.5rem;
|
||||
transition: background-color 0.2s;
|
||||
}
|
||||
|
||||
.file-item:hover {
|
||||
background-color: #4a5568;
|
||||
}
|
||||
|
||||
.file-item.selected {
|
||||
background-color: #3182ce;
|
||||
}
|
||||
|
||||
.file-item.drag-target {
|
||||
background-color: #2b6cb0;
|
||||
outline: 1px dashed #90cdf4;
|
||||
}
|
||||
|
||||
.file-item.dragging-file {
|
||||
opacity: 0.55;
|
||||
}
|
||||
|
||||
.file-item.directory {
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.file-item.root-drop {
|
||||
border: 1px dashed #4a5568;
|
||||
margin-bottom: 0.5rem;
|
||||
}
|
||||
|
||||
.file-icon {
|
||||
font-size: 1rem;
|
||||
}
|
||||
|
||||
.loading {
|
||||
padding: 1rem;
|
||||
text-align: center;
|
||||
color: #a0aec0;
|
||||
}
|
||||
|
||||
/* Main Content */
|
||||
.main-content {
|
||||
flex: 1;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
background-color: white;
|
||||
}
|
||||
|
||||
.editor-header {
|
||||
padding: 1rem;
|
||||
border-bottom: 1px solid #e2e8f0;
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
background-color: #f7fafc;
|
||||
}
|
||||
|
||||
.file-info {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 1rem;
|
||||
}
|
||||
|
||||
.runtime-hint {
|
||||
font-size: 0.75rem;
|
||||
color: #718096;
|
||||
border: 1px solid #e2e8f0;
|
||||
border-radius: 6px;
|
||||
padding: 0.2rem 0.45rem;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
#current-file {
|
||||
font-weight: 600;
|
||||
color: #2d3748;
|
||||
}
|
||||
|
||||
.save-status {
|
||||
font-size: 0.875rem;
|
||||
color: #718096;
|
||||
}
|
||||
|
||||
.save-status.saved {
|
||||
color: #38a169;
|
||||
}
|
||||
|
||||
.save-status.unsaved {
|
||||
color: #e53e3e;
|
||||
}
|
||||
|
||||
.mode-toggle {
|
||||
display: inline-flex;
|
||||
border: 1px solid #cbd5e0;
|
||||
border-radius: 8px;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.mode-btn {
|
||||
border: none;
|
||||
background: #edf2f7;
|
||||
color: #4a5568;
|
||||
padding: 0.45rem 0.8rem;
|
||||
font-size: 0.85rem;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.mode-btn + .mode-btn {
|
||||
border-left: 1px solid #cbd5e0;
|
||||
}
|
||||
|
||||
.mode-btn.active {
|
||||
background: #3182ce;
|
||||
color: white;
|
||||
}
|
||||
|
||||
.editor-actions {
|
||||
display: flex;
|
||||
gap: 0.5rem;
|
||||
}
|
||||
|
||||
#run-file-select {
|
||||
min-width: 220px;
|
||||
padding: 0.5rem 0.65rem;
|
||||
border: 1px solid #cbd5e0;
|
||||
border-radius: 6px;
|
||||
font-size: 0.85rem;
|
||||
background: white;
|
||||
}
|
||||
|
||||
.editor-actions button {
|
||||
padding: 0.5rem 1rem;
|
||||
border: 1px solid #e2e8f0;
|
||||
background-color: white;
|
||||
color: #4a5568;
|
||||
border-radius: 6px;
|
||||
cursor: pointer;
|
||||
font-size: 0.875rem;
|
||||
transition: all 0.2s;
|
||||
}
|
||||
|
||||
.editor-actions button:hover:not(:disabled) {
|
||||
background-color: #f7fafc;
|
||||
border-color: #cbd5e0;
|
||||
}
|
||||
|
||||
.editor-actions button:disabled {
|
||||
opacity: 0.5;
|
||||
cursor: not-allowed;
|
||||
}
|
||||
|
||||
.editor-actions button:not(:disabled):active {
|
||||
background-color: #edf2f7;
|
||||
}
|
||||
|
||||
.editor-container {
|
||||
flex: 1;
|
||||
position: relative;
|
||||
min-height: 0;
|
||||
}
|
||||
|
||||
.hidden {
|
||||
display: none !important;
|
||||
}
|
||||
|
||||
.completion-dropdown {
|
||||
position: absolute;
|
||||
z-index: 30;
|
||||
display: none;
|
||||
min-width: 220px;
|
||||
max-width: 420px;
|
||||
max-height: 220px;
|
||||
overflow-y: auto;
|
||||
background: #ffffff;
|
||||
border: 1px solid #cbd5e0;
|
||||
border-radius: 6px;
|
||||
box-shadow: 0 8px 20px rgba(0, 0, 0, 0.18);
|
||||
}
|
||||
|
||||
.completion-item {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
gap: 1rem;
|
||||
padding: 0.4rem 0.6rem;
|
||||
cursor: pointer;
|
||||
font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace;
|
||||
font-size: 13px;
|
||||
}
|
||||
|
||||
.completion-item:hover,
|
||||
.completion-item.active {
|
||||
background: #ebf8ff;
|
||||
}
|
||||
|
||||
.completion-name {
|
||||
color: #1a202c;
|
||||
}
|
||||
|
||||
.completion-type {
|
||||
color: #718096;
|
||||
font-size: 12px;
|
||||
}
|
||||
|
||||
.tabs {
|
||||
display: flex;
|
||||
gap: 4px;
|
||||
padding: 0.4rem 0.5rem;
|
||||
border-bottom: 1px solid #e2e8f0;
|
||||
background: #f8fafc;
|
||||
overflow-x: auto;
|
||||
}
|
||||
|
||||
.tab {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 0.5rem;
|
||||
padding: 0.35rem 0.6rem;
|
||||
border: 1px solid #cbd5e0;
|
||||
border-radius: 6px;
|
||||
background: white;
|
||||
color: #2d3748;
|
||||
cursor: pointer;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.tab.active {
|
||||
border-color: #3182ce;
|
||||
background: #ebf8ff;
|
||||
}
|
||||
|
||||
.tab-title {
|
||||
max-width: 260px;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
}
|
||||
|
||||
.tab-close {
|
||||
border: none;
|
||||
background: transparent;
|
||||
color: #718096;
|
||||
cursor: pointer;
|
||||
font-size: 14px;
|
||||
line-height: 1;
|
||||
}
|
||||
|
||||
.tab-close:hover {
|
||||
color: #e53e3e;
|
||||
}
|
||||
|
||||
#editor {
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
border: none;
|
||||
outline: none;
|
||||
font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace;
|
||||
font-size: 14px;
|
||||
line-height: 1.5;
|
||||
padding: 1rem;
|
||||
resize: none;
|
||||
}
|
||||
|
||||
/* CodeMirror 6 styling */
|
||||
.cm-editor {
|
||||
height: 100%;
|
||||
font-size: 14px;
|
||||
line-height: 1.5;
|
||||
}
|
||||
|
||||
.cm-focused {
|
||||
outline: none;
|
||||
}
|
||||
|
||||
.console-container {
|
||||
height: 220px;
|
||||
border-top: 1px solid #e2e8f0;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
background: #0f172a;
|
||||
}
|
||||
|
||||
.console-header {
|
||||
padding: 0.5rem 0.75rem;
|
||||
font-size: 0.85rem;
|
||||
color: #cbd5e1;
|
||||
border-bottom: 1px solid #1e293b;
|
||||
}
|
||||
|
||||
.console-output {
|
||||
flex: 1;
|
||||
margin: 0;
|
||||
padding: 0.75rem;
|
||||
overflow: auto;
|
||||
font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace;
|
||||
font-size: 13px;
|
||||
line-height: 1.45;
|
||||
color: #e2e8f0;
|
||||
white-space: pre-wrap;
|
||||
}
|
||||
|
||||
/* Modal */
|
||||
.modal {
|
||||
display: none;
|
||||
position: fixed;
|
||||
z-index: 1000;
|
||||
left: 0;
|
||||
top: 0;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
background-color: rgba(0, 0, 0, 0.5);
|
||||
}
|
||||
|
||||
.modal-content {
|
||||
background-color: white;
|
||||
margin: 15% auto;
|
||||
padding: 2rem;
|
||||
border-radius: 8px;
|
||||
width: 400px;
|
||||
box-shadow: 0 10px 25px rgba(0, 0, 0, 0.2);
|
||||
}
|
||||
|
||||
.modal-content h3 {
|
||||
margin-bottom: 1rem;
|
||||
color: #2d3748;
|
||||
}
|
||||
|
||||
.modal-content input {
|
||||
width: 100%;
|
||||
padding: 0.75rem;
|
||||
border: 1px solid #e2e8f0;
|
||||
border-radius: 6px;
|
||||
font-size: 1rem;
|
||||
margin-bottom: 1rem;
|
||||
}
|
||||
|
||||
.modal-content input:focus {
|
||||
outline: none;
|
||||
border-color: #3182ce;
|
||||
box-shadow: 0 0 0 3px rgba(49, 130, 206, 0.1);
|
||||
}
|
||||
|
||||
.modal-actions {
|
||||
display: flex;
|
||||
gap: 0.5rem;
|
||||
justify-content: flex-end;
|
||||
}
|
||||
|
||||
.modal-actions button {
|
||||
padding: 0.5rem 1rem;
|
||||
border: 1px solid #e2e8f0;
|
||||
background-color: white;
|
||||
color: #4a5568;
|
||||
border-radius: 6px;
|
||||
cursor: pointer;
|
||||
font-size: 0.875rem;
|
||||
transition: all 0.2s;
|
||||
}
|
||||
|
||||
.modal-actions button:hover {
|
||||
background-color: #f7fafc;
|
||||
border-color: #cbd5e0;
|
||||
}
|
||||
|
||||
.modal-actions button:first-child {
|
||||
background-color: #3182ce;
|
||||
color: white;
|
||||
border-color: #3182ce;
|
||||
}
|
||||
|
||||
.modal-actions button:first-child:hover {
|
||||
background-color: #2c5aa0;
|
||||
border-color: #2c5aa0;
|
||||
}
|
||||
|
||||
/* Responsive design */
|
||||
@media (max-width: 768px) {
|
||||
.sidebar {
|
||||
width: 250px;
|
||||
}
|
||||
|
||||
.modal-content {
|
||||
width: 90%;
|
||||
margin: 20% auto;
|
||||
}
|
||||
}
|
||||
|
||||
/* Scrollbar styling */
|
||||
.file-tree::-webkit-scrollbar {
|
||||
width: 6px;
|
||||
}
|
||||
|
||||
.file-tree::-webkit-scrollbar-track {
|
||||
background: #2d3748;
|
||||
}
|
||||
|
||||
.file-tree::-webkit-scrollbar-thumb {
|
||||
background: #4a5568;
|
||||
border-radius: 3px;
|
||||
}
|
||||
|
||||
.file-tree::-webkit-scrollbar-thumb:hover {
|
||||
background: #718096;
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user