Spaces:
Running
Running
Deploy 684217f676e8b0a2126452d47c10ddc3dc7aea74
Browse files- .dockerignore +32 -0
- Dockerfile +26 -0
- Makefile +40 -0
- README.md +9 -0
- cmd/server/main.go +135 -0
- go.mod +22 -0
- go.sum +49 -0
- internal/auth/auth.go +59 -0
- internal/auth/auth_test.go +73 -0
- internal/config/config.go +75 -0
- internal/database/database.go +87 -0
- internal/database/ddl.go +97 -0
- internal/database/ddl/180820260133_create_users.sql +13 -0
- internal/database/ddl_test.go +53 -0
- internal/database/migrations/0001_init.sql +40 -0
- internal/database/migrations/0002_drop_unused.sql +5 -0
- internal/logs/handler.go +55 -0
- internal/logs/hub.go +74 -0
- internal/logs/hub_test.go +96 -0
- internal/models/models.go +493 -0
- internal/models/models_test.go +92 -0
- internal/selfping/selfping.go +72 -0
- internal/selfping/selfping_test.go +87 -0
- internal/web/handlers.go +203 -0
- internal/web/handlers_test.go +131 -0
- internal/web/logs_handler.go +77 -0
- internal/web/middleware.go +155 -0
- internal/web/render.go +107 -0
- internal/web/server.go +134 -0
- internal/web/static/htmx.min.js +1 -0
- internal/web/static/markitdown.js +113 -0
- internal/web/static/style.css +485 -0
- internal/web/templates/base.html +68 -0
- internal/web/templates/pages/home.html +37 -0
- internal/web/templates/pages/login.html +19 -0
- internal/web/templates/pages/markitdown.html +17 -0
- scripts/smoke.sh +56 -0
.dockerignore
ADDED
|
@@ -0,0 +1,32 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Git
|
| 2 |
+
.git
|
| 3 |
+
.gitignore
|
| 4 |
+
.github
|
| 5 |
+
|
| 6 |
+
# Docs (README.md IS shipped - HF Space needs its frontmatter for sdk/port)
|
| 7 |
+
*.md
|
| 8 |
+
!README.md
|
| 9 |
+
|
| 10 |
+
# Secrets (never ship - injected as HF Space secrets by deploy.yml)
|
| 11 |
+
.env
|
| 12 |
+
.env.local
|
| 13 |
+
.env.*
|
| 14 |
+
!.env.example
|
| 15 |
+
!.env.hf.example
|
| 16 |
+
|
| 17 |
+
# Build / local artifacts
|
| 18 |
+
bin/
|
| 19 |
+
*.exe
|
| 20 |
+
*.test
|
| 21 |
+
*.out
|
| 22 |
+
|
| 23 |
+
# Runtime data (HF provides persistent /data - seeded at runtime, not baked)
|
| 24 |
+
data/
|
| 25 |
+
*.db
|
| 26 |
+
*.sqlite3
|
| 27 |
+
*.log
|
| 28 |
+
|
| 29 |
+
# Dev-only, not needed in the image
|
| 30 |
+
scripts/
|
| 31 |
+
website/
|
| 32 |
+
.DS_Store
|
Dockerfile
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# ---- build stage ----
|
| 2 |
+
FROM golang:1.26-alpine AS build
|
| 3 |
+
WORKDIR /src
|
| 4 |
+
|
| 5 |
+
# Cache dependencies first.
|
| 6 |
+
COPY go.mod go.sum ./
|
| 7 |
+
RUN go mod download
|
| 8 |
+
|
| 9 |
+
COPY . .
|
| 10 |
+
# Everything (templates, static assets, migrations) is embedded at compile
|
| 11 |
+
# time, so the output is a single self-contained static binary.
|
| 12 |
+
RUN CGO_ENABLED=0 GOOS=linux go build -trimpath -ldflags="-s -w" -o /out/markitdown ./cmd/server
|
| 13 |
+
RUN mkdir /data
|
| 14 |
+
|
| 15 |
+
# ---- runtime stage: distroless, no shell, non-root, ~15MB image ----
|
| 16 |
+
FROM gcr.io/distroless/static-debian12:nonroot
|
| 17 |
+
COPY --from=build /out/markitdown /markitdown
|
| 18 |
+
COPY --from=build --chown=nonroot:nonroot /data /data
|
| 19 |
+
# Hugging Face Spaces (Docker SDK) requires the container to listen on 7860.
|
| 20 |
+
# These are defaults only: HF Space secrets and `docker run --env-file .env`
|
| 21 |
+
# override them (local .env uses PORT=8909).
|
| 22 |
+
ENV PORT=7860
|
| 23 |
+
ENV DATABASE_URL=file:/data/markitdown.db?_busy_timeout=5000&_foreign_keys=on
|
| 24 |
+
EXPOSE 7860
|
| 25 |
+
USER nonroot:nonroot
|
| 26 |
+
ENTRYPOINT ["/markitdown"]
|
Makefile
ADDED
|
@@ -0,0 +1,40 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
.PHONY: build run test vet smoke logs docker-build docker-run docker-stop clean
|
| 2 |
+
|
| 3 |
+
IMAGE := markitdown
|
| 4 |
+
DB_VOLUME := markitdown-data
|
| 5 |
+
# SQLite lives at /data inside the container; override for local runs if needed.
|
| 6 |
+
DB_URL := file:/data/markitdown.db?_busy_timeout=5000&_foreign_keys=on
|
| 7 |
+
|
| 8 |
+
# Local development uses the SQLite database at data/pageturner.db.
|
| 9 |
+
build:
|
| 10 |
+
go build -o bin/markitdown ./cmd/server
|
| 11 |
+
|
| 12 |
+
run:
|
| 13 |
+
go run ./cmd/server
|
| 14 |
+
|
| 15 |
+
test:
|
| 16 |
+
go test ./...
|
| 17 |
+
|
| 18 |
+
smoke:
|
| 19 |
+
bash scripts/smoke.sh 8909
|
| 20 |
+
|
| 21 |
+
vet:
|
| 22 |
+
go vet ./...
|
| 23 |
+
|
| 24 |
+
logs:
|
| 25 |
+
docker logs -f markitdown
|
| 26 |
+
|
| 27 |
+
# Single-image production flow (no compose): build once, run anywhere.
|
| 28 |
+
docker-build:
|
| 29 |
+
docker build -t $(IMAGE) .
|
| 30 |
+
|
| 31 |
+
docker-run:
|
| 32 |
+
docker run -d --name markitdown -p 8909:8909 --env-file .env \
|
| 33 |
+
-e DATABASE_URL="$(DB_URL)" \
|
| 34 |
+
-v $(DB_VOLUME):/data --restart unless-stopped $(IMAGE)
|
| 35 |
+
|
| 36 |
+
docker-stop:
|
| 37 |
+
docker rm -f markitdown
|
| 38 |
+
|
| 39 |
+
clean:
|
| 40 |
+
rm -rf bin
|
README.md
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
---
|
| 2 |
+
title: Htmx + Go (FullStack)
|
| 3 |
+
emoji: 🔄
|
| 4 |
+
colorFrom: blue
|
| 5 |
+
colorTo: green
|
| 6 |
+
sdk: docker
|
| 7 |
+
pinned: false
|
| 8 |
+
app_port: 7860
|
| 9 |
+
---
|
cmd/server/main.go
ADDED
|
@@ -0,0 +1,135 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
package main
|
| 2 |
+
|
| 3 |
+
import (
|
| 4 |
+
"context"
|
| 5 |
+
"errors"
|
| 6 |
+
"log/slog"
|
| 7 |
+
"net/http"
|
| 8 |
+
"os"
|
| 9 |
+
"os/signal"
|
| 10 |
+
"strings"
|
| 11 |
+
"syscall"
|
| 12 |
+
"time"
|
| 13 |
+
|
| 14 |
+
"pageturner/internal/auth"
|
| 15 |
+
"pageturner/internal/config"
|
| 16 |
+
"pageturner/internal/database"
|
| 17 |
+
"pageturner/internal/logs"
|
| 18 |
+
"pageturner/internal/models"
|
| 19 |
+
"pageturner/internal/selfping"
|
| 20 |
+
"pageturner/internal/web"
|
| 21 |
+
)
|
| 22 |
+
|
| 23 |
+
func main() {
|
| 24 |
+
cfg := config.Load()
|
| 25 |
+
hub := logs.NewHub(200) // last 200 log lines, replayed to new stream viewers
|
| 26 |
+
log := newLogger(cfg.LogFormat, hub)
|
| 27 |
+
slog.SetDefault(log)
|
| 28 |
+
|
| 29 |
+
ctx := context.Background()
|
| 30 |
+
|
| 31 |
+
pool, err := database.Connect(ctx, cfg.DatabaseURL)
|
| 32 |
+
if err != nil {
|
| 33 |
+
log.Error("database connection failed", "error", err)
|
| 34 |
+
os.Exit(1)
|
| 35 |
+
}
|
| 36 |
+
defer pool.Close()
|
| 37 |
+
|
| 38 |
+
if err := database.Migrate(ctx, pool); err != nil {
|
| 39 |
+
log.Error("migrations failed", "error", err)
|
| 40 |
+
os.Exit(1)
|
| 41 |
+
}
|
| 42 |
+
if err := database.SyncDDL(ctx, pool); err != nil {
|
| 43 |
+
log.Error("ddl sync failed", "error", err)
|
| 44 |
+
os.Exit(1)
|
| 45 |
+
}
|
| 46 |
+
log.Info("database ready, migrations applied and ddl synced")
|
| 47 |
+
|
| 48 |
+
store := models.NewStore(pool)
|
| 49 |
+
seedUser(ctx, store, log)
|
| 50 |
+
srv := web.NewServer(cfg, store, log, hub)
|
| 51 |
+
|
| 52 |
+
httpServer := &http.Server{
|
| 53 |
+
Addr: ":" + cfg.Port,
|
| 54 |
+
Handler: srv.Handler(),
|
| 55 |
+
ReadHeaderTimeout: 5 * time.Second,
|
| 56 |
+
ReadTimeout: 10 * time.Second,
|
| 57 |
+
WriteTimeout: 30 * time.Second,
|
| 58 |
+
IdleTimeout: 60 * time.Second,
|
| 59 |
+
}
|
| 60 |
+
|
| 61 |
+
go func() {
|
| 62 |
+
log.Info("Pageturner listening", "addr", httpServer.Addr)
|
| 63 |
+
if err := httpServer.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) {
|
| 64 |
+
log.Error("server error", "error", err)
|
| 65 |
+
os.Exit(1)
|
| 66 |
+
}
|
| 67 |
+
}()
|
| 68 |
+
|
| 69 |
+
// Optional keep-warm scheduler for platforms that sleep on inactivity
|
| 70 |
+
// (e.g. Hugging Face Spaces): GETs the public URL every SELF_PING_INTERVAL.
|
| 71 |
+
// It stops as part of graceful shutdown below.
|
| 72 |
+
pingCtx, stopPing := context.WithCancel(context.Background())
|
| 73 |
+
if cfg.SelfPingEnabled && cfg.SelfPingURL != "" {
|
| 74 |
+
go selfping.Run(pingCtx, log, cfg.SelfPingURL, cfg.SelfPingEvery)
|
| 75 |
+
} else if cfg.SelfPingEnabled {
|
| 76 |
+
log.Warn("self-ping enabled but SELF_PING_URL is empty; scheduler not started")
|
| 77 |
+
}
|
| 78 |
+
|
| 79 |
+
// Graceful shutdown on Ctrl-C / SIGTERM.
|
| 80 |
+
stop := make(chan os.Signal, 1)
|
| 81 |
+
signal.Notify(stop, os.Interrupt, syscall.SIGTERM)
|
| 82 |
+
<-stop
|
| 83 |
+
|
| 84 |
+
log.Info("shutting down")
|
| 85 |
+
stopPing()
|
| 86 |
+
shutdownCtx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
| 87 |
+
defer cancel()
|
| 88 |
+
if err := httpServer.Shutdown(shutdownCtx); err != nil {
|
| 89 |
+
log.Error("shutdown", "error", err)
|
| 90 |
+
}
|
| 91 |
+
pool.Close()
|
| 92 |
+
log.Info("bye")
|
| 93 |
+
}
|
| 94 |
+
|
| 95 |
+
func newLogger(format string, hub *logs.Hub) *slog.Logger {
|
| 96 |
+
opts := &slog.HandlerOptions{Level: slog.LevelInfo}
|
| 97 |
+
var inner slog.Handler
|
| 98 |
+
if format == "json" {
|
| 99 |
+
inner = slog.NewJSONHandler(os.Stdout, opts)
|
| 100 |
+
} else {
|
| 101 |
+
inner = slog.NewTextHandler(os.Stdout, opts)
|
| 102 |
+
}
|
| 103 |
+
// Output goes to stdout as before, but every line is also published to the
|
| 104 |
+
// hub so the frontend log viewer can stream it live.
|
| 105 |
+
return slog.New(logs.NewStreamHandler(inner, hub))
|
| 106 |
+
}
|
| 107 |
+
|
| 108 |
+
// seedUser creates the SEED_EMAIL account on boot when SEED_EMAIL and
|
| 109 |
+
// SEED_PASSWORD are set (see .env). It is a no-op when the user exists,
|
| 110 |
+
// so restarts are safe.
|
| 111 |
+
func seedUser(ctx context.Context, store *models.Store, log *slog.Logger) {
|
| 112 |
+
email := strings.ToLower(strings.TrimSpace(os.Getenv("SEED_EMAIL")))
|
| 113 |
+
if email == "" {
|
| 114 |
+
return
|
| 115 |
+
}
|
| 116 |
+
password := os.Getenv("SEED_PASSWORD")
|
| 117 |
+
if password == "" {
|
| 118 |
+
log.Error("SEED_EMAIL is set but SEED_PASSWORD is empty; skipping seed user")
|
| 119 |
+
return
|
| 120 |
+
}
|
| 121 |
+
if _, err := store.UserByEmail(ctx, email); err == nil {
|
| 122 |
+
log.Info("seed user already exists", "email", email)
|
| 123 |
+
return
|
| 124 |
+
}
|
| 125 |
+
hash, err := auth.HashPassword(password)
|
| 126 |
+
if err != nil {
|
| 127 |
+
log.Error("seed user hashing failed", "error", err)
|
| 128 |
+
return
|
| 129 |
+
}
|
| 130 |
+
if _, err := store.CreateUser(ctx, email, hash); err != nil {
|
| 131 |
+
log.Error("seed user creation failed", "error", err)
|
| 132 |
+
return
|
| 133 |
+
}
|
| 134 |
+
log.Info("seed user created", "email", email)
|
| 135 |
+
}
|
go.mod
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
module pageturner
|
| 2 |
+
|
| 3 |
+
go 1.26
|
| 4 |
+
|
| 5 |
+
require (
|
| 6 |
+
golang.org/x/crypto v0.31.0
|
| 7 |
+
modernc.org/sqlite v1.36.1
|
| 8 |
+
)
|
| 9 |
+
|
| 10 |
+
require (
|
| 11 |
+
github.com/dustin/go-humanize v1.0.1 // indirect
|
| 12 |
+
github.com/google/uuid v1.6.0 // indirect
|
| 13 |
+
github.com/mattn/go-isatty v0.0.20 // indirect
|
| 14 |
+
github.com/ncruces/go-strftime v0.1.9 // indirect
|
| 15 |
+
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec // indirect
|
| 16 |
+
golang.org/x/exp v0.0.0-20230315142452-642cacee5cc0 // indirect
|
| 17 |
+
golang.org/x/sync v0.10.0 // indirect
|
| 18 |
+
golang.org/x/sys v0.30.0 // indirect
|
| 19 |
+
modernc.org/libc v1.61.13 // indirect
|
| 20 |
+
modernc.org/mathutil v1.7.1 // indirect
|
| 21 |
+
modernc.org/memory v1.8.2 // indirect
|
| 22 |
+
)
|
go.sum
ADDED
|
@@ -0,0 +1,49 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
github.com/dustin/go-humanize v1.0.1 h1:GzkhY7T5VNhEkwH0PVJgjz+fX1rhBrR7pRT3mDkpeCY=
|
| 2 |
+
github.com/dustin/go-humanize v1.0.1/go.mod h1:Mu1zIs6XwVuF/gI1OepvI0qD18qycQx+mFykh5fBlto=
|
| 3 |
+
github.com/google/pprof v0.0.0-20240409012703-83162a5b38cd h1:gbpYu9NMq8jhDVbvlGkMFWCjLFlqqEZjEmObmhUy6Vo=
|
| 4 |
+
github.com/google/pprof v0.0.0-20240409012703-83162a5b38cd/go.mod h1:kf6iHlnVGwgKolg33glAes7Yg/8iWP8ukqeldJSO7jw=
|
| 5 |
+
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
|
| 6 |
+
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
|
| 7 |
+
github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY=
|
| 8 |
+
github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
|
| 9 |
+
github.com/ncruces/go-strftime v0.1.9 h1:bY0MQC28UADQmHmaF5dgpLmImcShSi2kHU9XLdhx/f4=
|
| 10 |
+
github.com/ncruces/go-strftime v0.1.9/go.mod h1:Fwc5htZGVVkseilnfgOVb9mKy6w1naJmn9CehxcKcls=
|
| 11 |
+
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec h1:W09IVJc94icq4NjY3clb7Lk8O1qJ8BdBEF8z0ibU0rE=
|
| 12 |
+
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec/go.mod h1:qqbHyh8v60DhA7CoWK5oRCqLrMHRGoxYCSS9EjAz6Eo=
|
| 13 |
+
golang.org/x/crypto v0.31.0 h1:ihbySMvVjLAeSH1IbfcRTkD/iNscyz8rGzjF/E5hV6U=
|
| 14 |
+
golang.org/x/crypto v0.31.0/go.mod h1:kDsLvtWBEx7MV9tJOj9bnXsPbxwJQ6csT/x4KIN4Ssk=
|
| 15 |
+
golang.org/x/exp v0.0.0-20230315142452-642cacee5cc0 h1:pVgRXcIictcr+lBQIFeiwuwtDIs4eL21OuM9nyAADmo=
|
| 16 |
+
golang.org/x/exp v0.0.0-20230315142452-642cacee5cc0/go.mod h1:CxIveKay+FTh1D0yPZemJVgC/95VzuuOLq5Qi4xnoYc=
|
| 17 |
+
golang.org/x/mod v0.19.0 h1:fEdghXQSo20giMthA7cd28ZC+jts4amQ3YMXiP5oMQ8=
|
| 18 |
+
golang.org/x/mod v0.19.0/go.mod h1:hTbmBsO62+eylJbnUtE2MGJUyE7QWk4xUqPFrRgJ+7c=
|
| 19 |
+
golang.org/x/sync v0.10.0 h1:3NQrjDixjgGwUOCaF8w2+VYHv0Ve/vGYSbdkTa98gmQ=
|
| 20 |
+
golang.org/x/sync v0.10.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk=
|
| 21 |
+
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
| 22 |
+
golang.org/x/sys v0.30.0 h1:QjkSwP/36a20jFYWkSue1YwXzLmsV5Gfq7Eiy72C1uc=
|
| 23 |
+
golang.org/x/sys v0.30.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
|
| 24 |
+
golang.org/x/tools v0.23.0 h1:SGsXPZ+2l4JsgaCKkx+FQ9YZ5XEtA1GZYuoDjenLjvg=
|
| 25 |
+
golang.org/x/tools v0.23.0/go.mod h1:pnu6ufv6vQkll6szChhK3C3L/ruaIv5eBeztNG8wtsI=
|
| 26 |
+
modernc.org/cc/v4 v4.24.4 h1:TFkx1s6dCkQpd6dKurBNmpo+G8Zl4Sq/ztJ+2+DEsh0=
|
| 27 |
+
modernc.org/cc/v4 v4.24.4/go.mod h1:uVtb5OGqUKpoLWhqwNQo/8LwvoiEBLvZXIQ/SmO6mL0=
|
| 28 |
+
modernc.org/ccgo/v4 v4.23.16 h1:Z2N+kk38b7SfySC1ZkpGLN2vthNJP1+ZzGZIlH7uBxo=
|
| 29 |
+
modernc.org/ccgo/v4 v4.23.16/go.mod h1:nNma8goMTY7aQZQNTyN9AIoJfxav4nvTnvKThAeMDdo=
|
| 30 |
+
modernc.org/fileutil v1.3.0 h1:gQ5SIzK3H9kdfai/5x41oQiKValumqNTDXMvKo62HvE=
|
| 31 |
+
modernc.org/fileutil v1.3.0/go.mod h1:XatxS8fZi3pS8/hKG2GH/ArUogfxjpEKs3Ku3aK4JyQ=
|
| 32 |
+
modernc.org/gc/v2 v2.6.3 h1:aJVhcqAte49LF+mGveZ5KPlsp4tdGdAOT4sipJXADjw=
|
| 33 |
+
modernc.org/gc/v2 v2.6.3/go.mod h1:YgIahr1ypgfe7chRuJi2gD7DBQiKSLMPgBQe9oIiito=
|
| 34 |
+
modernc.org/libc v1.61.13 h1:3LRd6ZO1ezsFiX1y+bHd1ipyEHIJKvuprv0sLTBwLW8=
|
| 35 |
+
modernc.org/libc v1.61.13/go.mod h1:8F/uJWL/3nNil0Lgt1Dpz+GgkApWh04N3el3hxJcA6E=
|
| 36 |
+
modernc.org/mathutil v1.7.1 h1:GCZVGXdaN8gTqB1Mf/usp1Y/hSqgI2vAGGP4jZMCxOU=
|
| 37 |
+
modernc.org/mathutil v1.7.1/go.mod h1:4p5IwJITfppl0G4sUEDtCr4DthTaT47/N3aT6MhfgJg=
|
| 38 |
+
modernc.org/memory v1.8.2 h1:cL9L4bcoAObu4NkxOlKWBWtNHIsnnACGF/TbqQ6sbcI=
|
| 39 |
+
modernc.org/memory v1.8.2/go.mod h1:ZbjSvMO5NQ1A2i3bWeDiVMxIorXwdClKE/0SZ+BMotU=
|
| 40 |
+
modernc.org/opt v0.1.4 h1:2kNGMRiUjrp4LcaPuLY2PzUfqM/w9N23quVwhKt5Qm8=
|
| 41 |
+
modernc.org/opt v0.1.4/go.mod h1:03fq9lsNfvkYSfxrfUhZCWPk1lm4cq4N+Bh//bEtgns=
|
| 42 |
+
modernc.org/sortutil v1.2.1 h1:+xyoGf15mM3NMlPDnFqrteY07klSFxLElE2PVuWIJ7w=
|
| 43 |
+
modernc.org/sortutil v1.2.1/go.mod h1:7ZI3a3REbai7gzCLcotuw9AC4VZVpYMjDzETGsSMqJE=
|
| 44 |
+
modernc.org/sqlite v1.36.1 h1:bDa8BJUH4lg6EGkLbahKe/8QqoF8p9gArSc6fTqYhyQ=
|
| 45 |
+
modernc.org/sqlite v1.36.1/go.mod h1:7MPwH7Z6bREicF9ZVUR78P1IKuxfZ8mRIDHD0iD+8TU=
|
| 46 |
+
modernc.org/strutil v1.2.1 h1:UneZBkQA+DX2Rp35KcM69cSsNES9ly8mQWD71HKlOA0=
|
| 47 |
+
modernc.org/strutil v1.2.1/go.mod h1:EHkiggD70koQxjVdSBM3JKM7k6L0FbGE5eymy9i3B9A=
|
| 48 |
+
modernc.org/token v1.1.0 h1:Xl7Ap9dKaEs5kLoOQeQmPWevfnk/DM5qcLcYlA8ys6Y=
|
| 49 |
+
modernc.org/token v1.1.0/go.mod h1:UGzOrNV1mAFSEB63lOFHIpNRUVMvYTc6yu1SMY/XTDM=
|
internal/auth/auth.go
ADDED
|
@@ -0,0 +1,59 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
package auth
|
| 2 |
+
|
| 3 |
+
import (
|
| 4 |
+
"crypto/rand"
|
| 5 |
+
"crypto/sha256"
|
| 6 |
+
"crypto/subtle"
|
| 7 |
+
"encoding/base64"
|
| 8 |
+
"encoding/hex"
|
| 9 |
+
"errors"
|
| 10 |
+
|
| 11 |
+
"golang.org/x/crypto/bcrypt"
|
| 12 |
+
)
|
| 13 |
+
|
| 14 |
+
// HashPassword returns a bcrypt hash of the plaintext password.
|
| 15 |
+
func HashPassword(plain string) (string, error) {
|
| 16 |
+
b, err := bcrypt.GenerateFromPassword([]byte(plain), bcrypt.DefaultCost)
|
| 17 |
+
if err != nil {
|
| 18 |
+
return "", err
|
| 19 |
+
}
|
| 20 |
+
return string(b), nil
|
| 21 |
+
}
|
| 22 |
+
|
| 23 |
+
// CheckPassword reports whether plain matches the stored bcrypt hash.
|
| 24 |
+
func CheckPassword(hash, plain string) bool {
|
| 25 |
+
return bcrypt.CompareHashAndPassword([]byte(hash), []byte(plain)) == nil
|
| 26 |
+
}
|
| 27 |
+
|
| 28 |
+
// NewToken returns a cryptographically random URL-safe token (32 bytes).
|
| 29 |
+
func NewToken() (string, error) {
|
| 30 |
+
b := make([]byte, 32)
|
| 31 |
+
if _, err := rand.Read(b); err != nil {
|
| 32 |
+
return "", err
|
| 33 |
+
}
|
| 34 |
+
return base64.RawURLEncoding.EncodeToString(b), nil
|
| 35 |
+
}
|
| 36 |
+
|
| 37 |
+
// HashToken hashes a session token for storage. The raw token is only ever
|
| 38 |
+
// kept in the user's cookie; the DB stores the SHA-256 digest.
|
| 39 |
+
func HashToken(token string) string {
|
| 40 |
+
sum := sha256.Sum256([]byte(token))
|
| 41 |
+
return hex.EncodeToString(sum[:])
|
| 42 |
+
}
|
| 43 |
+
|
| 44 |
+
// NewCSRF returns a random CSRF token (32 bytes, hex).
|
| 45 |
+
func NewCSRF() (string, error) {
|
| 46 |
+
b := make([]byte, 32)
|
| 47 |
+
if _, err := rand.Read(b); err != nil {
|
| 48 |
+
return "", err
|
| 49 |
+
}
|
| 50 |
+
return hex.EncodeToString(b), nil
|
| 51 |
+
}
|
| 52 |
+
|
| 53 |
+
// ConstantTimeEqual compares two strings in constant time.
|
| 54 |
+
func ConstantTimeEqual(a, b string) bool {
|
| 55 |
+
return subtle.ConstantTimeCompare([]byte(a), []byte(b)) == 1
|
| 56 |
+
}
|
| 57 |
+
|
| 58 |
+
// ErrToken is returned when token generation fails (system entropy error).
|
| 59 |
+
var ErrToken = errors.New("failed to generate secure token")
|
internal/auth/auth_test.go
ADDED
|
@@ -0,0 +1,73 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
package auth
|
| 2 |
+
|
| 3 |
+
import "testing"
|
| 4 |
+
|
| 5 |
+
func TestHashAndCheckPassword(t *testing.T) {
|
| 6 |
+
hash, err := HashPassword("s3cret-pass")
|
| 7 |
+
if err != nil {
|
| 8 |
+
t.Fatalf("HashPassword: %v", err)
|
| 9 |
+
}
|
| 10 |
+
if hash == "s3cret-pass" {
|
| 11 |
+
t.Fatal("hash must not equal plaintext")
|
| 12 |
+
}
|
| 13 |
+
if !CheckPassword(hash, "s3cret-pass") {
|
| 14 |
+
t.Fatal("expected correct password to verify")
|
| 15 |
+
}
|
| 16 |
+
if CheckPassword(hash, "wrong-pass") {
|
| 17 |
+
t.Fatal("expected wrong password to fail")
|
| 18 |
+
}
|
| 19 |
+
}
|
| 20 |
+
|
| 21 |
+
func TestHashPasswordCost(t *testing.T) {
|
| 22 |
+
// bcrypt output must be 60 chars.
|
| 23 |
+
hash, err := HashPassword("x")
|
| 24 |
+
if err != nil {
|
| 25 |
+
t.Fatalf("HashPassword: %v", err)
|
| 26 |
+
}
|
| 27 |
+
if len(hash) != 60 {
|
| 28 |
+
t.Fatalf("expected 60-char bcrypt hash, got %d", len(hash))
|
| 29 |
+
}
|
| 30 |
+
}
|
| 31 |
+
|
| 32 |
+
func TestNewTokenUniqueness(t *testing.T) {
|
| 33 |
+
seen := map[string]bool{}
|
| 34 |
+
for i := 0; i < 100; i++ {
|
| 35 |
+
tok, err := NewToken()
|
| 36 |
+
if err != nil {
|
| 37 |
+
t.Fatalf("NewToken: %v", err)
|
| 38 |
+
}
|
| 39 |
+
if len(tok) < 32 {
|
| 40 |
+
t.Fatalf("token too short: %d", len(tok))
|
| 41 |
+
}
|
| 42 |
+
if seen[tok] {
|
| 43 |
+
t.Fatal("duplicate token generated")
|
| 44 |
+
}
|
| 45 |
+
seen[tok] = true
|
| 46 |
+
}
|
| 47 |
+
}
|
| 48 |
+
|
| 49 |
+
func TestHashTokenIsDeterministicDigest(t *testing.T) {
|
| 50 |
+
a := HashToken("abc123")
|
| 51 |
+
b := HashToken("abc123")
|
| 52 |
+
if a != b {
|
| 53 |
+
t.Fatal("same input must hash identically")
|
| 54 |
+
}
|
| 55 |
+
if HashToken("abc123") == HashToken("abc124") {
|
| 56 |
+
t.Fatal("different inputs must differ")
|
| 57 |
+
}
|
| 58 |
+
if a == "abc123" {
|
| 59 |
+
t.Fatal("token must be hashed, not stored raw")
|
| 60 |
+
}
|
| 61 |
+
}
|
| 62 |
+
|
| 63 |
+
func TestConstantTimeEqual(t *testing.T) {
|
| 64 |
+
if !ConstantTimeEqual("token", "token") {
|
| 65 |
+
t.Fatal("equal strings must compare true")
|
| 66 |
+
}
|
| 67 |
+
if ConstantTimeEqual("token", "tokem") {
|
| 68 |
+
t.Fatal("different strings must compare false")
|
| 69 |
+
}
|
| 70 |
+
if ConstantTimeEqual("", "x") || ConstantTimeEqual("x", "") {
|
| 71 |
+
t.Fatal("empty vs non-empty must compare false")
|
| 72 |
+
}
|
| 73 |
+
}
|
internal/config/config.go
ADDED
|
@@ -0,0 +1,75 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
package config
|
| 2 |
+
|
| 3 |
+
import (
|
| 4 |
+
"log/slog"
|
| 5 |
+
"os"
|
| 6 |
+
"time"
|
| 7 |
+
)
|
| 8 |
+
|
| 9 |
+
// Config holds all runtime configuration, sourced from environment variables.
|
| 10 |
+
type Config struct {
|
| 11 |
+
Port string
|
| 12 |
+
DatabaseURL string
|
| 13 |
+
SessionSecret string
|
| 14 |
+
SessionTTL time.Duration
|
| 15 |
+
LogFormat string
|
| 16 |
+
SelfPingEnabled bool
|
| 17 |
+
SelfPingURL string
|
| 18 |
+
SelfPingEvery time.Duration
|
| 19 |
+
}
|
| 20 |
+
|
| 21 |
+
// Load reads configuration from the environment, applying development-friendly
|
| 22 |
+
// defaults. Production deployments should set every variable explicitly.
|
| 23 |
+
func Load() Config {
|
| 24 |
+
cfg := Config{
|
| 25 |
+
Port: getenv("PORT", "8909"),
|
| 26 |
+
DatabaseURL: getenv("DATABASE_URL", "file:data/pageturner.db?_busy_timeout=5000&_foreign_keys=on"),
|
| 27 |
+
SessionSecret: getenv("SESSION_SECRET", "dev-secret-change-me-in-production"),
|
| 28 |
+
SessionTTL: durationEnv("SESSION_TTL", 168*time.Hour),
|
| 29 |
+
LogFormat: getenv("LOG_FORMAT", "text"),
|
| 30 |
+
SelfPingEnabled: boolEnv("SELF_PING_ENABLED", false),
|
| 31 |
+
SelfPingURL: getenv("SELF_PING_URL", ""),
|
| 32 |
+
SelfPingEvery: durationEnv("SELF_PING_INTERVAL", 15*time.Minute),
|
| 33 |
+
}
|
| 34 |
+
|
| 35 |
+
if cfg.SessionSecret == "dev-secret-change-me-in-production" {
|
| 36 |
+
slog.Warn("SESSION_SECRET is unset; using an insecure development secret. Set SESSION_SECRET in production.")
|
| 37 |
+
}
|
| 38 |
+
if cfg.SelfPingEnabled && cfg.SelfPingURL == "" {
|
| 39 |
+
slog.Warn("SELF_PING_ENABLED is true but SELF_PING_URL is empty; self-ping scheduler will stay idle.")
|
| 40 |
+
}
|
| 41 |
+
return cfg
|
| 42 |
+
}
|
| 43 |
+
|
| 44 |
+
// CookieSecure reports whether session/CSRF cookies should set the Secure flag.
|
| 45 |
+
func (c Config) CookieSecure() bool {
|
| 46 |
+
return os.Getenv("COOKIE_SECURE") == "true"
|
| 47 |
+
}
|
| 48 |
+
|
| 49 |
+
func getenv(key, fallback string) string {
|
| 50 |
+
if v := os.Getenv(key); v != "" {
|
| 51 |
+
return v
|
| 52 |
+
}
|
| 53 |
+
return fallback
|
| 54 |
+
}
|
| 55 |
+
|
| 56 |
+
func durationEnv(key string, fallback time.Duration) time.Duration {
|
| 57 |
+
if v := os.Getenv(key); v != "" {
|
| 58 |
+
if d, err := time.ParseDuration(v); err == nil {
|
| 59 |
+
return d
|
| 60 |
+
}
|
| 61 |
+
}
|
| 62 |
+
return fallback
|
| 63 |
+
}
|
| 64 |
+
|
| 65 |
+
func boolEnv(key string, fallback bool) bool {
|
| 66 |
+
if v := os.Getenv(key); v != "" {
|
| 67 |
+
switch v {
|
| 68 |
+
case "1", "t", "T", "true", "TRUE", "True":
|
| 69 |
+
return true
|
| 70 |
+
case "0", "f", "F", "false", "FALSE", "False":
|
| 71 |
+
return false
|
| 72 |
+
}
|
| 73 |
+
}
|
| 74 |
+
return fallback
|
| 75 |
+
}
|
internal/database/database.go
ADDED
|
@@ -0,0 +1,87 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
package database
|
| 2 |
+
|
| 3 |
+
import (
|
| 4 |
+
"context"
|
| 5 |
+
"database/sql"
|
| 6 |
+
"embed"
|
| 7 |
+
"fmt"
|
| 8 |
+
"sort"
|
| 9 |
+
"time"
|
| 10 |
+
|
| 11 |
+
_ "modernc.org/sqlite"
|
| 12 |
+
)
|
| 13 |
+
|
| 14 |
+
//go:embed migrations/*.sql
|
| 15 |
+
var migrationsFS embed.FS
|
| 16 |
+
|
| 17 |
+
// Connect opens a SQLite database and verifies connectivity.
|
| 18 |
+
func Connect(ctx context.Context, databaseURL string) (*sql.DB, error) {
|
| 19 |
+
db, err := sql.Open("sqlite", databaseURL)
|
| 20 |
+
if err != nil {
|
| 21 |
+
return nil, fmt.Errorf("open DATABASE_URL: %w", err)
|
| 22 |
+
}
|
| 23 |
+
|
| 24 |
+
ctx, cancel := context.WithTimeout(ctx, 10*time.Second)
|
| 25 |
+
defer cancel()
|
| 26 |
+
if err := db.PingContext(ctx); err != nil {
|
| 27 |
+
db.Close()
|
| 28 |
+
return nil, fmt.Errorf("ping database: %w", err)
|
| 29 |
+
}
|
| 30 |
+
return db, nil
|
| 31 |
+
}
|
| 32 |
+
|
| 33 |
+
// Migrate applies pending SQL migrations in filename order.
|
| 34 |
+
func Migrate(ctx context.Context, db *sql.DB) error {
|
| 35 |
+
entries, err := migrationsFS.ReadDir("migrations")
|
| 36 |
+
if err != nil {
|
| 37 |
+
return fmt.Errorf("read migrations: %w", err)
|
| 38 |
+
}
|
| 39 |
+
names := make([]string, 0, len(entries))
|
| 40 |
+
for _, e := range entries {
|
| 41 |
+
names = append(names, e.Name())
|
| 42 |
+
}
|
| 43 |
+
sort.Strings(names)
|
| 44 |
+
|
| 45 |
+
if _, err := db.ExecContext(ctx, `
|
| 46 |
+
CREATE TABLE IF NOT EXISTS schema_migrations (
|
| 47 |
+
version TEXT PRIMARY KEY,
|
| 48 |
+
applied_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP
|
| 49 |
+
)`); err != nil {
|
| 50 |
+
return fmt.Errorf("ensure schema_migrations: %w", err)
|
| 51 |
+
}
|
| 52 |
+
|
| 53 |
+
for _, name := range names {
|
| 54 |
+
var applied bool
|
| 55 |
+
err := db.QueryRowContext(ctx,
|
| 56 |
+
"SELECT EXISTS(SELECT 1 FROM schema_migrations WHERE version = ?)", name).
|
| 57 |
+
Scan(&applied)
|
| 58 |
+
if err != nil {
|
| 59 |
+
return fmt.Errorf("check migration %s: %w", name, err)
|
| 60 |
+
}
|
| 61 |
+
if applied {
|
| 62 |
+
continue
|
| 63 |
+
}
|
| 64 |
+
|
| 65 |
+
body, err := migrationsFS.ReadFile("migrations/" + name)
|
| 66 |
+
if err != nil {
|
| 67 |
+
return fmt.Errorf("read migration %s: %w", name, err)
|
| 68 |
+
}
|
| 69 |
+
tx, err := db.BeginTx(ctx, nil)
|
| 70 |
+
if err != nil {
|
| 71 |
+
return fmt.Errorf("begin migration %s: %w", name, err)
|
| 72 |
+
}
|
| 73 |
+
if _, err := tx.ExecContext(ctx, string(body)); err != nil {
|
| 74 |
+
tx.Rollback() //nolint:errcheck
|
| 75 |
+
return fmt.Errorf("apply migration %s: %w", name, err)
|
| 76 |
+
}
|
| 77 |
+
if _, err := tx.ExecContext(ctx,
|
| 78 |
+
"INSERT INTO schema_migrations (version) VALUES (?)", name); err != nil {
|
| 79 |
+
tx.Rollback() //nolint:errcheck
|
| 80 |
+
return fmt.Errorf("record migration %s: %w", name, err)
|
| 81 |
+
}
|
| 82 |
+
if err := tx.Commit(); err != nil {
|
| 83 |
+
return fmt.Errorf("commit migration %s: %w", name, err)
|
| 84 |
+
}
|
| 85 |
+
}
|
| 86 |
+
return nil
|
| 87 |
+
}
|
internal/database/ddl.go
ADDED
|
@@ -0,0 +1,97 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
package database
|
| 2 |
+
|
| 3 |
+
import (
|
| 4 |
+
"context"
|
| 5 |
+
"database/sql"
|
| 6 |
+
"embed"
|
| 7 |
+
"fmt"
|
| 8 |
+
"log/slog"
|
| 9 |
+
"sort"
|
| 10 |
+
"strconv"
|
| 11 |
+
"strings"
|
| 12 |
+
)
|
| 13 |
+
|
| 14 |
+
//go:embed ddl/*.sql
|
| 15 |
+
var ddlFS embed.FS
|
| 16 |
+
|
| 17 |
+
const initialLastSynced int64 = 180820260136
|
| 18 |
+
|
| 19 |
+
// SyncDDL applies timestamped SQL scripts newer than the stored marker.
|
| 20 |
+
func SyncDDL(ctx context.Context, db *sql.DB) error {
|
| 21 |
+
if _, err := db.ExecContext(ctx, `
|
| 22 |
+
CREATE TABLE IF NOT EXISTS last_synced (
|
| 23 |
+
id SMALLINT PRIMARY KEY DEFAULT 1 CHECK (id = 1),
|
| 24 |
+
synced_at BIGINT NOT NULL,
|
| 25 |
+
updated_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP
|
| 26 |
+
)`); err != nil {
|
| 27 |
+
return fmt.Errorf("ensure last_synced table: %w", err)
|
| 28 |
+
}
|
| 29 |
+
if _, err := db.ExecContext(ctx,
|
| 30 |
+
`INSERT INTO last_synced (id, synced_at) VALUES (1, ?) ON CONFLICT (id) DO NOTHING`,
|
| 31 |
+
initialLastSynced); err != nil {
|
| 32 |
+
return fmt.Errorf("seed last_synced: %w", err)
|
| 33 |
+
}
|
| 34 |
+
|
| 35 |
+
var syncedAt int64
|
| 36 |
+
if err := db.QueryRowContext(ctx, `SELECT synced_at FROM last_synced WHERE id = 1`).Scan(&syncedAt); err != nil {
|
| 37 |
+
return fmt.Errorf("read last_synced: %w", err)
|
| 38 |
+
}
|
| 39 |
+
|
| 40 |
+
entries, err := ddlFS.ReadDir("ddl")
|
| 41 |
+
if err != nil {
|
| 42 |
+
return fmt.Errorf("read ddl folder: %w", err)
|
| 43 |
+
}
|
| 44 |
+
names := make([]string, 0, len(entries))
|
| 45 |
+
for _, e := range entries {
|
| 46 |
+
names = append(names, e.Name())
|
| 47 |
+
}
|
| 48 |
+
sort.Strings(names)
|
| 49 |
+
|
| 50 |
+
log := slog.Default()
|
| 51 |
+
for _, name := range names {
|
| 52 |
+
if !strings.HasSuffix(name, ".sql") {
|
| 53 |
+
continue
|
| 54 |
+
}
|
| 55 |
+
ts, err := ddlTimestamp(name)
|
| 56 |
+
if err != nil {
|
| 57 |
+
return fmt.Errorf("invalid ddl script name %q: %w", name, err)
|
| 58 |
+
}
|
| 59 |
+
if ts <= syncedAt {
|
| 60 |
+
continue
|
| 61 |
+
}
|
| 62 |
+
body, err := ddlFS.ReadFile("ddl/" + name)
|
| 63 |
+
if err != nil {
|
| 64 |
+
return fmt.Errorf("read ddl script %s: %w", name, err)
|
| 65 |
+
}
|
| 66 |
+
tx, err := db.BeginTx(ctx, nil)
|
| 67 |
+
if err != nil {
|
| 68 |
+
return fmt.Errorf("begin ddl script %s: %w", name, err)
|
| 69 |
+
}
|
| 70 |
+
if _, err := tx.ExecContext(ctx, string(body)); err != nil {
|
| 71 |
+
tx.Rollback() //nolint:errcheck
|
| 72 |
+
return fmt.Errorf("apply ddl script %s: %w", name, err)
|
| 73 |
+
}
|
| 74 |
+
if _, err := tx.ExecContext(ctx,
|
| 75 |
+
`UPDATE last_synced SET synced_at = ?, updated_at = CURRENT_TIMESTAMP WHERE id = 1`, ts); err != nil {
|
| 76 |
+
tx.Rollback() //nolint:errcheck
|
| 77 |
+
return fmt.Errorf("advance last_synced for %s: %w", name, err)
|
| 78 |
+
}
|
| 79 |
+
if err := tx.Commit(); err != nil {
|
| 80 |
+
return fmt.Errorf("commit ddl script %s: %w", name, err)
|
| 81 |
+
}
|
| 82 |
+
log.Info("ddl applied", "script", name, "synced_at", ts)
|
| 83 |
+
}
|
| 84 |
+
return nil
|
| 85 |
+
}
|
| 86 |
+
|
| 87 |
+
func ddlTimestamp(name string) (int64, error) {
|
| 88 |
+
base := strings.TrimSuffix(name, ".sql")
|
| 89 |
+
if len(base) < 13 || base[12] != '_' {
|
| 90 |
+
return 0, fmt.Errorf("expected <12 digit timestamp>_<name>.sql, got %q", name)
|
| 91 |
+
}
|
| 92 |
+
ts, err := strconv.ParseInt(base[:12], 10, 64)
|
| 93 |
+
if err != nil {
|
| 94 |
+
return 0, fmt.Errorf("timestamp %q is not numeric", base[:12])
|
| 95 |
+
}
|
| 96 |
+
return ts, nil
|
| 97 |
+
}
|
internal/database/ddl/180820260133_create_users.sql
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
-- Example DDL script — naming convention: DDMMYYYYHHMM_<name>.sql
|
| 2 |
+
-- 180820260133 = 18 Aug 2026, 01:33
|
| 3 |
+
--
|
| 4 |
+
-- On startup the app compares each script's timestamp against the
|
| 5 |
+
-- last_synced marker (seeded to 180820260136 = 18 Aug 2026, 01:36) and only
|
| 6 |
+
-- runs scripts NEWER than the marker. This file sits at/below the baseline,
|
| 7 |
+
-- so it is treated as already applied and never executes — it exists purely
|
| 8 |
+
-- to show the format.
|
| 9 |
+
--
|
| 10 |
+
-- To apply new schema changes: drop a file here named with the current
|
| 11 |
+
-- day-month-year-hour-minute, e.g. 180820261530_add_reviews.sql, and it will
|
| 12 |
+
-- run automatically on the next app start.
|
| 13 |
+
SELECT 1;
|
internal/database/ddl_test.go
ADDED
|
@@ -0,0 +1,53 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
package database
|
| 2 |
+
|
| 3 |
+
import (
|
| 4 |
+
"context"
|
| 5 |
+
"os"
|
| 6 |
+
"testing"
|
| 7 |
+
)
|
| 8 |
+
|
| 9 |
+
// TestSyncDDL verifies the last_synced marker table is created and seeded on a
|
| 10 |
+
// fresh database and that SyncDDL is idempotent across runs. Runs only when
|
| 11 |
+
// TEST_DATABASE_URL is set, mirroring the other integration tests.
|
| 12 |
+
func TestSyncDDL(t *testing.T) {
|
| 13 |
+
dsn := os.Getenv("TEST_DATABASE_URL")
|
| 14 |
+
if dsn == "" {
|
| 15 |
+
t.Skip("TEST_DATABASE_URL not set; skipping integration test")
|
| 16 |
+
}
|
| 17 |
+
ctx := context.Background()
|
| 18 |
+
|
| 19 |
+
db, err := Connect(ctx, dsn)
|
| 20 |
+
if err != nil {
|
| 21 |
+
t.Fatalf("connect: %v", err)
|
| 22 |
+
}
|
| 23 |
+
defer db.Close()
|
| 24 |
+
|
| 25 |
+
// Ensure the table is created fresh so the seed assertion is meaningful.
|
| 26 |
+
if _, err := db.ExecContext(ctx, `DROP TABLE IF EXISTS last_synced`); err != nil {
|
| 27 |
+
t.Fatalf("drop last_synced: %v", err)
|
| 28 |
+
}
|
| 29 |
+
|
| 30 |
+
if err := SyncDDL(ctx, db); err != nil {
|
| 31 |
+
t.Fatalf("SyncDDL (first run): %v", err)
|
| 32 |
+
}
|
| 33 |
+
|
| 34 |
+
var syncedAt int64
|
| 35 |
+
if err := db.QueryRowContext(ctx, `SELECT synced_at FROM last_synced WHERE id = 1`).Scan(&syncedAt); err != nil {
|
| 36 |
+
t.Fatalf("read last_synced: %v", err)
|
| 37 |
+
}
|
| 38 |
+
if syncedAt != initialLastSynced {
|
| 39 |
+
t.Fatalf("synced_at = %d, want baseline %d", syncedAt, initialLastSynced)
|
| 40 |
+
}
|
| 41 |
+
|
| 42 |
+
// A second run must be a no-op, not an error.
|
| 43 |
+
if err := SyncDDL(ctx, db); err != nil {
|
| 44 |
+
t.Fatalf("SyncDDL (second run, should be idempotent): %v", err)
|
| 45 |
+
}
|
| 46 |
+
var again int64
|
| 47 |
+
if err := db.QueryRowContext(ctx, `SELECT synced_at FROM last_synced WHERE id = 1`).Scan(&again); err != nil {
|
| 48 |
+
t.Fatalf("re-read last_synced: %v", err)
|
| 49 |
+
}
|
| 50 |
+
if again != syncedAt {
|
| 51 |
+
t.Fatalf("synced_at changed across idempotent runs: %d -> %d", syncedAt, again)
|
| 52 |
+
}
|
| 53 |
+
}
|
internal/database/migrations/0001_init.sql
ADDED
|
@@ -0,0 +1,40 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
-- Pageturner initial schema
|
| 2 |
+
CREATE TABLE users (
|
| 3 |
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
| 4 |
+
email TEXT NOT NULL UNIQUE,
|
| 5 |
+
password_hash TEXT NOT NULL,
|
| 6 |
+
created_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP
|
| 7 |
+
);
|
| 8 |
+
|
| 9 |
+
CREATE TABLE sessions (
|
| 10 |
+
token_hash TEXT PRIMARY KEY,
|
| 11 |
+
user_id BIGINT NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
| 12 |
+
expires_at TEXT NOT NULL,
|
| 13 |
+
created_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP
|
| 14 |
+
);
|
| 15 |
+
|
| 16 |
+
CREATE INDEX sessions_user_idx ON sessions(user_id);
|
| 17 |
+
CREATE INDEX sessions_expires_idx ON sessions(expires_at);
|
| 18 |
+
|
| 19 |
+
CREATE TABLE books (
|
| 20 |
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
| 21 |
+
user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
| 22 |
+
title TEXT NOT NULL,
|
| 23 |
+
author TEXT NOT NULL,
|
| 24 |
+
status TEXT NOT NULL DEFAULT 'to_read'
|
| 25 |
+
CHECK (status IN ('to_read', 'reading', 'finished')),
|
| 26 |
+
rating INT CHECK (rating BETWEEN 1 AND 5),
|
| 27 |
+
review TEXT,
|
| 28 |
+
created_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
| 29 |
+
finished_at TEXT
|
| 30 |
+
);
|
| 31 |
+
|
| 32 |
+
CREATE INDEX books_user_idx ON books(user_id);
|
| 33 |
+
CREATE INDEX books_user_status_idx ON books(user_id, status);
|
| 34 |
+
|
| 35 |
+
CREATE TABLE reading_goals (
|
| 36 |
+
user_id BIGINT PRIMARY KEY REFERENCES users(id) ON DELETE CASCADE,
|
| 37 |
+
year INT NOT NULL,
|
| 38 |
+
goal INT NOT NULL DEFAULT 10 CHECK (goal BETWEEN 1 AND 500),
|
| 39 |
+
updated_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP
|
| 40 |
+
);
|
internal/database/migrations/0002_drop_unused.sql
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
-- Markitdown runs auth-only: users + sessions are the live tables.
|
| 2 |
+
-- The book-tracker era tables (books, reading_goals) are unused by every
|
| 3 |
+
-- route, so drop them. Indexes die with their tables in SQLite.
|
| 4 |
+
DROP TABLE IF EXISTS books;
|
| 5 |
+
DROP TABLE IF EXISTS reading_goals;
|
internal/logs/handler.go
ADDED
|
@@ -0,0 +1,55 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
package logs
|
| 2 |
+
|
| 3 |
+
import (
|
| 4 |
+
"context"
|
| 5 |
+
"fmt"
|
| 6 |
+
"log/slog"
|
| 7 |
+
"strings"
|
| 8 |
+
)
|
| 9 |
+
|
| 10 |
+
// StreamHandler wraps another slog.Handler (the real stdout sink, text or JSON)
|
| 11 |
+
// and additionally publishes a human-readable rendering of every record to the
|
| 12 |
+
// Hub, so the live log stream mirrors the terminal output.
|
| 13 |
+
type StreamHandler struct {
|
| 14 |
+
inner slog.Handler
|
| 15 |
+
hub *Hub
|
| 16 |
+
}
|
| 17 |
+
|
| 18 |
+
// NewStreamHandler wraps inner so handled records are also published to hub.
|
| 19 |
+
func NewStreamHandler(inner slog.Handler, hub *Hub) slog.Handler {
|
| 20 |
+
return &StreamHandler{inner: inner, hub: hub}
|
| 21 |
+
}
|
| 22 |
+
|
| 23 |
+
func (h *StreamHandler) Enabled(ctx context.Context, level slog.Level) bool {
|
| 24 |
+
return h.inner.Enabled(ctx, level)
|
| 25 |
+
}
|
| 26 |
+
|
| 27 |
+
func (h *StreamHandler) Handle(ctx context.Context, r slog.Record) error {
|
| 28 |
+
h.hub.Publish(formatRecord(&r))
|
| 29 |
+
return h.inner.Handle(ctx, r)
|
| 30 |
+
}
|
| 31 |
+
|
| 32 |
+
func (h *StreamHandler) WithAttrs(attrs []slog.Attr) slog.Handler {
|
| 33 |
+
return &StreamHandler{inner: h.inner.WithAttrs(attrs), hub: h.hub}
|
| 34 |
+
}
|
| 35 |
+
|
| 36 |
+
func (h *StreamHandler) WithGroup(name string) slog.Handler {
|
| 37 |
+
return &StreamHandler{inner: h.inner.WithGroup(name), hub: h.hub}
|
| 38 |
+
}
|
| 39 |
+
|
| 40 |
+
// formatRecord renders a record as a plain, terminal-friendly line:
|
| 41 |
+
//
|
| 42 |
+
// 2026-08-18 01:36:00.000 INFO database ready key=value
|
| 43 |
+
func formatRecord(r *slog.Record) string {
|
| 44 |
+
var b strings.Builder
|
| 45 |
+
fmt.Fprintf(&b, "%s %-7s %s", r.Time.Format("2006-01-02 15:04:05.000"), r.Level.String(), r.Message)
|
| 46 |
+
r.Attrs(func(a slog.Attr) bool {
|
| 47 |
+
if a.Key == "" {
|
| 48 |
+
return true
|
| 49 |
+
}
|
| 50 |
+
b.WriteByte(' ')
|
| 51 |
+
b.WriteString(a.String())
|
| 52 |
+
return true
|
| 53 |
+
})
|
| 54 |
+
return b.String()
|
| 55 |
+
}
|
internal/logs/hub.go
ADDED
|
@@ -0,0 +1,74 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
// Package logs bridges backend logging to live subscribers (SSE). A Hub keeps
|
| 2 |
+
// a bounded history of recent log lines and fans new lines out to every open
|
| 3 |
+
// subscriber, mirroring the log stream pattern used by the reference app.
|
| 4 |
+
package logs
|
| 5 |
+
|
| 6 |
+
import (
|
| 7 |
+
"context"
|
| 8 |
+
"sync"
|
| 9 |
+
)
|
| 10 |
+
|
| 11 |
+
// Hub is a bounded, thread-safe ring buffer of log lines plus a fan-out of new
|
| 12 |
+
// lines to subscribers. Slow subscribers are dropped rather than allowed to
|
| 13 |
+
// block the logger.
|
| 14 |
+
type Hub struct {
|
| 15 |
+
mu sync.Mutex
|
| 16 |
+
subs map[chan string]struct{}
|
| 17 |
+
history []string
|
| 18 |
+
max int
|
| 19 |
+
}
|
| 20 |
+
|
| 21 |
+
// NewHub returns a Hub that retains at most max recent lines.
|
| 22 |
+
func NewHub(max int) *Hub {
|
| 23 |
+
if max < 1 {
|
| 24 |
+
max = 1
|
| 25 |
+
}
|
| 26 |
+
return &Hub{
|
| 27 |
+
subs: make(map[chan string]struct{}),
|
| 28 |
+
max: max,
|
| 29 |
+
}
|
| 30 |
+
}
|
| 31 |
+
|
| 32 |
+
// Publish appends line to the history and delivers it to every subscriber.
|
| 33 |
+
func (h *Hub) Publish(line string) {
|
| 34 |
+
h.mu.Lock()
|
| 35 |
+
defer h.mu.Unlock()
|
| 36 |
+
|
| 37 |
+
h.history = append(h.history, line)
|
| 38 |
+
if len(h.history) > h.max {
|
| 39 |
+
h.history = h.history[len(h.history)-h.max:]
|
| 40 |
+
}
|
| 41 |
+
for ch := range h.subs {
|
| 42 |
+
select {
|
| 43 |
+
case ch <- line:
|
| 44 |
+
default: // subscriber backed up — drop the line for it
|
| 45 |
+
}
|
| 46 |
+
}
|
| 47 |
+
}
|
| 48 |
+
|
| 49 |
+
// History returns a copy of the retained lines, oldest first.
|
| 50 |
+
func (h *Hub) History() []string {
|
| 51 |
+
h.mu.Lock()
|
| 52 |
+
defer h.mu.Unlock()
|
| 53 |
+
out := make([]string, len(h.history))
|
| 54 |
+
copy(out, h.history)
|
| 55 |
+
return out
|
| 56 |
+
}
|
| 57 |
+
|
| 58 |
+
// Subscribe registers a new subscriber for the lifetime of ctx. The returned
|
| 59 |
+
// channel is closed when ctx is done or the hub is garbage collected.
|
| 60 |
+
func (h *Hub) Subscribe(ctx context.Context) <-chan string {
|
| 61 |
+
ch := make(chan string, 128)
|
| 62 |
+
h.mu.Lock()
|
| 63 |
+
h.subs[ch] = struct{}{}
|
| 64 |
+
h.mu.Unlock()
|
| 65 |
+
|
| 66 |
+
go func() {
|
| 67 |
+
<-ctx.Done()
|
| 68 |
+
h.mu.Lock()
|
| 69 |
+
delete(h.subs, ch)
|
| 70 |
+
close(ch)
|
| 71 |
+
h.mu.Unlock()
|
| 72 |
+
}()
|
| 73 |
+
return ch
|
| 74 |
+
}
|
internal/logs/hub_test.go
ADDED
|
@@ -0,0 +1,96 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
package logs
|
| 2 |
+
|
| 3 |
+
import (
|
| 4 |
+
"context"
|
| 5 |
+
"log/slog"
|
| 6 |
+
"strings"
|
| 7 |
+
"testing"
|
| 8 |
+
"time"
|
| 9 |
+
)
|
| 10 |
+
|
| 11 |
+
func TestHubHistoryBounded(t *testing.T) {
|
| 12 |
+
h := NewHub(3)
|
| 13 |
+
for i := 0; i < 5; i++ {
|
| 14 |
+
h.Publish("line-" + string(rune('a'+i)))
|
| 15 |
+
}
|
| 16 |
+
got := h.History()
|
| 17 |
+
want := []string{"line-c", "line-d", "line-e"}
|
| 18 |
+
if len(got) != len(want) {
|
| 19 |
+
t.Fatalf("History() = %v, want %v", got, want)
|
| 20 |
+
}
|
| 21 |
+
for i := range want {
|
| 22 |
+
if got[i] != want[i] {
|
| 23 |
+
t.Fatalf("History() = %v, want %v", got, want)
|
| 24 |
+
}
|
| 25 |
+
}
|
| 26 |
+
}
|
| 27 |
+
|
| 28 |
+
func TestHubSubscribeReceivesAndCloses(t *testing.T) {
|
| 29 |
+
h := NewHub(10)
|
| 30 |
+
ctx, cancel := context.WithCancel(context.Background())
|
| 31 |
+
defer cancel()
|
| 32 |
+
|
| 33 |
+
ch := h.Subscribe(ctx)
|
| 34 |
+
h.Publish("hello")
|
| 35 |
+
|
| 36 |
+
select {
|
| 37 |
+
case line := <-ch:
|
| 38 |
+
if line != "hello" {
|
| 39 |
+
t.Fatalf("got %q, want hello", line)
|
| 40 |
+
}
|
| 41 |
+
case <-time.After(time.Second):
|
| 42 |
+
t.Fatal("subscriber did not receive published line")
|
| 43 |
+
}
|
| 44 |
+
|
| 45 |
+
cancel()
|
| 46 |
+
select {
|
| 47 |
+
case _, ok := <-ch:
|
| 48 |
+
if ok {
|
| 49 |
+
t.Fatal("channel should be closed after context cancel")
|
| 50 |
+
}
|
| 51 |
+
case <-time.After(time.Second):
|
| 52 |
+
t.Fatal("channel not closed after context cancel")
|
| 53 |
+
}
|
| 54 |
+
}
|
| 55 |
+
|
| 56 |
+
func TestHubSlowSubscriberDoesNotBlock(t *testing.T) {
|
| 57 |
+
h := NewHub(10)
|
| 58 |
+
// A subscriber that never reads: Publish must still return promptly.
|
| 59 |
+
h.Subscribe(context.Background())
|
| 60 |
+
done := make(chan struct{})
|
| 61 |
+
go func() {
|
| 62 |
+
defer close(done)
|
| 63 |
+
for i := 0; i < 1000; i++ {
|
| 64 |
+
h.Publish("x")
|
| 65 |
+
}
|
| 66 |
+
}()
|
| 67 |
+
select {
|
| 68 |
+
case <-done:
|
| 69 |
+
case <-time.After(time.Second):
|
| 70 |
+
t.Fatal("Publish blocked on a slow subscriber")
|
| 71 |
+
}
|
| 72 |
+
}
|
| 73 |
+
|
| 74 |
+
func TestStreamHandlerPublishesAndForwards(t *testing.T) {
|
| 75 |
+
h := NewHub(10)
|
| 76 |
+
var buf strings.Builder
|
| 77 |
+
inner := slog.NewTextHandler(&buf, &slog.HandlerOptions{Level: slog.LevelInfo})
|
| 78 |
+
logger := slog.New(NewStreamHandler(inner, h))
|
| 79 |
+
|
| 80 |
+
logger.Info("database ready", "synced_at", 180820260136)
|
| 81 |
+
|
| 82 |
+
history := h.History()
|
| 83 |
+
if len(history) != 1 {
|
| 84 |
+
t.Fatalf("hub history = %v, want 1 line", history)
|
| 85 |
+
}
|
| 86 |
+
line := history[0]
|
| 87 |
+
if !strings.Contains(line, "INFO") || !strings.Contains(line, "database ready") {
|
| 88 |
+
t.Fatalf("stream line = %q, want INFO database ready", line)
|
| 89 |
+
}
|
| 90 |
+
if !strings.Contains(line, "synced_at=180820260136") {
|
| 91 |
+
t.Fatalf("stream line = %q, want synced_at attr", line)
|
| 92 |
+
}
|
| 93 |
+
if buf.Len() == 0 {
|
| 94 |
+
t.Fatal("inner handler did not receive the record")
|
| 95 |
+
}
|
| 96 |
+
}
|
internal/models/models.go
ADDED
|
@@ -0,0 +1,493 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
package models
|
| 2 |
+
|
| 3 |
+
import (
|
| 4 |
+
"context"
|
| 5 |
+
"database/sql"
|
| 6 |
+
"errors"
|
| 7 |
+
"fmt"
|
| 8 |
+
"strings"
|
| 9 |
+
"time"
|
| 10 |
+
)
|
| 11 |
+
|
| 12 |
+
// ErrNotFound is returned when a requested row does not exist.
|
| 13 |
+
var ErrNotFound = errors.New("not found")
|
| 14 |
+
|
| 15 |
+
// BookStatus values.
|
| 16 |
+
const (
|
| 17 |
+
StatusToRead = "to_read"
|
| 18 |
+
StatusReading = "reading"
|
| 19 |
+
StatusFinished = "finished"
|
| 20 |
+
)
|
| 21 |
+
|
| 22 |
+
// ValidStatus reports whether s is a legal book status.
|
| 23 |
+
func ValidStatus(s string) bool {
|
| 24 |
+
switch s {
|
| 25 |
+
case StatusToRead, StatusReading, StatusFinished:
|
| 26 |
+
return true
|
| 27 |
+
}
|
| 28 |
+
return false
|
| 29 |
+
}
|
| 30 |
+
|
| 31 |
+
// User is an account row.
|
| 32 |
+
type User struct {
|
| 33 |
+
ID int64
|
| 34 |
+
Email string
|
| 35 |
+
PasswordHash string
|
| 36 |
+
CreatedAt time.Time
|
| 37 |
+
}
|
| 38 |
+
|
| 39 |
+
// Session is a stored login session row.
|
| 40 |
+
type Session struct {
|
| 41 |
+
TokenHash string
|
| 42 |
+
UserID int64
|
| 43 |
+
ExpiresAt time.Time
|
| 44 |
+
}
|
| 45 |
+
|
| 46 |
+
// Book is a single shelf entry.
|
| 47 |
+
type Book struct {
|
| 48 |
+
ID int64
|
| 49 |
+
UserID int64
|
| 50 |
+
Title string
|
| 51 |
+
Author string
|
| 52 |
+
Status string
|
| 53 |
+
Rating *int
|
| 54 |
+
Review *string
|
| 55 |
+
CreatedAt time.Time
|
| 56 |
+
FinishedAt *time.Time
|
| 57 |
+
}
|
| 58 |
+
|
| 59 |
+
// Stars renders the 1-5 rating as ★/☆ text, or "" when unrated.
|
| 60 |
+
func (b Book) Stars() string {
|
| 61 |
+
if b.Rating == nil {
|
| 62 |
+
return ""
|
| 63 |
+
}
|
| 64 |
+
n := *b.Rating
|
| 65 |
+
if n < 1 {
|
| 66 |
+
n = 1
|
| 67 |
+
}
|
| 68 |
+
if n > 5 {
|
| 69 |
+
n = 5
|
| 70 |
+
}
|
| 71 |
+
return strings.Repeat("★", n) + strings.Repeat("☆", 5-n)
|
| 72 |
+
}
|
| 73 |
+
|
| 74 |
+
// RatingValue returns the rating as a plain int (0 when unrated).
|
| 75 |
+
func (b Book) RatingValue() int {
|
| 76 |
+
if b.Rating == nil {
|
| 77 |
+
return 0
|
| 78 |
+
}
|
| 79 |
+
return *b.Rating
|
| 80 |
+
}
|
| 81 |
+
|
| 82 |
+
// ReviewText returns the review text, or "" when absent.
|
| 83 |
+
func (b Book) ReviewText() string {
|
| 84 |
+
if b.Review == nil {
|
| 85 |
+
return ""
|
| 86 |
+
}
|
| 87 |
+
return *b.Review
|
| 88 |
+
}
|
| 89 |
+
|
| 90 |
+
// FinishedDate returns the formatted completion date, or "" when not finished.
|
| 91 |
+
func (b Book) FinishedDate() string {
|
| 92 |
+
if b.FinishedAt == nil {
|
| 93 |
+
return ""
|
| 94 |
+
}
|
| 95 |
+
return b.FinishedAt.Format("Jan 2, 2006")
|
| 96 |
+
}
|
| 97 |
+
|
| 98 |
+
// ReadingGoal is a yearly reading target.
|
| 99 |
+
type ReadingGoal struct {
|
| 100 |
+
UserID int64
|
| 101 |
+
Year int
|
| 102 |
+
Goal int
|
| 103 |
+
}
|
| 104 |
+
|
| 105 |
+
// Stats aggregates a user's shelf for the dashboard.
|
| 106 |
+
type Stats struct {
|
| 107 |
+
Total int
|
| 108 |
+
ToRead int
|
| 109 |
+
Reading int
|
| 110 |
+
Finished int
|
| 111 |
+
Goal int
|
| 112 |
+
FinishedYear int
|
| 113 |
+
Year int
|
| 114 |
+
}
|
| 115 |
+
|
| 116 |
+
// Progress returns the percentage (0-100) of this year's goal completed.
|
| 117 |
+
func (s Stats) Progress() int {
|
| 118 |
+
if s.Goal <= 0 {
|
| 119 |
+
return 0
|
| 120 |
+
}
|
| 121 |
+
p := s.FinishedYear * 100 / s.Goal
|
| 122 |
+
if p > 100 {
|
| 123 |
+
return 100
|
| 124 |
+
}
|
| 125 |
+
return p
|
| 126 |
+
}
|
| 127 |
+
|
| 128 |
+
// Store wraps all data access for the app.
|
| 129 |
+
type Store struct {
|
| 130 |
+
db *sql.DB
|
| 131 |
+
}
|
| 132 |
+
|
| 133 |
+
func NewStore(db *sql.DB) *Store { return &Store{db: db} }
|
| 134 |
+
|
| 135 |
+
// Ping verifies database connectivity.
|
| 136 |
+
func (s *Store) Ping(ctx context.Context) error {
|
| 137 |
+
return s.db.PingContext(ctx)
|
| 138 |
+
}
|
| 139 |
+
|
| 140 |
+
// --- Users ---
|
| 141 |
+
|
| 142 |
+
// sqliteTime converts a timestamp column value into time.Time. SQLite stores
|
| 143 |
+
// CURRENT_TIMESTAMP / datetime('now', ...) as "2006-01-02 15:04:05" TEXT,
|
| 144 |
+
// which the driver hands back as string/[]byte — database/sql cannot scan
|
| 145 |
+
// that directly into time.Time, so timestamp columns are scanned into `any`
|
| 146 |
+
// and converted here.
|
| 147 |
+
func sqliteTime(v any) (time.Time, error) {
|
| 148 |
+
switch t := v.(type) {
|
| 149 |
+
case nil:
|
| 150 |
+
return time.Time{}, nil
|
| 151 |
+
case time.Time:
|
| 152 |
+
return t, nil
|
| 153 |
+
case string:
|
| 154 |
+
return parseSQLiteTime(t)
|
| 155 |
+
case []byte:
|
| 156 |
+
return parseSQLiteTime(string(t))
|
| 157 |
+
default:
|
| 158 |
+
return time.Time{}, fmt.Errorf("unsupported timestamp type %T", v)
|
| 159 |
+
}
|
| 160 |
+
}
|
| 161 |
+
|
| 162 |
+
func parseSQLiteTime(s string) (time.Time, error) {
|
| 163 |
+
s = strings.TrimSpace(s)
|
| 164 |
+
if s == "" {
|
| 165 |
+
return time.Time{}, nil
|
| 166 |
+
}
|
| 167 |
+
for _, layout := range []string{
|
| 168 |
+
"2006-01-02 15:04:05",
|
| 169 |
+
"2006-01-02T15:04:05Z07:00",
|
| 170 |
+
time.RFC3339,
|
| 171 |
+
"2006-01-02",
|
| 172 |
+
} {
|
| 173 |
+
if tm, err := time.Parse(layout, s); err == nil {
|
| 174 |
+
return tm, nil
|
| 175 |
+
}
|
| 176 |
+
}
|
| 177 |
+
return time.Time{}, fmt.Errorf("unparseable timestamp %q", s)
|
| 178 |
+
}
|
| 179 |
+
|
| 180 |
+
// sqliteTimePtr is sqliteTime for nullable columns (NULL/"" -> nil).
|
| 181 |
+
func sqliteTimePtr(v any) (*time.Time, error) {
|
| 182 |
+
if v == nil {
|
| 183 |
+
return nil, nil
|
| 184 |
+
}
|
| 185 |
+
if s, ok := v.(string); ok && strings.TrimSpace(s) == "" {
|
| 186 |
+
return nil, nil
|
| 187 |
+
}
|
| 188 |
+
if b, ok := v.([]byte); ok && strings.TrimSpace(string(b)) == "" {
|
| 189 |
+
return nil, nil
|
| 190 |
+
}
|
| 191 |
+
tm, err := sqliteTime(v)
|
| 192 |
+
if err != nil {
|
| 193 |
+
return nil, err
|
| 194 |
+
}
|
| 195 |
+
return &tm, nil
|
| 196 |
+
}
|
| 197 |
+
|
| 198 |
+
func (s *Store) CreateUser(ctx context.Context, email, passwordHash string) (User, error) {
|
| 199 |
+
var u User
|
| 200 |
+
var created any
|
| 201 |
+
err := s.db.QueryRowContext(ctx,
|
| 202 |
+
`INSERT INTO users (email, password_hash) VALUES ($1, $2)
|
| 203 |
+
RETURNING id, email, password_hash, created_at`,
|
| 204 |
+
email, passwordHash).Scan(&u.ID, &u.Email, &u.PasswordHash, &created)
|
| 205 |
+
if err != nil {
|
| 206 |
+
return User{}, err
|
| 207 |
+
}
|
| 208 |
+
u.CreatedAt, err = sqliteTime(created)
|
| 209 |
+
return u, err
|
| 210 |
+
}
|
| 211 |
+
|
| 212 |
+
func (s *Store) UserByEmail(ctx context.Context, email string) (User, error) {
|
| 213 |
+
var u User
|
| 214 |
+
var created any
|
| 215 |
+
err := s.db.QueryRowContext(ctx,
|
| 216 |
+
`SELECT id, email, password_hash, created_at FROM users WHERE email = $1`,
|
| 217 |
+
email).Scan(&u.ID, &u.Email, &u.PasswordHash, &created)
|
| 218 |
+
if errors.Is(err, sql.ErrNoRows) {
|
| 219 |
+
return User{}, ErrNotFound
|
| 220 |
+
}
|
| 221 |
+
if err != nil {
|
| 222 |
+
return User{}, err
|
| 223 |
+
}
|
| 224 |
+
u.CreatedAt, err = sqliteTime(created)
|
| 225 |
+
return u, err
|
| 226 |
+
}
|
| 227 |
+
|
| 228 |
+
func (s *Store) UserByID(ctx context.Context, id int64) (User, error) {
|
| 229 |
+
var u User
|
| 230 |
+
var created any
|
| 231 |
+
err := s.db.QueryRowContext(ctx,
|
| 232 |
+
`SELECT id, email, password_hash, created_at FROM users WHERE id = $1`,
|
| 233 |
+
id).Scan(&u.ID, &u.Email, &u.PasswordHash, &created)
|
| 234 |
+
if errors.Is(err, sql.ErrNoRows) {
|
| 235 |
+
return User{}, ErrNotFound
|
| 236 |
+
}
|
| 237 |
+
if err != nil {
|
| 238 |
+
return User{}, err
|
| 239 |
+
}
|
| 240 |
+
u.CreatedAt, err = sqliteTime(created)
|
| 241 |
+
return u, err
|
| 242 |
+
}
|
| 243 |
+
|
| 244 |
+
// --- Sessions ---
|
| 245 |
+
|
| 246 |
+
func (s *Store) CreateSession(ctx context.Context, tokenHash string, userID int64, ttl time.Duration) error {
|
| 247 |
+
_, err := s.db.ExecContext(ctx,
|
| 248 |
+
`INSERT INTO sessions (token_hash, user_id, expires_at) VALUES (?, ?, datetime('now', ?))`,
|
| 249 |
+
tokenHash, userID, fmt.Sprintf("+%d seconds", int64(ttl/time.Second)))
|
| 250 |
+
return err
|
| 251 |
+
}
|
| 252 |
+
|
| 253 |
+
// UserForSession resolves a token hash to its user, deleting expired sessions.
|
| 254 |
+
func (s *Store) UserForSession(ctx context.Context, tokenHash string) (User, error) {
|
| 255 |
+
var (
|
| 256 |
+
u User
|
| 257 |
+
created any
|
| 258 |
+
expires any
|
| 259 |
+
)
|
| 260 |
+
err := s.db.QueryRowContext(ctx,
|
| 261 |
+
`SELECT u.id, u.email, u.password_hash, u.created_at, s.expires_at
|
| 262 |
+
FROM sessions s JOIN users u ON u.id = s.user_id
|
| 263 |
+
WHERE s.token_hash = $1`,
|
| 264 |
+
tokenHash).Scan(&u.ID, &u.Email, &u.PasswordHash, &created, &expires)
|
| 265 |
+
if errors.Is(err, sql.ErrNoRows) {
|
| 266 |
+
return User{}, ErrNotFound
|
| 267 |
+
}
|
| 268 |
+
if err != nil {
|
| 269 |
+
return User{}, err
|
| 270 |
+
}
|
| 271 |
+
if u.CreatedAt, err = sqliteTime(created); err != nil {
|
| 272 |
+
return User{}, err
|
| 273 |
+
}
|
| 274 |
+
expiresAt, err := sqliteTime(expires)
|
| 275 |
+
if err != nil {
|
| 276 |
+
return User{}, err
|
| 277 |
+
}
|
| 278 |
+
if time.Now().After(expiresAt) {
|
| 279 |
+
_, _ = s.db.ExecContext(ctx, `DELETE FROM sessions WHERE token_hash = ?`, tokenHash)
|
| 280 |
+
return User{}, ErrNotFound
|
| 281 |
+
}
|
| 282 |
+
return u, nil
|
| 283 |
+
}
|
| 284 |
+
|
| 285 |
+
func (s *Store) DeleteSession(ctx context.Context, tokenHash string) error {
|
| 286 |
+
_, err := s.db.ExecContext(ctx, `DELETE FROM sessions WHERE token_hash = ?`, tokenHash)
|
| 287 |
+
return err
|
| 288 |
+
}
|
| 289 |
+
|
| 290 |
+
// --- Books ---
|
| 291 |
+
|
| 292 |
+
// BookFilter narrows a book listing.
|
| 293 |
+
type BookFilter struct {
|
| 294 |
+
Status string
|
| 295 |
+
Search string
|
| 296 |
+
}
|
| 297 |
+
|
| 298 |
+
// ListBooks returns a user's books, newest first, optionally filtered.
|
| 299 |
+
func (s *Store) ListBooks(ctx context.Context, userID int64, f BookFilter) ([]Book, error) {
|
| 300 |
+
query := `SELECT id, user_id, title, author, status, rating, review, created_at, finished_at
|
| 301 |
+
FROM books WHERE user_id = ?`
|
| 302 |
+
args := []any{userID}
|
| 303 |
+
if f.Status != "" {
|
| 304 |
+
query += ` AND status = ?`
|
| 305 |
+
args = append(args, f.Status)
|
| 306 |
+
}
|
| 307 |
+
if f.Search != "" {
|
| 308 |
+
query += ` AND (lower(title) LIKE lower(?) OR lower(author) LIKE lower(?))`
|
| 309 |
+
args = append(args, "%"+f.Search+"%", "%"+f.Search+"%")
|
| 310 |
+
}
|
| 311 |
+
query += ` ORDER BY created_at DESC LIMIT 200`
|
| 312 |
+
|
| 313 |
+
rows, err := s.db.QueryContext(ctx, query, args...)
|
| 314 |
+
if err != nil {
|
| 315 |
+
return nil, err
|
| 316 |
+
}
|
| 317 |
+
defer rows.Close()
|
| 318 |
+
|
| 319 |
+
var books []Book
|
| 320 |
+
for rows.Next() {
|
| 321 |
+
var b Book
|
| 322 |
+
var created, finished any
|
| 323 |
+
if err := rows.Scan(&b.ID, &b.UserID, &b.Title, &b.Author, &b.Status,
|
| 324 |
+
&b.Rating, &b.Review, &created, &finished); err != nil {
|
| 325 |
+
return nil, err
|
| 326 |
+
}
|
| 327 |
+
if b.CreatedAt, err = sqliteTime(created); err != nil {
|
| 328 |
+
return nil, err
|
| 329 |
+
}
|
| 330 |
+
if b.FinishedAt, err = sqliteTimePtr(finished); err != nil {
|
| 331 |
+
return nil, err
|
| 332 |
+
}
|
| 333 |
+
books = append(books, b)
|
| 334 |
+
}
|
| 335 |
+
return books, rows.Err()
|
| 336 |
+
}
|
| 337 |
+
|
| 338 |
+
// CreateBook inserts a book, marking finished_at when status is finished.
|
| 339 |
+
func (s *Store) CreateBook(ctx context.Context, userID int64, title, author, status string) (Book, error) {
|
| 340 |
+
var b Book
|
| 341 |
+
var created, finished any
|
| 342 |
+
err := s.db.QueryRowContext(ctx,
|
| 343 |
+
`INSERT INTO books (user_id, title, author, status, finished_at)
|
| 344 |
+
VALUES (?, ?, ?, ?, CASE WHEN ? = 'finished' THEN CURRENT_TIMESTAMP END)
|
| 345 |
+
RETURNING id, user_id, title, author, status, rating, review, created_at, finished_at`,
|
| 346 |
+
userID, title, author, status, status).
|
| 347 |
+
Scan(&b.ID, &b.UserID, &b.Title, &b.Author, &b.Status, &b.Rating, &b.Review, &created, &finished)
|
| 348 |
+
if err != nil {
|
| 349 |
+
return Book{}, err
|
| 350 |
+
}
|
| 351 |
+
if b.CreatedAt, err = sqliteTime(created); err != nil {
|
| 352 |
+
return Book{}, err
|
| 353 |
+
}
|
| 354 |
+
b.FinishedAt, err = sqliteTimePtr(finished)
|
| 355 |
+
return b, err
|
| 356 |
+
}
|
| 357 |
+
|
| 358 |
+
func (s *Store) BookByID(ctx context.Context, userID, bookID int64) (Book, error) {
|
| 359 |
+
var b Book
|
| 360 |
+
var created, finished any
|
| 361 |
+
err := s.db.QueryRowContext(ctx,
|
| 362 |
+
`SELECT id, user_id, title, author, status, rating, review, created_at, finished_at
|
| 363 |
+
FROM books WHERE id = $1 AND user_id = $2`,
|
| 364 |
+
bookID, userID).
|
| 365 |
+
Scan(&b.ID, &b.UserID, &b.Title, &b.Author, &b.Status, &b.Rating, &b.Review, &created, &finished)
|
| 366 |
+
if errors.Is(err, sql.ErrNoRows) {
|
| 367 |
+
return Book{}, ErrNotFound
|
| 368 |
+
}
|
| 369 |
+
if err != nil {
|
| 370 |
+
return Book{}, err
|
| 371 |
+
}
|
| 372 |
+
if b.CreatedAt, err = sqliteTime(created); err != nil {
|
| 373 |
+
return Book{}, err
|
| 374 |
+
}
|
| 375 |
+
b.FinishedAt, err = sqliteTimePtr(finished)
|
| 376 |
+
return b, err
|
| 377 |
+
}
|
| 378 |
+
|
| 379 |
+
// UpdateBook applies editable fields. Empty status keeps the current value.
|
| 380 |
+
// Transitioning to/from "finished" maintains finished_at.
|
| 381 |
+
func (s *Store) UpdateBook(ctx context.Context, userID, bookID int64, title, author, status string, rating *int, review *string) error {
|
| 382 |
+
tag, err := s.db.ExecContext(ctx,
|
| 383 |
+
`UPDATE books SET
|
| 384 |
+
title = ?, author = ?,
|
| 385 |
+
status = ?,
|
| 386 |
+
rating = ?,
|
| 387 |
+
review = ?,
|
| 388 |
+
finished_at = CASE
|
| 389 |
+
WHEN ? = 'finished' AND finished_at IS NULL THEN CURRENT_TIMESTAMP
|
| 390 |
+
WHEN ? <> 'finished' THEN NULL
|
| 391 |
+
ELSE finished_at END
|
| 392 |
+
WHERE id = ? AND user_id = ?`,
|
| 393 |
+
title, author, status, rating, review, status, status, bookID, userID)
|
| 394 |
+
if err != nil {
|
| 395 |
+
return err
|
| 396 |
+
}
|
| 397 |
+
rowsAffected, err := tag.RowsAffected()
|
| 398 |
+
if err != nil {
|
| 399 |
+
return err
|
| 400 |
+
}
|
| 401 |
+
if rowsAffected == 0 {
|
| 402 |
+
return ErrNotFound
|
| 403 |
+
}
|
| 404 |
+
return nil
|
| 405 |
+
}
|
| 406 |
+
|
| 407 |
+
// SetBookStatus is a quick single-field update used by the HTMX status select.
|
| 408 |
+
func (s *Store) SetBookStatus(ctx context.Context, userID, bookID int64, status string) error {
|
| 409 |
+
tag, err := s.db.ExecContext(ctx,
|
| 410 |
+
`UPDATE books SET status = ?,
|
| 411 |
+
finished_at = CASE
|
| 412 |
+
WHEN ? = 'finished' AND finished_at IS NULL THEN CURRENT_TIMESTAMP
|
| 413 |
+
WHEN ? <> 'finished' THEN NULL
|
| 414 |
+
ELSE finished_at END
|
| 415 |
+
WHERE id = ? AND user_id = ?`,
|
| 416 |
+
status, status, status, bookID, userID)
|
| 417 |
+
if err != nil {
|
| 418 |
+
return err
|
| 419 |
+
}
|
| 420 |
+
rowsAffected, err := tag.RowsAffected()
|
| 421 |
+
if err != nil {
|
| 422 |
+
return err
|
| 423 |
+
}
|
| 424 |
+
if rowsAffected == 0 {
|
| 425 |
+
return ErrNotFound
|
| 426 |
+
}
|
| 427 |
+
return nil
|
| 428 |
+
}
|
| 429 |
+
|
| 430 |
+
func (s *Store) DeleteBook(ctx context.Context, userID, bookID int64) error {
|
| 431 |
+
tag, err := s.db.ExecContext(ctx, `DELETE FROM books WHERE id = ? AND user_id = ?`, bookID, userID)
|
| 432 |
+
if err != nil {
|
| 433 |
+
return err
|
| 434 |
+
}
|
| 435 |
+
rowsAffected, err := tag.RowsAffected()
|
| 436 |
+
if err != nil {
|
| 437 |
+
return err
|
| 438 |
+
}
|
| 439 |
+
if rowsAffected == 0 {
|
| 440 |
+
return ErrNotFound
|
| 441 |
+
}
|
| 442 |
+
return nil
|
| 443 |
+
}
|
| 444 |
+
|
| 445 |
+
// --- Reading goals ---
|
| 446 |
+
|
| 447 |
+
func (s *Store) GetGoal(ctx context.Context, userID int64, year int) (ReadingGoal, error) {
|
| 448 |
+
var g ReadingGoal
|
| 449 |
+
err := s.db.QueryRowContext(ctx,
|
| 450 |
+
`SELECT user_id, year, goal FROM reading_goals WHERE user_id = $1 AND year = $2`,
|
| 451 |
+
userID, year).Scan(&g.UserID, &g.Year, &g.Goal)
|
| 452 |
+
if errors.Is(err, sql.ErrNoRows) {
|
| 453 |
+
return ReadingGoal{}, ErrNotFound
|
| 454 |
+
}
|
| 455 |
+
return g, err
|
| 456 |
+
}
|
| 457 |
+
|
| 458 |
+
// UpsertGoal sets the reading goal for a user/year.
|
| 459 |
+
func (s *Store) UpsertGoal(ctx context.Context, userID int64, year, goal int) error {
|
| 460 |
+
_, err := s.db.ExecContext(ctx,
|
| 461 |
+
`INSERT INTO reading_goals (user_id, year, goal)
|
| 462 |
+
VALUES (?, ?, ?)
|
| 463 |
+
ON CONFLICT (user_id) DO UPDATE SET goal = excluded.goal, year = excluded.year, updated_at = CURRENT_TIMESTAMP`,
|
| 464 |
+
userID, year, goal)
|
| 465 |
+
return err
|
| 466 |
+
}
|
| 467 |
+
|
| 468 |
+
// --- Stats ---
|
| 469 |
+
|
| 470 |
+
// StatsFor returns dashboard aggregates for the given user and year.
|
| 471 |
+
func (s *Store) StatsFor(ctx context.Context, userID int64, year int) (Stats, error) {
|
| 472 |
+
var st Stats
|
| 473 |
+
st.Year = year
|
| 474 |
+
err := s.db.QueryRowContext(ctx,
|
| 475 |
+
`SELECT
|
| 476 |
+
sum(CASE WHEN status = 'to_read' THEN 1 ELSE 0 END),
|
| 477 |
+
sum(CASE WHEN status = 'reading' THEN 1 ELSE 0 END),
|
| 478 |
+
sum(CASE WHEN status = 'finished' THEN 1 ELSE 0 END),
|
| 479 |
+
sum(CASE WHEN status = 'finished' AND strftime('%Y', coalesce(finished_at, created_at)) = ? THEN 1 ELSE 0 END),
|
| 480 |
+
count(*)
|
| 481 |
+
FROM books WHERE user_id = ?`,
|
| 482 |
+
fmt.Sprintf("%04d", year), userID).Scan(&st.ToRead, &st.Reading, &st.Finished, &st.FinishedYear, &st.Total)
|
| 483 |
+
if err != nil {
|
| 484 |
+
return Stats{}, err
|
| 485 |
+
}
|
| 486 |
+
g, err := s.GetGoal(ctx, userID, year)
|
| 487 |
+
if err == nil {
|
| 488 |
+
st.Goal = g.Goal
|
| 489 |
+
} else if !errors.Is(err, ErrNotFound) {
|
| 490 |
+
return Stats{}, err
|
| 491 |
+
}
|
| 492 |
+
return st, nil
|
| 493 |
+
}
|
internal/models/models_test.go
ADDED
|
@@ -0,0 +1,92 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
package models
|
| 2 |
+
|
| 3 |
+
import (
|
| 4 |
+
"strings"
|
| 5 |
+
"testing"
|
| 6 |
+
"time"
|
| 7 |
+
)
|
| 8 |
+
|
| 9 |
+
func TestValidStatus(t *testing.T) {
|
| 10 |
+
for _, s := range []string{StatusToRead, StatusReading, StatusFinished} {
|
| 11 |
+
if !ValidStatus(s) {
|
| 12 |
+
t.Errorf("expected %q to be valid", s)
|
| 13 |
+
}
|
| 14 |
+
}
|
| 15 |
+
for _, s := range []string{"", "read", "DONE", "finished "} {
|
| 16 |
+
if ValidStatus(s) {
|
| 17 |
+
t.Errorf("expected %q to be invalid", s)
|
| 18 |
+
}
|
| 19 |
+
}
|
| 20 |
+
}
|
| 21 |
+
|
| 22 |
+
func TestStatsProgress(t *testing.T) {
|
| 23 |
+
cases := []struct {
|
| 24 |
+
goal, finished int
|
| 25 |
+
want int
|
| 26 |
+
}{
|
| 27 |
+
{10, 0, 0},
|
| 28 |
+
{10, 5, 50},
|
| 29 |
+
{10, 10, 100},
|
| 30 |
+
{10, 15, 100}, // over-achievement caps at 100
|
| 31 |
+
{0, 5, 0}, // no goal → no progress
|
| 32 |
+
}
|
| 33 |
+
for _, c := range cases {
|
| 34 |
+
s := Stats{Goal: c.goal, FinishedYear: c.finished}
|
| 35 |
+
if got := s.Progress(); got != c.want {
|
| 36 |
+
t.Errorf("Progress(goal=%d, finished=%d) = %d, want %d", c.goal, c.finished, got, c.want)
|
| 37 |
+
}
|
| 38 |
+
}
|
| 39 |
+
}
|
| 40 |
+
|
| 41 |
+
func TestBookStars(t *testing.T) {
|
| 42 |
+
r := func(n int) *int { return &n }
|
| 43 |
+
|
| 44 |
+
cases := []struct {
|
| 45 |
+
rating *int
|
| 46 |
+
want string
|
| 47 |
+
}{
|
| 48 |
+
{nil, ""},
|
| 49 |
+
{r(5), "★★★★★"},
|
| 50 |
+
{r(3), "★★★☆☆"},
|
| 51 |
+
{r(1), "★☆☆☆☆"},
|
| 52 |
+
{r(0), "★☆☆☆☆"}, // clamped up
|
| 53 |
+
{r(9), "★★★★★"}, // clamped down
|
| 54 |
+
}
|
| 55 |
+
for _, c := range cases {
|
| 56 |
+
b := Book{Rating: c.rating}
|
| 57 |
+
if got := b.Stars(); got != c.want {
|
| 58 |
+
t.Errorf("Stars(%v) = %q, want %q", c.rating, got, c.want)
|
| 59 |
+
}
|
| 60 |
+
}
|
| 61 |
+
}
|
| 62 |
+
|
| 63 |
+
func TestBookRatingValueAndText(t *testing.T) {
|
| 64 |
+
r := 4
|
| 65 |
+
b := Book{Rating: &r}
|
| 66 |
+
if b.RatingValue() != 4 {
|
| 67 |
+
t.Errorf("RatingValue() = %d, want 4", b.RatingValue())
|
| 68 |
+
}
|
| 69 |
+
if (Book{}).RatingValue() != 0 {
|
| 70 |
+
t.Error("unrated book must report 0")
|
| 71 |
+
}
|
| 72 |
+
|
| 73 |
+
review := "loved it"
|
| 74 |
+
b2 := Book{Review: &review}
|
| 75 |
+
if b2.ReviewText() != "loved it" {
|
| 76 |
+
t.Errorf("ReviewText() = %q", b2.ReviewText())
|
| 77 |
+
}
|
| 78 |
+
if (Book{}).ReviewText() != "" {
|
| 79 |
+
t.Error("nil review must be empty string")
|
| 80 |
+
}
|
| 81 |
+
}
|
| 82 |
+
|
| 83 |
+
func TestBookFinishedDate(t *testing.T) {
|
| 84 |
+
if (Book{}).FinishedDate() != "" {
|
| 85 |
+
t.Error("unfinished book must have no date")
|
| 86 |
+
}
|
| 87 |
+
when := time.Date(2026, 3, 15, 0, 0, 0, 0, time.UTC)
|
| 88 |
+
b := Book{FinishedAt: &when}
|
| 89 |
+
if !strings.Contains(b.FinishedDate(), "2026") {
|
| 90 |
+
t.Errorf("FinishedDate() = %q, want a 2026 date", b.FinishedDate())
|
| 91 |
+
}
|
| 92 |
+
}
|
internal/selfping/selfping.go
ADDED
|
@@ -0,0 +1,72 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
// Package selfping keeps a hosting platform (e.g. a Hugging Face Space,
|
| 2 |
+
// which sleeps after inactivity) warm by GET-ing the app's own public URL
|
| 3 |
+
// on a fixed interval. Traffic goes through the platform's public proxy, so
|
| 4 |
+
// each tick counts as incoming activity.
|
| 5 |
+
//
|
| 6 |
+
// The scheduler is opt-in: see SELF_PING_ENABLED / SELF_PING_URL /
|
| 7 |
+
// SELF_PING_INTERVAL in internal/config. A failed ping is logged and the
|
| 8 |
+
// schedule continues; Run returns only when ctx is cancelled.
|
| 9 |
+
package selfping
|
| 10 |
+
|
| 11 |
+
import (
|
| 12 |
+
"context"
|
| 13 |
+
"io"
|
| 14 |
+
"log/slog"
|
| 15 |
+
"net/http"
|
| 16 |
+
"time"
|
| 17 |
+
)
|
| 18 |
+
|
| 19 |
+
// requestTimeout bounds a single ping so one slow probe can never overlap
|
| 20 |
+
// the next tick.
|
| 21 |
+
const requestTimeout = 15 * time.Second
|
| 22 |
+
|
| 23 |
+
// Run pings url every interval until ctx is cancelled. The first probe fires
|
| 24 |
+
// after one interval (not immediately) so the server is listening by then.
|
| 25 |
+
func Run(ctx context.Context, log *slog.Logger, url string, interval time.Duration) {
|
| 26 |
+
if url == "" {
|
| 27 |
+
log.Warn("self-ping idle: no URL configured")
|
| 28 |
+
return
|
| 29 |
+
}
|
| 30 |
+
if interval <= 0 {
|
| 31 |
+
log.Warn("self-ping idle: non-positive interval", "interval", interval)
|
| 32 |
+
return
|
| 33 |
+
}
|
| 34 |
+
log.Info("self-ping scheduler armed", "url", url, "interval", interval)
|
| 35 |
+
ticker := time.NewTicker(interval)
|
| 36 |
+
defer ticker.Stop()
|
| 37 |
+
for {
|
| 38 |
+
select {
|
| 39 |
+
case <-ctx.Done():
|
| 40 |
+
log.Info("self-ping scheduler stopped")
|
| 41 |
+
return
|
| 42 |
+
case at := <-ticker.C:
|
| 43 |
+
pingOnce(log, url, at)
|
| 44 |
+
}
|
| 45 |
+
}
|
| 46 |
+
}
|
| 47 |
+
|
| 48 |
+
// pingOnce performs a single GET and logs the outcome (status only, the body
|
| 49 |
+
// is discarded). It is a separate function so tests can drive it directly.
|
| 50 |
+
func pingOnce(log *slog.Logger, url string, at time.Time) {
|
| 51 |
+
ctx, cancel := context.WithTimeout(context.Background(), requestTimeout)
|
| 52 |
+
defer cancel()
|
| 53 |
+
req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)
|
| 54 |
+
if err != nil {
|
| 55 |
+
log.Error("self-ping request build failed", "error", err)
|
| 56 |
+
return
|
| 57 |
+
}
|
| 58 |
+
start := time.Now()
|
| 59 |
+
resp, err := http.DefaultClient.Do(req)
|
| 60 |
+
latency := time.Since(start)
|
| 61 |
+
if err != nil {
|
| 62 |
+
log.Warn("self-ping failed", "url", url, "latency", latency, "error", err)
|
| 63 |
+
return
|
| 64 |
+
}
|
| 65 |
+
io.Copy(io.Discard, io.LimitReader(resp.Body, 4<<10))
|
| 66 |
+
resp.Body.Close()
|
| 67 |
+
if resp.StatusCode != http.StatusOK {
|
| 68 |
+
log.Warn("self-ping unhealthy", "url", url, "status", resp.StatusCode, "latency", latency, "tick", at.UTC().Format(time.RFC3339))
|
| 69 |
+
return
|
| 70 |
+
}
|
| 71 |
+
log.Info("self-ping ok", "url", url, "status", resp.StatusCode, "latency", latency)
|
| 72 |
+
}
|
internal/selfping/selfping_test.go
ADDED
|
@@ -0,0 +1,87 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
package selfping
|
| 2 |
+
|
| 3 |
+
import (
|
| 4 |
+
"context"
|
| 5 |
+
"io"
|
| 6 |
+
"log/slog"
|
| 7 |
+
"net/http"
|
| 8 |
+
"net/http/httptest"
|
| 9 |
+
"sync/atomic"
|
| 10 |
+
"testing"
|
| 11 |
+
"time"
|
| 12 |
+
)
|
| 13 |
+
|
| 14 |
+
func testLogger() *slog.Logger {
|
| 15 |
+
return slog.New(slog.NewTextHandler(io.Discard, nil))
|
| 16 |
+
}
|
| 17 |
+
|
| 18 |
+
func TestPingOnceSuccess(t *testing.T) {
|
| 19 |
+
var hits atomic.Int32
|
| 20 |
+
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
| 21 |
+
hits.Add(1)
|
| 22 |
+
w.WriteHeader(http.StatusOK)
|
| 23 |
+
}))
|
| 24 |
+
defer srv.Close()
|
| 25 |
+
|
| 26 |
+
pingOnce(testLogger(), srv.URL, time.Now())
|
| 27 |
+
if hits.Load() != 1 {
|
| 28 |
+
t.Fatalf("expected 1 hit, got %d", hits.Load())
|
| 29 |
+
}
|
| 30 |
+
}
|
| 31 |
+
|
| 32 |
+
func TestPingOnceUnhealthyDoesNotPanic(t *testing.T) {
|
| 33 |
+
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
| 34 |
+
w.WriteHeader(http.StatusServiceUnavailable)
|
| 35 |
+
}))
|
| 36 |
+
defer srv.Close()
|
| 37 |
+
|
| 38 |
+
// Must return (and log a warning) rather than propagate an error.
|
| 39 |
+
pingOnce(testLogger(), srv.URL, time.Now())
|
| 40 |
+
}
|
| 41 |
+
|
| 42 |
+
func TestPingOnceBadURL(t *testing.T) {
|
| 43 |
+
// Unreachable port: must log and return, never block past the timeout.
|
| 44 |
+
pingOnce(testLogger(), "http://127.0.0.1:1/healthz", time.Now())
|
| 45 |
+
}
|
| 46 |
+
|
| 47 |
+
func TestRunTicksAndStops(t *testing.T) {
|
| 48 |
+
var hits atomic.Int32
|
| 49 |
+
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
| 50 |
+
hits.Add(1)
|
| 51 |
+
w.WriteHeader(http.StatusOK)
|
| 52 |
+
}))
|
| 53 |
+
defer srv.Close()
|
| 54 |
+
|
| 55 |
+
ctx, cancel := context.WithCancel(context.Background())
|
| 56 |
+
done := make(chan struct{})
|
| 57 |
+
go func() {
|
| 58 |
+
defer close(done)
|
| 59 |
+
Run(ctx, testLogger(), srv.URL, 20*time.Millisecond)
|
| 60 |
+
}()
|
| 61 |
+
time.Sleep(120 * time.Millisecond)
|
| 62 |
+
cancel()
|
| 63 |
+
select {
|
| 64 |
+
case <-done:
|
| 65 |
+
case <-time.After(2 * time.Second):
|
| 66 |
+
t.Fatal("Run did not return after context cancel")
|
| 67 |
+
}
|
| 68 |
+
if hits.Load() == 0 {
|
| 69 |
+
t.Fatal("expected at least one tick while context was live")
|
| 70 |
+
}
|
| 71 |
+
}
|
| 72 |
+
|
| 73 |
+
func TestRunIdleOnEmptyURL(t *testing.T) {
|
| 74 |
+
ctx, cancel := context.WithCancel(context.Background())
|
| 75 |
+
done := make(chan struct{})
|
| 76 |
+
go func() {
|
| 77 |
+
defer close(done)
|
| 78 |
+
Run(ctx, testLogger(), "", time.Minute)
|
| 79 |
+
}()
|
| 80 |
+
select {
|
| 81 |
+
case <-done:
|
| 82 |
+
case <-time.After(2 * time.Second):
|
| 83 |
+
cancel()
|
| 84 |
+
t.Fatal("Run with empty URL did not return immediately")
|
| 85 |
+
}
|
| 86 |
+
cancel()
|
| 87 |
+
}
|
internal/web/handlers.go
ADDED
|
@@ -0,0 +1,203 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
package web
|
| 2 |
+
|
| 3 |
+
import (
|
| 4 |
+
"context"
|
| 5 |
+
"encoding/json"
|
| 6 |
+
"fmt"
|
| 7 |
+
"net/http"
|
| 8 |
+
"strings"
|
| 9 |
+
"time"
|
| 10 |
+
|
| 11 |
+
"pageturner/internal/auth"
|
| 12 |
+
"pageturner/internal/models"
|
| 13 |
+
)
|
| 14 |
+
|
| 15 |
+
// pageData carries everything templates need.
|
| 16 |
+
type pageData struct {
|
| 17 |
+
User models.User
|
| 18 |
+
CSRF string
|
| 19 |
+
Error string
|
| 20 |
+
Email string
|
| 21 |
+
// Bare renders the page chromeless (no nav, no footer) for full-viewport
|
| 22 |
+
// app screens like /markitdown.
|
| 23 |
+
Bare bool
|
| 24 |
+
}
|
| 25 |
+
|
| 26 |
+
// --- Health ---
|
| 27 |
+
|
| 28 |
+
func (s *Server) handleHealth(w http.ResponseWriter, r *http.Request) {
|
| 29 |
+
ctx, cancel := context.WithTimeout(r.Context(), 2*time.Second)
|
| 30 |
+
defer cancel()
|
| 31 |
+
if err := s.store.Ping(ctx); err != nil {
|
| 32 |
+
w.Header().Set("Content-Type", "application/json")
|
| 33 |
+
w.WriteHeader(http.StatusServiceUnavailable)
|
| 34 |
+
json.NewEncoder(w).Encode(map[string]string{"status": "unhealthy", "error": err.Error()}) //nolint:errcheck
|
| 35 |
+
return
|
| 36 |
+
}
|
| 37 |
+
w.Header().Set("Content-Type", "application/json")
|
| 38 |
+
json.NewEncoder(w).Encode(map[string]string{"status": "ok"}) //nolint:errcheck
|
| 39 |
+
}
|
| 40 |
+
|
| 41 |
+
// --- Home (public landing) ---
|
| 42 |
+
|
| 43 |
+
func (s *Server) handleHome(w http.ResponseWriter, r *http.Request) {
|
| 44 |
+
render(w, r, "home", pageData{User: userFrom(r), CSRF: csrfFrom(r)})
|
| 45 |
+
}
|
| 46 |
+
|
| 47 |
+
// --- Auth ---
|
| 48 |
+
|
| 49 |
+
func (s *Server) handleLoginGet(w http.ResponseWriter, r *http.Request) {
|
| 50 |
+
if _, err := r.Cookie("session"); err == nil {
|
| 51 |
+
http.Redirect(w, r, "/markitdown", http.StatusSeeOther)
|
| 52 |
+
return
|
| 53 |
+
}
|
| 54 |
+
render(w, r, "login", pageData{CSRF: csrfFrom(r)})
|
| 55 |
+
}
|
| 56 |
+
|
| 57 |
+
func (s *Server) handleLoginPost(w http.ResponseWriter, r *http.Request) {
|
| 58 |
+
email := strings.TrimSpace(r.FormValue("email"))
|
| 59 |
+
password := r.FormValue("password")
|
| 60 |
+
|
| 61 |
+
user, err := s.store.UserByEmail(r.Context(), strings.ToLower(email))
|
| 62 |
+
if err != nil || !auth.CheckPassword(user.PasswordHash, password) {
|
| 63 |
+
render(w, r, "login", pageData{CSRF: csrfFrom(r), Email: email, Error: "Invalid email or password."})
|
| 64 |
+
return
|
| 65 |
+
}
|
| 66 |
+
s.startSession(w, r, user)
|
| 67 |
+
http.Redirect(w, r, "/markitdown", http.StatusSeeOther)
|
| 68 |
+
}
|
| 69 |
+
|
| 70 |
+
func (s *Server) handleLogout(w http.ResponseWriter, r *http.Request) {
|
| 71 |
+
if c, err := r.Cookie("session"); err == nil {
|
| 72 |
+
_ = s.store.DeleteSession(r.Context(), auth.HashToken(c.Value))
|
| 73 |
+
}
|
| 74 |
+
http.SetCookie(w, s.sessionCookie("", -1))
|
| 75 |
+
http.SetCookie(w, s.csrfCookie("", -1))
|
| 76 |
+
http.Redirect(w, r, "/login", http.StatusSeeOther)
|
| 77 |
+
}
|
| 78 |
+
|
| 79 |
+
// startSession creates a DB session, rotates the CSRF token, and sets cookies.
|
| 80 |
+
func (s *Server) startSession(w http.ResponseWriter, r *http.Request, user models.User) {
|
| 81 |
+
token, err := auth.NewToken()
|
| 82 |
+
if err != nil {
|
| 83 |
+
render(w, r, "login", pageData{CSRF: csrfFrom(r), Email: user.Email, Error: "Could not create session. Please try again."})
|
| 84 |
+
return
|
| 85 |
+
}
|
| 86 |
+
if err := s.store.CreateSession(r.Context(), auth.HashToken(token), user.ID, s.cfg.SessionTTL); err != nil {
|
| 87 |
+
render(w, r, "login", pageData{CSRF: csrfFrom(r), Email: user.Email, Error: "Could not create session. Please try again."})
|
| 88 |
+
return
|
| 89 |
+
}
|
| 90 |
+
http.SetCookie(w, s.sessionCookie(token, s.ttlSeconds()))
|
| 91 |
+
|
| 92 |
+
csrf := newCSRFOrEmpty()
|
| 93 |
+
http.SetCookie(w, s.csrfCookie(csrf, s.ttlSeconds()))
|
| 94 |
+
}
|
| 95 |
+
|
| 96 |
+
// --- Markitdown (authenticated) ---
|
| 97 |
+
|
| 98 |
+
func (s *Server) handleMarkitdown(w http.ResponseWriter, r *http.Request) {
|
| 99 |
+
user, ok := s.requireUser(r)
|
| 100 |
+
if !ok {
|
| 101 |
+
http.Error(w, "unauthorized", http.StatusUnauthorized)
|
| 102 |
+
return
|
| 103 |
+
}
|
| 104 |
+
render(w, r, "markitdown", pageData{User: user, CSRF: csrfFrom(r), Bare: true})
|
| 105 |
+
}
|
| 106 |
+
|
| 107 |
+
// sseChunk mimics one OpenAI chat-completion streaming delta.
|
| 108 |
+
type sseChunk struct {
|
| 109 |
+
Delta string `json:"delta"`
|
| 110 |
+
Done bool `json:"done"`
|
| 111 |
+
}
|
| 112 |
+
|
| 113 |
+
// handleMarkitdownStream streams a dummy "OpenAI" response as SSE: an invoice
|
| 114 |
+
// extracted as markdown, chunked word-by-word so the right panel can render
|
| 115 |
+
// it live like a PDF extraction.
|
| 116 |
+
func (s *Server) handleMarkitdownStream(w http.ResponseWriter, r *http.Request) {
|
| 117 |
+
if _, ok := s.requireUser(r); !ok {
|
| 118 |
+
http.Error(w, "unauthorized", http.StatusUnauthorized)
|
| 119 |
+
return
|
| 120 |
+
}
|
| 121 |
+
rc := http.NewResponseController(w)
|
| 122 |
+
_ = rc.SetWriteDeadline(time.Time{})
|
| 123 |
+
|
| 124 |
+
w.Header().Set("Content-Type", "text/event-stream")
|
| 125 |
+
w.Header().Set("Cache-Control", "no-cache")
|
| 126 |
+
w.Header().Set("Connection", "keep-alive")
|
| 127 |
+
w.Header().Set("X-Accel-Buffering", "no")
|
| 128 |
+
|
| 129 |
+
raw := strings.TrimSpace(r.URL.Query().Get("text"))
|
| 130 |
+
md := dummyInvoiceMarkdown(raw)
|
| 131 |
+
|
| 132 |
+
// Chunk by words to feel like token streaming.
|
| 133 |
+
words := strings.SplitAfter(md, " ")
|
| 134 |
+
flusher, _ := w.(http.Flusher)
|
| 135 |
+
for _, wd := range words {
|
| 136 |
+
select {
|
| 137 |
+
case <-r.Context().Done():
|
| 138 |
+
return
|
| 139 |
+
default:
|
| 140 |
+
}
|
| 141 |
+
payload, _ := json.Marshal(sseChunk{Delta: wd})
|
| 142 |
+
fmt.Fprintf(w, "data: %s\n\n", payload)
|
| 143 |
+
if flusher != nil {
|
| 144 |
+
flusher.Flush()
|
| 145 |
+
} else {
|
| 146 |
+
_ = rc.Flush()
|
| 147 |
+
}
|
| 148 |
+
time.Sleep(45 * time.Millisecond)
|
| 149 |
+
}
|
| 150 |
+
done, _ := json.Marshal(sseChunk{Done: true})
|
| 151 |
+
fmt.Fprintf(w, "data: %s\n\n", done)
|
| 152 |
+
if flusher != nil {
|
| 153 |
+
flusher.Flush()
|
| 154 |
+
} else {
|
| 155 |
+
_ = rc.Flush()
|
| 156 |
+
}
|
| 157 |
+
}
|
| 158 |
+
|
| 159 |
+
// dummyInvoiceMarkdown builds a deterministic invoice-style markdown doc from
|
| 160 |
+
// whatever the user pasted, so the demo always shows a plausible extraction.
|
| 161 |
+
func dummyInvoiceMarkdown(raw string) string {
|
| 162 |
+
source := strings.TrimSpace(raw)
|
| 163 |
+
if len(source) > 140 {
|
| 164 |
+
source = source[:140] + "…"
|
| 165 |
+
}
|
| 166 |
+
if source == "" {
|
| 167 |
+
source = "Pasted PDF text"
|
| 168 |
+
}
|
| 169 |
+
lines := []string{
|
| 170 |
+
"# INVOICE",
|
| 171 |
+
"",
|
| 172 |
+
"**Acme Corp.** · 548 Market St, San Francisco, CA",
|
| 173 |
+
"Invoice **#INV-2026-0847** · Issued Aug 18, 2026 · Due Sep 01, 2026",
|
| 174 |
+
"",
|
| 175 |
+
"---",
|
| 176 |
+
"",
|
| 177 |
+
"## Bill to",
|
| 178 |
+
"",
|
| 179 |
+
"Globex Inc. — accounts-payable@globex.example",
|
| 180 |
+
"",
|
| 181 |
+
"> Source excerpt: \"" + source + "\"",
|
| 182 |
+
"",
|
| 183 |
+
"## Line items",
|
| 184 |
+
"",
|
| 185 |
+
"| Item | Qty | Unit | Amount |",
|
| 186 |
+
"| --- | ---: | ---: | ---: |",
|
| 187 |
+
"| Design system audit | 12 hrs | $150.00 | $1,800.00 |",
|
| 188 |
+
"| Markitdown extraction API | 4,200 pages | $0.04 | $168.00 |",
|
| 189 |
+
"| Priority support | 1 mo | $99.00 | $99.00 |",
|
| 190 |
+
"",
|
| 191 |
+
"## Summary",
|
| 192 |
+
"",
|
| 193 |
+
"- Subtotal: **$2,067.00**",
|
| 194 |
+
"- Tax (8.5%): **$175.70**",
|
| 195 |
+
"- **Total due: $2,242.70**",
|
| 196 |
+
"",
|
| 197 |
+
"---",
|
| 198 |
+
"",
|
| 199 |
+
"_Extracted with Markitdown · confidence 0.98 · 3 pages · model markitdown-dummy-1_",
|
| 200 |
+
"",
|
| 201 |
+
}
|
| 202 |
+
return strings.Join(lines, "\n")
|
| 203 |
+
}
|
internal/web/handlers_test.go
ADDED
|
@@ -0,0 +1,131 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
package web
|
| 2 |
+
|
| 3 |
+
import (
|
| 4 |
+
"database/sql"
|
| 5 |
+
"log/slog"
|
| 6 |
+
"net/http"
|
| 7 |
+
"net/http/httptest"
|
| 8 |
+
"os"
|
| 9 |
+
"strings"
|
| 10 |
+
"testing"
|
| 11 |
+
|
| 12 |
+
_ "modernc.org/sqlite"
|
| 13 |
+
|
| 14 |
+
"pageturner/internal/config"
|
| 15 |
+
"pageturner/internal/logs"
|
| 16 |
+
"pageturner/internal/models"
|
| 17 |
+
)
|
| 18 |
+
|
| 19 |
+
func testLogger() *slog.Logger {
|
| 20 |
+
return slog.New(slog.NewTextHandler(os.Stdout, &slog.HandlerOptions{Level: slog.LevelError}))
|
| 21 |
+
}
|
| 22 |
+
|
| 23 |
+
func testServerNoDB(t *testing.T) *Server {
|
| 24 |
+
t.Helper()
|
| 25 |
+
cfg := config.Load()
|
| 26 |
+
cfg.DatabaseURL = "file:/path-that-does-not-exist/pageturner.db?mode=ro"
|
| 27 |
+
|
| 28 |
+
db, err := sql.Open("sqlite", cfg.DatabaseURL)
|
| 29 |
+
if err != nil {
|
| 30 |
+
t.Fatalf("open database: %v", err)
|
| 31 |
+
}
|
| 32 |
+
t.Cleanup(func() { db.Close() })
|
| 33 |
+
return NewServer(cfg, models.NewStore(db), testLogger(), logs.NewHub(200))
|
| 34 |
+
}
|
| 35 |
+
|
| 36 |
+
// TestHealthUnreachable verifies /healthz reports 503 when the DB is down.
|
| 37 |
+
func TestHealthUnreachable(t *testing.T) {
|
| 38 |
+
srv := testServerNoDB(t)
|
| 39 |
+
req := httptest.NewRequest(http.MethodGet, "/healthz", nil)
|
| 40 |
+
rec := httptest.NewRecorder()
|
| 41 |
+
srv.Handler().ServeHTTP(rec, req)
|
| 42 |
+
|
| 43 |
+
if rec.Code != http.StatusServiceUnavailable {
|
| 44 |
+
t.Fatalf("GET /healthz with DB down = %d, want %d", rec.Code, http.StatusServiceUnavailable)
|
| 45 |
+
}
|
| 46 |
+
if !strings.Contains(rec.Body.String(), "unhealthy") {
|
| 47 |
+
t.Fatalf("body = %q, want unhealthy JSON", rec.Body.String())
|
| 48 |
+
}
|
| 49 |
+
}
|
| 50 |
+
|
| 51 |
+
// TestLoginPageRenders verifies the public login page renders the CSRF form.
|
| 52 |
+
func TestLoginPageRenders(t *testing.T) {
|
| 53 |
+
srv := testServerNoDB(t)
|
| 54 |
+
req := httptest.NewRequest(http.MethodGet, "/login", nil)
|
| 55 |
+
rec := httptest.NewRecorder()
|
| 56 |
+
srv.Handler().ServeHTTP(rec, req)
|
| 57 |
+
|
| 58 |
+
if rec.Code != http.StatusOK {
|
| 59 |
+
t.Fatalf("GET /login = %d, want 200", rec.Code)
|
| 60 |
+
}
|
| 61 |
+
body := rec.Body.String()
|
| 62 |
+
if !strings.Contains(body, "Welcome back.") {
|
| 63 |
+
t.Fatal("login page missing heading")
|
| 64 |
+
}
|
| 65 |
+
if !strings.Contains(body, `name="csrf"`) {
|
| 66 |
+
t.Fatal("login page missing CSRF field")
|
| 67 |
+
}
|
| 68 |
+
if !strings.Contains(body, "/static/htmx.min.js") {
|
| 69 |
+
t.Fatal("login page missing vendored htmx script")
|
| 70 |
+
}
|
| 71 |
+
}
|
| 72 |
+
|
| 73 |
+
// TestHomeRenders verifies the public landing page renders without a database.
|
| 74 |
+
func TestHomeRenders(t *testing.T) {
|
| 75 |
+
srv := testServerNoDB(t)
|
| 76 |
+
req := httptest.NewRequest(http.MethodGet, "/", nil)
|
| 77 |
+
rec := httptest.NewRecorder()
|
| 78 |
+
srv.Handler().ServeHTTP(rec, req)
|
| 79 |
+
|
| 80 |
+
if rec.Code != http.StatusOK {
|
| 81 |
+
t.Fatalf("GET / = %d, want 200", rec.Code)
|
| 82 |
+
}
|
| 83 |
+
body := rec.Body.String()
|
| 84 |
+
if !strings.Contains(body, "Markitdown") {
|
| 85 |
+
t.Fatal("home page missing brand")
|
| 86 |
+
}
|
| 87 |
+
if !strings.Contains(body, "/markitdown") {
|
| 88 |
+
t.Fatal("home page missing converter link")
|
| 89 |
+
}
|
| 90 |
+
}
|
| 91 |
+
|
| 92 |
+
// TestMarkitdownRequiresAuth verifies /markitdown redirects anonymous users.
|
| 93 |
+
func TestMarkitdownRequiresAuth(t *testing.T) {
|
| 94 |
+
srv := testServerNoDB(t)
|
| 95 |
+
req := httptest.NewRequest(http.MethodGet, "/markitdown", nil)
|
| 96 |
+
rec := httptest.NewRecorder()
|
| 97 |
+
srv.Handler().ServeHTTP(rec, req)
|
| 98 |
+
|
| 99 |
+
if rec.Code != http.StatusSeeOther {
|
| 100 |
+
t.Fatalf("GET /markitdown anonymous = %d, want 303 to /login", rec.Code)
|
| 101 |
+
}
|
| 102 |
+
if loc := rec.Header().Get("Location"); loc != "/login" {
|
| 103 |
+
t.Fatalf("redirect = %q, want /login", loc)
|
| 104 |
+
}
|
| 105 |
+
}
|
| 106 |
+
|
| 107 |
+
// TestMarkitdownStreamRequiresAuth verifies the SSE endpoint rejects anonymous users.
|
| 108 |
+
func TestMarkitdownStreamRequiresAuth(t *testing.T) {
|
| 109 |
+
srv := testServerNoDB(t)
|
| 110 |
+
req := httptest.NewRequest(http.MethodGet, "/markitdown/stream?text=hello", nil)
|
| 111 |
+
req.Header.Set("HX-Request", "true")
|
| 112 |
+
rec := httptest.NewRecorder()
|
| 113 |
+
srv.Handler().ServeHTTP(rec, req)
|
| 114 |
+
|
| 115 |
+
if rec.Code != http.StatusUnauthorized {
|
| 116 |
+
t.Fatalf("GET /markitdown/stream anonymous = %d, want 401", rec.Code)
|
| 117 |
+
}
|
| 118 |
+
}
|
| 119 |
+
|
| 120 |
+
// TestDummyInvoiceMarkdown verifies the dummy extraction always yields an invoice doc.
|
| 121 |
+
func TestDummyInvoiceMarkdown(t *testing.T) {
|
| 122 |
+
md := dummyInvoiceMarkdown("ACME billed Globex $10")
|
| 123 |
+
for _, want := range []string{"# INVOICE", "| Item |", "Total due"} {
|
| 124 |
+
if !strings.Contains(md, want) {
|
| 125 |
+
t.Fatalf("invoice markdown missing %q:\n%s", want, md)
|
| 126 |
+
}
|
| 127 |
+
}
|
| 128 |
+
if got := dummyInvoiceMarkdown(""); !strings.Contains(got, "# INVOICE") {
|
| 129 |
+
t.Fatal("empty input should still yield an invoice doc")
|
| 130 |
+
}
|
| 131 |
+
}
|
internal/web/logs_handler.go
ADDED
|
@@ -0,0 +1,77 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
package web
|
| 2 |
+
|
| 3 |
+
import (
|
| 4 |
+
"encoding/json"
|
| 5 |
+
"fmt"
|
| 6 |
+
"net/http"
|
| 7 |
+
"strings"
|
| 8 |
+
"time"
|
| 9 |
+
)
|
| 10 |
+
|
| 11 |
+
// sseLogEvent is the JSON payload sent down the log stream.
|
| 12 |
+
type sseLogEvent struct {
|
| 13 |
+
Text string `json:"text"`
|
| 14 |
+
Color string `json:"color"`
|
| 15 |
+
Ts int64 `json:"ts"`
|
| 16 |
+
}
|
| 17 |
+
|
| 18 |
+
// handleLogStream streams backend log lines to the browser over
|
| 19 |
+
// Server-Sent Events: history is replayed first, then new lines are pushed
|
| 20 |
+
// as they are emitted. Idle connections get a comment heartbeat so proxies
|
| 21 |
+
// don't close them.
|
| 22 |
+
func (s *Server) handleLogStream(w http.ResponseWriter, r *http.Request) {
|
| 23 |
+
rc := http.NewResponseController(w)
|
| 24 |
+
// The server's WriteTimeout would kill a long-lived stream; clear it.
|
| 25 |
+
_ = rc.SetWriteDeadline(time.Time{})
|
| 26 |
+
|
| 27 |
+
w.Header().Set("Content-Type", "text/event-stream")
|
| 28 |
+
w.Header().Set("Cache-Control", "no-cache")
|
| 29 |
+
w.Header().Set("Connection", "keep-alive")
|
| 30 |
+
w.Header().Set("X-Accel-Buffering", "no")
|
| 31 |
+
|
| 32 |
+
s.log.Info("log stream opened")
|
| 33 |
+
for _, line := range s.hub.History() {
|
| 34 |
+
writeLogEvent(w, line)
|
| 35 |
+
}
|
| 36 |
+
if err := rc.Flush(); err != nil {
|
| 37 |
+
s.log.Warn("log stream flush", "error", err)
|
| 38 |
+
return
|
| 39 |
+
}
|
| 40 |
+
|
| 41 |
+
ch := s.hub.Subscribe(r.Context())
|
| 42 |
+
ticker := time.NewTicker(15 * time.Second)
|
| 43 |
+
defer ticker.Stop()
|
| 44 |
+
|
| 45 |
+
for {
|
| 46 |
+
select {
|
| 47 |
+
case <-r.Context().Done():
|
| 48 |
+
return
|
| 49 |
+
case line := <-ch:
|
| 50 |
+
writeLogEvent(w, line)
|
| 51 |
+
_ = rc.Flush()
|
| 52 |
+
case <-ticker.C:
|
| 53 |
+
fmt.Fprint(w, ": ping\n\n")
|
| 54 |
+
_ = rc.Flush()
|
| 55 |
+
}
|
| 56 |
+
}
|
| 57 |
+
}
|
| 58 |
+
|
| 59 |
+
// writeLogEvent sends one line as an SSE data frame.
|
| 60 |
+
func writeLogEvent(w http.ResponseWriter, line string) {
|
| 61 |
+
event, _ := json.Marshal(sseLogEvent{Text: line, Color: classifyLogLine(line), Ts: time.Now().UnixMilli()})
|
| 62 |
+
fmt.Fprintf(w, "data: %s\n\n", event)
|
| 63 |
+
}
|
| 64 |
+
|
| 65 |
+
// classifyLogLine picks a terminal color class from the line's level token.
|
| 66 |
+
func classifyLogLine(line string) string {
|
| 67 |
+
switch {
|
| 68 |
+
case strings.Contains(line, "ERROR"):
|
| 69 |
+
return "error"
|
| 70 |
+
case strings.Contains(line, "WARN"):
|
| 71 |
+
return "warn"
|
| 72 |
+
case strings.Contains(line, "DEBUG"):
|
| 73 |
+
return "dim"
|
| 74 |
+
default:
|
| 75 |
+
return "default"
|
| 76 |
+
}
|
| 77 |
+
}
|
internal/web/middleware.go
ADDED
|
@@ -0,0 +1,155 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
package web
|
| 2 |
+
|
| 3 |
+
import (
|
| 4 |
+
"net/http"
|
| 5 |
+
"time"
|
| 6 |
+
|
| 7 |
+
"pageturner/internal/auth"
|
| 8 |
+
"pageturner/internal/models"
|
| 9 |
+
)
|
| 10 |
+
|
| 11 |
+
// statusRecorder captures the response status code for logging.
|
| 12 |
+
type statusRecorder struct {
|
| 13 |
+
http.ResponseWriter
|
| 14 |
+
status int
|
| 15 |
+
}
|
| 16 |
+
|
| 17 |
+
func (r *statusRecorder) WriteHeader(code int) {
|
| 18 |
+
r.status = code
|
| 19 |
+
r.ResponseWriter.WriteHeader(code)
|
| 20 |
+
}
|
| 21 |
+
|
| 22 |
+
// Unwrap exposes the underlying ResponseWriter so http.ResponseController
|
| 23 |
+
// (streaming flush, write-deadline control) works through the middleware.
|
| 24 |
+
func (r *statusRecorder) Unwrap() http.ResponseWriter { return r.ResponseWriter }
|
| 25 |
+
|
| 26 |
+
// recoverPanic converts panics into 500s instead of crashing the process.
|
| 27 |
+
func (s *Server) recoverPanic(next http.Handler) http.Handler {
|
| 28 |
+
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
| 29 |
+
defer func() {
|
| 30 |
+
if rec := recover(); rec != nil {
|
| 31 |
+
s.log.Error("panic recovered", "panic", rec, "path", r.URL.Path)
|
| 32 |
+
http.Error(w, "internal server error", http.StatusInternalServerError)
|
| 33 |
+
}
|
| 34 |
+
}()
|
| 35 |
+
next.ServeHTTP(w, r)
|
| 36 |
+
})
|
| 37 |
+
}
|
| 38 |
+
|
| 39 |
+
// requestLog emits one structured log line per request.
|
| 40 |
+
func (s *Server) requestLog(next http.Handler) http.Handler {
|
| 41 |
+
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
| 42 |
+
start := time.Now()
|
| 43 |
+
rec := &statusRecorder{ResponseWriter: w, status: http.StatusOK}
|
| 44 |
+
next.ServeHTTP(rec, r)
|
| 45 |
+
s.log.Info("request",
|
| 46 |
+
"method", r.Method,
|
| 47 |
+
"path", r.URL.Path,
|
| 48 |
+
"status", rec.status,
|
| 49 |
+
"duration_ms", time.Since(start).Milliseconds(),
|
| 50 |
+
"ip", r.RemoteAddr,
|
| 51 |
+
)
|
| 52 |
+
})
|
| 53 |
+
}
|
| 54 |
+
|
| 55 |
+
// csrf protects state-changing requests using the double-submit pattern: the
|
| 56 |
+
// token lives in the "csrf" cookie and must also arrive in the X-CSRF-Token
|
| 57 |
+
// header (set globally by htmx) or a "csrf" form field. For every request it
|
| 58 |
+
// also exposes the current token to handlers via the request context, so forms
|
| 59 |
+
// re-rendered after an error keep a valid token for the next submit.
|
| 60 |
+
func (s *Server) csrf(next http.Handler) http.Handler {
|
| 61 |
+
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
| 62 |
+
switch r.Method {
|
| 63 |
+
case http.MethodGet, http.MethodHead, http.MethodOptions:
|
| 64 |
+
// Safe methods pass through, but make sure a token exists (creating
|
| 65 |
+
// the cookie if needed) so the rendered page can put it in forms.
|
| 66 |
+
token := csrfCookieValue(r)
|
| 67 |
+
if token == "" {
|
| 68 |
+
token = newCSRFOrEmpty()
|
| 69 |
+
http.SetCookie(w, s.csrfCookie(token, s.ttlSeconds()))
|
| 70 |
+
}
|
| 71 |
+
next.ServeHTTP(w, r.WithContext(contextWithCSRF(r.Context(), token)))
|
| 72 |
+
return
|
| 73 |
+
}
|
| 74 |
+
|
| 75 |
+
cookie, err := r.Cookie("csrf")
|
| 76 |
+
if err != nil {
|
| 77 |
+
http.Error(w, "missing CSRF token", http.StatusForbidden)
|
| 78 |
+
return
|
| 79 |
+
}
|
| 80 |
+
submitted := r.Header.Get("X-CSRF-Token")
|
| 81 |
+
if submitted == "" {
|
| 82 |
+
submitted = r.FormValue("csrf")
|
| 83 |
+
}
|
| 84 |
+
if !auth.ConstantTimeEqual(cookie.Value, submitted) {
|
| 85 |
+
http.Error(w, "invalid CSRF token", http.StatusForbidden)
|
| 86 |
+
return
|
| 87 |
+
}
|
| 88 |
+
// Expose the validated token so error re-renders keep the same token
|
| 89 |
+
// in the form instead of an empty one that would fail the next submit.
|
| 90 |
+
next.ServeHTTP(w, r.WithContext(contextWithCSRF(r.Context(), cookie.Value)))
|
| 91 |
+
})
|
| 92 |
+
}
|
| 93 |
+
|
| 94 |
+
// requireAuth loads the session user and attaches them to the request context.
|
| 95 |
+
// Public routes (home/login/health/static) pass through untouched.
|
| 96 |
+
func (s *Server) requireAuth(next http.Handler) http.Handler {
|
| 97 |
+
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
| 98 |
+
// Public routes.
|
| 99 |
+
switch {
|
| 100 |
+
case r.URL.Path == "/" || r.URL.Path == "/login":
|
| 101 |
+
next.ServeHTTP(w, r)
|
| 102 |
+
return
|
| 103 |
+
case r.URL.Path == "/healthz":
|
| 104 |
+
next.ServeHTTP(w, r)
|
| 105 |
+
return
|
| 106 |
+
case len(r.URL.Path) >= 8 && r.URL.Path[:8] == "/static/":
|
| 107 |
+
next.ServeHTTP(w, r)
|
| 108 |
+
return
|
| 109 |
+
}
|
| 110 |
+
|
| 111 |
+
cookie, err := r.Cookie("session")
|
| 112 |
+
if err != nil {
|
| 113 |
+
s.redirectLogin(w, r)
|
| 114 |
+
return
|
| 115 |
+
}
|
| 116 |
+
user, err := s.store.UserForSession(r.Context(), auth.HashToken(cookie.Value))
|
| 117 |
+
if err != nil {
|
| 118 |
+
s.redirectLogin(w, r)
|
| 119 |
+
return
|
| 120 |
+
}
|
| 121 |
+
|
| 122 |
+
// The csrf middleware (which wraps this one) ensures the token cookie
|
| 123 |
+
// exists and exposes it via context for every request.
|
| 124 |
+
ctx := contextWithUser(r.Context(), user)
|
| 125 |
+
next.ServeHTTP(w, r.WithContext(ctx))
|
| 126 |
+
})
|
| 127 |
+
}
|
| 128 |
+
|
| 129 |
+
// redirectLogin sends a normal or htmx-aware redirect to the login page.
|
| 130 |
+
func (s *Server) redirectLogin(w http.ResponseWriter, r *http.Request) {
|
| 131 |
+
if isHTMX(r) {
|
| 132 |
+
w.Header().Set("HX-Redirect", "/login")
|
| 133 |
+
w.WriteHeader(http.StatusUnauthorized)
|
| 134 |
+
return
|
| 135 |
+
}
|
| 136 |
+
http.Redirect(w, r, "/login", http.StatusSeeOther)
|
| 137 |
+
}
|
| 138 |
+
|
| 139 |
+
// csrfCookieValue reads the csrf cookie value, if present.
|
| 140 |
+
func csrfCookieValue(r *http.Request) string {
|
| 141 |
+
if c, err := r.Cookie("csrf"); err == nil && c.Value != "" {
|
| 142 |
+
return c.Value
|
| 143 |
+
}
|
| 144 |
+
return ""
|
| 145 |
+
}
|
| 146 |
+
|
| 147 |
+
// requireUser returns the authenticated user, or nil if somehow absent.
|
| 148 |
+
func (s *Server) requireUser(r *http.Request) (models.User, bool) {
|
| 149 |
+
u := userFrom(r)
|
| 150 |
+
if u.ID == 0 {
|
| 151 |
+
s.log.Warn("authenticated route reached without user in context", "path", r.URL.Path)
|
| 152 |
+
return models.User{}, false
|
| 153 |
+
}
|
| 154 |
+
return u, true
|
| 155 |
+
}
|
internal/web/render.go
ADDED
|
@@ -0,0 +1,107 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
package web
|
| 2 |
+
|
| 3 |
+
import (
|
| 4 |
+
"embed"
|
| 5 |
+
"fmt"
|
| 6 |
+
"html/template"
|
| 7 |
+
"io/fs"
|
| 8 |
+
"log/slog"
|
| 9 |
+
"net/http"
|
| 10 |
+
"strings"
|
| 11 |
+
"time"
|
| 12 |
+
)
|
| 13 |
+
|
| 14 |
+
//go:embed templates static
|
| 15 |
+
var content embed.FS
|
| 16 |
+
|
| 17 |
+
// funcs are shared by every template set.
|
| 18 |
+
var funcs = template.FuncMap{
|
| 19 |
+
"stars": stars,
|
| 20 |
+
"timefmt": timefmt,
|
| 21 |
+
}
|
| 22 |
+
|
| 23 |
+
// pageNames are the standalone pages, each parsed into its own template set so
|
| 24 |
+
// their "content" block definitions don't collide with each other.
|
| 25 |
+
var pageNames = []string{"home", "login", "markitdown"}
|
| 26 |
+
|
| 27 |
+
// fragments holds base.html plus all partials, shared across pages.
|
| 28 |
+
var fragments *template.Template
|
| 29 |
+
|
| 30 |
+
// pages maps a page name to a template set containing base + partials + page.
|
| 31 |
+
var pages map[string]*template.Template
|
| 32 |
+
|
| 33 |
+
func init() {
|
| 34 |
+
var err error
|
| 35 |
+
fragments, err = template.New("").Funcs(funcs).ParseFS(content,
|
| 36 |
+
"templates/*.html",
|
| 37 |
+
)
|
| 38 |
+
if err != nil {
|
| 39 |
+
panic(fmt.Sprintf("parse base/partials templates: %v", err))
|
| 40 |
+
}
|
| 41 |
+
|
| 42 |
+
pages = make(map[string]*template.Template, len(pageNames))
|
| 43 |
+
for _, name := range pageNames {
|
| 44 |
+
// Clone the shared set, then parse this page's file into the clone.
|
| 45 |
+
set, err := fragments.Clone()
|
| 46 |
+
if err != nil {
|
| 47 |
+
panic(fmt.Sprintf("clone template set: %v", err))
|
| 48 |
+
}
|
| 49 |
+
body, err := content.ReadFile("templates/pages/" + name + ".html")
|
| 50 |
+
if err != nil {
|
| 51 |
+
panic(fmt.Sprintf("read page %s: %v", name, err))
|
| 52 |
+
}
|
| 53 |
+
if _, err := set.New(name).Parse(string(body)); err != nil {
|
| 54 |
+
panic(fmt.Sprintf("parse page %s: %v", name, err))
|
| 55 |
+
}
|
| 56 |
+
pages[name] = set
|
| 57 |
+
}
|
| 58 |
+
}
|
| 59 |
+
|
| 60 |
+
// templateLog is set by NewServer so render failures are visible in logs.
|
| 61 |
+
var templateLog = slog.Default()
|
| 62 |
+
|
| 63 |
+
// render executes a named template with data. Page names resolve to their own
|
| 64 |
+
// template set; anything else is treated as a fragment from the shared set.
|
| 65 |
+
func render(w http.ResponseWriter, r *http.Request, name string, data any) {
|
| 66 |
+
if set, ok := pages[name]; ok {
|
| 67 |
+
if err := set.ExecuteTemplate(w, name, data); err != nil {
|
| 68 |
+
templateLog.Error("template execution failed", "template", name, "error", err)
|
| 69 |
+
http.Error(w, "template error", http.StatusInternalServerError)
|
| 70 |
+
}
|
| 71 |
+
return
|
| 72 |
+
}
|
| 73 |
+
if err := fragments.ExecuteTemplate(w, name, data); err != nil {
|
| 74 |
+
templateLog.Error("template execution failed", "template", name, "error", err)
|
| 75 |
+
http.Error(w, "template error", http.StatusInternalServerError)
|
| 76 |
+
}
|
| 77 |
+
}
|
| 78 |
+
|
| 79 |
+
// staticFiles serves the embedded static assets with long-lived caching.
|
| 80 |
+
func staticFiles() http.Handler {
|
| 81 |
+
sub, err := fs.Sub(content, "static")
|
| 82 |
+
if err != nil {
|
| 83 |
+
panic(fmt.Sprintf("embed static: %v", err))
|
| 84 |
+
}
|
| 85 |
+
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
| 86 |
+
if strings.HasSuffix(r.URL.Path, ".js") || strings.HasSuffix(r.URL.Path, ".css") {
|
| 87 |
+
// Versioned URLs (?v=) carry the cache-busting; revalidate often.
|
| 88 |
+
w.Header().Set("Cache-Control", "public, max-age=3600, must-revalidate")
|
| 89 |
+
}
|
| 90 |
+
http.FileServer(http.FS(sub)).ServeHTTP(w, r)
|
| 91 |
+
})
|
| 92 |
+
}
|
| 93 |
+
|
| 94 |
+
// stars renders a 1-5 star rating as plain text (safe, no escaping needed).
|
| 95 |
+
func stars(n int) string {
|
| 96 |
+
if n < 0 {
|
| 97 |
+
n = 0
|
| 98 |
+
}
|
| 99 |
+
if n > 5 {
|
| 100 |
+
n = 5
|
| 101 |
+
}
|
| 102 |
+
return strings.Repeat("★", n) + strings.Repeat("☆", 5-n)
|
| 103 |
+
}
|
| 104 |
+
|
| 105 |
+
func timefmt(t time.Time) string {
|
| 106 |
+
return t.Format("Jan 2, 2006")
|
| 107 |
+
}
|
internal/web/server.go
ADDED
|
@@ -0,0 +1,134 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
package web
|
| 2 |
+
|
| 3 |
+
import (
|
| 4 |
+
"context"
|
| 5 |
+
"log/slog"
|
| 6 |
+
"net/http"
|
| 7 |
+
"time"
|
| 8 |
+
|
| 9 |
+
"pageturner/internal/auth"
|
| 10 |
+
"pageturner/internal/config"
|
| 11 |
+
"pageturner/internal/logs"
|
| 12 |
+
"pageturner/internal/models"
|
| 13 |
+
)
|
| 14 |
+
|
| 15 |
+
type ctxKey int
|
| 16 |
+
|
| 17 |
+
const (
|
| 18 |
+
userKey ctxKey = iota
|
| 19 |
+
csrfKey
|
| 20 |
+
)
|
| 21 |
+
|
| 22 |
+
// Server wires routes, middleware and handlers together.
|
| 23 |
+
type Server struct {
|
| 24 |
+
cfg config.Config
|
| 25 |
+
store *models.Store
|
| 26 |
+
handler http.Handler
|
| 27 |
+
log *slog.Logger
|
| 28 |
+
hub *logs.Hub
|
| 29 |
+
}
|
| 30 |
+
|
| 31 |
+
func NewServer(cfg config.Config, store *models.Store, log *slog.Logger, hub *logs.Hub) *Server {
|
| 32 |
+
s := &Server{
|
| 33 |
+
cfg: cfg,
|
| 34 |
+
store: store,
|
| 35 |
+
log: log,
|
| 36 |
+
hub: hub,
|
| 37 |
+
}
|
| 38 |
+
templateLog = log
|
| 39 |
+
s.routes(http.NewServeMux())
|
| 40 |
+
return s
|
| 41 |
+
}
|
| 42 |
+
|
| 43 |
+
func (s *Server) routes(mux *http.ServeMux) {
|
| 44 |
+
// Public
|
| 45 |
+
mux.HandleFunc("GET /healthz", s.handleHealth)
|
| 46 |
+
mux.HandleFunc("GET /{$}", s.handleHome)
|
| 47 |
+
mux.HandleFunc("GET /login", s.handleLoginGet)
|
| 48 |
+
mux.HandleFunc("POST /login", s.handleLoginPost)
|
| 49 |
+
mux.Handle("GET /static/", http.StripPrefix("/static/", staticFiles()))
|
| 50 |
+
|
| 51 |
+
// Authenticated
|
| 52 |
+
mux.HandleFunc("POST /logout", s.handleLogout)
|
| 53 |
+
mux.HandleFunc("GET /markitdown", s.handleMarkitdown)
|
| 54 |
+
mux.HandleFunc("GET /markitdown/stream", s.handleMarkitdownStream)
|
| 55 |
+
mux.HandleFunc("GET /logs/stream", s.handleLogStream)
|
| 56 |
+
|
| 57 |
+
// Wrap the whole router; the last middleware listed runs first, so the
|
| 58 |
+
// execution order is: requireAuth → csrf → requestLog → recoverPanic.
|
| 59 |
+
s.handler = wrap(mux, s.recoverPanic, s.requestLog, s.csrf, s.requireAuth)
|
| 60 |
+
}
|
| 61 |
+
|
| 62 |
+
// Handler returns the fully wrapped http.Handler.
|
| 63 |
+
func (s *Server) Handler() http.Handler { return s.handler }
|
| 64 |
+
|
| 65 |
+
// wrap nests middlewares inside-out: each one wraps the previous result, so
|
| 66 |
+
// the last listed middleware runs first for every request.
|
| 67 |
+
func wrap(h http.Handler, mws ...func(http.Handler) http.Handler) http.Handler {
|
| 68 |
+
for _, mw := range mws {
|
| 69 |
+
h = mw(h)
|
| 70 |
+
}
|
| 71 |
+
return h
|
| 72 |
+
}
|
| 73 |
+
|
| 74 |
+
// --- context helpers ---
|
| 75 |
+
|
| 76 |
+
func contextWithUser(ctx context.Context, u models.User) context.Context {
|
| 77 |
+
return context.WithValue(ctx, userKey, u)
|
| 78 |
+
}
|
| 79 |
+
|
| 80 |
+
func userFrom(r *http.Request) models.User {
|
| 81 |
+
u, _ := r.Context().Value(userKey).(models.User)
|
| 82 |
+
return u
|
| 83 |
+
}
|
| 84 |
+
|
| 85 |
+
func contextWithCSRF(ctx context.Context, token string) context.Context {
|
| 86 |
+
return context.WithValue(ctx, csrfKey, token)
|
| 87 |
+
}
|
| 88 |
+
|
| 89 |
+
func csrfFrom(r *http.Request) string {
|
| 90 |
+
t, _ := r.Context().Value(csrfKey).(string)
|
| 91 |
+
return t
|
| 92 |
+
}
|
| 93 |
+
|
| 94 |
+
// --- small helpers ---
|
| 95 |
+
|
| 96 |
+
func (s *Server) sessionCookie(token string, maxAge int) *http.Cookie {
|
| 97 |
+
return &http.Cookie{
|
| 98 |
+
Name: "session",
|
| 99 |
+
Value: token,
|
| 100 |
+
Path: "/",
|
| 101 |
+
HttpOnly: true,
|
| 102 |
+
Secure: s.cfg.CookieSecure(),
|
| 103 |
+
SameSite: http.SameSiteLaxMode,
|
| 104 |
+
MaxAge: maxAge,
|
| 105 |
+
}
|
| 106 |
+
}
|
| 107 |
+
|
| 108 |
+
func (s *Server) csrfCookie(token string, maxAge int) *http.Cookie {
|
| 109 |
+
return &http.Cookie{
|
| 110 |
+
Name: "csrf",
|
| 111 |
+
Value: token,
|
| 112 |
+
Path: "/",
|
| 113 |
+
HttpOnly: true,
|
| 114 |
+
Secure: s.cfg.CookieSecure(),
|
| 115 |
+
SameSite: http.SameSiteLaxMode,
|
| 116 |
+
MaxAge: maxAge,
|
| 117 |
+
}
|
| 118 |
+
}
|
| 119 |
+
|
| 120 |
+
func (s *Server) ttlSeconds() int {
|
| 121 |
+
return int(s.cfg.SessionTTL / time.Second)
|
| 122 |
+
}
|
| 123 |
+
|
| 124 |
+
func isHTMX(r *http.Request) bool {
|
| 125 |
+
return r.Header.Get("HX-Request") == "true"
|
| 126 |
+
}
|
| 127 |
+
|
| 128 |
+
func newCSRFOrEmpty() string {
|
| 129 |
+
t, err := auth.NewCSRF()
|
| 130 |
+
if err != nil {
|
| 131 |
+
return ""
|
| 132 |
+
}
|
| 133 |
+
return t
|
| 134 |
+
}
|
internal/web/static/htmx.min.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
var htmx=function(){"use strict";const Q={onLoad:null,process:null,on:null,off:null,trigger:null,ajax:null,find:null,findAll:null,closest:null,values:function(e,t){const n=cn(e,t||"post");return n.values},remove:null,addClass:null,removeClass:null,toggleClass:null,takeClass:null,swap:null,defineExtension:null,removeExtension:null,logAll:null,logNone:null,logger:null,config:{historyEnabled:true,historyCacheSize:10,refreshOnHistoryMiss:false,defaultSwapStyle:"innerHTML",defaultSwapDelay:0,defaultSettleDelay:20,includeIndicatorStyles:true,indicatorClass:"htmx-indicator",requestClass:"htmx-request",addedClass:"htmx-added",settlingClass:"htmx-settling",swappingClass:"htmx-swapping",allowEval:true,allowScriptTags:true,inlineScriptNonce:"",inlineStyleNonce:"",attributesToSettle:["class","style","width","height"],withCredentials:false,timeout:0,wsReconnectDelay:"full-jitter",wsBinaryType:"blob",disableSelector:"[hx-disable], [data-hx-disable]",scrollBehavior:"instant",defaultFocusScroll:false,getCacheBusterParam:false,globalViewTransitions:false,methodsThatUseUrlParams:["get","delete"],selfRequestsOnly:true,ignoreTitle:false,scrollIntoViewOnBoost:true,triggerSpecsCache:null,disableInheritance:false,responseHandling:[{code:"204",swap:false},{code:"[23]..",swap:true},{code:"[45]..",swap:false,error:true}],allowNestedOobSwaps:true},parseInterval:null,_:null,version:"2.0.4"};Q.onLoad=j;Q.process=kt;Q.on=ye;Q.off=be;Q.trigger=he;Q.ajax=Rn;Q.find=u;Q.findAll=x;Q.closest=g;Q.remove=z;Q.addClass=K;Q.removeClass=G;Q.toggleClass=W;Q.takeClass=Z;Q.swap=$e;Q.defineExtension=Fn;Q.removeExtension=Bn;Q.logAll=V;Q.logNone=_;Q.parseInterval=d;Q._=e;const n={addTriggerHandler:St,bodyContains:le,canAccessLocalStorage:B,findThisElement:Se,filterValues:hn,swap:$e,hasAttribute:s,getAttributeValue:te,getClosestAttributeValue:re,getClosestMatch:o,getExpressionVars:En,getHeaders:fn,getInputValues:cn,getInternalData:ie,getSwapSpecification:gn,getTriggerSpecs:st,getTarget:Ee,makeFragment:P,mergeObjects:ce,makeSettleInfo:xn,oobSwap:He,querySelectorExt:ae,settleImmediately:Kt,shouldCancel:ht,triggerEvent:he,triggerErrorEvent:fe,withExtensions:Ft};const r=["get","post","put","delete","patch"];const H=r.map(function(e){return"[hx-"+e+"], [data-hx-"+e+"]"}).join(", ");function d(e){if(e==undefined){return undefined}let t=NaN;if(e.slice(-2)=="ms"){t=parseFloat(e.slice(0,-2))}else if(e.slice(-1)=="s"){t=parseFloat(e.slice(0,-1))*1e3}else if(e.slice(-1)=="m"){t=parseFloat(e.slice(0,-1))*1e3*60}else{t=parseFloat(e)}return isNaN(t)?undefined:t}function ee(e,t){return e instanceof Element&&e.getAttribute(t)}function s(e,t){return!!e.hasAttribute&&(e.hasAttribute(t)||e.hasAttribute("data-"+t))}function te(e,t){return ee(e,t)||ee(e,"data-"+t)}function c(e){const t=e.parentElement;if(!t&&e.parentNode instanceof ShadowRoot)return e.parentNode;return t}function ne(){return document}function m(e,t){return e.getRootNode?e.getRootNode({composed:t}):ne()}function o(e,t){while(e&&!t(e)){e=c(e)}return e||null}function i(e,t,n){const r=te(t,n);const o=te(t,"hx-disinherit");var i=te(t,"hx-inherit");if(e!==t){if(Q.config.disableInheritance){if(i&&(i==="*"||i.split(" ").indexOf(n)>=0)){return r}else{return null}}if(o&&(o==="*"||o.split(" ").indexOf(n)>=0)){return"unset"}}return r}function re(t,n){let r=null;o(t,function(e){return!!(r=i(t,ue(e),n))});if(r!=="unset"){return r}}function h(e,t){const n=e instanceof Element&&(e.matches||e.matchesSelector||e.msMatchesSelector||e.mozMatchesSelector||e.webkitMatchesSelector||e.oMatchesSelector);return!!n&&n.call(e,t)}function T(e){const t=/<([a-z][^\/\0>\x20\t\r\n\f]*)/i;const n=t.exec(e);if(n){return n[1].toLowerCase()}else{return""}}function q(e){const t=new DOMParser;return t.parseFromString(e,"text/html")}function L(e,t){while(t.childNodes.length>0){e.append(t.childNodes[0])}}function A(e){const t=ne().createElement("script");se(e.attributes,function(e){t.setAttribute(e.name,e.value)});t.textContent=e.textContent;t.async=false;if(Q.config.inlineScriptNonce){t.nonce=Q.config.inlineScriptNonce}return t}function N(e){return e.matches("script")&&(e.type==="text/javascript"||e.type==="module"||e.type==="")}function I(e){Array.from(e.querySelectorAll("script")).forEach(e=>{if(N(e)){const t=A(e);const n=e.parentNode;try{n.insertBefore(t,e)}catch(e){O(e)}finally{e.remove()}}})}function P(e){const t=e.replace(/<head(\s[^>]*)?>[\s\S]*?<\/head>/i,"");const n=T(t);let r;if(n==="html"){r=new DocumentFragment;const i=q(e);L(r,i.body);r.title=i.title}else if(n==="body"){r=new DocumentFragment;const i=q(t);L(r,i.body);r.title=i.title}else{const i=q('<body><template class="internal-htmx-wrapper">'+t+"</template></body>");r=i.querySelector("template").content;r.title=i.title;var o=r.querySelector("title");if(o&&o.parentNode===r){o.remove();r.title=o.innerText}}if(r){if(Q.config.allowScriptTags){I(r)}else{r.querySelectorAll("script").forEach(e=>e.remove())}}return r}function oe(e){if(e){e()}}function t(e,t){return Object.prototype.toString.call(e)==="[object "+t+"]"}function k(e){return typeof e==="function"}function D(e){return t(e,"Object")}function ie(e){const t="htmx-internal-data";let n=e[t];if(!n){n=e[t]={}}return n}function M(t){const n=[];if(t){for(let e=0;e<t.length;e++){n.push(t[e])}}return n}function se(t,n){if(t){for(let e=0;e<t.length;e++){n(t[e])}}}function X(e){const t=e.getBoundingClientRect();const n=t.top;const r=t.bottom;return n<window.innerHeight&&r>=0}function le(e){return e.getRootNode({composed:true})===document}function F(e){return e.trim().split(/\s+/)}function ce(e,t){for(const n in t){if(t.hasOwnProperty(n)){e[n]=t[n]}}return e}function S(e){try{return JSON.parse(e)}catch(e){O(e);return null}}function B(){const e="htmx:localStorageTest";try{localStorage.setItem(e,e);localStorage.removeItem(e);return true}catch(e){return false}}function U(t){try{const e=new URL(t);if(e){t=e.pathname+e.search}if(!/^\/$/.test(t)){t=t.replace(/\/+$/,"")}return t}catch(e){return t}}function e(e){return vn(ne().body,function(){return eval(e)})}function j(t){const e=Q.on("htmx:load",function(e){t(e.detail.elt)});return e}function V(){Q.logger=function(e,t,n){if(console){console.log(t,e,n)}}}function _(){Q.logger=null}function u(e,t){if(typeof e!=="string"){return e.querySelector(t)}else{return u(ne(),e)}}function x(e,t){if(typeof e!=="string"){return e.querySelectorAll(t)}else{return x(ne(),e)}}function E(){return window}function z(e,t){e=y(e);if(t){E().setTimeout(function(){z(e);e=null},t)}else{c(e).removeChild(e)}}function ue(e){return e instanceof Element?e:null}function $(e){return e instanceof HTMLElement?e:null}function J(e){return typeof e==="string"?e:null}function f(e){return e instanceof Element||e instanceof Document||e instanceof DocumentFragment?e:null}function K(e,t,n){e=ue(y(e));if(!e){return}if(n){E().setTimeout(function(){K(e,t);e=null},n)}else{e.classList&&e.classList.add(t)}}function G(e,t,n){let r=ue(y(e));if(!r){return}if(n){E().setTimeout(function(){G(r,t);r=null},n)}else{if(r.classList){r.classList.remove(t);if(r.classList.length===0){r.removeAttribute("class")}}}}function W(e,t){e=y(e);e.classList.toggle(t)}function Z(e,t){e=y(e);se(e.parentElement.children,function(e){G(e,t)});K(ue(e),t)}function g(e,t){e=ue(y(e));if(e&&e.closest){return e.closest(t)}else{do{if(e==null||h(e,t)){return e}}while(e=e&&ue(c(e)));return null}}function l(e,t){return e.substring(0,t.length)===t}function Y(e,t){return e.substring(e.length-t.length)===t}function ge(e){const t=e.trim();if(l(t,"<")&&Y(t,"/>")){return t.substring(1,t.length-2)}else{return t}}function p(t,r,n){if(r.indexOf("global ")===0){return p(t,r.slice(7),true)}t=y(t);const o=[];{let t=0;let n=0;for(let e=0;e<r.length;e++){const l=r[e];if(l===","&&t===0){o.push(r.substring(n,e));n=e+1;continue}if(l==="<"){t++}else if(l==="/"&&e<r.length-1&&r[e+1]===">"){t--}}if(n<r.length){o.push(r.substring(n))}}const i=[];const s=[];while(o.length>0){const r=ge(o.shift());let e;if(r.indexOf("closest ")===0){e=g(ue(t),ge(r.substr(8)))}else if(r.indexOf("find ")===0){e=u(f(t),ge(r.substr(5)))}else if(r==="next"||r==="nextElementSibling"){e=ue(t).nextElementSibling}else if(r.indexOf("next ")===0){e=pe(t,ge(r.substr(5)),!!n)}else if(r==="previous"||r==="previousElementSibling"){e=ue(t).previousElementSibling}else if(r.indexOf("previous ")===0){e=me(t,ge(r.substr(9)),!!n)}else if(r==="document"){e=document}else if(r==="window"){e=window}else if(r==="body"){e=document.body}else if(r==="root"){e=m(t,!!n)}else if(r==="host"){e=t.getRootNode().host}else{s.push(r)}if(e){i.push(e)}}if(s.length>0){const e=s.join(",");const c=f(m(t,!!n));i.push(...M(c.querySelectorAll(e)))}return i}var pe=function(t,e,n){const r=f(m(t,n)).querySelectorAll(e);for(let e=0;e<r.length;e++){const o=r[e];if(o.compareDocumentPosition(t)===Node.DOCUMENT_POSITION_PRECEDING){return o}}};var me=function(t,e,n){const r=f(m(t,n)).querySelectorAll(e);for(let e=r.length-1;e>=0;e--){const o=r[e];if(o.compareDocumentPosition(t)===Node.DOCUMENT_POSITION_FOLLOWING){return o}}};function ae(e,t){if(typeof e!=="string"){return p(e,t)[0]}else{return p(ne().body,e)[0]}}function y(e,t){if(typeof e==="string"){return u(f(t)||document,e)}else{return e}}function xe(e,t,n,r){if(k(t)){return{target:ne().body,event:J(e),listener:t,options:n}}else{return{target:y(e),event:J(t),listener:n,options:r}}}function ye(t,n,r,o){Vn(function(){const e=xe(t,n,r,o);e.target.addEventListener(e.event,e.listener,e.options)});const e=k(n);return e?n:r}function be(t,n,r){Vn(function(){const e=xe(t,n,r);e.target.removeEventListener(e.event,e.listener)});return k(n)?n:r}const ve=ne().createElement("output");function we(e,t){const n=re(e,t);if(n){if(n==="this"){return[Se(e,t)]}else{const r=p(e,n);if(r.length===0){O('The selector "'+n+'" on '+t+" returned no matches!");return[ve]}else{return r}}}}function Se(e,t){return ue(o(e,function(e){return te(ue(e),t)!=null}))}function Ee(e){const t=re(e,"hx-target");if(t){if(t==="this"){return Se(e,"hx-target")}else{return ae(e,t)}}else{const n=ie(e);if(n.boosted){return ne().body}else{return e}}}function Ce(t){const n=Q.config.attributesToSettle;for(let e=0;e<n.length;e++){if(t===n[e]){return true}}return false}function Oe(t,n){se(t.attributes,function(e){if(!n.hasAttribute(e.name)&&Ce(e.name)){t.removeAttribute(e.name)}});se(n.attributes,function(e){if(Ce(e.name)){t.setAttribute(e.name,e.value)}})}function Re(t,e){const n=Un(e);for(let e=0;e<n.length;e++){const r=n[e];try{if(r.isInlineSwap(t)){return true}}catch(e){O(e)}}return t==="outerHTML"}function He(e,o,i,t){t=t||ne();let n="#"+ee(o,"id");let s="outerHTML";if(e==="true"){}else if(e.indexOf(":")>0){s=e.substring(0,e.indexOf(":"));n=e.substring(e.indexOf(":")+1)}else{s=e}o.removeAttribute("hx-swap-oob");o.removeAttribute("data-hx-swap-oob");const r=p(t,n,false);if(r){se(r,function(e){let t;const n=o.cloneNode(true);t=ne().createDocumentFragment();t.appendChild(n);if(!Re(s,e)){t=f(n)}const r={shouldSwap:true,target:e,fragment:t};if(!he(e,"htmx:oobBeforeSwap",r))return;e=r.target;if(r.shouldSwap){qe(t);_e(s,e,e,t,i);Te()}se(i.elts,function(e){he(e,"htmx:oobAfterSwap",r)})});o.parentNode.removeChild(o)}else{o.parentNode.removeChild(o);fe(ne().body,"htmx:oobErrorNoTarget",{content:o})}return e}function Te(){const e=u("#--htmx-preserve-pantry--");if(e){for(const t of[...e.children]){const n=u("#"+t.id);n.parentNode.moveBefore(t,n);n.remove()}e.remove()}}function qe(e){se(x(e,"[hx-preserve], [data-hx-preserve]"),function(e){const t=te(e,"id");const n=ne().getElementById(t);if(n!=null){if(e.moveBefore){let e=u("#--htmx-preserve-pantry--");if(e==null){ne().body.insertAdjacentHTML("afterend","<div id='--htmx-preserve-pantry--'></div>");e=u("#--htmx-preserve-pantry--")}e.moveBefore(n,null)}else{e.parentNode.replaceChild(n,e)}}})}function Le(l,e,c){se(e.querySelectorAll("[id]"),function(t){const n=ee(t,"id");if(n&&n.length>0){const r=n.replace("'","\\'");const o=t.tagName.replace(":","\\:");const e=f(l);const i=e&&e.querySelector(o+"[id='"+r+"']");if(i&&i!==e){const s=t.cloneNode();Oe(t,i);c.tasks.push(function(){Oe(t,s)})}}})}function Ae(e){return function(){G(e,Q.config.addedClass);kt(ue(e));Ne(f(e));he(e,"htmx:load")}}function Ne(e){const t="[autofocus]";const n=$(h(e,t)?e:e.querySelector(t));if(n!=null){n.focus()}}function a(e,t,n,r){Le(e,n,r);while(n.childNodes.length>0){const o=n.firstChild;K(ue(o),Q.config.addedClass);e.insertBefore(o,t);if(o.nodeType!==Node.TEXT_NODE&&o.nodeType!==Node.COMMENT_NODE){r.tasks.push(Ae(o))}}}function Ie(e,t){let n=0;while(n<e.length){t=(t<<5)-t+e.charCodeAt(n++)|0}return t}function Pe(t){let n=0;if(t.attributes){for(let e=0;e<t.attributes.length;e++){const r=t.attributes[e];if(r.value){n=Ie(r.name,n);n=Ie(r.value,n)}}}return n}function ke(t){const n=ie(t);if(n.onHandlers){for(let e=0;e<n.onHandlers.length;e++){const r=n.onHandlers[e];be(t,r.event,r.listener)}delete n.onHandlers}}function De(e){const t=ie(e);if(t.timeout){clearTimeout(t.timeout)}if(t.listenerInfos){se(t.listenerInfos,function(e){if(e.on){be(e.on,e.trigger,e.listener)}})}ke(e);se(Object.keys(t),function(e){if(e!=="firstInitCompleted")delete t[e]})}function b(e){he(e,"htmx:beforeCleanupElement");De(e);if(e.children){se(e.children,function(e){b(e)})}}function Me(t,e,n){if(t instanceof Element&&t.tagName==="BODY"){return Ve(t,e,n)}let r;const o=t.previousSibling;const i=c(t);if(!i){return}a(i,t,e,n);if(o==null){r=i.firstChild}else{r=o.nextSibling}n.elts=n.elts.filter(function(e){return e!==t});while(r&&r!==t){if(r instanceof Element){n.elts.push(r)}r=r.nextSibling}b(t);if(t instanceof Element){t.remove()}else{t.parentNode.removeChild(t)}}function Xe(e,t,n){return a(e,e.firstChild,t,n)}function Fe(e,t,n){return a(c(e),e,t,n)}function Be(e,t,n){return a(e,null,t,n)}function Ue(e,t,n){return a(c(e),e.nextSibling,t,n)}function je(e){b(e);const t=c(e);if(t){return t.removeChild(e)}}function Ve(e,t,n){const r=e.firstChild;a(e,r,t,n);if(r){while(r.nextSibling){b(r.nextSibling);e.removeChild(r.nextSibling)}b(r);e.removeChild(r)}}function _e(t,e,n,r,o){switch(t){case"none":return;case"outerHTML":Me(n,r,o);return;case"afterbegin":Xe(n,r,o);return;case"beforebegin":Fe(n,r,o);return;case"beforeend":Be(n,r,o);return;case"afterend":Ue(n,r,o);return;case"delete":je(n);return;default:var i=Un(e);for(let e=0;e<i.length;e++){const s=i[e];try{const l=s.handleSwap(t,n,r,o);if(l){if(Array.isArray(l)){for(let e=0;e<l.length;e++){const c=l[e];if(c.nodeType!==Node.TEXT_NODE&&c.nodeType!==Node.COMMENT_NODE){o.tasks.push(Ae(c))}}}return}}catch(e){O(e)}}if(t==="innerHTML"){Ve(n,r,o)}else{_e(Q.config.defaultSwapStyle,e,n,r,o)}}}function ze(e,n,r){var t=x(e,"[hx-swap-oob], [data-hx-swap-oob]");se(t,function(e){if(Q.config.allowNestedOobSwaps||e.parentElement===null){const t=te(e,"hx-swap-oob");if(t!=null){He(t,e,n,r)}}else{e.removeAttribute("hx-swap-oob");e.removeAttribute("data-hx-swap-oob")}});return t.length>0}function $e(e,t,r,o){if(!o){o={}}e=y(e);const i=o.contextElement?m(o.contextElement,false):ne();const n=document.activeElement;let s={};try{s={elt:n,start:n?n.selectionStart:null,end:n?n.selectionEnd:null}}catch(e){}const l=xn(e);if(r.swapStyle==="textContent"){e.textContent=t}else{let n=P(t);l.title=n.title;if(o.selectOOB){const u=o.selectOOB.split(",");for(let t=0;t<u.length;t++){const a=u[t].split(":",2);let e=a[0].trim();if(e.indexOf("#")===0){e=e.substring(1)}const f=a[1]||"true";const h=n.querySelector("#"+e);if(h){He(f,h,l,i)}}}ze(n,l,i);se(x(n,"template"),function(e){if(e.content&&ze(e.content,l,i)){e.remove()}});if(o.select){const d=ne().createDocumentFragment();se(n.querySelectorAll(o.select),function(e){d.appendChild(e)});n=d}qe(n);_e(r.swapStyle,o.contextElement,e,n,l);Te()}if(s.elt&&!le(s.elt)&&ee(s.elt,"id")){const g=document.getElementById(ee(s.elt,"id"));const p={preventScroll:r.focusScroll!==undefined?!r.focusScroll:!Q.config.defaultFocusScroll};if(g){if(s.start&&g.setSelectionRange){try{g.setSelectionRange(s.start,s.end)}catch(e){}}g.focus(p)}}e.classList.remove(Q.config.swappingClass);se(l.elts,function(e){if(e.classList){e.classList.add(Q.config.settlingClass)}he(e,"htmx:afterSwap",o.eventInfo)});if(o.afterSwapCallback){o.afterSwapCallback()}if(!r.ignoreTitle){kn(l.title)}const c=function(){se(l.tasks,function(e){e.call()});se(l.elts,function(e){if(e.classList){e.classList.remove(Q.config.settlingClass)}he(e,"htmx:afterSettle",o.eventInfo)});if(o.anchor){const e=ue(y("#"+o.anchor));if(e){e.scrollIntoView({block:"start",behavior:"auto"})}}yn(l.elts,r);if(o.afterSettleCallback){o.afterSettleCallback()}};if(r.settleDelay>0){E().setTimeout(c,r.settleDelay)}else{c()}}function Je(e,t,n){const r=e.getResponseHeader(t);if(r.indexOf("{")===0){const o=S(r);for(const i in o){if(o.hasOwnProperty(i)){let e=o[i];if(D(e)){n=e.target!==undefined?e.target:n}else{e={value:e}}he(n,i,e)}}}else{const s=r.split(",");for(let e=0;e<s.length;e++){he(n,s[e].trim(),[])}}}const Ke=/\s/;const v=/[\s,]/;const Ge=/[_$a-zA-Z]/;const We=/[_$a-zA-Z0-9]/;const Ze=['"',"'","/"];const w=/[^\s]/;const Ye=/[{(]/;const Qe=/[})]/;function et(e){const t=[];let n=0;while(n<e.length){if(Ge.exec(e.charAt(n))){var r=n;while(We.exec(e.charAt(n+1))){n++}t.push(e.substring(r,n+1))}else if(Ze.indexOf(e.charAt(n))!==-1){const o=e.charAt(n);var r=n;n++;while(n<e.length&&e.charAt(n)!==o){if(e.charAt(n)==="\\"){n++}n++}t.push(e.substring(r,n+1))}else{const i=e.charAt(n);t.push(i)}n++}return t}function tt(e,t,n){return Ge.exec(e.charAt(0))&&e!=="true"&&e!=="false"&&e!=="this"&&e!==n&&t!=="."}function nt(r,o,i){if(o[0]==="["){o.shift();let e=1;let t=" return (function("+i+"){ return (";let n=null;while(o.length>0){const s=o[0];if(s==="]"){e--;if(e===0){if(n===null){t=t+"true"}o.shift();t+=")})";try{const l=vn(r,function(){return Function(t)()},function(){return true});l.source=t;return l}catch(e){fe(ne().body,"htmx:syntax:error",{error:e,source:t});return null}}}else if(s==="["){e++}if(tt(s,n,i)){t+="(("+i+"."+s+") ? ("+i+"."+s+") : (window."+s+"))"}else{t=t+s}n=o.shift()}}}function C(e,t){let n="";while(e.length>0&&!t.test(e[0])){n+=e.shift()}return n}function rt(e){let t;if(e.length>0&&Ye.test(e[0])){e.shift();t=C(e,Qe).trim();e.shift()}else{t=C(e,v)}return t}const ot="input, textarea, select";function it(e,t,n){const r=[];const o=et(t);do{C(o,w);const l=o.length;const c=C(o,/[,\[\s]/);if(c!==""){if(c==="every"){const u={trigger:"every"};C(o,w);u.pollInterval=d(C(o,/[,\[\s]/));C(o,w);var i=nt(e,o,"event");if(i){u.eventFilter=i}r.push(u)}else{const a={trigger:c};var i=nt(e,o,"event");if(i){a.eventFilter=i}C(o,w);while(o.length>0&&o[0]!==","){const f=o.shift();if(f==="changed"){a.changed=true}else if(f==="once"){a.once=true}else if(f==="consume"){a.consume=true}else if(f==="delay"&&o[0]===":"){o.shift();a.delay=d(C(o,v))}else if(f==="from"&&o[0]===":"){o.shift();if(Ye.test(o[0])){var s=rt(o)}else{var s=C(o,v);if(s==="closest"||s==="find"||s==="next"||s==="previous"){o.shift();const h=rt(o);if(h.length>0){s+=" "+h}}}a.from=s}else if(f==="target"&&o[0]===":"){o.shift();a.target=rt(o)}else if(f==="throttle"&&o[0]===":"){o.shift();a.throttle=d(C(o,v))}else if(f==="queue"&&o[0]===":"){o.shift();a.queue=C(o,v)}else if(f==="root"&&o[0]===":"){o.shift();a[f]=rt(o)}else if(f==="threshold"&&o[0]===":"){o.shift();a[f]=C(o,v)}else{fe(e,"htmx:syntax:error",{token:o.shift()})}C(o,w)}r.push(a)}}if(o.length===l){fe(e,"htmx:syntax:error",{token:o.shift()})}C(o,w)}while(o[0]===","&&o.shift());if(n){n[t]=r}return r}function st(e){const t=te(e,"hx-trigger");let n=[];if(t){const r=Q.config.triggerSpecsCache;n=r&&r[t]||it(e,t,r)}if(n.length>0){return n}else if(h(e,"form")){return[{trigger:"submit"}]}else if(h(e,'input[type="button"], input[type="submit"]')){return[{trigger:"click"}]}else if(h(e,ot)){return[{trigger:"change"}]}else{return[{trigger:"click"}]}}function lt(e){ie(e).cancelled=true}function ct(e,t,n){const r=ie(e);r.timeout=E().setTimeout(function(){if(le(e)&&r.cancelled!==true){if(!gt(n,e,Mt("hx:poll:trigger",{triggerSpec:n,target:e}))){t(e)}ct(e,t,n)}},n.pollInterval)}function ut(e){return location.hostname===e.hostname&&ee(e,"href")&&ee(e,"href").indexOf("#")!==0}function at(e){return g(e,Q.config.disableSelector)}function ft(t,n,e){if(t instanceof HTMLAnchorElement&&ut(t)&&(t.target===""||t.target==="_self")||t.tagName==="FORM"&&String(ee(t,"method")).toLowerCase()!=="dialog"){n.boosted=true;let r,o;if(t.tagName==="A"){r="get";o=ee(t,"href")}else{const i=ee(t,"method");r=i?i.toLowerCase():"get";o=ee(t,"action");if(o==null||o===""){o=ne().location.href}if(r==="get"&&o.includes("?")){o=o.replace(/\?[^#]+/,"")}}e.forEach(function(e){pt(t,function(e,t){const n=ue(e);if(at(n)){b(n);return}de(r,o,n,t)},n,e,true)})}}function ht(e,t){const n=ue(t);if(!n){return false}if(e.type==="submit"||e.type==="click"){if(n.tagName==="FORM"){return true}if(h(n,'input[type="submit"], button')&&(h(n,"[form]")||g(n,"form")!==null)){return true}if(n instanceof HTMLAnchorElement&&n.href&&(n.getAttribute("href")==="#"||n.getAttribute("href").indexOf("#")!==0)){return true}}return false}function dt(e,t){return ie(e).boosted&&e instanceof HTMLAnchorElement&&t.type==="click"&&(t.ctrlKey||t.metaKey)}function gt(e,t,n){const r=e.eventFilter;if(r){try{return r.call(t,n)!==true}catch(e){const o=r.source;fe(ne().body,"htmx:eventFilter:error",{error:e,source:o});return true}}return false}function pt(l,c,e,u,a){const f=ie(l);let t;if(u.from){t=p(l,u.from)}else{t=[l]}if(u.changed){if(!("lastValue"in f)){f.lastValue=new WeakMap}t.forEach(function(e){if(!f.lastValue.has(u)){f.lastValue.set(u,new WeakMap)}f.lastValue.get(u).set(e,e.value)})}se(t,function(i){const s=function(e){if(!le(l)){i.removeEventListener(u.trigger,s);return}if(dt(l,e)){return}if(a||ht(e,l)){e.preventDefault()}if(gt(u,l,e)){return}const t=ie(e);t.triggerSpec=u;if(t.handledFor==null){t.handledFor=[]}if(t.handledFor.indexOf(l)<0){t.handledFor.push(l);if(u.consume){e.stopPropagation()}if(u.target&&e.target){if(!h(ue(e.target),u.target)){return}}if(u.once){if(f.triggeredOnce){return}else{f.triggeredOnce=true}}if(u.changed){const n=event.target;const r=n.value;const o=f.lastValue.get(u);if(o.has(n)&&o.get(n)===r){return}o.set(n,r)}if(f.delayed){clearTimeout(f.delayed)}if(f.throttle){return}if(u.throttle>0){if(!f.throttle){he(l,"htmx:trigger");c(l,e);f.throttle=E().setTimeout(function(){f.throttle=null},u.throttle)}}else if(u.delay>0){f.delayed=E().setTimeout(function(){he(l,"htmx:trigger");c(l,e)},u.delay)}else{he(l,"htmx:trigger");c(l,e)}}};if(e.listenerInfos==null){e.listenerInfos=[]}e.listenerInfos.push({trigger:u.trigger,listener:s,on:i});i.addEventListener(u.trigger,s)})}let mt=false;let xt=null;function yt(){if(!xt){xt=function(){mt=true};window.addEventListener("scroll",xt);window.addEventListener("resize",xt);setInterval(function(){if(mt){mt=false;se(ne().querySelectorAll("[hx-trigger*='revealed'],[data-hx-trigger*='revealed']"),function(e){bt(e)})}},200)}}function bt(e){if(!s(e,"data-hx-revealed")&&X(e)){e.setAttribute("data-hx-revealed","true");const t=ie(e);if(t.initHash){he(e,"revealed")}else{e.addEventListener("htmx:afterProcessNode",function(){he(e,"revealed")},{once:true})}}}function vt(e,t,n,r){const o=function(){if(!n.loaded){n.loaded=true;he(e,"htmx:trigger");t(e)}};if(r>0){E().setTimeout(o,r)}else{o()}}function wt(t,n,e){let i=false;se(r,function(r){if(s(t,"hx-"+r)){const o=te(t,"hx-"+r);i=true;n.path=o;n.verb=r;e.forEach(function(e){St(t,e,n,function(e,t){const n=ue(e);if(g(n,Q.config.disableSelector)){b(n);return}de(r,o,n,t)})})}});return i}function St(r,e,t,n){if(e.trigger==="revealed"){yt();pt(r,n,t,e);bt(ue(r))}else if(e.trigger==="intersect"){const o={};if(e.root){o.root=ae(r,e.root)}if(e.threshold){o.threshold=parseFloat(e.threshold)}const i=new IntersectionObserver(function(t){for(let e=0;e<t.length;e++){const n=t[e];if(n.isIntersecting){he(r,"intersect");break}}},o);i.observe(ue(r));pt(ue(r),n,t,e)}else if(!t.firstInitCompleted&&e.trigger==="load"){if(!gt(e,r,Mt("load",{elt:r}))){vt(ue(r),n,t,e.delay)}}else if(e.pollInterval>0){t.polling=true;ct(ue(r),n,e)}else{pt(r,n,t,e)}}function Et(e){const t=ue(e);if(!t){return false}const n=t.attributes;for(let e=0;e<n.length;e++){const r=n[e].name;if(l(r,"hx-on:")||l(r,"data-hx-on:")||l(r,"hx-on-")||l(r,"data-hx-on-")){return true}}return false}const Ct=(new XPathEvaluator).createExpression('.//*[@*[ starts-with(name(), "hx-on:") or starts-with(name(), "data-hx-on:") or'+' starts-with(name(), "hx-on-") or starts-with(name(), "data-hx-on-") ]]');function Ot(e,t){if(Et(e)){t.push(ue(e))}const n=Ct.evaluate(e);let r=null;while(r=n.iterateNext())t.push(ue(r))}function Rt(e){const t=[];if(e instanceof DocumentFragment){for(const n of e.childNodes){Ot(n,t)}}else{Ot(e,t)}return t}function Ht(e){if(e.querySelectorAll){const n=", [hx-boost] a, [data-hx-boost] a, a[hx-boost], a[data-hx-boost]";const r=[];for(const i in Mn){const s=Mn[i];if(s.getSelectors){var t=s.getSelectors();if(t){r.push(t)}}}const o=e.querySelectorAll(H+n+", form, [type='submit'],"+" [hx-ext], [data-hx-ext], [hx-trigger], [data-hx-trigger]"+r.flat().map(e=>", "+e).join(""));return o}else{return[]}}function Tt(e){const t=g(ue(e.target),"button, input[type='submit']");const n=Lt(e);if(n){n.lastButtonClicked=t}}function qt(e){const t=Lt(e);if(t){t.lastButtonClicked=null}}function Lt(e){const t=g(ue(e.target),"button, input[type='submit']");if(!t){return}const n=y("#"+ee(t,"form"),t.getRootNode())||g(t,"form");if(!n){return}return ie(n)}function At(e){e.addEventListener("click",Tt);e.addEventListener("focusin",Tt);e.addEventListener("focusout",qt)}function Nt(t,e,n){const r=ie(t);if(!Array.isArray(r.onHandlers)){r.onHandlers=[]}let o;const i=function(e){vn(t,function(){if(at(t)){return}if(!o){o=new Function("event",n)}o.call(t,e)})};t.addEventListener(e,i);r.onHandlers.push({event:e,listener:i})}function It(t){ke(t);for(let e=0;e<t.attributes.length;e++){const n=t.attributes[e].name;const r=t.attributes[e].value;if(l(n,"hx-on")||l(n,"data-hx-on")){const o=n.indexOf("-on")+3;const i=n.slice(o,o+1);if(i==="-"||i===":"){let e=n.slice(o+1);if(l(e,":")){e="htmx"+e}else if(l(e,"-")){e="htmx:"+e.slice(1)}else if(l(e,"htmx-")){e="htmx:"+e.slice(5)}Nt(t,e,r)}}}}function Pt(t){if(g(t,Q.config.disableSelector)){b(t);return}const n=ie(t);const e=Pe(t);if(n.initHash!==e){De(t);n.initHash=e;he(t,"htmx:beforeProcessNode");const r=st(t);const o=wt(t,n,r);if(!o){if(re(t,"hx-boost")==="true"){ft(t,n,r)}else if(s(t,"hx-trigger")){r.forEach(function(e){St(t,e,n,function(){})})}}if(t.tagName==="FORM"||ee(t,"type")==="submit"&&s(t,"form")){At(t)}n.firstInitCompleted=true;he(t,"htmx:afterProcessNode")}}function kt(e){e=y(e);if(g(e,Q.config.disableSelector)){b(e);return}Pt(e);se(Ht(e),function(e){Pt(e)});se(Rt(e),It)}function Dt(e){return e.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase()}function Mt(e,t){let n;if(window.CustomEvent&&typeof window.CustomEvent==="function"){n=new CustomEvent(e,{bubbles:true,cancelable:true,composed:true,detail:t})}else{n=ne().createEvent("CustomEvent");n.initCustomEvent(e,true,true,t)}return n}function fe(e,t,n){he(e,t,ce({error:t},n))}function Xt(e){return e==="htmx:afterProcessNode"}function Ft(e,t){se(Un(e),function(e){try{t(e)}catch(e){O(e)}})}function O(e){if(console.error){console.error(e)}else if(console.log){console.log("ERROR: ",e)}}function he(e,t,n){e=y(e);if(n==null){n={}}n.elt=e;const r=Mt(t,n);if(Q.logger&&!Xt(t)){Q.logger(e,t,n)}if(n.error){O(n.error);he(e,"htmx:error",{errorInfo:n})}let o=e.dispatchEvent(r);const i=Dt(t);if(o&&i!==t){const s=Mt(i,r.detail);o=o&&e.dispatchEvent(s)}Ft(ue(e),function(e){o=o&&(e.onEvent(t,r)!==false&&!r.defaultPrevented)});return o}let Bt=location.pathname+location.search;function Ut(){const e=ne().querySelector("[hx-history-elt],[data-hx-history-elt]");return e||ne().body}function jt(t,e){if(!B()){return}const n=_t(e);const r=ne().title;const o=window.scrollY;if(Q.config.historyCacheSize<=0){localStorage.removeItem("htmx-history-cache");return}t=U(t);const i=S(localStorage.getItem("htmx-history-cache"))||[];for(let e=0;e<i.length;e++){if(i[e].url===t){i.splice(e,1);break}}const s={url:t,content:n,title:r,scroll:o};he(ne().body,"htmx:historyItemCreated",{item:s,cache:i});i.push(s);while(i.length>Q.config.historyCacheSize){i.shift()}while(i.length>0){try{localStorage.setItem("htmx-history-cache",JSON.stringify(i));break}catch(e){fe(ne().body,"htmx:historyCacheError",{cause:e,cache:i});i.shift()}}}function Vt(t){if(!B()){return null}t=U(t);const n=S(localStorage.getItem("htmx-history-cache"))||[];for(let e=0;e<n.length;e++){if(n[e].url===t){return n[e]}}return null}function _t(e){const t=Q.config.requestClass;const n=e.cloneNode(true);se(x(n,"."+t),function(e){G(e,t)});se(x(n,"[data-disabled-by-htmx]"),function(e){e.removeAttribute("disabled")});return n.innerHTML}function zt(){const e=Ut();const t=Bt||location.pathname+location.search;let n;try{n=ne().querySelector('[hx-history="false" i],[data-hx-history="false" i]')}catch(e){n=ne().querySelector('[hx-history="false"],[data-hx-history="false"]')}if(!n){he(ne().body,"htmx:beforeHistorySave",{path:t,historyElt:e});jt(t,e)}if(Q.config.historyEnabled)history.replaceState({htmx:true},ne().title,window.location.href)}function $t(e){if(Q.config.getCacheBusterParam){e=e.replace(/org\.htmx\.cache-buster=[^&]*&?/,"");if(Y(e,"&")||Y(e,"?")){e=e.slice(0,-1)}}if(Q.config.historyEnabled){history.pushState({htmx:true},"",e)}Bt=e}function Jt(e){if(Q.config.historyEnabled)history.replaceState({htmx:true},"",e);Bt=e}function Kt(e){se(e,function(e){e.call(undefined)})}function Gt(o){const e=new XMLHttpRequest;const i={path:o,xhr:e};he(ne().body,"htmx:historyCacheMiss",i);e.open("GET",o,true);e.setRequestHeader("HX-Request","true");e.setRequestHeader("HX-History-Restore-Request","true");e.setRequestHeader("HX-Current-URL",ne().location.href);e.onload=function(){if(this.status>=200&&this.status<400){he(ne().body,"htmx:historyCacheMissLoad",i);const e=P(this.response);const t=e.querySelector("[hx-history-elt],[data-hx-history-elt]")||e;const n=Ut();const r=xn(n);kn(e.title);qe(e);Ve(n,t,r);Te();Kt(r.tasks);Bt=o;he(ne().body,"htmx:historyRestore",{path:o,cacheMiss:true,serverResponse:this.response})}else{fe(ne().body,"htmx:historyCacheMissLoadError",i)}};e.send()}function Wt(e){zt();e=e||location.pathname+location.search;const t=Vt(e);if(t){const n=P(t.content);const r=Ut();const o=xn(r);kn(t.title);qe(n);Ve(r,n,o);Te();Kt(o.tasks);E().setTimeout(function(){window.scrollTo(0,t.scroll)},0);Bt=e;he(ne().body,"htmx:historyRestore",{path:e,item:t})}else{if(Q.config.refreshOnHistoryMiss){window.location.reload(true)}else{Gt(e)}}}function Zt(e){let t=we(e,"hx-indicator");if(t==null){t=[e]}se(t,function(e){const t=ie(e);t.requestCount=(t.requestCount||0)+1;e.classList.add.call(e.classList,Q.config.requestClass)});return t}function Yt(e){let t=we(e,"hx-disabled-elt");if(t==null){t=[]}se(t,function(e){const t=ie(e);t.requestCount=(t.requestCount||0)+1;e.setAttribute("disabled","");e.setAttribute("data-disabled-by-htmx","")});return t}function Qt(e,t){se(e.concat(t),function(e){const t=ie(e);t.requestCount=(t.requestCount||1)-1});se(e,function(e){const t=ie(e);if(t.requestCount===0){e.classList.remove.call(e.classList,Q.config.requestClass)}});se(t,function(e){const t=ie(e);if(t.requestCount===0){e.removeAttribute("disabled");e.removeAttribute("data-disabled-by-htmx")}})}function en(t,n){for(let e=0;e<t.length;e++){const r=t[e];if(r.isSameNode(n)){return true}}return false}function tn(e){const t=e;if(t.name===""||t.name==null||t.disabled||g(t,"fieldset[disabled]")){return false}if(t.type==="button"||t.type==="submit"||t.tagName==="image"||t.tagName==="reset"||t.tagName==="file"){return false}if(t.type==="checkbox"||t.type==="radio"){return t.checked}return true}function nn(t,e,n){if(t!=null&&e!=null){if(Array.isArray(e)){e.forEach(function(e){n.append(t,e)})}else{n.append(t,e)}}}function rn(t,n,r){if(t!=null&&n!=null){let e=r.getAll(t);if(Array.isArray(n)){e=e.filter(e=>n.indexOf(e)<0)}else{e=e.filter(e=>e!==n)}r.delete(t);se(e,e=>r.append(t,e))}}function on(t,n,r,o,i){if(o==null||en(t,o)){return}else{t.push(o)}if(tn(o)){const s=ee(o,"name");let e=o.value;if(o instanceof HTMLSelectElement&&o.multiple){e=M(o.querySelectorAll("option:checked")).map(function(e){return e.value})}if(o instanceof HTMLInputElement&&o.files){e=M(o.files)}nn(s,e,n);if(i){sn(o,r)}}if(o instanceof HTMLFormElement){se(o.elements,function(e){if(t.indexOf(e)>=0){rn(e.name,e.value,n)}else{t.push(e)}if(i){sn(e,r)}});new FormData(o).forEach(function(e,t){if(e instanceof File&&e.name===""){return}nn(t,e,n)})}}function sn(e,t){const n=e;if(n.willValidate){he(n,"htmx:validation:validate");if(!n.checkValidity()){t.push({elt:n,message:n.validationMessage,validity:n.validity});he(n,"htmx:validation:failed",{message:n.validationMessage,validity:n.validity})}}}function ln(n,e){for(const t of e.keys()){n.delete(t)}e.forEach(function(e,t){n.append(t,e)});return n}function cn(e,t){const n=[];const r=new FormData;const o=new FormData;const i=[];const s=ie(e);if(s.lastButtonClicked&&!le(s.lastButtonClicked)){s.lastButtonClicked=null}let l=e instanceof HTMLFormElement&&e.noValidate!==true||te(e,"hx-validate")==="true";if(s.lastButtonClicked){l=l&&s.lastButtonClicked.formNoValidate!==true}if(t!=="get"){on(n,o,i,g(e,"form"),l)}on(n,r,i,e,l);if(s.lastButtonClicked||e.tagName==="BUTTON"||e.tagName==="INPUT"&&ee(e,"type")==="submit"){const u=s.lastButtonClicked||e;const a=ee(u,"name");nn(a,u.value,o)}const c=we(e,"hx-include");se(c,function(e){on(n,r,i,ue(e),l);if(!h(e,"form")){se(f(e).querySelectorAll(ot),function(e){on(n,r,i,e,l)})}});ln(r,o);return{errors:i,formData:r,values:An(r)}}function un(e,t,n){if(e!==""){e+="&"}if(String(n)==="[object Object]"){n=JSON.stringify(n)}const r=encodeURIComponent(n);e+=encodeURIComponent(t)+"="+r;return e}function an(e){e=qn(e);let n="";e.forEach(function(e,t){n=un(n,t,e)});return n}function fn(e,t,n){const r={"HX-Request":"true","HX-Trigger":ee(e,"id"),"HX-Trigger-Name":ee(e,"name"),"HX-Target":te(t,"id"),"HX-Current-URL":ne().location.href};bn(e,"hx-headers",false,r);if(n!==undefined){r["HX-Prompt"]=n}if(ie(e).boosted){r["HX-Boosted"]="true"}return r}function hn(n,e){const t=re(e,"hx-params");if(t){if(t==="none"){return new FormData}else if(t==="*"){return n}else if(t.indexOf("not ")===0){se(t.slice(4).split(","),function(e){e=e.trim();n.delete(e)});return n}else{const r=new FormData;se(t.split(","),function(t){t=t.trim();if(n.has(t)){n.getAll(t).forEach(function(e){r.append(t,e)})}});return r}}else{return n}}function dn(e){return!!ee(e,"href")&&ee(e,"href").indexOf("#")>=0}function gn(e,t){const n=t||re(e,"hx-swap");const r={swapStyle:ie(e).boosted?"innerHTML":Q.config.defaultSwapStyle,swapDelay:Q.config.defaultSwapDelay,settleDelay:Q.config.defaultSettleDelay};if(Q.config.scrollIntoViewOnBoost&&ie(e).boosted&&!dn(e)){r.show="top"}if(n){const s=F(n);if(s.length>0){for(let e=0;e<s.length;e++){const l=s[e];if(l.indexOf("swap:")===0){r.swapDelay=d(l.slice(5))}else if(l.indexOf("settle:")===0){r.settleDelay=d(l.slice(7))}else if(l.indexOf("transition:")===0){r.transition=l.slice(11)==="true"}else if(l.indexOf("ignoreTitle:")===0){r.ignoreTitle=l.slice(12)==="true"}else if(l.indexOf("scroll:")===0){const c=l.slice(7);var o=c.split(":");const u=o.pop();var i=o.length>0?o.join(":"):null;r.scroll=u;r.scrollTarget=i}else if(l.indexOf("show:")===0){const a=l.slice(5);var o=a.split(":");const f=o.pop();var i=o.length>0?o.join(":"):null;r.show=f;r.showTarget=i}else if(l.indexOf("focus-scroll:")===0){const h=l.slice("focus-scroll:".length);r.focusScroll=h=="true"}else if(e==0){r.swapStyle=l}else{O("Unknown modifier in hx-swap: "+l)}}}}return r}function pn(e){return re(e,"hx-encoding")==="multipart/form-data"||h(e,"form")&&ee(e,"enctype")==="multipart/form-data"}function mn(t,n,r){let o=null;Ft(n,function(e){if(o==null){o=e.encodeParameters(t,r,n)}});if(o!=null){return o}else{if(pn(n)){return ln(new FormData,qn(r))}else{return an(r)}}}function xn(e){return{tasks:[],elts:[e]}}function yn(e,t){const n=e[0];const r=e[e.length-1];if(t.scroll){var o=null;if(t.scrollTarget){o=ue(ae(n,t.scrollTarget))}if(t.scroll==="top"&&(n||o)){o=o||n;o.scrollTop=0}if(t.scroll==="bottom"&&(r||o)){o=o||r;o.scrollTop=o.scrollHeight}}if(t.show){var o=null;if(t.showTarget){let e=t.showTarget;if(t.showTarget==="window"){e="body"}o=ue(ae(n,e))}if(t.show==="top"&&(n||o)){o=o||n;o.scrollIntoView({block:"start",behavior:Q.config.scrollBehavior})}if(t.show==="bottom"&&(r||o)){o=o||r;o.scrollIntoView({block:"end",behavior:Q.config.scrollBehavior})}}}function bn(r,e,o,i){if(i==null){i={}}if(r==null){return i}const s=te(r,e);if(s){let e=s.trim();let t=o;if(e==="unset"){return null}if(e.indexOf("javascript:")===0){e=e.slice(11);t=true}else if(e.indexOf("js:")===0){e=e.slice(3);t=true}if(e.indexOf("{")!==0){e="{"+e+"}"}let n;if(t){n=vn(r,function(){return Function("return ("+e+")")()},{})}else{n=S(e)}for(const l in n){if(n.hasOwnProperty(l)){if(i[l]==null){i[l]=n[l]}}}}return bn(ue(c(r)),e,o,i)}function vn(e,t,n){if(Q.config.allowEval){return t()}else{fe(e,"htmx:evalDisallowedError");return n}}function wn(e,t){return bn(e,"hx-vars",true,t)}function Sn(e,t){return bn(e,"hx-vals",false,t)}function En(e){return ce(wn(e),Sn(e))}function Cn(t,n,r){if(r!==null){try{t.setRequestHeader(n,r)}catch(e){t.setRequestHeader(n,encodeURIComponent(r));t.setRequestHeader(n+"-URI-AutoEncoded","true")}}}function On(t){if(t.responseURL&&typeof URL!=="undefined"){try{const e=new URL(t.responseURL);return e.pathname+e.search}catch(e){fe(ne().body,"htmx:badResponseUrl",{url:t.responseURL})}}}function R(e,t){return t.test(e.getAllResponseHeaders())}function Rn(t,n,r){t=t.toLowerCase();if(r){if(r instanceof Element||typeof r==="string"){return de(t,n,null,null,{targetOverride:y(r)||ve,returnPromise:true})}else{let e=y(r.target);if(r.target&&!e||r.source&&!e&&!y(r.source)){e=ve}return de(t,n,y(r.source),r.event,{handler:r.handler,headers:r.headers,values:r.values,targetOverride:e,swapOverride:r.swap,select:r.select,returnPromise:true})}}else{return de(t,n,null,null,{returnPromise:true})}}function Hn(e){const t=[];while(e){t.push(e);e=e.parentElement}return t}function Tn(e,t,n){let r;let o;if(typeof URL==="function"){o=new URL(t,document.location.href);const i=document.location.origin;r=i===o.origin}else{o=t;r=l(t,document.location.origin)}if(Q.config.selfRequestsOnly){if(!r){return false}}return he(e,"htmx:validateUrl",ce({url:o,sameHost:r},n))}function qn(e){if(e instanceof FormData)return e;const t=new FormData;for(const n in e){if(e.hasOwnProperty(n)){if(e[n]&&typeof e[n].forEach==="function"){e[n].forEach(function(e){t.append(n,e)})}else if(typeof e[n]==="object"&&!(e[n]instanceof Blob)){t.append(n,JSON.stringify(e[n]))}else{t.append(n,e[n])}}}return t}function Ln(r,o,e){return new Proxy(e,{get:function(t,e){if(typeof e==="number")return t[e];if(e==="length")return t.length;if(e==="push"){return function(e){t.push(e);r.append(o,e)}}if(typeof t[e]==="function"){return function(){t[e].apply(t,arguments);r.delete(o);t.forEach(function(e){r.append(o,e)})}}if(t[e]&&t[e].length===1){return t[e][0]}else{return t[e]}},set:function(e,t,n){e[t]=n;r.delete(o);e.forEach(function(e){r.append(o,e)});return true}})}function An(o){return new Proxy(o,{get:function(e,t){if(typeof t==="symbol"){const r=Reflect.get(e,t);if(typeof r==="function"){return function(){return r.apply(o,arguments)}}else{return r}}if(t==="toJSON"){return()=>Object.fromEntries(o)}if(t in e){if(typeof e[t]==="function"){return function(){return o[t].apply(o,arguments)}}else{return e[t]}}const n=o.getAll(t);if(n.length===0){return undefined}else if(n.length===1){return n[0]}else{return Ln(e,t,n)}},set:function(t,n,e){if(typeof n!=="string"){return false}t.delete(n);if(e&&typeof e.forEach==="function"){e.forEach(function(e){t.append(n,e)})}else if(typeof e==="object"&&!(e instanceof Blob)){t.append(n,JSON.stringify(e))}else{t.append(n,e)}return true},deleteProperty:function(e,t){if(typeof t==="string"){e.delete(t)}return true},ownKeys:function(e){return Reflect.ownKeys(Object.fromEntries(e))},getOwnPropertyDescriptor:function(e,t){return Reflect.getOwnPropertyDescriptor(Object.fromEntries(e),t)}})}function de(t,n,r,o,i,D){let s=null;let l=null;i=i!=null?i:{};if(i.returnPromise&&typeof Promise!=="undefined"){var e=new Promise(function(e,t){s=e;l=t})}if(r==null){r=ne().body}const M=i.handler||Dn;const X=i.select||null;if(!le(r)){oe(s);return e}const c=i.targetOverride||ue(Ee(r));if(c==null||c==ve){fe(r,"htmx:targetError",{target:te(r,"hx-target")});oe(l);return e}let u=ie(r);const a=u.lastButtonClicked;if(a){const L=ee(a,"formaction");if(L!=null){n=L}const A=ee(a,"formmethod");if(A!=null){if(A.toLowerCase()!=="dialog"){t=A}}}const f=re(r,"hx-confirm");if(D===undefined){const K=function(e){return de(t,n,r,o,i,!!e)};const G={target:c,elt:r,path:n,verb:t,triggeringEvent:o,etc:i,issueRequest:K,question:f};if(he(r,"htmx:confirm",G)===false){oe(s);return e}}let h=r;let d=re(r,"hx-sync");let g=null;let F=false;if(d){const N=d.split(":");const I=N[0].trim();if(I==="this"){h=Se(r,"hx-sync")}else{h=ue(ae(r,I))}d=(N[1]||"drop").trim();u=ie(h);if(d==="drop"&&u.xhr&&u.abortable!==true){oe(s);return e}else if(d==="abort"){if(u.xhr){oe(s);return e}else{F=true}}else if(d==="replace"){he(h,"htmx:abort")}else if(d.indexOf("queue")===0){const W=d.split(" ");g=(W[1]||"last").trim()}}if(u.xhr){if(u.abortable){he(h,"htmx:abort")}else{if(g==null){if(o){const P=ie(o);if(P&&P.triggerSpec&&P.triggerSpec.queue){g=P.triggerSpec.queue}}if(g==null){g="last"}}if(u.queuedRequests==null){u.queuedRequests=[]}if(g==="first"&&u.queuedRequests.length===0){u.queuedRequests.push(function(){de(t,n,r,o,i)})}else if(g==="all"){u.queuedRequests.push(function(){de(t,n,r,o,i)})}else if(g==="last"){u.queuedRequests=[];u.queuedRequests.push(function(){de(t,n,r,o,i)})}oe(s);return e}}const p=new XMLHttpRequest;u.xhr=p;u.abortable=F;const m=function(){u.xhr=null;u.abortable=false;if(u.queuedRequests!=null&&u.queuedRequests.length>0){const e=u.queuedRequests.shift();e()}};const B=re(r,"hx-prompt");if(B){var x=prompt(B);if(x===null||!he(r,"htmx:prompt",{prompt:x,target:c})){oe(s);m();return e}}if(f&&!D){if(!confirm(f)){oe(s);m();return e}}let y=fn(r,c,x);if(t!=="get"&&!pn(r)){y["Content-Type"]="application/x-www-form-urlencoded"}if(i.headers){y=ce(y,i.headers)}const U=cn(r,t);let b=U.errors;const j=U.formData;if(i.values){ln(j,qn(i.values))}const V=qn(En(r));const v=ln(j,V);let w=hn(v,r);if(Q.config.getCacheBusterParam&&t==="get"){w.set("org.htmx.cache-buster",ee(c,"id")||"true")}if(n==null||n===""){n=ne().location.href}const S=bn(r,"hx-request");const _=ie(r).boosted;let E=Q.config.methodsThatUseUrlParams.indexOf(t)>=0;const C={boosted:_,useUrlParams:E,formData:w,parameters:An(w),unfilteredFormData:v,unfilteredParameters:An(v),headers:y,target:c,verb:t,errors:b,withCredentials:i.credentials||S.credentials||Q.config.withCredentials,timeout:i.timeout||S.timeout||Q.config.timeout,path:n,triggeringEvent:o};if(!he(r,"htmx:configRequest",C)){oe(s);m();return e}n=C.path;t=C.verb;y=C.headers;w=qn(C.parameters);b=C.errors;E=C.useUrlParams;if(b&&b.length>0){he(r,"htmx:validation:halted",C);oe(s);m();return e}const z=n.split("#");const $=z[0];const O=z[1];let R=n;if(E){R=$;const Z=!w.keys().next().done;if(Z){if(R.indexOf("?")<0){R+="?"}else{R+="&"}R+=an(w);if(O){R+="#"+O}}}if(!Tn(r,R,C)){fe(r,"htmx:invalidPath",C);oe(l);return e}p.open(t.toUpperCase(),R,true);p.overrideMimeType("text/html");p.withCredentials=C.withCredentials;p.timeout=C.timeout;if(S.noHeaders){}else{for(const k in y){if(y.hasOwnProperty(k)){const Y=y[k];Cn(p,k,Y)}}}const H={xhr:p,target:c,requestConfig:C,etc:i,boosted:_,select:X,pathInfo:{requestPath:n,finalRequestPath:R,responsePath:null,anchor:O}};p.onload=function(){try{const t=Hn(r);H.pathInfo.responsePath=On(p);M(r,H);if(H.keepIndicators!==true){Qt(T,q)}he(r,"htmx:afterRequest",H);he(r,"htmx:afterOnLoad",H);if(!le(r)){let e=null;while(t.length>0&&e==null){const n=t.shift();if(le(n)){e=n}}if(e){he(e,"htmx:afterRequest",H);he(e,"htmx:afterOnLoad",H)}}oe(s);m()}catch(e){fe(r,"htmx:onLoadError",ce({error:e},H));throw e}};p.onerror=function(){Qt(T,q);fe(r,"htmx:afterRequest",H);fe(r,"htmx:sendError",H);oe(l);m()};p.onabort=function(){Qt(T,q);fe(r,"htmx:afterRequest",H);fe(r,"htmx:sendAbort",H);oe(l);m()};p.ontimeout=function(){Qt(T,q);fe(r,"htmx:afterRequest",H);fe(r,"htmx:timeout",H);oe(l);m()};if(!he(r,"htmx:beforeRequest",H)){oe(s);m();return e}var T=Zt(r);var q=Yt(r);se(["loadstart","loadend","progress","abort"],function(t){se([p,p.upload],function(e){e.addEventListener(t,function(e){he(r,"htmx:xhr:"+t,{lengthComputable:e.lengthComputable,loaded:e.loaded,total:e.total})})})});he(r,"htmx:beforeSend",H);const J=E?null:mn(p,r,w);p.send(J);return e}function Nn(e,t){const n=t.xhr;let r=null;let o=null;if(R(n,/HX-Push:/i)){r=n.getResponseHeader("HX-Push");o="push"}else if(R(n,/HX-Push-Url:/i)){r=n.getResponseHeader("HX-Push-Url");o="push"}else if(R(n,/HX-Replace-Url:/i)){r=n.getResponseHeader("HX-Replace-Url");o="replace"}if(r){if(r==="false"){return{}}else{return{type:o,path:r}}}const i=t.pathInfo.finalRequestPath;const s=t.pathInfo.responsePath;const l=re(e,"hx-push-url");const c=re(e,"hx-replace-url");const u=ie(e).boosted;let a=null;let f=null;if(l){a="push";f=l}else if(c){a="replace";f=c}else if(u){a="push";f=s||i}if(f){if(f==="false"){return{}}if(f==="true"){f=s||i}if(t.pathInfo.anchor&&f.indexOf("#")===-1){f=f+"#"+t.pathInfo.anchor}return{type:a,path:f}}else{return{}}}function In(e,t){var n=new RegExp(e.code);return n.test(t.toString(10))}function Pn(e){for(var t=0;t<Q.config.responseHandling.length;t++){var n=Q.config.responseHandling[t];if(In(n,e.status)){return n}}return{swap:false}}function kn(e){if(e){const t=u("title");if(t){t.innerHTML=e}else{window.document.title=e}}}function Dn(o,i){const s=i.xhr;let l=i.target;const e=i.etc;const c=i.select;if(!he(o,"htmx:beforeOnLoad",i))return;if(R(s,/HX-Trigger:/i)){Je(s,"HX-Trigger",o)}if(R(s,/HX-Location:/i)){zt();let e=s.getResponseHeader("HX-Location");var t;if(e.indexOf("{")===0){t=S(e);e=t.path;delete t.path}Rn("get",e,t).then(function(){$t(e)});return}const n=R(s,/HX-Refresh:/i)&&s.getResponseHeader("HX-Refresh")==="true";if(R(s,/HX-Redirect:/i)){i.keepIndicators=true;location.href=s.getResponseHeader("HX-Redirect");n&&location.reload();return}if(n){i.keepIndicators=true;location.reload();return}if(R(s,/HX-Retarget:/i)){if(s.getResponseHeader("HX-Retarget")==="this"){i.target=o}else{i.target=ue(ae(o,s.getResponseHeader("HX-Retarget")))}}const u=Nn(o,i);const r=Pn(s);const a=r.swap;let f=!!r.error;let h=Q.config.ignoreTitle||r.ignoreTitle;let d=r.select;if(r.target){i.target=ue(ae(o,r.target))}var g=e.swapOverride;if(g==null&&r.swapOverride){g=r.swapOverride}if(R(s,/HX-Retarget:/i)){if(s.getResponseHeader("HX-Retarget")==="this"){i.target=o}else{i.target=ue(ae(o,s.getResponseHeader("HX-Retarget")))}}if(R(s,/HX-Reswap:/i)){g=s.getResponseHeader("HX-Reswap")}var p=s.response;var m=ce({shouldSwap:a,serverResponse:p,isError:f,ignoreTitle:h,selectOverride:d,swapOverride:g},i);if(r.event&&!he(l,r.event,m))return;if(!he(l,"htmx:beforeSwap",m))return;l=m.target;p=m.serverResponse;f=m.isError;h=m.ignoreTitle;d=m.selectOverride;g=m.swapOverride;i.target=l;i.failed=f;i.successful=!f;if(m.shouldSwap){if(s.status===286){lt(o)}Ft(o,function(e){p=e.transformResponse(p,s,o)});if(u.type){zt()}var x=gn(o,g);if(!x.hasOwnProperty("ignoreTitle")){x.ignoreTitle=h}l.classList.add(Q.config.swappingClass);let n=null;let r=null;if(c){d=c}if(R(s,/HX-Reselect:/i)){d=s.getResponseHeader("HX-Reselect")}const y=re(o,"hx-select-oob");const b=re(o,"hx-select");let e=function(){try{if(u.type){he(ne().body,"htmx:beforeHistoryUpdate",ce({history:u},i));if(u.type==="push"){$t(u.path);he(ne().body,"htmx:pushedIntoHistory",{path:u.path})}else{Jt(u.path);he(ne().body,"htmx:replacedInHistory",{path:u.path})}}$e(l,p,x,{select:d||b,selectOOB:y,eventInfo:i,anchor:i.pathInfo.anchor,contextElement:o,afterSwapCallback:function(){if(R(s,/HX-Trigger-After-Swap:/i)){let e=o;if(!le(o)){e=ne().body}Je(s,"HX-Trigger-After-Swap",e)}},afterSettleCallback:function(){if(R(s,/HX-Trigger-After-Settle:/i)){let e=o;if(!le(o)){e=ne().body}Je(s,"HX-Trigger-After-Settle",e)}oe(n)}})}catch(e){fe(o,"htmx:swapError",i);oe(r);throw e}};let t=Q.config.globalViewTransitions;if(x.hasOwnProperty("transition")){t=x.transition}if(t&&he(o,"htmx:beforeTransition",i)&&typeof Promise!=="undefined"&&document.startViewTransition){const v=new Promise(function(e,t){n=e;r=t});const w=e;e=function(){document.startViewTransition(function(){w();return v})}}if(x.swapDelay>0){E().setTimeout(e,x.swapDelay)}else{e()}}if(f){fe(o,"htmx:responseError",ce({error:"Response Status Error Code "+s.status+" from "+i.pathInfo.requestPath},i))}}const Mn={};function Xn(){return{init:function(e){return null},getSelectors:function(){return null},onEvent:function(e,t){return true},transformResponse:function(e,t,n){return e},isInlineSwap:function(e){return false},handleSwap:function(e,t,n,r){return false},encodeParameters:function(e,t,n){return null}}}function Fn(e,t){if(t.init){t.init(n)}Mn[e]=ce(Xn(),t)}function Bn(e){delete Mn[e]}function Un(e,n,r){if(n==undefined){n=[]}if(e==undefined){return n}if(r==undefined){r=[]}const t=te(e,"hx-ext");if(t){se(t.split(","),function(e){e=e.replace(/ /g,"");if(e.slice(0,7)=="ignore:"){r.push(e.slice(7));return}if(r.indexOf(e)<0){const t=Mn[e];if(t&&n.indexOf(t)<0){n.push(t)}}})}return Un(ue(c(e)),n,r)}var jn=false;ne().addEventListener("DOMContentLoaded",function(){jn=true});function Vn(e){if(jn||ne().readyState==="complete"){e()}else{ne().addEventListener("DOMContentLoaded",e)}}function _n(){if(Q.config.includeIndicatorStyles!==false){const e=Q.config.inlineStyleNonce?` nonce="${Q.config.inlineStyleNonce}"`:"";ne().head.insertAdjacentHTML("beforeend","<style"+e+"> ."+Q.config.indicatorClass+"{opacity:0} ."+Q.config.requestClass+" ."+Q.config.indicatorClass+"{opacity:1; transition: opacity 200ms ease-in;} ."+Q.config.requestClass+"."+Q.config.indicatorClass+"{opacity:1; transition: opacity 200ms ease-in;} </style>")}}function zn(){const e=ne().querySelector('meta[name="htmx-config"]');if(e){return S(e.content)}else{return null}}function $n(){const e=zn();if(e){Q.config=ce(Q.config,e)}}Vn(function(){$n();_n();let e=ne().body;kt(e);const t=ne().querySelectorAll("[hx-trigger='restored'],[data-hx-trigger='restored']");e.addEventListener("htmx:abort",function(e){const t=e.target;const n=ie(t);if(n&&n.xhr){n.xhr.abort()}});const n=window.onpopstate?window.onpopstate.bind(window):null;window.onpopstate=function(e){if(e.state&&e.state.htmx){Wt();se(t,function(e){he(e,"htmx:restored",{document:ne(),triggerEvent:he})})}else{if(n){n(e)}}};E().setTimeout(function(){he(e,"htmx:load",{});e=null},0)});return Q}();
|
internal/web/static/markitdown.js
ADDED
|
@@ -0,0 +1,113 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
// Markitdown converter — streams dummy OpenAI-style SSE deltas from
|
| 2 |
+
// GET /markitdown/stream and renders the accumulating markdown live as a
|
| 3 |
+
// formatted invoice view in the right panel.
|
| 4 |
+
(function () {
|
| 5 |
+
'use strict';
|
| 6 |
+
|
| 7 |
+
function esc(s) {
|
| 8 |
+
return s.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');
|
| 9 |
+
}
|
| 10 |
+
|
| 11 |
+
function inline(s) {
|
| 12 |
+
s = esc(s);
|
| 13 |
+
s = s.replace(/\*\*(.+?)\*\*/g, '<strong>$1</strong>');
|
| 14 |
+
s = s.replace(/_(.+?)_/g, '<em>$1</em>');
|
| 15 |
+
return s;
|
| 16 |
+
}
|
| 17 |
+
|
| 18 |
+
// Minimal markdown renderer: headings, hr, blockquote, tables, lists, paragraphs.
|
| 19 |
+
function renderMarkdown(md) {
|
| 20 |
+
var lines = md.split('\n');
|
| 21 |
+
var html = '';
|
| 22 |
+
var inTable = false;
|
| 23 |
+
var inList = false;
|
| 24 |
+
for (var i = 0; i < lines.length; i++) {
|
| 25 |
+
var line = lines[i];
|
| 26 |
+
var t = line.trim();
|
| 27 |
+
if (/^\|.*\|$/.test(t)) {
|
| 28 |
+
var cells = t.split('|').slice(1, -1).map(function (c) { return c.trim(); });
|
| 29 |
+
if (/^:?-+:?$/.test(cells[0].replace(/ /g, ''))) continue; // separator row
|
| 30 |
+
if (!inTable) { html += '<table>'; inTable = true; }
|
| 31 |
+
var tag = inTable && html.slice(-7) === '<table>' ? 'th' : 'td';
|
| 32 |
+
html += '<tr>' + cells.map(function (c) { return '<' + tag + '>' + inline(c) + '</' + tag + '>'; }).join('') + '</tr>';
|
| 33 |
+
continue;
|
| 34 |
+
}
|
| 35 |
+
if (inTable) { html += '</table>'; inTable = false; }
|
| 36 |
+
if (t === '---') { html += '<hr>'; continue; }
|
| 37 |
+
if (t.indexOf('# ') === 0) { html += '<h1>' + inline(t.slice(2)) + '</h1>'; continue; }
|
| 38 |
+
if (t.indexOf('## ') === 0) { html += '<h2>' + inline(t.slice(3)) + '</h2>'; continue; }
|
| 39 |
+
if (t.indexOf('> ') === 0) { html += '<blockquote>' + inline(t.slice(2)) + '</blockquote>'; continue; }
|
| 40 |
+
if (t.indexOf('- ') === 0) {
|
| 41 |
+
if (!inList) { html += '<ul>'; inList = true; }
|
| 42 |
+
html += '<li>' + inline(t.slice(2)) + '</li>';
|
| 43 |
+
continue;
|
| 44 |
+
}
|
| 45 |
+
if (inList) { html += '</ul>'; inList = false; }
|
| 46 |
+
if (t === '') continue;
|
| 47 |
+
html += '<p>' + inline(line) + '</p>';
|
| 48 |
+
}
|
| 49 |
+
if (inTable) html += '</table>';
|
| 50 |
+
if (inList) html += '</ul>';
|
| 51 |
+
return html;
|
| 52 |
+
}
|
| 53 |
+
|
| 54 |
+
function init() {
|
| 55 |
+
var input = document.getElementById('md-input');
|
| 56 |
+
var btn = document.getElementById('md-convert');
|
| 57 |
+
var clear = document.getElementById('md-clear');
|
| 58 |
+
var out = document.getElementById('md-output');
|
| 59 |
+
var status = document.getElementById('md-status');
|
| 60 |
+
if (!input || !btn || !out) return;
|
| 61 |
+
|
| 62 |
+
var es = null;
|
| 63 |
+
|
| 64 |
+
function setStatus(t) { if (status) status.textContent = t; }
|
| 65 |
+
|
| 66 |
+
function stop() {
|
| 67 |
+
if (es) { es.close(); es = null; }
|
| 68 |
+
btn.disabled = false;
|
| 69 |
+
btn.textContent = 'Convert';
|
| 70 |
+
}
|
| 71 |
+
|
| 72 |
+
if (clear) clear.addEventListener('click', function () {
|
| 73 |
+
stop();
|
| 74 |
+
input.value = '';
|
| 75 |
+
out.innerHTML = '<span class="md-empty">Nothing converted yet. Your invoice will appear here.</span>';
|
| 76 |
+
setStatus('Idle.');
|
| 77 |
+
input.focus();
|
| 78 |
+
});
|
| 79 |
+
|
| 80 |
+
btn.addEventListener('click', function () {
|
| 81 |
+
stop();
|
| 82 |
+
var text = input.value.trim();
|
| 83 |
+
var md = '';
|
| 84 |
+
btn.disabled = true;
|
| 85 |
+
btn.textContent = 'Streaming…';
|
| 86 |
+
setStatus('Converting… streaming deltas.');
|
| 87 |
+
out.innerHTML = '<span class="md-cursor"></span>';
|
| 88 |
+
|
| 89 |
+
es = new EventSource('/markitdown/stream?text=' + encodeURIComponent(text));
|
| 90 |
+
es.onmessage = function (ev) {
|
| 91 |
+
var msg;
|
| 92 |
+
try { msg = JSON.parse(ev.data); } catch (e) { return; }
|
| 93 |
+
if (msg.done) {
|
| 94 |
+
stop();
|
| 95 |
+
setStatus('Done. Invoice ready.');
|
| 96 |
+
return;
|
| 97 |
+
}
|
| 98 |
+
if (msg.delta) {
|
| 99 |
+
md += msg.delta;
|
| 100 |
+
out.innerHTML = renderMarkdown(md) + '<span class="md-cursor"></span>';
|
| 101 |
+
out.scrollTop = out.scrollHeight;
|
| 102 |
+
}
|
| 103 |
+
};
|
| 104 |
+
es.onerror = function () {
|
| 105 |
+
stop();
|
| 106 |
+
setStatus('Stream interrupted. Try again.');
|
| 107 |
+
};
|
| 108 |
+
});
|
| 109 |
+
}
|
| 110 |
+
|
| 111 |
+
if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', init);
|
| 112 |
+
else init();
|
| 113 |
+
})();
|
internal/web/static/style.css
ADDED
|
@@ -0,0 +1,485 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
/* Markitdown — Mobbin monochrome system. Ink #141414 on canvas #ffffff,
|
| 2 |
+
structure from neutral tints, stadium-pill interaction language. */
|
| 3 |
+
|
| 4 |
+
:root {
|
| 5 |
+
--ink: #141414;
|
| 6 |
+
--ink-soft: #262626;
|
| 7 |
+
--canvas: #ffffff;
|
| 8 |
+
--canvas-soft: #f3f3f3;
|
| 9 |
+
--field: #f0f0f0;
|
| 10 |
+
--hairline-soft: #f0f0f0;
|
| 11 |
+
--hairline: #e0e0e0;
|
| 12 |
+
--muted: #707070;
|
| 13 |
+
--faint: #adadad;
|
| 14 |
+
--accent: #0066ff;
|
| 15 |
+
--on-primary: #ffffff;
|
| 16 |
+
--rounded-sm: 16px;
|
| 17 |
+
--rounded-md: 24px;
|
| 18 |
+
--rounded-full: 9999px;
|
| 19 |
+
--font: "Inter", -apple-system, "Helvetica Neue", Arial, sans-serif;
|
| 20 |
+
}
|
| 21 |
+
|
| 22 |
+
*, *::before, *::after { box-sizing: border-box; }
|
| 23 |
+
|
| 24 |
+
html { -webkit-text-size-adjust: 100%; }
|
| 25 |
+
|
| 26 |
+
img, svg, video, canvas { max-width: 100%; height: auto; }
|
| 27 |
+
|
| 28 |
+
body {
|
| 29 |
+
margin: 0;
|
| 30 |
+
font-family: var(--font);
|
| 31 |
+
font-weight: 450;
|
| 32 |
+
font-size: 16px;
|
| 33 |
+
line-height: 1.38;
|
| 34 |
+
color: var(--ink);
|
| 35 |
+
background: var(--canvas);
|
| 36 |
+
min-height: 100vh;
|
| 37 |
+
min-height: 100svh;
|
| 38 |
+
display: flex;
|
| 39 |
+
flex-direction: column;
|
| 40 |
+
overflow-x: clip;
|
| 41 |
+
}
|
| 42 |
+
|
| 43 |
+
a { color: inherit; }
|
| 44 |
+
|
| 45 |
+
/* Floating pill nav */
|
| 46 |
+
.nav-wrap {
|
| 47 |
+
position: sticky;
|
| 48 |
+
top: 12px;
|
| 49 |
+
z-index: 50;
|
| 50 |
+
display: flex;
|
| 51 |
+
justify-content: center;
|
| 52 |
+
padding: 12px 16px 0;
|
| 53 |
+
}
|
| 54 |
+
|
| 55 |
+
.nav-pill {
|
| 56 |
+
display: flex;
|
| 57 |
+
align-items: center;
|
| 58 |
+
gap: 24px;
|
| 59 |
+
width: min(880px, 100%);
|
| 60 |
+
padding: 10px 10px 10px 20px;
|
| 61 |
+
background: var(--canvas-soft);
|
| 62 |
+
border-radius: var(--rounded-full);
|
| 63 |
+
}
|
| 64 |
+
|
| 65 |
+
.nav-brand {
|
| 66 |
+
display: inline-flex;
|
| 67 |
+
align-items: center;
|
| 68 |
+
gap: 10px;
|
| 69 |
+
text-decoration: none;
|
| 70 |
+
font-weight: 650;
|
| 71 |
+
}
|
| 72 |
+
|
| 73 |
+
.brand-squircle {
|
| 74 |
+
display: grid;
|
| 75 |
+
place-items: center;
|
| 76 |
+
width: 32px;
|
| 77 |
+
height: 32px;
|
| 78 |
+
border-radius: 30%;
|
| 79 |
+
background: var(--ink);
|
| 80 |
+
color: var(--on-primary);
|
| 81 |
+
font-weight: 650;
|
| 82 |
+
font-size: 16px;
|
| 83 |
+
}
|
| 84 |
+
|
| 85 |
+
.brand-word { font-size: 16px; }
|
| 86 |
+
|
| 87 |
+
.nav-links {
|
| 88 |
+
display: flex;
|
| 89 |
+
align-items: center;
|
| 90 |
+
gap: 4px;
|
| 91 |
+
margin-left: auto;
|
| 92 |
+
}
|
| 93 |
+
|
| 94 |
+
.nav-link {
|
| 95 |
+
padding: 10px 14px;
|
| 96 |
+
border-radius: var(--rounded-full);
|
| 97 |
+
text-decoration: none;
|
| 98 |
+
font-size: 16px;
|
| 99 |
+
font-weight: 600;
|
| 100 |
+
}
|
| 101 |
+
|
| 102 |
+
.nav-link:hover { background: var(--field); }
|
| 103 |
+
|
| 104 |
+
.nav-email {
|
| 105 |
+
max-width: 200px;
|
| 106 |
+
overflow: hidden;
|
| 107 |
+
text-overflow: ellipsis;
|
| 108 |
+
white-space: nowrap;
|
| 109 |
+
color: var(--muted);
|
| 110 |
+
font-size: 14px;
|
| 111 |
+
padding: 0 8px;
|
| 112 |
+
}
|
| 113 |
+
|
| 114 |
+
.nav-cta-form { margin: 0; }
|
| 115 |
+
|
| 116 |
+
/* Pills */
|
| 117 |
+
.btn-primary {
|
| 118 |
+
display: inline-flex;
|
| 119 |
+
align-items: center;
|
| 120 |
+
justify-content: center;
|
| 121 |
+
min-height: 44px;
|
| 122 |
+
padding: 0 24px;
|
| 123 |
+
border: none;
|
| 124 |
+
border-radius: var(--rounded-full);
|
| 125 |
+
background: var(--ink);
|
| 126 |
+
color: var(--on-primary);
|
| 127 |
+
font: inherit;
|
| 128 |
+
font-size: 16px;
|
| 129 |
+
font-weight: 600;
|
| 130 |
+
text-decoration: none;
|
| 131 |
+
cursor: pointer;
|
| 132 |
+
white-space: nowrap;
|
| 133 |
+
}
|
| 134 |
+
|
| 135 |
+
.btn-primary:hover { background: var(--ink-soft); }
|
| 136 |
+
.btn-primary:disabled { opacity: 0.45; cursor: wait; }
|
| 137 |
+
|
| 138 |
+
.btn-outline {
|
| 139 |
+
display: inline-flex;
|
| 140 |
+
align-items: center;
|
| 141 |
+
justify-content: center;
|
| 142 |
+
min-height: 44px;
|
| 143 |
+
padding: 0 24px;
|
| 144 |
+
border: 1px solid var(--hairline);
|
| 145 |
+
border-radius: var(--rounded-full);
|
| 146 |
+
background: var(--canvas);
|
| 147 |
+
color: var(--ink);
|
| 148 |
+
font: inherit;
|
| 149 |
+
font-size: 16px;
|
| 150 |
+
font-weight: 600;
|
| 151 |
+
text-decoration: none;
|
| 152 |
+
cursor: pointer;
|
| 153 |
+
white-space: nowrap;
|
| 154 |
+
}
|
| 155 |
+
|
| 156 |
+
.btn-soft {
|
| 157 |
+
display: inline-flex;
|
| 158 |
+
align-items: center;
|
| 159 |
+
min-height: 44px;
|
| 160 |
+
padding: 0 24px;
|
| 161 |
+
border-radius: var(--rounded-full);
|
| 162 |
+
background: var(--canvas-soft);
|
| 163 |
+
color: var(--ink);
|
| 164 |
+
font-weight: 600;
|
| 165 |
+
text-decoration: none;
|
| 166 |
+
}
|
| 167 |
+
|
| 168 |
+
/* Page — fluid container, capped for ultrawide */
|
| 169 |
+
.page {
|
| 170 |
+
flex: 1;
|
| 171 |
+
width: min(1120px, 100%);
|
| 172 |
+
margin: 0 auto;
|
| 173 |
+
padding: clamp(48px, 8vw, 80px) clamp(16px, 4vw, 24px) 0;
|
| 174 |
+
}
|
| 175 |
+
|
| 176 |
+
.hero { text-align: center; max-width: 820px; margin: 0 auto; padding-inline: 4px; }
|
| 177 |
+
.hero h1 {
|
| 178 |
+
margin: 0;
|
| 179 |
+
font-size: clamp(2.5rem, 2rem + 4.5vw, 5rem);
|
| 180 |
+
font-weight: 650;
|
| 181 |
+
line-height: 1.0;
|
| 182 |
+
text-wrap: balance;
|
| 183 |
+
}
|
| 184 |
+
.hero-sub {
|
| 185 |
+
margin: 24px auto 0;
|
| 186 |
+
max-width: 620px;
|
| 187 |
+
font-size: clamp(1rem, 0.9rem + 1vw, 1.25rem);
|
| 188 |
+
font-weight: 300;
|
| 189 |
+
line-height: 1.38;
|
| 190 |
+
color: var(--ink);
|
| 191 |
+
text-wrap: pretty;
|
| 192 |
+
}
|
| 193 |
+
.hero-ctas {
|
| 194 |
+
display: flex;
|
| 195 |
+
gap: 12px;
|
| 196 |
+
justify-content: center;
|
| 197 |
+
margin-top: 32px;
|
| 198 |
+
flex-wrap: wrap;
|
| 199 |
+
}
|
| 200 |
+
|
| 201 |
+
.card-grid {
|
| 202 |
+
display: grid;
|
| 203 |
+
grid-template-columns: repeat(3, 1fr);
|
| 204 |
+
gap: 16px;
|
| 205 |
+
margin-top: 80px;
|
| 206 |
+
}
|
| 207 |
+
|
| 208 |
+
.feature-card {
|
| 209 |
+
background: var(--canvas);
|
| 210 |
+
border: 1px solid var(--hairline-soft);
|
| 211 |
+
border-radius: var(--rounded-md);
|
| 212 |
+
padding: 32px;
|
| 213 |
+
}
|
| 214 |
+
|
| 215 |
+
.feature-card h3 { margin: 0 0 12px; font-size: 24px; font-weight: 650; line-height: 1.25; }
|
| 216 |
+
.feature-card p { margin: 0; color: var(--muted); font-size: 14px; line-height: 1.43; }
|
| 217 |
+
|
| 218 |
+
.faq { margin: 80px 0; display: grid; gap: 12px; }
|
| 219 |
+
.faq-row {
|
| 220 |
+
background: var(--canvas-soft);
|
| 221 |
+
border-radius: var(--rounded-sm);
|
| 222 |
+
padding: 20px 24px;
|
| 223 |
+
font-size: 16px;
|
| 224 |
+
}
|
| 225 |
+
|
| 226 |
+
/* Auth */
|
| 227 |
+
.auth-wrap {
|
| 228 |
+
display: flex;
|
| 229 |
+
justify-content: center;
|
| 230 |
+
padding: 40px 0 80px;
|
| 231 |
+
}
|
| 232 |
+
|
| 233 |
+
.auth-card {
|
| 234 |
+
width: min(440px, 100%);
|
| 235 |
+
background: var(--canvas);
|
| 236 |
+
border: 1px solid var(--hairline-soft);
|
| 237 |
+
border-radius: var(--rounded-md);
|
| 238 |
+
padding: 32px;
|
| 239 |
+
}
|
| 240 |
+
|
| 241 |
+
.auth-card h1 { margin: 0; font-size: 32px; font-weight: 650; line-height: 1.13; }
|
| 242 |
+
.auth-card .auth-sub { margin: 12px 0 24px; color: var(--muted); font-size: 14px; }
|
| 243 |
+
|
| 244 |
+
.text-input {
|
| 245 |
+
width: 100%;
|
| 246 |
+
border: none;
|
| 247 |
+
background: var(--field);
|
| 248 |
+
border-radius: var(--rounded-sm);
|
| 249 |
+
padding: 12px 16px;
|
| 250 |
+
font: inherit;
|
| 251 |
+
font-size: 16px;
|
| 252 |
+
color: var(--ink);
|
| 253 |
+
margin-bottom: 12px;
|
| 254 |
+
}
|
| 255 |
+
|
| 256 |
+
.text-input::placeholder { color: var(--faint); }
|
| 257 |
+
.text-input:focus { outline: 2px solid var(--ink); outline-offset: 0; }
|
| 258 |
+
|
| 259 |
+
.auth-card .btn-primary { width: 100%; margin-top: 8px; }
|
| 260 |
+
.auth-card .btn-outline { width: 100%; margin-top: 12px; }
|
| 261 |
+
.auth-error {
|
| 262 |
+
background: var(--canvas-soft);
|
| 263 |
+
border: 1px solid var(--hairline);
|
| 264 |
+
border-radius: var(--rounded-sm);
|
| 265 |
+
padding: 12px 16px;
|
| 266 |
+
font-size: 14px;
|
| 267 |
+
margin: 0 0 16px;
|
| 268 |
+
}
|
| 269 |
+
.auth-fine { color: var(--faint); font-size: 12px; margin: 16px 0 0; text-align: center; }
|
| 270 |
+
.auth-alt { text-align: center; font-size: 14px; color: var(--muted); }
|
| 271 |
+
|
| 272 |
+
/* Markitdown converter — chromeless full-viewport app screen.
|
| 273 |
+
The page itself never scrolls; the two panes scroll internally. */
|
| 274 |
+
|
| 275 |
+
body.is-app {
|
| 276 |
+
height: 100vh;
|
| 277 |
+
height: 100dvh;
|
| 278 |
+
overflow: hidden;
|
| 279 |
+
}
|
| 280 |
+
|
| 281 |
+
.page-app {
|
| 282 |
+
width: 100%;
|
| 283 |
+
max-width: none;
|
| 284 |
+
margin: 0;
|
| 285 |
+
padding: 16px;
|
| 286 |
+
height: 100vh;
|
| 287 |
+
height: 100dvh;
|
| 288 |
+
display: flex;
|
| 289 |
+
}
|
| 290 |
+
|
| 291 |
+
.md-app {
|
| 292 |
+
flex: 1;
|
| 293 |
+
min-height: 0;
|
| 294 |
+
min-width: 0;
|
| 295 |
+
display: grid;
|
| 296 |
+
/* Locked geometry: equal panes, fixed rail. minmax(0, …) kills content
|
| 297 |
+
minimums so tracks can never distort. */
|
| 298 |
+
grid-template-columns: minmax(0, 1fr) 140px minmax(0, 1fr);
|
| 299 |
+
gap: 12px;
|
| 300 |
+
}
|
| 301 |
+
|
| 302 |
+
body.is-app .md-pane {
|
| 303 |
+
min-height: 0;
|
| 304 |
+
min-width: 0;
|
| 305 |
+
height: 100%;
|
| 306 |
+
padding: 12px;
|
| 307 |
+
}
|
| 308 |
+
|
| 309 |
+
.md-rail {
|
| 310 |
+
display: flex;
|
| 311 |
+
flex-direction: column;
|
| 312 |
+
align-items: stretch;
|
| 313 |
+
justify-content: center;
|
| 314 |
+
gap: 12px;
|
| 315 |
+
min-width: 0;
|
| 316 |
+
}
|
| 317 |
+
|
| 318 |
+
.md-rail .btn-primary,
|
| 319 |
+
.md-rail .btn-outline { width: 100%; }
|
| 320 |
+
|
| 321 |
+
#md-input {
|
| 322 |
+
flex: 1;
|
| 323 |
+
min-height: 0;
|
| 324 |
+
min-width: 0;
|
| 325 |
+
width: 100%;
|
| 326 |
+
height: 100%;
|
| 327 |
+
resize: none;
|
| 328 |
+
border: none;
|
| 329 |
+
background: var(--field);
|
| 330 |
+
border-radius: var(--rounded-sm);
|
| 331 |
+
padding: 16px;
|
| 332 |
+
font: inherit;
|
| 333 |
+
font-size: 16px;
|
| 334 |
+
line-height: 1.5;
|
| 335 |
+
}
|
| 336 |
+
|
| 337 |
+
#md-input:focus { outline: 2px solid var(--ink); }
|
| 338 |
+
|
| 339 |
+
.md-output {
|
| 340 |
+
flex: 1;
|
| 341 |
+
min-height: 0;
|
| 342 |
+
height: 100%;
|
| 343 |
+
background: var(--canvas-soft);
|
| 344 |
+
border-radius: var(--rounded-sm);
|
| 345 |
+
padding: 24px;
|
| 346 |
+
overflow-y: auto;
|
| 347 |
+
overflow-x: auto;
|
| 348 |
+
overflow-wrap: anywhere;
|
| 349 |
+
font-size: 14px;
|
| 350 |
+
}
|
| 351 |
+
|
| 352 |
+
.md-output .md-empty { color: var(--faint); }
|
| 353 |
+
.md-output h1 { font-size: 32px; font-weight: 650; line-height: 1.13; margin: 0 0 12px; }
|
| 354 |
+
.md-output h2 { font-size: 20px; font-weight: 600; margin: 24px 0 8px; }
|
| 355 |
+
.md-output table { width: 100%; border-collapse: collapse; margin: 12px 0; font-size: 13px; }
|
| 356 |
+
.md-output th, .md-output td { text-align: left; padding: 8px; border-bottom: 1px solid var(--canvas-soft); }
|
| 357 |
+
.md-output th { font-size: 12px; color: var(--muted); }
|
| 358 |
+
.md-output hr { border: none; border-top: 1px solid var(--hairline); margin: 20px 0; }
|
| 359 |
+
.md-output blockquote {
|
| 360 |
+
margin: 12px 0;
|
| 361 |
+
padding: 12px 16px;
|
| 362 |
+
background: var(--canvas);
|
| 363 |
+
border-radius: var(--rounded-sm);
|
| 364 |
+
color: var(--muted);
|
| 365 |
+
}
|
| 366 |
+
.md-output ul { padding-left: 20px; }
|
| 367 |
+
.md-cursor {
|
| 368 |
+
display: inline-block;
|
| 369 |
+
width: 8px;
|
| 370 |
+
height: 16px;
|
| 371 |
+
background: var(--ink);
|
| 372 |
+
vertical-align: text-bottom;
|
| 373 |
+
animation: blink 1s step-end infinite;
|
| 374 |
+
}
|
| 375 |
+
@keyframes blink { 50% { opacity: 0; } }
|
| 376 |
+
|
| 377 |
+
/* Footer — polarity inversion */
|
| 378 |
+
.footer {
|
| 379 |
+
margin-top: 120px;
|
| 380 |
+
background: var(--ink);
|
| 381 |
+
color: var(--on-primary);
|
| 382 |
+
border-radius: var(--rounded-md) var(--rounded-md) 0 0;
|
| 383 |
+
}
|
| 384 |
+
|
| 385 |
+
.footer-inner { width: min(1120px, 100%); margin: 0 auto; padding: clamp(48px, 7vw, 80px) clamp(16px, 4vw, 24px) 40px; }
|
| 386 |
+
.footer-word { font-size: clamp(2rem, 1.5rem + 3vw, 2.75rem); font-weight: 650; line-height: 1.13; text-wrap: balance; }
|
| 387 |
+
.footer-tag { color: var(--faint); margin: 12px 0 0; }
|
| 388 |
+
.footer-cols { display: flex; gap: 80px; margin-top: 32px; }
|
| 389 |
+
.footer-col { display: grid; gap: 8px; }
|
| 390 |
+
.footer-col a { color: var(--faint); text-decoration: none; font-size: 14px; }
|
| 391 |
+
.footer-col a:hover { color: var(--on-primary); }
|
| 392 |
+
.footer-bottom {
|
| 393 |
+
display: flex;
|
| 394 |
+
justify-content: space-between;
|
| 395 |
+
gap: 16px;
|
| 396 |
+
flex-wrap: wrap;
|
| 397 |
+
margin-top: 48px;
|
| 398 |
+
padding-top: 24px;
|
| 399 |
+
border-top: 1px solid var(--ink-soft);
|
| 400 |
+
color: var(--faint);
|
| 401 |
+
font-size: 12px;
|
| 402 |
+
}
|
| 403 |
+
|
| 404 |
+
/* Responsive — extreme small (320px) to extreme large (2560px+) */
|
| 405 |
+
|
| 406 |
+
/* 2xl: ultrawide — cap the measure, let canvas breathe around it */
|
| 407 |
+
@media (min-width: 1536px) {
|
| 408 |
+
.page { width: min(1280px, 100%); }
|
| 409 |
+
.page-app { width: 100%; max-width: none; }
|
| 410 |
+
.nav-pill { width: min(1020px, 100%); }
|
| 411 |
+
.footer-inner { width: min(1280px, 100%); }
|
| 412 |
+
.md-pane { min-height: 64vh; }
|
| 413 |
+
}
|
| 414 |
+
|
| 415 |
+
/* lg: small laptop / landscape tablet */
|
| 416 |
+
@media (max-width: 1024px) {
|
| 417 |
+
.card-grid { grid-template-columns: repeat(2, 1fr); margin-top: 64px; }
|
| 418 |
+
.card-grid .feature-card:last-child { grid-column: 1 / -1; }
|
| 419 |
+
.faq { margin: 64px 0; }
|
| 420 |
+
.footer { margin-top: 80px; }
|
| 421 |
+
}
|
| 422 |
+
|
| 423 |
+
/* md: narrow screens — panes stay LEFT and RIGHT at every width.
|
| 424 |
+
Only the chrome tightens; the 3-column grid never stacks. */
|
| 425 |
+
|
| 426 |
+
/* md-: phones */
|
| 427 |
+
@media (max-width: 840px) {
|
| 428 |
+
.card-grid { grid-template-columns: 1fr; }
|
| 429 |
+
.nav-pill { gap: 12px; padding: 8px 8px 8px 14px; }
|
| 430 |
+
.nav-links { gap: 0; }
|
| 431 |
+
.nav-links .nav-link { display: none; }
|
| 432 |
+
.nav-email { display: none; }
|
| 433 |
+
.footer-cols { flex-wrap: wrap; gap: 32px; }
|
| 434 |
+
}
|
| 435 |
+
|
| 436 |
+
/* sm: narrow phones */
|
| 437 |
+
@media (max-width: 640px) {
|
| 438 |
+
.nav-wrap { top: 8px; padding: 8px 12px 0; }
|
| 439 |
+
.hero-ctas .btn-primary,
|
| 440 |
+
.hero-ctas .btn-outline,
|
| 441 |
+
.hero-ctas .btn-soft { flex: 1 1 100%; }
|
| 442 |
+
.feature-card { padding: 24px; }
|
| 443 |
+
.faq-row { padding: 16px; font-size: 14px; }
|
| 444 |
+
.auth-wrap { padding: 24px 0 64px; }
|
| 445 |
+
.auth-card { padding: 24px; }
|
| 446 |
+
.page-app { padding: 8px; }
|
| 447 |
+
/* Small screens: input on top, buttons in the middle, output at the
|
| 448 |
+
bottom. Still exactly one viewport tall; panes scroll internally. */
|
| 449 |
+
.md-app {
|
| 450 |
+
gap: 8px;
|
| 451 |
+
grid-template-columns: 1fr;
|
| 452 |
+
grid-template-rows: 1fr auto 1fr;
|
| 453 |
+
}
|
| 454 |
+
body.is-app .md-pane { padding: 8px; }
|
| 455 |
+
.md-rail { flex-direction: row; gap: 8px; }
|
| 456 |
+
.md-rail .btn-primary,
|
| 457 |
+
.md-rail .btn-outline { flex: 1; }
|
| 458 |
+
.md-rail .btn-primary,
|
| 459 |
+
.md-rail .btn-outline { padding: 0 12px; font-size: 13px; }
|
| 460 |
+
.md-output { padding: 16px; }
|
| 461 |
+
.md-output table { display: block; overflow-x: auto; font-size: 12px; }
|
| 462 |
+
.footer-cols { flex-direction: column; gap: 24px; margin-top: 24px; }
|
| 463 |
+
.footer-bottom { flex-direction: column; gap: 8px; }
|
| 464 |
+
}
|
| 465 |
+
|
| 466 |
+
/* xs: extreme small (≤400px) — logomark-only nav, full-bleed stacking */
|
| 467 |
+
@media (max-width: 400px) {
|
| 468 |
+
body { font-size: 15px; }
|
| 469 |
+
.brand-word { display: none; }
|
| 470 |
+
.nav-pill .btn-primary { padding: 0 16px; font-size: 14px; }
|
| 471 |
+
.btn-primary, .btn-outline, .btn-soft { min-height: 48px; }
|
| 472 |
+
.text-input { font-size: 16px; } /* no iOS auto-zoom */
|
| 473 |
+
}
|
| 474 |
+
|
| 475 |
+
/* Touch: keep every target comfortably tappable */
|
| 476 |
+
@media (pointer: coarse) {
|
| 477 |
+
.nav-link { padding: 12px 16px; }
|
| 478 |
+
.footer-col a { padding: 6px 0; }
|
| 479 |
+
}
|
| 480 |
+
|
| 481 |
+
/* Reduced motion: static cursor, no blink */
|
| 482 |
+
@media (prefers-reduced-motion: reduce) {
|
| 483 |
+
*, *::before, *::after { animation: none !important; transition: none !important; }
|
| 484 |
+
.md-cursor { animation: none; }
|
| 485 |
+
}
|
internal/web/templates/base.html
ADDED
|
@@ -0,0 +1,68 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{{define "base"}}<!DOCTYPE html>
|
| 2 |
+
<html lang="en">
|
| 3 |
+
<head>
|
| 4 |
+
<meta charset="utf-8">
|
| 5 |
+
<meta name="viewport" content="width=device-width, initial-scale=1">
|
| 6 |
+
<title>Markitdown — paste text, get clean markdown.</title>
|
| 7 |
+
<link rel="preconnect" href="https://fonts.googleapis.com">
|
| 8 |
+
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
|
| 9 |
+
<link href="https://fonts.googleapis.com/css2?family=Inter:opsz,wght@14..32,300;14..32,450;14..32,600;14..32,650&display=swap" rel="stylesheet">
|
| 10 |
+
<link rel="stylesheet" href="/static/style.css?v=4">
|
| 11 |
+
<script src="/static/htmx.min.js" defer></script>
|
| 12 |
+
</head>
|
| 13 |
+
<body class="{{if .Bare}}is-app{{end}}" hx-headers='{"X-CSRF-Token": "{{.CSRF}}"}'>
|
| 14 |
+
{{if not .Bare}}
|
| 15 |
+
<div class="nav-wrap">
|
| 16 |
+
<nav class="nav-pill" aria-label="Primary">
|
| 17 |
+
<a class="nav-brand" href="/">
|
| 18 |
+
<span class="brand-squircle">M</span>
|
| 19 |
+
<span class="brand-word">Markitdown</span>
|
| 20 |
+
</a>
|
| 21 |
+
<div class="nav-links">
|
| 22 |
+
<a class="nav-link" href="/">Home</a>
|
| 23 |
+
<a class="nav-link" href="/markitdown">Converter</a>
|
| 24 |
+
{{if .User.ID}}
|
| 25 |
+
<span class="nav-email">{{.User.Email}}</span>
|
| 26 |
+
{{else}}
|
| 27 |
+
<a class="nav-link" href="/login">Log in</a>
|
| 28 |
+
{{end}}
|
| 29 |
+
</div>
|
| 30 |
+
{{if .User.ID}}
|
| 31 |
+
<form method="post" action="/logout" class="nav-cta-form">
|
| 32 |
+
<input type="hidden" name="csrf" value="{{.CSRF}}">
|
| 33 |
+
<button class="btn-primary" type="submit">Log out</button>
|
| 34 |
+
</form>
|
| 35 |
+
{{else}}
|
| 36 |
+
<a class="btn-primary" href="/login">Get started</a>
|
| 37 |
+
{{end}}
|
| 38 |
+
</nav>
|
| 39 |
+
</div>
|
| 40 |
+
{{end}}
|
| 41 |
+
<main class="page{{if .Bare}} page-app{{end}}">
|
| 42 |
+
{{block "content" .}}{{end}}
|
| 43 |
+
</main>
|
| 44 |
+
{{if not .Bare}}
|
| 45 |
+
<footer class="footer">
|
| 46 |
+
<div class="footer-inner">
|
| 47 |
+
<div class="footer-word">Markitdown.</div>
|
| 48 |
+
<p class="footer-tag">Paste messy text. Stream back clean, invoice-ready markdown.</p>
|
| 49 |
+
<div class="footer-cols">
|
| 50 |
+
<div class="footer-col">
|
| 51 |
+
<a href="/">Home</a>
|
| 52 |
+
<a href="/markitdown">Converter</a>
|
| 53 |
+
</div>
|
| 54 |
+
<div class="footer-col">
|
| 55 |
+
<a href="/login">Log in</a>
|
| 56 |
+
<a href="/healthz">System health</a>
|
| 57 |
+
</div>
|
| 58 |
+
</div>
|
| 59 |
+
<div class="footer-bottom">
|
| 60 |
+
<span>© 2026 Markitdown. All rights reserved.</span>
|
| 61 |
+
<span>Built with Go + HTMX.</span>
|
| 62 |
+
</div>
|
| 63 |
+
</div>
|
| 64 |
+
</footer>
|
| 65 |
+
{{end}}
|
| 66 |
+
</body>
|
| 67 |
+
</html>
|
| 68 |
+
{{end}}
|
internal/web/templates/pages/home.html
ADDED
|
@@ -0,0 +1,37 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{{define "home"}}{{template "base" .}}{{end}}
|
| 2 |
+
|
| 3 |
+
{{define "content"}}
|
| 4 |
+
<section class="hero">
|
| 5 |
+
<h1>Discover real-world markdown inspiration.</h1>
|
| 6 |
+
<p class="hero-sub">Paste messy text on the left. Stream back a clean, invoice-ready document on the right.</p>
|
| 7 |
+
<div class="hero-ctas">
|
| 8 |
+
<a class="btn-primary" href="/markitdown">Open converter</a>
|
| 9 |
+
{{if .User.ID}}
|
| 10 |
+
<span class="btn-soft">Signed in as {{.User.Email}}</span>
|
| 11 |
+
{{else}}
|
| 12 |
+
<a class="btn-outline" href="/login">Log in</a>
|
| 13 |
+
{{end}}
|
| 14 |
+
</div>
|
| 15 |
+
</section>
|
| 16 |
+
|
| 17 |
+
<section class="card-grid">
|
| 18 |
+
<div class="feature-card">
|
| 19 |
+
<h3>Paste anything.</h3>
|
| 20 |
+
<p>Raw PDF text, copied email threads, chaotic notes. The left panel takes it all.</p>
|
| 21 |
+
</div>
|
| 22 |
+
<div class="feature-card">
|
| 23 |
+
<h3>Convert in one tap.</h3>
|
| 24 |
+
<p>A single pill button opens a streaming extraction, chunk by chunk.</p>
|
| 25 |
+
</div>
|
| 26 |
+
<div class="feature-card">
|
| 27 |
+
<h3>Read it live.</h3>
|
| 28 |
+
<p>The invoice renders as markdown arrives, exactly like a fresh export.</p>
|
| 29 |
+
</div>
|
| 30 |
+
</section>
|
| 31 |
+
|
| 32 |
+
<section class="faq">
|
| 33 |
+
<div class="faq-row">How does the demo stream work? The server sends OpenAI-style deltas over SSE.</div>
|
| 34 |
+
<div class="faq-row">Do I need an account? Log in once, then open the converter.</div>
|
| 35 |
+
<div class="faq-row">Is my text stored? No. The demo builds a deterministic preview in memory.</div>
|
| 36 |
+
</section>
|
| 37 |
+
{{end}}
|
internal/web/templates/pages/login.html
ADDED
|
@@ -0,0 +1,19 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{{define "login"}}{{template "base" .}}{{end}}
|
| 2 |
+
|
| 3 |
+
{{define "content"}}
|
| 4 |
+
<div class="auth-wrap">
|
| 5 |
+
<div class="auth-card">
|
| 6 |
+
<h1>Welcome back.</h1>
|
| 7 |
+
<p class="auth-sub">Log in to open the Markitdown converter.</p>
|
| 8 |
+
{{if .Error}}<p class="auth-error" role="alert">{{.Error}}</p>{{end}}
|
| 9 |
+
<form method="post" action="/login">
|
| 10 |
+
<input type="hidden" name="csrf" value="{{.CSRF}}">
|
| 11 |
+
<input class="text-input" type="email" name="email" value="{{.Email}}" placeholder="Email address" required autofocus autocomplete="email">
|
| 12 |
+
<input class="text-input" type="password" name="password" placeholder="Password" required autocomplete="current-password">
|
| 13 |
+
<button class="btn-primary" type="submit">Continue</button>
|
| 14 |
+
</form>
|
| 15 |
+
<button class="btn-outline" type="button" onclick="return false;">Continue with Google</button>
|
| 16 |
+
<p class="auth-fine">Protected by session cookies + double-submit CSRF. No tracking.</p>
|
| 17 |
+
</div>
|
| 18 |
+
</div>
|
| 19 |
+
{{end}}
|
internal/web/templates/pages/markitdown.html
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{{define "markitdown"}}{{template "base" .}}{{end}}
|
| 2 |
+
|
| 3 |
+
{{define "content"}}
|
| 4 |
+
<section class="md-app">
|
| 5 |
+
<div class="md-pane">
|
| 6 |
+
<textarea id="md-input" placeholder="Paste text…" aria-label="Source text"></textarea>
|
| 7 |
+
</div>
|
| 8 |
+
<div class="md-rail">
|
| 9 |
+
<a class="btn-outline" href="/">Home</a>
|
| 10 |
+
<button class="btn-primary" id="md-convert" type="button">Convert</button>
|
| 11 |
+
</div>
|
| 12 |
+
<div class="md-pane">
|
| 13 |
+
<div class="md-output" id="md-output" aria-live="polite"><span class="md-empty">Output will stream here.</span></div>
|
| 14 |
+
</div>
|
| 15 |
+
</section>
|
| 16 |
+
<script src="/static/markitdown.js" defer></script>
|
| 17 |
+
{{end}}
|
scripts/smoke.sh
ADDED
|
@@ -0,0 +1,56 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env bash
|
| 2 |
+
# End-to-end smoke test for Markitdown.
|
| 3 |
+
# Usage: scripts/smoke.sh [port]
|
| 4 |
+
set -euo pipefail
|
| 5 |
+
|
| 6 |
+
PORT="${1:-8090}"
|
| 7 |
+
BASE="http://localhost:${PORT}"
|
| 8 |
+
JAR="$(mktemp)"
|
| 9 |
+
LOG="$(mktemp)"
|
| 10 |
+
cleanup() { [[ -n "${PID:-}" ]] && kill "$PID" 2>/dev/null || true; rm -f "$JAR" "$LOG"; }
|
| 11 |
+
trap cleanup EXIT
|
| 12 |
+
|
| 13 |
+
echo "== building =="
|
| 14 |
+
go build -o bin/markitdown ./cmd/server
|
| 15 |
+
|
| 16 |
+
echo "== starting server on :${PORT} =="
|
| 17 |
+
PORT="$PORT" ./bin/markitdown >"$LOG" 2>&1 &
|
| 18 |
+
PID=$!
|
| 19 |
+
for _ in $(seq 1 30); do
|
| 20 |
+
curl -sf "$BASE/healthz" >/dev/null 2>&1 && break
|
| 21 |
+
sleep 0.5
|
| 22 |
+
done
|
| 23 |
+
|
| 24 |
+
pass() { echo " ✓ $1"; }
|
| 25 |
+
fail() { echo " ✗ $1"; kill "$PID"; exit 1; }
|
| 26 |
+
|
| 27 |
+
echo "== health =="
|
| 28 |
+
curl -sf "$BASE/healthz" | grep -q '"status":"ok"' && pass "healthz returns ok" || fail "healthz"
|
| 29 |
+
|
| 30 |
+
echo "== home =="
|
| 31 |
+
curl -sf "$BASE/" | grep -q "Markitdown" && pass "home renders" || fail "home"
|
| 32 |
+
|
| 33 |
+
echo "== login =="
|
| 34 |
+
curl -sf -c "$JAR" "$BASE/login" -o /tmp/pt-login.html
|
| 35 |
+
grep -q 'name="csrf" value="' /tmp/pt-login.html && pass "login page has CSRF token" || fail "no CSRF on login page"
|
| 36 |
+
grep -q "Welcome back." /tmp/pt-login.html && pass "login heading renders" || fail "login heading"
|
| 37 |
+
|
| 38 |
+
echo "== markitdown requires auth =="
|
| 39 |
+
CODE=$(curl -s -o /dev/null -w "%{http_code}" "$BASE/markitdown")
|
| 40 |
+
[[ "$CODE" == "303" ]] && pass "markitdown redirects anonymous to login (got $CODE)" || fail "markitdown auth ($CODE)"
|
| 41 |
+
|
| 42 |
+
echo "== stream requires auth =="
|
| 43 |
+
CODE=$(curl -s -o /dev/null -w "%{http_code}" "$BASE/markitdown/stream?text=hello")
|
| 44 |
+
[[ "$CODE" == "303" ]] && pass "stream redirects anonymous (got $CODE)" || fail "stream auth ($CODE)"
|
| 45 |
+
|
| 46 |
+
echo "== static assets =="
|
| 47 |
+
curl -sf "$BASE/static/htmx.min.js" | head -c 20 | grep -q "htmx" && pass "htmx served locally" || fail "htmx asset"
|
| 48 |
+
curl -sf "$BASE/static/style.css" | grep -q "nav-pill" && pass "theme css served" || fail "css asset"
|
| 49 |
+
curl -sf "$BASE/static/markitdown.js" | grep -q "EventSource" && pass "converter js served" || fail "converter asset"
|
| 50 |
+
|
| 51 |
+
echo "== CSRF rejected without token =="
|
| 52 |
+
CODE=$(curl -s -o /dev/null -w "%{http_code}" -b "$JAR" -d "email=x@y.z&password=secret123" "$BASE/login")
|
| 53 |
+
[[ "$CODE" == "403" ]] && pass "CSRF protection blocks tokenless POST (got $CODE)" || fail "csrf ($CODE)"
|
| 54 |
+
|
| 55 |
+
echo ""
|
| 56 |
+
echo "ALL SMOKE CHECKS PASSED ✅"
|