mirror of
https://github.com/jakejarvis/sofa.git
synced 2026-08-29 03:55:38 -04:00
* Convert to Turborepo monorepo with shared API contract package Restructure the repository as a monorepo in preparation for adding future clients (mobile app, CLI). Extract the oRPC contract and Zod schemas into `@sofa/api` (packages/api/) as a JIT internal package, and relocate the Next.js app to `@sofa/web` (apps/web/). - Add Turborepo with Bun workspaces for task orchestration and caching - Extract `contract.ts` and `schemas.ts` into `@sofa/api` package - Move all app code, configs, tests, and migrations to `apps/web/` - Update 17 import paths from `@/lib/orpc/schemas` to `@sofa/api/schemas` - Add `outputFileTracingRoot` and `transpilePackages` to next.config.ts - Rewrite Dockerfile with `turbo prune --docker` for efficient builds - Update CI workflows to use `turbo run` for lint/check-types/test - Update CLAUDE.md with monorepo structure and commands Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * Extract standalone Hono API server and split shared packages Separate all server-side concerns from the Next.js frontend into a new `apps/server/` Hono app and dedicated shared packages, making `@sofa/web` a frontend-only app with no direct DB or service access. - Add `@sofa/server` (`apps/server/`) — Hono API on port 3001 hosting oRPC procedures, Better Auth, cron jobs, and non-RPC routes - Add `@sofa/core` (`packages/core/`) — All 15 business logic services moved from `apps/web/lib/services/`; tests moved to `packages/core/test/` - Add `@sofa/db` (`packages/db/`) — DB client, schema, migrations, constants, and logger extracted from `apps/web/lib/db/` and `lib/` - Add `@sofa/tmdb` (`packages/tmdb/`) — TMDB client and image helpers moved from `apps/web/lib/tmdb/` - Add `@sofa/auth` (`packages/auth/`) — Better Auth server config moved from `apps/web/lib/auth/` - Move oRPC procedures, handler, router, middleware to `apps/server/src/orpc/` - Move Hono route handlers (avatars, backups, images, lists, webhooks, health) to `apps/server/src/routes/`; delete equivalent Next.js API routes - Strip `apps/web` to frontend-only: no DB imports, no service imports, all data via oRPC client calls to the API server - Add `entrypoint.sh` to start API server, wait for health, then Next.js - Update `next.config.ts` rewrites to proxy `/rpc/*` and `/api/*` to `INTERNAL_API_URL` (default `http://localhost:3001`) - Update Dockerfile and CLAUDE.md for the new structure * Migrate web app from Next.js to Vite + TanStack Router SPA and add workspace catalog Replace Next.js with a pure Vite SPA using TanStack Router for file-based routing, removing all SSR complexity. The API server (Hono) now serves both API routes and SPA static files in production, simplifying Docker to a single-process container. Key changes: - Vite 7 + @tanstack/react-router with file-based routing via plugin - Route guards via beforeLoad + authClient.getSession() (replaces server-side auth) - Route loaders with queryClient.ensureQueryData() (replaces SSR data fetching) - Self-hosted fonts via @fontsource (replaces next/font/google) - Tailwind v4 via @tailwindcss/vite (replaces @tailwindcss/postcss) - Single oRPC client (removed SSR client and server-side session helper) - Hono serves SPA static files in production (single port 3000) - Single-process Dockerfile (removed entrypoint.sh) - Bun workspace catalog for centralized dependency version management Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * Extract @sofa/logger and @sofa/config shared packages - Add `@sofa/logger` (`packages/logger/`) — standalone logger package extracted from `@sofa/db/logger`; update all imports across server, core, auth, db, and tmdb packages - Add `@sofa/config` (`packages/config/`) — standalone config/constants package extracted from `@sofa/db/constants`; exports `DATA_DIR`, `DATABASE_URL`, `CACHE_DIR`, `AVATAR_DIR`, `BACKUP_DIR` - Move `.env.example` from `apps/web/` to repo root; update server dev scripts to load it via `--env-file=../../.env` - Move image serving from `/api/images` to `/images`; add `serveStatic` fast path in `index.ts` for cached files before falling back to the TMDB fetch route; add `/images` proxy to Vite dev config - Fix `Sparkline` component: replace `ResponsiveContainer` with `ResizeObserver` to avoid SSR/hydration issues with recharts - Replace `VITE_SERVER_URL` env var with `window.location.origin` in the oRPC client (always same-origin in both dev and production) * Fix asset caching, SPA 404 fallback, and DATA_DIR resolution - Add `Cache-Control: immutable` header for hashed `/assets/*` files; return 404 for missing asset paths instead of falling back to `index.html` (prevents serving stale chunks after deploy) - Wrap `query.invalidate` in an arrow function in the oRPC QueryClient error handler to avoid illegal invocation errors - Resolve `DATA_DIR` to an absolute path via `path.resolve()` so relative paths work regardless of the process working directory * Migrate @sofa/logger to pino for structured logging - Replace custom logger implementation in `packages/logger/` with pino + pino-pretty; add both as workspace catalog dependencies - Add `pino` and `pino-pretty` to the workspace catalog in `package.json` - Fix `log.error()` calls in oRPC and OpenAPI handlers to pass the error directly instead of wrapping it in `{ error }` to match pino's serializer expectations * Rename discoverProcedure/statsProcedure exports to discover/stats * Add TanStackDevtools unified panel and VS Code workspace config - Replace separate Router/Query devtools with unified `TanStackDevtools` from `@tanstack/react-devtools` + `@tanstack/devtools-vite` plugin - Wrap app in `<StrictMode>` in `main.tsx` - Add `.vscode/settings.json` (Biome formatter, format-on-save, readonly `routeTree.gen.ts`) and `.vscode/extensions.json` (recommended extensions) * Move test DB helpers to @sofa/db/test-utils and add root bunfig.toml Extract in-memory SQLite setup and fixture helpers (insertUser, insertTitle, etc.) from packages/core/test/sqlite.ts into packages/db/src/test-utils.ts so DB test utilities live alongside the schema they depend on. Use import.meta.dir for CWD-independent migration path resolution. Add root bunfig.toml so `bun test` works from the repo root in addition to `bun run test` (turbo). Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * Fix devtools plugin order and whitespace-only TMDB token check Move devtools() to first position in Vite plugins array per TanStack docs, and trim TMDB_API_READ_ACCESS_TOKEN before boolean coercion so whitespace-only values are treated as unconfigured. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
340 lines
11 KiB
TypeScript
340 lines
11 KiB
TypeScript
import { beforeEach, describe, expect, test } from "bun:test";
|
|
import {
|
|
clearAllTables,
|
|
insertAvailabilityOffer,
|
|
insertEpisodeWatch,
|
|
insertMovieWatch,
|
|
insertRating,
|
|
insertRecommendation,
|
|
insertStatus,
|
|
insertTitle,
|
|
insertTvShow,
|
|
insertUser,
|
|
} from "@sofa/db/test-utils";
|
|
import {
|
|
getContinueWatchingFeed,
|
|
getNewAvailableFeed,
|
|
getRecommendationsFeed,
|
|
getRecommendationsForTitle,
|
|
getUserStats,
|
|
getWatchCount,
|
|
getWatchHistory,
|
|
} from "../src/discovery";
|
|
|
|
beforeEach(() => {
|
|
clearAllTables();
|
|
});
|
|
|
|
// ── getWatchCount ───────────────────────────────────────────────────
|
|
|
|
describe("getWatchCount", () => {
|
|
test("counts movie watches within period", () => {
|
|
insertUser();
|
|
insertTitle({ id: "m1", tmdbId: 1 });
|
|
insertTitle({ id: "m2", tmdbId: 2 });
|
|
insertMovieWatch("user-1", "m1");
|
|
insertMovieWatch("user-1", "m2");
|
|
|
|
const count = getWatchCount("user-1", "movies", "this_month");
|
|
expect(count).toBe(2);
|
|
});
|
|
|
|
test("counts episode watches within period", () => {
|
|
insertUser();
|
|
const { episodeIds } = insertTvShow();
|
|
insertEpisodeWatch("user-1", episodeIds[0]);
|
|
insertEpisodeWatch("user-1", episodeIds[1]);
|
|
|
|
const count = getWatchCount("user-1", "episodes", "this_week");
|
|
expect(count).toBe(2);
|
|
});
|
|
|
|
test("excludes watches outside period", () => {
|
|
insertUser();
|
|
insertTitle({ id: "m1", tmdbId: 1 });
|
|
// Watch from 2 years ago
|
|
const oldDate = new Date();
|
|
oldDate.setFullYear(oldDate.getFullYear() - 2);
|
|
insertMovieWatch("user-1", "m1", oldDate);
|
|
|
|
const count = getWatchCount("user-1", "movies", "this_year");
|
|
expect(count).toBe(0);
|
|
});
|
|
|
|
test("returns 0 when no watches exist", () => {
|
|
insertUser();
|
|
const count = getWatchCount("user-1", "movies", "today");
|
|
expect(count).toBe(0);
|
|
});
|
|
});
|
|
|
|
// ── getWatchHistory ─────────────────────────────────────────────────
|
|
|
|
describe("getWatchHistory", () => {
|
|
test("returns bucketed history with correct total count", () => {
|
|
insertUser();
|
|
insertTitle({ id: "m1", tmdbId: 1 });
|
|
insertTitle({ id: "m2", tmdbId: 2 });
|
|
insertMovieWatch("user-1", "m1");
|
|
insertMovieWatch("user-1", "m2");
|
|
|
|
const history = getWatchHistory("user-1", "movies", "this_week");
|
|
expect(history).toBeArrayOfSize(7);
|
|
const totalCount = history.reduce((sum, b) => sum + b.count, 0);
|
|
expect(totalCount).toBe(2);
|
|
});
|
|
|
|
test("returns all-zero buckets when no watches", () => {
|
|
insertUser();
|
|
const history = getWatchHistory("user-1", "movies", "this_month");
|
|
expect(history).toBeArrayOfSize(30);
|
|
expect(history.every((b) => b.count === 0)).toBe(true);
|
|
});
|
|
|
|
test("returns correct bucket count for today period", () => {
|
|
insertUser();
|
|
const history = getWatchHistory("user-1", "episodes", "today");
|
|
expect(history).toBeArrayOfSize(24);
|
|
});
|
|
|
|
test("returns correct bucket count for this_year period", () => {
|
|
insertUser();
|
|
const history = getWatchHistory("user-1", "movies", "this_year");
|
|
expect(history).toBeArrayOfSize(12);
|
|
});
|
|
});
|
|
|
|
// ── getUserStats ────────────────────────────────────────────────────
|
|
|
|
describe("getUserStats", () => {
|
|
test("returns correct stats", () => {
|
|
insertUser();
|
|
insertTitle({ id: "m1", tmdbId: 1 });
|
|
insertTitle({ id: "m2", tmdbId: 2 });
|
|
const { titleId } = insertTvShow("tv-1", 99999, 1, 3);
|
|
|
|
insertMovieWatch("user-1", "m1");
|
|
insertMovieWatch("user-1", "m2");
|
|
insertEpisodeWatch("user-1", "tv-1-s1e1");
|
|
|
|
insertStatus("user-1", "m1", "completed");
|
|
insertStatus("user-1", "m2", "completed");
|
|
insertStatus("user-1", titleId, "in_progress");
|
|
|
|
const stats = getUserStats("user-1");
|
|
expect(stats.moviesThisMonth).toBe(2);
|
|
expect(stats.episodesThisWeek).toBe(1);
|
|
expect(stats.librarySize).toBe(3);
|
|
expect(stats.completed).toBe(2);
|
|
});
|
|
|
|
test("returns zeros when no data", () => {
|
|
insertUser();
|
|
const stats = getUserStats("user-1");
|
|
expect(stats.moviesThisMonth).toBe(0);
|
|
expect(stats.episodesThisWeek).toBe(0);
|
|
expect(stats.librarySize).toBe(0);
|
|
expect(stats.completed).toBe(0);
|
|
});
|
|
});
|
|
|
|
// ── getContinueWatchingFeed ─────────────────────────────────────────
|
|
|
|
describe("getContinueWatchingFeed", () => {
|
|
test("returns in-progress shows with next unwatched episode", () => {
|
|
insertUser();
|
|
const { titleId, episodeIds } = insertTvShow("tv-1", 99999, 1, 3);
|
|
insertStatus("user-1", titleId, "in_progress");
|
|
insertEpisodeWatch("user-1", episodeIds[0]);
|
|
|
|
const feed = getContinueWatchingFeed("user-1");
|
|
expect(feed).toHaveLength(1);
|
|
expect(feed[0].title.id).toBe(titleId);
|
|
expect(feed[0].nextEpisode?.episodeNumber).toBe(2);
|
|
expect(feed[0].watchedEpisodes).toBe(1);
|
|
expect(feed[0].totalEpisodes).toBe(3);
|
|
});
|
|
|
|
test("excludes completed shows", () => {
|
|
insertUser();
|
|
const { titleId } = insertTvShow("tv-1", 99999, 1, 3);
|
|
insertStatus("user-1", titleId, "completed");
|
|
|
|
const feed = getContinueWatchingFeed("user-1");
|
|
expect(feed).toHaveLength(0);
|
|
});
|
|
|
|
test("excludes movies", () => {
|
|
insertUser();
|
|
insertTitle({ id: "m1", tmdbId: 1, type: "movie" });
|
|
insertStatus("user-1", "m1", "in_progress");
|
|
|
|
const feed = getContinueWatchingFeed("user-1");
|
|
expect(feed).toHaveLength(0);
|
|
});
|
|
|
|
test("returns empty when no in-progress shows", () => {
|
|
insertUser();
|
|
const feed = getContinueWatchingFeed("user-1");
|
|
expect(feed).toHaveLength(0);
|
|
});
|
|
|
|
test("sorts by most recent watch", () => {
|
|
insertUser();
|
|
const show1 = insertTvShow("tv-1", 11111, 1, 3);
|
|
const show2 = insertTvShow("tv-2", 22222, 1, 3);
|
|
insertStatus("user-1", show1.titleId, "in_progress");
|
|
insertStatus("user-1", show2.titleId, "in_progress");
|
|
|
|
const older = new Date("2026-01-01");
|
|
const newer = new Date("2026-03-01");
|
|
insertEpisodeWatch("user-1", show1.episodeIds[0], older);
|
|
insertEpisodeWatch("user-1", show2.episodeIds[0], newer);
|
|
|
|
const feed = getContinueWatchingFeed("user-1");
|
|
expect(feed).toHaveLength(2);
|
|
expect(feed[0].title.id).toBe("tv-2");
|
|
expect(feed[1].title.id).toBe("tv-1");
|
|
});
|
|
|
|
test("skips show when all episodes are watched (no next episode)", () => {
|
|
insertUser();
|
|
const { titleId, episodeIds } = insertTvShow("tv-1", 99999, 1, 2);
|
|
insertStatus("user-1", titleId, "in_progress");
|
|
for (const epId of episodeIds) {
|
|
insertEpisodeWatch("user-1", epId);
|
|
}
|
|
|
|
const feed = getContinueWatchingFeed("user-1");
|
|
expect(feed).toHaveLength(0);
|
|
});
|
|
});
|
|
|
|
// ── getNewAvailableFeed ─────────────────────────────────────────────
|
|
|
|
describe("getNewAvailableFeed", () => {
|
|
test("returns titles with availability offers", () => {
|
|
insertUser();
|
|
insertTitle({ id: "m1", tmdbId: 1 });
|
|
insertStatus("user-1", "m1", "watchlist");
|
|
insertAvailabilityOffer("m1");
|
|
|
|
const feed = getNewAvailableFeed("user-1");
|
|
expect(feed).toHaveLength(1);
|
|
expect(feed[0].titleId).toBe("m1");
|
|
});
|
|
|
|
test("excludes titles without availability", () => {
|
|
insertUser();
|
|
insertTitle({ id: "m1", tmdbId: 1 });
|
|
insertStatus("user-1", "m1", "watchlist");
|
|
|
|
const feed = getNewAvailableFeed("user-1");
|
|
expect(feed).toHaveLength(0);
|
|
});
|
|
|
|
test("excludes titles not in user library", () => {
|
|
insertUser();
|
|
insertTitle({ id: "m1", tmdbId: 1 });
|
|
insertAvailabilityOffer("m1");
|
|
|
|
const feed = getNewAvailableFeed("user-1");
|
|
expect(feed).toHaveLength(0);
|
|
});
|
|
});
|
|
|
|
// ── getRecommendationsFeed ──────────────────────────────────────────
|
|
|
|
describe("getRecommendationsFeed", () => {
|
|
test("returns recommendations from completed titles", () => {
|
|
insertUser();
|
|
insertTitle({ id: "m1", tmdbId: 1, title: "Source Movie" });
|
|
insertTitle({ id: "m2", tmdbId: 2, title: "Recommended Movie" });
|
|
insertStatus("user-1", "m1", "completed");
|
|
insertRecommendation("m1", "m2", { rank: 1 });
|
|
|
|
const feed = getRecommendationsFeed("user-1");
|
|
expect(feed).toHaveLength(1);
|
|
expect(feed[0]?.id).toBe("m2");
|
|
});
|
|
|
|
test("returns recommendations from highly-rated titles", () => {
|
|
insertUser();
|
|
insertTitle({ id: "m1", tmdbId: 1 });
|
|
insertTitle({ id: "m2", tmdbId: 2 });
|
|
insertStatus("user-1", "m1", "watchlist");
|
|
insertRating("user-1", "m1", 5);
|
|
insertRecommendation("m1", "m2", { rank: 1 });
|
|
|
|
const feed = getRecommendationsFeed("user-1");
|
|
expect(feed).toHaveLength(1);
|
|
});
|
|
|
|
test("excludes already-tracked titles", () => {
|
|
insertUser();
|
|
insertTitle({ id: "m1", tmdbId: 1 });
|
|
insertTitle({ id: "m2", tmdbId: 2 });
|
|
insertStatus("user-1", "m1", "completed");
|
|
insertStatus("user-1", "m2", "watchlist");
|
|
insertRecommendation("m1", "m2", { rank: 1 });
|
|
|
|
const feed = getRecommendationsFeed("user-1");
|
|
expect(feed).toHaveLength(0);
|
|
});
|
|
|
|
test("returns empty when no source titles", () => {
|
|
insertUser();
|
|
const feed = getRecommendationsFeed("user-1");
|
|
expect(feed).toHaveLength(0);
|
|
});
|
|
|
|
test("scores higher when recommended by multiple sources", () => {
|
|
insertUser();
|
|
insertTitle({ id: "m1", tmdbId: 1 });
|
|
insertTitle({ id: "m2", tmdbId: 2 });
|
|
insertTitle({ id: "m3", tmdbId: 3 });
|
|
insertTitle({ id: "rec1", tmdbId: 10, title: "Double Recommended" });
|
|
insertTitle({ id: "rec2", tmdbId: 20, title: "Single Recommended" });
|
|
insertStatus("user-1", "m1", "completed");
|
|
insertStatus("user-1", "m2", "completed");
|
|
|
|
// rec1 recommended by both m1 and m2
|
|
insertRecommendation("m1", "rec1", { rank: 1 });
|
|
insertRecommendation("m2", "rec1", { rank: 1 });
|
|
// rec2 recommended only by m1
|
|
insertRecommendation("m1", "rec2", { rank: 1 });
|
|
|
|
const feed = getRecommendationsFeed("user-1");
|
|
expect(feed).toHaveLength(2);
|
|
expect(feed[0]?.id).toBe("rec1");
|
|
});
|
|
});
|
|
|
|
// ── getRecommendationsForTitle ──────────────────────────────────────
|
|
|
|
describe("getRecommendationsForTitle", () => {
|
|
test("returns ordered recommendations for a title", () => {
|
|
insertTitle({ id: "m1", tmdbId: 1 });
|
|
insertTitle({ id: "rec1", tmdbId: 10, title: "Rec One" });
|
|
insertTitle({ id: "rec2", tmdbId: 20, title: "Rec Two" });
|
|
insertRecommendation("m1", "rec1", { rank: 2 });
|
|
insertRecommendation("m1", "rec2", { rank: 1 });
|
|
|
|
const recs = getRecommendationsForTitle("m1");
|
|
expect(recs).toHaveLength(2);
|
|
expect(recs[0].title).toBe("Rec Two");
|
|
expect(recs[1].title).toBe("Rec One");
|
|
});
|
|
|
|
test("returns empty for unknown title", () => {
|
|
const recs = getRecommendationsForTitle("nonexistent");
|
|
expect(recs).toHaveLength(0);
|
|
});
|
|
|
|
test("returns empty when no recommendations exist", () => {
|
|
insertTitle({ id: "m1", tmdbId: 1 });
|
|
const recs = getRecommendationsForTitle("m1");
|
|
expect(recs).toHaveLength(0);
|
|
});
|
|
});
|