From 21ff151e38802a1b19c4c2c0ed6b35e4bb774f3c Mon Sep 17 00:00:00 2001 From: Swastik Dan <57379785+Swastikdan@users.noreply.github.com> Date: Sat, 15 Aug 2026 23:40:29 +0530 Subject: [PATCH 01/27] feat: add Cloudflare Workers backend (D1 + Nitro + Drizzle) replacing Convex server-side Port all Convex mutations/queries to TanStack Start server functions backed by D1 (Drizzle ORM + Upstash query cache), Clerk session verification on the Worker, RBAC, Gemini AI via REST, and a daily watchlist-snapshot cron task. Wire up wrangler.toml + D1 migrations, make the cloudflare_module Nitro preset production-only so `vite dev` stays on plain Node SSR, and fix the dev-time `h3-rules` module resolution so `pnpm dev:web` and `wrangler dev` both serve the app (health endpoint pings D1; cron trigger verified locally). --- .env.example | 13 + .gitignore | 6 + drizzle.config.ts | 10 + drizzle/0000_dear_warbound.sql | 139 ++ drizzle/meta/0000_snapshot.json | 980 ++++++++++++ drizzle/meta/_journal.json | 13 + nitro.config.ts | 32 +- package.json | 18 +- pnpm-lock.yaml | 2072 ++++++++++++++++++++++---- pnpm-workspace.yaml | 1 + server/routes/api/health.ts | 63 + server/tasks/snapshots.ts | 19 + src/lib/tmdb.ts | 6 +- src/server/ai.ts | 181 +++ src/server/auth.ts | 218 +++ src/server/db/client.ts | 38 + src/server/db/schema.ts | 239 +++ src/server/env.ts | 38 + src/server/fns/admin.ts | 220 +++ src/server/fns/import-export.ts | 97 ++ src/server/fns/lists.ts | 399 +++++ src/server/fns/recommendations.ts | 939 ++++++++++++ src/server/fns/users.ts | 55 + src/server/fns/watchlist.ts | 530 +++++++ src/server/helpers/snapshots.ts | 89 ++ src/server/helpers/watch-item.ts | 137 ++ src/server/prompts.ts | 411 +++++ src/server/rbac.ts | 277 ++++ src/server/schema/admin.ts | 25 + src/server/schema/common.ts | 77 + src/server/schema/import.ts | 33 + src/server/schema/lists.ts | 56 + src/server/schema/recommendations.ts | 109 ++ src/server/schema/watchlist.ts | 92 ++ wrangler.toml | 25 + 35 files changed, 7369 insertions(+), 288 deletions(-) create mode 100644 drizzle.config.ts create mode 100644 drizzle/0000_dear_warbound.sql create mode 100644 drizzle/meta/0000_snapshot.json create mode 100644 drizzle/meta/_journal.json create mode 100644 server/routes/api/health.ts create mode 100644 server/tasks/snapshots.ts create mode 100644 src/server/ai.ts create mode 100644 src/server/auth.ts create mode 100644 src/server/db/client.ts create mode 100644 src/server/db/schema.ts create mode 100644 src/server/env.ts create mode 100644 src/server/fns/admin.ts create mode 100644 src/server/fns/import-export.ts create mode 100644 src/server/fns/lists.ts create mode 100644 src/server/fns/recommendations.ts create mode 100644 src/server/fns/users.ts create mode 100644 src/server/fns/watchlist.ts create mode 100644 src/server/helpers/snapshots.ts create mode 100644 src/server/helpers/watch-item.ts create mode 100644 src/server/prompts.ts create mode 100644 src/server/rbac.ts create mode 100644 src/server/schema/admin.ts create mode 100644 src/server/schema/common.ts create mode 100644 src/server/schema/import.ts create mode 100644 src/server/schema/lists.ts create mode 100644 src/server/schema/recommendations.ts create mode 100644 src/server/schema/watchlist.ts create mode 100644 wrangler.toml diff --git a/.env.example b/.env.example index d82f2088..05b47a70 100644 --- a/.env.example +++ b/.env.example @@ -21,3 +21,16 @@ CONVEX_DEPLOY_KEY=prod:your-deployment|your-deploy-key # AI Providers (server-only — never expose in client code) OPENROUTER_API_KEY=sk-or-v1-your-key GEMINI_API_KEY=your_gemini_key + +# ---- Cloudflare Workers backend (post-Convex migration) ---- +# Local dev secrets live in .dev.vars (gitignored); production uses +# `wrangler secret put ` with the same names. + +# Clerk (server-side session token verification via @clerk/backend) +CLERK_SECRET_KEY=sk_test_YOUR_CLERK_SECRET_KEY +CLERK_ISSUER_URL=https://your-app.clerk.accounts.dev + +# Upstash Redis (Drizzle query cache + rate limiting) +UPSTASH_REDIS_REST_URL=https://your-db.upstash.io +UPSTASH_REDIS_REST_TOKEN=your-rest-token +UPSTASH_REDIS_READONLY_REST_TOKEN=your-readonly-rest-token diff --git a/.gitignore b/.gitignore index 0539a16c..be7721f6 100644 --- a/.gitignore +++ b/.gitignore @@ -19,3 +19,9 @@ implementation_plan.md .skills-lock.json .agents skills-lock.json + +# Cloudflare / wrangler +.dev.vars +.wrangler/ +convex-export/ + diff --git a/drizzle.config.ts b/drizzle.config.ts new file mode 100644 index 00000000..35a10da3 --- /dev/null +++ b/drizzle.config.ts @@ -0,0 +1,10 @@ +import { defineConfig } from "drizzle-kit"; + +// generate-only config: `drizzle-kit generate` emits SQL migrations into ./drizzle. +// They are applied to D1 with `wrangler d1 migrations apply pebbly [--local|--remote]`, +// so no live DB connection (driver) is required here. +export default defineConfig({ + dialect: "sqlite", + schema: "./src/server/db/schema.ts", + out: "./drizzle", +}); diff --git a/drizzle/0000_dear_warbound.sql b/drizzle/0000_dear_warbound.sql new file mode 100644 index 00000000..ea1fe7d4 --- /dev/null +++ b/drizzle/0000_dear_warbound.sql @@ -0,0 +1,139 @@ +CREATE TABLE `ai_recommendations` ( + `id` text PRIMARY KEY NOT NULL, + `user_id` text NOT NULL, + `recommendations` text NOT NULL, + `original_recommendations` text, + `watchlist_hash` text DEFAULT '' NOT NULL, + `input_stats` text NOT NULL, + `model` text NOT NULL, + `media_type_preference` text, + `genre_preference` text, + `generation_type` text, + `verified` integer DEFAULT false, + `created_at` integer NOT NULL, + FOREIGN KEY (`user_id`) REFERENCES `users`(`id`) ON UPDATE no action ON DELETE cascade +); +--> statement-breakpoint +CREATE INDEX `ai_recs_user_created_idx` ON `ai_recommendations` (`user_id`,`created_at`);--> statement-breakpoint +CREATE TABLE `episode_progress` ( + `id` text PRIMARY KEY NOT NULL, + `user_id` text NOT NULL, + `tmdb_id` integer NOT NULL, + `season` integer NOT NULL, + `episode` integer NOT NULL, + `is_watched` integer DEFAULT false NOT NULL, + `updated_at` integer NOT NULL, + FOREIGN KEY (`user_id`) REFERENCES `users`(`id`) ON UPDATE no action ON DELETE cascade +); +--> statement-breakpoint +CREATE UNIQUE INDEX `episode_user_season_ep_uq` ON `episode_progress` (`user_id`,`tmdb_id`,`season`,`episode`);--> statement-breakpoint +CREATE TABLE `homepage_recommendations` ( + `id` text PRIMARY KEY NOT NULL, + `user_id` text NOT NULL, + `recommendations` text NOT NULL, + `previous_recommendations` text, + `last_attempted_at` integer DEFAULT 0 NOT NULL, + `last_updated_at` integer DEFAULT 0 NOT NULL, + `status` text DEFAULT 'none' NOT NULL, + FOREIGN KEY (`user_id`) REFERENCES `users`(`id`) ON UPDATE no action ON DELETE cascade +); +--> statement-breakpoint +CREATE UNIQUE INDEX `homepage_recommendations_user_id_unique` ON `homepage_recommendations` (`user_id`);--> statement-breakpoint +CREATE TABLE `list_items` ( + `id` text PRIMARY KEY NOT NULL, + `user_id` text NOT NULL, + `list_id` text NOT NULL, + `tmdb_id` integer NOT NULL, + `media_type` text NOT NULL, + `added_at` integer NOT NULL, + `title` text, + `image` text, + `backdrop` text, + `rating` integer, + `release_date` text, + `overview` text, + FOREIGN KEY (`user_id`) REFERENCES `users`(`id`) ON UPDATE no action ON DELETE cascade, + FOREIGN KEY (`list_id`) REFERENCES `lists`(`id`) ON UPDATE no action ON DELETE cascade +); +--> statement-breakpoint +CREATE UNIQUE INDEX `list_items_list_media_uq` ON `list_items` (`list_id`,`tmdb_id`,`media_type`);--> statement-breakpoint +CREATE INDEX `list_items_user_media_idx` ON `list_items` (`user_id`,`tmdb_id`,`media_type`);--> statement-breakpoint +CREATE TABLE `lists` ( + `id` text PRIMARY KEY NOT NULL, + `user_id` text NOT NULL, + `name` text NOT NULL, + `color` text, + `visibility` text, + `list_type` text, + `sort_order` integer DEFAULT 0 NOT NULL, + `created_at` integer NOT NULL, + `updated_at` integer NOT NULL, + FOREIGN KEY (`user_id`) REFERENCES `users`(`id`) ON UPDATE no action ON DELETE cascade +); +--> statement-breakpoint +CREATE UNIQUE INDEX `lists_user_name_uq` ON `lists` (`user_id`,`name`);--> statement-breakpoint +CREATE INDEX `lists_user_sort_idx` ON `lists` (`user_id`,`sort_order`);--> statement-breakpoint +CREATE TABLE `recommendation_feedback` ( + `id` text PRIMARY KEY NOT NULL, + `user_id` text NOT NULL, + `tmdb_id` integer NOT NULL, + `media_type` text NOT NULL, + `title` text NOT NULL, + `feedback` text NOT NULL, + `updated_at` integer NOT NULL, + FOREIGN KEY (`user_id`) REFERENCES `users`(`id`) ON UPDATE no action ON DELETE cascade +); +--> statement-breakpoint +CREATE UNIQUE INDEX `feedback_user_media_uq` ON `recommendation_feedback` (`user_id`,`tmdb_id`,`media_type`);--> statement-breakpoint +CREATE INDEX `feedback_user_feedback_idx` ON `recommendation_feedback` (`user_id`,`feedback`);--> statement-breakpoint +CREATE TABLE `role_permissions` ( + `role` text NOT NULL, + `feature` text NOT NULL, + `enabled` integer DEFAULT true NOT NULL +); +--> statement-breakpoint +CREATE INDEX `role_permissions_pk` ON `role_permissions` (`role`,`feature`);--> statement-breakpoint +CREATE TABLE `users` ( + `id` text PRIMARY KEY NOT NULL, + `token_identifier` text NOT NULL, + `name` text, + `image` text, + `email` text, + `roles` text DEFAULT '[]', + `is_admin` integer DEFAULT false, + `is_banned` integer DEFAULT false +); +--> statement-breakpoint +CREATE UNIQUE INDEX `users_token_identifier_unique` ON `users` (`token_identifier`);--> statement-breakpoint +CREATE TABLE `watch_items` ( + `id` text PRIMARY KEY NOT NULL, + `user_id` text NOT NULL, + `tmdb_id` integer NOT NULL, + `media_type` text NOT NULL, + `in_watchlist` integer DEFAULT false, + `progress_status` text, + `reaction` text, + `progress` integer DEFAULT 0, + `title` text, + `image` text, + `rating` integer, + `release_date` text, + `overview` text, + `updated_at` integer NOT NULL, + FOREIGN KEY (`user_id`) REFERENCES `users`(`id`) ON UPDATE no action ON DELETE cascade, + CONSTRAINT "watch_items_progress_range" CHECK("watch_items"."progress" between 0 and 100), + CONSTRAINT "watch_items_rating_range" CHECK("watch_items"."rating" between 0 and 10) +); +--> statement-breakpoint +CREATE UNIQUE INDEX `watch_items_user_media_uq` ON `watch_items` (`user_id`,`tmdb_id`,`media_type`);--> statement-breakpoint +CREATE INDEX `watch_items_user_status_idx` ON `watch_items` (`user_id`,`progress_status`);--> statement-breakpoint +CREATE INDEX `watch_items_user_updated_idx` ON `watch_items` (`user_id`,`updated_at`);--> statement-breakpoint +CREATE TABLE `watchlist_snapshots` ( + `id` text PRIMARY KEY NOT NULL, + `user_id` text NOT NULL, + `items` text, + `created_at` integer NOT NULL, + FOREIGN KEY (`user_id`) REFERENCES `users`(`id`) ON UPDATE no action ON DELETE cascade +); +--> statement-breakpoint +CREATE INDEX `snapshots_user_created_idx` ON `watchlist_snapshots` (`user_id`,`created_at`); \ No newline at end of file diff --git a/drizzle/meta/0000_snapshot.json b/drizzle/meta/0000_snapshot.json new file mode 100644 index 00000000..ef0c9cc2 --- /dev/null +++ b/drizzle/meta/0000_snapshot.json @@ -0,0 +1,980 @@ +{ + "version": "6", + "dialect": "sqlite", + "id": "28c96ef3-0b1e-4128-8d3d-a6f1a1b5c209", + "prevId": "00000000-0000-0000-0000-000000000000", + "tables": { + "ai_recommendations": { + "name": "ai_recommendations", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "recommendations": { + "name": "recommendations", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "original_recommendations": { + "name": "original_recommendations", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "watchlist_hash": { + "name": "watchlist_hash", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "''" + }, + "input_stats": { + "name": "input_stats", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "model": { + "name": "model", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "media_type_preference": { + "name": "media_type_preference", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "genre_preference": { + "name": "genre_preference", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "generation_type": { + "name": "generation_type", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "verified": { + "name": "verified", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false, + "default": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": { + "ai_recs_user_created_idx": { + "name": "ai_recs_user_created_idx", + "columns": [ + "user_id", + "created_at" + ], + "isUnique": false + } + }, + "foreignKeys": { + "ai_recommendations_user_id_users_id_fk": { + "name": "ai_recommendations_user_id_users_id_fk", + "tableFrom": "ai_recommendations", + "tableTo": "users", + "columnsFrom": [ + "user_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "episode_progress": { + "name": "episode_progress", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "tmdb_id": { + "name": "tmdb_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "season": { + "name": "season", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "episode": { + "name": "episode", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "is_watched": { + "name": "is_watched", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": false + }, + "updated_at": { + "name": "updated_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": { + "episode_user_season_ep_uq": { + "name": "episode_user_season_ep_uq", + "columns": [ + "user_id", + "tmdb_id", + "season", + "episode" + ], + "isUnique": true + } + }, + "foreignKeys": { + "episode_progress_user_id_users_id_fk": { + "name": "episode_progress_user_id_users_id_fk", + "tableFrom": "episode_progress", + "tableTo": "users", + "columnsFrom": [ + "user_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "homepage_recommendations": { + "name": "homepage_recommendations", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "recommendations": { + "name": "recommendations", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "previous_recommendations": { + "name": "previous_recommendations", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "last_attempted_at": { + "name": "last_attempted_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 0 + }, + "last_updated_at": { + "name": "last_updated_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 0 + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'none'" + } + }, + "indexes": { + "homepage_recommendations_user_id_unique": { + "name": "homepage_recommendations_user_id_unique", + "columns": [ + "user_id" + ], + "isUnique": true + } + }, + "foreignKeys": { + "homepage_recommendations_user_id_users_id_fk": { + "name": "homepage_recommendations_user_id_users_id_fk", + "tableFrom": "homepage_recommendations", + "tableTo": "users", + "columnsFrom": [ + "user_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "list_items": { + "name": "list_items", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "list_id": { + "name": "list_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "tmdb_id": { + "name": "tmdb_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "media_type": { + "name": "media_type", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "added_at": { + "name": "added_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "title": { + "name": "title", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "image": { + "name": "image", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "backdrop": { + "name": "backdrop", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "rating": { + "name": "rating", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "release_date": { + "name": "release_date", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "overview": { + "name": "overview", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": { + "list_items_list_media_uq": { + "name": "list_items_list_media_uq", + "columns": [ + "list_id", + "tmdb_id", + "media_type" + ], + "isUnique": true + }, + "list_items_user_media_idx": { + "name": "list_items_user_media_idx", + "columns": [ + "user_id", + "tmdb_id", + "media_type" + ], + "isUnique": false + } + }, + "foreignKeys": { + "list_items_user_id_users_id_fk": { + "name": "list_items_user_id_users_id_fk", + "tableFrom": "list_items", + "tableTo": "users", + "columnsFrom": [ + "user_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "list_items_list_id_lists_id_fk": { + "name": "list_items_list_id_lists_id_fk", + "tableFrom": "list_items", + "tableTo": "lists", + "columnsFrom": [ + "list_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "lists": { + "name": "lists", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "color": { + "name": "color", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "visibility": { + "name": "visibility", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "list_type": { + "name": "list_type", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "sort_order": { + "name": "sort_order", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 0 + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "updated_at": { + "name": "updated_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": { + "lists_user_name_uq": { + "name": "lists_user_name_uq", + "columns": [ + "user_id", + "name" + ], + "isUnique": true + }, + "lists_user_sort_idx": { + "name": "lists_user_sort_idx", + "columns": [ + "user_id", + "sort_order" + ], + "isUnique": false + } + }, + "foreignKeys": { + "lists_user_id_users_id_fk": { + "name": "lists_user_id_users_id_fk", + "tableFrom": "lists", + "tableTo": "users", + "columnsFrom": [ + "user_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "recommendation_feedback": { + "name": "recommendation_feedback", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "tmdb_id": { + "name": "tmdb_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "media_type": { + "name": "media_type", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "title": { + "name": "title", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "feedback": { + "name": "feedback", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "updated_at": { + "name": "updated_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": { + "feedback_user_media_uq": { + "name": "feedback_user_media_uq", + "columns": [ + "user_id", + "tmdb_id", + "media_type" + ], + "isUnique": true + }, + "feedback_user_feedback_idx": { + "name": "feedback_user_feedback_idx", + "columns": [ + "user_id", + "feedback" + ], + "isUnique": false + } + }, + "foreignKeys": { + "recommendation_feedback_user_id_users_id_fk": { + "name": "recommendation_feedback_user_id_users_id_fk", + "tableFrom": "recommendation_feedback", + "tableTo": "users", + "columnsFrom": [ + "user_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "role_permissions": { + "name": "role_permissions", + "columns": { + "role": { + "name": "role", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "feature": { + "name": "feature", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "enabled": { + "name": "enabled", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": true + } + }, + "indexes": { + "role_permissions_pk": { + "name": "role_permissions_pk", + "columns": [ + "role", + "feature" + ], + "isUnique": false + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "users": { + "name": "users", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "token_identifier": { + "name": "token_identifier", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "image": { + "name": "image", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "email": { + "name": "email", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "roles": { + "name": "roles", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false, + "default": "'[]'" + }, + "is_admin": { + "name": "is_admin", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false, + "default": false + }, + "is_banned": { + "name": "is_banned", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false, + "default": false + } + }, + "indexes": { + "users_token_identifier_unique": { + "name": "users_token_identifier_unique", + "columns": [ + "token_identifier" + ], + "isUnique": true + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "watch_items": { + "name": "watch_items", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "tmdb_id": { + "name": "tmdb_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "media_type": { + "name": "media_type", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "in_watchlist": { + "name": "in_watchlist", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false, + "default": false + }, + "progress_status": { + "name": "progress_status", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "reaction": { + "name": "reaction", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "progress": { + "name": "progress", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false, + "default": 0 + }, + "title": { + "name": "title", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "image": { + "name": "image", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "rating": { + "name": "rating", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "release_date": { + "name": "release_date", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "overview": { + "name": "overview", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "updated_at": { + "name": "updated_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": { + "watch_items_user_media_uq": { + "name": "watch_items_user_media_uq", + "columns": [ + "user_id", + "tmdb_id", + "media_type" + ], + "isUnique": true + }, + "watch_items_user_status_idx": { + "name": "watch_items_user_status_idx", + "columns": [ + "user_id", + "progress_status" + ], + "isUnique": false + }, + "watch_items_user_updated_idx": { + "name": "watch_items_user_updated_idx", + "columns": [ + "user_id", + "updated_at" + ], + "isUnique": false + } + }, + "foreignKeys": { + "watch_items_user_id_users_id_fk": { + "name": "watch_items_user_id_users_id_fk", + "tableFrom": "watch_items", + "tableTo": "users", + "columnsFrom": [ + "user_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": { + "watch_items_progress_range": { + "name": "watch_items_progress_range", + "value": "\"watch_items\".\"progress\" between 0 and 100" + }, + "watch_items_rating_range": { + "name": "watch_items_rating_range", + "value": "\"watch_items\".\"rating\" between 0 and 10" + } + } + }, + "watchlist_snapshots": { + "name": "watchlist_snapshots", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "items": { + "name": "items", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": { + "snapshots_user_created_idx": { + "name": "snapshots_user_created_idx", + "columns": [ + "user_id", + "created_at" + ], + "isUnique": false + } + }, + "foreignKeys": { + "watchlist_snapshots_user_id_users_id_fk": { + "name": "watchlist_snapshots_user_id_users_id_fk", + "tableFrom": "watchlist_snapshots", + "tableTo": "users", + "columnsFrom": [ + "user_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + } + }, + "views": {}, + "enums": {}, + "_meta": { + "schemas": {}, + "tables": {}, + "columns": {} + }, + "internal": { + "indexes": {} + } +} \ No newline at end of file diff --git a/drizzle/meta/_journal.json b/drizzle/meta/_journal.json new file mode 100644 index 00000000..a9e10b59 --- /dev/null +++ b/drizzle/meta/_journal.json @@ -0,0 +1,13 @@ +{ + "version": "7", + "dialect": "sqlite", + "entries": [ + { + "idx": 0, + "version": "6", + "when": 1786817243575, + "tag": "0000_dear_warbound", + "breakpoints": true + } + ] +} \ No newline at end of file diff --git a/nitro.config.ts b/nitro.config.ts index 5393dd64..d240bdca 100644 --- a/nitro.config.ts +++ b/nitro.config.ts @@ -1,12 +1,32 @@ -// @ts-nocheck -import { defineNitroConfig } from "nitropack"; +import { defineNitroConfig } from "nitro/config"; export default defineNitroConfig({ + // Scan `server/` for Nitro routes/tasks/plugins (the tanstack app's own + // `src/server` code is bundled by the TanStack plugin, not scanned here). + scanDirs: ["./server"], + // Enable Nitro's experimental task system, which is what Cloudflare Cron + // Triggers dispatch to (the cloudflare-module preset's `scheduled()` handler + // calls `runCronTasks(controller.cron)` when tasks are enabled). + experimental: { + tasks: true, + }, + // Daily watchlist snapshot at 03:00 UTC — matches the `[triggers]` cron in + // wrangler.toml. The task itself lives in server/tasks/snapshots.ts. + scheduledTasks: { + "0 3 * * *": "snapshots", + }, routeRules: { "/assets/**": { headers: { - "Cache-Control": "public, max-age=31536000, immutable" - } - } - } + "Cache-Control": "public, max-age=31536000, immutable", + }, + }, + }, + // Cloudflare Workers is the deployment target for production builds only. + // In dev (`vite dev`), the default nitro-dev preset is used so the Vite SSR + // server runs as plain Node — full Worker emulation (D1, secrets, cron) is + // exercised via `wrangler dev` against the built output instead. + $production: { + preset: "cloudflare_module", + }, }); diff --git a/package.json b/package.json index fb8eb961..0e1cc5bb 100644 --- a/package.json +++ b/package.json @@ -5,9 +5,14 @@ "scripts": { "dev": "concurrently -n web,convex -c blue,magenta \"vite dev --port 5296 --host\" \"pnpm dlx convex dev\"", "dev:web": "vite dev --port 3000", + "dev:cf": "wrangler dev", "build": "vite build", "build:vercel": "pnpm dlx convex deploy --cmd 'pnpm run build' --cmd-url-env-var-name VITE_CONVEX_URL", "start": "vite preview --port 5296", + "db:generate": "drizzle-kit generate", + "db:migrate:local": "wrangler d1 migrations apply pebbly --local", + "db:migrate:prod": "wrangler d1 migrations apply pebbly --remote", + "deploy:cf": "pnpm build && wrangler deploy", "lint": "biome lint --max-diagnostics 20", "format": "biome format --write .", "typecheck": "tsc --noEmit", @@ -22,6 +27,7 @@ "dependencies": { "@better-fetch/fetch": "^1.3.1", "@better-fetch/logger": "^1.3.1", + "@clerk/backend": "^3.16.1", "@clerk/react": "^6.12.8", "@clerk/ui": "^1.26.0", "@convex-dev/react-query": "^0.1.0", @@ -44,12 +50,18 @@ "@tanstack/react-start": "^1.168.32", "@tanstack/router-plugin": "^1.168.23", "@unpic/react": "^1.0.2", + "@upstash/ratelimit": "^2.0.8", + "@upstash/redis": "^1.38.2", "@vercel/speed-insights": "^1.3.1", "class-variance-authority": "^0.7.1", "clsx": "^2.1.1", "convex": "^1.42.3", + "drizzle-orm": "^0.45.2", + "h3": "2.0.1-rc.26", + "h3-rules": "0.1.0", "lucide-react": "^0.544.0", "nitro": "npm:nitro-nightly@latest", + "nitropack": "^2.13.4", "postcss": "^8.5.23", "radix-ui": "^1.6.7", "react": "^19.2.8", @@ -58,10 +70,12 @@ "tailwindcss": "^4.3.3", "valibot": "^1.4.2", "vite-tsconfig-paths": "^5.1.4", + "zod": "^4.4.3", "zustand": "^5.0.14" }, "devDependencies": { "@biomejs/biome": "2.4.13", + "@cloudflare/workers-types": "^5.20260808.1", "@fontsource-variable/bricolage-grotesque": "^5.3.0", "@tanstack/react-devtools": "^0.7.11", "@tanstack/react-query-devtools": "^5.101.4", @@ -73,6 +87,7 @@ "babel-plugin-react-compiler": "^1.0.0", "baseline-browser-mapping": "^2.11.3", "concurrently": "^9.2.4", + "drizzle-kit": "^0.31.10", "husky": "^9.1.7", "jsdom": "^27.4.0", "lint-staged": "^17.2.0", @@ -80,6 +95,7 @@ "terser": "^5.49.0", "tw-animate-css": "^1.4.0", "typescript": "^5.9.3", - "vite": "^7.3.6" + "vite": "^7.3.6", + "wrangler": "^4.120.0" } } diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index ab645313..6ba85ac1 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -14,6 +14,9 @@ importers: '@better-fetch/logger': specifier: ^1.3.1 version: 1.3.1 + '@clerk/backend': + specifier: ^3.16.1 + version: 3.16.1(react-dom@19.2.8(react@19.2.8))(react@19.2.8) '@clerk/react': specifier: ^6.12.8 version: 6.12.8(react-dom@19.2.8(react@19.2.8))(react@19.2.8) @@ -28,7 +31,7 @@ importers: version: 5.3.0 '@google/genai': specifier: ^1.52.0 - version: 1.52.0(@modelcontextprotocol/sdk@1.29.0(supports-color@10.2.2)(zod@3.25.76))(bufferutil@4.1.0)(supports-color@10.2.2)(utf-8-validate@6.0.6) + version: 1.52.0(@modelcontextprotocol/sdk@1.29.0(supports-color@10.2.2)(zod@4.4.3))(bufferutil@4.1.0)(supports-color@10.2.2)(utf-8-validate@6.0.6) '@radix-ui/react-accordion': specifier: ^1.2.20 version: 1.2.20(@types/react-dom@19.2.3(@types/react@19.2.17))(@types/react@19.2.17)(react-dom@19.2.8(react@19.2.8))(react@19.2.8) @@ -55,10 +58,10 @@ importers: version: 4.3.3 '@tailwindcss/vite': specifier: ^4.3.3 - version: 4.3.3(vite@7.3.6(@types/node@22.20.1)(jiti@2.7.0)(lightningcss@1.32.0)(terser@5.49.0)(yaml@2.9.0)) + version: 4.3.3(vite@7.3.6(@types/node@22.20.1)(jiti@2.7.0)(lightningcss@1.32.0)(terser@5.49.0)(tsx@4.23.11)(yaml@2.9.0)) '@tanstack/nitro-v2-vite-plugin': specifier: ^1.155.0 - version: 1.155.0(srvx@0.8.16)(supports-color@10.2.2)(vite@7.3.6(@types/node@22.20.1)(jiti@2.7.0)(lightningcss@1.32.0)(terser@5.49.0)(yaml@2.9.0)) + version: 1.155.0(@upstash/redis@1.38.2)(drizzle-orm@0.45.2(@cloudflare/workers-types@5.20260808.1)(@upstash/redis@1.38.2))(rolldown@1.2.3)(srvx@0.11.22)(supports-color@10.2.2)(vite@7.3.6(@types/node@22.20.1)(jiti@2.7.0)(lightningcss@1.32.0)(terser@5.49.0)(tsx@4.23.11)(yaml@2.9.0)) '@tanstack/react-query': specifier: ^5.101.4 version: 5.101.4(react@19.2.8) @@ -73,13 +76,19 @@ importers: version: 1.130.17(@tanstack/react-query@5.101.4(react@19.2.8))(@tanstack/react-router@1.170.18(react-dom@19.2.8(react@19.2.8))(react@19.2.8))(@tanstack/router-core@1.171.15)(react-dom@19.2.8(react@19.2.8))(react@19.2.8) '@tanstack/react-start': specifier: ^1.168.32 - version: 1.168.32(crossws@0.4.5(srvx@0.8.16))(react-dom@19.2.8(react@19.2.8))(react@19.2.8)(supports-color@10.2.2)(vite@7.3.6(@types/node@22.20.1)(jiti@2.7.0)(lightningcss@1.32.0)(terser@5.49.0)(yaml@2.9.0)) + version: 1.168.32(crossws@0.4.10(srvx@0.11.22))(react-dom@19.2.8(react@19.2.8))(react@19.2.8)(supports-color@10.2.2)(vite@7.3.6(@types/node@22.20.1)(jiti@2.7.0)(lightningcss@1.32.0)(terser@5.49.0)(tsx@4.23.11)(yaml@2.9.0)) '@tanstack/router-plugin': specifier: ^1.168.23 - version: 1.168.23(@tanstack/react-router@1.170.18(react-dom@19.2.8(react@19.2.8))(react@19.2.8))(supports-color@10.2.2)(vite@7.3.6(@types/node@22.20.1)(jiti@2.7.0)(lightningcss@1.32.0)(terser@5.49.0)(yaml@2.9.0)) + version: 1.168.23(@tanstack/react-router@1.170.18(react-dom@19.2.8(react@19.2.8))(react@19.2.8))(supports-color@10.2.2)(vite@7.3.6(@types/node@22.20.1)(jiti@2.7.0)(lightningcss@1.32.0)(terser@5.49.0)(tsx@4.23.11)(yaml@2.9.0)) '@unpic/react': specifier: ^1.0.2 version: 1.0.2(react-dom@19.2.8(react@19.2.8))(react@19.2.8) + '@upstash/ratelimit': + specifier: ^2.0.8 + version: 2.0.8(@upstash/redis@1.38.2) + '@upstash/redis': + specifier: ^1.38.2 + version: 1.38.2 '@vercel/speed-insights': specifier: ^1.3.1 version: 1.3.1(react@19.2.8) @@ -92,12 +101,24 @@ importers: convex: specifier: ^1.42.3 version: 1.42.3(@clerk/react@6.12.8(react-dom@19.2.8(react@19.2.8))(react@19.2.8))(bufferutil@4.1.0)(react@19.2.8)(utf-8-validate@6.0.6) + drizzle-orm: + specifier: ^0.45.2 + version: 0.45.2(@cloudflare/workers-types@5.20260808.1)(@upstash/redis@1.38.2) + h3: + specifier: 2.0.1-rc.26 + version: 2.0.1-rc.26(crossws@0.4.10(srvx@0.11.22)) + h3-rules: + specifier: 0.1.0 + version: 0.1.0(h3@2.0.1-rc.26(crossws@0.4.10(srvx@0.11.22)))(ocache@0.2.0) lucide-react: specifier: ^0.544.0 version: 0.544.0(react@19.2.8) nitro: specifier: npm:nitro-nightly@latest - version: nitro-nightly@4.0.0-20251010-091516-7cafddba(ioredis@5.11.1(supports-color@10.2.2))(lru-cache@11.5.1)(vite@7.3.6(@types/node@22.20.1)(jiti@2.7.0)(lightningcss@1.32.0)(terser@5.49.0)(yaml@2.9.0)) + version: nitro-nightly@3.0.1-20260731-205209-52abde8a(@upstash/redis@1.38.2)(chokidar@5.0.0)(dotenv@17.4.2)(drizzle-orm@0.45.2(@cloudflare/workers-types@5.20260808.1)(@upstash/redis@1.38.2))(giget@3.2.0)(ioredis@5.11.1(supports-color@10.2.2))(jiti@2.7.0)(lru-cache@11.5.1)(rollup@4.61.1)(vite@7.3.6(@types/node@22.20.1)(jiti@2.7.0)(lightningcss@1.32.0)(terser@5.49.0)(tsx@4.23.11)(yaml@2.9.0))(wrangler@4.120.0(@cloudflare/workers-types@5.20260808.1)(bufferutil@4.1.0)(utf-8-validate@6.0.6)) + nitropack: + specifier: ^2.13.4 + version: 2.13.4(@upstash/redis@1.38.2)(drizzle-orm@0.45.2(@cloudflare/workers-types@5.20260808.1)(@upstash/redis@1.38.2))(rolldown@1.2.3)(srvx@0.11.22)(supports-color@10.2.2) postcss: specifier: ^8.5.23 version: 8.5.23 @@ -121,7 +142,10 @@ importers: version: 1.4.2(typescript@5.9.3) vite-tsconfig-paths: specifier: ^5.1.4 - version: 5.1.4(supports-color@10.2.2)(typescript@5.9.3)(vite@7.3.6(@types/node@22.20.1)(jiti@2.7.0)(lightningcss@1.32.0)(terser@5.49.0)(yaml@2.9.0)) + version: 5.1.4(supports-color@10.2.2)(typescript@5.9.3)(vite@7.3.6(@types/node@22.20.1)(jiti@2.7.0)(lightningcss@1.32.0)(terser@5.49.0)(tsx@4.23.11)(yaml@2.9.0)) + zod: + specifier: ^4.4.3 + version: 4.4.3 zustand: specifier: ^5.0.14 version: 5.0.14(@types/react@19.2.17)(react@19.2.8)(use-sync-external-store@1.6.0(react@19.2.8)) @@ -129,6 +153,9 @@ importers: '@biomejs/biome': specifier: 2.4.13 version: 2.4.13 + '@cloudflare/workers-types': + specifier: ^5.20260808.1 + version: 5.20260808.1 '@fontsource-variable/bricolage-grotesque': specifier: ^5.3.0 version: 5.3.0 @@ -152,7 +179,7 @@ importers: version: 19.2.3(@types/react@19.2.17) '@vitejs/plugin-react': specifier: ^5.2.0 - version: 5.2.0(supports-color@10.2.2)(vite@7.3.6(@types/node@22.20.1)(jiti@2.7.0)(lightningcss@1.32.0)(terser@5.49.0)(yaml@2.9.0)) + version: 5.2.0(supports-color@10.2.2)(vite@7.3.6(@types/node@22.20.1)(jiti@2.7.0)(lightningcss@1.32.0)(terser@5.49.0)(tsx@4.23.11)(yaml@2.9.0)) babel-plugin-react-compiler: specifier: ^1.0.0 version: 1.0.0 @@ -162,6 +189,9 @@ importers: concurrently: specifier: ^9.2.4 version: 9.2.4 + drizzle-kit: + specifier: ^0.31.10 + version: 0.31.10 husky: specifier: ^9.1.7 version: 9.1.7 @@ -185,7 +215,10 @@ importers: version: 5.9.3 vite: specifier: ^7.3.6 - version: 7.3.6(@types/node@22.20.1)(jiti@2.7.0)(lightningcss@1.32.0)(terser@5.49.0)(yaml@2.9.0) + version: 7.3.6(@types/node@22.20.1)(jiti@2.7.0)(lightningcss@1.32.0)(terser@5.49.0)(tsx@4.23.11)(yaml@2.9.0) + wrangler: + specifier: ^4.120.0 + version: 4.120.0(@cloudflare/workers-types@5.20260808.1)(bufferutil@4.1.0)(utf-8-validate@6.0.6) packages: @@ -417,6 +450,10 @@ packages: cpu: [x64] os: [win32] + '@clerk/backend@3.16.1': + resolution: {integrity: sha512-tbsrGqw45ar7PDnEV3gwkHE/HM1EwRcYPPLyL3Hw9H0Ms5fG7hZ8+EJegPJ4DpKdfvOw5M+hYMeCVKwv3NxahA==} + engines: {node: '>=20.9.0'} + '@clerk/localizations@4.13.8': resolution: {integrity: sha512-xM5XlvlvKEKpHwojsqGhrK023izLpnE5ExPdA8qOIQDTWzC3/2CIngliijYL1hyA485zkgew0yHOXwHTJRmoVw==} engines: {node: '>=20.9.0'} @@ -440,6 +477,18 @@ packages: react-dom: optional: true + '@clerk/shared@4.27.1': + resolution: {integrity: sha512-eAin1Iy42P3vkytTebD99BhxDm6Yh72Kf8xnpM401Yz/hPUe/Ut4jFqU64xzlhf/RTCPfoTkOHaNDWdMACwXjQ==} + engines: {node: '>=20.9.0'} + peerDependencies: + react: ^18.0.0 || ~19.0.3 || ~19.1.4 || ~19.2.3 || ~19.3.0-0 + react-dom: ^18.0.0 || ~19.0.3 || ~19.1.4 || ~19.2.3 || ~19.3.0-0 + peerDependenciesMeta: + react: + optional: true + react-dom: + optional: true + '@clerk/ui@1.26.0': resolution: {integrity: sha512-wvJqM9vWvHNyznJmC5h2RpJ2YMeTfDOcFuPUD2e4vPkv42oqL4CPg84+2zjinCuYbRRf3F6lbVDO5Q3wOEHMYw==} engines: {node: '>=20.9.0'} @@ -451,12 +500,62 @@ packages: resolution: {integrity: sha512-SIOD2DxrRRwQ+jgzlXCqoEFiKOFqaPjhnNTGKXSRLvp1HiOvapLaFG2kEr9dYQTYe8rKrd9uvDUzmAITeNyaHQ==} engines: {node: '>=18.0.0'} + '@cloudflare/kv-asset-handler@0.5.0': + resolution: {integrity: sha512-jxQYkj8dSIzc0cD6cMMNdOc1UVjqSqu8BZdor5s8cGjW2I8BjODt/kWPVdY+u9zj3ms75Q5qaZgnxUad83+eAg==} + engines: {node: '>=22.0.0'} + + '@cloudflare/unenv-preset@2.16.1': + resolution: {integrity: sha512-ECxObrMfyTl5bhQf/lZCXwo5G6xX9IAUo+nDMKK4SZ8m4Jvvxp52vilxyySSWh2YTZz8+HQ07qGH/2rEom1vDw==} + peerDependencies: + unenv: 2.0.0-rc.24 + workerd: '>1.20260305.0 <2.0.0-0' + peerDependenciesMeta: + workerd: + optional: true + + '@cloudflare/workerd-darwin-64@1.20260801.1': + resolution: {integrity: sha512-wuJWbXpKvncJi1P0GKS+iYpN5tHdb7JPJJ/+6ZQe8zzovHHVMkLJPNBsgWpqeUhpM3g9qTwEKd2rglNKejuh5A==} + engines: {node: '>=16'} + cpu: [x64] + os: [darwin] + + '@cloudflare/workerd-darwin-arm64@1.20260801.1': + resolution: {integrity: sha512-kwoZiTpnhNrF3+APx84Q/oAqvJ3sU9yefGagwm/ASaH/2W19x0vghkW/r4qCoHCK0WW7EPugZ+aXjgPMRtlq1Q==} + engines: {node: '>=16'} + cpu: [arm64] + os: [darwin] + + '@cloudflare/workerd-linux-64@1.20260801.1': + resolution: {integrity: sha512-r0vAxCZH+Jih9Unm1yoyiByPNWNgawcKciOHDm5Q37ZVGOkKLsT9AtLe3yLSaul76WrKqtf+JP2n0WW32VBLJg==} + engines: {node: '>=16'} + cpu: [x64] + os: [linux] + + '@cloudflare/workerd-linux-arm64@1.20260801.1': + resolution: {integrity: sha512-zWgpdZtSozvIgzQNmQiDSF8yEOQJUkRAWNsDXXzAAoy+fCn8YUoSibj3mpFSbZRvbUldeBEaW6SCdC2VEMkhNQ==} + engines: {node: '>=16'} + cpu: [arm64] + os: [linux] + + '@cloudflare/workerd-windows-64@1.20260801.1': + resolution: {integrity: sha512-2oQz+Ksu4ji6e/+ZoYX+tWQEcxAii2p7l+iR8kx48W1llMalaufAsmVxTlk+3/vrM7D3/2c0iK448e0UQTcIMg==} + engines: {node: '>=16'} + cpu: [x64] + os: [win32] + + '@cloudflare/workers-types@5.20260808.1': + resolution: {integrity: sha512-DN7G9SMyeOq031YhQexoExFAK78ms74cFiFF1teDlTK4+LjHgIc5Z8VbvXQtcCIP//o38btxzxW0b9MGPA83CA==} + '@convex-dev/react-query@0.1.0': resolution: {integrity: sha512-ULmBZCtAQDUePdBhUv7hj1Yy4QiCelhi6uEIOtMpjW8db6W9CFKvQwLt9heLngccFyMFfAZdOfSrT+cP4AH0Jw==} peerDependencies: '@tanstack/react-query': ^5.0.0 convex: ^1.29.3 + '@cspotcode/source-map-support@0.8.1': + resolution: {integrity: sha512-IchNf6dN4tHoMFIn/7OE8LWZ19Y6q/67Bmf6vnGREv8RSbBVb9LPJxEcnwrcwX6ixSvaiGoomAUvu4YSxXrVgw==} + engines: {node: '>=12'} + '@csstools/color-helpers@6.0.2': resolution: {integrity: sha512-LMGQLS9EuADloEFkcTBR3BwV/CGHV7zyDxVRtVDTwdI2Ca4it0CCVTT9wCkxSgokjE5Ho41hEPgb8OEUwoXr6Q==} engines: {node: '>=20.19.0'} @@ -500,6 +599,12 @@ packages: '@dotenvx/primitives@0.8.0': resolution: {integrity: sha512-VYJy0uhFm9zTJ1TxBaW/pA8bjbOM/OttaNMwZ1RHG4JKyRG7DhSdiqD1ipQoAyoD22olUtxbP78W9xY3Wd11bg==} + '@drizzle-team/brocli@0.10.2': + resolution: {integrity: sha512-z33Il7l5dKjUgGULTqBsQBQwckHh5AbIuxhdsIxDDiZAzBOrZO6q9ogcWC65kU382AfynTfgNumVcNIjuIua6w==} + + '@emnapi/runtime@1.11.3': + resolution: {integrity: sha512-Xz4Tpyki7XyrpbUK1jR1AhdAdaXyhhY4lZ3neLodmhpuWfy2PAQN5B46sAiU4liOXGLkHypn/qU+jvfWSCYYLA==} + '@emotion/babel-plugin@11.13.5': resolution: {integrity: sha512-pxHCpT2ex+0q+HH91/zsdHkw/lXd468DIN2zvfvLtPKLLMo6gQj7oLObq8PhkrxOZb/gGCq03S3Z7PDhS8pduQ==} @@ -544,6 +649,14 @@ packages: '@emotion/weak-memoize@0.3.1': resolution: {integrity: sha512-EsBwpc7hBUJWAsNPBmJy4hxWx12v6bshQsldrVmjxJoc3isbxhOrF2IcCpaXxfvq03NwkI7sbsOLXbYuqF/8Ww==} + '@esbuild-kit/core-utils@3.3.2': + resolution: {integrity: sha512-sPRAnw9CdSsRmEtnsl2WXWdyquogVpB3yZ3dgwJfe8zrOzTsV7cJvmwrKVa+0ma5BoiGJ+BoqkMvawbayKUsqQ==} + deprecated: 'Merged into tsx: https://tsx.hirok.io' + + '@esbuild-kit/esm-loader@2.6.5': + resolution: {integrity: sha512-FxEMIkJKnodyA1OaCUoEvbYRkoZlLZ4d/eXFu9Fh8CbBBgP5EmZxrfTRyN0qpXZ4vOvqnE5YdRdcrmUUXuU+dA==} + deprecated: 'Merged into tsx: https://tsx.hirok.io' + '@esbuild/aix-ppc64@0.25.12': resolution: {integrity: sha512-Hhmwd6CInZ3dwpuGTF8fJG6yoWmsToE+vYgD4nytZVxcu1ulHpUQRAB1UJ8+N1Am3Mz4+xOByoQoSZf4D+CpkA==} engines: {node: '>=18'} @@ -562,6 +675,18 @@ packages: cpu: [ppc64] os: [aix] + '@esbuild/aix-ppc64@0.28.1': + resolution: {integrity: sha512-Svl7tq8k/08+p6CXPpRjQ1fKX+1odH/BQbb48fV6fj3CWHhsoIOoY87w1oHXm0qEpkIK3ZfVgp0hed3XBXzXMQ==} + engines: {node: '>=18'} + cpu: [ppc64] + os: [aix] + + '@esbuild/android-arm64@0.18.20': + resolution: {integrity: sha512-Nz4rJcchGDtENV0eMKUNa6L12zz2zBDXuhj/Vjh18zGqB44Bi7MBMSXjgunJgjRhCmKOjnPuZp4Mb6OKqtMHLQ==} + engines: {node: '>=12'} + cpu: [arm64] + os: [android] + '@esbuild/android-arm64@0.25.12': resolution: {integrity: sha512-6AAmLG7zwD1Z159jCKPvAxZd4y/VTO0VkprYy+3N2FtJ8+BQWFXU+OxARIwA46c5tdD9SsKGZ/1ocqBS/gAKHg==} engines: {node: '>=18'} @@ -580,6 +705,18 @@ packages: cpu: [arm64] os: [android] + '@esbuild/android-arm64@0.28.1': + resolution: {integrity: sha512-34EGEbCIAgosYz6goLcopX6Mo7NyGv9tfwEM2/7Ce2VcVRk568iSvniGWcUXIy7wEDR1wzolcxcriFVrWYcwBg==} + engines: {node: '>=18'} + cpu: [arm64] + os: [android] + + '@esbuild/android-arm@0.18.20': + resolution: {integrity: sha512-fyi7TDI/ijKKNZTUJAQqiG5T7YjJXgnzkURqmGj13C6dCqckZBLdl4h7bkhHt/t0WP+zO9/zwroDvANaOqO5Sw==} + engines: {node: '>=12'} + cpu: [arm] + os: [android] + '@esbuild/android-arm@0.25.12': resolution: {integrity: sha512-VJ+sKvNA/GE7Ccacc9Cha7bpS8nyzVv0jdVgwNDaR4gDMC/2TTRc33Ip8qrNYUcpkOHUT5OZ0bUcNNVZQ9RLlg==} engines: {node: '>=18'} @@ -598,6 +735,18 @@ packages: cpu: [arm] os: [android] + '@esbuild/android-arm@0.28.1': + resolution: {integrity: sha512-0k2F129Xdio1TdJfzJ8sy1Q47vUD2NnwdhiAf7drUN1EBTfPf4hsFCtmMgu/6m8JSzsBrlmVjudMBQqOfG8usQ==} + engines: {node: '>=18'} + cpu: [arm] + os: [android] + + '@esbuild/android-x64@0.18.20': + resolution: {integrity: sha512-8GDdlePJA8D6zlZYJV/jnrRAi6rOiNaCC/JclcXpB+KIuvfBN4owLtgzY2bsxnx666XjJx2kDPUmnTtR8qKQUg==} + engines: {node: '>=12'} + cpu: [x64] + os: [android] + '@esbuild/android-x64@0.25.12': resolution: {integrity: sha512-5jbb+2hhDHx5phYR2By8GTWEzn6I9UqR11Kwf22iKbNpYrsmRB18aX/9ivc5cabcUiAT/wM+YIZ6SG9QO6a8kg==} engines: {node: '>=18'} @@ -616,6 +765,18 @@ packages: cpu: [x64] os: [android] + '@esbuild/android-x64@0.28.1': + resolution: {integrity: sha512-dbwY7ltSMDWsRatcRpCnES4F+im88OCUgGZjy52shC7GqHRE/cYlxNbB4Z4UpJswpcc4Qxd2oE/ufM0p61IKng==} + engines: {node: '>=18'} + cpu: [x64] + os: [android] + + '@esbuild/darwin-arm64@0.18.20': + resolution: {integrity: sha512-bxRHW5kHU38zS2lPTPOyuyTm+S+eobPUnTNkdJEfAddYgEcll4xkT8DB9d2008DtTbl7uJag2HuE5NZAZgnNEA==} + engines: {node: '>=12'} + cpu: [arm64] + os: [darwin] + '@esbuild/darwin-arm64@0.25.12': resolution: {integrity: sha512-N3zl+lxHCifgIlcMUP5016ESkeQjLj/959RxxNYIthIg+CQHInujFuXeWbWMgnTo4cp5XVHqFPmpyu9J65C1Yg==} engines: {node: '>=18'} @@ -634,6 +795,18 @@ packages: cpu: [arm64] os: [darwin] + '@esbuild/darwin-arm64@0.28.1': + resolution: {integrity: sha512-TZbWkQY7kvTAXbXUT7uVACR5cMHsDiSz9z7ZKAX/RTq/WJEk3QyRr0wZpNhBDX+/0CtdqUIJlOiodQcta6tY3Q==} + engines: {node: '>=18'} + cpu: [arm64] + os: [darwin] + + '@esbuild/darwin-x64@0.18.20': + resolution: {integrity: sha512-pc5gxlMDxzm513qPGbCbDukOdsGtKhfxD1zJKXjCCcU7ju50O7MeAZ8c4krSJcOIJGFR+qx21yMMVYwiQvyTyQ==} + engines: {node: '>=12'} + cpu: [x64] + os: [darwin] + '@esbuild/darwin-x64@0.25.12': resolution: {integrity: sha512-HQ9ka4Kx21qHXwtlTUVbKJOAnmG1ipXhdWTmNXiPzPfWKpXqASVcWdnf2bnL73wgjNrFXAa3yYvBSd9pzfEIpA==} engines: {node: '>=18'} @@ -652,6 +825,18 @@ packages: cpu: [x64] os: [darwin] + '@esbuild/darwin-x64@0.28.1': + resolution: {integrity: sha512-zfdzgK9ACBNZLI/CyHTOx81SyNbM6YXn7rxSgX97VjyiPl9W1i4Ka4fgKECEoFCKGpvBj5qArWIGgQjOwkgskQ==} + engines: {node: '>=18'} + cpu: [x64] + os: [darwin] + + '@esbuild/freebsd-arm64@0.18.20': + resolution: {integrity: sha512-yqDQHy4QHevpMAaxhhIwYPMv1NECwOvIpGCZkECn8w2WFHXjEwrBn3CeNIYsibZ/iZEUemj++M26W3cNR5h+Tw==} + engines: {node: '>=12'} + cpu: [arm64] + os: [freebsd] + '@esbuild/freebsd-arm64@0.25.12': resolution: {integrity: sha512-gA0Bx759+7Jve03K1S0vkOu5Lg/85dou3EseOGUes8flVOGxbhDDh/iZaoek11Y8mtyKPGF3vP8XhnkDEAmzeg==} engines: {node: '>=18'} @@ -670,6 +855,18 @@ packages: cpu: [arm64] os: [freebsd] + '@esbuild/freebsd-arm64@0.28.1': + resolution: {integrity: sha512-wG2EA8ENdEI0qhkSZMjfqrdY+ziCYCPMmtZjjIwOmXFjmyzEHn+UUxk5of+SYsjtfs3VpnlC7QLzSI5hY/rOAw==} + engines: {node: '>=18'} + cpu: [arm64] + os: [freebsd] + + '@esbuild/freebsd-x64@0.18.20': + resolution: {integrity: sha512-tgWRPPuQsd3RmBZwarGVHZQvtzfEBOreNuxEMKFcd5DaDn2PbBxfwLcj4+aenoh7ctXcbXmOQIn8HI6mCSw5MQ==} + engines: {node: '>=12'} + cpu: [x64] + os: [freebsd] + '@esbuild/freebsd-x64@0.25.12': resolution: {integrity: sha512-TGbO26Yw2xsHzxtbVFGEXBFH0FRAP7gtcPE7P5yP7wGy7cXK2oO7RyOhL5NLiqTlBh47XhmIUXuGciXEqYFfBQ==} engines: {node: '>=18'} @@ -688,6 +885,18 @@ packages: cpu: [x64] os: [freebsd] + '@esbuild/freebsd-x64@0.28.1': + resolution: {integrity: sha512-i7dZ9vQgnvSCzi/rYCXNgtF/U+eKZNJBzu3eTQbRgHnM7tNSizLOkRFAl3qzVc/Op/u5YkHHa4pf/3DOYHthLQ==} + engines: {node: '>=18'} + cpu: [x64] + os: [freebsd] + + '@esbuild/linux-arm64@0.18.20': + resolution: {integrity: sha512-2YbscF+UL7SQAVIpnWvYwM+3LskyDmPhe31pE7/aoTMFKKzIc9lLbyGUpmmb8a8AixOL61sQ/mFh3jEjHYFvdA==} + engines: {node: '>=12'} + cpu: [arm64] + os: [linux] + '@esbuild/linux-arm64@0.25.12': resolution: {integrity: sha512-8bwX7a8FghIgrupcxb4aUmYDLp8pX06rGh5HqDT7bB+8Rdells6mHvrFHHW2JAOPZUbnjUpKTLg6ECyzvas2AQ==} engines: {node: '>=18'} @@ -706,6 +915,18 @@ packages: cpu: [arm64] os: [linux] + '@esbuild/linux-arm64@0.28.1': + resolution: {integrity: sha512-yHs+0uc8+nvEAfAfxrWQKK5peSNzBc4PegcMO0EJ2hT71uA7vB8Ihg2e77R2P7SG5uYjPbHlLLmve4LLLRCf0g==} + engines: {node: '>=18'} + cpu: [arm64] + os: [linux] + + '@esbuild/linux-arm@0.18.20': + resolution: {integrity: sha512-/5bHkMWnq1EgKr1V+Ybz3s1hWXok7mDFUMQ4cG10AfW3wL02PSZi5kFpYKrptDsgb2WAJIvRcDm+qIvXf/apvg==} + engines: {node: '>=12'} + cpu: [arm] + os: [linux] + '@esbuild/linux-arm@0.25.12': resolution: {integrity: sha512-lPDGyC1JPDou8kGcywY0YILzWlhhnRjdof3UlcoqYmS9El818LLfJJc3PXXgZHrHCAKs/Z2SeZtDJr5MrkxtOw==} engines: {node: '>=18'} @@ -724,6 +945,18 @@ packages: cpu: [arm] os: [linux] + '@esbuild/linux-arm@0.28.1': + resolution: {integrity: sha512-qVXBOHQS+d5Y722GwJzJUtOLlX7km3CraOaGormF1pDtPd2C/l1SHRPgjLunLGe51Sh5YYWKMFDyV4SxgMQYTQ==} + engines: {node: '>=18'} + cpu: [arm] + os: [linux] + + '@esbuild/linux-ia32@0.18.20': + resolution: {integrity: sha512-P4etWwq6IsReT0E1KHU40bOnzMHoH73aXp96Fs8TIT6z9Hu8G6+0SHSw9i2isWrD2nbx2qo5yUqACgdfVGx7TA==} + engines: {node: '>=12'} + cpu: [ia32] + os: [linux] + '@esbuild/linux-ia32@0.25.12': resolution: {integrity: sha512-0y9KrdVnbMM2/vG8KfU0byhUN+EFCny9+8g202gYqSSVMonbsCfLjUO+rCci7pM0WBEtz+oK/PIwHkzxkyharA==} engines: {node: '>=18'} @@ -742,6 +975,18 @@ packages: cpu: [ia32] os: [linux] + '@esbuild/linux-ia32@0.28.1': + resolution: {integrity: sha512-d1z4ZuP0ajrfz/FhGT4vv278rX8KnPPJx8i5+AtK7TYbx9Le9F1hyzurZpkEyjkGa9dUGhQow4C1NmeGvqxN2w==} + engines: {node: '>=18'} + cpu: [ia32] + os: [linux] + + '@esbuild/linux-loong64@0.18.20': + resolution: {integrity: sha512-nXW8nqBTrOpDLPgPY9uV+/1DjxoQ7DoB2N8eocyq8I9XuqJ7BiAMDMf9n1xZM9TgW0J8zrquIb/A7s3BJv7rjg==} + engines: {node: '>=12'} + cpu: [loong64] + os: [linux] + '@esbuild/linux-loong64@0.25.12': resolution: {integrity: sha512-h///Lr5a9rib/v1GGqXVGzjL4TMvVTv+s1DPoxQdz7l/AYv6LDSxdIwzxkrPW438oUXiDtwM10o9PmwS/6Z0Ng==} engines: {node: '>=18'} @@ -760,6 +1005,18 @@ packages: cpu: [loong64] os: [linux] + '@esbuild/linux-loong64@0.28.1': + resolution: {integrity: sha512-M5sRjUVZrkm1OAPR3dlOYzNmN+loZKGVi1VUQGrwuqLcbR6qeAz+famMhjASeH3YVKvZz+zT1jlh/keC3Rj/lg==} + engines: {node: '>=18'} + cpu: [loong64] + os: [linux] + + '@esbuild/linux-mips64el@0.18.20': + resolution: {integrity: sha512-d5NeaXZcHp8PzYy5VnXV3VSd2D328Zb+9dEq5HE6bw6+N86JVPExrA6O68OPwobntbNJ0pzCpUFZTo3w0GyetQ==} + engines: {node: '>=12'} + cpu: [mips64el] + os: [linux] + '@esbuild/linux-mips64el@0.25.12': resolution: {integrity: sha512-iyRrM1Pzy9GFMDLsXn1iHUm18nhKnNMWscjmp4+hpafcZjrr2WbT//d20xaGljXDBYHqRcl8HnxbX6uaA/eGVw==} engines: {node: '>=18'} @@ -778,6 +1035,18 @@ packages: cpu: [mips64el] os: [linux] + '@esbuild/linux-mips64el@0.28.1': + resolution: {integrity: sha512-mRObBZeHh2OxcBFPWE/FjylkRgZdYuiTR3vaTozquCGOH14iP9oN4x4Ge81CoIDYQrXmIxpFumJBu5MtZpnQJQ==} + engines: {node: '>=18'} + cpu: [mips64el] + os: [linux] + + '@esbuild/linux-ppc64@0.18.20': + resolution: {integrity: sha512-WHPyeScRNcmANnLQkq6AfyXRFr5D6N2sKgkFo2FqguP44Nw2eyDlbTdZwd9GYk98DZG9QItIiTlFLHJHjxP3FA==} + engines: {node: '>=12'} + cpu: [ppc64] + os: [linux] + '@esbuild/linux-ppc64@0.25.12': resolution: {integrity: sha512-9meM/lRXxMi5PSUqEXRCtVjEZBGwB7P/D4yT8UG/mwIdze2aV4Vo6U5gD3+RsoHXKkHCfSxZKzmDssVlRj1QQA==} engines: {node: '>=18'} @@ -796,6 +1065,18 @@ packages: cpu: [ppc64] os: [linux] + '@esbuild/linux-ppc64@0.28.1': + resolution: {integrity: sha512-slScBsMAb3GFDcdrCgLwZtPYRoH2H/youv10QiZyRjmsP48fznoveWytSgCI/R0ZcUgpc0ZhIUEx6LHts8yrfQ==} + engines: {node: '>=18'} + cpu: [ppc64] + os: [linux] + + '@esbuild/linux-riscv64@0.18.20': + resolution: {integrity: sha512-WSxo6h5ecI5XH34KC7w5veNnKkju3zBRLEQNY7mv5mtBmrP/MjNBCAlsM2u5hDBlS3NGcTQpoBvRzqBcRtpq1A==} + engines: {node: '>=12'} + cpu: [riscv64] + os: [linux] + '@esbuild/linux-riscv64@0.25.12': resolution: {integrity: sha512-Zr7KR4hgKUpWAwb1f3o5ygT04MzqVrGEGXGLnj15YQDJErYu/BGg+wmFlIDOdJp0PmB0lLvxFIOXZgFRrdjR0w==} engines: {node: '>=18'} @@ -814,6 +1095,18 @@ packages: cpu: [riscv64] os: [linux] + '@esbuild/linux-riscv64@0.28.1': + resolution: {integrity: sha512-kw0owk1o0GFETUJyW0jc0G4Yzs0BHZn0JDZ8JRT088vjJYX777BAs1fDGxAC+q831qOs2DTC96mNsG2opdfyyQ==} + engines: {node: '>=18'} + cpu: [riscv64] + os: [linux] + + '@esbuild/linux-s390x@0.18.20': + resolution: {integrity: sha512-+8231GMs3mAEth6Ja1iK0a1sQ3ohfcpzpRLH8uuc5/KVDFneH6jtAJLFGafpzpMRO6DzJ6AvXKze9LfFMrIHVQ==} + engines: {node: '>=12'} + cpu: [s390x] + os: [linux] + '@esbuild/linux-s390x@0.25.12': resolution: {integrity: sha512-MsKncOcgTNvdtiISc/jZs/Zf8d0cl/t3gYWX8J9ubBnVOwlk65UIEEvgBORTiljloIWnBzLs4qhzPkJcitIzIg==} engines: {node: '>=18'} @@ -832,6 +1125,18 @@ packages: cpu: [s390x] os: [linux] + '@esbuild/linux-s390x@0.28.1': + resolution: {integrity: sha512-/lAIjX8aYFRByhh6L5rYtPEDRqa9de/4V/juOXcta5frjvzXO4/sqEtyytse0g3zZFuWu5cDN0MkLz2qRDD2Ag==} + engines: {node: '>=18'} + cpu: [s390x] + os: [linux] + + '@esbuild/linux-x64@0.18.20': + resolution: {integrity: sha512-UYqiqemphJcNsFEskc73jQ7B9jgwjWrSayxawS6UVFZGWrAAtkzjxSqnoclCXxWtfwLdzU+vTpcNYhpn43uP1w==} + engines: {node: '>=12'} + cpu: [x64] + os: [linux] + '@esbuild/linux-x64@0.25.12': resolution: {integrity: sha512-uqZMTLr/zR/ed4jIGnwSLkaHmPjOjJvnm6TVVitAa08SLS9Z0VM8wIRx7gWbJB5/J54YuIMInDquWyYvQLZkgw==} engines: {node: '>=18'} @@ -850,6 +1155,12 @@ packages: cpu: [x64] os: [linux] + '@esbuild/linux-x64@0.28.1': + resolution: {integrity: sha512-u/anNYF2mmVOEDwLtnQ1wOr3EZ9sTNGLWrsYGYwHWzGA3Si84IOkHXlbWTD1NB+9/1lcnweYKO54uhxZydNzfA==} + engines: {node: '>=18'} + cpu: [x64] + os: [linux] + '@esbuild/netbsd-arm64@0.25.12': resolution: {integrity: sha512-xXwcTq4GhRM7J9A8Gv5boanHhRa/Q9KLVmcyXHCTaM4wKfIpWkdXiMog/KsnxzJ0A1+nD+zoecuzqPmCRyBGjg==} engines: {node: '>=18'} @@ -868,6 +1179,18 @@ packages: cpu: [arm64] os: [netbsd] + '@esbuild/netbsd-arm64@0.28.1': + resolution: {integrity: sha512-oks0DYbLwWMmaakTsCb+zL4E+aHRVLom9IJZOAthMQEPiQmydXHkziYEsGYRx0uNV/IjEKGAV941JzH02pflqw==} + engines: {node: '>=18'} + cpu: [arm64] + os: [netbsd] + + '@esbuild/netbsd-x64@0.18.20': + resolution: {integrity: sha512-iO1c++VP6xUBUmltHZoMtCUdPlnPGdBom6IrO4gyKPFFVBKioIImVooR5I83nTew5UOYrk3gIJhbZh8X44y06A==} + engines: {node: '>=12'} + cpu: [x64] + os: [netbsd] + '@esbuild/netbsd-x64@0.25.12': resolution: {integrity: sha512-Ld5pTlzPy3YwGec4OuHh1aCVCRvOXdH8DgRjfDy/oumVovmuSzWfnSJg+VtakB9Cm0gxNO9BzWkj6mtO1FMXkQ==} engines: {node: '>=18'} @@ -886,6 +1209,12 @@ packages: cpu: [x64] os: [netbsd] + '@esbuild/netbsd-x64@0.28.1': + resolution: {integrity: sha512-aeL6lAnN89Hz43Mlh1G8ARasbuoYvSITDEx0tHh5b7jJnHcssqgjy9Yx430GDpmCa6OyrKoS0aNRjKundRizGg==} + engines: {node: '>=18'} + cpu: [x64] + os: [netbsd] + '@esbuild/openbsd-arm64@0.25.12': resolution: {integrity: sha512-fF96T6KsBo/pkQI950FARU9apGNTSlZGsv1jZBAlcLL1MLjLNIWPBkj5NlSz8aAzYKg+eNqknrUJ24QBybeR5A==} engines: {node: '>=18'} @@ -904,6 +1233,18 @@ packages: cpu: [arm64] os: [openbsd] + '@esbuild/openbsd-arm64@0.28.1': + resolution: {integrity: sha512-MEFJe5C3R8pwXdZ5Y21oo6m7ePiS0d9pWucn99O/wvyJZChoIQKrQDxKrGeW8F5+T0okTHesAmDeiHDTIq0V/Q==} + engines: {node: '>=18'} + cpu: [arm64] + os: [openbsd] + + '@esbuild/openbsd-x64@0.18.20': + resolution: {integrity: sha512-e5e4YSsuQfX4cxcygw/UCPIEP6wbIL+se3sxPdCiMbFLBWu0eiZOJ7WoD+ptCLrmjZBK1Wk7I6D/I3NglUGOxg==} + engines: {node: '>=12'} + cpu: [x64] + os: [openbsd] + '@esbuild/openbsd-x64@0.25.12': resolution: {integrity: sha512-MZyXUkZHjQxUvzK7rN8DJ3SRmrVrke8ZyRusHlP+kuwqTcfWLyqMOE3sScPPyeIXN/mDJIfGXvcMqCgYKekoQw==} engines: {node: '>=18'} @@ -922,6 +1263,12 @@ packages: cpu: [x64] os: [openbsd] + '@esbuild/openbsd-x64@0.28.1': + resolution: {integrity: sha512-i/ZLIOafE0Z8cI/XANJAixoJL/uRAoS2xOA3rb0xN+KK0K177cMAsQYkzHtBrtMXAKuAc7HGgcWiZ/sRC1Nxgw==} + engines: {node: '>=18'} + cpu: [x64] + os: [openbsd] + '@esbuild/openharmony-arm64@0.25.12': resolution: {integrity: sha512-rm0YWsqUSRrjncSXGA7Zv78Nbnw4XL6/dzr20cyrQf7ZmRcsovpcRBdhD43Nuk3y7XIoW2OxMVvwuRvk9XdASg==} engines: {node: '>=18'} @@ -940,6 +1287,18 @@ packages: cpu: [arm64] os: [openharmony] + '@esbuild/openharmony-arm64@0.28.1': + resolution: {integrity: sha512-ge+Z7EXFNt2BO1oAMsVpiQ8EwndV9i1xXerAeTIK7AtPs3bKFXQM7nlRxDSIUIMeueR1CNXxqztLzdNeReKBJg==} + engines: {node: '>=18'} + cpu: [arm64] + os: [openharmony] + + '@esbuild/sunos-x64@0.18.20': + resolution: {integrity: sha512-kDbFRFp0YpTQVVrqUd5FTYmWo45zGaXe0X8E1G/LKFC0v8x0vWrhOWSLITcCn63lmZIxfOMXtCfti/RxN/0wnQ==} + engines: {node: '>=12'} + cpu: [x64] + os: [sunos] + '@esbuild/sunos-x64@0.25.12': resolution: {integrity: sha512-3wGSCDyuTHQUzt0nV7bocDy72r2lI33QL3gkDNGkod22EsYl04sMf0qLb8luNKTOmgF/eDEDP5BFNwoBKH441w==} engines: {node: '>=18'} @@ -958,6 +1317,18 @@ packages: cpu: [x64] os: [sunos] + '@esbuild/sunos-x64@0.28.1': + resolution: {integrity: sha512-BEjgtECkL3vY+SaSQ6nzVfiALUeFxpawyp8Jmf5PtYhf1Ug40N1h/hxlhts+f1FvSvarEigdxS3BlSMI2PJLcQ==} + engines: {node: '>=18'} + cpu: [x64] + os: [sunos] + + '@esbuild/win32-arm64@0.18.20': + resolution: {integrity: sha512-ddYFR6ItYgoaq4v4JmQQaAI5s7npztfV4Ag6NrhiaW0RrnOXqBkgwZLofVTlq1daVTQNhtI5oieTvkRPfZrePg==} + engines: {node: '>=12'} + cpu: [arm64] + os: [win32] + '@esbuild/win32-arm64@0.25.12': resolution: {integrity: sha512-rMmLrur64A7+DKlnSuwqUdRKyd3UE7oPJZmnljqEptesKM8wx9J8gx5u0+9Pq0fQQW8vqeKebwNXdfOyP+8Bsg==} engines: {node: '>=18'} @@ -976,6 +1347,18 @@ packages: cpu: [arm64] os: [win32] + '@esbuild/win32-arm64@0.28.1': + resolution: {integrity: sha512-lCv9eK/H6ZJWbE7bh2nw54CZ9M2nupBxJcTsdk/QQnWkdSjKGuxmmH8/GWrlT1eMmZfn4dGcCjRte397WqfQXA==} + engines: {node: '>=18'} + cpu: [arm64] + os: [win32] + + '@esbuild/win32-ia32@0.18.20': + resolution: {integrity: sha512-Wv7QBi3ID/rROT08SABTS7eV4hX26sVduqDOTe1MvGMjNd3EjOz4b7zeexIR62GTIEKrfJXKL9LFxTYgkyeu7g==} + engines: {node: '>=12'} + cpu: [ia32] + os: [win32] + '@esbuild/win32-ia32@0.25.12': resolution: {integrity: sha512-HkqnmmBoCbCwxUKKNPBixiWDGCpQGVsrQfJoVGYLPT41XWF8lHuE5N6WhVia2n4o5QK5M4tYr21827fNhi4byQ==} engines: {node: '>=18'} @@ -994,6 +1377,18 @@ packages: cpu: [ia32] os: [win32] + '@esbuild/win32-ia32@0.28.1': + resolution: {integrity: sha512-zvb/mB2bSCoJOpoCBgYKKpX6YM6mJBlBUVUtVj41DlZJVEB6/0CKlRYxP5wWl1C1ILiCoAU5wZZ4q1P3qeS6Eg==} + engines: {node: '>=18'} + cpu: [ia32] + os: [win32] + + '@esbuild/win32-x64@0.18.20': + resolution: {integrity: sha512-kTdfRcSiDfQca/y9QIkng02avJ+NCaQvrMejlsB3RRv5sE9rRoeBPISaZpKxHELzRxZyLvNts1P27W3wV+8geQ==} + engines: {node: '>=12'} + cpu: [x64] + os: [win32] + '@esbuild/win32-x64@0.25.12': resolution: {integrity: sha512-alJC0uCZpTFrSL0CCDjcgleBXPnCrEAhTBILpeAp7M/OFgoqtAetfBzX0xM00MUsVVPpVjlPuMbREqnZCXaTnA==} engines: {node: '>=18'} @@ -1012,6 +1407,12 @@ packages: cpu: [x64] os: [win32] + '@esbuild/win32-x64@0.28.1': + resolution: {integrity: sha512-bm4Mowrv+GXMlpWX++EcXw/iLyd1o3+bJkC2DkWXYVvgZCqD/bSj9ctZeAMC3cIxgjRVR2Dufaiu4YPxr5gW1A==} + engines: {node: '>=18'} + cpu: [x64] + os: [win32] + '@exodus/bytes@1.15.1': resolution: {integrity: sha512-S6mL0yNB/Abt9Ei4tq8gDhcczc4S3+vQ4ra7vxnAf+YHC02srtqxKKZghx2Dq6p0e66THKwR6r8N6P95wEty7Q==} engines: {node: ^20.19.0 || ^22.12.0 || >=24.0.0} @@ -1021,50 +1422,212 @@ packages: '@noble/hashes': optional: true - '@floating-ui/core@1.7.5': - resolution: {integrity: sha512-1Ih4WTWyw0+lKyFMcBHGbb5U5FtuHJuujoyyr5zTaWS5EYMeT6Jb2AuDeftsCsEuchO+mM2ij5+q9crhydzLhQ==} + '@floating-ui/core@1.7.5': + resolution: {integrity: sha512-1Ih4WTWyw0+lKyFMcBHGbb5U5FtuHJuujoyyr5zTaWS5EYMeT6Jb2AuDeftsCsEuchO+mM2ij5+q9crhydzLhQ==} + + '@floating-ui/dom@1.7.6': + resolution: {integrity: sha512-9gZSAI5XM36880PPMm//9dfiEngYoC6Am2izES1FF406YFsjvyBMmeJ2g4SAju3xWwtuynNRFL2s9hgxpLI5SQ==} + + '@floating-ui/react-dom@2.1.8': + resolution: {integrity: sha512-cC52bHwM/n/CxS87FH0yWdngEZrjdtLW/qVruo68qg+prK7ZQ4YGdut2GyDVpoGeAYe/h899rVeOVm6Oi40k2A==} + peerDependencies: + react: '>=16.8.0' + react-dom: '>=16.8.0' + + '@floating-ui/react@0.27.12': + resolution: {integrity: sha512-kKlWNrpIQxF1B/a2MZvE0/uyKby4960yjO91W7nVyNKmmfNi62xU9HCjL1M1eWzx/LFj/VPSwJVbwQk9Pq/68A==} + peerDependencies: + react: '>=17.0.0' + react-dom: '>=17.0.0' + + '@floating-ui/utils@0.2.11': + resolution: {integrity: sha512-RiB/yIh78pcIxl6lLMG0CgBXAZ2Y0eVHqMPYugu+9U0AeT6YBeiJpf7lbdJNIugFP5SIjwNRgo4DhR1Qxi26Gg==} + + '@fontsource-variable/bricolage-grotesque@5.3.0': + resolution: {integrity: sha512-TLi9Q4hJjS2UvoTMRSS2nHu6c4R56lAw60NR9QYtVRCHn0XtsFpiEhNffZ8Glsoxu6wEEwLKBP8lb94J52PNBA==} + + '@fontsource-variable/inter@5.3.0': + resolution: {integrity: sha512-OupL48va4JNofb97w6NYeF9S7W/kHNKM0Er8Dem5nqi4jeOLrVJDoE8tZEpnMJmtkvNbB1EIPPwHcdkF6b1oUA==} + + '@formkit/auto-animate@0.8.4': + resolution: {integrity: sha512-DHHC01EJ1p70Q0z/ZFRBIY8NDnmfKccQoyoM84Tgb6omLMat6jivCdf272Y8k3nf4Lzdin/Y4R9q8uFtU0GbnA==} + + '@google/genai@1.52.0': + resolution: {integrity: sha512-gwSvbpiN/17O9TbsqSsE/OzZcpv5Fo4RQjdngGgogtuB9RsyJ8ZHhX5KjHj1bp5N9snN2eK8LDGXSaWW2hof8Q==} + engines: {node: '>=20.0.0'} + peerDependencies: + '@modelcontextprotocol/sdk': ^1.25.2 + peerDependenciesMeta: + '@modelcontextprotocol/sdk': + optional: true + + '@hono/node-server@1.19.15': + resolution: {integrity: sha512-Za2ai6TLdKjUvnur+eenO6nuYYipVAEhyCAdaV8IRvmU9kK8crOZUSYvIXn72E4f8fJqyAbpcJuTsYYmZp9Deg==} + engines: {node: '>=18.14.1'} + peerDependencies: + hono: ^4 + + '@img/colour@1.1.0': + resolution: {integrity: sha512-Td76q7j57o/tLVdgS746cYARfSyxk8iEfRxewL9h4OMzYhbW4TAcppl0mT4eyqXddh6L/jwoM75mo7ixa/pCeQ==} + engines: {node: '>=18'} + + '@img/sharp-darwin-arm64@0.35.2': + resolution: {integrity: sha512-eEieHsMksAW4IiO5NzauESRl2D2qz3J/kwUxUrSfV06A93eEaRfMpHXyUb1mAqrR7i8U9A0GRqE9pjn6u1Jjpg==} + engines: {node: '>=20.9.0'} + cpu: [arm64] + os: [darwin] + + '@img/sharp-darwin-x64@0.35.2': + resolution: {integrity: sha512-BaktuGPCeHJMARpodR8jK4uKiZrPAy9WrfQW0sdI37clracq8Bp01AYS3SZgi5FS/y5twa9t4+LIuuxQjqRrWw==} + engines: {node: '>=20.9.0'} + cpu: [x64] + os: [darwin] + + '@img/sharp-freebsd-wasm32@0.35.2': + resolution: {integrity: sha512-YoAxdnd8hPUkvLHd3bWY+YA8nw3xM/RyRopYucNsWHVSan8NLVM3X2volsfoRDcXdUJPg6tXahSd7HXPK7lRnw==} + engines: {node: '>=20.9.0'} + os: [freebsd] + + '@img/sharp-libvips-darwin-arm64@1.3.1': + resolution: {integrity: sha512-4V/M3roRMTYjiwZY9IOVQOE8OyeCxFAkYmyZDrZl51uOKjibm3oeEJ4WAmLxutAfzFbC9jqUiPs2gbnGflH+7g==} + cpu: [arm64] + os: [darwin] + + '@img/sharp-libvips-darwin-x64@1.3.1': + resolution: {integrity: sha512-c0/DxItpJv2+dGhgycJBBgotdqruGYDvA79drdh0MD1dFpy7JzJ/PlXwi1H4rFf0eTy8tgbI91aHDnZIceY3jQ==} + cpu: [x64] + os: [darwin] + + '@img/sharp-libvips-linux-arm64@1.3.1': + resolution: {integrity: sha512-JznefmcK9j1JKPz8AkQDh89kjojubyfOasWBPKfzMIhPwsgDy9evpE/naJTXXXmghS1iFwR8u/kTwh/I2/+GCw==} + cpu: [arm64] + os: [linux] + libc: [glibc] + + '@img/sharp-libvips-linux-arm@1.3.1': + resolution: {integrity: sha512-aGGy9aWzXgHBG7HNyQPWorZthlp7+x6fDRoPAQbGO3ThcttuTyKIx3NuSHb6zb4gBNq6/yNn9f1cy9nFKS/Vmg==} + cpu: [arm] + os: [linux] + libc: [glibc] + + '@img/sharp-libvips-linux-ppc64@1.3.1': + resolution: {integrity: sha512-1EkwGNCZk6iWNCMWqrvdJ+r1j0PT1zIz60CNPhYnJlK/zyeWqlsPZIe+ocBVqPF8k/Ssee/NCk+tE9Ryrko6ng==} + cpu: [ppc64] + os: [linux] + libc: [glibc] + + '@img/sharp-libvips-linux-riscv64@1.3.1': + resolution: {integrity: sha512-Ilays+w2bXdnxzxtQdmXR62u8o8GYa3eL4+Gr+1KiE4xperMZUslRaVPJwwPkzlHEjGfXAfRVAa/7CYCtSqsBw==} + cpu: [riscv64] + os: [linux] + libc: [glibc] + + '@img/sharp-libvips-linux-s390x@1.3.1': + resolution: {integrity: sha512-VfBwVHQTbRoj4XlpA/KLZ7ltgMpz+4WSejFzQ+GnoImjo1PtEJ59QB2qR1xQEeRPYIkNrPIm2L4cICMvz4C2ew==} + cpu: [s390x] + os: [linux] + libc: [glibc] + + '@img/sharp-libvips-linux-x64@1.3.1': + resolution: {integrity: sha512-+c8ukgwU62DS54nCAjw7keOfHUkmr0B5QHEdcOqRnodF/MNXJbVI8Eopoj4B/0H8Asr65I+A4Amrn7a85/md6A==} + cpu: [x64] + os: [linux] + libc: [glibc] + + '@img/sharp-libvips-linuxmusl-arm64@1.3.1': + resolution: {integrity: sha512-qlKb/pwbkAi1WMsJrYHk7CuDrd12s27U2QnRhFYUoJNrRCmkosMTttuRFat/DDB3IlDm5qE1TJgZ4JDnHX8Ldw==} + cpu: [arm64] + os: [linux] + libc: [musl] + + '@img/sharp-libvips-linuxmusl-x64@1.3.1': + resolution: {integrity: sha512-yO21HwoUVLN8Qa+/SBjQLMYwBWAVJjeGPNe+hc0OUeMeifEtJqu5a1c4HayE1nNpDih9y3/KkoltfkDodmKAlg==} + cpu: [x64] + os: [linux] + libc: [musl] + + '@img/sharp-linux-arm64@0.35.2': + resolution: {integrity: sha512-af12Pnd0ZGu2HfP8NayB0kk6eC/lrfbQE6HlR4jD+34wdJ1Vw9TF6TMn6ZvffT+WgqVsl0hRbmNvz2u/23VmwA==} + engines: {node: '>=20.9.0'} + cpu: [arm64] + os: [linux] + libc: [glibc] + + '@img/sharp-linux-arm@0.35.2': + resolution: {integrity: sha512-SE4kzF2mepn6z+6E7L6lsV8FzuLL6IPQdyX8ZiwROAG/G8td+hP/m7FsFPwidtrF19gvajuC9l6TxAVcsA4S7A==} + engines: {node: '>=20.9.0'} + cpu: [arm] + os: [linux] + libc: [glibc] + + '@img/sharp-linux-ppc64@0.35.2': + resolution: {integrity: sha512-hYSBm7zcNtDCozCxQHYZJiu63b/bXsgRZuOxCIBZsStMM9Vap47iFHdbX4kCvQsblPB/k+clhELpdQJHQLSHvg==} + engines: {node: '>=20.9.0'} + cpu: [ppc64] + os: [linux] + libc: [glibc] - '@floating-ui/dom@1.7.6': - resolution: {integrity: sha512-9gZSAI5XM36880PPMm//9dfiEngYoC6Am2izES1FF406YFsjvyBMmeJ2g4SAju3xWwtuynNRFL2s9hgxpLI5SQ==} + '@img/sharp-linux-riscv64@0.35.2': + resolution: {integrity: sha512-qQt0Kc13+Hoan/Awq/qMSQw3L+RI1NCRPgD5cUJ/1WSSmIoysLOc72jlRM3E0OHN9Yr313jgeQ2T+zW+F03QFA==} + engines: {node: '>=20.9.0'} + cpu: [riscv64] + os: [linux] + libc: [glibc] - '@floating-ui/react-dom@2.1.8': - resolution: {integrity: sha512-cC52bHwM/n/CxS87FH0yWdngEZrjdtLW/qVruo68qg+prK7ZQ4YGdut2GyDVpoGeAYe/h899rVeOVm6Oi40k2A==} - peerDependencies: - react: '>=16.8.0' - react-dom: '>=16.8.0' + '@img/sharp-linux-s390x@0.35.2': + resolution: {integrity: sha512-E4fLLfRPzDLlEeDaTzI98OFLcv++WL5ChLLMwPoVd0CIoZQqupBSNbOisPL5am9XsbQ9T84+iiMpUvbFtkunbA==} + engines: {node: '>=20.9.0'} + cpu: [s390x] + os: [linux] + libc: [glibc] - '@floating-ui/react@0.27.12': - resolution: {integrity: sha512-kKlWNrpIQxF1B/a2MZvE0/uyKby4960yjO91W7nVyNKmmfNi62xU9HCjL1M1eWzx/LFj/VPSwJVbwQk9Pq/68A==} - peerDependencies: - react: '>=17.0.0' - react-dom: '>=17.0.0' + '@img/sharp-linux-x64@0.35.2': + resolution: {integrity: sha512-gi0zFJJRLswfCZmHtJdikXPOc5u7qamSOS3NHedLqLd4W8Q0NqjdBr6TTRIgsfFjqfTsHFgdfvJ9LwqSgcHiAA==} + engines: {node: '>=20.9.0'} + cpu: [x64] + os: [linux] + libc: [glibc] - '@floating-ui/utils@0.2.11': - resolution: {integrity: sha512-RiB/yIh78pcIxl6lLMG0CgBXAZ2Y0eVHqMPYugu+9U0AeT6YBeiJpf7lbdJNIugFP5SIjwNRgo4DhR1Qxi26Gg==} + '@img/sharp-linuxmusl-arm64@0.35.2': + resolution: {integrity: sha512-siWbOW1u6HFnFLrp0waKyW7VEf7jYvcDWdrXEFa8AkdAQgEvuu5Fz8/Y70w9EeqAdwDtfU012BhEHHaDqvQNzg==} + engines: {node: '>=20.9.0'} + cpu: [arm64] + os: [linux] + libc: [musl] - '@fontsource-variable/bricolage-grotesque@5.3.0': - resolution: {integrity: sha512-TLi9Q4hJjS2UvoTMRSS2nHu6c4R56lAw60NR9QYtVRCHn0XtsFpiEhNffZ8Glsoxu6wEEwLKBP8lb94J52PNBA==} + '@img/sharp-linuxmusl-x64@0.35.2': + resolution: {integrity: sha512-YBqMMcjDi4QGYiSn4vNOYBhmlC4z5AXqkOUUqI2e0AFA4urNv4ESgOgwNl3K+4etQhha0twXlzeF20bbULm9Yg==} + engines: {node: '>=20.9.0'} + cpu: [x64] + os: [linux] + libc: [musl] - '@fontsource-variable/inter@5.3.0': - resolution: {integrity: sha512-OupL48va4JNofb97w6NYeF9S7W/kHNKM0Er8Dem5nqi4jeOLrVJDoE8tZEpnMJmtkvNbB1EIPPwHcdkF6b1oUA==} + '@img/sharp-wasm32@0.35.2': + resolution: {integrity: sha512-Mrv4JQNYVQ94xH+jzZ9r+gowleN8mv2FTgKT+PI6bx5C0G8TdNYndu161pg2i7uoBwxy2ImPMHrJOM2LZef7Bw==} + engines: {node: '>=20.9.0'} - '@formkit/auto-animate@0.8.4': - resolution: {integrity: sha512-DHHC01EJ1p70Q0z/ZFRBIY8NDnmfKccQoyoM84Tgb6omLMat6jivCdf272Y8k3nf4Lzdin/Y4R9q8uFtU0GbnA==} + '@img/sharp-webcontainers-wasm32@0.35.2': + resolution: {integrity: sha512-QNV27pxs9wpApEiCfvHM1RDoP1w1+2KrUWWDPEhEwg+latvOrfuhWrHWZKwdSFwU6jh3myjw/yOCRsUIuOft3g==} + engines: {node: '>=20.9.0'} + cpu: [wasm32] - '@google/genai@1.52.0': - resolution: {integrity: sha512-gwSvbpiN/17O9TbsqSsE/OzZcpv5Fo4RQjdngGgogtuB9RsyJ8ZHhX5KjHj1bp5N9snN2eK8LDGXSaWW2hof8Q==} - engines: {node: '>=20.0.0'} - peerDependencies: - '@modelcontextprotocol/sdk': ^1.25.2 - peerDependenciesMeta: - '@modelcontextprotocol/sdk': - optional: true + '@img/sharp-win32-arm64@0.35.2': + resolution: {integrity: sha512-BiVRYc/t6/Vl3e1hBx0hugG4oN9Pydf4fgMSpxTQJmwGUg/YoXTWHiFeRymHfCZzifxu4F4rpk/I67D0LQ20wQ==} + engines: {node: '>=20.9.0'} + cpu: [arm64] + os: [win32] - '@hono/node-server@1.19.15': - resolution: {integrity: sha512-Za2ai6TLdKjUvnur+eenO6nuYYipVAEhyCAdaV8IRvmU9kK8crOZUSYvIXn72E4f8fJqyAbpcJuTsYYmZp9Deg==} - engines: {node: '>=18.14.1'} - peerDependencies: - hono: ^4 + '@img/sharp-win32-ia32@0.35.2': + resolution: {integrity: sha512-YYEhx9PImCC7T0tI8JDMi4DB9LwLCXCU5OWNYEXAxh5Q1ShKkyC6byxzoBJ3gEFDnH2lQckWuDe70G7mB2XJog==} + engines: {node: ^20.9.0} + cpu: [ia32] + os: [win32] + + '@img/sharp-win32-x64@0.35.2': + resolution: {integrity: sha512-imoOyBcoM/iiUr4J6VPpCNjPnjvP/Gks95898yB8YqoGGYmHYbOyCuNv9FMhFgtaiHFGbHW8bxKqRV6VjtXThQ==} + engines: {node: '>=20.9.0'} + cpu: [x64] + os: [win32] '@ioredis/commands@1.10.0': resolution: {integrity: sha512-UmeW7z4LfctwoQ5wkhVzgq8tXkreED2xZGpX+Bg+zA+WJFZCT6c062AfCK/Dfk81xZnnwdhJCUMkitihRaoC2Q==} @@ -1108,6 +1671,9 @@ packages: '@jridgewell/trace-mapping@0.3.31': resolution: {integrity: sha512-zzNR+SdQSDJzc8joaeP8QQoCQr8NuYx2dIIytl1QeBEZHJ9uW6hebsrYgbz8hJwUQao3TWCMtmfV8Nu1twOLAw==} + '@jridgewell/trace-mapping@0.3.9': + resolution: {integrity: sha512-3Belt6tdc8bPgAtbcmdtNJlirVoTmEb5e2gC94PnkwEW9jI6CAHUeoG85tjWP5WquqfavoMtMwiG4P926ZKKuQ==} + '@mapbox/node-pre-gyp@2.0.3': resolution: {integrity: sha512-uwPAhccfFJlsfCxMYTwOdVfOz3xqyj8xYL3zJj8f0pb30tLohnnFPhLuqp4/qoEz8sNxe4SESZedcBojRefIzg==} engines: {node: '>=18'} @@ -1159,6 +1725,9 @@ packages: resolution: {integrity: sha512-hAX0pT/73190NLqBPPWSdBVGtbY6VOhWYK3qqHqtXQ1gK7kS2yz4+ivsN07hpJ6I3aeMtKP6J6npsEKOAzuTLA==} engines: {node: '>=20.0'} + '@oxc-project/types@0.143.0': + resolution: {integrity: sha512-u6JZdLBTLotrNC9Vd6vPssINdzcCzleKAH6EJKImQb7GtYvX5keN2dxkoK44stCc4tffE6QQRtZTXVSzsLUlWA==} + '@parcel/watcher-android-arm64@2.5.6': resolution: {integrity: sha512-YQxSS34tPF/6ZG7r/Ih9xy+kP/WwediEUsqmtf0cuCV5TPPKw/PQHRhueUo6JdeFJaqV3pyjm0GdYjZotbRt/A==} engines: {node: '>= 10.0.0'} @@ -1260,6 +1829,9 @@ packages: '@poppinss/colors@4.1.6': resolution: {integrity: sha512-H9xkIdFswbS8n1d6vmRd8+c10t2Qe+rZITbbDHHkQixH5+2x1FDGmi/0K+WgWiqQFKPSlIYB7jlH6Kpfn6Fleg==} + '@poppinss/dumper@0.6.5': + resolution: {integrity: sha512-NBdYIb90J7LfOI32dOewKI1r7wnkiH6m920puQ3qHUeZkxNkQiFnXVWoE6YtFSv6QOiPPf7ys6i+HWWecDz7sw==} + '@poppinss/dumper@0.7.0': resolution: {integrity: sha512-0UTYalzk2t6S4rA2uHOz5bSSW2CHdv4vggJI6Alg90yvl0UgXs6XSXpH96OH+bRkX4J/06djv29pqXJ0lq5Kag==} @@ -2047,9 +2619,102 @@ packages: '@types/react': optional: true + '@rolldown/binding-android-arm64@1.2.3': + resolution: {integrity: sha512-zrJtHDcaZJ1Fp7xf4hNl+7seH9Cn/N5TwLYkhgXREtBwAd/jaqW3uqeHxpDugJLVICWg4eW44kOQEGJ1r6jCGw==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [arm64] + os: [android] + + '@rolldown/binding-darwin-arm64@1.2.3': + resolution: {integrity: sha512-ieIiibVCp0tX7TLu2cafoNPv8wJyYi01ekXpbf8q2j7F4rGAhhXb/eQh7ge9DRBY78GwmRQtvjZDux7EDbA8kA==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [arm64] + os: [darwin] + + '@rolldown/binding-darwin-x64@1.2.3': + resolution: {integrity: sha512-Zh9tCon19eDXJoihx0rqKhMUlMYqzwj3aPsSuHmI4RWZh62dWUL+DJN4C5YQya5TcQBJU/Fe8+rY0jhXTQITqA==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [x64] + os: [darwin] + + '@rolldown/binding-freebsd-x64@1.2.3': + resolution: {integrity: sha512-nGbJWewA1wrXXZiQhjAT5rhibGfns5ZNkDVqxsO6zJ3f3YvpoDNNmGMSbbhLuXKjNScaBJVOAboztAWVespQMg==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [x64] + os: [freebsd] + + '@rolldown/binding-linux-arm-gnueabihf@1.2.3': + resolution: {integrity: sha512-QNniJr5Kml0kDEB98jiDOJjXNroxIIi0IXIbdYzY26Xt1pVbeP62+KnoIZLwirOymX/0jDk/2gI/bNUv7A7OIw==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [arm] + os: [linux] + + '@rolldown/binding-linux-arm64-gnu@1.2.3': + resolution: {integrity: sha512-TkqEAcmmvH3I/q4114NB4RVt6241Dao48pF45uLcFGrwAaIn0iITgTAKP/dLjbN0R4buJjGb91+UHSoFmpgIWw==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [arm64] + os: [linux] + libc: [glibc] + + '@rolldown/binding-linux-arm64-musl@1.2.3': + resolution: {integrity: sha512-NHqjnxpsndf4MPymxteFAWHHfkTL8HjWh1KB7z23ofZ6QO2euONuxDXjat69dKZRALnGypg8k8SsK8vZJoXv1Q==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [arm64] + os: [linux] + libc: [musl] + + '@rolldown/binding-linux-ppc64-gnu@1.2.3': + resolution: {integrity: sha512-6tbrbwfz5GB9DQ4Jwo6hy9v+vR31xZlvzZ6n5Xut6Hhx5PvrA9q/HsK8KMaYQp063iqZGXwNvZtYNLD7EM/x0w==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [ppc64] + os: [linux] + libc: [glibc] + + '@rolldown/binding-linux-s390x-gnu@1.2.3': + resolution: {integrity: sha512-oyuXxXmoZHjXC917IAPFAAv4wWAa0cM9afk8nx1+9/jNNOX1uPf8yDA6p7G0RypOfw/X0PQt5IfoquY1um+zSg==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [s390x] + os: [linux] + libc: [glibc] + + '@rolldown/binding-linux-x64-gnu@1.2.3': + resolution: {integrity: sha512-TytMwF2KVGqP2tgd0I1OY0PAv78dZRAYcF5ssDzjM34SUXCED3uXvSd5+lHoC0bTD6eEdFz7LdQNCO1y0oVk9w==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [x64] + os: [linux] + libc: [glibc] + + '@rolldown/binding-linux-x64-musl@1.2.3': + resolution: {integrity: sha512-/E9m3qstrJFVPoULV25mVQblSNExY2+kBsYe4sy0Tn0yOOgJ8wZbZt3KnRbF/XeU2Gl1STKUQnDNTqhIE5MD4A==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [x64] + os: [linux] + libc: [musl] + + '@rolldown/binding-openharmony-arm64@1.2.3': + resolution: {integrity: sha512-Kr0OcsoQI816i6HOl3vFHpd1K0eZyh76zgfj4c1nTyaTsd5r2Mj1lwM4R90y/qaCfmTn9eHy0SKwi98eitRxug==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [arm64] + os: [openharmony] + + '@rolldown/binding-win32-arm64-msvc@1.2.3': + resolution: {integrity: sha512-hOtMwTqnME+/gJcH/PCZ0wn0zPUjiWOgkHpxbSJpfGKMezHltx1S7/k1SitzVa7Ww2cqrDDaFbZEhcJZO8o+Jw==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [arm64] + os: [win32] + + '@rolldown/binding-win32-x64-msvc@1.2.3': + resolution: {integrity: sha512-ekcqMMkI2PlhYnfzQnB/cEdYUVVJViWvoUyLrbzgDoi3Snfc1mVBwdnc306ufA5ejy8JSPjT2RlW1nQSjW7efg==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [x64] + os: [win32] + '@rolldown/pluginutils@1.0.0-rc.3': resolution: {integrity: sha512-eybk3TjzzzV97Dlj5c+XrBFW57eTNhzod66y9HrBlzJ6NsCrWCp/2kaPS3K9wJmurBC0Tdw4yPjXKZqlznim3Q==} + '@rolldown/pluginutils@1.0.1': + resolution: {integrity: sha512-2j9bGt5Jh8hj+vPtgzPtl72j0yRxHAyumoo6TNfAjsLB04UtpSvPbPcDcBMxz7n+9CYB0c1GxQFxYRg2jimqGw==} + '@rollup/plugin-alias@6.0.0': resolution: {integrity: sha512-tPCzJOtS7uuVZd+xPhoy5W4vThe6KWXNmsFCNktaAh5RTqcLiSfT4huPQIXkgJ6YCOjJHvecOAzQxLFhPxKr+g==} engines: {node: '>=20.19.0'} @@ -2785,6 +3450,9 @@ packages: '@speed-highlight/core@1.2.15': resolution: {integrity: sha512-BMq1K3DsElxDWawkX6eLg9+CKJrTVGCBAWVuHXVUV2u0s2711qiChLSId6ikYPfxhdYocLNt3wWwSvDiTvFabw==} + '@stablelib/base64@1.0.1': + resolution: {integrity: sha512-1bnPQqSxSuc3Ii6MhBysoWCg58j97aUjuCSZrGSmDxNqtytIi0k8utUenAwTZN4V5mXXYGsVUI9zeBqy+jBOSQ==} + '@stylexjs/stylex@0.19.0': resolution: {integrity: sha512-CnUFp7YMaDLDeemsWOfJgoC/gKM5P/yBNMcpJaE6ChJmXr7s0DJwSeGTTlHJcqqwN9OW1qGtmARWLFhGZN1pTA==} @@ -3216,6 +3884,18 @@ packages: next: optional: true + '@upstash/core-analytics@0.0.10': + resolution: {integrity: sha512-7qJHGxpQgQr9/vmeS1PktEwvNAF7TI4iJDi8Pu2CFZ9YUGHZH4fOP5TfYlZ4aVxfopnELiE4BS4FBjyK7V1/xQ==} + engines: {node: '>=16.0.0'} + + '@upstash/ratelimit@2.0.8': + resolution: {integrity: sha512-YSTMBJ1YIxsoPkUMX/P4DDks/xV5YYCswWMamU8ZIfK9ly6ppjRnVOyBhMDXBmzjODm4UQKcxsJPvaeFAijp5w==} + peerDependencies: + '@upstash/redis': ^1.34.3 + + '@upstash/redis@1.38.2': + resolution: {integrity: sha512-RZ+JaRCVIS+ZTGnjOnDMr+/0aqDxsBb5rV6aW+Pys4SGELwr5lwE3UbLHRCHqMQ5Ulxj0b/CFBHfbmE175Otog==} + '@vercel/nft@1.10.2': resolution: {integrity: sha512-w+WyX5Ulmj4dtTZrxaulqrjaLZHSbnPzx75SJsTNYmotKsqn1JlLnDJa+lz5hn90HJofhl/2MAtw0mCrgM3qYw==} engines: {node: '>=20'} @@ -3488,6 +4168,9 @@ packages: bindings@1.5.0: resolution: {integrity: sha512-p2q/t/mhvuOj/UeLlV6566GD/guowlr0hHxClI0W9m7MWYkL1F0hLo+0Aexs9HSPCtR1SXQ0TD3MMKrXZajbiQ==} + blake3-wasm@2.1.5: + resolution: {integrity: sha512-F1+K8EbfOZE49dtoPtmxUQrpXaBIl3ICvasLh+nJta0xkz+9kF/7uet9fLnwKqhDrmj6g+6K3Tw9yQPUg2ka5g==} + bn.js@5.2.5: resolution: {integrity: sha512-Vq886eXykuP5E6HcKSSStP3bJgrE6In5WKxVUvJ8XGpWWYs2xZHWqUwzCtGgEtBcxyd57KBFDPFoUfNzdaHCNg==} @@ -3766,6 +4449,10 @@ packages: resolution: {integrity: sha512-yki5XnKuf750l50uGTllt6kKILY4nQ1eNIQatoXEByZ5dWgnKqbnqmTrBE5B4N7lrMJKQ2ytWMiTO2o0v6Ew/w==} engines: {node: '>= 0.6'} + cookie@1.1.1: + resolution: {integrity: sha512-ei8Aos7ja0weRpFzJnEA9UHJ/7XQmqglbRwnf2ATjcB9Wq874VKH9kfjjirM6UhU2/E5fFYadylyhFldcqSidQ==} + engines: {node: '>=18'} + copy-to-clipboard@3.3.3: resolution: {integrity: sha512-2KV8NhB5JqC3ky0r9PMCAZKbUHSwtEo4CwCs0KXgruG43gX5PMqDEBbVU4OUzw2MuAWUfsuFmWvEKG5QRfSnJA==} @@ -3812,8 +4499,8 @@ packages: crossws@0.3.5: resolution: {integrity: sha512-ojKiDvcmByhwa8YYqbQI/hg7MEU0NC03+pSdEq4ZUnZR9xXpwk7E43SMNGkn+JxJGPFtNvQ48+vV2p+P1ml5PA==} - crossws@0.4.5: - resolution: {integrity: sha512-wUR89x/Rw7/8t+vn0CmGDYM9TD6VtARGb0LD5jq2wjtMy1vCP4M+sm6N6TigWeTYvnA8MoW29NqqXD0ep0rfBA==} + crossws@0.4.10: + resolution: {integrity: sha512-pz3oubH/dt12KjqsUB0IuXW4nwRDQ583iDsP4555Cpdqx0NoU7pGlWBcayyFI8f/l/idRpgjMEfwuOxSWJYlIA==} peerDependencies: srvx: '>=0.11.5' peerDependenciesMeta: @@ -3981,6 +4668,102 @@ packages: resolution: {integrity: sha512-nI4U3TottKAcAD9LLud4Cb7b2QztQMUEfHbvhTH09bqXTxnSie8WnjPALV/WMCrJZ6UV/qHJ6L03OqO3LcdYZw==} engines: {node: '>=12'} + drizzle-kit@0.31.10: + resolution: {integrity: sha512-7OZcmQUrdGI+DUNNsKBn1aW8qSoKuTH7d0mYgSP8bAzdFzKoovxEFnoGQp2dVs82EOJeYycqRtciopszwUf8bw==} + hasBin: true + + drizzle-orm@0.45.2: + resolution: {integrity: sha512-kY0BSaTNYWnoDMVoyY8uxmyHjpJW1geOmBMdSSicKo9CIIWkSxMIj2rkeSR51b8KAPB7m+qysjuHme5nKP+E5Q==} + peerDependencies: + '@aws-sdk/client-rds-data': '>=3' + '@cloudflare/workers-types': '>=4' + '@electric-sql/pglite': '>=0.2.0' + '@libsql/client': '>=0.10.0' + '@libsql/client-wasm': '>=0.10.0' + '@neondatabase/serverless': '>=0.10.0' + '@op-engineering/op-sqlite': '>=2' + '@opentelemetry/api': ^1.4.1 + '@planetscale/database': '>=1.13' + '@prisma/client': '*' + '@tidbcloud/serverless': '*' + '@types/better-sqlite3': '*' + '@types/pg': '*' + '@types/sql.js': '*' + '@upstash/redis': '>=1.34.7' + '@vercel/postgres': '>=0.8.0' + '@xata.io/client': '*' + better-sqlite3: '>=7' + bun-types: '*' + expo-sqlite: '>=14.0.0' + gel: '>=2' + knex: '*' + kysely: '*' + mysql2: '>=2' + pg: '>=8' + postgres: '>=3' + prisma: '*' + sql.js: '>=1' + sqlite3: '>=5' + peerDependenciesMeta: + '@aws-sdk/client-rds-data': + optional: true + '@cloudflare/workers-types': + optional: true + '@electric-sql/pglite': + optional: true + '@libsql/client': + optional: true + '@libsql/client-wasm': + optional: true + '@neondatabase/serverless': + optional: true + '@op-engineering/op-sqlite': + optional: true + '@opentelemetry/api': + optional: true + '@planetscale/database': + optional: true + '@prisma/client': + optional: true + '@tidbcloud/serverless': + optional: true + '@types/better-sqlite3': + optional: true + '@types/pg': + optional: true + '@types/sql.js': + optional: true + '@upstash/redis': + optional: true + '@vercel/postgres': + optional: true + '@xata.io/client': + optional: true + better-sqlite3: + optional: true + bun-types: + optional: true + expo-sqlite: + optional: true + gel: + optional: true + knex: + optional: true + kysely: + optional: true + mysql2: + optional: true + pg: + optional: true + postgres: + optional: true + prisma: + optional: true + sql.js: + optional: true + sqlite3: + optional: true + dunder-proto@1.0.1: resolution: {integrity: sha512-KIN/nDJBQRcXw0MLVhZE9iQHmG68qAVIBg9CqmUYjmQIhgij9U5MFvrqkUL5FbtyyzZuOeOt0zdeRe4UY7ct+A==} engines: {node: '>= 0.4'} @@ -4033,6 +4816,24 @@ packages: resolution: {integrity: sha512-+h1lkLKhZMTYjog1VEpJNG7NZJWcuc2DDk/qsqSTRRCOXiLjeQ1d1/udrUGhqMxUgAlwKNZ0cf2uqan5GLuS2A==} engines: {node: '>=6'} + env-runner@0.1.16: + resolution: {integrity: sha512-2LRJM4P2KLX6J83QZZrMqvgCDt/D5ea7wPcI3yYiy5cG/9rX5QwdwZFx0D7ktWnjdRyZxYjttGGorb5nFqb1CA==} + hasBin: true + peerDependencies: + '@netlify/runtime': ^4.1.23 + '@vercel/queue': '>=0.2.0' + miniflare: ^4.20260515.0 + wrangler: ^4.0.0 + peerDependenciesMeta: + '@netlify/runtime': + optional: true + '@vercel/queue': + optional: true + miniflare: + optional: true + wrangler: + optional: true + error-ex@1.3.4: resolution: {integrity: sha512-sqQamAnR14VgCr1A618A3sGrygcpK+HEbenA/HiEAkkUwcZIIB/tgWqHFxWgOyDh4nB4JCRimh79dR5Ywc9MDQ==} @@ -4060,6 +4861,11 @@ packages: es6-promisify@5.0.0: resolution: {integrity: sha512-C+d6UdsYDk0lMebHNR4S2NybQMMngAOnOwYBQjTOiv0MkoJMP0Myw2mgpDLBcpfCmRLxyFqYhS/CfOENq4SJhQ==} + esbuild@0.18.20: + resolution: {integrity: sha512-ceqxoedUrcayh7Y7ZX6NdbbDzGROiyVBgC4PriJThBKSVPWnnFHZAkfI1lJT8QFkOwH4qOS2SJkS4wvpGl8BpA==} + engines: {node: '>=12'} + hasBin: true + esbuild@0.25.12: resolution: {integrity: sha512-bbPBYYrtZbkt6Os6FiTLCTFxvq4tt3JKall1vRwshA3fdVztsLAatFaZobhkBC8/BrPetoa0oksYoKXoG4ryJg==} engines: {node: '>=18'} @@ -4075,6 +4881,11 @@ packages: engines: {node: '>=18'} hasBin: true + esbuild@0.28.1: + resolution: {integrity: sha512-HrJrvZv5ayxBzPfwphOoNzkzOIIlifzk0KJrGK2c8R4+LKpMtpYLQeUdjnwjWv/LZlkH2laZk+4w78pi99D4Vw==} + engines: {node: '>=18'} + hasBin: true + escalade@3.2.0: resolution: {integrity: sha512-WUj2qlxaQtO4g6Pq5c29GTcWGDyd8itL8zTlipgECz3JesAiiOKotd8JU6otB3PACgG6xkJUyVhboMS+bje/jA==} engines: {node: '>=6'} @@ -4151,6 +4962,9 @@ packages: exsolve@1.0.8: resolution: {integrity: sha512-LmDxfWXwcTArk8fUEnOfSZpHOJ6zOMUJKOtFLFqJLoKJetuQG874Uc7/Kki7zFLzYybmZhp1M7+98pfMqeX8yA==} + exsolve@1.1.1: + resolution: {integrity: sha512-9U/jZUgjnSGyntRr6y5Muu1MJcwFl6kPu7k8qLF0IMNfLqvw0NZ4nnVDq0RVoZ0RvCyumib4Ez3KYrVfilrw+g==} + extend@3.0.2: resolution: {integrity: sha512-fjquC59cD7CyW6urNXK0FBufkZcoiGG80wTuPujX590cB5Ttln20E2UB4S/WARVqhXffZl2LNgS+gQdPIIim/g==} @@ -4168,6 +4982,9 @@ packages: resolution: {integrity: sha512-7MptL8U0cqcFdzIzwOTHoilX9x5BrNqye7Z/LuC7kCMRio1EMSyqRK3BEAUD7sXRq4iT4AzTVuZdhgQ2TCvYLg==} engines: {node: '>=8.6.0'} + fast-sha256@1.3.0: + resolution: {integrity: sha512-n11RGP/lrWEFI/bWdygLxhI+pVeo1ZYIVwvvPkW7azl/rOy+F3HYRZ2K5zeE9mmkhQppyv9sQFx0JM9UabnpPQ==} + fast-stable-stringify@1.0.0: resolution: {integrity: sha512-wpYMUmFu5f00Sm0cj2pfivpmawLZ0NKdviQ4w9zJeR8JVtOpOxHmLaJuj0vxvGqMJQWyP/COUkF75/57OKyRag==} @@ -4316,6 +5133,9 @@ packages: resolution: {integrity: sha512-kVCxPF3vQM/N0B1PmoqVUqgHP+EeVjmZSQn+1oCRPxd2P21P2F19lIgbR3HBosbB1PUhOAoctJnfEn2GbN2eZA==} engines: {node: '>=18'} + get-tsconfig@4.14.1: + resolution: {integrity: sha512-Dz/6HxkrxgNehhxLVeyv8sad9UzF2xBVeaKBQNDfJ5XiSXmp2gTR0eO0RWiT2NCKS5aGP9jjkOMggTN90qU50A==} + giget@3.2.0: resolution: {integrity: sha512-GvHTWcykIR/fP8cj8dMpuMMkvaeJfPvYnhq0oW+chSeIr+ldX21ifU2Ms6KBoyKZQZmVaUAAhQ2EZ68KJF8a7A==} hasBin: true @@ -4367,24 +5187,34 @@ packages: resolution: {integrity: sha512-O1Ld7Dr+nqPnmGpdhzLmMTQ4vAsD+rHwMm1NLUmoUFFymBOMKxCCrtDxqdBRYXdeEPEi3SyoR4TizJLQrnKBNA==} engines: {node: ^12.20.0 || ^14.13.1 || >=16.0.0} + h3-rules@0.1.0: + resolution: {integrity: sha512-MrUUH1E/yoM7hvpKVbLs/CFeindwiTn7Fcfo+zXDpfuRYbcpJDPkYGGttCSiHNJmjUQNYQ5yn9veUIqFonYXuw==} + peerDependencies: + h3: ^2.0.1-rc.25 + ocache: '>=0.2.0' + peerDependenciesMeta: + ocache: + optional: true + h3@1.15.11: resolution: {integrity: sha512-L3THSe2MPeBwgIZVSH5zLdBBU90TOxarvhK9d04IDY2AmVS8j2Jz2LIWtwsGOU3lu2I5jCN7FNvVfY2+XyF+mg==} - h3@2.0.1-rc.2: - resolution: {integrity: sha512-2vS7OETzPDzGQxmmcs6ttu7p0NW25zAdkPXYOr43dn4GZf81uUljJvupa158mcpUGpsQUqIy4O4THWUQT1yVeA==} + h3@2.0.1-rc.20: + resolution: {integrity: sha512-28ljodXuUp0fZovdiSRq4G9OgrxCztrJe5VdYzXAB7ueRvI7pIUqLU14Xi3XqdYJ/khXjfpUOOD2EQa6CmBgsg==} engines: {node: '>=20.11.1'} + hasBin: true peerDependencies: crossws: ^0.4.1 peerDependenciesMeta: crossws: optional: true - h3@2.0.1-rc.20: - resolution: {integrity: sha512-28ljodXuUp0fZovdiSRq4G9OgrxCztrJe5VdYzXAB7ueRvI7pIUqLU14Xi3XqdYJ/khXjfpUOOD2EQa6CmBgsg==} + h3@2.0.1-rc.26: + resolution: {integrity: sha512-GDxlvDsKxgjRvG5UBRJYyGJTMWLV30CJ4cV+e7QCTgftDHihrvio1fVPbNembhEr6J4WNm8IWy3fookgyTweLw==} engines: {node: '>=20.11.1'} hasBin: true peerDependencies: - crossws: ^0.4.1 + crossws: ^0.4.9 peerDependenciesMeta: crossws: optional: true @@ -4426,6 +5256,9 @@ packages: hookable@5.5.3: resolution: {integrity: sha512-Yc+BQe8SvoXH1643Qez1zqLRmbA5rCL+sSmk6TVos0LWVfNIB7PGncdlId77WzLGSIB5KaWgTaNTs2lNVEI6VQ==} + hookable@6.1.1: + resolution: {integrity: sha512-U9LYDy1CwhMCnprUfeAZWZGByVbhd54hwepegYTK7Pi5NvqEj63ifz5z+xukznehT7i6NIZRu89Ay1AZmRsLEQ==} + html-encoding-sniffer@6.0.0: resolution: {integrity: sha512-CV9TW3Y3f8/wT0BRFc1/KAVQ3TUHiXmaAb6VW9vtiMFf7SLoMd1PdAc4W3KFOFETBJUb90KatHqlsZMWV+R9Gg==} engines: {node: ^20.19.0 || ^22.12.0 || >=24.0.0} @@ -4446,8 +5279,8 @@ packages: resolution: {integrity: sha512-vK9P5/iUfdl95AI+JVyUuIcVtd4ofvtrOr3HNtM2yxC9bnMbEdp3x01OhQNnjb8IJYi38VlTE3mBXwcfvywuSw==} engines: {node: '>= 14'} - httpxy@0.5.3: - resolution: {integrity: sha512-SMS9V6Sn7VWaS11lYhoAr0ceoaiolTWf4jYdJn0NJhCdKMu9R2H9Fh0LBDWBHQF6HRLI1PmaePYsjanSpE5PEw==} + httpxy@0.5.5: + resolution: {integrity: sha512-uDjmnPyp1q4Sgzf3w+J/Fc6UqcCEj0x4Wjp7OqK5dGhNeDgpyrAmnS6ey8QWrX3SWDon2DMKf9sBa5X9+CVyMA==} human-signals@2.1.0: resolution: {integrity: sha512-B4FFZ6q/T2jhhksgkbEW3HBvWIfDW85snkQgawt07S7J5QXTk6BkNV+0yAeZrM5QpMAdYlocGoljn0sJ/WQkFw==} @@ -5024,6 +5857,10 @@ packages: resolution: {integrity: sha512-VP79XUPxV2CigYP3jWwAUFSku2aKqBH7uTAapFWCBqutsbmDo96KY5o8uh6U+/YSIn5OxJnXp73beVkpqMIGhA==} engines: {node: '>=18'} + miniflare@5.20260801.1-alpha: + resolution: {integrity: sha512-BHPVzIDA6mbx7LefxpvkXW7DHx9FKB9GorZatbnrrFTt3CVMU8zuUpbgyCuebwDKcTTOZos43ta8GQ0eMVEpxA==} + engines: {node: '>=22.0.0'} + minimatch@10.2.5: resolution: {integrity: sha512-MULkVLfKGYDFYejP07QOurDLLQpcjk7Fw+7jXS2R2czRQzR56yHRveU5NDJEOviH+hETZKSkIk5c+T23GjFUMg==} engines: {node: 18 || 20 || >=22} @@ -5075,24 +5912,39 @@ packages: resolution: {integrity: sha512-8Ofs/AUQh8MaEcrlq5xOX0CQ9ypTF5dl78mjlMNfOK08fzpgTHQRQPBxcPlEtIw0yRpws+Zo/3r+5WRby7u3Gg==} engines: {node: '>= 0.6'} - nf3@0.1.12: - resolution: {integrity: sha512-qbMXT7RTGh74MYWPeqTIED8nDW70NXOULVHpdWcdZ7IVHVnAsMV9fNugSNnvooipDc1FMOzpis7T9nXJEbJhvQ==} + nf3@0.3.23: + resolution: {integrity: sha512-RWVLAWozmVD3AaDmaU3qMGB3v+yNlH5d9qqStI4e/WLlNQVnJ4YErGDbYCIrGFyrHdbF6I6Baf0Ae6c7tFYmSg==} - nitro-nightly@4.0.0-20251010-091516-7cafddba: - resolution: {integrity: sha512-biADkmoR/Nb9OmUURTfDI2BpGo2IMEt2RbsiMhjqdwz2w3tEm+tx0Hd28LXjBCwid+l8jpqyfmpwc8jzwdng3w==} + nitro-nightly@3.0.1-20260731-205209-52abde8a: + resolution: {integrity: sha512-KI1rwOJPgD0U57mE+1AefoEPjd+aJPJ4GCTLym0cXyfBBi8JtVsHmtB/4D3g1RaDwntjoz8H5nWnWGg7agYnuA==} engines: {node: ^20.19.0 || >=22.12.0} hasBin: true peerDependencies: - rolldown: '*' - vite: ^7 + '@vercel/queue': ^0.4.0 + dotenv: '*' + giget: '*' + jiti: ^2.7.0 + rollup: ^4.62.2 + vite: ^7 || ^8 xml2js: ^0.6.2 + zephyr-agent: ^1.1.2 peerDependenciesMeta: - rolldown: + '@vercel/queue': + optional: true + dotenv: + optional: true + giget: + optional: true + jiti: + optional: true + rollup: optional: true vite: optional: true xml2js: optional: true + zephyr-agent: + optional: true nitropack@2.13.4: resolution: {integrity: sha512-tX7bT6zxNeMwkc6hxHiZeUoTOjVrcjoh1Z3cmxOlodIqjl4HISgqfGOmkWSayky3Nv9Z5+KQH52F8nmXJY5AAA==} @@ -5182,9 +6034,15 @@ packages: resolution: {integrity: sha512-EFVjAYfzWqWsBMRHPMAXLCDIJnpMhdWAqR7xG6M6a2cs6PMFpl/+Z20w9zDW4vkxOFfddegBKq9Rehd0bxWE7A==} engines: {node: '>= 10'} + ocache@0.2.0: + resolution: {integrity: sha512-QE+SxXf/A8yR01rEOg2X5KwUe+mARHo1xQXl+iwLMzLIH06S5lBOZhhHQWp7T5etfFa8nOnRhvjGuo9YBCWwig==} + ofetch@1.5.1: resolution: {integrity: sha512-2W4oUZlVaqAPAil6FUg/difl6YhqhUR7x2eZY4bQCko22UXg3hptq9KLQdqFClV+Wu85UX7hNtdGTngi/1BxcA==} + ofetch@2.0.0-alpha.3: + resolution: {integrity: sha512-zpYTCs2byOuft65vI3z43Dd6iSdFbOZZLb9/d21aCpx2rGastVU9dOCv0lu4ykc1Ur1anAYjDi3SUvR0vq50JA==} + ohash@2.0.11: resolution: {integrity: sha512-RdR9FQrFwNBNXAr4GixM8YaRZRJ5PUWbKYbE5eOsrwAjJW0q2REGcf79oYPsLyskQCZG1PLN+S/K1V00joZAoQ==} @@ -5295,6 +6153,9 @@ packages: resolution: {integrity: sha512-3O/iVVsJAPsOnpwWIeD+d6z/7PmqApyQePUtCndjatj/9I5LylHvt5qluFaBT3I5h3r1ejfR056c+FCv+NnNXg==} engines: {node: 18 || 20 || >=22} + path-to-regexp@6.3.0: + resolution: {integrity: sha512-Yhpw4T9C6hPpgPeA28us07OJeqZ5EzQTkbfwuhsUg0c237RomFoETJgmp2sa3F/41gfLE6G5cqcYwznmeEeOlQ==} + path-to-regexp@8.4.2: resolution: {integrity: sha512-qRcuIdP69NPm4qbACK+aDogI5CBDMi1jKe0ry5rSQJz8JVLsC7jV8XpiJjGRLLol3N+R5ihGYcrPLTno6pAdBA==} @@ -5552,10 +6413,6 @@ packages: regenerator-runtime@0.13.11: resolution: {integrity: sha512-kY1AZVr2Ra+t+piVaJ4gxaFaReZVH40AKNo7UCX6W+dEwBo/2oZJzqfuN1qLq1oL45o56cPaTXELwrTh8Fpggg==} - rendu@0.0.6: - resolution: {integrity: sha512-nZ512Dw0MxKiIYfCVv8DPe6ig4m0Qt3FOYBJEXrammjIYBBPuHaudc0AGfYx+iyOw2q0itAtPywiVZXtTFCsig==} - hasBin: true - require-directory@2.1.1: resolution: {integrity: sha512-fGxEI7+wsG9xrvdjsrlmL22OMTTiHRwAMroiEeMgq8gzoLC/PQr7RsRDSTLUg/bZAZtF+TVIkHc6/4RIKrui+Q==} engines: {node: '>=0.10.0'} @@ -5575,6 +6432,9 @@ packages: resolution: {integrity: sha512-qYg9KP24dD5qka9J47d0aVky0N+b4fTU89LN9iDnjB5waksiC49rvMB0PrUJQGoTmH50XPiqOvAjDfaijGxYZw==} engines: {node: '>=8'} + resolve-pkg-maps@1.0.0: + resolution: {integrity: sha512-seS2Tj26TBVOC2NIc2rOe2y2ZO7efxITtLZcGSOnHHNOQ7CkiUBfw0Iw2ck6xkIhPwLhKNLS8BO+hEpngQlqzw==} + resolve@1.22.12: resolution: {integrity: sha512-TyeJ1zif53BPfHootBGwPRYT1RUt6oGWsaQr8UyZW/eAm9bKoijtvruSDEmZHm92CwS9nj7/fWttqPCgzep8CA==} engines: {node: '>= 0.4'} @@ -5592,6 +6452,11 @@ packages: resolution: {integrity: sha512-g6QUff04oZpHs0eG5p83rFLhHeV00ug/Yf9nZM6fLeUrPguBTkTQOdpAWWspMh55TZfVQDPaN3NQJfbVRAxdIw==} engines: {iojs: '>=1.0.0', node: '>=0.10.0'} + rolldown@1.2.3: + resolution: {integrity: sha512-rn9wpmxplLf7NLNyCk9FyWh3FM43DbY8jOzCdEPzH7uflhTftRbCEpqi6Ly2osgoU8OwObtmavMbWLaWy4LX7A==} + engines: {node: ^20.19.0 || >=22.12.0} + hasBin: true + rollup-plugin-visualizer@7.0.1: resolution: {integrity: sha512-UJUT4+1Ho4OcWmPYU3sYXgUqI8B8Ayfe06MX7y0qCJ1K8aGoKtR/NDd/2nZqM7ADkrzny+I99Ul7GgyoiVNAgg==} engines: {node: '>=22'} @@ -5610,12 +6475,12 @@ packages: engines: {node: '>=18.0.0', npm: '>=8.0.0'} hasBin: true - rou3@0.7.12: - resolution: {integrity: sha512-iFE4hLDuloSWcD7mjdCDhx2bKcIsYbtOTpfH5MHHLSKMOUyjqQXTeZVa289uuwEGEKFoE/BAPbhaU4B774nceg==} - rou3@0.8.1: resolution: {integrity: sha512-ePa+XGk00/3HuCqrEnK3LxJW7I0SdNg6EFzKUJG73hMAdDcOUC/i/aSz7LSDwLrGr33kal/rqOGydzwl6U7zBA==} + rou3@0.9.1: + resolution: {integrity: sha512-z/sSmzvtwMDDnxsPVhfWMuG6F6mbmhFDXoVqLmMfbpDD9qfV3GDmSQpf0+W296/ZDIpW2wcMmBfpVFzcnOi/nA==} + router@2.2.0: resolution: {integrity: sha512-nLTrUKm2UyiL7rlhapu/Zl45FwNgkZGaCpZbIHajDYgwlJCOzLSk+cIPAnsEqV955GjILJnKbdQC1nVPz+gAYQ==} engines: {node: '>= 18'} @@ -5656,8 +6521,8 @@ packages: resolution: {integrity: sha512-BR7VvDCVHO+q2xBEWskxS6DJE1qRnb7DxzUrogb71CWoSficBxYsiAGd+Kl0mmq/MprG9yArRkyrQxTO6XjMzA==} hasBin: true - semver@7.8.2: - resolution: {integrity: sha512-c8jsqUZm3omBOI66G90z1Dyw5z622G8oLG+omfsHBJf3CWQTlOcwOjvOG6wtiNfW6anKm/eA39LMwMtMez2TiQ==} + semver@7.8.5: + resolution: {integrity: sha512-Y7/KDsb8LjooZpwaqGyulO6DQlksgCncchHGk+sZIY4SBvUocMBEFH5Ur1fI4dV+Jvl0w6cjvucaIi40puRioA==} engines: {node: '>=10'} hasBin: true @@ -5709,6 +6574,10 @@ packages: engines: {node: '>=20.18.1'} hasBin: true + sharp@0.35.2: + resolution: {integrity: sha512-FVtFjtBCMiJS6yb5CX7Sop45WFMpeGw6oRKuJnXYgf/f1ms/D7LE/ZUSNxnW7rZ/dbslQWYkoqFHGPaDBtaK4w==} + engines: {node: '>=20.9.0'} + shebang-command@2.0.0: resolution: {integrity: sha512-kHxr2zZpYtdmrN1qDjrrX/Z1rR1kG8Dx+gkpK1G4eXmvXswmcE1hTWBWYUzlraYw1/yZp6YuDY77YtvbN0dmDA==} engines: {node: '>=8'} @@ -5777,13 +6646,13 @@ packages: resolution: {integrity: sha512-i5uvt8C3ikiWeNZSVZNWcfZPItFQOsYTUAOkcUPGd8DqDy1uOUikjt5dG+uRlwyvR108Fb9DOd4GvXfT0N2/uQ==} engines: {node: '>= 12'} - srvx@0.11.16: - resolution: {integrity: sha512-bp07zRuycfTY43IjAvvTFnmnJi8ikW0VFiHwOhhYcVW/L4xQ1XY4PAd4Nuum1rsA17C39zL7x+CDhrn5AL32Rw==} + srvx@0.11.22: + resolution: {integrity: sha512-LqZxxBDMKuMAZzFzJnDCkFOrs9MZQZr0LvHiO/SuSZVdQaXD7xQ5UWTUxheJrQPve1qk9MG2B/yttUvJxw8egQ==} engines: {node: '>=20.16.0'} hasBin: true - srvx@0.8.16: - resolution: {integrity: sha512-hmcGW4CgroeSmzgF1Ihwgl+Ths0JqAJ7HwjP2X7e3JzY7u4IydLMcdnlqGQiQGUswz+PO9oh/KtCpOISIvs9QQ==} + srvx@0.12.5: + resolution: {integrity: sha512-IuvtDNQg5EIwv3c6dleyau7u8hCyGQ7D6+V/QM799Aud07z0wCUcurKLTRfyG33C8oUY+UWcVBFkfHMcbtmRLA==} engines: {node: '>=20.16.0'} hasBin: true @@ -5797,6 +6666,9 @@ packages: standard-as-callback@2.1.0: resolution: {integrity: sha512-qoRRSyROncaz1z0mvYqIE4lCd9p2R90i6GxW3uZv5ucSu8tU7B5HXUP1gG8pVZsYNVaXjk8ClXHPttLyxAL48A==} + standardwebhooks@1.0.0: + resolution: {integrity: sha512-BbHGOQK9olHPMvQNHWul6MYlrRTAOKn03rOe4A8O3CLWhNf4YHBqq2HJKKC+sfqpxiBY52pNeesD6jIiLDz8jg==} + statuses@1.5.0: resolution: {integrity: sha512-OpZ3zP+jT1PI7I8nemJX4AKmAX070ZkYPVWV/AaKTJl+tXCTGyVdC1a4SL8RUQYEwk/f34ZX8UTykN68FwrqAA==} engines: {node: '>= 0.6'} @@ -5932,11 +6804,6 @@ packages: teex@1.0.1: resolution: {integrity: sha512-eYE6iEI62Ni1H8oIa7KlDU6uQBtqr4Eajni3wX7rpfXD8ysFx8z0+dri+KWEPWpBsxXfxu58x/0jvTVT1ekOSg==} - terser@5.48.0: - resolution: {integrity: sha512-J/9An6vs9Us6wKRriSFXBWdRZapREHqFzdNUKk0pmu804EMR6dr6winwo7e5JDxN4xahxQsuysyYFwlwj4XN/Q==} - engines: {node: '>=10'} - hasBin: true - terser@5.49.0: resolution: {integrity: sha512-SNiDnXyHSrxVcIOtVbULzcTmniUiwcV7Nwdyj1twVubeTmbjoa8p69KKDpfkdoOavuM4/GRm1+ykI8qqnavHoA==} engines: {node: '>=10'} @@ -6023,6 +6890,11 @@ packages: tslib@2.8.1: resolution: {integrity: sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==} + tsx@4.23.11: + resolution: {integrity: sha512-Ry2oTEUnhBdeEdWIztY8kf3/nBGnPnjMLVGL0YfdRXMORuPER5NlKmayqxtxRxwB1xBN+RivRaJfe7PM1rtiyw==} + engines: {node: '>=18.0.0'} + hasBin: true + tw-animate-css@1.4.0: resolution: {integrity: sha512-7bziOlRqH0hJx80h/3mbicLW7o8qLsH5+RaLR2t+OHM3D0JlWGODQKQ4cxbK7WlvmUxpcj6Kgu6EKqjrGFe3QQ==} @@ -6065,8 +6937,9 @@ packages: resolution: {integrity: sha512-uZsKNuzQxDMUY6M3pIMvy5tvlGmtq8XJ2oLAkfRKGNu+1VQAIvLy2xIVG5ATZl5wDXl/tddByAWCizRbOme+TA==} engines: {node: '>=20.18.1'} - unenv@2.0.0-rc.21: - resolution: {integrity: sha512-Wj7/AMtE9MRnAXa6Su3Lk0LNCfqDYgfwVjwRFVum9U7wsto1imuHqk4kTm7Jni+5A0Hn7dttL6O/zjvUvoo+8A==} + undici@7.29.0: + resolution: {integrity: sha512-IDxfleLmmbSskfWSUATiN1nfn2rDuvnMOqb5CWR92iIfojA0Ud+ulOAAEQ57LPr9rWmsreUyf5lwyao+7GNNVw==} + engines: {node: '>=20.18.1'} unenv@2.0.0-rc.24: resolution: {integrity: sha512-i7qRCmY42zmCwnYlh9H2SvLEypEFGye5iRmEMKjcGi7zk9UquigRjFtTLz0TYqr0ZGLZhaMHl/foy1bZR+Cwlw==} @@ -6171,37 +7044,37 @@ packages: optional: true idb-keyval: optional: true - ioredis: - optional: true - uploadthing: - optional: true - - unstorage@2.0.0-alpha.3: - resolution: {integrity: sha512-BeoqISVh8jxqnPseHH7/92twe2VkQztrudXg8RFZVbXb4ckkFdpLk1LnNvsUndDltyodBMVxgI6V7JcbJYt2VQ==} - peerDependencies: - '@azure/app-configuration': ^1.8.0 - '@azure/cosmos': ^4.2.0 - '@azure/data-tables': ^13.3.0 - '@azure/identity': ^4.6.0 - '@azure/keyvault-secrets': ^4.9.0 - '@azure/storage-blob': ^12.26.0 - '@capacitor/preferences': ^6.0.3 || ^7.0.0 - '@deno/kv': '>=0.9.0' + ioredis: + optional: true + uploadthing: + optional: true + + unstorage@2.0.0-alpha.7: + resolution: {integrity: sha512-ELPztchk2zgFJnakyodVY3vJWGW9jy//keJ32IOJVGUMyaPydwcA1FtVvWqT0TNRch9H+cMNEGllfVFfScImog==} + peerDependencies: + '@azure/app-configuration': ^1.11.0 + '@azure/cosmos': ^4.9.1 + '@azure/data-tables': ^13.3.2 + '@azure/identity': ^4.13.0 + '@azure/keyvault-secrets': ^4.10.0 + '@azure/storage-blob': ^12.31.0 + '@capacitor/preferences': ^6 || ^7 || ^8 + '@deno/kv': '>=0.13.0' '@netlify/blobs': ^6.5.0 || ^7.0.0 || ^8.1.0 || ^9.0.0 || ^10.0.0 '@planetscale/database': ^1.19.0 - '@upstash/redis': ^1.34.3 - '@vercel/blob': '>=0.27.1' + '@upstash/redis': ^1.36.2 + '@vercel/blob': '>=0.27.3' '@vercel/functions': ^2.2.12 || ^3.0.0 '@vercel/kv': ^1.0.1 aws4fetch: ^1.0.20 - chokidar: ^4.0.3 - db0: '>=0.2.1' - idb-keyval: ^6.2.1 - ioredis: ^5.4.2 - lru-cache: ^11.2.2 - mongodb: ^6.20.0 - ofetch: ^1.4.1 - uploadthing: ^7.4.4 + chokidar: ^4 || ^5 + db0: '>=0.3.4' + idb-keyval: ^6.2.2 + ioredis: ^5.9.3 + lru-cache: ^11.2.6 + mongodb: ^6 || ^7 + ofetch: '*' + uploadthing: ^7.7.4 peerDependenciesMeta: '@azure/app-configuration': optional: true @@ -6442,6 +7315,21 @@ packages: engines: {node: ^16.13.0 || >=18.0.0} hasBin: true + workerd@1.20260801.1: + resolution: {integrity: sha512-/g9JGTyqnHtoIscpBHqKD8swE2V4StBs2i69PmLiOhH45OP95jCFICl4F1hKlgN57rqfni5LiCitttoX5OOkVA==} + engines: {node: '>=16'} + hasBin: true + + wrangler@4.120.0: + resolution: {integrity: sha512-cBmu/MeaB/fPacC0JpATs4duTOCagBxrZo+vBzuTX06tLzwSyAHE1drlHUZ8rP0VqVz1fy3ReGYTiHdKkoHltg==} + engines: {node: '>=22.0.0'} + hasBin: true + peerDependencies: + '@cloudflare/workers-types': ^5.20260801.1 + peerDependenciesMeta: + '@cloudflare/workers-types': + optional: true + wrap-ansi@6.2.0: resolution: {integrity: sha512-r6lPcBGxZXlIcymEu7InxDMhdW0KDxpLgoFLcguasxCaJ/SOIZwINatK9KY/tf+ZrlywOKU0UDj3ATXUBfxJXA==} engines: {node: '>=8'} @@ -6558,6 +7446,9 @@ packages: youch-core@0.3.3: resolution: {integrity: sha512-ho7XuGjLaJ2hWHoK8yFnsUGy2Y5uDpqSTq1FkHLK4/oqKtyUU1AFbOOxY4IpC9f0fTLjwYbslUz0Po5BpD1wrA==} + youch@4.1.0-beta.10: + resolution: {integrity: sha512-rLfVLB4FgQneDr0dv1oddCVZmKjcJ6yX6mS4pU82Mq/Dt9a3cLZQ62pDBL4AUO+uVrCvtWz3ZFUL2HFAFJ/BXQ==} + youch@4.1.1: resolution: {integrity: sha512-mxW3qiSnl+GRxXsaUMzv2Mbada1Y8CDltET9UxejDQe6DBYlSekghl5U5K0ReAikcHDi0G1vKZEmmo/NWAGKLA==} @@ -6863,6 +7754,15 @@ snapshots: '@biomejs/cli-win32-x64@2.4.13': optional: true + '@clerk/backend@3.16.1(react-dom@19.2.8(react@19.2.8))(react@19.2.8)': + dependencies: + '@clerk/shared': 4.27.1(react-dom@19.2.8(react@19.2.8))(react@19.2.8) + standardwebhooks: 1.0.0 + tslib: 2.8.1 + transitivePeerDependencies: + - react + - react-dom + '@clerk/localizations@4.13.8(react-dom@19.2.8(react@19.2.8))(react@19.2.8)': dependencies: '@clerk/shared': 4.25.8(react-dom@19.2.8(react@19.2.8))(react@19.2.8) @@ -6887,6 +7787,16 @@ snapshots: react: 19.2.8 react-dom: 19.2.8(react@19.2.8) + '@clerk/shared@4.27.1(react-dom@19.2.8(react@19.2.8))(react@19.2.8)': + dependencies: + '@tanstack/query-core': 5.101.4 + dequal: 2.0.3 + glob-to-regexp: 0.4.1 + js-cookie: 3.0.7 + optionalDependencies: + react: 19.2.8 + react-dom: 19.2.8(react@19.2.8) + '@clerk/ui@1.26.0(@solana/web3.js@1.98.4(bufferutil@4.1.0)(typescript@5.9.3)(utf-8-validate@6.0.6))(@types/react@19.2.17)(bs58@6.0.0)(bufferutil@4.1.0)(react-dom@19.2.8(react@19.2.8))(react-native@0.86.0(@babel/core@7.29.7(supports-color@10.2.2))(@types/react@19.2.17)(bufferutil@4.1.0)(react@19.2.8)(supports-color@10.2.2)(utf-8-validate@6.0.6))(react@19.2.8)(supports-color@10.2.2)(typescript@5.9.3)(utf-8-validate@6.0.6)': dependencies: '@clerk/localizations': 4.13.8(react-dom@19.2.8(react@19.2.8))(react@19.2.8) @@ -6921,11 +7831,40 @@ snapshots: '@cloudflare/kv-asset-handler@0.4.2': {} + '@cloudflare/kv-asset-handler@0.5.0': {} + + '@cloudflare/unenv-preset@2.16.1(unenv@2.0.0-rc.24)(workerd@1.20260801.1)': + dependencies: + unenv: 2.0.0-rc.24 + optionalDependencies: + workerd: 1.20260801.1 + + '@cloudflare/workerd-darwin-64@1.20260801.1': + optional: true + + '@cloudflare/workerd-darwin-arm64@1.20260801.1': + optional: true + + '@cloudflare/workerd-linux-64@1.20260801.1': + optional: true + + '@cloudflare/workerd-linux-arm64@1.20260801.1': + optional: true + + '@cloudflare/workerd-windows-64@1.20260801.1': + optional: true + + '@cloudflare/workers-types@5.20260808.1': {} + '@convex-dev/react-query@0.1.0(@tanstack/react-query@5.101.4(react@19.2.8))(convex@1.42.3(@clerk/react@6.12.8(react-dom@19.2.8(react@19.2.8))(react@19.2.8))(bufferutil@4.1.0)(react@19.2.8)(utf-8-validate@6.0.6))': dependencies: '@tanstack/react-query': 5.101.4(react@19.2.8) convex: 1.42.3(@clerk/react@6.12.8(react-dom@19.2.8(react@19.2.8))(react@19.2.8))(bufferutil@4.1.0)(react@19.2.8)(utf-8-validate@6.0.6) + '@cspotcode/source-map-support@0.8.1': + dependencies: + '@jridgewell/trace-mapping': 0.3.9 + '@csstools/color-helpers@6.0.2': {} '@csstools/css-calc@3.2.1(@csstools/css-parser-algorithms@4.0.0(@csstools/css-tokenizer@4.0.0))(@csstools/css-tokenizer@4.0.0)': @@ -6971,6 +7910,13 @@ snapshots: '@dotenvx/primitives@0.8.0': {} + '@drizzle-team/brocli@0.10.2': {} + + '@emnapi/runtime@1.11.3': + dependencies: + tslib: 2.8.1 + optional: true + '@emotion/babel-plugin@11.13.5(supports-color@10.2.2)': dependencies: '@babel/helper-module-imports': 7.29.7(supports-color@10.2.2) @@ -7037,6 +7983,16 @@ snapshots: '@emotion/weak-memoize@0.3.1': {} + '@esbuild-kit/core-utils@3.3.2': + dependencies: + esbuild: 0.18.20 + source-map-support: 0.5.21 + + '@esbuild-kit/esm-loader@2.6.5': + dependencies: + '@esbuild-kit/core-utils': 3.3.2 + get-tsconfig: 4.14.1 + '@esbuild/aix-ppc64@0.25.12': optional: true @@ -7046,6 +8002,12 @@ snapshots: '@esbuild/aix-ppc64@0.28.0': optional: true + '@esbuild/aix-ppc64@0.28.1': + optional: true + + '@esbuild/android-arm64@0.18.20': + optional: true + '@esbuild/android-arm64@0.25.12': optional: true @@ -7055,6 +8017,12 @@ snapshots: '@esbuild/android-arm64@0.28.0': optional: true + '@esbuild/android-arm64@0.28.1': + optional: true + + '@esbuild/android-arm@0.18.20': + optional: true + '@esbuild/android-arm@0.25.12': optional: true @@ -7064,6 +8032,12 @@ snapshots: '@esbuild/android-arm@0.28.0': optional: true + '@esbuild/android-arm@0.28.1': + optional: true + + '@esbuild/android-x64@0.18.20': + optional: true + '@esbuild/android-x64@0.25.12': optional: true @@ -7073,6 +8047,12 @@ snapshots: '@esbuild/android-x64@0.28.0': optional: true + '@esbuild/android-x64@0.28.1': + optional: true + + '@esbuild/darwin-arm64@0.18.20': + optional: true + '@esbuild/darwin-arm64@0.25.12': optional: true @@ -7082,6 +8062,12 @@ snapshots: '@esbuild/darwin-arm64@0.28.0': optional: true + '@esbuild/darwin-arm64@0.28.1': + optional: true + + '@esbuild/darwin-x64@0.18.20': + optional: true + '@esbuild/darwin-x64@0.25.12': optional: true @@ -7091,6 +8077,12 @@ snapshots: '@esbuild/darwin-x64@0.28.0': optional: true + '@esbuild/darwin-x64@0.28.1': + optional: true + + '@esbuild/freebsd-arm64@0.18.20': + optional: true + '@esbuild/freebsd-arm64@0.25.12': optional: true @@ -7100,6 +8092,12 @@ snapshots: '@esbuild/freebsd-arm64@0.28.0': optional: true + '@esbuild/freebsd-arm64@0.28.1': + optional: true + + '@esbuild/freebsd-x64@0.18.20': + optional: true + '@esbuild/freebsd-x64@0.25.12': optional: true @@ -7109,6 +8107,12 @@ snapshots: '@esbuild/freebsd-x64@0.28.0': optional: true + '@esbuild/freebsd-x64@0.28.1': + optional: true + + '@esbuild/linux-arm64@0.18.20': + optional: true + '@esbuild/linux-arm64@0.25.12': optional: true @@ -7118,6 +8122,12 @@ snapshots: '@esbuild/linux-arm64@0.28.0': optional: true + '@esbuild/linux-arm64@0.28.1': + optional: true + + '@esbuild/linux-arm@0.18.20': + optional: true + '@esbuild/linux-arm@0.25.12': optional: true @@ -7127,6 +8137,12 @@ snapshots: '@esbuild/linux-arm@0.28.0': optional: true + '@esbuild/linux-arm@0.28.1': + optional: true + + '@esbuild/linux-ia32@0.18.20': + optional: true + '@esbuild/linux-ia32@0.25.12': optional: true @@ -7136,6 +8152,12 @@ snapshots: '@esbuild/linux-ia32@0.28.0': optional: true + '@esbuild/linux-ia32@0.28.1': + optional: true + + '@esbuild/linux-loong64@0.18.20': + optional: true + '@esbuild/linux-loong64@0.25.12': optional: true @@ -7145,6 +8167,12 @@ snapshots: '@esbuild/linux-loong64@0.28.0': optional: true + '@esbuild/linux-loong64@0.28.1': + optional: true + + '@esbuild/linux-mips64el@0.18.20': + optional: true + '@esbuild/linux-mips64el@0.25.12': optional: true @@ -7154,6 +8182,12 @@ snapshots: '@esbuild/linux-mips64el@0.28.0': optional: true + '@esbuild/linux-mips64el@0.28.1': + optional: true + + '@esbuild/linux-ppc64@0.18.20': + optional: true + '@esbuild/linux-ppc64@0.25.12': optional: true @@ -7163,6 +8197,12 @@ snapshots: '@esbuild/linux-ppc64@0.28.0': optional: true + '@esbuild/linux-ppc64@0.28.1': + optional: true + + '@esbuild/linux-riscv64@0.18.20': + optional: true + '@esbuild/linux-riscv64@0.25.12': optional: true @@ -7172,6 +8212,12 @@ snapshots: '@esbuild/linux-riscv64@0.28.0': optional: true + '@esbuild/linux-riscv64@0.28.1': + optional: true + + '@esbuild/linux-s390x@0.18.20': + optional: true + '@esbuild/linux-s390x@0.25.12': optional: true @@ -7181,6 +8227,12 @@ snapshots: '@esbuild/linux-s390x@0.28.0': optional: true + '@esbuild/linux-s390x@0.28.1': + optional: true + + '@esbuild/linux-x64@0.18.20': + optional: true + '@esbuild/linux-x64@0.25.12': optional: true @@ -7190,6 +8242,9 @@ snapshots: '@esbuild/linux-x64@0.28.0': optional: true + '@esbuild/linux-x64@0.28.1': + optional: true + '@esbuild/netbsd-arm64@0.25.12': optional: true @@ -7199,6 +8254,12 @@ snapshots: '@esbuild/netbsd-arm64@0.28.0': optional: true + '@esbuild/netbsd-arm64@0.28.1': + optional: true + + '@esbuild/netbsd-x64@0.18.20': + optional: true + '@esbuild/netbsd-x64@0.25.12': optional: true @@ -7208,6 +8269,9 @@ snapshots: '@esbuild/netbsd-x64@0.28.0': optional: true + '@esbuild/netbsd-x64@0.28.1': + optional: true + '@esbuild/openbsd-arm64@0.25.12': optional: true @@ -7217,6 +8281,12 @@ snapshots: '@esbuild/openbsd-arm64@0.28.0': optional: true + '@esbuild/openbsd-arm64@0.28.1': + optional: true + + '@esbuild/openbsd-x64@0.18.20': + optional: true + '@esbuild/openbsd-x64@0.25.12': optional: true @@ -7226,6 +8296,9 @@ snapshots: '@esbuild/openbsd-x64@0.28.0': optional: true + '@esbuild/openbsd-x64@0.28.1': + optional: true + '@esbuild/openharmony-arm64@0.25.12': optional: true @@ -7235,6 +8308,12 @@ snapshots: '@esbuild/openharmony-arm64@0.28.0': optional: true + '@esbuild/openharmony-arm64@0.28.1': + optional: true + + '@esbuild/sunos-x64@0.18.20': + optional: true + '@esbuild/sunos-x64@0.25.12': optional: true @@ -7244,6 +8323,12 @@ snapshots: '@esbuild/sunos-x64@0.28.0': optional: true + '@esbuild/sunos-x64@0.28.1': + optional: true + + '@esbuild/win32-arm64@0.18.20': + optional: true + '@esbuild/win32-arm64@0.25.12': optional: true @@ -7253,75 +8338,196 @@ snapshots: '@esbuild/win32-arm64@0.28.0': optional: true + '@esbuild/win32-arm64@0.28.1': + optional: true + + '@esbuild/win32-ia32@0.18.20': + optional: true + '@esbuild/win32-ia32@0.25.12': optional: true - '@esbuild/win32-ia32@0.27.0': + '@esbuild/win32-ia32@0.27.0': + optional: true + + '@esbuild/win32-ia32@0.28.0': + optional: true + + '@esbuild/win32-ia32@0.28.1': + optional: true + + '@esbuild/win32-x64@0.18.20': + optional: true + + '@esbuild/win32-x64@0.25.12': + optional: true + + '@esbuild/win32-x64@0.27.0': + optional: true + + '@esbuild/win32-x64@0.28.0': + optional: true + + '@esbuild/win32-x64@0.28.1': + optional: true + + '@exodus/bytes@1.15.1(@noble/hashes@1.8.0)': + optionalDependencies: + '@noble/hashes': 1.8.0 + + '@floating-ui/core@1.7.5': + dependencies: + '@floating-ui/utils': 0.2.11 + + '@floating-ui/dom@1.7.6': + dependencies: + '@floating-ui/core': 1.7.5 + '@floating-ui/utils': 0.2.11 + + '@floating-ui/react-dom@2.1.8(react-dom@19.2.8(react@19.2.8))(react@19.2.8)': + dependencies: + '@floating-ui/dom': 1.7.6 + react: 19.2.8 + react-dom: 19.2.8(react@19.2.8) + + '@floating-ui/react@0.27.12(react-dom@19.2.8(react@19.2.8))(react@19.2.8)': + dependencies: + '@floating-ui/react-dom': 2.1.8(react-dom@19.2.8(react@19.2.8))(react@19.2.8) + '@floating-ui/utils': 0.2.11 + react: 19.2.8 + react-dom: 19.2.8(react@19.2.8) + tabbable: 6.5.0 + + '@floating-ui/utils@0.2.11': {} + + '@fontsource-variable/bricolage-grotesque@5.3.0': {} + + '@fontsource-variable/inter@5.3.0': {} + + '@formkit/auto-animate@0.8.4': {} + + '@google/genai@1.52.0(@modelcontextprotocol/sdk@1.29.0(supports-color@10.2.2)(zod@4.4.3))(bufferutil@4.1.0)(supports-color@10.2.2)(utf-8-validate@6.0.6)': + dependencies: + google-auth-library: 10.7.0(supports-color@10.2.2) + p-retry: 4.6.2 + protobufjs: 7.6.2 + ws: 8.21.0(bufferutil@4.1.0)(utf-8-validate@6.0.6) + optionalDependencies: + '@modelcontextprotocol/sdk': 1.29.0(supports-color@10.2.2)(zod@4.4.3) + transitivePeerDependencies: + - bufferutil + - supports-color + - utf-8-validate + + '@hono/node-server@1.19.15(hono@4.12.32)': + dependencies: + hono: 4.12.32 + + '@img/colour@1.1.0': {} + + '@img/sharp-darwin-arm64@0.35.2': + optionalDependencies: + '@img/sharp-libvips-darwin-arm64': 1.3.1 + optional: true + + '@img/sharp-darwin-x64@0.35.2': + optionalDependencies: + '@img/sharp-libvips-darwin-x64': 1.3.1 + optional: true + + '@img/sharp-freebsd-wasm32@0.35.2': + dependencies: + '@img/sharp-wasm32': 0.35.2 + optional: true + + '@img/sharp-libvips-darwin-arm64@1.3.1': + optional: true + + '@img/sharp-libvips-darwin-x64@1.3.1': + optional: true + + '@img/sharp-libvips-linux-arm64@1.3.1': + optional: true + + '@img/sharp-libvips-linux-arm@1.3.1': + optional: true + + '@img/sharp-libvips-linux-ppc64@1.3.1': + optional: true + + '@img/sharp-libvips-linux-riscv64@1.3.1': + optional: true + + '@img/sharp-libvips-linux-s390x@1.3.1': + optional: true + + '@img/sharp-libvips-linux-x64@1.3.1': + optional: true + + '@img/sharp-libvips-linuxmusl-arm64@1.3.1': + optional: true + + '@img/sharp-libvips-linuxmusl-x64@1.3.1': + optional: true + + '@img/sharp-linux-arm64@0.35.2': + optionalDependencies: + '@img/sharp-libvips-linux-arm64': 1.3.1 optional: true - '@esbuild/win32-ia32@0.28.0': + '@img/sharp-linux-arm@0.35.2': + optionalDependencies: + '@img/sharp-libvips-linux-arm': 1.3.1 optional: true - '@esbuild/win32-x64@0.25.12': + '@img/sharp-linux-ppc64@0.35.2': + optionalDependencies: + '@img/sharp-libvips-linux-ppc64': 1.3.1 optional: true - '@esbuild/win32-x64@0.27.0': + '@img/sharp-linux-riscv64@0.35.2': + optionalDependencies: + '@img/sharp-libvips-linux-riscv64': 1.3.1 optional: true - '@esbuild/win32-x64@0.28.0': + '@img/sharp-linux-s390x@0.35.2': + optionalDependencies: + '@img/sharp-libvips-linux-s390x': 1.3.1 optional: true - '@exodus/bytes@1.15.1(@noble/hashes@1.8.0)': + '@img/sharp-linux-x64@0.35.2': optionalDependencies: - '@noble/hashes': 1.8.0 + '@img/sharp-libvips-linux-x64': 1.3.1 + optional: true - '@floating-ui/core@1.7.5': - dependencies: - '@floating-ui/utils': 0.2.11 + '@img/sharp-linuxmusl-arm64@0.35.2': + optionalDependencies: + '@img/sharp-libvips-linuxmusl-arm64': 1.3.1 + optional: true - '@floating-ui/dom@1.7.6': - dependencies: - '@floating-ui/core': 1.7.5 - '@floating-ui/utils': 0.2.11 + '@img/sharp-linuxmusl-x64@0.35.2': + optionalDependencies: + '@img/sharp-libvips-linuxmusl-x64': 1.3.1 + optional: true - '@floating-ui/react-dom@2.1.8(react-dom@19.2.8(react@19.2.8))(react@19.2.8)': + '@img/sharp-wasm32@0.35.2': dependencies: - '@floating-ui/dom': 1.7.6 - react: 19.2.8 - react-dom: 19.2.8(react@19.2.8) + '@emnapi/runtime': 1.11.3 + optional: true - '@floating-ui/react@0.27.12(react-dom@19.2.8(react@19.2.8))(react@19.2.8)': + '@img/sharp-webcontainers-wasm32@0.35.2': dependencies: - '@floating-ui/react-dom': 2.1.8(react-dom@19.2.8(react@19.2.8))(react@19.2.8) - '@floating-ui/utils': 0.2.11 - react: 19.2.8 - react-dom: 19.2.8(react@19.2.8) - tabbable: 6.5.0 - - '@floating-ui/utils@0.2.11': {} - - '@fontsource-variable/bricolage-grotesque@5.3.0': {} - - '@fontsource-variable/inter@5.3.0': {} + '@img/sharp-wasm32': 0.35.2 + optional: true - '@formkit/auto-animate@0.8.4': {} + '@img/sharp-win32-arm64@0.35.2': + optional: true - '@google/genai@1.52.0(@modelcontextprotocol/sdk@1.29.0(supports-color@10.2.2)(zod@3.25.76))(bufferutil@4.1.0)(supports-color@10.2.2)(utf-8-validate@6.0.6)': - dependencies: - google-auth-library: 10.7.0(supports-color@10.2.2) - p-retry: 4.6.2 - protobufjs: 7.6.2 - ws: 8.21.0(bufferutil@4.1.0)(utf-8-validate@6.0.6) - optionalDependencies: - '@modelcontextprotocol/sdk': 1.29.0(supports-color@10.2.2)(zod@3.25.76) - transitivePeerDependencies: - - bufferutil - - supports-color - - utf-8-validate + '@img/sharp-win32-ia32@0.35.2': + optional: true - '@hono/node-server@1.19.15(hono@4.12.32)': - dependencies: - hono: 4.12.32 + '@img/sharp-win32-x64@0.35.2': + optional: true '@ioredis/commands@1.10.0': {} @@ -7377,6 +8583,11 @@ snapshots: '@jridgewell/resolve-uri': 3.1.2 '@jridgewell/sourcemap-codec': 1.5.5 + '@jridgewell/trace-mapping@0.3.9': + dependencies: + '@jridgewell/resolve-uri': 3.1.2 + '@jridgewell/sourcemap-codec': 1.5.5 + '@mapbox/node-pre-gyp@2.0.3(supports-color@10.2.2)': dependencies: consola: 3.4.2 @@ -7384,7 +8595,7 @@ snapshots: https-proxy-agent: 7.0.6(supports-color@10.2.2) node-fetch: 2.7.0 nopt: 8.1.0 - semver: 7.8.2 + semver: 7.8.5 tar: 7.5.16 transitivePeerDependencies: - encoding @@ -7412,6 +8623,29 @@ snapshots: transitivePeerDependencies: - supports-color + '@modelcontextprotocol/sdk@1.29.0(supports-color@10.2.2)(zod@4.4.3)': + dependencies: + '@hono/node-server': 1.19.15(hono@4.12.32) + ajv: 8.20.0 + ajv-formats: 3.0.1(ajv@8.20.0) + content-type: 1.0.5 + cors: 2.8.6 + cross-spawn: 7.0.6 + eventsource: 3.0.7 + eventsource-parser: 3.1.0 + express: 5.2.1(supports-color@10.2.2) + express-rate-limit: 8.6.0(express@5.2.1(supports-color@10.2.2))(supports-color@10.2.2) + hono: 4.12.32 + jose: 6.2.4 + json-schema-typed: 8.0.2 + pkce-challenge: 5.0.1 + raw-body: 3.0.2 + zod: 4.4.3 + zod-to-json-schema: 3.25.2(zod@4.4.3) + transitivePeerDependencies: + - supports-color + optional: true + '@noble/curves@1.9.7': dependencies: '@noble/hashes': 1.8.0 @@ -7447,6 +8681,8 @@ snapshots: '@oozcitak/util@10.0.0': {} + '@oxc-project/types@0.143.0': {} + '@parcel/watcher-android-arm64@2.5.6': optional: true @@ -7480,7 +8716,7 @@ snapshots: '@parcel/watcher-wasm@2.5.6': dependencies: is-glob: 4.0.3 - picomatch: 4.0.4 + picomatch: 4.0.5 '@parcel/watcher-win32-arm64@2.5.6': optional: true @@ -7496,7 +8732,7 @@ snapshots: detect-libc: 2.1.2 is-glob: 4.0.3 node-addon-api: 7.1.1 - picomatch: 4.0.4 + picomatch: 4.0.5 optionalDependencies: '@parcel/watcher-android-arm64': 2.5.6 '@parcel/watcher-darwin-arm64': 2.5.6 @@ -7519,6 +8755,12 @@ snapshots: dependencies: kleur: 4.1.5 + '@poppinss/dumper@0.6.5': + dependencies: + '@poppinss/colors': 4.1.6 + '@sindresorhus/is': 7.2.0 + supports-color: 10.2.2 + '@poppinss/dumper@0.7.0': dependencies: '@poppinss/colors': 4.1.6 @@ -8322,7 +9564,7 @@ snapshots: metro: 0.84.4(bufferutil@4.1.0)(supports-color@10.2.2)(utf-8-validate@6.0.6) metro-config: 0.84.4(bufferutil@4.1.0)(supports-color@10.2.2)(utf-8-validate@6.0.6) metro-core: 0.84.4 - semver: 7.8.2 + semver: 7.8.5 transitivePeerDependencies: - bufferutil - supports-color @@ -8372,8 +9614,52 @@ snapshots: optionalDependencies: '@types/react': 19.2.17 + '@rolldown/binding-android-arm64@1.2.3': + optional: true + + '@rolldown/binding-darwin-arm64@1.2.3': + optional: true + + '@rolldown/binding-darwin-x64@1.2.3': + optional: true + + '@rolldown/binding-freebsd-x64@1.2.3': + optional: true + + '@rolldown/binding-linux-arm-gnueabihf@1.2.3': + optional: true + + '@rolldown/binding-linux-arm64-gnu@1.2.3': + optional: true + + '@rolldown/binding-linux-arm64-musl@1.2.3': + optional: true + + '@rolldown/binding-linux-ppc64-gnu@1.2.3': + optional: true + + '@rolldown/binding-linux-s390x-gnu@1.2.3': + optional: true + + '@rolldown/binding-linux-x64-gnu@1.2.3': + optional: true + + '@rolldown/binding-linux-x64-musl@1.2.3': + optional: true + + '@rolldown/binding-openharmony-arm64@1.2.3': + optional: true + + '@rolldown/binding-win32-arm64-msvc@1.2.3': + optional: true + + '@rolldown/binding-win32-x64-msvc@1.2.3': + optional: true + '@rolldown/pluginutils@1.0.0-rc.3': {} + '@rolldown/pluginutils@1.0.1': {} + '@rollup/plugin-alias@6.0.0(rollup@4.61.1)': optionalDependencies: rollup: 4.61.1 @@ -8383,10 +9669,10 @@ snapshots: '@rollup/pluginutils': 5.4.0(rollup@4.61.1) commondir: 1.0.1 estree-walker: 2.0.2 - fdir: 6.5.0(picomatch@4.0.4) + fdir: 6.5.0(picomatch@4.0.5) is-reference: 1.2.1 magic-string: 0.30.21 - picomatch: 4.0.4 + picomatch: 4.0.5 optionalDependencies: rollup: 4.61.1 @@ -8425,7 +9711,7 @@ snapshots: dependencies: serialize-javascript: 7.0.5 smob: 1.6.2 - terser: 5.48.0 + terser: 5.49.0 optionalDependencies: rollup: 4.61.1 @@ -8433,7 +9719,7 @@ snapshots: dependencies: '@types/estree': 1.0.9 estree-walker: 2.0.2 - picomatch: 4.0.4 + picomatch: 4.0.5 optionalDependencies: rollup: 4.61.1 @@ -9221,6 +10507,8 @@ snapshots: '@speed-highlight/core@1.2.15': {} + '@stablelib/base64@1.0.1': {} + '@stylexjs/stylex@0.19.0': dependencies: css-mediaquery: 0.1.2 @@ -9304,12 +10592,12 @@ snapshots: postcss: 8.5.23 tailwindcss: 4.3.3 - '@tailwindcss/vite@4.3.3(vite@7.3.6(@types/node@22.20.1)(jiti@2.7.0)(lightningcss@1.32.0)(terser@5.49.0)(yaml@2.9.0))': + '@tailwindcss/vite@4.3.3(vite@7.3.6(@types/node@22.20.1)(jiti@2.7.0)(lightningcss@1.32.0)(terser@5.49.0)(tsx@4.23.11)(yaml@2.9.0))': dependencies: '@tailwindcss/node': 4.3.3 '@tailwindcss/oxide': 4.3.3 tailwindcss: 4.3.3 - vite: 7.3.6(@types/node@22.20.1)(jiti@2.7.0)(lightningcss@1.32.0)(terser@5.49.0)(yaml@2.9.0) + vite: 7.3.6(@types/node@22.20.1)(jiti@2.7.0)(lightningcss@1.32.0)(terser@5.49.0)(tsx@4.23.11)(yaml@2.9.0) '@tanstack/devtools-client@0.0.3': dependencies: @@ -9350,11 +10638,11 @@ snapshots: '@tanstack/history@1.162.0': {} - '@tanstack/nitro-v2-vite-plugin@1.155.0(srvx@0.8.16)(supports-color@10.2.2)(vite@7.3.6(@types/node@22.20.1)(jiti@2.7.0)(lightningcss@1.32.0)(terser@5.49.0)(yaml@2.9.0))': + '@tanstack/nitro-v2-vite-plugin@1.155.0(@upstash/redis@1.38.2)(drizzle-orm@0.45.2(@cloudflare/workers-types@5.20260808.1)(@upstash/redis@1.38.2))(rolldown@1.2.3)(srvx@0.11.22)(supports-color@10.2.2)(vite@7.3.6(@types/node@22.20.1)(jiti@2.7.0)(lightningcss@1.32.0)(terser@5.49.0)(tsx@4.23.11)(yaml@2.9.0))': dependencies: - nitropack: 2.13.4(srvx@0.8.16)(supports-color@10.2.2) + nitropack: 2.13.4(@upstash/redis@1.38.2)(drizzle-orm@0.45.2(@cloudflare/workers-types@5.20260808.1)(@upstash/redis@1.38.2))(rolldown@1.2.3)(srvx@0.11.22)(supports-color@10.2.2) pathe: 2.0.3 - vite: 7.3.6(@types/node@22.20.1)(jiti@2.7.0)(lightningcss@1.32.0)(terser@5.49.0)(yaml@2.9.0) + vite: 7.3.6(@types/node@22.20.1)(jiti@2.7.0)(lightningcss@1.32.0)(terser@5.49.0)(tsx@4.23.11)(yaml@2.9.0) transitivePeerDependencies: - '@azure/app-configuration' - '@azure/cosmos' @@ -9464,15 +10752,15 @@ snapshots: react: 19.2.8 react-dom: 19.2.8(react@19.2.8) - '@tanstack/react-start-rsc@0.1.31(crossws@0.4.5(srvx@0.8.16))(react-dom@19.2.8(react@19.2.8))(react@19.2.8)(supports-color@10.2.2)(vite@7.3.6(@types/node@22.20.1)(jiti@2.7.0)(lightningcss@1.32.0)(terser@5.49.0)(yaml@2.9.0))': + '@tanstack/react-start-rsc@0.1.31(crossws@0.4.10(srvx@0.11.22))(react-dom@19.2.8(react@19.2.8))(react@19.2.8)(supports-color@10.2.2)(vite@7.3.6(@types/node@22.20.1)(jiti@2.7.0)(lightningcss@1.32.0)(terser@5.49.0)(tsx@4.23.11)(yaml@2.9.0))': dependencies: '@tanstack/react-router': 1.170.18(react-dom@19.2.8(react@19.2.8))(react@19.2.8) '@tanstack/router-core': 1.171.15 '@tanstack/router-utils': 1.162.2(supports-color@10.2.2) '@tanstack/start-client-core': 1.170.14 '@tanstack/start-fn-stubs': 1.162.0 - '@tanstack/start-plugin-core': 1.171.24(@tanstack/react-router@1.170.18(react-dom@19.2.8(react@19.2.8))(react@19.2.8))(crossws@0.4.5(srvx@0.8.16))(supports-color@10.2.2)(vite@7.3.6(@types/node@22.20.1)(jiti@2.7.0)(lightningcss@1.32.0)(terser@5.49.0)(yaml@2.9.0)) - '@tanstack/start-server-core': 1.169.17(crossws@0.4.5(srvx@0.8.16)) + '@tanstack/start-plugin-core': 1.171.24(@tanstack/react-router@1.170.18(react-dom@19.2.8(react@19.2.8))(react@19.2.8))(crossws@0.4.10(srvx@0.11.22))(supports-color@10.2.2)(vite@7.3.6(@types/node@22.20.1)(jiti@2.7.0)(lightningcss@1.32.0)(terser@5.49.0)(tsx@4.23.11)(yaml@2.9.0)) + '@tanstack/start-server-core': 1.169.17(crossws@0.4.10(srvx@0.11.22)) '@tanstack/start-storage-context': 1.167.17 pathe: 2.0.3 react: 19.2.8 @@ -9485,31 +10773,31 @@ snapshots: - vite-plugin-solid - webpack - '@tanstack/react-start-server@1.167.22(crossws@0.4.5(srvx@0.8.16))(react-dom@19.2.8(react@19.2.8))(react@19.2.8)': + '@tanstack/react-start-server@1.167.22(crossws@0.4.10(srvx@0.11.22))(react-dom@19.2.8(react@19.2.8))(react@19.2.8)': dependencies: '@tanstack/react-router': 1.170.18(react-dom@19.2.8(react@19.2.8))(react@19.2.8) '@tanstack/router-core': 1.171.15 - '@tanstack/start-server-core': 1.169.17(crossws@0.4.5(srvx@0.8.16)) + '@tanstack/start-server-core': 1.169.17(crossws@0.4.10(srvx@0.11.22)) react: 19.2.8 react-dom: 19.2.8(react@19.2.8) transitivePeerDependencies: - crossws - '@tanstack/react-start@1.168.32(crossws@0.4.5(srvx@0.8.16))(react-dom@19.2.8(react@19.2.8))(react@19.2.8)(supports-color@10.2.2)(vite@7.3.6(@types/node@22.20.1)(jiti@2.7.0)(lightningcss@1.32.0)(terser@5.49.0)(yaml@2.9.0))': + '@tanstack/react-start@1.168.32(crossws@0.4.10(srvx@0.11.22))(react-dom@19.2.8(react@19.2.8))(react@19.2.8)(supports-color@10.2.2)(vite@7.3.6(@types/node@22.20.1)(jiti@2.7.0)(lightningcss@1.32.0)(terser@5.49.0)(tsx@4.23.11)(yaml@2.9.0))': dependencies: '@tanstack/react-router': 1.170.18(react-dom@19.2.8(react@19.2.8))(react@19.2.8) '@tanstack/react-start-client': 1.168.16(react-dom@19.2.8(react@19.2.8))(react@19.2.8) - '@tanstack/react-start-rsc': 0.1.31(crossws@0.4.5(srvx@0.8.16))(react-dom@19.2.8(react@19.2.8))(react@19.2.8)(supports-color@10.2.2)(vite@7.3.6(@types/node@22.20.1)(jiti@2.7.0)(lightningcss@1.32.0)(terser@5.49.0)(yaml@2.9.0)) - '@tanstack/react-start-server': 1.167.22(crossws@0.4.5(srvx@0.8.16))(react-dom@19.2.8(react@19.2.8))(react@19.2.8) + '@tanstack/react-start-rsc': 0.1.31(crossws@0.4.10(srvx@0.11.22))(react-dom@19.2.8(react@19.2.8))(react@19.2.8)(supports-color@10.2.2)(vite@7.3.6(@types/node@22.20.1)(jiti@2.7.0)(lightningcss@1.32.0)(terser@5.49.0)(tsx@4.23.11)(yaml@2.9.0)) + '@tanstack/react-start-server': 1.167.22(crossws@0.4.10(srvx@0.11.22))(react-dom@19.2.8(react@19.2.8))(react@19.2.8) '@tanstack/router-utils': 1.162.2(supports-color@10.2.2) '@tanstack/start-client-core': 1.170.14 - '@tanstack/start-plugin-core': 1.171.24(@tanstack/react-router@1.170.18(react-dom@19.2.8(react@19.2.8))(react@19.2.8))(crossws@0.4.5(srvx@0.8.16))(supports-color@10.2.2)(vite@7.3.6(@types/node@22.20.1)(jiti@2.7.0)(lightningcss@1.32.0)(terser@5.49.0)(yaml@2.9.0)) - '@tanstack/start-server-core': 1.169.17(crossws@0.4.5(srvx@0.8.16)) + '@tanstack/start-plugin-core': 1.171.24(@tanstack/react-router@1.170.18(react-dom@19.2.8(react@19.2.8))(react@19.2.8))(crossws@0.4.10(srvx@0.11.22))(supports-color@10.2.2)(vite@7.3.6(@types/node@22.20.1)(jiti@2.7.0)(lightningcss@1.32.0)(terser@5.49.0)(tsx@4.23.11)(yaml@2.9.0)) + '@tanstack/start-server-core': 1.169.17(crossws@0.4.10(srvx@0.11.22)) pathe: 2.0.3 react: 19.2.8 react-dom: 19.2.8(react@19.2.8) optionalDependencies: - vite: 7.3.6(@types/node@22.20.1)(jiti@2.7.0)(lightningcss@1.32.0)(terser@5.49.0)(yaml@2.9.0) + vite: 7.3.6(@types/node@22.20.1)(jiti@2.7.0)(lightningcss@1.32.0)(terser@5.49.0)(tsx@4.23.11)(yaml@2.9.0) transitivePeerDependencies: - '@rspack/core' - crossws @@ -9553,7 +10841,7 @@ snapshots: transitivePeerDependencies: - supports-color - '@tanstack/router-plugin@1.168.23(@tanstack/react-router@1.170.18(react-dom@19.2.8(react@19.2.8))(react@19.2.8))(supports-color@10.2.2)(vite@7.3.6(@types/node@22.20.1)(jiti@2.7.0)(lightningcss@1.32.0)(terser@5.49.0)(yaml@2.9.0))': + '@tanstack/router-plugin@1.168.23(@tanstack/react-router@1.170.18(react-dom@19.2.8(react@19.2.8))(react@19.2.8))(supports-color@10.2.2)(vite@7.3.6(@types/node@22.20.1)(jiti@2.7.0)(lightningcss@1.32.0)(terser@5.49.0)(tsx@4.23.11)(yaml@2.9.0))': dependencies: '@babel/core': 7.29.7(supports-color@10.2.2) '@babel/template': 7.29.7 @@ -9566,7 +10854,7 @@ snapshots: zod: 4.4.3 optionalDependencies: '@tanstack/react-router': 1.170.18(react-dom@19.2.8(react@19.2.8))(react@19.2.8) - vite: 7.3.6(@types/node@22.20.1)(jiti@2.7.0)(lightningcss@1.32.0)(terser@5.49.0)(yaml@2.9.0) + vite: 7.3.6(@types/node@22.20.1)(jiti@2.7.0)(lightningcss@1.32.0)(terser@5.49.0)(tsx@4.23.11)(yaml@2.9.0) transitivePeerDependencies: - supports-color @@ -9597,30 +10885,30 @@ snapshots: '@tanstack/start-fn-stubs@1.162.0': {} - '@tanstack/start-plugin-core@1.171.24(@tanstack/react-router@1.170.18(react-dom@19.2.8(react@19.2.8))(react@19.2.8))(crossws@0.4.5(srvx@0.8.16))(supports-color@10.2.2)(vite@7.3.6(@types/node@22.20.1)(jiti@2.7.0)(lightningcss@1.32.0)(terser@5.49.0)(yaml@2.9.0))': + '@tanstack/start-plugin-core@1.171.24(@tanstack/react-router@1.170.18(react-dom@19.2.8(react@19.2.8))(react@19.2.8))(crossws@0.4.10(srvx@0.11.22))(supports-color@10.2.2)(vite@7.3.6(@types/node@22.20.1)(jiti@2.7.0)(lightningcss@1.32.0)(terser@5.49.0)(tsx@4.23.11)(yaml@2.9.0))': dependencies: '@babel/code-frame': 7.27.1 '@babel/core': 7.29.7(supports-color@10.2.2) '@babel/types': 7.29.7 '@tanstack/router-core': 1.171.15 '@tanstack/router-generator': 1.167.21(supports-color@10.2.2) - '@tanstack/router-plugin': 1.168.23(@tanstack/react-router@1.170.18(react-dom@19.2.8(react@19.2.8))(react@19.2.8))(supports-color@10.2.2)(vite@7.3.6(@types/node@22.20.1)(jiti@2.7.0)(lightningcss@1.32.0)(terser@5.49.0)(yaml@2.9.0)) + '@tanstack/router-plugin': 1.168.23(@tanstack/react-router@1.170.18(react-dom@19.2.8(react@19.2.8))(react@19.2.8))(supports-color@10.2.2)(vite@7.3.6(@types/node@22.20.1)(jiti@2.7.0)(lightningcss@1.32.0)(terser@5.49.0)(tsx@4.23.11)(yaml@2.9.0)) '@tanstack/router-utils': 1.162.2(supports-color@10.2.2) - '@tanstack/start-server-core': 1.169.17(crossws@0.4.5(srvx@0.8.16)) + '@tanstack/start-server-core': 1.169.17(crossws@0.4.10(srvx@0.11.22)) exsolve: 1.0.8 lightningcss: 1.32.0 pathe: 2.0.3 picomatch: 4.0.4 seroval: 1.5.4 source-map: 0.7.6 - srvx: 0.11.16 + srvx: 0.11.22 tinyglobby: 0.2.17 ufo: 1.6.4 - vitefu: 1.1.3(vite@7.3.6(@types/node@22.20.1)(jiti@2.7.0)(lightningcss@1.32.0)(terser@5.49.0)(yaml@2.9.0)) + vitefu: 1.1.3(vite@7.3.6(@types/node@22.20.1)(jiti@2.7.0)(lightningcss@1.32.0)(terser@5.49.0)(tsx@4.23.11)(yaml@2.9.0)) xmlbuilder2: 4.0.3 zod: 4.4.3 optionalDependencies: - vite: 7.3.6(@types/node@22.20.1)(jiti@2.7.0)(lightningcss@1.32.0)(terser@5.49.0)(yaml@2.9.0) + vite: 7.3.6(@types/node@22.20.1)(jiti@2.7.0)(lightningcss@1.32.0)(terser@5.49.0)(tsx@4.23.11)(yaml@2.9.0) transitivePeerDependencies: - '@tanstack/react-router' - crossws @@ -9628,14 +10916,14 @@ snapshots: - vite-plugin-solid - webpack - '@tanstack/start-server-core@1.169.17(crossws@0.4.5(srvx@0.8.16))': + '@tanstack/start-server-core@1.169.17(crossws@0.4.10(srvx@0.11.22))': dependencies: '@tanstack/history': 1.162.0 '@tanstack/router-core': 1.171.15 '@tanstack/start-client-core': 1.170.14 '@tanstack/start-storage-context': 1.167.17 fetchdts: 0.1.7 - h3-v2: h3@2.0.1-rc.20(crossws@0.4.5(srvx@0.8.16)) + h3-v2: h3@2.0.1-rc.20(crossws@0.4.10(srvx@0.11.22)) seroval: 1.5.4 transitivePeerDependencies: - crossws @@ -9743,6 +11031,19 @@ snapshots: react: 19.2.8 react-dom: 19.2.8(react@19.2.8) + '@upstash/core-analytics@0.0.10': + dependencies: + '@upstash/redis': 1.38.2 + + '@upstash/ratelimit@2.0.8(@upstash/redis@1.38.2)': + dependencies: + '@upstash/core-analytics': 0.0.10 + '@upstash/redis': 1.38.2 + + '@upstash/redis@1.38.2': + dependencies: + uncrypto: 0.1.3 + '@vercel/nft@1.10.2(rollup@4.61.1)(supports-color@10.2.2)': dependencies: '@mapbox/node-pre-gyp': 2.0.3(supports-color@10.2.2) @@ -9755,7 +11056,7 @@ snapshots: glob: 13.0.6 graceful-fs: 4.2.11 node-gyp-build: 4.8.4 - picomatch: 4.0.4 + picomatch: 4.0.5 resolve-from: 5.0.0 transitivePeerDependencies: - encoding @@ -9766,7 +11067,7 @@ snapshots: optionalDependencies: react: 19.2.8 - '@vitejs/plugin-react@5.2.0(supports-color@10.2.2)(vite@7.3.6(@types/node@22.20.1)(jiti@2.7.0)(lightningcss@1.32.0)(terser@5.49.0)(yaml@2.9.0))': + '@vitejs/plugin-react@5.2.0(supports-color@10.2.2)(vite@7.3.6(@types/node@22.20.1)(jiti@2.7.0)(lightningcss@1.32.0)(terser@5.49.0)(tsx@4.23.11)(yaml@2.9.0))': dependencies: '@babel/core': 7.29.7(supports-color@10.2.2) '@babel/plugin-transform-react-jsx-self': 7.29.7(@babel/core@7.29.7(supports-color@10.2.2)) @@ -9774,7 +11075,7 @@ snapshots: '@rolldown/pluginutils': 1.0.0-rc.3 '@types/babel__core': 7.20.5 react-refresh: 0.18.0 - vite: 7.3.6(@types/node@22.20.1)(jiti@2.7.0)(lightningcss@1.32.0)(terser@5.49.0)(yaml@2.9.0) + vite: 7.3.6(@types/node@22.20.1)(jiti@2.7.0)(lightningcss@1.32.0)(terser@5.49.0)(tsx@4.23.11)(yaml@2.9.0) transitivePeerDependencies: - supports-color @@ -9991,6 +11292,8 @@ snapshots: dependencies: file-uri-to-path: 1.0.0 + blake3-wasm@2.1.5: {} + bn.js@5.2.5: {} body-parser@2.3.0(supports-color@10.2.2): @@ -10073,7 +11376,7 @@ snapshots: confbox: 0.2.4 defu: 6.1.7 dotenv: 17.4.2 - exsolve: 1.0.8 + exsolve: 1.1.1 giget: 3.2.0 jiti: 2.7.0 ohash: 2.0.11 @@ -10228,7 +11531,7 @@ snapshots: json-schema-typed: 7.0.3 onetime: 5.1.2 pkg-up: 3.1.0 - semver: 7.8.2 + semver: 7.8.5 confbox@0.1.8: {} @@ -10277,6 +11580,8 @@ snapshots: cookie@0.7.2: {} + cookie@1.1.1: {} + copy-to-clipboard@3.3.3: dependencies: toggle-selection: 1.0.6 @@ -10326,9 +11631,9 @@ snapshots: dependencies: uncrypto: 0.1.3 - crossws@0.4.5(srvx@0.8.16): + crossws@0.4.10(srvx@0.11.22): optionalDependencies: - srvx: 0.8.16 + srvx: 0.11.22 css-mediaquery@0.1.2: {} @@ -10357,7 +11662,9 @@ snapshots: whatwg-mimetype: 5.0.0 whatwg-url: 15.1.0 - db0@0.3.4: {} + db0@0.3.4(drizzle-orm@0.45.2(@cloudflare/workers-types@5.20260808.1)(@upstash/redis@1.38.2)): + optionalDependencies: + drizzle-orm: 0.45.2(@cloudflare/workers-types@5.20260808.1)(@upstash/redis@1.38.2) debounce-fn@4.0.0: dependencies: @@ -10428,6 +11735,18 @@ snapshots: dotenv@17.4.2: {} + drizzle-kit@0.31.10: + dependencies: + '@drizzle-team/brocli': 0.10.2 + '@esbuild-kit/esm-loader': 2.6.5 + esbuild: 0.25.12 + tsx: 4.23.11 + + drizzle-orm@0.45.2(@cloudflare/workers-types@5.20260808.1)(@upstash/redis@1.38.2): + optionalDependencies: + '@cloudflare/workers-types': 5.20260808.1 + '@upstash/redis': 1.38.2 + dunder-proto@1.0.1: dependencies: call-bind-apply-helpers: 1.0.2 @@ -10470,6 +11789,15 @@ snapshots: env-paths@2.2.1: {} + env-runner@0.1.16(wrangler@4.120.0(@cloudflare/workers-types@5.20260808.1)(bufferutil@4.1.0)(utf-8-validate@6.0.6)): + dependencies: + crossws: 0.4.10(srvx@0.11.22) + exsolve: 1.1.1 + httpxy: 0.5.5 + srvx: 0.11.22 + optionalDependencies: + wrangler: 4.120.0(@cloudflare/workers-types@5.20260808.1)(bufferutil@4.1.0)(utf-8-validate@6.0.6) + error-ex@1.3.4: dependencies: is-arrayish: 0.2.1 @@ -10494,6 +11822,31 @@ snapshots: dependencies: es6-promise: 4.2.8 + esbuild@0.18.20: + optionalDependencies: + '@esbuild/android-arm': 0.18.20 + '@esbuild/android-arm64': 0.18.20 + '@esbuild/android-x64': 0.18.20 + '@esbuild/darwin-arm64': 0.18.20 + '@esbuild/darwin-x64': 0.18.20 + '@esbuild/freebsd-arm64': 0.18.20 + '@esbuild/freebsd-x64': 0.18.20 + '@esbuild/linux-arm': 0.18.20 + '@esbuild/linux-arm64': 0.18.20 + '@esbuild/linux-ia32': 0.18.20 + '@esbuild/linux-loong64': 0.18.20 + '@esbuild/linux-mips64el': 0.18.20 + '@esbuild/linux-ppc64': 0.18.20 + '@esbuild/linux-riscv64': 0.18.20 + '@esbuild/linux-s390x': 0.18.20 + '@esbuild/linux-x64': 0.18.20 + '@esbuild/netbsd-x64': 0.18.20 + '@esbuild/openbsd-x64': 0.18.20 + '@esbuild/sunos-x64': 0.18.20 + '@esbuild/win32-arm64': 0.18.20 + '@esbuild/win32-ia32': 0.18.20 + '@esbuild/win32-x64': 0.18.20 + esbuild@0.25.12: optionalDependencies: '@esbuild/aix-ppc64': 0.25.12 @@ -10581,6 +11934,35 @@ snapshots: '@esbuild/win32-ia32': 0.28.0 '@esbuild/win32-x64': 0.28.0 + esbuild@0.28.1: + optionalDependencies: + '@esbuild/aix-ppc64': 0.28.1 + '@esbuild/android-arm': 0.28.1 + '@esbuild/android-arm64': 0.28.1 + '@esbuild/android-x64': 0.28.1 + '@esbuild/darwin-arm64': 0.28.1 + '@esbuild/darwin-x64': 0.28.1 + '@esbuild/freebsd-arm64': 0.28.1 + '@esbuild/freebsd-x64': 0.28.1 + '@esbuild/linux-arm': 0.28.1 + '@esbuild/linux-arm64': 0.28.1 + '@esbuild/linux-ia32': 0.28.1 + '@esbuild/linux-loong64': 0.28.1 + '@esbuild/linux-mips64el': 0.28.1 + '@esbuild/linux-ppc64': 0.28.1 + '@esbuild/linux-riscv64': 0.28.1 + '@esbuild/linux-s390x': 0.28.1 + '@esbuild/linux-x64': 0.28.1 + '@esbuild/netbsd-arm64': 0.28.1 + '@esbuild/netbsd-x64': 0.28.1 + '@esbuild/openbsd-arm64': 0.28.1 + '@esbuild/openbsd-x64': 0.28.1 + '@esbuild/openharmony-arm64': 0.28.1 + '@esbuild/sunos-x64': 0.28.1 + '@esbuild/win32-arm64': 0.28.1 + '@esbuild/win32-ia32': 0.28.1 + '@esbuild/win32-x64': 0.28.1 + escalade@3.2.0: {} escape-html@1.0.3: {} @@ -10689,6 +12071,8 @@ snapshots: exsolve@1.0.8: {} + exsolve@1.1.1: {} + extend@3.0.2: {} eyes@0.1.8: {} @@ -10705,6 +12089,8 @@ snapshots: merge2: 1.4.1 micromatch: 4.0.8 + fast-sha256@1.3.0: {} + fast-stable-stringify@1.0.0: {} fast-uri@3.1.4: {} @@ -10861,6 +12247,10 @@ snapshots: '@sec-ant/readable-stream': 0.4.1 is-stream: 4.0.1 + get-tsconfig@4.14.1: + dependencies: + resolve-pkg-maps: 1.0.0 + giget@3.2.0: {} glob-parent@5.1.2: @@ -10920,6 +12310,14 @@ snapshots: dependencies: duplexer: 0.1.2 + h3-rules@0.1.0(h3@2.0.1-rc.26(crossws@0.4.10(srvx@0.11.22)))(ocache@0.2.0): + dependencies: + h3: 2.0.1-rc.26(crossws@0.4.10(srvx@0.11.22)) + rou3: 0.9.1 + ufo: 1.6.4 + optionalDependencies: + ocache: 0.2.0 + h3@1.15.11: dependencies: cookie-es: 1.2.3 @@ -10932,21 +12330,19 @@ snapshots: ufo: 1.6.4 uncrypto: 0.1.3 - h3@2.0.1-rc.2(crossws@0.4.5(srvx@0.8.16)): + h3@2.0.1-rc.20(crossws@0.4.10(srvx@0.11.22)): dependencies: - cookie-es: 2.0.1 - fetchdts: 0.1.7 - rou3: 0.7.12 - srvx: 0.8.16 + rou3: 0.8.1 + srvx: 0.11.22 optionalDependencies: - crossws: 0.4.5(srvx@0.8.16) + crossws: 0.4.10(srvx@0.11.22) - h3@2.0.1-rc.20(crossws@0.4.5(srvx@0.8.16)): + h3@2.0.1-rc.26(crossws@0.4.10(srvx@0.11.22)): dependencies: - rou3: 0.8.1 - srvx: 0.11.16 + rou3: 0.9.1 + srvx: 0.12.5 optionalDependencies: - crossws: 0.4.5(srvx@0.8.16) + crossws: 0.4.10(srvx@0.11.22) has-flag@4.0.0: {} @@ -10978,6 +12374,8 @@ snapshots: hookable@5.5.3: {} + hookable@6.1.1: {} + html-encoding-sniffer@6.0.0(@noble/hashes@1.8.0): dependencies: '@exodus/bytes': 1.15.1(@noble/hashes@1.8.0) @@ -11008,7 +12406,7 @@ snapshots: transitivePeerDependencies: - supports-color - httpxy@0.5.3: {} + httpxy@0.5.5: {} human-signals@2.1.0: {} @@ -11357,13 +12755,13 @@ snapshots: optionalDependencies: yaml: 2.9.0 - listhen@1.10.0(srvx@0.8.16): + listhen@1.10.0(srvx@0.11.22): dependencies: '@parcel/watcher': 2.5.6 '@parcel/watcher-wasm': 2.5.6 citty: 0.2.2 consola: 3.4.2 - crossws: 0.4.5(srvx@0.8.16) + crossws: 0.4.10(srvx@0.11.22) defu: 6.1.7 get-port-please: 3.2.0 h3: 1.15.11 @@ -11652,6 +13050,18 @@ snapshots: mimic-function@5.0.1: {} + miniflare@5.20260801.1-alpha(bufferutil@4.1.0)(utf-8-validate@6.0.6): + dependencies: + '@cspotcode/source-map-support': 0.8.1 + sharp: 0.35.2 + undici: 7.29.0 + workerd: 1.20260801.1 + ws: 8.21.0(bufferutil@4.1.0)(utf-8-validate@6.0.6) + youch: 4.1.0-beta.10 + transitivePeerDependencies: + - bufferutil + - utf-8-validate + minimatch@10.2.5: dependencies: brace-expansion: 5.0.6 @@ -11691,29 +13101,32 @@ snapshots: negotiator@1.0.0: {} - nf3@0.1.12: {} + nf3@0.3.23: {} - nitro-nightly@4.0.0-20251010-091516-7cafddba(ioredis@5.11.1(supports-color@10.2.2))(lru-cache@11.5.1)(vite@7.3.6(@types/node@22.20.1)(jiti@2.7.0)(lightningcss@1.32.0)(terser@5.49.0)(yaml@2.9.0)): + nitro-nightly@3.0.1-20260731-205209-52abde8a(@upstash/redis@1.38.2)(chokidar@5.0.0)(dotenv@17.4.2)(drizzle-orm@0.45.2(@cloudflare/workers-types@5.20260808.1)(@upstash/redis@1.38.2))(giget@3.2.0)(ioredis@5.11.1(supports-color@10.2.2))(jiti@2.7.0)(lru-cache@11.5.1)(rollup@4.61.1)(vite@7.3.6(@types/node@22.20.1)(jiti@2.7.0)(lightningcss@1.32.0)(terser@5.49.0)(tsx@4.23.11)(yaml@2.9.0))(wrangler@4.120.0(@cloudflare/workers-types@5.20260808.1)(bufferutil@4.1.0)(utf-8-validate@6.0.6)): dependencies: consola: 3.4.2 - cookie-es: 2.0.1 - crossws: 0.4.5(srvx@0.8.16) - db0: 0.3.4 - esbuild: 0.25.12 - fetchdts: 0.1.7 - h3: 2.0.1-rc.2(crossws@0.4.5(srvx@0.8.16)) - jiti: 2.7.0 - nf3: 0.1.12 - ofetch: 1.5.1 + crossws: 0.4.10(srvx@0.11.22) + db0: 0.3.4(drizzle-orm@0.45.2(@cloudflare/workers-types@5.20260808.1)(@upstash/redis@1.38.2)) + env-runner: 0.1.16(wrangler@4.120.0(@cloudflare/workers-types@5.20260808.1)(bufferutil@4.1.0)(utf-8-validate@6.0.6)) + h3: 2.0.1-rc.26(crossws@0.4.10(srvx@0.11.22)) + h3-rules: 0.1.0(h3@2.0.1-rc.26(crossws@0.4.10(srvx@0.11.22)))(ocache@0.2.0) + hookable: 6.1.1 + nf3: 0.3.23 + ocache: 0.2.0 + ofetch: 2.0.0-alpha.3 ohash: 2.0.11 - rendu: 0.0.6 - rollup: 4.61.1 - srvx: 0.8.16 - undici: 7.27.2 - unenv: 2.0.0-rc.21 - unstorage: 2.0.0-alpha.3(db0@0.3.4)(ioredis@5.11.1(supports-color@10.2.2))(lru-cache@11.5.1)(ofetch@1.5.1) + rolldown: 1.2.3 + rou3: 0.9.1 + srvx: 0.11.22 + unenv: 2.0.0-rc.24 + unstorage: 2.0.0-alpha.7(@upstash/redis@1.38.2)(chokidar@5.0.0)(db0@0.3.4(drizzle-orm@0.45.2(@cloudflare/workers-types@5.20260808.1)(@upstash/redis@1.38.2)))(ioredis@5.11.1(supports-color@10.2.2))(lru-cache@11.5.1)(ofetch@2.0.0-alpha.3) optionalDependencies: - vite: 7.3.6(@types/node@22.20.1)(jiti@2.7.0)(lightningcss@1.32.0)(terser@5.49.0)(yaml@2.9.0) + dotenv: 17.4.2 + giget: 3.2.0 + jiti: 2.7.0 + rollup: 4.61.1 + vite: 7.3.6(@types/node@22.20.1)(jiti@2.7.0)(lightningcss@1.32.0)(terser@5.49.0)(tsx@4.23.11)(yaml@2.9.0) transitivePeerDependencies: - '@azure/app-configuration' - '@azure/cosmos' @@ -11726,6 +13139,7 @@ snapshots: - '@electric-sql/pglite' - '@libsql/client' - '@netlify/blobs' + - '@netlify/runtime' - '@planetscale/database' - '@upstash/redis' - '@vercel/blob' @@ -11738,12 +13152,14 @@ snapshots: - idb-keyval - ioredis - lru-cache + - miniflare - mongodb - mysql2 - sqlite3 - uploadthing + - wrangler - nitropack@2.13.4(srvx@0.8.16)(supports-color@10.2.2): + nitropack@2.13.4(@upstash/redis@1.38.2)(drizzle-orm@0.45.2(@cloudflare/workers-types@5.20260808.1)(@upstash/redis@1.38.2))(rolldown@1.2.3)(srvx@0.11.22)(supports-color@10.2.2): dependencies: '@cloudflare/kv-asset-handler': 0.4.2 '@rollup/plugin-alias': 6.0.0(rollup@4.61.1) @@ -11764,24 +13180,24 @@ snapshots: cookie-es: 2.0.1 croner: 10.0.1 crossws: 0.3.5 - db0: 0.3.4 + db0: 0.3.4(drizzle-orm@0.45.2(@cloudflare/workers-types@5.20260808.1)(@upstash/redis@1.38.2)) defu: 6.1.7 destr: 2.0.5 dot-prop: 10.1.0 - esbuild: 0.28.0 + esbuild: 0.28.1 escape-string-regexp: 5.0.0 etag: 1.8.1 - exsolve: 1.0.8 + exsolve: 1.1.1 globby: 16.2.0 gzip-size: 7.0.0 h3: 1.15.11 hookable: 5.5.3 - httpxy: 0.5.3 + httpxy: 0.5.5 ioredis: 5.11.1(supports-color@10.2.2) jiti: 2.7.0 klona: 2.0.6 knitwork: 1.3.0 - listhen: 1.10.0(srvx@0.8.16) + listhen: 1.10.0(srvx@0.11.22) magic-string: 0.30.21 magicast: 0.5.3 mime: 4.1.0 @@ -11796,9 +13212,9 @@ snapshots: pretty-bytes: 7.1.0 radix3: 1.1.2 rollup: 4.61.1 - rollup-plugin-visualizer: 7.0.1(rollup@4.61.1) + rollup-plugin-visualizer: 7.0.1(rolldown@1.2.3)(rollup@4.61.1) scule: 1.3.0 - semver: 7.8.2 + semver: 7.8.5 serve-placeholder: 2.0.2 serve-static: 2.2.1(supports-color@10.2.2) source-map: 0.7.6 @@ -11808,9 +13224,9 @@ snapshots: uncrypto: 0.1.3 unctx: 2.5.0 unenv: 2.0.0-rc.24 - unimport: 6.3.0 + unimport: 6.3.0(rolldown@1.2.3) unplugin-utils: 0.3.1 - unstorage: 1.17.5(db0@0.3.4)(ioredis@5.11.1(supports-color@10.2.2)) + unstorage: 1.17.5(@upstash/redis@1.38.2)(db0@0.3.4(drizzle-orm@0.45.2(@cloudflare/workers-types@5.20260808.1)(@upstash/redis@1.38.2)))(ioredis@5.11.1(supports-color@10.2.2)) untyped: 2.0.0 unwasm: 0.5.3 youch: 4.1.1 @@ -11901,12 +13317,18 @@ snapshots: object-treeify@1.1.33: {} + ocache@0.2.0: + dependencies: + ohash: 2.0.11 + ofetch@1.5.1: dependencies: destr: 2.0.5 node-fetch-native: 1.6.7 ufo: 1.6.4 + ofetch@2.0.0-alpha.3: {} + ohash@2.0.11: {} on-finished@2.3.0: @@ -12023,6 +13445,8 @@ snapshots: lru-cache: 11.5.1 minipass: 7.1.3 + path-to-regexp@6.3.0: {} + path-to-regexp@8.4.2: {} path-type@4.0.0: {} @@ -12052,7 +13476,7 @@ snapshots: pkg-types@2.3.1: dependencies: confbox: 0.2.4 - exsolve: 1.0.8 + exsolve: 1.1.1 pathe: 2.0.3 pkg-up@3.1.0: @@ -12277,7 +13701,7 @@ snapshots: react-refresh: 0.14.2 regenerator-runtime: 0.13.11 scheduler: 0.27.0 - semver: 7.8.2 + semver: 7.8.5 stacktrace-parser: 0.1.11 tinyglobby: 0.2.17 whatwg-fetch: 3.6.20 @@ -12366,11 +13790,6 @@ snapshots: regenerator-runtime@0.13.11: {} - rendu@0.0.6: - dependencies: - cookie-es: 2.0.1 - srvx: 0.8.16 - require-directory@2.1.1: {} require-from-string@2.0.2: {} @@ -12381,6 +13800,8 @@ snapshots: resolve-from@5.0.0: {} + resolve-pkg-maps@1.0.0: {} + resolve@1.22.12: dependencies: es-errors: 1.3.0 @@ -12397,13 +13818,34 @@ snapshots: reusify@1.1.0: {} - rollup-plugin-visualizer@7.0.1(rollup@4.61.1): + rolldown@1.2.3: + dependencies: + '@oxc-project/types': 0.143.0 + '@rolldown/pluginutils': 1.0.1 + optionalDependencies: + '@rolldown/binding-android-arm64': 1.2.3 + '@rolldown/binding-darwin-arm64': 1.2.3 + '@rolldown/binding-darwin-x64': 1.2.3 + '@rolldown/binding-freebsd-x64': 1.2.3 + '@rolldown/binding-linux-arm-gnueabihf': 1.2.3 + '@rolldown/binding-linux-arm64-gnu': 1.2.3 + '@rolldown/binding-linux-arm64-musl': 1.2.3 + '@rolldown/binding-linux-ppc64-gnu': 1.2.3 + '@rolldown/binding-linux-s390x-gnu': 1.2.3 + '@rolldown/binding-linux-x64-gnu': 1.2.3 + '@rolldown/binding-linux-x64-musl': 1.2.3 + '@rolldown/binding-openharmony-arm64': 1.2.3 + '@rolldown/binding-win32-arm64-msvc': 1.2.3 + '@rolldown/binding-win32-x64-msvc': 1.2.3 + + rollup-plugin-visualizer@7.0.1(rolldown@1.2.3)(rollup@4.61.1): dependencies: open: 11.0.0 - picomatch: 4.0.4 + picomatch: 4.0.5 source-map: 0.7.6 yargs: 18.0.0 optionalDependencies: + rolldown: 1.2.3 rollup: 4.61.1 rollup@4.61.1: @@ -12437,10 +13879,10 @@ snapshots: '@rollup/rollup-win32-x64-msvc': 4.61.1 fsevents: 2.3.3 - rou3@0.7.12: {} - rou3@0.8.1: {} + rou3@0.9.1: {} + router@2.2.0(supports-color@10.2.2): dependencies: debug: 4.4.3(supports-color@10.2.2) @@ -12490,7 +13932,7 @@ snapshots: semver@6.3.1: {} - semver@7.8.2: {} + semver@7.8.5: {} send@0.19.2(supports-color@10.2.2): dependencies: @@ -12602,6 +14044,38 @@ snapshots: - supports-color - typescript + sharp@0.35.2: + dependencies: + '@img/colour': 1.1.0 + detect-libc: 2.1.2 + semver: 7.8.5 + optionalDependencies: + '@img/sharp-darwin-arm64': 0.35.2 + '@img/sharp-darwin-x64': 0.35.2 + '@img/sharp-freebsd-wasm32': 0.35.2 + '@img/sharp-libvips-darwin-arm64': 1.3.1 + '@img/sharp-libvips-darwin-x64': 1.3.1 + '@img/sharp-libvips-linux-arm': 1.3.1 + '@img/sharp-libvips-linux-arm64': 1.3.1 + '@img/sharp-libvips-linux-ppc64': 1.3.1 + '@img/sharp-libvips-linux-riscv64': 1.3.1 + '@img/sharp-libvips-linux-s390x': 1.3.1 + '@img/sharp-libvips-linux-x64': 1.3.1 + '@img/sharp-libvips-linuxmusl-arm64': 1.3.1 + '@img/sharp-libvips-linuxmusl-x64': 1.3.1 + '@img/sharp-linux-arm': 0.35.2 + '@img/sharp-linux-arm64': 0.35.2 + '@img/sharp-linux-ppc64': 0.35.2 + '@img/sharp-linux-riscv64': 0.35.2 + '@img/sharp-linux-s390x': 0.35.2 + '@img/sharp-linux-x64': 0.35.2 + '@img/sharp-linuxmusl-arm64': 0.35.2 + '@img/sharp-linuxmusl-x64': 0.35.2 + '@img/sharp-webcontainers-wasm32': 0.35.2 + '@img/sharp-win32-arm64': 0.35.2 + '@img/sharp-win32-ia32': 0.35.2 + '@img/sharp-win32-x64': 0.35.2 + shebang-command@2.0.0: dependencies: shebang-regex: 3.0.0 @@ -12667,9 +14141,9 @@ snapshots: source-map@0.7.6: {} - srvx@0.11.16: {} + srvx@0.11.22: {} - srvx@0.8.16: {} + srvx@0.12.5: {} stackframe@1.3.4: {} @@ -12679,6 +14153,11 @@ snapshots: standard-as-callback@2.1.0: {} + standardwebhooks@1.0.0: + dependencies: + '@stablelib/base64': 1.0.1 + fast-sha256: 1.3.0 + statuses@1.5.0: {} statuses@2.0.2: {} @@ -12812,13 +14291,6 @@ snapshots: - bare-abort-controller - react-native-b4a - terser@5.48.0: - dependencies: - '@jridgewell/source-map': 0.3.11 - acorn: 8.16.0 - commander: 2.20.3 - source-map-support: 0.5.21 - terser@5.49.0: dependencies: '@jridgewell/source-map': 0.3.11 @@ -12892,6 +14364,12 @@ snapshots: tslib@2.8.1: {} + tsx@4.23.11: + dependencies: + esbuild: 0.28.1 + optionalDependencies: + fsevents: 2.3.3 + tw-animate-css@1.4.0: {} type-fest@0.7.1: {} @@ -12927,13 +14405,7 @@ snapshots: undici@7.27.2: {} - unenv@2.0.0-rc.21: - dependencies: - defu: 6.1.7 - exsolve: 1.0.8 - ohash: 2.0.11 - pathe: 2.0.3 - ufo: 1.6.4 + undici@7.29.0: {} unenv@2.0.0-rc.24: dependencies: @@ -12943,7 +14415,7 @@ snapshots: unicorn-magic@0.4.0: {} - unimport@6.3.0: + unimport@6.3.0(rolldown@1.2.3): dependencies: acorn: 8.16.0 escape-string-regexp: 5.0.0 @@ -12952,13 +14424,15 @@ snapshots: magic-string: 0.30.21 mlly: 1.8.2 pathe: 2.0.3 - picomatch: 4.0.4 + picomatch: 4.0.5 pkg-types: 2.3.1 scule: 1.3.0 strip-literal: 3.1.0 tinyglobby: 0.2.17 unplugin: 3.0.0 unplugin-utils: 0.3.1 + optionalDependencies: + rolldown: 1.2.3 universalify@2.0.1: {} @@ -12969,13 +14443,13 @@ snapshots: unplugin-utils@0.3.1: dependencies: pathe: 2.0.3 - picomatch: 4.0.4 + picomatch: 4.0.5 unplugin@2.3.11: dependencies: '@jridgewell/remapping': 2.3.5 acorn: 8.16.0 - picomatch: 4.0.4 + picomatch: 4.0.5 webpack-virtual-modules: 0.6.2 unplugin@3.0.0: @@ -12984,7 +14458,7 @@ snapshots: picomatch: 4.0.4 webpack-virtual-modules: 0.6.2 - unstorage@1.17.5(db0@0.3.4)(ioredis@5.11.1(supports-color@10.2.2)): + unstorage@1.17.5(@upstash/redis@1.38.2)(db0@0.3.4(drizzle-orm@0.45.2(@cloudflare/workers-types@5.20260808.1)(@upstash/redis@1.38.2)))(ioredis@5.11.1(supports-color@10.2.2)): dependencies: anymatch: 3.1.3 chokidar: 5.0.0 @@ -12995,15 +14469,18 @@ snapshots: ofetch: 1.5.1 ufo: 1.6.4 optionalDependencies: - db0: 0.3.4 + '@upstash/redis': 1.38.2 + db0: 0.3.4(drizzle-orm@0.45.2(@cloudflare/workers-types@5.20260808.1)(@upstash/redis@1.38.2)) ioredis: 5.11.1(supports-color@10.2.2) - unstorage@2.0.0-alpha.3(db0@0.3.4)(ioredis@5.11.1(supports-color@10.2.2))(lru-cache@11.5.1)(ofetch@1.5.1): + unstorage@2.0.0-alpha.7(@upstash/redis@1.38.2)(chokidar@5.0.0)(db0@0.3.4(drizzle-orm@0.45.2(@cloudflare/workers-types@5.20260808.1)(@upstash/redis@1.38.2)))(ioredis@5.11.1(supports-color@10.2.2))(lru-cache@11.5.1)(ofetch@2.0.0-alpha.3): optionalDependencies: - db0: 0.3.4 + '@upstash/redis': 1.38.2 + chokidar: 5.0.0 + db0: 0.3.4(drizzle-orm@0.45.2(@cloudflare/workers-types@5.20260808.1)(@upstash/redis@1.38.2)) ioredis: 5.11.1(supports-color@10.2.2) lru-cache: 11.5.1 - ofetch: 1.5.1 + ofetch: 2.0.0-alpha.3 untun@0.1.3: dependencies: @@ -13021,7 +14498,7 @@ snapshots: unwasm@0.5.3: dependencies: - exsolve: 1.0.8 + exsolve: 1.1.1 knitwork: 1.3.0 magic-string: 0.30.21 mlly: 1.8.2 @@ -13076,18 +14553,18 @@ snapshots: vary@1.1.2: {} - vite-tsconfig-paths@5.1.4(supports-color@10.2.2)(typescript@5.9.3)(vite@7.3.6(@types/node@22.20.1)(jiti@2.7.0)(lightningcss@1.32.0)(terser@5.49.0)(yaml@2.9.0)): + vite-tsconfig-paths@5.1.4(supports-color@10.2.2)(typescript@5.9.3)(vite@7.3.6(@types/node@22.20.1)(jiti@2.7.0)(lightningcss@1.32.0)(terser@5.49.0)(tsx@4.23.11)(yaml@2.9.0)): dependencies: debug: 4.4.3(supports-color@10.2.2) globrex: 0.1.2 tsconfck: 3.1.6(typescript@5.9.3) optionalDependencies: - vite: 7.3.6(@types/node@22.20.1)(jiti@2.7.0)(lightningcss@1.32.0)(terser@5.49.0)(yaml@2.9.0) + vite: 7.3.6(@types/node@22.20.1)(jiti@2.7.0)(lightningcss@1.32.0)(terser@5.49.0)(tsx@4.23.11)(yaml@2.9.0) transitivePeerDependencies: - supports-color - typescript - vite@7.3.6(@types/node@22.20.1)(jiti@2.7.0)(lightningcss@1.32.0)(terser@5.49.0)(yaml@2.9.0): + vite@7.3.6(@types/node@22.20.1)(jiti@2.7.0)(lightningcss@1.32.0)(terser@5.49.0)(tsx@4.23.11)(yaml@2.9.0): dependencies: esbuild: 0.28.0 fdir: 6.5.0(picomatch@4.0.4) @@ -13101,11 +14578,12 @@ snapshots: jiti: 2.7.0 lightningcss: 1.32.0 terser: 5.49.0 + tsx: 4.23.11 yaml: 2.9.0 - vitefu@1.1.3(vite@7.3.6(@types/node@22.20.1)(jiti@2.7.0)(lightningcss@1.32.0)(terser@5.49.0)(yaml@2.9.0)): + vitefu@1.1.3(vite@7.3.6(@types/node@22.20.1)(jiti@2.7.0)(lightningcss@1.32.0)(terser@5.49.0)(tsx@4.23.11)(yaml@2.9.0)): optionalDependencies: - vite: 7.3.6(@types/node@22.20.1)(jiti@2.7.0)(lightningcss@1.32.0)(terser@5.49.0)(yaml@2.9.0) + vite: 7.3.6(@types/node@22.20.1)(jiti@2.7.0)(lightningcss@1.32.0)(terser@5.49.0)(tsx@4.23.11)(yaml@2.9.0) vlq@1.0.1: {} @@ -13151,6 +14629,31 @@ snapshots: dependencies: isexe: 3.1.5 + workerd@1.20260801.1: + optionalDependencies: + '@cloudflare/workerd-darwin-64': 1.20260801.1 + '@cloudflare/workerd-darwin-arm64': 1.20260801.1 + '@cloudflare/workerd-linux-64': 1.20260801.1 + '@cloudflare/workerd-linux-arm64': 1.20260801.1 + '@cloudflare/workerd-windows-64': 1.20260801.1 + + wrangler@4.120.0(@cloudflare/workers-types@5.20260808.1)(bufferutil@4.1.0)(utf-8-validate@6.0.6): + dependencies: + '@cloudflare/kv-asset-handler': 0.5.0 + '@cloudflare/unenv-preset': 2.16.1(unenv@2.0.0-rc.24)(workerd@1.20260801.1) + blake3-wasm: 2.1.5 + esbuild: 0.28.1 + miniflare: 5.20260801.1-alpha(bufferutil@4.1.0)(utf-8-validate@6.0.6) + path-to-regexp: 6.3.0 + unenv: 2.0.0-rc.24 + workerd: 1.20260801.1 + optionalDependencies: + '@cloudflare/workers-types': 5.20260808.1 + fsevents: 2.3.3 + transitivePeerDependencies: + - bufferutil + - utf-8-validate + wrap-ansi@6.2.0: dependencies: ansi-styles: 4.3.0 @@ -13268,6 +14771,14 @@ snapshots: '@poppinss/exception': 1.2.3 error-stack-parser-es: 1.0.5 + youch@4.1.0-beta.10: + dependencies: + '@poppinss/colors': 4.1.6 + '@poppinss/dumper': 0.6.5 + '@speed-highlight/core': 1.2.15 + cookie: 1.1.1 + youch-core: 0.3.3 + youch@4.1.1: dependencies: '@poppinss/colors': 4.1.6 @@ -13286,6 +14797,11 @@ snapshots: dependencies: zod: 3.25.76 + zod-to-json-schema@3.25.2(zod@4.4.3): + dependencies: + zod: 4.4.3 + optional: true + zod@3.25.76: {} zod@4.4.3: {} diff --git a/pnpm-workspace.yaml b/pnpm-workspace.yaml index afc881e4..86e7425b 100644 --- a/pnpm-workspace.yaml +++ b/pnpm-workspace.yaml @@ -17,3 +17,4 @@ allowBuilds: esbuild: true protobufjs: true utf-8-validate: false + workerd: false diff --git a/server/routes/api/health.ts b/server/routes/api/health.ts new file mode 100644 index 00000000..6f4c5aa8 --- /dev/null +++ b/server/routes/api/health.ts @@ -0,0 +1,63 @@ +// GET /api/health — pings D1 (select 1) and Redis (if configured) per §6.8. +import { defineEventHandler } from "h3"; +import { sql } from "drizzle-orm"; +import { getDb } from "../../../src/server/db/client"; +import { getEnv } from "../../../src/server/env"; + +type CheckResult = { ok: boolean; [key: string]: unknown }; + +export default defineEventHandler(async () => { + const env = getEnv(); + const started = Date.now(); + + const checks: Record = {}; + let ok = true; + + // D1 ping + try { + const db = getDb(env); + await db.run(sql`select 1`); + checks.db = { ok: true }; + } catch (error) { + ok = false; + checks.db = { + ok: false, + error: error instanceof Error ? error.message : String(error), + }; + } + + // Upstash ping (REST) — only when configured + const url = env.UPSTASH_REDIS_REST_URL; + const token = env.UPSTASH_REDIS_REST_TOKEN; + if ( + typeof url === "string" && + url.length > 0 && + typeof token === "string" && + token.length > 0 + ) { + try { + const res = await fetch(`${url}/ping`, { + headers: { Authorization: `Bearer ${token}` }, + }); + const body = await res.text(); + checks.redis = { ok: res.ok && body.includes("PONG"), status: res.status }; + if (!res.ok || !body.includes("PONG")) ok = false; + } catch (error) { + ok = false; + checks.redis = { + ok: false, + error: error instanceof Error ? error.message : String(error), + }; + } + } else { + checks.redis = { ok: true, skipped: "not configured" }; + } + + return { + ok, + service: "pebbly", + timestamp: new Date().toISOString(), + checks, + durationMs: Date.now() - started, + }; +}); diff --git a/server/tasks/snapshots.ts b/server/tasks/snapshots.ts new file mode 100644 index 00000000..5a7410c4 --- /dev/null +++ b/server/tasks/snapshots.ts @@ -0,0 +1,19 @@ +// Daily watchlist snapshot cron (03:00 UTC) — port of convex/crons.ts. +// +// Nitro's cloudflare-module preset wires the Worker `scheduled()` handler to +// Nitro's task system: the cron expression in wrangler.toml +// (`[triggers] crons = ["0 3 * * *"]`) is dispatched here via the +// `scheduledTasks` mapping in nitro.config.ts. +import { defineTask } from "nitro/task"; +import { createDailySnapshots } from "../../src/server/helpers/snapshots"; + +export default defineTask({ + meta: { + name: "snapshots", + description: "Create daily watchlist snapshots for all users", + }, + async run() { + await createDailySnapshots(); + return { result: "daily snapshots created" }; + }, +}); diff --git a/src/lib/tmdb.ts b/src/lib/tmdb.ts index efefefd6..550b9429 100644 --- a/src/lib/tmdb.ts +++ b/src/lib/tmdb.ts @@ -21,9 +21,9 @@ export const tmdbFetch = createFetch({ type: "linear", attempts: 2, delay: 500, - shouldRetry(context: { response?: { status: number } }) { - if (!context?.response) return true; - const status = context.response.status; + shouldRetry(response: Response | null) { + if (!response) return true; + const status = response.status; return status === 408 || status === 429 || status >= 500; }, }, diff --git a/src/server/ai.ts b/src/server/ai.ts new file mode 100644 index 00000000..24cb4e10 --- /dev/null +++ b/src/server/ai.ts @@ -0,0 +1,181 @@ +import { getEnvVar } from "./env"; + +// Port of `convex/ai.ts` — same retry/fallback logic, but Gemini is called over +// REST `fetch` instead of the `@google/genai` SDK (per the Cloudflare plan §6.7: +// the SDK may misbehave on the Workers runtime; the REST API is a drop-in +// replacement behind the same `callGeminiAI` signature). + +export interface Recommendation { + title: string; + tmdbId: number | null; + mediaType: "movie" | "tv"; + relevanceScore: number; + reasoning: string; +} + +export interface GeminiResult { + recommendations: Recommendation[]; +} + +export const MODELS_TO_TRY = [ + "gemini-3.1-flash-lite-preview", + "gemini-2.5-flash", + "gemini-2.0-flash", + "gemini-1.5-flash", +]; + +const GEMINI_REST_URL = + "https://generativelanguage.googleapis.com/v1beta/models"; + +type GeminiErrorLike = { + status?: number; + message?: string; +}; + +export function getErrorMessage(error: unknown) { + return error instanceof Error ? error.message : String(error); +} + +export function isHighDemandError(error: unknown) { + const candidate = error as GeminiErrorLike; + const message = candidate.message?.toLowerCase() ?? ""; + + return ( + candidate.status === 503 || + message.includes("high demand") || + message.includes("503") + ); +} + +export async function delay(ms: number) { + await new Promise((resolve) => setTimeout(resolve, ms)); +} + +async function generateContent( + apiKey: string, + model: string, + userPrompt: string, + systemInstruction: string, +): Promise { + const response = await fetch( + `${GEMINI_REST_URL}/${model}:generateContent?key=${encodeURIComponent(apiKey)}`, + { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ + contents: [{ parts: [{ text: userPrompt }] }], + systemInstruction: { parts: [{ text: systemInstruction }] }, + generationConfig: { responseMimeType: "application/json" }, + }), + }, + ); + + if (!response.ok) { + let message = `Gemini HTTP ${response.status}`; + try { + const body = (await response.json()) as { error?: { message?: string } }; + if (body.error?.message) message = body.error.message; + } catch { + // keep the status-only message + } + const error = new Error(message) as GeminiErrorLike; + error.status = response.status; + throw error; + } + + const data = (await response.json()) as { + candidates?: Array<{ content?: { parts?: Array<{ text?: string }> } }>; + }; + const text = data.candidates?.[0]?.content?.parts?.[0]?.text ?? ""; + return text; +} + +async function generateRecommendationResponse( + apiKey: string, + userPrompt: string, + systemInstruction: string, +) { + let highDemandError = false; + + for (const [index, model] of MODELS_TO_TRY.entries()) { + try { + const responseText = await generateContent( + apiKey, + model, + userPrompt, + systemInstruction, + ); + + if (responseText) { + return { responseText, usedModel: model, highDemandError }; + } + } catch (error) { + console.error(`Gemini model (${model}) error:`, getErrorMessage(error)); + highDemandError = highDemandError || isHighDemandError(error); + + if (index < MODELS_TO_TRY.length - 1) { + await delay(1000); + } + } + } + + return { responseText: "", usedModel: MODELS_TO_TRY[0], highDemandError }; +} + +export async function callGeminiAI( + prompt: string, + systemInstruction: string, + retries: number = 1, +): Promise<{ result?: GeminiResult; usedModel?: string; error?: string }> { + const apiKey = getEnvVar("GEMINI_API_KEY"); + if (!apiKey) { + console.error("GEMINI_API_KEY is not set"); + return { error: "api_unavailable" }; + } + + let responseText = ""; + let usedModel = MODELS_TO_TRY[0]; + let highDemandError = false; + let lastError = ""; + let success = false; + + for (let attempt = 1; attempt <= retries; attempt++) { + try { + const result = await generateRecommendationResponse( + apiKey, + prompt, + systemInstruction, + ); + if (result.responseText) { + responseText = result.responseText; + usedModel = result.usedModel; + highDemandError = result.highDemandError; + success = true; + break; + } else { + highDemandError = highDemandError || result.highDemandError; + } + } catch (error) { + lastError = getErrorMessage(error); + if (attempt < retries) { + await delay(1000); + } + } + } + + if (!success || !responseText) { + return { + error: highDemandError ? "high_demand" : lastError || "api_unavailable", + }; + } + + try { + const parsed = JSON.parse(responseText) as unknown; + if (!parsed || !Array.isArray((parsed as GeminiResult).recommendations)) { + return { error: "invalid_response" }; + } + return { result: parsed as GeminiResult, usedModel }; + } catch { + return { error: "invalid_response" }; + } +} diff --git a/src/server/auth.ts b/src/server/auth.ts new file mode 100644 index 00000000..53e8ce98 --- /dev/null +++ b/src/server/auth.ts @@ -0,0 +1,218 @@ +import { verifyToken } from "@clerk/backend"; +import { getCookie, getRequestHeader } from "@tanstack/react-start/server"; +import { and, eq } from "drizzle-orm"; +import { getDb } from "./db/client"; +import { users, watchItems } from "./db/schema"; +import { getEnv, getEnvVar } from "./env"; + +/** + * Clerk JWT payload shape (subset we rely on). `sub` is the Clerk user id. + */ +export interface ClerkSessionClaims { + sub: string; + sid?: string; + iss?: string; + public_meta?: Record | string; + publicMetadata?: Record | string; + name?: string | null; + nickname?: string | null; + email?: string | null; + picture?: string | null; + pictureUrl?: string | null; + [key: string]: unknown; +} + +/** + * Extract the Clerk session token from the incoming request. Prefers the + * `Authorization: Bearer` header (server-fn calls / API clients), then the + * standard Clerk `__session` cookie (browser same-origin calls). + */ +export function getSessionToken(): string | undefined { + const authHeader = getRequestHeader("authorization"); + if (authHeader && authHeader.toLowerCase().startsWith("bearer ")) { + return authHeader.slice(7); + } + return getCookie("__session") || getCookie("__clerk_db_jwt"); +} + +/** + * Verify the Clerk session token and return the JWT claims, or `null` when + * there is no session / the token is invalid. + */ +export async function getSessionClaims(): Promise { + const token = getSessionToken(); + if (!token) return null; + + const secretKey = getEnvVar("CLERK_SECRET_KEY"); + if (!secretKey) return null; + + try { + const claims = await verifyToken(token, { secretKey }); + return claims as ClerkSessionClaims; + } catch (error) { + console.error("Clerk token verification failed:", error); + return null; + } +} + +/** Derive the canonical tokenIdentifier (Convex Clerk format: `clerk|`). */ +export function toTokenIdentifier(sub: string): string { + return sub.startsWith("clerk|") ? sub : `clerk|${sub}`; +} + +/** Get admin flag from JWT public metadata (snake_case or camelCase claim). */ +export function getAdminFromClaims( + claims: ClerkSessionClaims | null, +): boolean | null { + if (!claims) return null; + const meta = + (claims.public_meta as Record | undefined) ?? + (claims.publicMetadata as Record | undefined); + if (meta && typeof meta === "object" && "isAdmin" in meta) { + return meta.isAdmin === true; + } + return null; +} + +/** + * Port of `convex/helpers/watch_item.ts` `getCurrentUser` — multi-format + * tokenIdentifier matching so users created under any prior format resolve. + */ +export async function findUserByClaims(claims: ClerkSessionClaims) { + const db = getDb(getEnv()); + const subject = claims.sub; + const tokenIdentifier = toTokenIdentifier(subject); + const candidates = new Set([ + tokenIdentifier, + subject, + `clerk|${subject}`, + ]); + + const allUsers = await db.select().from(users).limit(500); + + const matches = allUsers.filter( + (u) => + candidates.has(u.tokenIdentifier) || + (subject && u.tokenIdentifier.endsWith(`|${subject}`)) || + (subject && u.tokenIdentifier.endsWith(subject)), + ); + + if (matches.length === 0) return null; + if (matches.length === 1) return matches[0]; + + // Prefer the doc that already has watch items, then the exact tokenIdentifier. + for (const candidate of matches) { + const hasItems = await db + .select({ id: watchItems.id }) + .from(watchItems) + .where(eq(watchItems.userId, candidate.id)) + .limit(1); + if (hasItems.length > 0) return candidate; + } + + return ( + matches.find((u) => u.tokenIdentifier === tokenIdentifier) ?? matches[0] + ); +} + +export type AuthUser = NonNullable< + Awaited> +>; + +export type RequireUserResult = + | { user: AuthUser; claims: ClerkSessionClaims; error: null } + | { + user: null; + claims: null; + error: { ok: false; code: "UNAUTHORIZED"; message: string }; + }; + +/** + * `requireCurrentUser` port: resolves the user, creating one on first sign-in + * (identity from the verified Clerk claims). Returns a typed error result when + * unauthenticated. + */ +export async function requireUser(): Promise { + const claims = await getSessionClaims(); + if (!claims) { + return { + user: null, + claims: null, + error: { ok: false, code: "UNAUTHORIZED", message: "Unauthorized" }, + }; + } + + const db = getDb(getEnv()); + let user = await findUserByClaims(claims); + if (!user) { + const isAdmin = getAdminFromClaims(claims); + const id = crypto.randomUUID(); + await db.insert(users).values({ + id, + tokenIdentifier: toTokenIdentifier(claims.sub), + name: claims.name ?? claims.nickname ?? "Anonymous", + email: claims.email ?? undefined, + image: claims.picture ?? claims.pictureUrl ?? undefined, + isAdmin: isAdmin ?? false, + }); + user = (await db.select().from(users).where(eq(users.id, id)).limit(1))[0]; + } + + // Auto-consolidate orphaned watch items from duplicate user documents (port + // of the Convex `requireCurrentUser` consolidation step). + const subject = claims.sub; + const tokenIdentifier = toTokenIdentifier(subject); + const candidates = new Set([ + tokenIdentifier, + subject, + `clerk|${subject}`, + ]); + const allUsers = await db.select().from(users).limit(500); + const userMatches = allUsers.filter( + (u) => + candidates.has(u.tokenIdentifier) || + (subject && u.tokenIdentifier.endsWith(`|${subject}`)) || + (subject && u.tokenIdentifier.endsWith(subject)), + ); + + if (userMatches.length > 1) { + for (const dup of userMatches) { + if (dup.id === user.id) continue; + const dupItems = await db + .select() + .from(watchItems) + .where(eq(watchItems.userId, dup.id)) + .limit(500); + for (const item of dupItems) { + const existingInMain = await db + .select({ id: watchItems.id }) + .from(watchItems) + .where( + and( + eq(watchItems.userId, user.id), + eq(watchItems.tmdbId, item.tmdbId), + eq(watchItems.mediaType, item.mediaType), + ), + ) + .limit(1); + if (existingInMain.length === 0) { + await db + .update(watchItems) + .set({ userId: user.id }) + .where(eq(watchItems.id, item.id)); + } + } + } + } + + return { user, claims, error: null }; +} + +/** Shortcut: resolve the current user without creating one. */ +export async function getCurrentUser() { + const claims = await getSessionClaims(); + if (!claims) return null; + return findUserByClaims(claims); +} + +export type { Db } from "./db/client"; diff --git a/src/server/db/client.ts b/src/server/db/client.ts new file mode 100644 index 00000000..2061aaaf --- /dev/null +++ b/src/server/db/client.ts @@ -0,0 +1,38 @@ +import { upstashCache } from "drizzle-orm/cache/upstash"; +import { drizzle } from "drizzle-orm/d1"; +import type { Env } from "../env"; +import * as schema from "./schema"; + +/** + * Create a Drizzle instance bound to the Worker's D1 database, with an + * optional Upstash Redis cache layer. Cache is only wired up when the + * Upstash env vars are present (local dev without Redis still works). + * + * Opt in per query with `.$withCache({ config: { ex: 15 } })` — global caching + * is disabled so hot reads are cached explicitly. + */ +export function getDb(env: Env) { + const url = env.UPSTASH_REDIS_REST_URL; + const token = env.UPSTASH_REDIS_REST_TOKEN; + + if ( + typeof url === "string" && + url.length > 0 && + typeof token === "string" && + token.length > 0 + ) { + return drizzle(env.DB, { + schema, + cache: upstashCache({ + url, + token, + // global: false — opt in per query with .$withCache() + }), + }); + } + + return drizzle(env.DB, { schema }); +} + +export type Db = ReturnType; +export { schema }; diff --git a/src/server/db/schema.ts b/src/server/db/schema.ts new file mode 100644 index 00000000..4bf89398 --- /dev/null +++ b/src/server/db/schema.ts @@ -0,0 +1,239 @@ +import { sql } from "drizzle-orm"; +import { + check, + index, + integer, + sqliteTable, + text, + uniqueIndex, +} from "drizzle-orm/sqlite-core"; + +export const users = sqliteTable("users", { + id: text("id").primaryKey(), // Convex _id | uuid + tokenIdentifier: text("token_identifier").notNull().unique(), + name: text("name"), + image: text("image"), + email: text("email"), + roles: text("roles", { mode: "json" }).$type().default([]), + isAdmin: integer("is_admin", { mode: "boolean" }).default(false), + isBanned: integer("is_banned", { mode: "boolean" }).default(false), +}); + +export const watchItems = sqliteTable( + "watch_items", + { + id: text("id").primaryKey(), + userId: text("user_id") + .notNull() + .references(() => users.id, { onDelete: "cascade" }), + tmdbId: integer("tmdb_id").notNull(), + mediaType: text("media_type", { enum: ["movie", "tv"] }).notNull(), + inWatchlist: integer("in_watchlist", { mode: "boolean" }).default(false), + progressStatus: text("progress_status", { + enum: ["watch-later", "watching", "done", "dropped"], + }), + reaction: text("reaction", { + enum: ["loved", "liked", "mixed", "not-for-me", "recommended"], + }), + progress: integer("progress").default(0), // 0..100 + title: text("title"), + image: text("image"), + rating: integer("rating"), + releaseDate: text("release_date"), + overview: text("overview"), + updatedAt: integer("updated_at").notNull(), // ms epoch + }, + (t) => [ + uniqueIndex("watch_items_user_media_uq").on( + t.userId, + t.tmdbId, + t.mediaType, + ), + index("watch_items_user_status_idx").on(t.userId, t.progressStatus), + index("watch_items_user_updated_idx").on(t.userId, t.updatedAt), + check("watch_items_progress_range", sql`${t.progress} between 0 and 100`), + check("watch_items_rating_range", sql`${t.rating} between 0 and 10`), + ], +); + +export const watchlistSnapshots = sqliteTable( + "watchlist_snapshots", + { + id: text("id").primaryKey(), + userId: text("user_id") + .notNull() + .references(() => users.id, { onDelete: "cascade" }), + items: text("items", { mode: "json" }).$type< + Array<{ tmdbId: number; mediaType: string }> + >(), + createdAt: integer("created_at").notNull(), + }, + (t) => [index("snapshots_user_created_idx").on(t.userId, t.createdAt)], +); + +export const lists = sqliteTable( + "lists", + { + id: text("id").primaryKey(), + userId: text("user_id") + .notNull() + .references(() => users.id, { onDelete: "cascade" }), + name: text("name").notNull(), + color: text("color"), + visibility: text("visibility"), + listType: text("list_type"), + sortOrder: integer("sort_order").notNull().default(0), + createdAt: integer("created_at").notNull(), + updatedAt: integer("updated_at").notNull(), + }, + (t) => [ + uniqueIndex("lists_user_name_uq").on(t.userId, t.name), + index("lists_user_sort_idx").on(t.userId, t.sortOrder), + ], +); + +export const listItems = sqliteTable( + "list_items", + { + id: text("id").primaryKey(), + userId: text("user_id") + .notNull() + .references(() => users.id, { onDelete: "cascade" }), + listId: text("list_id") + .notNull() + .references(() => lists.id, { onDelete: "cascade" }), + tmdbId: integer("tmdb_id").notNull(), + mediaType: text("media_type", { enum: ["movie", "tv"] }).notNull(), + addedAt: integer("added_at").notNull(), + title: text("title"), + image: text("image"), + backdrop: text("backdrop"), + rating: integer("rating"), + releaseDate: text("release_date"), + overview: text("overview"), + }, + (t) => [ + uniqueIndex("list_items_list_media_uq").on(t.listId, t.tmdbId, t.mediaType), + // Covers both (user, media) and user-only lookups via leftmost prefix. + index("list_items_user_media_idx").on(t.userId, t.tmdbId, t.mediaType), + ], +); + +export const episodeProgress = sqliteTable( + "episode_progress", + { + id: text("id").primaryKey(), + userId: text("user_id") + .notNull() + .references(() => users.id, { onDelete: "cascade" }), + tmdbId: integer("tmdb_id").notNull(), + season: integer("season").notNull(), + episode: integer("episode").notNull(), + isWatched: integer("is_watched", { mode: "boolean" }) + .notNull() + .default(false), + updatedAt: integer("updated_at").notNull(), + }, + (t) => [ + // Covers (user), (user, show), and (user, show, season) — the 4 Convex indexes collapse here. + uniqueIndex("episode_user_season_ep_uq").on( + t.userId, + t.tmdbId, + t.season, + t.episode, + ), + ], +); + +export const aiRecommendations = sqliteTable( + "ai_recommendations", + { + id: text("id").primaryKey(), + userId: text("user_id") + .notNull() + .references(() => users.id, { onDelete: "cascade" }), + recommendations: text("recommendations", { mode: "json" }) + .$type() + .notNull(), + originalRecommendations: text("original_recommendations", { + mode: "json", + }).$type(), + watchlistHash: text("watchlist_hash").notNull().default(""), + inputStats: text("input_stats", { mode: "json" }) + .$type() + .notNull(), + model: text("model").notNull(), + mediaTypePreference: text("media_type_preference", { + enum: ["movie", "tv"], + }), + genrePreference: text("genre_preference"), + generationType: text("generation_type"), + verified: integer("verified", { mode: "boolean" }).default(false), + createdAt: integer("created_at").notNull(), + }, + (t) => [index("ai_recs_user_created_idx").on(t.userId, t.createdAt)], +); + +export const homepageRecommendations = sqliteTable("homepage_recommendations", { + id: text("id").primaryKey(), + userId: text("user_id") + .notNull() + .unique() + .references(() => users.id, { onDelete: "cascade" }), + recommendations: text("recommendations", { mode: "json" }) + .$type() + .notNull(), + previousRecommendations: text("previous_recommendations", { + mode: "json", + }).$type(), + lastAttemptedAt: integer("last_attempted_at").notNull().default(0), + lastUpdatedAt: integer("last_updated_at").notNull().default(0), + status: text("status").notNull().default("none"), +}); + +export const recommendationFeedback = sqliteTable( + "recommendation_feedback", + { + id: text("id").primaryKey(), + userId: text("user_id") + .notNull() + .references(() => users.id, { onDelete: "cascade" }), + tmdbId: integer("tmdb_id").notNull(), + mediaType: text("media_type", { enum: ["movie", "tv"] }).notNull(), + title: text("title").notNull(), + feedback: text("feedback", { + enum: ["like", "not_interested", "dislike"], + }).notNull(), + updatedAt: integer("updated_at").notNull(), + }, + (t) => [ + uniqueIndex("feedback_user_media_uq").on(t.userId, t.tmdbId, t.mediaType), + // (user, feedback) drives the homepage/generation feedback lookups — must not be dropped + index("feedback_user_feedback_idx").on(t.userId, t.feedback), + ], +); + +export const rolePermissions = sqliteTable( + "role_permissions", + { + role: text("role").notNull(), + feature: text("feature").notNull(), + enabled: integer("enabled", { mode: "boolean" }).notNull().default(true), + }, + (t) => [index("role_permissions_pk").on(t.role, t.feature)], +); + +export type Recommendation = { + title: string; + tmdbId: number | null; + mediaType: "movie" | "tv"; + relevanceScore: number; + reasoning: string; +}; + +export type InputStats = { + movieCount: number; + tvCount: number; + episodesWatched: number; + totalItems: number; +}; diff --git a/src/server/env.ts b/src/server/env.ts new file mode 100644 index 00000000..bcc9ff79 --- /dev/null +++ b/src/server/env.ts @@ -0,0 +1,38 @@ +import type { D1Database, Fetcher } from "@cloudflare/workers-types"; + +/** + * The Worker `env` binding. On the Cloudflare Workers runtime, Nitro's + * cloudflare-module handler sets `globalThis.__env__` on every request; in + * Node-based local dev (`vite dev`) the same names come from `process.env`. + */ +export interface Env { + DB: D1Database; + ASSETS?: Fetcher; + CLERK_SECRET_KEY?: string; + CLERK_ISSUER_URL?: string; + GEMINI_API_KEY?: string; + UPSTASH_REDIS_REST_URL?: string; + UPSTASH_REDIS_REST_TOKEN?: string; + UPSTASH_REDIS_READONLY_REST_TOKEN?: string; + CRON_SECRET?: string; + [key: string]: unknown; +} + +type WorkerEnvHolder = { __env__?: Env }; + +/** + * Read the current Worker environment bindings. Prefers the Worker runtime's + * `globalThis.__env__` (set by Nitro) and falls back to `process.env` for + * Node-based local development. + */ +export function getEnv(): Env { + const workerEnv = (globalThis as WorkerEnvHolder).__env__; + if (workerEnv) return workerEnv; + return process.env as unknown as Env; +} + +export function getEnvVar(name: keyof Env): string | undefined { + const value = getEnv()[name]; + if (typeof value === "string" && value.length > 0) return value; + return undefined; +} diff --git a/src/server/fns/admin.ts b/src/server/fns/admin.ts new file mode 100644 index 00000000..c99e2c18 --- /dev/null +++ b/src/server/fns/admin.ts @@ -0,0 +1,220 @@ +import { createServerFn } from "@tanstack/react-start"; +import { and, eq } from "drizzle-orm"; +import { type AuthUser, requireUser } from "../auth"; +import { getDb } from "../db/client"; +import { rolePermissions, users } from "../db/schema"; +import { getEnv } from "../env"; +import { + DYNAMIC_ROLES, + getUserFeatures, + isClerkAdmin, + syncRolePermissions, +} from "../rbac"; +import { + listUsersArgsSchema, + setRolePermissionArgsSchema, + setUserBannedArgsSchema, + setUserRolesArgsSchema, +} from "../schema/admin"; +import { type ApiResult, fail, ok } from "../schema/common"; + +async function requireAdmin(): Promise< + { user: AuthUser; error: null } | { user: null; error: ApiResult } +> { + const result = await requireUser(); + if (result.error) return { user: null, error: result.error }; + + const { user, claims } = result; + if (!isClerkAdmin(claims as unknown as Record, user)) { + return { + user: null, + error: fail("FORBIDDEN", "Forbidden: admin access required"), + }; + } + return { user, error: null }; +} + +export const getUserFeaturesFn = createServerFn({ method: "POST" }).handler( + async (): Promise< + ApiResult<{ + roles: string[]; + features: Record; + isAdmin: boolean; + isBanned: boolean; + }> + > => { + const claims = await requireUser(); + if (claims.error) { + return ok({ roles: [], features: {}, isAdmin: false, isBanned: false }); + } + return ok(await getUserFeatures(claims.claims, claims.user)); + }, +); + +export const getRolePermissions = createServerFn({ method: "POST" }).handler( + async (): Promise>>> => { + const admin = await requireAdmin(); + if (admin.error) return admin.error; + + const db = getDb(getEnv()); + const perms = await db.select().from(rolePermissions); + + const result: Record> = {}; + for (const role of DYNAMIC_ROLES) { + result[role] = {}; + const feature = + role === "video-player" ? "video-player" : "ai-recommendations"; + const perm = perms.find( + (p) => p.role === "global" && p.feature === feature, + ); + result[role][feature] = perm ? perm.enabled : true; + } + + return ok(result); + }, +); + +export const setRolePermission = createServerFn({ method: "POST" }) + .validator(setRolePermissionArgsSchema) + .handler(async ({ data }): Promise> => { + const admin = await requireAdmin(); + if (admin.error) return admin.error; + + if ( + data.feature !== "video-player" && + data.feature !== "ai-recommendations" + ) { + return fail("BAD_REQUEST", "Invalid feature"); + } + + const db = getDb(getEnv()); + await syncRolePermissions(db, true); + + const existing = await db + .select() + .from(rolePermissions) + .where( + and( + eq(rolePermissions.role, "global"), + eq(rolePermissions.feature, data.feature), + ), + ) + .limit(1); + + if (existing.length > 0) { + await db + .update(rolePermissions) + .set({ enabled: data.enabled }) + .where( + and( + eq(rolePermissions.role, "global"), + eq(rolePermissions.feature, data.feature), + ), + ); + } else { + await db.insert(rolePermissions).values({ + role: "global", + feature: data.feature, + enabled: data.enabled, + }); + } + + return ok({ ok: true }); + }); + +export const setUserRoles = createServerFn({ method: "POST" }) + .validator(setUserRolesArgsSchema) + .handler(async ({ data }): Promise> => { + const admin = await requireAdmin(); + if (admin.error) return admin.error; + + const db = getDb(getEnv()); + const target = await db + .select() + .from(users) + .where(eq(users.tokenIdentifier, data.tokenIdentifier)) + .limit(1); + + if (target.length === 0) return fail("NOT_FOUND", "User not found"); + + await db + .update(users) + .set({ + roles: data.roles.length > 0 ? data.roles : [], + }) + .where(eq(users.id, target[0].id)); + + return ok({ ok: true }); + }); + +export const setUserBanned = createServerFn({ method: "POST" }) + .validator(setUserBannedArgsSchema) + .handler(async ({ data }): Promise> => { + const admin = await requireAdmin(); + if (admin.error) return admin.error; + + const db = getDb(getEnv()); + const target = await db + .select() + .from(users) + .where(eq(users.tokenIdentifier, data.tokenIdentifier)) + .limit(1); + + if (target.length === 0) return fail("NOT_FOUND", "User not found"); + + if (admin.user.id === target[0].id) { + return fail("BAD_REQUEST", "Cannot ban yourself"); + } + + await db + .update(users) + .set({ isBanned: data.banned }) + .where(eq(users.id, target[0].id)); + + return ok({ ok: true }); + }); + +export const listUsers = createServerFn({ method: "POST" }) + .validator(listUsersArgsSchema) + .handler( + async ({ + data, + }): Promise< + ApiResult< + Array<{ + _id: string; + tokenIdentifier: string; + name: string; + email: string; + image: string | null; + roles: string[]; + isBanned: boolean; + isAdmin: boolean; + }> + > + > => { + const admin = await requireAdmin(); + if (admin.error) return admin.error; + + const db = getDb(getEnv()); + const rows = await db + .select() + .from(users) + .limit(data.limit ?? 200); + + return ok( + rows.map((u) => ({ + _id: u.id, + tokenIdentifier: u.tokenIdentifier, + name: u.name ?? "Anonymous", + email: u.email ?? "No email", + image: u.image, + roles: (u.roles ?? []).filter((role) => + DYNAMIC_ROLES.includes(role as (typeof DYNAMIC_ROLES)[number]), + ), + isBanned: u.isBanned ?? false, + isAdmin: isClerkAdmin(null, { isAdmin: u.isAdmin ?? false }), + })), + ); + }, + ); diff --git a/src/server/fns/import-export.ts b/src/server/fns/import-export.ts new file mode 100644 index 00000000..7486bee9 --- /dev/null +++ b/src/server/fns/import-export.ts @@ -0,0 +1,97 @@ +import { createServerFn } from "@tanstack/react-start"; +import { eq } from "drizzle-orm"; +import { requireUser } from "../auth"; +import { getDb } from "../db/client"; +import { watchItems } from "../db/schema"; +import { getEnv } from "../env"; +import { createWatchlistSnapshot } from "../helpers/snapshots"; +import { buildMetadataPatch } from "../helpers/watch-item"; +import { type ApiResult, ok } from "../schema/common"; +import { importWatchlistArgsSchema } from "../schema/import"; +import { syncEpisodeProgressRecord } from "./watchlist"; + +export const importWatchlist = createServerFn({ method: "POST" }) + .validator(importWatchlistArgsSchema) + .handler(async ({ data }): Promise> => { + const { user, error } = await requireUser(); + if (error) return error; + + const db = getDb(getEnv()); + const now = Date.now(); + const importedItems = new Map(); + + for (const item of data.items) { + importedItems.set(`${item.mediaType}:${item.tmdbId}`, item); + } + + const userWatchItems = await db + .select() + .from(watchItems) + .where(eq(watchItems.userId, user.id)); + + const existingMap = new Map(); + for (const item of userWatchItems) { + existingMap.set(`${item.mediaType}:${item.tmdbId}`, item); + } + + for (const item of importedItems.values()) { + const existing = existingMap.get(`${item.mediaType}:${item.tmdbId}`); + const progressStatus = item.progressStatus ?? "watch-later"; + const progress = + item.progress ?? + (progressStatus === "done" + ? 100 + : progressStatus === "watch-later" + ? 0 + : existing?.progress); + const metadata = buildMetadataPatch(item, existing ?? undefined); + + if (existing) { + await db + .update(watchItems) + .set({ + inWatchlist: true, + progressStatus, + progress, + reaction: item.reaction ?? existing.reaction ?? null, + updatedAt: now, + ...metadata, + }) + .where(eq(watchItems.id, existing.id)); + } else { + await db.insert(watchItems).values({ + id: crypto.randomUUID(), + userId: user.id, + tmdbId: item.tmdbId, + mediaType: item.mediaType, + inWatchlist: true, + progressStatus, + progress, + reaction: item.reaction ?? null, + updatedAt: now, + ...metadata, + }); + } + } + + const importedTvIds = new Set( + [...importedItems.values()] + .filter((item) => item.mediaType === "tv") + .map((item) => item.tmdbId), + ); + const episodeKeys = new Set(); + for (const episode of data.watchedEpisodes) { + if (!importedTvIds.has(episode.tmdbId)) continue; + const key = `${episode.tmdbId}:${episode.season}:${episode.episode}`; + if (episodeKeys.has(key)) continue; + episodeKeys.add(key); + await syncEpisodeProgressRecord( + user.id, + { ...episode, isWatched: true }, + now, + ); + } + + await createWatchlistSnapshot(db, user.id); + return ok({ imported: importedItems.size }); + }); diff --git a/src/server/fns/lists.ts b/src/server/fns/lists.ts new file mode 100644 index 00000000..53672814 --- /dev/null +++ b/src/server/fns/lists.ts @@ -0,0 +1,399 @@ +import { createServerFn } from "@tanstack/react-start"; +import { and, asc, desc, eq } from "drizzle-orm"; +import { getCurrentUser, requireUser } from "../auth"; +import { getDb } from "../db/client"; +import { listItems, lists, watchItems } from "../db/schema"; +import { getEnv } from "../env"; +import { type ApiResult, fail, ok } from "../schema/common"; +import { + createCustomListAndAddItemArgsSchema, + createCustomListArgsSchema, + deleteCustomListArgsSchema, + getItemListsArgsSchema, + getListItemsArgsSchema, + toggleListItemArgsSchema, + updateCustomListArgsSchema, +} from "../schema/lists"; + +// --------------------------------------------------------------------------- +// Reads +// --------------------------------------------------------------------------- + +export const getCustomLists = createServerFn({ method: "POST" }).handler( + async (): Promise< + ApiResult< + Array< + typeof lists.$inferSelect & { previews: string[]; itemCount: number } + > + > + > => { + const user = await getCurrentUser(); + if (!user) return ok([]); + + const db = getDb(getEnv()); + const userLists = await db + .select() + .from(lists) + .where(eq(lists.userId, user.id)) + .orderBy(asc(lists.sortOrder)) + .$withCache({ config: { ex: 15 } }); + + const allUserListItems = await db + .select() + .from(listItems) + .where(eq(listItems.userId, user.id)) + .$withCache({ config: { ex: 15 } }); + + const itemsByList = new Map(); + for (const item of allUserListItems) { + const existing = itemsByList.get(item.listId); + if (existing) { + existing.push(item); + } else { + itemsByList.set(item.listId, [item]); + } + } + + const listsWithPreviews = userLists.map((list) => { + const items = itemsByList.get(list.id) ?? []; + const previews = items + .map((item) => item.backdrop ?? item.image) + .filter((img): img is string => !!img) + .slice(0, 4); + + return { + ...list, + previews, + itemCount: items.length, + }; + }); + + return ok(listsWithPreviews); + }, +); + +export type EnrichedListItem = typeof listItems.$inferSelect & { + title: string | null; + image: string | null; + rating: number | null; + release_date: string | null; + overview: string | null; + progressStatus: string | null; + reaction: string | null; +}; + +export const getListItems = createServerFn({ method: "POST" }) + .validator(getListItemsArgsSchema) + .handler(async ({ data }): Promise> => { + const user = await getCurrentUser(); + if (!user) return ok([]); + + const db = getDb(getEnv()); + const list = await db + .select() + .from(lists) + .where(and(eq(lists.id, data.listId), eq(lists.userId, user.id))) + .limit(1) + .$withCache({ config: { ex: 15 } }); + + if (list.length === 0) return ok([]); + + const items = await db + .select() + .from(listItems) + .where( + and(eq(listItems.listId, data.listId), eq(listItems.userId, user.id)), + ) + .$withCache({ config: { ex: 15 } }); + + // Enrich with watch_item metadata (port of the N+1 loop — batch in one query). + const watchItemPromises = items.map((item) => + db + .select() + .from(watchItems) + .where( + and( + eq(watchItems.userId, user.id), + eq(watchItems.tmdbId, item.tmdbId), + eq(watchItems.mediaType, item.mediaType), + ), + ) + .limit(1), + ); + const watchItemRows = await Promise.all(watchItemPromises); + + const watchItemMap = new Map(); + for (const w of watchItemRows) { + if (w.length > 0) { + watchItemMap.set(`${w[0].tmdbId}_${w[0].mediaType}`, w); + } + } + + const enriched: EnrichedListItem[] = items.map((item) => { + const watchItem = watchItemMap.get( + `${item.tmdbId}_${item.mediaType}`, + )?.[0]; + + return { + ...item, + title: item.title ?? watchItem?.title ?? null, + image: item.image ?? watchItem?.image ?? null, + rating: item.rating ?? watchItem?.rating ?? null, + release_date: item.releaseDate ?? watchItem?.releaseDate ?? null, + overview: item.overview ?? watchItem?.overview ?? null, + progressStatus: watchItem?.progressStatus ?? null, + reaction: watchItem?.reaction ?? null, + }; + }); + + return ok(enriched); + }); + +export const getItemLists = createServerFn({ method: "POST" }) + .validator(getItemListsArgsSchema) + .handler(async ({ data }): Promise> => { + const user = await getCurrentUser(); + if (!user) return ok([]); + + const db = getDb(getEnv()); + const items = await db + .select({ listId: listItems.listId }) + .from(listItems) + .where( + and( + eq(listItems.userId, user.id), + eq(listItems.tmdbId, data.tmdbId), + eq(listItems.mediaType, data.mediaType), + ), + ) + .$withCache({ config: { ex: 15 } }); + + return ok(items.map((i) => i.listId)); + }); + +// --------------------------------------------------------------------------- +// Writes +// --------------------------------------------------------------------------- + +export const createCustomList = createServerFn({ method: "POST" }) + .validator(createCustomListArgsSchema) + .handler(async ({ data }): Promise> => { + const { user, error } = await requireUser(); + if (error) return error; + + const id = await createCustomListInner(user.id, data); + return ok(id); + }); + +export const createCustomListAndAddItem = createServerFn({ method: "POST" }) + .validator(createCustomListAndAddItemArgsSchema) + .handler(async ({ data }): Promise> => { + const { user, error } = await requireUser(); + if (error) return error; + + const listId = await createCustomListInner(user.id, { + name: data.name, + color: data.color, + visibility: data.visibility, + listType: data.listType, + }); + + await toggleListItemInner(user.id, { + listId, + tmdbId: data.tmdbId, + mediaType: data.mediaType, + title: data.title, + image: data.image, + backdrop: data.backdrop, + rating: data.rating, + release_date: data.release_date, + overview: data.overview, + }); + + return ok(listId); + }); + +export const updateCustomList = createServerFn({ method: "POST" }) + .validator(updateCustomListArgsSchema) + .handler(async ({ data }): Promise> => { + const { user, error } = await requireUser(); + if (error) return error; + + const db = getDb(getEnv()); + const list = await db + .select() + .from(lists) + .where(and(eq(lists.id, data.listId), eq(lists.userId, user.id))) + .limit(1); + if (list.length === 0) return fail("NOT_FOUND", "List not found"); + + const existing = list[0]; + + if (data.name !== undefined && data.name !== existing.name) { + const dup = await db + .select({ id: lists.id }) + .from(lists) + .where(and(eq(lists.userId, user.id), eq(lists.name, data.name))) + .limit(1); + if (dup.length > 0) + return fail("CONFLICT", "A list with this name already exists"); + } + + await db + .update(lists) + .set({ + ...(data.name !== undefined ? { name: data.name } : {}), + ...(data.color !== undefined ? { color: data.color } : {}), + ...(data.visibility !== undefined + ? { visibility: data.visibility } + : {}), + ...(data.listType !== undefined ? { listType: data.listType } : {}), + updatedAt: Date.now(), + }) + .where(eq(lists.id, existing.id)); + + return ok({ ok: true }); + }); + +export const deleteCustomList = createServerFn({ method: "POST" }) + .validator(deleteCustomListArgsSchema) + .handler(async ({ data }): Promise> => { + const { user, error } = await requireUser(); + if (error) return error; + + const db = getDb(getEnv()); + const list = await db + .select() + .from(lists) + .where(and(eq(lists.id, data.listId), eq(lists.userId, user.id))) + .limit(1); + if (list.length === 0) return fail("NOT_FOUND", "List not found"); + + // Cascade via FK, but keep the explicit loop for parity with the Convex + // batched delete (also bounded for D1). + while (true) { + const items = await db + .select({ id: listItems.id }) + .from(listItems) + .where(eq(listItems.listId, data.listId)) + .limit(200); + if (items.length === 0) break; + for (const item of items) { + await db.delete(listItems).where(eq(listItems.id, item.id)); + } + } + + await db.delete(lists).where(eq(lists.id, data.listId)); + return ok({ ok: true }); + }); + +export const toggleListItem = createServerFn({ method: "POST" }) + .validator(toggleListItemArgsSchema) + .handler(async ({ data }): Promise> => { + const { user, error } = await requireUser(); + if (error) return error; + + return ok(await toggleListItemInner(user.id, data)); + }); + +// --------------------------------------------------------------------------- +// Helpers +// --------------------------------------------------------------------------- + +async function createCustomListInner( + userId: string, + args: { + name: string; + color?: string; + visibility?: string; + listType?: string; + }, +): Promise { + const db = getDb(getEnv()); + const existing = await db + .select({ id: lists.id }) + .from(lists) + .where(and(eq(lists.userId, userId), eq(lists.name, args.name))) + .limit(1); + if (existing.length > 0) + throw new Error("A list with this name already exists"); + + const highestList = await db + .select({ sortOrder: lists.sortOrder }) + .from(lists) + .where(eq(lists.userId, userId)) + .orderBy(desc(lists.sortOrder)) + .limit(1); + const maxSort = highestList.length > 0 ? highestList[0].sortOrder : 0; + + const now = Date.now(); + const id = crypto.randomUUID(); + await db.insert(lists).values({ + id, + userId, + name: args.name, + color: args.color, + visibility: args.visibility, + listType: args.listType, + sortOrder: maxSort + 1, + createdAt: now, + updatedAt: now, + }); + return id; +} + +async function toggleListItemInner( + userId: string, + args: { + listId: string; + tmdbId: number; + mediaType: "movie" | "tv"; + title?: string; + image?: string; + backdrop?: string; + rating?: number; + release_date?: string; + overview?: string; + }, +): Promise { + const db = getDb(getEnv()); + const list = await db + .select({ id: lists.id }) + .from(lists) + .where(and(eq(lists.id, args.listId), eq(lists.userId, userId))) + .limit(1); + if (list.length === 0) throw new Error("List not found"); + + const existing = await db + .select() + .from(listItems) + .where( + and( + eq(listItems.listId, args.listId), + eq(listItems.tmdbId, args.tmdbId), + eq(listItems.mediaType, args.mediaType), + ), + ) + .limit(1); + + if (existing.length > 0) { + await db.delete(listItems).where(eq(listItems.id, existing[0].id)); + return false; + } + + await db.insert(listItems).values({ + id: crypto.randomUUID(), + userId, + listId: args.listId, + tmdbId: args.tmdbId, + mediaType: args.mediaType, + addedAt: Date.now(), + title: args.title, + image: args.image, + backdrop: args.backdrop, + rating: args.rating, + releaseDate: args.release_date, + overview: args.overview, + }); + return true; +} diff --git a/src/server/fns/recommendations.ts b/src/server/fns/recommendations.ts new file mode 100644 index 00000000..28d64d7f --- /dev/null +++ b/src/server/fns/recommendations.ts @@ -0,0 +1,939 @@ +import { createServerFn } from "@tanstack/react-start"; +import { and, desc, eq } from "drizzle-orm"; +import { callGeminiAI, MODELS_TO_TRY, type Recommendation } from "../ai"; +import { getCurrentUser, requireUser } from "../auth"; +import { getDb } from "../db/client"; +import { + aiRecommendations, + episodeProgress, + homepageRecommendations, + listItems, + lists, + type Recommendation as RecommendationRow, + recommendationFeedback, + watchItems, +} from "../db/schema"; +import { getEnv } from "../env"; +import { + buildCustomListPrompt, + buildGenrePrompt, + buildHomepageRecommendationsPrompt, + buildWatchlistPrompt, + type FeedbackSignals, + type WatchlistData, +} from "../prompts"; +import { hasFeature } from "../rbac"; +import { type ApiResult, fail, ok } from "../schema/common"; +import { + deleteRecommendationArgsSchema, + type GenerateResult, + generateRecommendationsArgsSchema, + getHomepageRecommendationsArgsSchema, + type HomepageRecommendationsResult, + removeRecommendationFeedbackArgsSchema, + setRecommendationFeedbackArgsSchema, + updateVerifiedRecommendationsArgsSchema, +} from "../schema/recommendations"; + +const RATE_LIMIT_MS = 2 * 60 * 1000; + +async function getAuthUser() { + const result = await requireUser(); + if (result.error) return null; + return result.user; +} + +async function ensureFeatureEnabled(): Promise | null> { + const result = await requireUser(); + if (result.error) return result.error; + const allowed = await hasFeature( + result.claims, + result.user, + "ai-recommendations", + ); + if (!allowed) { + return fail("FORBIDDEN", "Unauthorized: feature not enabled"); + } + return null; +} + +// --------------------------------------------------------------------------- +// Access / history +// --------------------------------------------------------------------------- + +export const getUserRecommendationAccess = createServerFn({ + method: "POST", +}).handler( + async (): Promise< + ApiResult< + | { hasAccess: true } + | { hasAccess: false; reason: "not_authenticated" | "feature_disabled" } + > + > => { + const user = await getCurrentUser(); + if (!user) { + return ok({ hasAccess: false, reason: "not_authenticated" }); + } + const result = await requireUser(); + if (result.error) { + return ok({ hasAccess: false, reason: "not_authenticated" }); + } + const allowed = await hasFeature( + result.claims, + result.user, + "ai-recommendations", + ); + if (!allowed) { + return ok({ hasAccess: false, reason: "feature_disabled" }); + } + return ok({ hasAccess: true }); + }, +); + +export const getRecommendationHistory = createServerFn({ + method: "POST", +}).handler( + async (): Promise> => { + const user = await getCurrentUser(); + if (!user) return ok([]); + const result = await requireUser(); + if (result.error) return ok([]); + const allowed = await hasFeature( + result.claims, + result.user, + "ai-recommendations", + ); + if (!allowed) return ok([]); + + const db = getDb(getEnv()); + const rows = await db + .select() + .from(aiRecommendations) + .where(eq(aiRecommendations.userId, user.id)) + .orderBy(desc(aiRecommendations.createdAt)) + .limit(20) + .$withCache({ config: { ex: 60 } }); + + return ok(rows); + }, +); + +export const deleteRecommendation = createServerFn({ method: "POST" }) + .validator(deleteRecommendationArgsSchema) + .handler(async ({ data }): Promise> => { + const { user, error } = await requireUser(); + if (error) return error; + + const db = getDb(getEnv()); + const entry = await db + .select() + .from(aiRecommendations) + .where(eq(aiRecommendations.id, data.id)) + .limit(1); + if (entry.length === 0) return fail("NOT_FOUND", "Not found"); + if (entry[0].userId !== user.id) { + return fail("UNAUTHORIZED", "Unauthorized"); + } + + await db.delete(aiRecommendations).where(eq(aiRecommendations.id, data.id)); + return ok({ ok: true }); + }); + +export const updateVerifiedRecommendations = createServerFn({ method: "POST" }) + .validator(updateVerifiedRecommendationsArgsSchema) + .handler(async ({ data }): Promise> => { + const { user, error } = await requireUser(); + if (error) return error; + + const db = getDb(getEnv()); + const entry = await db + .select() + .from(aiRecommendations) + .where(eq(aiRecommendations.id, data.id)) + .limit(1); + if (entry.length === 0) return fail("NOT_FOUND", "Not found"); + if (entry[0].userId !== user.id) { + return fail("UNAUTHORIZED", "Unauthorized"); + } + + const patch: Partial = { + recommendations: JSON.parse(data.recommendations) as RecommendationRow[], + verified: true, + }; + if (!entry[0].originalRecommendations) { + patch.originalRecommendations = entry[0].recommendations; + } + + await db + .update(aiRecommendations) + .set(patch) + .where(eq(aiRecommendations.id, data.id)); + return ok({ ok: true }); + }); + +// --------------------------------------------------------------------------- +// Feedback +// --------------------------------------------------------------------------- + +export const getRecommendationFeedback = createServerFn({ + method: "POST", +}).handler( + async (): Promise< + ApiResult<(typeof recommendationFeedback.$inferSelect)[]> + > => { + const user = await getCurrentUser(); + if (!user) return ok([]); + + const db = getDb(getEnv()); + const rows = await db + .select() + .from(recommendationFeedback) + .where(eq(recommendationFeedback.userId, user.id)) + .limit(100) + .$withCache({ config: { ex: 60 } }); + + return ok(rows); + }, +); + +export const setRecommendationFeedback = createServerFn({ method: "POST" }) + .validator(setRecommendationFeedbackArgsSchema) + .handler(async ({ data }): Promise> => { + const { user, error } = await requireUser(); + if (error) return error; + + const db = getDb(getEnv()); + const now = Date.now(); + + const existing = await db + .select() + .from(recommendationFeedback) + .where( + and( + eq(recommendationFeedback.userId, user.id), + eq(recommendationFeedback.tmdbId, data.tmdbId), + eq(recommendationFeedback.mediaType, data.mediaType), + ), + ) + .limit(1); + + if (existing.length > 0) { + await db + .update(recommendationFeedback) + .set({ feedback: data.feedback, updatedAt: now }) + .where(eq(recommendationFeedback.id, existing[0].id)); + } else { + await db.insert(recommendationFeedback).values({ + id: crypto.randomUUID(), + userId: user.id, + tmdbId: data.tmdbId, + mediaType: data.mediaType, + title: data.title, + feedback: data.feedback, + updatedAt: now, + }); + } + + // When user likes a recommendation, auto-add to watchlist with + // "recommended" reaction & Pebbly Picks list. + if (data.feedback === "like") { + const existingWatchItem = await db + .select() + .from(watchItems) + .where( + and( + eq(watchItems.userId, user.id), + eq(watchItems.tmdbId, data.tmdbId), + eq(watchItems.mediaType, data.mediaType), + ), + ) + .limit(1); + + if (existingWatchItem.length > 0) { + await db + .update(watchItems) + .set({ + inWatchlist: true, + reaction: existingWatchItem[0].reaction ?? "recommended", + updatedAt: now, + }) + .where(eq(watchItems.id, existingWatchItem[0].id)); + } else { + await db.insert(watchItems).values({ + id: crypto.randomUUID(), + userId: user.id, + tmdbId: data.tmdbId, + mediaType: data.mediaType, + inWatchlist: true, + progressStatus: "watch-later", + reaction: "recommended", + title: data.title, + image: data.image, + rating: data.rating, + releaseDate: data.release_date, + overview: data.overview, + updatedAt: now, + }); + } + + // Find or create the Pebbly Picks list + let pebblyList = await db + .select() + .from(lists) + .where(and(eq(lists.userId, user.id), eq(lists.name, "Pebbly Picks"))) + .limit(1); + + if (pebblyList.length === 0) { + const listId = crypto.randomUUID(); + await db.insert(lists).values({ + id: listId, + userId: user.id, + name: "Pebbly Picks", + listType: "pebbly-picks", + sortOrder: 0, + createdAt: now, + updatedAt: now, + }); + pebblyList = await db + .select() + .from(lists) + .where(eq(lists.id, listId)) + .limit(1); + } + + if (pebblyList.length > 0) { + const existingItem = await db + .select() + .from(listItems) + .where( + and( + eq(listItems.listId, pebblyList[0].id), + eq(listItems.tmdbId, data.tmdbId), + eq(listItems.mediaType, data.mediaType), + ), + ) + .limit(1); + + if (existingItem.length === 0) { + await db.insert(listItems).values({ + id: crypto.randomUUID(), + userId: user.id, + listId: pebblyList[0].id, + tmdbId: data.tmdbId, + mediaType: data.mediaType, + addedAt: now, + title: data.title, + image: data.image, + backdrop: data.backdrop, + rating: data.rating, + releaseDate: data.release_date, + overview: data.overview, + }); + } + } + } + + return ok({ ok: true }); + }); + +export const removeRecommendationFeedback = createServerFn({ method: "POST" }) + .validator(removeRecommendationFeedbackArgsSchema) + .handler(async ({ data }): Promise> => { + const { user, error } = await requireUser(); + if (error) return error; + + const db = getDb(getEnv()); + const existing = await db + .select() + .from(recommendationFeedback) + .where( + and( + eq(recommendationFeedback.userId, user.id), + eq(recommendationFeedback.tmdbId, data.tmdbId), + eq(recommendationFeedback.mediaType, data.mediaType), + ), + ) + .limit(1); + + if (existing.length > 0) { + await db + .delete(recommendationFeedback) + .where(eq(recommendationFeedback.id, existing[0].id)); + } + + return ok({ ok: true }); + }); + +// --------------------------------------------------------------------------- +// Homepage recommendations +// --------------------------------------------------------------------------- + +export const getHomepageRecommendations = createServerFn({ method: "POST" }) + .validator(getHomepageRecommendationsArgsSchema) + .handler( + async ({ data }): Promise> => { + const user = await getCurrentUser(); + if (!user) { + return ok({ + recommendations: [], + lastUpdatedAt: 0, + lastAttemptedAt: 0, + status: "none", + needsRefresh: false, + }); + } + + const db = getDb(getEnv()); + const entry = await db + .select() + .from(homepageRecommendations) + .where(eq(homepageRecommendations.userId, user.id)) + .limit(1) + .$withCache({ config: { ex: 60 } }); + + const notInterestedFeedback = await db + .select() + .from(recommendationFeedback) + .where( + and( + eq(recommendationFeedback.userId, user.id), + eq(recommendationFeedback.feedback, "not_interested"), + ), + ) + .$withCache({ config: { ex: 60 } }); + + const dislikeFeedback = await db + .select() + .from(recommendationFeedback) + .where( + and( + eq(recommendationFeedback.userId, user.id), + eq(recommendationFeedback.feedback, "dislike"), + ), + ) + .$withCache({ config: { ex: 60 } }); + + const excludedFeedbackIds = new Set([ + ...notInterestedFeedback.map((f) => f.tmdbId), + ...dislikeFeedback.map((f) => f.tmdbId), + ]); + + let recs: Recommendation[] = []; + const row = entry[0]; + if (row && row.recommendations) { + try { + const parsed = Array.isArray(row.recommendations) + ? row.recommendations + : (JSON.parse(row.recommendations) as Recommendation[]); + recs = parsed.filter( + (r) => r.tmdbId === null || !excludedFeedbackIds.has(r.tmdbId), + ); + } catch (e) { + console.error("Failed to parse homepage recommendations", e); + } + } + + const lastAttemptedAt = row?.lastAttemptedAt ?? 0; + const lastUpdatedAt = row?.lastUpdatedAt ?? 0; + const status = row?.status ?? "none"; + + const currentTime = data.now ?? Date.now(); + const isOlderThan24Hours = + currentTime > 0 && currentTime - lastAttemptedAt > 24 * 60 * 60 * 1000; + const hasFailedRecently = + status === "failed" && + currentTime > 0 && + currentTime - lastAttemptedAt < 1 * 60 * 60 * 1000; + const needsRefresh = !row || (isOlderThan24Hours && !hasFailedRecently); + + return ok({ + recommendations: recs, + lastUpdatedAt, + lastAttemptedAt, + status, + needsRefresh, + }); + }, + ); + +// --------------------------------------------------------------------------- +// Generation helpers (private — no longer separate RPCs) +// --------------------------------------------------------------------------- + +function computeHash( + items: Array<{ + tmdbId: number; + progressStatus?: string | null; + reaction?: string | null; + }>, + mediaTypePreference?: string, + genrePreference?: string, +): string { + const sorted = items + .map((i) => `${i.tmdbId}:${i.progressStatus ?? ""}:${i.reaction ?? ""}`) + .sort(); + let hash = 0; + const str = + sorted.join("|") + + `|mt:${mediaTypePreference ?? ""}|g:${genrePreference ?? ""}`; + for (let i = 0; i < str.length; i++) { + const char = str.charCodeAt(i); + hash = ((hash << 5) - hash + char) | 0; + } + return hash.toString(36); +} + +function normalizeTitleKey(title?: string | null): string { + return (title ?? "").toLowerCase().replace(/[^a-z0-9]/g, ""); +} + +async function gatherWatchlistData(userId: string): Promise { + const db = getDb(getEnv()); + const watchItemRows = await db + .select() + .from(watchItems) + .where(eq(watchItems.userId, userId)) + .orderBy(desc(watchItems.updatedAt)) + .limit(200); + + const listRows = await db + .select() + .from(lists) + .where(eq(lists.userId, userId)) + .limit(50); + + const listItemRows = await db + .select() + .from(listItems) + .where(eq(listItems.userId, userId)) + .orderBy(desc(listItems.addedAt)) + .limit(200); + + const episodeRows = await db + .select() + .from(episodeProgress) + .where(eq(episodeProgress.userId, userId)) + .orderBy(desc(episodeProgress.updatedAt)) + .limit(200); + + const watchedEpisodes = episodeRows.filter((e) => e.isWatched).length; + const movieCount = watchItemRows.filter( + (i) => i.mediaType === "movie", + ).length; + const tvCount = watchItemRows.filter((i) => i.mediaType === "tv").length; + + return { + watchItems: watchItemRows.map((i) => ({ + tmdbId: i.tmdbId, + mediaType: i.mediaType, + title: i.title, + rating: i.rating, + progressStatus: i.progressStatus, + reaction: i.reaction, + progress: i.progress, + })), + lists: listRows.map((l) => ({ _id: l.id, name: l.name })), + listItems: listItemRows.map((li) => ({ + listId: li.listId, + tmdbId: li.tmdbId, + mediaType: li.mediaType, + })), + inputStats: { + movieCount, + tvCount, + episodesWatched: watchedEpisodes, + totalItems: watchItemRows.length, + }, + }; +} + +async function getRecommendationFeedbackInternal(userId: string) { + const db = getDb(getEnv()); + return db + .select() + .from(recommendationFeedback) + .where(eq(recommendationFeedback.userId, userId)) + .limit(100); +} + +async function checkAndSetRecommendationCooldown( + userId: string, +): Promise { + const db = getDb(getEnv()); + const mostRecent = await db + .select() + .from(aiRecommendations) + .where(eq(aiRecommendations.userId, userId)) + .orderBy(desc(aiRecommendations.createdAt)) + .limit(1); + + const now = Date.now(); + if (mostRecent.length > 0 && now - mostRecent[0].createdAt < RATE_LIMIT_MS) { + return false; + } + + await db.insert(aiRecommendations).values({ + id: crypto.randomUUID(), + userId, + recommendations: [], + watchlistHash: "", + inputStats: { + movieCount: 0, + tvCount: 0, + episodesWatched: 0, + totalItems: 0, + }, + model: "placeholder", + createdAt: now, + }); + + return true; +} + +async function getHomepageAttemptInfo(userId: string) { + const db = getDb(getEnv()); + const entry = await db + .select() + .from(homepageRecommendations) + .where(eq(homepageRecommendations.userId, userId)) + .limit(1); + return entry.length > 0 + ? { lastAttemptedAt: entry[0].lastAttemptedAt, status: entry[0].status } + : null; +} + +async function getHomepageRecommendationEntryInternal(userId: string) { + const db = getDb(getEnv()); + const entry = await db + .select() + .from(homepageRecommendations) + .where(eq(homepageRecommendations.userId, userId)) + .limit(1); + return entry.length > 0 ? entry[0] : null; +} + +async function saveRecommendations(args: { + userId: string; + recommendations: string; + watchlistHash: string; + inputStats: { + movieCount: number; + tvCount: number; + episodesWatched: number; + totalItems: number; + }; + model: string; + mediaTypePreference?: string; + genrePreference?: string; + generationType?: string; +}) { + const db = getDb(getEnv()); + await db.insert(aiRecommendations).values({ + id: crypto.randomUUID(), + userId: args.userId, + recommendations: JSON.parse(args.recommendations) as RecommendationRow[], + watchlistHash: args.watchlistHash, + inputStats: args.inputStats, + model: args.model, + mediaTypePreference: args.mediaTypePreference as "movie" | "tv" | undefined, + genrePreference: args.genrePreference, + generationType: args.generationType, + createdAt: Date.now(), + }); +} + +async function saveHomepageRecommendations( + userId: string, + recommendations: string, +) { + const db = getDb(getEnv()); + const existing = await db + .select() + .from(homepageRecommendations) + .where(eq(homepageRecommendations.userId, userId)) + .limit(1); + + if (existing.length > 0) { + await db + .update(homepageRecommendations) + .set({ + previousRecommendations: existing[0].recommendations, + recommendations: JSON.parse(recommendations) as RecommendationRow[], + lastAttemptedAt: Date.now(), + lastUpdatedAt: Date.now(), + status: "success", + }) + .where(eq(homepageRecommendations.id, existing[0].id)); + } else { + await db.insert(homepageRecommendations).values({ + id: crypto.randomUUID(), + userId, + recommendations: JSON.parse(recommendations) as RecommendationRow[], + lastAttemptedAt: Date.now(), + lastUpdatedAt: Date.now(), + status: "success", + }); + } +} + +async function saveHomepageFailure(userId: string) { + const db = getDb(getEnv()); + const existing = await db + .select() + .from(homepageRecommendations) + .where(eq(homepageRecommendations.userId, userId)) + .limit(1); + + if (existing.length > 0) { + await db + .update(homepageRecommendations) + .set({ lastAttemptedAt: Date.now(), status: "failed" }) + .where(eq(homepageRecommendations.id, existing[0].id)); + } else { + await db.insert(homepageRecommendations).values({ + id: crypto.randomUUID(), + userId, + recommendations: [], + lastAttemptedAt: Date.now(), + lastUpdatedAt: 0, + status: "failed", + }); + } +} + +// --------------------------------------------------------------------------- +// generateRecommendations (action → server fn) +// --------------------------------------------------------------------------- + +export const generateRecommendations = createServerFn({ method: "POST" }) + .validator(generateRecommendationsArgsSchema) + .handler(async ({ data }): Promise> => { + const genType = data.generationType ?? "watchlist"; + + const user = await getAuthUser(); + if (!user) return fail("UNAUTHORIZED", "Unauthorized"); + + const featureError = await ensureFeatureEnabled(); + if (featureError) return featureError; + + const watchlistData = await gatherWatchlistData(user.id); + + if (genType === "watchlist" && watchlistData.watchItems.length === 0) { + return ok({ error: "empty_watchlist" }); + } + if (genType === "list" && data.listId) { + if ( + watchlistData.listItems.filter((li) => li.listId === data.listId) + .length === 0 + ) { + return ok({ error: "empty_watchlist" }); + } + } + + const allowed = await checkAndSetRecommendationCooldown(user.id); + if (!allowed) { + return ok({ error: "rate_limited" }); + } + + const feedbackList = await getRecommendationFeedbackInternal(user.id); + + const likedTitles = feedbackList + .filter((f) => f.feedback === "like") + .map((f) => f.title); + const dislikedTitles = feedbackList + .filter((f) => f.feedback === "not_interested") + .map((f) => f.title); + const dislikedTmdbIds = feedbackList + .filter((f) => f.feedback === "not_interested") + .map((f) => f.tmdbId); + + const excludeTmdbIds = [ + ...new Set([...(data.excludeTmdbIds ?? []), ...dislikedTmdbIds]), + ]; + + const feedbackSignals: FeedbackSignals = { + likedTitles, + dislikedTitles, + dislikedTmdbIds, + }; + + const userPrompt = + genType === "watchlist" + ? buildWatchlistPrompt( + watchlistData, + data.mediaTypePreference, + excludeTmdbIds, + data.yearFrom, + data.yearTo, + data.count, + feedbackSignals, + ) + : genType === "list" && data.listId + ? buildCustomListPrompt( + watchlistData, + data.listId, + data.mediaTypePreference, + excludeTmdbIds, + data.yearFrom, + data.yearTo, + data.count, + feedbackSignals, + ) + : buildGenrePrompt( + watchlistData, + data.mediaTypePreference, + data.genrePreference, + excludeTmdbIds, + data.yearFrom, + data.yearTo, + data.count, + feedbackSignals, + ); + + const systemInstruction = + "You are a movie and TV show recommendation engine. You analyze a user's watchlist and viewing preferences to suggest titles they would enjoy. You MUST only recommend real, existing movies and TV shows. Never invent fictional titles. Return your response as a JSON object with the exact schema specified by the user."; + + const aiResult = await callGeminiAI(userPrompt, systemInstruction, 1); + if (aiResult.error || !aiResult.result) { + return ok({ error: aiResult.error ?? "api_unavailable" }); + } + const parsed = aiResult.result; + const usedModel = aiResult.usedModel ?? MODELS_TO_TRY[0]; + + const existingIds = new Set([ + ...watchlistData.watchItems.map((item) => item.tmdbId), + ...excludeTmdbIds, + ]); + const existingTitles = new Set( + watchlistData.watchItems.map((item) => normalizeTitleKey(item.title)), + ); + parsed.recommendations = parsed.recommendations.filter( + (r) => + (r.tmdbId == null || !existingIds.has(r.tmdbId)) && + !existingTitles.has(normalizeTitleKey(r.title)), + ); + + const watchlistHash = computeHash( + watchlistData.watchItems, + data.mediaTypePreference, + data.genrePreference, + ); + await saveRecommendations({ + userId: user.id, + recommendations: JSON.stringify(parsed.recommendations), + watchlistHash, + inputStats: watchlistData.inputStats, + model: usedModel, + mediaTypePreference: data.mediaTypePreference, + genrePreference: data.genrePreference, + generationType: genType, + }); + + return ok({ + recommendations: parsed.recommendations, + inputStats: watchlistData.inputStats, + generatedAt: Date.now(), + cached: false, + }); + }); + +// --------------------------------------------------------------------------- +// generateHomepageRecommendations (action → server fn) +// --------------------------------------------------------------------------- + +export const generateHomepageRecommendations = createServerFn({ + method: "POST", +}).handler( + async (): Promise> => { + const user = await getAuthUser(); + if (!user) return fail("UNAUTHORIZED", "Unauthorized"); + + const featureError = await ensureFeatureEnabled(); + if (featureError) return featureError; + + const watchlistData = await gatherWatchlistData(user.id); + + const attemptInfo = await getHomepageAttemptInfo(user.id); + if ( + attemptInfo && + Date.now() - attemptInfo.lastAttemptedAt < RATE_LIMIT_MS + ) { + return ok({ success: false, error: "rate_limited" }); + } + + const feedbackList = await getRecommendationFeedbackInternal(user.id); + + const likedFeedback = feedbackList + .filter((f) => f.feedback === "like") + .map((f) => f.title); + + const dislikedFeedbackTitles = feedbackList + .filter( + (f) => f.feedback === "not_interested" || f.feedback === "dislike", + ) + .map((f) => f.title); + + const dislikedFeedbackIds = feedbackList + .filter( + (f) => f.feedback === "not_interested" || f.feedback === "dislike", + ) + .map((f) => f.tmdbId); + + const homepageEntry = await getHomepageRecommendationEntryInternal(user.id); + + let previousTitles: string[] = []; + let previousTmdbIds: number[] = []; + if (homepageEntry?.recommendations) { + try { + const prevRecs = Array.isArray(homepageEntry.recommendations) + ? homepageEntry.recommendations + : (JSON.parse(homepageEntry.recommendations) as Recommendation[]); + previousTitles = prevRecs.map((r) => r.title); + previousTmdbIds = prevRecs + .map((r) => r.tmdbId) + .filter((id): id is number => typeof id === "number"); + } catch { + // ignore parse error + } + } + + const systemInstruction = + "You are a movie and TV show recommendation engine. You analyze a user's watchlist and viewing preferences to suggest titles they would enjoy. You MUST only recommend real, existing movies and TV shows. Never invent fictional titles. Return your response as a JSON object with the exact schema specified by the user."; + + const prompt = buildHomepageRecommendationsPrompt( + watchlistData, + likedFeedback, + dislikedFeedbackTitles, + [...dislikedFeedbackIds, ...previousTmdbIds], + previousTitles, + ); + + const aiResult = await callGeminiAI(prompt, systemInstruction, 2); + if (aiResult.error || !aiResult.result) { + await saveHomepageFailure(user.id); + return ok({ success: false, error: aiResult.error ?? "api_unavailable" }); + } + const parsed = aiResult.result; + + const existingIds = new Set([ + ...watchlistData.watchItems.map((item) => item.tmdbId), + ...dislikedFeedbackIds, + ]); + const existingTitles = new Set( + watchlistData.watchItems.map((item) => normalizeTitleKey(item.title)), + ); + + parsed.recommendations = parsed.recommendations.filter( + (r) => + (r.tmdbId == null || !existingIds.has(r.tmdbId)) && + !existingTitles.has(normalizeTitleKey(r.title)), + ); + + await saveHomepageRecommendations( + user.id, + JSON.stringify(parsed.recommendations), + ); + + return ok({ success: true }); + }, +); diff --git a/src/server/fns/users.ts b/src/server/fns/users.ts new file mode 100644 index 00000000..b621729f --- /dev/null +++ b/src/server/fns/users.ts @@ -0,0 +1,55 @@ +import { createServerFn } from "@tanstack/react-start"; +import { eq } from "drizzle-orm"; +import { z } from "zod"; +import { getAdminFromClaims, getCurrentUser, requireUser } from "../auth"; +import { getDb } from "../db/client"; +import { users } from "../db/schema"; +import { getEnv } from "../env"; +import { syncRolePermissions } from "../rbac"; +import { type ApiResult, ok } from "../schema/common"; + +const storeUserArgsSchema = z.object({ + email: z.string().optional(), + name: z.string().optional(), + image: z.string().optional(), + isAdmin: z.boolean().optional(), +}); + +/** + * Port of `users.store` — upserts the user from the verified Clerk session. + * Admin status comes from the JWT `public_meta.isAdmin` claim first; the + * client-supplied value is only used to downgrade a stale JWT (never to elevate). + */ +export const storeUser = createServerFn({ method: "POST" }) + .validator(storeUserArgsSchema) + .handler(async ({ data }): Promise> => { + const result = await requireUser(); + if (result.error) return result.error; + + const { user, claims } = result; + const db = getDb(getEnv()); + await syncRolePermissions(db); + + const adminFromJwt = getAdminFromClaims(claims); + + const update: Partial = { + name: data.name, + image: data.image, + email: data.email, + }; + if (adminFromJwt !== null) { + update.isAdmin = adminFromJwt; + } else if (data.isAdmin === false) { + update.isAdmin = false; + } + + await db.update(users).set(update).where(eq(users.id, user.id)); + return ok(user.id); + }); + +export const getStatus = createServerFn({ method: "POST" }).handler( + async (): Promise> => { + const user = await getCurrentUser(); + return ok(user); + }, +); diff --git a/src/server/fns/watchlist.ts b/src/server/fns/watchlist.ts new file mode 100644 index 00000000..8c167c51 --- /dev/null +++ b/src/server/fns/watchlist.ts @@ -0,0 +1,530 @@ +import { createServerFn } from "@tanstack/react-start"; +import { and, desc, eq } from "drizzle-orm"; +import { z } from "zod"; +import { getCurrentUser, requireUser } from "../auth"; +import { getDb } from "../db/client"; +import { episodeProgress, watchItems } from "../db/schema"; +import { getEnv } from "../env"; +import { + buildMetadataPatch, + getWatchItem, + normalizeProgressStatus, + upsertWatchItem, +} from "../helpers/watch-item"; +import { type ApiResult, ok } from "../schema/common"; +import { + getWatchlistArgsSchema, + markEpisodeWatchedArgsSchema, + markSeasonEpisodesWatchedArgsSchema, + markShowEpisodesAndStatusArgsSchema, + mediaIdentityArgsSchema, + setProgressStatusArgsSchema, + setReactionArgsSchema, + setWatchlistMembershipArgsSchema, + updateProgressArgsSchema, +} from "../schema/watchlist"; + +// --------------------------------------------------------------------------- +// Reads +// --------------------------------------------------------------------------- + +export const getWatchlist = createServerFn({ method: "POST" }) + .validator(getWatchlistArgsSchema) + .handler( + async ({ + data, + }): Promise> => { + const user = await getCurrentUser(); + if (!user) return ok([]); + + const db = getDb(getEnv()); + const requestedLimit = + data.limit !== undefined && data.limit > 0 + ? Math.floor(data.limit) + : 200; + const boundedLimit = Math.min(requestedLimit, 500); + + const filters = [eq(watchItems.userId, user.id)]; + if (data.statusFilter) { + filters.push( + eq( + watchItems.progressStatus, + data.statusFilter as + | "watch-later" + | "watching" + | "done" + | "dropped", + ), + ); + } + + const rows = await db + .select() + .from(watchItems) + .where(and(...filters)) + .orderBy(desc(watchItems.updatedAt)) + .limit(boundedLimit) + .$withCache({ config: { ex: 15 } }); + + return ok(rows); + }, + ); + +export const getTrackedTmdbIds = createServerFn({ method: "POST" }).handler( + async (): Promise> => { + const user = await getCurrentUser(); + if (!user) return ok([]); + + const db = getDb(getEnv()); + const items = await db + .select({ tmdbId: watchItems.tmdbId }) + .from(watchItems) + .where(eq(watchItems.userId, user.id)) + .limit(500) + .$withCache({ config: { ex: 15 } }); + + return ok(items.map((item) => item.tmdbId)); + }, +); + +export const getMediaState = createServerFn({ method: "POST" }) + .validator(mediaIdentityArgsSchema) + .handler( + async ({ + data, + }): Promise> => { + const user = await getCurrentUser(); + if (!user) return ok(null); + + const db = getDb(getEnv()); + const rows = await db + .select() + .from(watchItems) + .where( + and( + eq(watchItems.userId, user.id), + eq(watchItems.tmdbId, data.tmdbId), + eq(watchItems.mediaType, data.mediaType), + ), + ) + .limit(1) + .$withCache({ config: { ex: 15 } }); + + return ok(rows[0] ?? null); + }, + ); + +// --------------------------------------------------------------------------- +// Writes +// --------------------------------------------------------------------------- + +export const updateProgress = createServerFn({ method: "POST" }) + .validator(updateProgressArgsSchema) + .handler(async ({ data }): Promise> => { + const { user, error } = await requireUser(); + if (error) return error; + + const db = getDb(getEnv()); + const existing = await getWatchItem(db, user.id, { + tmdbId: data.tmdbId, + mediaType: data.mediaType, + }); + + const now = Date.now(); + const nextProgress = + data.isWatched === true + ? 100 + : (data.progress ?? existing?.progress ?? 0); + + const currentProgressStatus = normalizeProgressStatus( + existing?.progressStatus, + ); + + const inferredProgressStatus = + data.isWatched === true + ? "done" + : nextProgress >= 95 + ? "done" + : nextProgress > 0 + ? "watching" + : undefined; + + const nextProgressStatus = currentProgressStatus ?? inferredProgressStatus; + + if (existing) { + await db + .update(watchItems) + .set({ + progress: nextProgress, + progressStatus: nextProgressStatus, + inWatchlist: true, + updatedAt: now, + ...buildMetadataPatch(data, existing), + }) + .where(eq(watchItems.id, existing.id)); + return ok({ ok: true }); + } + + await db.insert(watchItems).values({ + id: crypto.randomUUID(), + userId: user.id, + tmdbId: data.tmdbId, + mediaType: data.mediaType, + inWatchlist: true, + progress: nextProgress, + progressStatus: nextProgressStatus, + updatedAt: now, + ...buildMetadataPatch(data), + }); + return ok({ ok: true }); + }); + +export const removeFromContinueWatching = createServerFn({ method: "POST" }) + .validator(mediaIdentityArgsSchema) + .handler(async ({ data }): Promise> => { + const { user, error } = await requireUser(); + if (error) return error; + + const db = getDb(getEnv()); + const existing = await getWatchItem(db, user.id, data); + if (!existing) return ok({ ok: true }); + + await db + .update(watchItems) + .set({ + progressStatus: existing.inWatchlist ? "watch-later" : undefined, + progress: 0, + updatedAt: Date.now(), + }) + .where(eq(watchItems.id, existing.id)); + + return ok({ ok: true }); + }); + +export const setWatchlistMembership = createServerFn({ method: "POST" }) + .validator(setWatchlistMembershipArgsSchema) + .handler(async ({ data }): Promise> => { + const { user, error } = await requireUser(); + if (error) return error; + + const db = getDb(getEnv()); + await upsertWatchItem( + db, + user.id, + data.tmdbId, + data.mediaType, + (existing) => { + if (!existing && !data.inWatchlist) return null; + + const normalizedExisting = existing + ? normalizeProgressStatus(existing.progressStatus) + : undefined; + const progressStatus = existing + ? (normalizedExisting ?? + (data.inWatchlist ? "watch-later" : undefined)) + : "watch-later"; + + return { + inWatchlist: data.inWatchlist, + progressStatus, + ...(existing ? {} : { progress: 0 }), + title: data.title, + image: data.image, + rating: data.rating, + release_date: data.release_date, + overview: data.overview, + }; + }, + ); + + return ok({ ok: true }); + }); + +export const setProgressStatus = createServerFn({ method: "POST" }) + .validator(setProgressStatusArgsSchema) + .handler(async ({ data }): Promise> => { + const { user, error } = await requireUser(); + if (error) return error; + + const db = getDb(getEnv()); + await upsertWatchItem( + db, + user.id, + data.tmdbId, + data.mediaType, + (existing) => { + const normalized = + normalizeProgressStatus(data.progressStatus) ?? data.progressStatus; + let nextProgress: number | null | undefined = data.progress; + if (nextProgress === undefined) { + if (normalized === "watch-later") nextProgress = 0; + else if (normalized === "done") nextProgress = 100; + else nextProgress = existing?.progress ?? null; + } + + return { + inWatchlist: true, + progressStatus: normalized, + progress: nextProgress, + title: data.title, + image: data.image, + rating: data.rating, + release_date: data.release_date, + overview: data.overview, + }; + }, + ); + + return ok({ ok: true }); + }); + +export const setReaction = createServerFn({ method: "POST" }) + .validator(setReactionArgsSchema) + .handler(async ({ data }): Promise> => { + const { user, error } = await requireUser(); + if (error) return error; + + const db = getDb(getEnv()); + await upsertWatchItem( + db, + user.id, + data.tmdbId, + data.mediaType, + (existing) => { + const reaction = data.clearReaction + ? null + : data.reaction !== undefined + ? data.reaction + : existing?.reaction; + + return { + reaction, + title: data.title, + image: data.image, + rating: data.rating, + release_date: data.release_date, + overview: data.overview, + }; + }, + ); + + return ok({ ok: true }); + }); + +// --------------------------------------------------------------------------- +// Episode progress +// --------------------------------------------------------------------------- + +export async function syncEpisodeProgressRecord( + userId: string, + args: { + tmdbId: number; + season: number; + episode: number; + isWatched: boolean; + }, + now: number, +) { + const db = getDb(getEnv()); + const existing = await db + .select() + .from(episodeProgress) + .where( + and( + eq(episodeProgress.userId, userId), + eq(episodeProgress.tmdbId, args.tmdbId), + eq(episodeProgress.season, args.season), + eq(episodeProgress.episode, args.episode), + ), + ) + .limit(1); + + if (existing.length > 0) { + if (existing[0].isWatched !== args.isWatched) { + await db + .update(episodeProgress) + .set({ isWatched: args.isWatched, updatedAt: now }) + .where(eq(episodeProgress.id, existing[0].id)); + } + return; + } + + if (!args.isWatched) { + return; + } + + await db.insert(episodeProgress).values({ + id: crypto.randomUUID(), + userId, + tmdbId: args.tmdbId, + season: args.season, + episode: args.episode, + isWatched: args.isWatched, + updatedAt: now, + }); +} + +export const markEpisodeWatched = createServerFn({ method: "POST" }) + .validator(markEpisodeWatchedArgsSchema) + .handler(async ({ data }): Promise> => { + const { user, error } = await requireUser(); + if (error) return error; + + await syncEpisodeProgressRecord(user.id, data, Date.now()); + return ok({ ok: true }); + }); + +export const markSeasonEpisodesWatched = createServerFn({ method: "POST" }) + .validator(markSeasonEpisodesWatchedArgsSchema) + .handler(async ({ data }): Promise> => { + const { user, error } = await requireUser(); + if (error) return error; + + const now = Date.now(); + const uniqueEpisodes = Array.from(new Set(data.episodes)); + for (const epNum of uniqueEpisodes) { + await syncEpisodeProgressRecord( + user.id, + { + tmdbId: data.tmdbId, + season: data.season, + episode: epNum, + isWatched: data.isWatched, + }, + now, + ); + } + + return ok({ ok: true }); + }); + +export const markShowEpisodesAndStatus = createServerFn({ method: "POST" }) + .validator(markShowEpisodesAndStatusArgsSchema) + .handler(async ({ data }): Promise> => { + const { user, error } = await requireUser(); + if (error) return error; + + const db = getDb(getEnv()); + const now = Date.now(); + + if (data.progressStatus !== undefined) { + const existing = await getWatchItem(db, user.id, { + tmdbId: data.tmdbId, + mediaType: data.mediaType, + }); + + if (existing) { + await db + .update(watchItems) + .set({ + inWatchlist: true, + progressStatus: data.progressStatus, + progress: data.progress ?? existing.progress, + updatedAt: now, + ...buildMetadataPatch(data, existing), + }) + .where(eq(watchItems.id, existing.id)); + } else { + await db.insert(watchItems).values({ + id: crypto.randomUUID(), + userId: user.id, + tmdbId: data.tmdbId, + mediaType: data.mediaType, + inWatchlist: true, + progressStatus: data.progressStatus, + progress: data.progress ?? 0, + updatedAt: now, + ...buildMetadataPatch(data), + }); + } + } + + const allExisting = await db + .select() + .from(episodeProgress) + .where( + and( + eq(episodeProgress.userId, user.id), + eq(episodeProgress.tmdbId, data.tmdbId), + ), + ); + + if (data.clearAllEpisodes || (!data.isWatched && data.seasons.length > 0)) { + for (const ep of allExisting) { + if (ep.isWatched) { + await syncEpisodeProgressRecord( + user.id, + { + tmdbId: data.tmdbId, + season: ep.season, + episode: ep.episode, + isWatched: false, + }, + now, + ); + } + } + } else { + for (const seasonData of data.seasons) { + const uniqueEpisodes = Array.from(new Set(seasonData.episodes)); + for (const epNum of uniqueEpisodes) { + await syncEpisodeProgressRecord( + user.id, + { + tmdbId: data.tmdbId, + season: seasonData.season, + episode: epNum, + isWatched: data.isWatched, + }, + now, + ); + } + } + } + + return ok({ ok: true }); + }); + +export const getAllWatchedEpisodes = createServerFn({ method: "POST" }) + .validator( + // matches the Convex `getAllWatchedEpisodes({ tmdbId })` signature + z.object({ tmdbId: z.number() }), + ) + .handler( + async ({ + data, + }): Promise> => { + const user = await getCurrentUser(); + if (!user) return ok([]); + + const db = getDb(getEnv()); + const rows = await db + .select() + .from(episodeProgress) + .where( + and( + eq(episodeProgress.userId, user.id), + eq(episodeProgress.tmdbId, data.tmdbId), + ), + ) + .$withCache({ config: { ex: 15 } }); + + return ok(rows); + }, + ); + +export const getAllEpisodeProgress = createServerFn({ method: "POST" }).handler( + async (): Promise> => { + const user = await getCurrentUser(); + if (!user) return ok([]); + + const db = getDb(getEnv()); + const rows = await db + .select() + .from(episodeProgress) + .where(eq(episodeProgress.userId, user.id)) + .$withCache({ config: { ex: 15 } }); + + return ok(rows); + }, +); diff --git a/src/server/helpers/snapshots.ts b/src/server/helpers/snapshots.ts new file mode 100644 index 00000000..00eef925 --- /dev/null +++ b/src/server/helpers/snapshots.ts @@ -0,0 +1,89 @@ +import { desc, eq } from "drizzle-orm"; +import type { Db } from "../db/client"; +import { getDb } from "../db/client"; +import { users, watchItems, watchlistSnapshots } from "../db/schema"; +import { getEnv } from "../env"; + +/** + * Port of `createWatchlistSnapshot` — records the current watchlist media state + * (TMDB IDs & media types) unless it is identical to the latest snapshot. + */ +export async function createWatchlistSnapshot( + db: Db, + userId: string, +): Promise { + const items = await db + .select({ + tmdbId: watchItems.tmdbId, + mediaType: watchItems.mediaType, + inWatchlist: watchItems.inWatchlist, + }) + .from(watchItems) + .where(eq(watchItems.userId, userId)) + .limit(500); + + const watchlistItems = items + .filter((item) => item.inWatchlist !== false) + .map((item) => ({ tmdbId: item.tmdbId, mediaType: item.mediaType })) + .sort( + (a, b) => a.tmdbId - b.tmdbId || a.mediaType.localeCompare(b.mediaType), + ); + + const latest = await db + .select() + .from(watchlistSnapshots) + .where(eq(watchlistSnapshots.userId, userId)) + .orderBy(desc(watchlistSnapshots.createdAt)) + .limit(1); + + if ( + latest.length > 0 && + latest[0].items && + latest[0].items.length === watchlistItems.length && + latest[0].items.every( + (item, index) => + item.tmdbId === watchlistItems[index]?.tmdbId && + item.mediaType === watchlistItems[index]?.mediaType, + ) + ) { + return; + } + + await db.insert(watchlistSnapshots).values({ + id: crypto.randomUUID(), + userId, + items: watchlistItems.slice(0, 8000), + createdAt: Date.now(), + }); +} + +/** + * Port of `createDailySnapshots` — iterates users in batches of 50, creating a + * snapshot for each. Runs from the Cloudflare cron (server/tasks/snapshots.ts). + */ +export async function createDailySnapshots(): Promise { + const db = getDb(getEnv()); + + // D1 query limits: keep batches bounded (50 like Convex pagination). + let cursor = 0; + for (;;) { + const batch = await db + .select({ id: users.id }) + .from(users) + .orderBy(users.id) + .limit(50) + .offset(cursor); + + if (batch.length === 0) break; + + for (const user of batch) { + try { + await createWatchlistSnapshot(db, user.id); + } catch (error) { + console.error(`Failed to create snapshot for user ${user.id}:`, error); + } + } + + cursor += batch.length; + } +} diff --git a/src/server/helpers/watch-item.ts b/src/server/helpers/watch-item.ts new file mode 100644 index 00000000..d793a867 --- /dev/null +++ b/src/server/helpers/watch-item.ts @@ -0,0 +1,137 @@ +import { and, eq } from "drizzle-orm"; +import type { Db } from "../db/client"; +import { watchItems } from "../db/schema"; +import type { MediaType, ProgressStatus, Reaction } from "../schema/common"; + +const VALID_PROGRESS_STATUSES: ReadonlySet = new Set([ + "watch-later", + "watching", + "done", + "dropped", +]); + +export function normalizeProgressStatus( + status?: string | null, +): ProgressStatus | undefined { + if (!status) return undefined; + return (VALID_PROGRESS_STATUSES.has(status) ? status : undefined) as + | ProgressStatus + | undefined; +} + +export interface MediaIdentity { + tmdbId: number; + mediaType: MediaType; +} + +export type WatchItemMetadata = { + title?: string; + image?: string; + rating?: number; + release_date?: string; + overview?: string; +}; + +type MetadataDbPatch = { + title?: string; + image?: string; + rating?: number; + releaseDate?: string; + overview?: string; +}; + +export type WatchItemRow = typeof watchItems.$inferSelect; + +export async function getWatchItem( + db: Db, + userId: string, + media: MediaIdentity, +): Promise { + const rows = await db + .select() + .from(watchItems) + .where( + and( + eq(watchItems.userId, userId), + eq(watchItems.tmdbId, media.tmdbId), + eq(watchItems.mediaType, media.mediaType), + ), + ) + .limit(1); + return rows[0]; +} + +export function buildMetadataPatch( + metadata: WatchItemMetadata, + existing?: WatchItemRow | null, +): MetadataDbPatch { + return { + title: metadata.title ?? existing?.title ?? undefined, + image: metadata.image ?? existing?.image ?? undefined, + rating: metadata.rating ?? existing?.rating ?? undefined, + releaseDate: metadata.release_date ?? existing?.releaseDate ?? undefined, + overview: metadata.overview ?? existing?.overview ?? undefined, + }; +} + +export type UpsertUpdate = + | (Partial> & Partial) + | (( + existing: WatchItemRow | null, + ) => + | (Partial> & Partial) + | null); + +/** + * Port of `upsertWatchItem` — insert or patch the unique (user, tmdb, media) + * watch item row. Timestamps are always set here (`updatedAt`). + */ +export async function upsertWatchItem( + db: Db, + userId: string, + tmdbId: number, + mediaType: MediaType, + updates: UpsertUpdate, +) { + const existing = await getWatchItem(db, userId, { tmdbId, mediaType }); + const finalUpdates = + typeof updates === "function" ? updates(existing ?? null) : updates; + if (!finalUpdates) return; + + const now = Date.now(); + const metadataPatch = buildMetadataPatch(finalUpdates, existing); + + if (existing) { + const patch: Partial> = { + updatedAt: now, + ...metadataPatch, + }; + if ("inWatchlist" in finalUpdates) + patch.inWatchlist = finalUpdates.inWatchlist; + if ("progressStatus" in finalUpdates) + patch.progressStatus = finalUpdates.progressStatus; + if ("progress" in finalUpdates) patch.progress = finalUpdates.progress; + if ("reaction" in finalUpdates) patch.reaction = finalUpdates.reaction; + + await db + .update(watchItems) + .set(patch) + .where(eq(watchItems.id, existing.id)); + return existing; + } + + const id = crypto.randomUUID(); + await db.insert(watchItems).values({ + id, + userId, + tmdbId, + mediaType, + inWatchlist: finalUpdates.inWatchlist ?? false, + progressStatus: finalUpdates.progressStatus ?? undefined, + progress: finalUpdates.progress ?? 0, + reaction: (finalUpdates.reaction as Reaction | undefined) ?? undefined, + updatedAt: now, + ...metadataPatch, + }); + return undefined; +} diff --git a/src/server/prompts.ts b/src/server/prompts.ts new file mode 100644 index 00000000..493d79b6 --- /dev/null +++ b/src/server/prompts.ts @@ -0,0 +1,411 @@ +// Port of `convex/prompts.ts` — unchanged logic, types adapted to the D1 rows. + +export interface WatchItemSummary { + tmdbId: number; + mediaType: "movie" | "tv"; + title: string | null; + rating: number | null; + progressStatus: string | null; + reaction: string | null; + progress: number | null; +} + +export interface CustomListSummary { + _id: string; + name: string; +} + +export interface CustomListItemSummary { + listId: string; + tmdbId: number; + mediaType: string; +} + +export interface WatchlistData { + watchItems: WatchItemSummary[]; + lists: CustomListSummary[]; + listItems: CustomListItemSummary[]; + inputStats: { + movieCount: number; + tvCount: number; + episodesWatched: number; + totalItems: number; + }; +} + +export interface FeedbackSignals { + likedTitles?: string[]; + dislikedTitles?: string[]; + dislikedTmdbIds?: number[]; + previousTitles?: string[]; +} + +export interface BasePromptConfig { + mediaTypePreference?: string; + yearFrom?: number; + yearTo?: number; + existingIds: number[]; + existingTitles: string[]; + feedback?: FeedbackSignals; + watchlistText?: string; + recommendationGoal?: string; + statsText?: string; +} + +export const RESPONSE_SCHEMA = `Respond with this exact JSON schema: +{ + "recommendations": [ + { + "title": "string - exact official title", + "tmdbId": "number or null if unknown", + "mediaType": "movie" or "tv", + "relevanceScore": "number 0-100", + "reasoning": "string - 1-2 sentence explanation" + } + ] +}`; + +export function formatItem(i: WatchItemSummary): string { + const parts = [ + `- ${i.title ?? "Unknown"} (TMDB ID: ${i.tmdbId}, ${i.mediaType})`, + ]; + if (i.rating) parts.push(`Rating: ${i.rating}/10`); + if (i.reaction) parts.push(`Reaction: ${i.reaction}`); + return parts.join(" | "); +} + +export function buildWatchlistContext( + data: WatchlistData, + excludeTmdbIds: number[] = [], +): { + contextPrompt: string; + existingIds: number[]; + existingTitles: string[]; +} { + const { watchItems } = data; + + const loved = watchItems.filter( + (i) => i.reaction === "loved" || i.reaction === "liked", + ); + const watching = watchItems.filter((i) => i.progressStatus === "watching"); + const watchLater = watchItems.filter( + (i) => i.progressStatus === "watch-later", + ); + const disliked = watchItems.filter( + (i) => + i.reaction === "not-for-me" || + i.reaction === "mixed" || + i.progressStatus === "dropped", + ); + const done = watchItems.filter( + (i) => + i.progressStatus === "done" && + i.reaction !== "loved" && + i.reaction !== "liked", + ); + + const prioritized = new Set( + [...loved, ...watching, ...done, ...watchLater, ...disliked] + .slice(0, 50) + .map((i) => i.tmdbId), + ); + const existingIds = [ + ...new Set([...watchItems.map((i) => i.tmdbId), ...excludeTmdbIds]), + ]; + const existingTitles = watchItems + .map((i) => i.title) + .filter((title): title is string => !!title); + const inScope = (item: WatchItemSummary) => prioritized.has(item.tmdbId); + + let prompt = ""; + const scopedLoved = loved.filter(inScope); + const scopedWatching = watching.filter(inScope); + const scopedDone = done.filter(inScope); + const scopedWatchLater = watchLater.filter(inScope); + const scopedDisliked = disliked.filter(inScope); + + if (scopedLoved.length > 0) { + prompt += `## Content I loved/liked:\n${scopedLoved.map(formatItem).join("\n")}\n\n`; + } + if (scopedWatching.length > 0) { + prompt += `## Currently watching:\n${scopedWatching.map(formatItem).join("\n")}\n\n`; + } + if (scopedDone.length > 0) { + prompt += `## Completed (no strong reaction):\n${scopedDone.map(formatItem).join("\n")}\n\n`; + } + if (scopedWatchLater.length > 0) { + prompt += `## On my watch-later list:\n${scopedWatchLater.map(formatItem).join("\n")}\n\n`; + } + if (scopedDisliked.length > 0) { + prompt += `## Content I didn't enjoy (dropped/mixed/not-for-me):\n${scopedDisliked.map(formatItem).join("\n")}\n\n`; + } + + return { contextPrompt: prompt, existingIds, existingTitles }; +} + +export function appendFeedbackSignals( + prompt: string, + feedback?: FeedbackSignals, +): string { + let result = prompt; + if (feedback?.likedTitles && feedback.likedTitles.length > 0) { + result += `## Recommendations I explicitly liked and want more content similar to:\n${feedback.likedTitles.map((t) => `- ${t}`).join("\n")}\n\n`; + } + if (feedback?.dislikedTitles && feedback.dislikedTitles.length > 0) { + result += `## Recommendations I explicitly marked as "not interested" (avoid similar styles/genres):\n${feedback.dislikedTitles.map((t) => `- ${t}`).join("\n")}\n\n`; + } + if (feedback?.previousTitles && feedback.previousTitles.length > 0) { + result += `## Previously recommended titles (do NOT repeat these):\n${feedback.previousTitles.map((t) => `- ${t}`).join("\n")}\n\n`; + } + return result; +} + +export function buildBasePromptSections(config: BasePromptConfig): string { + let prompt = ""; + + prompt = appendFeedbackSignals(prompt, config.feedback); + + if (config.statsText) { + prompt += config.statsText; + } + + if (config.mediaTypePreference === "movie") { + prompt += `IMPORTANT: Only recommend MOVIES. Do not suggest any TV shows.\n\n`; + } else if (config.mediaTypePreference === "tv") { + prompt += `IMPORTANT: Only recommend TV SHOWS. Do not suggest any movies.\n\n`; + } + + if (config.recommendationGoal) { + prompt += config.recommendationGoal; + } + + if (config.existingIds.length > 0) { + const wlText = config.watchlistText ?? " (already in my watchlist)"; + prompt += `Do NOT recommend any title with these TMDB IDs${wlText}: ${config.existingIds.join(", ")}\n`; + } + if (config.existingTitles.length > 0) { + prompt += `Do NOT recommend any of these already tracked titles by name: ${config.existingTitles.join(", ")}\n`; + } + prompt += "\n"; + + if (config.yearFrom || config.yearTo) { + const from = config.yearFrom ?? 1900; + const to = config.yearTo ?? new Date().getFullYear(); + prompt += `IMPORTANT: Only recommend titles released between ${from} and ${to} (inclusive).\n\n`; + } + + return prompt; +} + +export function buildWatchlistPrompt( + data: WatchlistData, + mediaTypePreference?: string, + excludeTmdbIds: number[] = [], + yearFrom?: number, + yearTo?: number, + count?: number, + feedback?: FeedbackSignals, +): string { + const { lists, listItems, inputStats } = data; + const { contextPrompt, existingIds, existingTitles } = buildWatchlistContext( + data, + excludeTmdbIds, + ); + + let prompt = `Here is my watchlist data:\n\n` + contextPrompt; + + const listItemsByListId = new Map(); + for (const li of listItems) { + const listIdStr = String(li.listId); + let items = listItemsByListId.get(listIdStr); + if (!items) { + items = []; + listItemsByListId.set(listIdStr, items); + } + items.push(li); + } + + const watchItemByMediaKey = new Map(); + for (const w of data.watchItems) { + watchItemByMediaKey.set(`${w.tmdbId}_${w.mediaType}`, w); + } + + if (lists.length > 0) { + prompt += `## My custom lists:\n`; + for (const list of lists) { + const items = listItemsByListId.get(String(list._id)) ?? []; + const titles = items + .map((li) => { + const wi = watchItemByMediaKey.get(`${li.tmdbId}_${li.mediaType}`); + return wi?.title ?? `TMDB:${li.tmdbId}`; + }) + .join(", "); + prompt += `- "${list.name}": ${titles}\n`; + } + prompt += "\n"; + } + + const mediaLabel = + mediaTypePreference === "movie" + ? "movies" + : mediaTypePreference === "tv" + ? "TV shows" + : "movies and TV shows"; + const titleCount = Math.min(Math.max(count ?? 10, 1), 30); + + prompt += buildBasePromptSections({ + mediaTypePreference, + yearFrom, + yearTo, + existingIds, + existingTitles, + feedback, + watchlistText: " (already in my watchlist)", + recommendationGoal: `Based on this data, recommend exactly ${titleCount} ${mediaLabel} I would likely enjoy.\n`, + statsText: `## Stats:\n- ${inputStats.movieCount} movies, ${inputStats.tvCount} TV shows tracked\n- ${inputStats.episodesWatched} episodes watched\n\n`, + }); + + prompt += RESPONSE_SCHEMA; + + return prompt; +} + +export function buildGenrePrompt( + data: WatchlistData, + mediaTypePreference?: string, + genrePreference?: string, + excludeTmdbIds: number[] = [], + yearFrom?: number, + yearTo?: number, + count?: number, + feedback?: FeedbackSignals, +): string { + const { existingIds, existingTitles } = buildWatchlistContext( + data, + excludeTmdbIds, + ); + + const mediaLabel = + mediaTypePreference === "movie" + ? "movies" + : mediaTypePreference === "tv" + ? "TV shows" + : "movies and TV shows"; + const titleCount = Math.min(Math.max(count ?? 10, 1), 30); + + let prompt = `Recommend me exactly ${titleCount} popular and highly-rated ${mediaLabel}`; + + if (genrePreference) { + prompt += ` in these genres: ${genrePreference}`; + } + prompt += `.\n\n`; + + prompt += `Focus on well-known, critically acclaimed titles that are widely loved. Include a mix of classic and recent titles.\n\n`; + + prompt += buildBasePromptSections({ + mediaTypePreference, + yearFrom, + yearTo, + existingIds, + existingTitles, + feedback, + watchlistText: " (already in my watchlist)", + }); + + prompt += RESPONSE_SCHEMA; + return prompt; +} + +export function buildCustomListPrompt( + data: WatchlistData, + listId: string, + mediaTypePreference?: string, + excludeTmdbIds: number[] = [], + yearFrom?: number, + yearTo?: number, + count?: number, + feedback?: FeedbackSignals, +): string { + const { existingIds, existingTitles } = buildWatchlistContext( + data, + excludeTmdbIds, + ); + + const mediaLabel = + mediaTypePreference === "movie" + ? "movies" + : mediaTypePreference === "tv" + ? "TV shows" + : "movies and TV shows"; + const titleCount = Math.min(Math.max(count ?? 10, 1), 30); + + const list = data.lists.find((l) => l._id === listId); + const listName = list?.name ?? "this custom list"; + + const watchItemByMediaKey = new Map(); + for (const w of data.watchItems) { + watchItemByMediaKey.set(`${w.tmdbId}_${w.mediaType}`, w); + } + + const items = data.listItems.filter((li) => li.listId === listId); + const titles = items + .map((li) => { + const wi = watchItemByMediaKey.get(`${li.tmdbId}_${li.mediaType}`); + return wi?.title + ? `- ${wi.title} (${li.mediaType})` + : `- TMDB ID: ${li.tmdbId} (${li.mediaType})`; + }) + .join("\n"); + + let prompt = `Here are the movies and TV shows in my custom list "${listName}":\n\n${titles}\n\n`; + + prompt += buildBasePromptSections({ + mediaTypePreference, + yearFrom, + yearTo, + existingIds, + existingTitles, + feedback, + watchlistText: " (already in my overall watchlist)", + recommendationGoal: `Based on these titles, recommend exactly ${titleCount} ${mediaLabel} I would likely enjoy.\nFind movies/shows that share similar themes, genres, directors, actors, or vibe as the ones in the list.\n\n`, + }); + + prompt += RESPONSE_SCHEMA; + return prompt; +} + +export function buildHomepageRecommendationsPrompt( + data: WatchlistData, + likedFeedbackTitles: string[], + dislikedFeedbackTitles: string[], + excludeTmdbIds: number[], + previousTitles: string[], +): string { + const { inputStats } = data; + const { contextPrompt, existingIds, existingTitles } = buildWatchlistContext( + data, + excludeTmdbIds, + ); + + let prompt = + `You are generating personalized recommendations for the user's homepage.\n\n` + + `Here is the user's watchlist/viewing data:\n\n` + + contextPrompt; + + prompt += buildBasePromptSections({ + existingIds, + existingTitles, + feedback: { + likedTitles: likedFeedbackTitles, + dislikedTitles: dislikedFeedbackTitles, + previousTitles, + }, + watchlistText: "", + recommendationGoal: `Based on this data, recommend exactly 15 movies and 15 TV shows I would likely enjoy.\n`, + statsText: `## Stats:\n- ${inputStats.movieCount} movies, ${inputStats.tvCount} TV shows tracked\n- ${inputStats.episodesWatched} episodes watched\n\n`, + }); + + prompt += RESPONSE_SCHEMA; + + return prompt; +} diff --git a/src/server/rbac.ts b/src/server/rbac.ts new file mode 100644 index 00000000..79346597 --- /dev/null +++ b/src/server/rbac.ts @@ -0,0 +1,277 @@ +import { and, eq } from "drizzle-orm"; +import type { AuthUser, ClerkSessionClaims } from "./auth"; +import type { Db } from "./db/client"; +import { getDb } from "./db/client"; +import { rolePermissions } from "./db/schema"; +import { getEnv } from "./env"; + +export const DYNAMIC_ROLES = ["video-player", "ai-integrations"] as const; +export const VALID_FEATURES = ["video-player", "ai-recommendations"] as const; + +export type DynamicRbacRole = (typeof DYNAMIC_ROLES)[number]; +export type RbacFeature = (typeof VALID_FEATURES)[number]; + +const ADMIN_PERMISSIONS: Record = { + "video-player": true, + "ai-recommendations": true, +}; + +const DEFAULT_PERMISSIONS: Record< + DynamicRbacRole, + Record +> = { + "video-player": { + "video-player": true, + "ai-recommendations": false, + }, + "ai-integrations": { + "video-player": false, + "ai-recommendations": true, + }, +}; + +const ROLE_FEATURES: Record = { + "video-player": "video-player", + "ai-integrations": "ai-recommendations", +}; + +function parseClerkPublicMeta( + identity: Record | null, +): Record | null { + if (!identity) return null; + + const candidates = [identity.public_meta, identity.publicMetadata, identity]; + + for (const candidate of candidates) { + if (!candidate) continue; + if (typeof candidate === "string") { + try { + const parsed = JSON.parse(candidate) as unknown; + if (parsed && typeof parsed === "object") { + return parsed as Record; + } + } catch { + // Ignore malformed metadata claim payloads. + } + continue; + } + if (typeof candidate === "object") { + return candidate as Record; + } + } + + return null; +} + +export function isClerkAdmin( + identity: Record | null, + dbUser?: { isAdmin?: boolean | null } | null, +): boolean { + if (parseClerkPublicMeta(identity)?.isAdmin === true) return true; + if (dbUser?.isAdmin === true) return true; + return false; +} + +async function loadPermissions(db: Db) { + return db.select().from(rolePermissions).limit(100); +} + +async function computeRoleFeatures( + db: Db, + roles: string[], +): Promise> { + const features: Record = {}; + const allPermissions = await loadPermissions(db); + + const permissionMap = new Map(); + for (const p of allPermissions) { + permissionMap.set(`${p.role}:${p.feature}`, p.enabled); + } + + for (const feature of VALID_FEATURES) { + const globalEnabled = permissionMap.get(`global:${feature}`); + const isGloballyEnabled = + globalEnabled !== undefined ? globalEnabled : true; + + let enabled = false; + if (isGloballyEnabled) { + for (const role of roles) { + if (!DYNAMIC_ROLES.includes(role as DynamicRbacRole)) continue; + const existingEnabled = permissionMap.get(`${role}:${feature}`); + if (existingEnabled !== undefined) { + if (existingEnabled) enabled = true; + } else if ( + DEFAULT_PERMISSIONS[role as DynamicRbacRole]?.[feature] === true + ) { + enabled = true; + } + } + } + features[feature] = enabled; + } + + return features; +} + +/** + * `hasFeature` port — evaluates RBAC for the given feature. + * `user` may be null (unauthenticated); `claims` supplies the admin claim. + */ +export async function hasFeature( + claims: ClerkSessionClaims | null, + user: AuthUser | null, + feature: RbacFeature, +): Promise { + if (!claims) return false; + + if (user?.isBanned === true) return false; + if (isClerkAdmin(claims as unknown as Record, user)) { + return true; + } + if (!user) return false; + + const db = getDb(getEnv()); + const globalSetting = await db + .select() + .from(rolePermissions) + .where( + and( + eq(rolePermissions.role, "global"), + eq(rolePermissions.feature, feature), + ), + ) + .limit(1); + + const isGloballyEnabled = + globalSetting.length > 0 ? globalSetting[0].enabled : true; + if (!isGloballyEnabled) return false; + + for (const role of user.roles ?? []) { + if (!DYNAMIC_ROLES.includes(role as DynamicRbacRole)) continue; + + const existing = await db + .select() + .from(rolePermissions) + .where( + and( + eq(rolePermissions.role, role), + eq(rolePermissions.feature, feature), + ), + ) + .limit(1); + + if (existing.length > 0 && existing[0].enabled) return true; + if ( + existing.length === 0 && + DEFAULT_PERMISSIONS[role as DynamicRbacRole]?.[feature] + ) { + return true; + } + } + + return false; +} + +/** + * `getUserFeatures` port — returns the RBAC summary for the request. + */ +export async function getUserFeatures( + claims: ClerkSessionClaims | null, + user: AuthUser | null, +) { + if (!claims) { + return { + roles: [] as string[], + features: {}, + isAdmin: false, + isBanned: false, + }; + } + + if (user?.isBanned === true) { + return { + roles: [] as string[], + features: {}, + isAdmin: false, + isBanned: true, + }; + } + if (isClerkAdmin(claims as unknown as Record, user)) { + return { + roles: [] as string[], + features: { ...ADMIN_PERMISSIONS }, + isAdmin: true, + isBanned: false, + }; + } + if (!user) { + return { + roles: [] as string[], + features: {}, + isAdmin: false, + isBanned: false, + }; + } + + const db = getDb(getEnv()); + const roles = (user.roles ?? []).filter((role) => + DYNAMIC_ROLES.includes(role as DynamicRbacRole), + ); + const features = await computeRoleFeatures(db, roles); + + return { roles, features, isAdmin: false, isBanned: false }; +} + +/** + * `syncRolePermissions` port — prunes invalid rows and seeds defaults. + */ +export async function syncRolePermissions( + db: Db, + force = false, +): Promise { + const existingPermissions = await loadPermissions(db); + + if (!force && existingPermissions.length > 0) { + return; + } + + for (const permission of existingPermissions) { + const isValidRole = + DYNAMIC_ROLES.includes(permission.role as DynamicRbacRole) || + permission.role === "global"; + const isValidFeature = VALID_FEATURES.includes( + permission.feature as RbacFeature, + ); + if ( + !isValidRole || + !isValidFeature || + (permission.role !== "global" && + ROLE_FEATURES[permission.role as DynamicRbacRole] !== + permission.feature) + ) { + await db + .delete(rolePermissions) + .where( + and( + eq(rolePermissions.role, permission.role), + eq(rolePermissions.feature, permission.feature), + ), + ); + } + } + + for (const role of DYNAMIC_ROLES) { + const feature = ROLE_FEATURES[role]; + const existing = existingPermissions.find( + (permission) => + permission.role === role && permission.feature === feature, + ); + if (!existing) { + await db.insert(rolePermissions).values({ + role, + feature, + enabled: DEFAULT_PERMISSIONS[role][feature], + }); + } + } +} diff --git a/src/server/schema/admin.ts b/src/server/schema/admin.ts new file mode 100644 index 00000000..2e159d00 --- /dev/null +++ b/src/server/schema/admin.ts @@ -0,0 +1,25 @@ +import { z } from "zod"; + +export const setRolePermissionArgsSchema = z.object({ + role: z.string(), + feature: z.string(), + enabled: z.boolean(), +}); +export type SetRolePermissionArgs = z.infer; + +export const setUserRolesArgsSchema = z.object({ + tokenIdentifier: z.string(), + roles: z.array(z.enum(["video-player", "ai-integrations"])), +}); +export type SetUserRolesArgs = z.infer; + +export const setUserBannedArgsSchema = z.object({ + tokenIdentifier: z.string(), + banned: z.boolean(), +}); +export type SetUserBannedArgs = z.infer; + +export const listUsersArgsSchema = z.object({ + limit: z.number().optional(), +}); +export type ListUsersArgs = z.infer; diff --git a/src/server/schema/common.ts b/src/server/schema/common.ts new file mode 100644 index 00000000..65125327 --- /dev/null +++ b/src/server/schema/common.ts @@ -0,0 +1,77 @@ +import { z } from "zod"; + +export const mediaTypeSchema = z.enum(["movie", "tv"]); +export type MediaType = z.infer; + +export const progressStatusSchema = z.enum([ + "watch-later", + "watching", + "done", + "dropped", +]); +export type ProgressStatus = z.infer; + +export const reactionSchema = z.enum([ + "loved", + "liked", + "mixed", + "not-for-me", + "recommended", +]); +export type Reaction = z.infer; + +export const feedbackSchema = z.enum(["like", "not_interested", "dislike"]); +export type Feedback = z.infer; + +export const metadataSchema = z.object({ + title: z.string().optional(), + image: z.string().optional(), + rating: z.number().optional(), + release_date: z.string().optional(), + overview: z.string().optional(), +}); +export type MediaMetadata = z.infer; + +// --------------------------------------------------------------------------- +// Typed error contract (replaces Convex's bare `throw new Error`) +// --------------------------------------------------------------------------- + +export const errorCodeSchema = z.enum([ + "UNAUTHORIZED", + "FORBIDDEN", + "NOT_FOUND", + "RATE_LIMITED", + "CONFLICT", + "BAD_REQUEST", +]); +export type ErrorCode = z.infer; + +export type ApiResult = + | { ok: true; data: T } + | { ok: false; code: ErrorCode; message: string }; + +export const ok = (data: T): ApiResult => ({ ok: true, data }); + +export const fail = (code: ErrorCode, message: string): ApiResult => ({ + ok: false, + code, + message, +}); + +export class ApiError extends Error { + code: ErrorCode; + constructor(code: ErrorCode, message: string) { + super(message); + this.name = "ApiError"; + this.code = code; + } +} + +/** + * Unwrap a typed result on the client. Throws an `ApiError` on non-ok so + * TanStack Query's error path (and optimistic rollback) fires. + */ +export function unwrap(result: ApiResult): T { + if (result.ok) return result.data; + throw new ApiError(result.code, result.message); +} diff --git a/src/server/schema/import.ts b/src/server/schema/import.ts new file mode 100644 index 00000000..1e7a91a7 --- /dev/null +++ b/src/server/schema/import.ts @@ -0,0 +1,33 @@ +import { z } from "zod"; +import { + mediaTypeSchema, + progressStatusSchema, + reactionSchema, +} from "./common"; + +export const importItemSchema = z.object({ + tmdbId: z.number(), + mediaType: mediaTypeSchema, + title: z.string(), + image: z.string().optional(), + rating: z.number().optional(), + release_date: z.string().optional(), + overview: z.string().optional(), + progressStatus: progressStatusSchema.optional(), + progress: z.number().optional(), + reaction: reactionSchema.nullable().optional(), +}); +export type ImportItem = z.infer; + +export const watchedEpisodeSchema = z.object({ + tmdbId: z.number(), + season: z.number(), + episode: z.number(), +}); +export type WatchedEpisode = z.infer; + +export const importWatchlistArgsSchema = z.object({ + items: z.array(importItemSchema), + watchedEpisodes: z.array(watchedEpisodeSchema), +}); +export type ImportWatchlistArgs = z.infer; diff --git a/src/server/schema/lists.ts b/src/server/schema/lists.ts new file mode 100644 index 00000000..ccbf3b1c --- /dev/null +++ b/src/server/schema/lists.ts @@ -0,0 +1,56 @@ +import { z } from "zod"; +import { mediaTypeSchema, metadataSchema } from "./common"; + +export const createCustomListArgsSchema = z.object({ + name: z.string(), + color: z.string().optional(), + visibility: z.string().optional(), + listType: z.string().optional(), +}); +export type CreateCustomListArgs = z.infer; + +export const updateCustomListArgsSchema = z.object({ + listId: z.string(), + name: z.string().optional(), + color: z.string().optional(), + visibility: z.string().optional(), + listType: z.string().optional(), +}); +export type UpdateCustomListArgs = z.infer; + +export const deleteCustomListArgsSchema = z.object({ + listId: z.string(), +}); +export type DeleteCustomListArgs = z.infer; + +export const getListItemsArgsSchema = z.object({ + listId: z.string(), +}); +export type GetListItemsArgs = z.infer; + +export const getItemListsArgsSchema = z.object({ + tmdbId: z.number(), + mediaType: mediaTypeSchema, +}); +export type GetItemListsArgs = z.infer; + +export const toggleListItemArgsSchema = z + .object({ + listId: z.string(), + tmdbId: z.number(), + mediaType: mediaTypeSchema, + backdrop: z.string().optional(), + }) + .merge(metadataSchema); +export type ToggleListItemArgs = z.infer; + +export const createCustomListAndAddItemArgsSchema = createCustomListArgsSchema + .extend({ + tmdbId: z.number(), + mediaType: mediaTypeSchema, + backdrop: z.string().optional(), + }) + .merge(metadataSchema); +export type CreateCustomListAndAddItemArgs = z.infer< + typeof createCustomListAndAddItemArgsSchema +>; diff --git a/src/server/schema/recommendations.ts b/src/server/schema/recommendations.ts new file mode 100644 index 00000000..a3f5693c --- /dev/null +++ b/src/server/schema/recommendations.ts @@ -0,0 +1,109 @@ +import { z } from "zod"; +import { mediaTypeSchema } from "./common"; + +export const recommendationSchema = z.object({ + title: z.string(), + tmdbId: z.number().nullable(), + mediaType: mediaTypeSchema, + relevanceScore: z.number(), + reasoning: z.string(), +}); +export type Recommendation = z.infer; + +export const inputStatsSchema = z.object({ + movieCount: z.number(), + tvCount: z.number(), + episodesWatched: z.number(), + totalItems: z.number(), +}); +export type InputStats = z.infer; + +export const generateRecommendationsArgsSchema = z.object({ + generationType: z.string().optional(), + listId: z.string().optional(), + mediaTypePreference: mediaTypeSchema.optional(), + genrePreference: z.string().optional(), + excludeTmdbIds: z.array(z.number()).optional(), + yearFrom: z.number().optional(), + yearTo: z.number().optional(), + count: z.number().optional(), +}); +export type GenerateRecommendationsArgs = z.infer< + typeof generateRecommendationsArgsSchema +>; + +export type GenerateResult = + | { + recommendations: Recommendation[]; + inputStats: InputStats; + generatedAt: number; + cached: boolean; + } + | { error: string }; + +export const deleteRecommendationArgsSchema = z.object({ + id: z.string(), +}); +export type DeleteRecommendationArgs = z.infer< + typeof deleteRecommendationArgsSchema +>; + +export const updateVerifiedRecommendationsArgsSchema = z.object({ + id: z.string(), + recommendations: z.string(), +}); +export type UpdateVerifiedRecommendationsArgs = z.infer< + typeof updateVerifiedRecommendationsArgsSchema +>; + +export const setRecommendationFeedbackArgsSchema = z.object({ + tmdbId: z.number(), + mediaType: mediaTypeSchema, + title: z.string(), + feedback: z.enum(["not_interested", "like"]), + image: z.string().optional(), + backdrop: z.string().optional(), + rating: z.number().optional(), + release_date: z.string().optional(), + overview: z.string().optional(), +}); +export type SetRecommendationFeedbackArgs = z.infer< + typeof setRecommendationFeedbackArgsSchema +>; + +export const removeRecommendationFeedbackArgsSchema = z.object({ + tmdbId: z.number(), + mediaType: mediaTypeSchema, +}); +export type RemoveRecommendationFeedbackArgs = z.infer< + typeof removeRecommendationFeedbackArgsSchema +>; + +export const getHomepageRecommendationsArgsSchema = z.object({ + now: z.number().optional(), +}); +export type GetHomepageRecommendationsArgs = z.infer< + typeof getHomepageRecommendationsArgsSchema +>; + +export type HomepageRecommendationsResult = { + recommendations: Recommendation[]; + lastUpdatedAt: number; + lastAttemptedAt: number; + status: string; + needsRefresh: boolean; +}; + +export const getUserRecommendationAccessResultSchema = z.discriminatedUnion( + "hasAccess", + [ + z.object({ hasAccess: z.literal(true) }), + z.object({ + hasAccess: z.literal(false), + reason: z.enum(["not_authenticated", "feature_disabled"]), + }), + ], +); +export type UserRecommendationAccessResult = z.infer< + typeof getUserRecommendationAccessResultSchema +>; diff --git a/src/server/schema/watchlist.ts b/src/server/schema/watchlist.ts new file mode 100644 index 00000000..502e5368 --- /dev/null +++ b/src/server/schema/watchlist.ts @@ -0,0 +1,92 @@ +import { z } from "zod"; +import { + mediaTypeSchema, + metadataSchema, + progressStatusSchema, + reactionSchema, +} from "./common"; + +export const getWatchlistArgsSchema = z.object({ + limit: z.number().optional(), + statusFilter: z.string().optional(), +}); +export type GetWatchlistArgs = z.infer; + +export const mediaIdentityArgsSchema = z.object({ + tmdbId: z.number(), + mediaType: mediaTypeSchema, +}); +export type MediaIdentityArgs = z.infer; + +export const setWatchlistMembershipArgsSchema = mediaIdentityArgsSchema + .extend({ + inWatchlist: z.boolean(), + }) + .merge(metadataSchema); +export type SetWatchlistMembershipArgs = z.infer< + typeof setWatchlistMembershipArgsSchema +>; + +export const setProgressStatusArgsSchema = mediaIdentityArgsSchema + .extend({ + progressStatus: progressStatusSchema, + progress: z.number().optional(), + }) + .merge(metadataSchema); +export type SetProgressStatusArgs = z.infer; + +export const setReactionArgsSchema = mediaIdentityArgsSchema + .extend({ + reaction: reactionSchema.optional(), + clearReaction: z.boolean().optional(), + }) + .merge(metadataSchema); +export type SetReactionArgs = z.infer; + +export const updateProgressArgsSchema = mediaIdentityArgsSchema + .extend({ + progress: z.number().optional(), + isWatched: z.boolean().optional(), + }) + .merge(metadataSchema); +export type UpdateProgressArgs = z.infer; + +export const markEpisodeWatchedArgsSchema = z.object({ + tmdbId: z.number(), + season: z.number(), + episode: z.number(), + isWatched: z.boolean(), +}); +export type MarkEpisodeWatchedArgs = z.infer< + typeof markEpisodeWatchedArgsSchema +>; + +export const markSeasonEpisodesWatchedArgsSchema = z.object({ + tmdbId: z.number(), + season: z.number(), + episodes: z.array(z.number()), + isWatched: z.boolean(), +}); +export type MarkSeasonEpisodesWatchedArgs = z.infer< + typeof markSeasonEpisodesWatchedArgsSchema +>; + +export const markShowEpisodesAndStatusArgsSchema = z + .object({ + tmdbId: z.number(), + mediaType: mediaTypeSchema, + seasons: z.array( + z.object({ + season: z.number(), + episodes: z.array(z.number()), + }), + ), + isWatched: z.boolean(), + clearAllEpisodes: z.boolean().optional(), + progressStatus: progressStatusSchema.optional(), + progress: z.number().optional(), + }) + .merge(metadataSchema); +export type MarkShowEpisodesAndStatusArgs = z.infer< + typeof markShowEpisodesAndStatusArgsSchema +>; diff --git a/wrangler.toml b/wrangler.toml new file mode 100644 index 00000000..fa7864c9 --- /dev/null +++ b/wrangler.toml @@ -0,0 +1,25 @@ +# Cloudflare Workers + D1 (free tier) +name = "pebbly" +main = ".output/server/index.mjs" +compatibility_date = "2026-08-08" +compatibility_flags = ["nodejs_compat"] +workers_dev = true + +# Frontend static assets served from the edge +[assets] +directory = ".output/public" +binding = "ASSETS" + +# D1 database (free tier: 5 GB) +[[d1_databases]] +binding = "DB" +database_name = "pebbly" +database_id = "cf94e4ee-291d-499f-b463-ef61ee9d9e1d" +migrations_dir = "drizzle" + +# Daily watchlist snapshot, 03:00 UTC +[triggers] +crons = ["0 3 * * *"] + +# Non-secret server vars only. Secrets: wrangler secret put . +# Client VITE_* vars are inlined at build time from .env — they do NOT go here. From 99403d90d74883881bb0874ad8534ca9cd7a5d51 Mon Sep 17 00:00:00 2001 From: Swastik Dan <57379785+Swastikdan@users.noreply.github.com> Date: Sun, 16 Aug 2026 01:16:29 +0530 Subject: [PATCH 02/27] feat(backend): implement Cloudflare Workers backend with D1 and Nitro --- .env.example | 4 + .github/workflows/deploy.yml | 38 + drizzle.studio.config.ts | 41 + package.json | 35 +- server/routes/api/health.ts | 27 +- .../admin/admin-permission-toggles.tsx | 23 +- src/components/admin/admin-user-table.tsx | 64 +- src/components/custom-list-picker.tsx | 57 +- src/components/homepage-recommendations.tsx | 92 ++- src/components/user-sync.tsx | 20 +- src/hooks/optimistic-helpers.ts | 69 +- src/hooks/use-custom-lists.ts | 676 +++++++++-------- src/hooks/use-permissions.ts | 33 +- src/hooks/use-recommendations.ts | 123 +-- src/hooks/use-watch-progress.ts | 527 +++++++------ src/hooks/use-watchlist-import-export.ts | 49 +- src/hooks/use-watchlist.ts | 702 +++++++++++------- src/hooks/watchlist-store.ts | 24 +- src/lib/query/keys.ts | 32 + src/lib/server-types.ts | 36 + src/routeTree.gen.ts | 3 +- src/router.tsx | 10 +- src/routes/__root.tsx | 10 + src/routes/recommendations.lazy.tsx | 51 +- src/server/auth.ts | 56 +- src/server/db/client.ts | 8 + src/server/fns/admin.ts | 32 +- src/server/fns/recommendations.ts | 10 +- src/server/fns/watchlist.ts | 2 +- src/server/rbac.ts | 12 +- src/server/schema/common.ts | 12 +- src/start.ts | 31 + 32 files changed, 1793 insertions(+), 1116 deletions(-) create mode 100644 .github/workflows/deploy.yml create mode 100644 drizzle.studio.config.ts create mode 100644 src/lib/query/keys.ts create mode 100644 src/lib/server-types.ts create mode 100644 src/start.ts diff --git a/.env.example b/.env.example index 05b47a70..9cda1aca 100644 --- a/.env.example +++ b/.env.example @@ -34,3 +34,7 @@ CLERK_ISSUER_URL=https://your-app.clerk.accounts.dev UPSTASH_REDIS_REST_URL=https://your-db.upstash.io UPSTASH_REDIS_REST_TOKEN=your-rest-token UPSTASH_REDIS_READONLY_REST_TOKEN=your-readonly-rest-token + +# Cloudflare (only needed for `pnpm db:studio` remote dashboard + GitHub Actions) +CLOUDFLARE_API_TOKEN=your-api-token-with-d1-edit +CLOUDFLARE_ACCOUNT_ID=your-account-id diff --git a/.github/workflows/deploy.yml b/.github/workflows/deploy.yml new file mode 100644 index 00000000..3c7e68a6 --- /dev/null +++ b/.github/workflows/deploy.yml @@ -0,0 +1,38 @@ +name: Deploy Cloudflare +on: + push: + branches: [master] + +jobs: + deploy: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - uses: pnpm/action-setup@v4 + - uses: actions/setup-node@v4 + with: { node-version: 22, cache: pnpm } + - run: pnpm install --frozen-lockfile + - run: pnpm typecheck + + - name: Apply D1 migrations (prod) + uses: cloudflare/wrangler-action@v3 + with: + apiToken: ${{ secrets.CLOUDFLARE_API_TOKEN }} + accountId: ${{ secrets.CLOUDFLARE_ACCOUNT_ID }} + command: d1 migrations apply pebbly --remote + + - name: Build (Nitro cloudflare preset) + run: pnpm build + env: + VITE_CLERK_PUBLISHABLE_KEY: ${{ secrets.VITE_CLERK_PUBLISHABLE_KEY }} + VITE_PUBLIC_TMDB_ACCESS_TOKEN: ${{ secrets.VITE_PUBLIC_TMDB_ACCESS_TOKEN }} + VITE_PUBLIC_TMDB_API_URL: ${{ secrets.VITE_PUBLIC_TMDB_API_URL }} + VITE_PUBLIC_APP_URL: ${{ secrets.VITE_PUBLIC_APP_URL }} + VITE_PUBLIC_VIDEO_URL: ${{ secrets.VITE_PUBLIC_VIDEO_URL }} + + - name: Deploy Worker + uses: cloudflare/wrangler-action@v3 + with: + apiToken: ${{ secrets.CLOUDFLARE_API_TOKEN }} + accountId: ${{ secrets.CLOUDFLARE_ACCOUNT_ID }} + command: deploy diff --git a/drizzle.studio.config.ts b/drizzle.studio.config.ts new file mode 100644 index 00000000..9dca7715 --- /dev/null +++ b/drizzle.studio.config.ts @@ -0,0 +1,41 @@ +import { defineConfig } from "drizzle-kit"; +import fs from "node:fs"; + +/** + * Drizzle Studio dashboard for the remote (production) D1 database. + * + * pnpm db:studio + * + * Uses the `d1-http` driver (Cloudflare API) — no local sqlite client needed. + * Credentials come from the environment: + * - CLOUDFLARE_API_TOKEN (API token with "D1 Edit" permission) + * - CLOUDFLARE_ACCOUNT_ID (Cloudflare account id) + * The database id is read from wrangler.toml. + * + * For the local D1 database use: + * wrangler d1 execute pebbly --local --command "SELECT * FROM watch_items;" + */ +function readWranglerTomlValue(key: string): string | undefined { + try { + const raw = fs.readFileSync( + new URL("./wrangler.toml", import.meta.url), + "utf8", + ); + const match = raw.match(new RegExp(`^${key}\\s*=\\s*"([^"]+)"`, "m")); + return match?.[1]; + } catch { + return undefined; + } +} + +export default defineConfig({ + dialect: "sqlite", + schema: "./src/server/db/schema.ts", + out: "./drizzle", + driver: "d1-http", + dbCredentials: { + accountId: process.env.CLOUDFLARE_ACCOUNT_ID ?? "", + databaseId: readWranglerTomlValue("database_id") ?? "", + token: process.env.CLOUDFLARE_API_TOKEN ?? "", + }, +}); diff --git a/package.json b/package.json index 0e1cc5bb..3ec1cf22 100644 --- a/package.json +++ b/package.json @@ -1,24 +1,23 @@ { "name": "pebbly", "private": true, - "type": "module", - "scripts": { - "dev": "concurrently -n web,convex -c blue,magenta \"vite dev --port 5296 --host\" \"pnpm dlx convex dev\"", - "dev:web": "vite dev --port 3000", - "dev:cf": "wrangler dev", - "build": "vite build", - "build:vercel": "pnpm dlx convex deploy --cmd 'pnpm run build' --cmd-url-env-var-name VITE_CONVEX_URL", - "start": "vite preview --port 5296", - "db:generate": "drizzle-kit generate", - "db:migrate:local": "wrangler d1 migrations apply pebbly --local", - "db:migrate:prod": "wrangler d1 migrations apply pebbly --remote", - "deploy:cf": "pnpm build && wrangler deploy", - "lint": "biome lint --max-diagnostics 20", - "format": "biome format --write .", - "typecheck": "tsc --noEmit", - "typecheck:convex": "pnpm dlx convex typecheck", - "prepare": "husky" - }, + "type": "module", "scripts": { + "dev": "vite dev --port 3000", + "dev:web": "vite dev --port 3000", + "dev:cf": "wrangler dev", + "preview:cf": "pnpm build && wrangler dev", + "build": "vite build", + "start": "vite preview --port 5296", + "db:generate": "drizzle-kit generate", + "db:migrate:local": "wrangler d1 migrations apply pebbly --local", + "db:migrate:prod": "wrangler d1 migrations apply pebbly --remote", + "db:studio": "drizzle-kit studio --config drizzle.studio.config.ts", + "deploy:cf": "pnpm build && wrangler deploy", + "lint": "biome lint --max-diagnostics 20", + "format": "biome format --write .", + "typecheck": "tsc --noEmit", + "prepare": "husky" + }, "lint-staged": { "*.{js,jsx,ts,tsx,json,jsonc}": [ "biome check --fix --no-errors-on-unmatched --files-ignore-unknown=true" diff --git a/server/routes/api/health.ts b/server/routes/api/health.ts index 6f4c5aa8..27014171 100644 --- a/server/routes/api/health.ts +++ b/server/routes/api/health.ts @@ -13,17 +13,22 @@ export default defineEventHandler(async () => { const checks: Record = {}; let ok = true; - // D1 ping - try { - const db = getDb(env); - await db.run(sql`select 1`); - checks.db = { ok: true }; - } catch (error) { - ok = false; - checks.db = { - ok: false, - error: error instanceof Error ? error.message : String(error), - }; + // D1 ping — skipped when there's no binding (plain Node `vite dev`); on the + // Worker (`wrangler dev` / deployed) the DB binding is always present. + if (!env.DB) { + checks.db = { ok: true, skipped: "no D1 binding (vite dev)" }; + } else { + try { + const db = getDb(env); + await db.run(sql`select 1`); + checks.db = { ok: true }; + } catch (error) { + ok = false; + checks.db = { + ok: false, + error: error instanceof Error ? error.message : String(error), + }; + } } // Upstash ping (REST) — only when configured diff --git a/src/components/admin/admin-permission-toggles.tsx b/src/components/admin/admin-permission-toggles.tsx index 76679429..a9f7574a 100644 --- a/src/components/admin/admin-permission-toggles.tsx +++ b/src/components/admin/admin-permission-toggles.tsx @@ -1,4 +1,4 @@ -import { useMutation, useQuery } from "convex/react"; +import { useMutation, useQuery } from "@tanstack/react-query"; import { Activity, AlertTriangle, Zap } from "lucide-react"; import { Skeleton } from "@/components/ui/skeleton"; import { @@ -6,7 +6,8 @@ import { RBAC_FEATURES, type RbacFeature, } from "@/constants"; -import { api } from "../../../convex/_generated/api"; +import { getRolePermissions, setRolePermission } from "@/server/fns/admin"; +import { unwrap } from "@/server/schema/common"; const FEATURE_ROLES: Record = { "video-player": "video-player", @@ -100,10 +101,18 @@ function FeatureRow({ } export function AdminPermissionToggles() { - const rawPermissions = useQuery(api.admin.getRolePermissions, {}); - const setRolePermission = useMutation(api.admin.setRolePermission); + const rawPermissions = useQuery({ + queryKey: ["admin", "role-permissions"], + queryFn: () => unwrap(getRolePermissions()), + }); + const setRolePermissionMutation = useMutation({ + mutationFn: (args: { role: string; feature: string; enabled: boolean }) => + unwrap(setRolePermission({ data: args })), + }); - if (rawPermissions === undefined) { + const rawPermissionsData = rawPermissions.data; + + if (rawPermissionsData === undefined) { return (
@@ -112,7 +121,7 @@ export function AdminPermissionToggles() { ); } - const permissionsByRole = rawPermissions as Record< + const permissionsByRole = rawPermissionsData as Record< PermissionRole, Record >; @@ -127,7 +136,7 @@ export function AdminPermissionToggles() { featureLabel={config.label} permissionsByRole={permissionsByRole} onToggle={(role, enabled) => - setRolePermission({ role, feature, enabled }) + setRolePermissionMutation.mutate({ role, feature, enabled }) } /> ))} diff --git a/src/components/admin/admin-user-table.tsx b/src/components/admin/admin-user-table.tsx index bc06088e..843ae33e 100644 --- a/src/components/admin/admin-user-table.tsx +++ b/src/components/admin/admin-user-table.tsx @@ -1,5 +1,5 @@ import { useUser } from "@clerk/react"; -import { useMutation, useQuery } from "convex/react"; +import { useMutation, useQuery } from "@tanstack/react-query"; import { AlertCircle, Ban, @@ -25,7 +25,8 @@ import { import { Input } from "@/components/ui/input"; import { Skeleton } from "@/components/ui/skeleton"; import type { RbacRole } from "@/constants"; -import { api } from "../../../convex/_generated/api"; +import { listUsers, setUserBanned, setUserRoles } from "@/server/fns/admin"; +import { unwrap } from "@/server/schema/common"; type DynamicRbacRole = Exclude; @@ -46,9 +47,18 @@ type FilterTab = "all" | "active" | "banned"; export function AdminUserTable() { const { user: currentUser } = useUser(); - const users = useQuery(api.admin.listUsers, {}); - const setUserRoles = useMutation(api.admin.setUserRoles); - const setUserBanned = useMutation(api.admin.setUserBanned); + const usersQuery = useQuery({ + queryKey: ["admin", "users"], + queryFn: () => unwrap(listUsers({ data: {} })), + }); + const setUserRolesMutation = useMutation({ + mutationFn: (args: { tokenIdentifier: string; roles: DynamicRbacRole[] }) => + unwrap(setUserRoles({ data: args })), + }); + const setUserBannedMutation = useMutation({ + mutationFn: (args: { tokenIdentifier: string; banned: boolean }) => + unwrap(setUserBanned({ data: args })), + }); const [selectedUser, setSelectedUser] = useState(null); const [isSubmitting, setIsSubmitting] = useState(false); @@ -57,6 +67,8 @@ export function AdminUserTable() { const [search, setSearch] = useState(""); const [filterTab, setFilterTab] = useState("all"); + const users = usersQuery.data; + if (users === undefined) { return (
@@ -76,7 +88,7 @@ export function AdminUserTable() { setErrorMessage(null); try { - await setUserBanned({ + await setUserBannedMutation.mutateAsync({ tokenIdentifier: selectedUser.tokenIdentifier, banned: !selectedUser.isBanned, }); @@ -296,16 +308,18 @@ export function AdminUserTable() { const next = isActive ? currentRoles.filter((r) => r !== config.value) : [...currentRoles, config.value]; - setUserRoles({ - tokenIdentifier: user.tokenIdentifier, - roles: next, - }).catch((err) => { - setRoleError( - err instanceof Error - ? err.message - : String(err), - ); - }); + setUserRolesMutation + .mutateAsync({ + tokenIdentifier: user.tokenIdentifier, + roles: next, + }) + .catch((err) => { + setRoleError( + err instanceof Error + ? err.message + : String(err), + ); + }); }; return ( @@ -478,14 +492,16 @@ export function AdminUserTable() { const next = isActive ? currentRoles.filter((r) => r !== config.value) : [...currentRoles, config.value]; - setUserRoles({ - tokenIdentifier: user.tokenIdentifier, - roles: next, - }).catch((err) => { - setRoleError( - err instanceof Error ? err.message : String(err), - ); - }); + setUserRolesMutation + .mutateAsync({ + tokenIdentifier: user.tokenIdentifier, + roles: next, + }) + .catch((err) => { + setRoleError( + err instanceof Error ? err.message : String(err), + ); + }); }; return ( diff --git a/src/components/custom-list-picker.tsx b/src/components/custom-list-picker.tsx index a4bfad89..ca218fc4 100644 --- a/src/components/custom-list-picker.tsx +++ b/src/components/custom-list-picker.tsx @@ -1,5 +1,5 @@ import { useUser } from "@clerk/react"; -import { useMutation, useQuery } from "convex/react"; +import { useMutation, useQuery } from "@tanstack/react-query"; import { Plus } from "lucide-react"; import { useState } from "react"; import { @@ -8,11 +8,15 @@ import { DropdownMenuItem, DropdownMenuLabel, } from "@/components/ui/dropdown-menu"; -import { api } from "../../convex/_generated/api"; +import { queryKeys } from "@/lib/query/keys"; +import { + getCustomLists, + getItemLists, + toggleListItem, +} from "@/server/fns/lists"; +import { unwrap } from "@/server/schema/common"; import { CustomListDialog } from "./custom-list-dialog"; -const QUERY_SKIP = "skip" as const; - export function CustomListPicker({ tmdbId, mediaType, @@ -21,19 +25,33 @@ export function CustomListPicker({ mediaType: "movie" | "tv"; }) { const { isSignedIn } = useUser(); - const lists = useQuery( - api.watchlist.getCustomLists, - isSignedIn ? {} : QUERY_SKIP, - ); - const itemLists = useQuery( - api.watchlist.getItemLists, - isSignedIn ? { tmdbId, mediaType } : QUERY_SKIP, - ); - const toggleListItem = useMutation(api.watchlist.toggleListItem); + const listsQuery = useQuery({ + queryKey: queryKeys.lists.all(), + queryFn: () => unwrap(getCustomLists()), + enabled: !!isSignedIn, + }); + const itemListsQuery = useQuery({ + queryKey: queryKeys.lists.itemLists(tmdbId, mediaType), + queryFn: () => unwrap(getItemLists({ data: { tmdbId, mediaType } })), + enabled: !!isSignedIn, + }); + const toggleListItemMutation = useMutation({ + mutationFn: (args: { + listId: string; + tmdbId: number; + mediaType: "movie" | "tv"; + title?: string; + image?: string; + backdrop?: string; + rating?: number; + release_date?: string; + overview?: string; + }) => unwrap(toggleListItem({ data: args })), + }); const [showCreateDialog, setShowCreateDialog] = useState(false); - const safeList = lists ?? []; - const safeItemLists = itemLists ?? []; + const safeList = listsQuery.data ?? []; + const safeItemLists = itemListsQuery.data ?? []; return ( <> @@ -41,19 +59,20 @@ export function CustomListPicker({ Collections + {" "} {safeList .filter((list) => list.listType !== "pebbly-picks") .map((list) => { - const isInList = safeItemLists.includes(list._id); + const isInList = safeItemLists.includes(list.id); return ( e.preventDefault()} onCheckedChange={() => { - toggleListItem({ - listId: list._id, + toggleListItemMutation.mutate({ + listId: list.id, tmdbId, mediaType, }); diff --git a/src/components/homepage-recommendations.tsx b/src/components/homepage-recommendations.tsx index ee6b8ad4..18fdee0e 100644 --- a/src/components/homepage-recommendations.tsx +++ b/src/components/homepage-recommendations.tsx @@ -1,9 +1,5 @@ import { useUser } from "@clerk/react"; -import { - useAction, - useQuery as useConvexQuery, - useMutation, -} from "convex/react"; +import { useQuery } from "@tanstack/react-query"; import { Sparkles, ThumbsDown, ThumbsUp } from "lucide-react"; import { memo, useCallback, useEffect, useMemo, useRef, useState } from "react"; import { MediaCard, MediaCardSkeleton } from "@/components/media-card"; @@ -14,6 +10,7 @@ import { useAllMediaStates, useToggleWatchlistItem, } from "@/hooks/use-watchlist"; +import { queryKeys } from "@/lib/query/keys"; import { type AIRecommendation, titlesMatch, @@ -21,7 +18,14 @@ import { useTmdbSearchFallback, } from "@/lib/recommendation-engine"; import { cn } from "@/lib/utils"; -import { api } from "../../convex/_generated/api"; +import { + generateHomepageRecommendations, + getHomepageRecommendations, + getRecommendationFeedback, + removeRecommendationFeedback, + setRecommendationFeedback, +} from "@/server/fns/recommendations"; +import { unwrap } from "@/server/schema/common"; const getDismissKey = (rec: AIRecommendation) => `${rec.mediaType}:${rec.tmdbId ?? ""}:${rec.title}`; @@ -180,23 +184,27 @@ export function HomepageRecommendations() { const cachedRecommendationsRef = useRef<{ userId: string | null; - // biome-ignore lint/suspicious/noExplicitAny: Cached Convex query result + // biome-ignore lint/suspicious/noExplicitAny: Cached server query result recommendationsData: any; - // biome-ignore lint/suspicious/noExplicitAny: Cached Convex query result + // biome-ignore lint/suspicious/noExplicitAny: Cached server query result feedbackList: any; } | null>(null); const canAccessFeature = isSignedIn && hasFeature("ai-recommendations"); - const recommendationsData = useConvexQuery( - api.recommendations.getHomepageRecommendations, - canAccessFeature ? {} : "skip", - ); + const recommendationsQuery = useQuery({ + queryKey: queryKeys.recommendations.homepage(), + queryFn: () => unwrap(getHomepageRecommendations({ data: {} })), + enabled: canAccessFeature, + }); + const recommendationsData = recommendationsQuery.data; - const feedbackList = useConvexQuery( - api.recommendations.getRecommendationFeedback, - canAccessFeature ? {} : "skip", - ); + const feedbackQuery = useQuery({ + queryKey: ["recommendations", "feedback"], + queryFn: () => unwrap(getRecommendationFeedback()), + enabled: canAccessFeature, + }); + const feedbackList = feedbackQuery.data; // Update ref cache when fresh data is loaded useEffect(() => { @@ -225,19 +233,14 @@ export function HomepageRecommendations() { ? (cachedRecommendationsRef.current?.feedbackList as typeof feedbackList) : null); - const generateRecs = useAction( - api.recommendations.generateHomepageRecommendations, - ); - const setFeedback = useMutation( - api.recommendations.setRecommendationFeedback, - ); - const removeFeedback = useMutation( - api.recommendations.removeRecommendationFeedback, - ); - const [isGenerating, setIsGenerating] = useState(false); const isGeneratingRef = useRef(false); + const refreshHomepage = useCallback(() => { + void recommendationsQuery.refetch(); + void feedbackQuery.refetch(); + }, [recommendationsQuery, feedbackQuery]); + useEffect(() => { if ( canAccessFeature && @@ -246,7 +249,12 @@ export function HomepageRecommendations() { ) { isGeneratingRef.current = true; setIsGenerating(true); - generateRecs() + generateHomepageRecommendations() + .then((result) => { + if (result.ok && result.data.success) { + refreshHomepage(); + } + }) .catch((err) => { console.error("Failed to generate homepage recommendations:", err); }) @@ -255,7 +263,7 @@ export function HomepageRecommendations() { isGeneratingRef.current = false; }); } - }, [canAccessFeature, resolvedRecsData?.needsRefresh, generateRecs]); + }, [canAccessFeature, resolvedRecsData?.needsRefresh, refreshHomepage]); const toggleWatchlist = useToggleWatchlistItem(); @@ -365,22 +373,24 @@ export function HomepageRecommendations() { try { if (feedback === "unlike") { - await removeFeedback({ - tmdbId: resolvedId, - mediaType: rec.mediaType, + await removeRecommendationFeedback({ + data: { tmdbId: resolvedId, mediaType: rec.mediaType }, }); } else { - await setFeedback({ - tmdbId: resolvedId, - mediaType: rec.mediaType, - title: rec.title, - feedback: feedback === "dislike" ? "not_interested" : "like", - image: metadata?.image, - rating: metadata?.rating, - release_date: metadata?.release_date, - overview: metadata?.overview, + await setRecommendationFeedback({ + data: { + tmdbId: resolvedId, + mediaType: rec.mediaType, + title: rec.title, + feedback: feedback === "dislike" ? "not_interested" : "like", + image: metadata?.image, + rating: metadata?.rating, + release_date: metadata?.release_date, + overview: metadata?.overview, + }, }); } + refreshHomepage(); } catch (err) { console.error("Failed to update recommendation feedback:", err); if (feedback === "dislike") { @@ -405,7 +415,7 @@ export function HomepageRecommendations() { } } }, - [setFeedback, removeFeedback, toggleWatchlist], + [refreshHomepage, toggleWatchlist], ); if (!isLoaded || !canAccessFeature) { diff --git a/src/components/user-sync.tsx b/src/components/user-sync.tsx index 08662010..be8c78bb 100644 --- a/src/components/user-sync.tsx +++ b/src/components/user-sync.tsx @@ -1,28 +1,28 @@ import { useClerk, useUser } from "@clerk/react"; -import { useMutation } from "convex/react"; import { useEffect } from "react"; import { usePermissions } from "@/hooks/use-permissions"; -import { api } from "../../convex/_generated/api"; +import { storeUser } from "@/server/fns/users"; export const UserSync = () => { const { user, isLoaded } = useUser(); const { signOut } = useClerk(); - const storeUser = useMutation(api.users.store); const { isBanned, isSignedIn, loading } = usePermissions(); - // Sync user profile data to Convex on mount / user change + // Sync user profile data to D1 on mount / user change useEffect(() => { if (isLoaded && user) { storeUser({ - name: user.fullName ?? user.username ?? "Anonymous", - email: user.primaryEmailAddress?.emailAddress, - image: user.imageUrl, - isAdmin: user.publicMetadata?.isAdmin === true, + data: { + name: user.fullName ?? user.username ?? "Anonymous", + email: user.primaryEmailAddress?.emailAddress, + image: user.imageUrl, + isAdmin: user.publicMetadata?.isAdmin === true, + }, }).catch((error) => { - console.error("Failed to sync user to Convex:", error); + console.error("Failed to sync user to backend:", error); }); } - }, [isLoaded, user, storeUser]); + }, [isLoaded, user]); // Enforce ban: sign the user out immediately when banned status is confirmed. // This clears their Clerk session so there is no client-side bypass. diff --git a/src/hooks/optimistic-helpers.ts b/src/hooks/optimistic-helpers.ts index 5c9d32b2..b658ba2c 100644 --- a/src/hooks/optimistic-helpers.ts +++ b/src/hooks/optimistic-helpers.ts @@ -1,16 +1,63 @@ -// biome-ignore lint/suspicious/noExplicitAny: generic optimistic updater helper for convex queries -export function createOptimisticUpdater( - // biome-ignore lint/suspicious/noExplicitAny: generic optimistic updater helper for convex queries - queryReference: any, +import type { QueryClient } from "@tanstack/react-query"; + +/** + * Optimistic updater port for TanStack Query. `getKey(args)` resolves the + * query key (from the keys factory), `updateFn` patches the cached array. + */ +export function createOptimisticUpdater>( + getKey: (args: A) => readonly unknown[], updateFn: (items: T[], args: A) => T[], - // biome-ignore lint/suspicious/noExplicitAny: generic optimistic updater helper for convex queries - getQueryArgs: (args: A) => any = () => ({}), ) { - // biome-ignore lint/suspicious/noExplicitAny: generic optimistic updater helper for convex queries - return (localStore: any, args: A) => { - const queryArgs = getQueryArgs(args); + return (queryClient: QueryClient, args: A) => { + const key = getKey(args); const current = - (localStore.getQuery(queryReference, queryArgs) as T[] | undefined) ?? []; - localStore.setQuery(queryReference, queryArgs, updateFn(current, args)); + (queryClient.getQueryData(key) as T[] | undefined) ?? []; + queryClient.setQueryData(key, updateFn(current, args)); }; } + +type Snapshot = { queryKey: readonly unknown[]; previous: unknown }; + +/** + * Begin an optimistic update across a set of query keys: cancels in-flight + * queries, snapshots current data, applies `apply()`, and returns a rollback + * function (to be invoked from `onError`). + */ +export async function beginOptimistic( + queryClient: QueryClient, + queryKeys: readonly (readonly unknown[])[], + apply: () => void, +): Promise<() => void> { + await Promise.all( + queryKeys.map((queryKey) => + queryClient.cancelQueries({ queryKey: queryKey as never }), + ), + ); + + const snapshots: Snapshot[] = queryKeys.map((queryKey) => ({ + queryKey, + previous: queryClient.getQueryData(queryKey as never), + })); + + apply(); + + return () => { + for (const { queryKey, previous } of snapshots) { + if (previous === undefined) { + queryClient.removeQueries({ queryKey: queryKey as never }); + } else { + queryClient.setQueryData(queryKey as never, previous as never); + } + } + }; +} + +/** Patch a single cached value (e.g. `getMediaState`). */ +export function setCached( + queryClient: QueryClient, + queryKey: readonly unknown[], + update: (current: T | undefined) => T | undefined, +) { + const current = queryClient.getQueryData(queryKey as never); + queryClient.setQueryData(queryKey as never, update(current)); +} diff --git a/src/hooks/use-custom-lists.ts b/src/hooks/use-custom-lists.ts index 97b2f2c2..6cc6b7e3 100644 --- a/src/hooks/use-custom-lists.ts +++ b/src/hooks/use-custom-lists.ts @@ -1,29 +1,51 @@ import { useUser } from "@clerk/react"; -import { useMutation, useQuery } from "convex/react"; +import { + type QueryClient, + useMutation, + useQuery, + useQueryClient, +} from "@tanstack/react-query"; import { useCallback, useMemo } from "react"; +import { queryKeys } from "@/lib/query/keys"; +import type { CustomListRow, ListItemRow } from "@/lib/server-types"; +import { + createCustomList, + createCustomListAndAddItem, + deleteCustomList, + getCustomLists, + getItemLists, + getListItems, + toggleListItem, + updateCustomList, +} from "@/server/fns/lists"; +import { unwrap } from "@/server/schema/common"; import type { ProgressStatus, ReactionStatus } from "@/types"; -import { api } from "../../convex/_generated/api"; -import type { Id } from "../../convex/_generated/dataModel"; +import { beginOptimistic } from "./optimistic-helpers"; import { useLocalListsStore } from "./use-local-lists-store"; import { useWatchlistStore } from "./watchlist-store"; -const QUERY_SKIP = "skip" as const; - -function toListId(listId: string) { - return listId as Id<"lists">; -} - export function useCustomLists() { const { isSignedIn } = useUser(); const localLists = useLocalListsStore((state) => state.lists); const localItems = useLocalListsStore((state) => state.listItems); - const remoteLists = useQuery( - api.watchlist.getCustomLists, - isSignedIn ? {} : QUERY_SKIP, - ); + const remote = useQuery({ + queryKey: queryKeys.lists.all(), + queryFn: () => unwrap(getCustomLists()), + enabled: !!isSignedIn, + }); const lists = useMemo(() => { - if (isSignedIn) return remoteLists ?? []; + if (isSignedIn) { + // Normalize the server rows to the legacy client shape (`_id`, + // optional fields) so list consumers work unchanged. + return (remote.data ?? []).map((list) => ({ + ...list, + _id: list.id, + color: list.color ?? undefined, + visibility: list.visibility ?? undefined, + listType: list.listType ?? undefined, + })); + } return localLists.map((list) => { const items = localItems.filter((i) => i.listId === list._id); @@ -38,11 +60,11 @@ export function useCustomLists() { itemCount: items.length, }; }); - }, [isSignedIn, remoteLists, localLists, localItems]); + }, [isSignedIn, remote.data, localLists, localItems]); return { lists, - loading: isSignedIn && remoteLists === undefined, + loading: isSignedIn && remote.isPending, isAvailable: true, }; } @@ -51,15 +73,23 @@ export function useCustomListItems(listId: string | null) { const { isSignedIn } = useUser(); const localItems = useLocalListsStore((state) => state.listItems); const localMediaState = useWatchlistStore((state) => state.mediaState); - const remoteItems = useQuery( - api.watchlist.getListItems, - isSignedIn && listId ? { listId: toListId(listId) } : QUERY_SKIP, - ); + const remote = useQuery({ + queryKey: queryKeys.lists.items(listId ?? ""), + queryFn: () => unwrap(getListItems({ data: { listId: listId! } })), + enabled: !!isSignedIn && !!listId, + }); return useMemo(() => { if (isSignedIn) { - return (remoteItems ?? []).map((item) => ({ + return (remote.data ?? []).map((item) => ({ ...item, + _id: item.id, + title: item.title ?? undefined, + image: item.image ?? undefined, + backdrop: item.backdrop ?? undefined, + rating: item.rating ?? undefined, + release_date: item.releaseDate ?? undefined, + overview: item.overview ?? undefined, mediaType: item.mediaType as "movie" | "tv", progressStatus: item.progressStatus as ProgressStatus | undefined, reaction: item.reaction as ReactionStatus | undefined, @@ -84,100 +114,130 @@ export function useCustomListItems(listId: string | null) { reaction: watchItem?.reaction || undefined, }; }); - }, [isSignedIn, remoteItems, listId, localItems, localMediaState]); + }, [isSignedIn, remote.data, listId, localItems, localMediaState]); } export function useItemLists(tmdbId: number, mediaType: "movie" | "tv") { const { isSignedIn } = useUser(); const localItems = useLocalListsStore((state) => state.listItems); - const remoteListIds = useQuery( - api.watchlist.getItemLists, - isSignedIn ? { tmdbId, mediaType } : QUERY_SKIP, - ); + const remote = useQuery({ + queryKey: queryKeys.lists.itemLists(tmdbId, mediaType), + queryFn: () => unwrap(getItemLists({ data: { tmdbId, mediaType } })), + enabled: !!isSignedIn, + }); return useMemo(() => { - if (isSignedIn) return remoteListIds ?? []; + if (isSignedIn) return remote.data ?? []; return localItems .filter((item) => item.tmdbId === tmdbId && item.mediaType === mediaType) .map((item) => item.listId); - }, [isSignedIn, remoteListIds, tmdbId, mediaType, localItems]); + }, [isSignedIn, remote.data, tmdbId, mediaType, localItems]); } -function deleteCustomListOptimisticUpdate( - localStore: any, - args: { listId: string }, +async function deleteCustomListOptimistic( + queryClient: QueryClient, + listId: string, ) { - const current = localStore.getQuery(api.watchlist.getCustomLists, {}) ?? []; - localStore.setQuery( - api.watchlist.getCustomLists, - {}, - current.filter((l: any) => l._id !== args.listId), - ); + return beginOptimistic(queryClient, [queryKeys.lists.all()], () => { + const current = + (queryClient.getQueryData(queryKeys.lists.all()) as + | CustomListRow[] + | undefined) ?? []; + queryClient.setQueryData( + queryKeys.lists.all(), + current.filter((l) => l.id !== listId), + ); + }); } export function useDeleteCustomList() { const { isSignedIn } = useUser(); + const queryClient = useQueryClient(); const deleteListLocal = useLocalListsStore((state) => state.deleteList); - const deleteList = useMutation( - api.watchlist.deleteCustomList, - ).withOptimisticUpdate(deleteCustomListOptimisticUpdate); + + const mutation = useMutation({ + mutationFn: (listId: string) => + unwrap(deleteCustomList({ data: { listId } })), + onMutate: (listId) => deleteCustomListOptimistic(queryClient, listId), + onError: (error, _listId, rollback) => { + console.error("Failed to delete custom list", error); + rollback?.(); + }, + onSettled: () => { + void queryClient.invalidateQueries({ queryKey: queryKeys.lists.all() }); + }, + }); return useCallback( async (listId: string) => { if (isSignedIn) { - await deleteList({ listId: toListId(listId) }); + await mutation.mutateAsync(listId); } else { deleteListLocal(listId); } }, - [isSignedIn, deleteList, deleteListLocal], + [isSignedIn, mutation, deleteListLocal], ); } -function createCustomListOptimisticUpdate( - localStore: any, - args: { - name: string; - color?: string; - visibility?: string; - listType?: string; - }, +type CreateListArgs = { + name: string; + color?: string; + visibility?: string; + listType?: string; +}; + +async function createCustomListOptimistic( + queryClient: QueryClient, + args: CreateListArgs, ) { - const current = localStore.getQuery(api.watchlist.getCustomLists, {}) ?? []; - const now = Date.now(); - localStore.setQuery(api.watchlist.getCustomLists, {}, [ - ...current, - { - _id: `optimistic_${now}`, - name: args.name, - color: args.color, - visibility: args.visibility, - listType: args.listType, - sortOrder: current.length, - createdAt: now, - updatedAt: now, - previews: [], - itemCount: 0, - }, - ]); + return beginOptimistic(queryClient, [queryKeys.lists.all()], () => { + const current = + (queryClient.getQueryData(queryKeys.lists.all()) as + | CustomListRow[] + | undefined) ?? []; + const now = Date.now(); + queryClient.setQueryData(queryKeys.lists.all(), [ + ...current, + { + id: `optimistic_${now}`, + userId: "optimistic", + name: args.name, + color: args.color ?? null, + visibility: args.visibility ?? null, + listType: args.listType ?? null, + sortOrder: current.length, + createdAt: now, + updatedAt: now, + previews: [], + itemCount: 0, + }, + ]); + }); } export function useCreateCustomList() { const { isSignedIn } = useUser(); + const queryClient = useQueryClient(); const createListLocal = useLocalListsStore((state) => state.createList); - const createList = useMutation( - api.watchlist.createCustomList, - ).withOptimisticUpdate(createCustomListOptimisticUpdate); + + const mutation = useMutation({ + mutationFn: (args: CreateListArgs) => + unwrap(createCustomList({ data: args })), + onMutate: (args) => createCustomListOptimistic(queryClient, args), + onError: (error, _args, rollback) => { + console.error("Failed to create custom list", error); + rollback?.(); + }, + onSettled: () => { + void queryClient.invalidateQueries({ queryKey: queryKeys.lists.all() }); + }, + }); return useCallback( - async (args: { - name: string; - color?: string; - visibility?: string; - listType?: string; - }) => { + async (args: CreateListArgs) => { if (isSignedIn) { - return await createList(args); + return await mutation.mutateAsync(args); } return createListLocal( args.name, @@ -186,165 +246,158 @@ export function useCreateCustomList() { args.listType, ); }, - [isSignedIn, createList, createListLocal], + [isSignedIn, mutation, createListLocal], ); } -function createListAndAddOptimisticUpdate( - localStore: any, - args: { - name: string; - color?: string; - visibility?: string; - listType?: string; - tmdbId: number; - mediaType: "movie" | "tv"; - title?: string; - image?: string; - backdrop?: string; - rating?: number; - release_date?: string; - overview?: string; - }, +type CreateListAndAddArgs = CreateListArgs & { + tmdbId: number; + mediaType: "movie" | "tv"; + title?: string; + image?: string; + backdrop?: string; + rating?: number; + release_date?: string; + overview?: string; +}; + +async function createListAndAddOptimistic( + queryClient: QueryClient, + args: CreateListAndAddArgs, ) { - const current = localStore.getQuery(api.watchlist.getCustomLists, {}) ?? []; const now = Date.now(); const optimisticId = `optimistic_${now}`; - - localStore.setQuery(api.watchlist.getCustomLists, {}, [ - ...current, - { - _id: optimisticId, - name: args.name, - color: args.color, - visibility: args.visibility, - listType: args.listType, - sortOrder: current.length, - createdAt: now, - updatedAt: now, - previews: [args.backdrop ?? args.image].filter(Boolean), - itemCount: 1, - }, - ]); - - // Optimistically add item to the list items query - const listItemsKey = { listId: optimisticId }; - const currentListItems = - localStore.getQuery(api.watchlist.getListItems, listItemsKey) ?? []; - localStore.setQuery(api.watchlist.getListItems, listItemsKey, [ - ...currentListItems, - { - _id: `optimistic_item_${now}`, - listId: optimisticId, - tmdbId: args.tmdbId, - mediaType: args.mediaType, - addedAt: now, - title: args.title, - image: args.image, - backdrop: args.backdrop, - rating: args.rating, - release_date: args.release_date, - overview: args.overview, + return beginOptimistic( + queryClient, + [ + queryKeys.lists.all(), + queryKeys.lists.items(optimisticId), + queryKeys.lists.itemLists(args.tmdbId, args.mediaType), + ], + () => { + const current = + (queryClient.getQueryData(queryKeys.lists.all()) as + | CustomListRow[] + | undefined) ?? []; + queryClient.setQueryData(queryKeys.lists.all(), [ + ...current, + { + id: optimisticId, + userId: "optimistic", + name: args.name, + color: args.color ?? null, + visibility: args.visibility ?? null, + listType: args.listType ?? null, + sortOrder: current.length, + createdAt: now, + updatedAt: now, + previews: [args.backdrop ?? args.image].filter(Boolean) as string[], + itemCount: 1, + }, + ]); + + const itemListsKey = queryKeys.lists.itemLists( + args.tmdbId, + args.mediaType, + ); + const currentItemLists = + (queryClient.getQueryData(itemListsKey) as + | string[] + | undefined) ?? []; + queryClient.setQueryData(itemListsKey, [ + ...currentItemLists, + optimisticId, + ]); }, - ]); - - // Optimistically add list to itemLists query for this media - const itemListsKey = { tmdbId: args.tmdbId, mediaType: args.mediaType }; - const currentItemLists = - localStore.getQuery(api.watchlist.getItemLists, itemListsKey) ?? []; - localStore.setQuery(api.watchlist.getItemLists, itemListsKey, [ - ...currentItemLists, - optimisticId, - ]); + ); } export function useCreateCustomListAndAddItem() { const { isSignedIn } = useUser(); + const queryClient = useQueryClient(); const createListAndAddLocal = useLocalListsStore( (state) => state.createListAndAddItem, ); - const createListAndAdd = useMutation( - api.watchlist.createCustomListAndAddItem, - ).withOptimisticUpdate(createListAndAddOptimisticUpdate); + + const mutation = useMutation({ + mutationFn: (args: CreateListAndAddArgs) => + unwrap(createCustomListAndAddItem({ data: args })), + onMutate: (args) => createListAndAddOptimistic(queryClient, args), + onError: (error, _args, rollback) => { + console.error("Failed to create list and add item", error); + rollback?.(); + }, + onSettled: () => { + void queryClient.invalidateQueries({ queryKey: queryKeys.lists.all() }); + void queryClient.invalidateQueries({ queryKey: ["lists", "items"] }); + void queryClient.invalidateQueries({ queryKey: ["lists", "item-lists"] }); + }, + }); return useCallback( - async (args: { - name: string; - color?: string; - visibility?: string; - listType?: string; - tmdbId: number; - mediaType: "movie" | "tv"; - title?: string; - image?: string; - backdrop?: string; - rating?: number; - release_date?: string; - overview?: string; - }) => { + async (args: CreateListAndAddArgs) => { if (isSignedIn) { - return await createListAndAdd(args); + return await mutation.mutateAsync(args); } createListAndAddLocal(args); }, - [isSignedIn, createListAndAdd, createListAndAddLocal], + [isSignedIn, mutation, createListAndAddLocal], ); } -function updateCustomListOptimisticUpdate( - localStore: any, - args: { - listId: string; - name?: string; - color?: string; - visibility?: string; - listType?: string; - }, +type UpdateListArgs = CreateListArgs & { listId: string }; + +async function updateCustomListOptimistic( + queryClient: QueryClient, + args: UpdateListArgs, ) { - const current = localStore.getQuery(api.watchlist.getCustomLists, {}) ?? []; - localStore.setQuery( - api.watchlist.getCustomLists, - {}, - current.map((l: any) => - l._id === args.listId - ? { - ...l, - ...(args.name !== undefined && { name: args.name }), - ...(args.color !== undefined && { color: args.color }), - ...(args.visibility !== undefined && { - visibility: args.visibility, - }), - ...(args.listType !== undefined && { listType: args.listType }), - updatedAt: Date.now(), - } - : l, - ), - ); + return beginOptimistic(queryClient, [queryKeys.lists.all()], () => { + const current = + (queryClient.getQueryData(queryKeys.lists.all()) as + | CustomListRow[] + | undefined) ?? []; + queryClient.setQueryData( + queryKeys.lists.all(), + current.map((l) => + l.id === args.listId + ? { + ...l, + ...(args.name !== undefined && { name: args.name }), + ...(args.color !== undefined && { color: args.color }), + ...(args.visibility !== undefined && { + visibility: args.visibility, + }), + ...(args.listType !== undefined && { listType: args.listType }), + updatedAt: Date.now(), + } + : l, + ), + ); + }); } export function useUpdateCustomList() { const { isSignedIn } = useUser(); + const queryClient = useQueryClient(); const updateListLocal = useLocalListsStore((state) => state.updateList); - const updateList = useMutation( - api.watchlist.updateCustomList, - ).withOptimisticUpdate(updateCustomListOptimisticUpdate); + + const mutation = useMutation({ + mutationFn: (args: UpdateListArgs) => + unwrap(updateCustomList({ data: args })), + onMutate: (args) => updateCustomListOptimistic(queryClient, args), + onError: (error, _args, rollback) => { + console.error("Failed to update custom list", error); + rollback?.(); + }, + onSettled: () => { + void queryClient.invalidateQueries({ queryKey: queryKeys.lists.all() }); + }, + }); return useCallback( - async (args: { - listId: string; - name: string; - color?: string; - visibility?: string; - listType?: string; - }) => { + async (args: UpdateListArgs) => { if (isSignedIn) { - await updateList({ - listId: toListId(args.listId), - name: args.name, - color: args.color, - visibility: args.visibility, - listType: args.listType, - }); + await mutation.mutateAsync(args); } else { updateListLocal( args.listId, @@ -355,130 +408,133 @@ export function useUpdateCustomList() { ); } }, - [isSignedIn, updateList, updateListLocal], + [isSignedIn, mutation, updateListLocal], ); } -function toggleListItemOptimisticUpdate( - localStore: any, - args: { - listId: string; - tmdbId: number; - mediaType: "movie" | "tv"; - title?: string; - image?: string; - backdrop?: string; - rating?: number; - release_date?: string; - overview?: string; - }, +type ToggleListItemArgs = { + listId: string; + tmdbId: number; + mediaType: "movie" | "tv"; + title?: string; + image?: string; + backdrop?: string; + rating?: number; + release_date?: string; + overview?: string; +}; + +async function toggleListItemOptimistic( + queryClient: QueryClient, + args: ToggleListItemArgs, ) { - // Update itemLists query for this media - const itemListsKey = { tmdbId: args.tmdbId, mediaType: args.mediaType }; - const currentItemLists = - localStore.getQuery(api.watchlist.getItemLists, itemListsKey) ?? []; - const exists = currentItemLists.includes(args.listId); - - if (exists) { - localStore.setQuery( - api.watchlist.getItemLists, - itemListsKey, - currentItemLists.filter((id: string) => id !== args.listId), - ); - } else { - localStore.setQuery(api.watchlist.getItemLists, itemListsKey, [ - ...currentItemLists, - args.listId, - ]); - } - - // Update list items query for this list - const listItemsKey = { listId: args.listId }; - const currentListItems = - localStore.getQuery(api.watchlist.getListItems, listItemsKey) ?? []; - - if (exists) { - localStore.setQuery( - api.watchlist.getListItems, - listItemsKey, - currentListItems.filter((i: any) => i.tmdbId !== args.tmdbId), - ); - } else { - localStore.setQuery(api.watchlist.getListItems, listItemsKey, [ - ...currentListItems, - { - _id: `optimistic_${Date.now()}`, - listId: args.listId, - tmdbId: args.tmdbId, - mediaType: args.mediaType, - addedAt: Date.now(), - title: args.title, - image: args.image, - backdrop: args.backdrop, - rating: args.rating, - release_date: args.release_date, - overview: args.overview, - }, - ]); - } - - // Bump itemCount on the parent list - const customLists = - localStore.getQuery(api.watchlist.getCustomLists, {}) ?? []; - localStore.setQuery( - api.watchlist.getCustomLists, - {}, - customLists.map((l: any) => - l._id === args.listId - ? { - ...l, - itemCount: exists - ? Math.max(0, (l.itemCount ?? 1) - 1) - : (l.itemCount ?? 0) + 1, - updatedAt: Date.now(), - } - : l, - ), + const itemListsKey = queryKeys.lists.itemLists(args.tmdbId, args.mediaType); + const itemsKey = queryKeys.lists.items(args.listId); + return beginOptimistic( + queryClient, + [itemListsKey, itemsKey, queryKeys.lists.all()], + () => { + const currentItemLists = + (queryClient.getQueryData(itemListsKey) as + | string[] + | undefined) ?? []; + const exists = currentItemLists.includes(args.listId); + + if (exists) { + queryClient.setQueryData( + itemListsKey, + currentItemLists.filter((id) => id !== args.listId), + ); + } else { + queryClient.setQueryData(itemListsKey, [ + ...currentItemLists, + args.listId, + ]); + } + + const currentItems = + (queryClient.getQueryData(itemsKey) as + | ListItemRow[] + | undefined) ?? []; + if (exists) { + queryClient.setQueryData( + itemsKey, + currentItems.filter((i) => i.tmdbId !== args.tmdbId), + ); + } else { + queryClient.setQueryData(itemsKey, [ + ...currentItems, + { + id: `optimistic_${Date.now()}`, + userId: "optimistic", + listId: args.listId, + tmdbId: args.tmdbId, + mediaType: args.mediaType, + addedAt: Date.now(), + title: args.title ?? null, + image: args.image ?? null, + backdrop: args.backdrop ?? null, + rating: args.rating ?? null, + releaseDate: args.release_date ?? null, + overview: args.overview ?? null, + progressStatus: null, + reaction: null, + } as ListItemRow, + ]); + } + + const lists = + (queryClient.getQueryData(queryKeys.lists.all()) as + | CustomListRow[] + | undefined) ?? []; + queryClient.setQueryData( + queryKeys.lists.all(), + lists.map((l) => + l.id === args.listId + ? { + ...l, + itemCount: exists + ? Math.max(0, (l.itemCount ?? 1) - 1) + : (l.itemCount ?? 0) + 1, + updatedAt: Date.now(), + } + : l, + ), + ); + }, ); } export function useToggleListItem() { const { isSignedIn } = useUser(); + const queryClient = useQueryClient(); const toggleListItemLocal = useLocalListsStore( (state) => state.toggleListItem, ); - const toggleListItem = useMutation( - api.watchlist.toggleListItem, - ).withOptimisticUpdate(toggleListItemOptimisticUpdate); + + const mutation = useMutation({ + mutationFn: (args: ToggleListItemArgs) => + unwrap(toggleListItem({ data: args })), + onMutate: (args) => toggleListItemOptimistic(queryClient, args), + onError: (error, _args, rollback) => { + console.error("Failed to toggle list item", error); + rollback?.(); + }, + onSettled: () => { + void queryClient.invalidateQueries({ queryKey: queryKeys.lists.all() }); + void queryClient.invalidateQueries({ queryKey: ["lists", "items"] }); + void queryClient.invalidateQueries({ queryKey: ["lists", "item-lists"] }); + }, + }); return useCallback( - async (args: { - listId: string; - tmdbId: number; - mediaType: "movie" | "tv"; - title?: string; - image?: string; - backdrop?: string; - rating?: number; - release_date?: string; - overview?: string; - }) => { + async (args: ToggleListItemArgs) => { if (isSignedIn) { - await toggleListItem({ - listId: toListId(args.listId), - tmdbId: args.tmdbId, - mediaType: args.mediaType, - title: args.title, - image: args.image, - backdrop: args.backdrop, - rating: args.rating, - release_date: args.release_date, - overview: args.overview, - }); + await mutation.mutateAsync(args); } else { toggleListItemLocal(args); } }, - [isSignedIn, toggleListItem, toggleListItemLocal], + [isSignedIn, mutation, toggleListItemLocal], ); } diff --git a/src/hooks/use-permissions.ts b/src/hooks/use-permissions.ts index 058401e1..9945814e 100644 --- a/src/hooks/use-permissions.ts +++ b/src/hooks/use-permissions.ts @@ -1,17 +1,10 @@ import { useUser } from "@clerk/react"; -import { useQuery } from "convex/react"; +import { useQuery } from "@tanstack/react-query"; import { useCallback } from "react"; import type { RbacFeature, RbacRole } from "@/constants"; -import { api } from "../../convex/_generated/api"; - -const QUERY_SKIP = "skip" as const; - -interface UserFeaturesResult { - roles: string[]; - features: Record; - isAdmin: boolean; - isBanned: boolean; -} +import { queryKeys } from "@/lib/query/keys"; +import { getUserFeaturesFn } from "@/server/fns/admin"; +import { unwrap } from "@/server/schema/common"; interface PermissionState { roles: RbacRole[]; @@ -27,16 +20,16 @@ export function usePermissions(): PermissionState & { hasRole: (role: RbacRole) => boolean; } { const { isSignedIn, isLoaded, user } = useUser(); - const raw = useQuery( - api.admin.getUserFeatures, - isSignedIn ? {} : QUERY_SKIP, - ) as UserFeaturesResult | undefined; + const raw = useQuery({ + queryKey: queryKeys.permissions(), + queryFn: () => unwrap(getUserFeaturesFn()), + enabled: !!isSignedIn, + }); const clerkIsAdmin = user?.publicMetadata?.isAdmin === true; - const loading = - !isLoaded || (isSignedIn && !clerkIsAdmin && raw === undefined); + const loading = !isLoaded || (isSignedIn && !clerkIsAdmin && raw.isPending); - const isBanned = raw?.isBanned === true; + const isBanned = raw.data?.isBanned === true; const features = clerkIsAdmin ? ({ @@ -48,11 +41,11 @@ export function usePermissions(): PermissionState & { "video-player": false, "ai-recommendations": false, } as Record) - : ((raw?.features ?? {}) as Record); + : ((raw.data?.features ?? {}) as Record); const roles = clerkIsAdmin ? (["admin"] as RbacRole[]) - : ((raw?.roles ?? []) as RbacRole[]); + : ((raw.data?.roles ?? []) as RbacRole[]); const isAdmin = clerkIsAdmin; diff --git a/src/hooks/use-recommendations.ts b/src/hooks/use-recommendations.ts index 88cb65f0..881f6e42 100644 --- a/src/hooks/use-recommendations.ts +++ b/src/hooks/use-recommendations.ts @@ -1,36 +1,21 @@ import { useUser } from "@clerk/react"; -import { useAction, useMutation, useQuery } from "convex/react"; -import { useCallback, useState } from "react"; +import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query"; +import { useCallback, useMemo, useState } from "react"; import { usePermissions } from "@/hooks/use-permissions"; +import { queryKeys } from "@/lib/query/keys"; +import { + deleteRecommendation, + generateRecommendations, + getRecommendationHistory, + updateVerifiedRecommendations, +} from "@/server/fns/recommendations"; +import { unwrap } from "@/server/schema/common"; import type { AIRecommendation } from "@/types"; -import { api } from "../../convex/_generated/api"; -import type { Id } from "../../convex/_generated/dataModel"; - -const QUERY_SKIP = "skip" as const; - -function toRecommendationId(id: string) { - return id as Id<"ai_recommendations">; -} - -function removeFromOptimisticSet(current: Set, id: string) { - const next = new Set(current); - next.delete(id); - return next; -} function logRecommendationError(action: string, error: unknown) { console.error(`Failed to ${action}`, error); } -function parseRecommendationPayload(payload: string): AIRecommendation[] { - try { - return JSON.parse(payload) as AIRecommendation[]; - } catch (error) { - console.error("Failed to parse recommendations payload", error); - return []; - } -} - /** @deprecated Use `usePermissions()` from `@/hooks/usePermissions` instead. */ export function useRecommendationAccess() { const { hasFeature, loading, isSignedIn } = usePermissions(); @@ -53,7 +38,7 @@ export interface GenerateOptions { } export interface RecommendationHistoryEntry { - _id: string; + id: string; recommendations: AIRecommendation[]; inputStats: { movieCount: number; @@ -85,43 +70,66 @@ type GenerateResult = export function useRecommendations() { const { isSignedIn } = useUser(); - const rawHistory = useQuery( - api.recommendations.getRecommendationHistory, - isSignedIn ? {} : QUERY_SKIP, - ); - - const generateAction = useAction(api.recommendations.generateRecommendations); - const deleteMutation = useMutation(api.recommendations.deleteRecommendation); - const updateVerifiedMutation = useMutation( - api.recommendations.updateVerifiedRecommendations, - ); + const queryClient = useQueryClient(); + const historyQuery = useQuery({ + queryKey: queryKeys.recommendations.history(), + queryFn: () => unwrap(getRecommendationHistory()), + enabled: !!isSignedIn, + }); const [isGenerating, setIsGenerating] = useState(false); const [error, setError] = useState(null); const [optimisticDeletedIds, setOptimisticDeletedIds] = useState>( new Set(), ); - const history: RecommendationHistoryEntry[] = (rawHistory ?? []) - .filter((entry) => !optimisticDeletedIds.has(entry._id)) - .map((entry) => ({ - _id: entry._id, - recommendations: parseRecommendationPayload(entry.recommendations), - inputStats: entry.inputStats, - createdAt: entry.createdAt, - generationType: entry.generationType ?? "watchlist", - mediaTypePreference: entry.mediaTypePreference, - genrePreference: entry.genrePreference, - verified: entry.verified ?? false, - })); + const history: RecommendationHistoryEntry[] = useMemo( + () => + (historyQuery.data ?? []) + .filter((entry) => !optimisticDeletedIds.has(entry.id)) + .map((entry) => ({ + id: entry.id, + recommendations: entry.recommendations ?? [], + inputStats: entry.inputStats, + createdAt: entry.createdAt, + generationType: entry.generationType ?? "watchlist", + mediaTypePreference: entry.mediaTypePreference ?? undefined, + genrePreference: entry.genrePreference ?? undefined, + verified: entry.verified ?? false, + })), + [historyQuery.data, optimisticDeletedIds], + ); + + const deleteMutation = useMutation({ + mutationFn: (id: string) => unwrap(deleteRecommendation({ data: { id } })), + onError: (err, id) => { + logRecommendationError("delete recommendation", err); + setOptimisticDeletedIds((prev) => { + const next = new Set(prev); + next.delete(id); + return next; + }); + }, + onSettled: () => { + void queryClient.invalidateQueries({ + queryKey: queryKeys.recommendations.history(), + }); + }, + }); const generate = useCallback( async (options?: GenerateOptions) => { setIsGenerating(true); setError(null); try { - const result: GenerateResult = await generateAction(options ?? {}); + const result: GenerateResult = await unwrap( + generateRecommendations({ data: options ?? {} }), + ); if ("error" in result) { setError(result.error); + } else { + void queryClient.invalidateQueries({ + queryKey: queryKeys.recommendations.history(), + }); } } catch (e) { setError(e instanceof Error ? e.message : "Unknown error"); @@ -129,17 +137,16 @@ export function useRecommendations() { setIsGenerating(false); } }, - [generateAction], + [queryClient], ); const deleteEntry = useCallback( async (id: string) => { setOptimisticDeletedIds((prev) => new Set(prev).add(id)); try { - await deleteMutation({ id: toRecommendationId(id) }); + await deleteMutation.mutateAsync(id); } catch (error) { logRecommendationError("delete recommendation", error); - setOptimisticDeletedIds((prev) => removeFromOptimisticSet(prev, id)); } }, [deleteMutation], @@ -148,18 +155,20 @@ export function useRecommendations() { const updateVerified = useCallback( async (id: string, recommendations: AIRecommendation[]) => { try { - await updateVerifiedMutation({ - id: toRecommendationId(id), - recommendations: JSON.stringify(recommendations), + await updateVerifiedRecommendations({ + data: { id, recommendations: JSON.stringify(recommendations) }, + }); + void queryClient.invalidateQueries({ + queryKey: queryKeys.recommendations.history(), }); } catch (error) { logRecommendationError("update verified recommendations", error); } }, - [updateVerifiedMutation], + [queryClient], ); - const loading = isSignedIn && rawHistory === undefined; + const loading = isSignedIn && historyQuery.isPending; return { history, diff --git a/src/hooks/use-watch-progress.ts b/src/hooks/use-watch-progress.ts index fbe52878..c86037a7 100644 --- a/src/hooks/use-watch-progress.ts +++ b/src/hooks/use-watch-progress.ts @@ -1,30 +1,28 @@ import { useUser } from "@clerk/react"; - -import { useMutation, useQuery } from "convex/react"; - +import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query"; import { useCallback, useEffect, useMemo, useState } from "react"; - -import { api } from "../../convex/_generated/api"; - -import type { Id } from "../../convex/_generated/dataModel"; - +import { queryKeys } from "@/lib/query/keys"; +import type { EpisodeProgressRow } from "@/lib/server-types"; +import { + getAllWatchedEpisodes, + getWatchlist, + markEpisodeWatched, + markSeasonEpisodesWatched, + setProgressStatus, + updateProgress, +} from "@/server/fns/watchlist"; +import { unwrap } from "@/server/schema/common"; +import { beginOptimistic } from "./optimistic-helpers"; import { useLocalProgressStore } from "./use-local-progress-store"; - import { useMediaState, useWatchlistStore } from "./use-watchlist"; export interface WatchProgressData { id: string; - type: "movie" | "tv"; - timestamp: number; - percent: number; - duration: number; - lastUpdated: number; - context?: { season?: number; episode?: number; @@ -66,8 +64,6 @@ function makeEpisodeKey( return `${tvId}:${season}:${episode}`; } -const QUERY_SKIP = "skip" as const; - function isNonNegativeIntegerLike(value: unknown): boolean { if (typeof value === "number") return Number.isInteger(value) && value >= 0; if (typeof value !== "string") return false; @@ -146,15 +142,14 @@ function createOptimisticEpisodeProgress( episode: number, suffix: string, now: number, -) { +): EpisodeProgressRow { return { - _id: `optimistic_${suffix}` as Id<"episode_progress">, - _creationTime: now, - userId: "optimistic" as unknown as Id<"users">, + id: `optimistic_${suffix}`, + userId: "optimistic", tmdbId, season, episode, - isWatched: true as const, + isWatched: true, updatedAt: now, }; } @@ -171,13 +166,33 @@ export function usePlayerProgressListener(activeContext?: { overview?: string; }) { const { isSignedIn } = useUser(); - const updateProgress = useMutation(api.watchlist.updateProgress); - const markEpisodeWatchedMut = useMutation(api.watchlist.markEpisodeWatched); const setLocalProgress = useWatchlistStore((state) => state.setProgressLocal); const markLocalEpisode = useLocalProgressStore( (state) => state.markEpisodeWatched, ); + const updateProgressMutation = useMutation({ + mutationFn: (args: { + tmdbId: number; + mediaType: "movie" | "tv"; + progress?: number; + title?: string; + image?: string; + rating?: number; + release_date?: string; + overview?: string; + }) => unwrap(updateProgress({ data: args })), + }); + + const markEpisodeMutation = useMutation({ + mutationFn: (args: { + tmdbId: number; + season: number; + episode: number; + isWatched: boolean; + }) => unwrap(markEpisodeWatched({ data: args })), + }); + useEffect(() => { if (typeof window === "undefined") return; @@ -287,14 +302,16 @@ export function usePlayerProgressListener(activeContext?: { }; if (isSignedIn) { - void updateProgress({ - tmdbId: Number(id), - mediaType, - progress: safeProgress, - ...metadata, - }).catch((error) => - logWatchProgressError("persist playback progress", error), - ); + void updateProgressMutation + .mutateAsync({ + tmdbId: Number(id), + mediaType, + progress: safeProgress, + ...metadata, + }) + .catch((error) => + logWatchProgressError("persist playback progress", error), + ); if ( (playerEvent === "ended" || safeProgress >= 95) && @@ -302,17 +319,19 @@ export function usePlayerProgressListener(activeContext?: { season !== undefined && episode !== undefined ) { - void markEpisodeWatchedMut({ - tmdbId: Number(id), - season, - episode, - isWatched: true, - }).catch((error) => - logWatchProgressError( - "mark an episode watched from player progress", - error, - ), - ); + void markEpisodeMutation + .mutateAsync({ + tmdbId: Number(id), + season, + episode, + isWatched: true, + }) + .catch((error) => + logWatchProgressError( + "mark an episode watched from player progress", + error, + ), + ); } } else { setLocalProgress(String(id), mediaType, safeProgress, metadata); @@ -332,8 +351,8 @@ export function usePlayerProgressListener(activeContext?: { window.addEventListener("message", handleMessage); return () => window.removeEventListener("message", handleMessage); }, [ - updateProgress, - markEpisodeWatchedMut, + updateProgressMutation, + markEpisodeMutation, isSignedIn, setLocalProgress, markLocalEpisode, @@ -349,11 +368,12 @@ export function useWatchProgress( const { isSignedIn } = useUser(); const tmdbId = Number(id); - const watchedEpisodes = - useQuery( - api.watchlist.getAllWatchedEpisodes, - isSignedIn && mediaType === "tv" ? { tmdbId } : QUERY_SKIP, - ) || []; + const watchedEpisodesQuery = useQuery({ + queryKey: queryKeys.watchlist.episodes(tmdbId), + queryFn: () => unwrap(getAllWatchedEpisodes({ data: { tmdbId } })), + enabled: !!isSignedIn && mediaType === "tv", + }); + const watchedEpisodes = watchedEpisodesQuery.data ?? []; const localEpisodes = useLocalProgressStore((state) => state.watchedEpisodes); @@ -411,7 +431,6 @@ export function useWatchProgress( if (mediaType === "tv") { if (lastPlayed) { const { season, episode } = lastPlayed; - // Check if this episode is already fully watched. const isThisWatched = isSignedIn ? watchedEpisodes.some( (e) => @@ -426,7 +445,6 @@ export function useWatchProgress( } } - // If not in localStorage, fall back to the highest watched episode + 1, or S1E1 if (!context) { const watchedList = isSignedIn ? watchedEpisodes @@ -482,16 +500,22 @@ export function useWatchProgress( export function useContinueWatching() { const { isSignedIn } = useUser(); - const convexData = useQuery( - api.watchlist.getWatchlist, - isSignedIn ? { statusFilter: "watching", limit: 50 } : QUERY_SKIP, - ); + const remote = useQuery({ + queryKey: queryKeys.watchlist.list({ statusFilter: "watching", limit: 50 }), + queryFn: () => + unwrap( + getWatchlist({ + data: { statusFilter: "watching", limit: 50 }, + }), + ), + enabled: !!isSignedIn, + }); const localMediaState = useWatchlistStore((state) => state.mediaState); const items = useMemo(() => { if (isSignedIn) { - if (!convexData) return []; - return convexData + if (!remote.data) return []; + return remote.data .filter((item) => item.progressStatus === "watching") .map((item) => ({ id: String(item.tmdbId), @@ -500,11 +524,11 @@ export function useContinueWatching() { percent: item.progress ?? 0, duration: 0, lastUpdated: item.updatedAt, - title: item.title, - image: item.image, - rating: item.rating, - release_date: item.release_date, - overview: item.overview, + title: item.title ?? undefined, + image: item.image ?? undefined, + rating: item.rating ?? undefined, + release_date: item.releaseDate ?? undefined, + overview: item.overview ?? undefined, })) .sort((a, b) => b.lastUpdated - a.lastUpdated); } @@ -525,112 +549,58 @@ export function useContinueWatching() { overview: item.overview, })) .sort((a, b) => b.lastUpdated - a.lastUpdated); - }, [isSignedIn, convexData, localMediaState]); + }, [isSignedIn, remote.data, localMediaState]); return { items, allItems: items }; } export function useRemoveFromContinueWatching() { const { isSignedIn } = useUser(); - const setProgressStatusConvex = useMutation(api.watchlist.setProgressStatus); - const setProgressStatusLocal = useWatchlistStore( + const queryClient = useQueryClient(); + const setLocalProgressStatus = useWatchlistStore( (state) => state.setProgressStatusLocal, ); const clearShowProgress = useLocalProgressStore( (state) => state.clearShowProgress, ); + const mutation = useMutation({ + mutationFn: (args: { tmdbId: number; mediaType: "movie" | "tv" }) => + unwrap( + setProgressStatus({ + data: { + ...args, + progressStatus: "watch-later", + progress: 0, + }, + }), + ), + onSettled: () => { + void queryClient.invalidateQueries({ + queryKey: queryKeys.watchlist.list(), + }); + }, + }); + const removeFromContinueWatching = useCallback( async (tmdbId: number, mediaType: "movie" | "tv") => { if (isSignedIn) { try { - await setProgressStatusConvex({ - tmdbId, - mediaType, - progressStatus: "watch-later", - progress: 0, - }); + await mutation.mutateAsync({ tmdbId, mediaType }); } catch (error) { console.error("Failed to remove item from continue watching:", error); } } - setProgressStatusLocal(String(tmdbId), mediaType, "watch-later", 0); + setLocalProgressStatus(String(tmdbId), mediaType, "watch-later", 0); clearShowProgress(tmdbId); }, - [ - isSignedIn, - setProgressStatusConvex, - setProgressStatusLocal, - clearShowProgress, - ], + [isSignedIn, mutation, setLocalProgressStatus, clearShowProgress], ); return { removeFromContinueWatching }; } -import { createOptimisticUpdater } from "./optimistic-helpers"; - -const markEpisodeWatchedOptimisticUpdate = createOptimisticUpdater( - api.watchlist.getAllWatchedEpisodes, - (current: any[], args: any) => { - if (!args.isWatched) { - return current.filter( - (episode: any) => - !(episode.season === args.season && episode.episode === args.episode), - ); - } - const already = current.some( - (episode: any) => - episode.season === args.season && episode.episode === args.episode, - ); - if (already) return current; - - const now = Date.now(); - return [ - ...current, - createOptimisticEpisodeProgress( - args.tmdbId, - args.season, - args.episode, - String(now), - now, - ), - ]; - }, - (args) => ({ tmdbId: args.tmdbId }), -); - -const markSeasonEpisodesWatchedOptimisticUpdate = createOptimisticUpdater( - api.watchlist.getAllWatchedEpisodes, - (current: any[], args: any) => { - const filtered = current.filter( - (episode: any) => - !( - episode.season === args.season && - args.episodes.includes(episode.episode) - ), - ); - - if (!args.isWatched) { - return filtered; - } - - const now = Date.now(); - const newEpisodes = args.episodes.map((episode: any) => - createOptimisticEpisodeProgress( - args.tmdbId, - args.season, - episode, - `${now}_${episode}`, - now, - ), - ); - return [...filtered, ...newEpisodes]; - }, - (args) => ({ tmdbId: args.tmdbId }), -); - export function useEpisodeWatched( tvId: number | string, totalEpisodes?: number, @@ -639,11 +609,12 @@ export function useEpisodeWatched( const tmdbId = Number(tvId); const { isSignedIn } = useUser(); const mediaState = useMediaState(String(tvId), "tv"); - const watchedEpisodes = - useQuery( - api.watchlist.getAllWatchedEpisodes, - isSignedIn ? { tmdbId } : QUERY_SKIP, - ) || []; + const watchedEpisodesQuery = useQuery({ + queryKey: queryKeys.watchlist.episodes(tmdbId), + queryFn: () => unwrap(getAllWatchedEpisodes({ data: { tmdbId } })), + enabled: !!isSignedIn, + }); + const watchedEpisodes = watchedEpisodesQuery.data ?? []; const localEpisodes = useLocalProgressStore((state) => state.watchedEpisodes); const markLocalEpisode = useLocalProgressStore( (state) => state.markEpisodeWatched, @@ -694,16 +665,138 @@ export function useEpisodeWatched( const watchedCount = Object.keys(watchedMap).length; - const markEpisodeWatchedMut = useMutation( - api.watchlist.markEpisodeWatched, - ).withOptimisticUpdate(markEpisodeWatchedOptimisticUpdate); + const markEpisodeMutation = useMutation({ + mutationFn: (args: { + tmdbId: number; + season: number; + episode: number; + isWatched: boolean; + }) => unwrap(markEpisodeWatched({ data: args })), + onMutate: async (args) => { + const key = queryKeys.watchlist.episodes(args.tmdbId); + return beginOptimistic(queryClient, [key], () => { + const current = (queryClient.getQueryData(key) ?? + []) as EpisodeProgressRow[]; + if (!args.isWatched) { + queryClient.setQueryData( + key, + current.filter( + (episode) => + !( + episode.season === args.season && + episode.episode === args.episode + ), + ), + ); + return; + } + const already = current.some( + (episode) => + episode.season === args.season && episode.episode === args.episode, + ); + if (already) return; + const now = Date.now(); + queryClient.setQueryData(key, [ + ...current, + createOptimisticEpisodeProgress( + args.tmdbId, + args.season, + args.episode, + String(now), + now, + ), + ]); + }); + }, + onError: (error, _args, rollback) => { + logWatchProgressError("toggle episode watched", error); + rollback?.(); + }, + onSettled: () => { + void queryClient.invalidateQueries({ + queryKey: ["watchlist", "episodes"], + }); + }, + }); - const markEpisodesWatchedBatch = useMutation( - api.watchlist.markSeasonEpisodesWatched, - ).withOptimisticUpdate(markSeasonEpisodesWatchedOptimisticUpdate); + const markSeasonMutation = useMutation({ + mutationFn: (args: { + tmdbId: number; + season: number; + episodes: number[]; + isWatched: boolean; + }) => unwrap(markSeasonEpisodesWatched({ data: args })), + onMutate: async (args) => { + const key = queryKeys.watchlist.episodes(args.tmdbId); + return beginOptimistic(queryClient, [key], () => { + const current = (queryClient.getQueryData(key) ?? + []) as EpisodeProgressRow[]; + const filtered = current.filter( + (episode) => + !( + episode.season === args.season && + args.episodes.includes(episode.episode) + ), + ); + if (!args.isWatched) { + queryClient.setQueryData(key, filtered); + return; + } + const now = Date.now(); + const newEpisodes = args.episodes.map((episode) => + createOptimisticEpisodeProgress( + args.tmdbId, + args.season, + episode, + `${now}_${episode}`, + now, + ), + ); + queryClient.setQueryData(key, [ + ...filtered, + ...newEpisodes, + ]); + }); + }, + onError: (error, _args, rollback) => { + logWatchProgressError("mark season episodes watched", error); + rollback?.(); + }, + onSettled: () => { + void queryClient.invalidateQueries({ + queryKey: ["watchlist", "episodes"], + }); + }, + }); + + const updateProgressMutation = useMutation({ + mutationFn: (args: { + tmdbId: number; + mediaType: "movie" | "tv"; + progress?: number; + }) => unwrap(updateProgress({ data: args })), + }); + + const setProgressStatusMutation = useMutation({ + mutationFn: (args: { + tmdbId: number; + mediaType: "movie" | "tv"; + progressStatus: "watch-later" | "watching" | "done" | "dropped"; + progress?: number; + title?: string; + image?: string; + rating?: number; + release_date?: string; + overview?: string; + }) => unwrap(setProgressStatus({ data: args })), + onSettled: () => { + void queryClient.invalidateQueries({ + queryKey: queryKeys.watchlist.list(), + }); + }, + }); - const updateProgress = useMutation(api.watchlist.updateProgress); - const setProgressStatus = useMutation(api.watchlist.setProgressStatus); + const queryClient = useQueryClient(); const hasMediaState = !!mediaState; const currentProgress = mediaState?.progress ?? 0; const currentProgressStatus = mediaState?.progressStatus ?? null; @@ -743,11 +836,13 @@ export function useEpisodeWatched( if (currentProgressStatus === "watching" && derivedStatus !== "watching") { if (shouldWriteProgress) { if (isSignedIn) { - void updateProgress({ - tmdbId, - mediaType: "tv", - progress: derivedProgress, - }).catch((error) => logWatchProgressError("sync TV progress", error)); + void updateProgressMutation + .mutateAsync({ + tmdbId, + mediaType: "tv", + progress: derivedProgress, + }) + .catch((error) => logWatchProgressError("sync TV progress", error)); } else { setProgressLocal( String(tvId), @@ -762,21 +857,29 @@ export function useEpisodeWatched( if (isSignedIn) { if (shouldWriteStatus) { - void setProgressStatus({ - tmdbId, - mediaType: "tv", - progressStatus: derivedStatus as any, - progress: derivedProgress, - ...remoteShowMetadata, - }).catch((error) => - logWatchProgressError("sync TV progress status", error), - ); + void setProgressStatusMutation + .mutateAsync({ + tmdbId, + mediaType: "tv", + progressStatus: derivedStatus as + | "watch-later" + | "watching" + | "done" + | "dropped", + progress: derivedProgress, + ...remoteShowMetadata, + }) + .catch((error) => + logWatchProgressError("sync TV progress status", error), + ); } else if (shouldWriteProgress) { - void updateProgress({ - tmdbId, - mediaType: "tv", - progress: derivedProgress, - }).catch((error) => logWatchProgressError("sync TV progress", error)); + void updateProgressMutation + .mutateAsync({ + tmdbId, + mediaType: "tv", + progress: derivedProgress, + }) + .catch((error) => logWatchProgressError("sync TV progress", error)); } return; } @@ -788,7 +891,7 @@ export function useEpisodeWatched( setProgressStatusLocal( String(tvId), "tv", - derivedStatus as any, + derivedStatus as Parameters[2], derivedProgress, localShowMetadata, ); @@ -805,8 +908,8 @@ export function useEpisodeWatched( remoteShowMetadata, tmdbId, tvId, - updateProgress, - setProgressStatus, + updateProgressMutation, + setProgressStatusMutation, setProgressLocal, setProgressStatusLocal, ]); @@ -823,7 +926,7 @@ export function useEpisodeWatched( const isWatched = !isEpisodeWatched(season, episode); if (isSignedIn) { - markEpisodeWatchedMut({ tmdbId, season, episode, isWatched }); + markEpisodeMutation.mutate({ tmdbId, season, episode, isWatched }); } else { markLocalEpisode(tmdbId, season, episode, isWatched); } @@ -831,7 +934,7 @@ export function useEpisodeWatched( [ isEpisodeWatched, isSignedIn, - markEpisodeWatchedMut, + markEpisodeMutation, markLocalEpisode, tmdbId, ], @@ -840,26 +943,24 @@ export function useEpisodeWatched( const markSeasonWatched = useCallback( (season: number, episodes: number[]) => { if (isSignedIn) { - markEpisodesWatchedBatch({ tmdbId, season, episodes, isWatched: true }); + markSeasonMutation.mutate({ + tmdbId, + season, + episodes, + isWatched: true, + }); return; } markLocalSeason(tmdbId, season, episodes, true); }, - [isSignedIn, markEpisodesWatchedBatch, markLocalSeason, tmdbId], + [isSignedIn, markSeasonMutation, markLocalSeason, tmdbId], ); const unmarkSeasonWatched = useCallback( (season: number, episodes: number[]) => { - let _watchedToRemove = 0; - for (const episode of episodes) { - if (watchedMap[makeEpisodeKey(tmdbId, season, episode)]) { - _watchedToRemove++; - } - } - if (isSignedIn) { - markEpisodesWatchedBatch({ + markSeasonMutation.mutate({ tmdbId, season, episodes, @@ -869,7 +970,7 @@ export function useEpisodeWatched( markLocalSeason(tmdbId, season, episodes, false); } }, - [isSignedIn, markEpisodesWatchedBatch, markLocalSeason, tmdbId, watchedMap], + [isSignedIn, markSeasonMutation, markLocalSeason, tmdbId], ); const isSeasonFullyWatched = useCallback( @@ -905,19 +1006,21 @@ export function useEpisodeWatched( const markShowCompleted = useCallback( (_totalEpisodesOverride: number) => { if (isSignedIn) { - void setProgressStatus({ - tmdbId, - mediaType: "tv", - progressStatus: "done", - progress: 100, - title: showMeta?.title ?? `TV Show ${tvId}`, - image: showMeta?.image ?? "", - rating: showMeta?.rating ?? 0, - release_date: showMeta?.release_date || undefined, - overview: showMeta?.overview || undefined, - }).catch((error) => - logWatchProgressError("mark show completed", error), - ); + void setProgressStatusMutation + .mutateAsync({ + tmdbId, + mediaType: "tv", + progressStatus: "done", + progress: 100, + title: showMeta?.title ?? `TV Show ${tvId}`, + image: showMeta?.image ?? "", + rating: showMeta?.rating ?? 0, + release_date: showMeta?.release_date || undefined, + overview: showMeta?.overview || undefined, + }) + .catch((error) => + logWatchProgressError("mark show completed", error), + ); return; } @@ -932,7 +1035,7 @@ export function useEpisodeWatched( [ isSignedIn, localShowMetadata, - setProgressStatus, + setProgressStatusMutation, setProgressStatusLocal, showMeta?.image, showMeta?.overview, @@ -963,26 +1066,24 @@ export function useEpisodeProgress( ) { const { isSignedIn } = useUser(); - const data = useQuery( - api.watchlist.getAllWatchedEpisodes, - isSignedIn - ? { - tmdbId: Number(tvId), - } - : QUERY_SKIP, - ); + const data = useQuery({ + queryKey: queryKeys.watchlist.episodes(Number(tvId)), + queryFn: () => + unwrap(getAllWatchedEpisodes({ data: { tmdbId: Number(tvId) } })), + enabled: !!isSignedIn, + }); const localEpisodes = useLocalProgressStore((state) => state.watchedEpisodes); return useMemo(() => { if (isSignedIn) { - const isWatched = !!data?.some( + const isWatched = !!data.data?.some( (e) => e.season === season && e.episode === episode && e.isWatched, ); return isWatched ? 100 : 0; } return localEpisodes[makeEpisodeKey(tvId, season, episode)] ? 100 : 0; - }, [isSignedIn, data, localEpisodes, tvId, season, episode]); + }, [isSignedIn, data.data, localEpisodes, tvId, season, episode]); } export function buildPlayerUrl(opts: { diff --git a/src/hooks/use-watchlist-import-export.ts b/src/hooks/use-watchlist-import-export.ts index bf585f1d..63313f5b 100644 --- a/src/hooks/use-watchlist-import-export.ts +++ b/src/hooks/use-watchlist-import-export.ts @@ -1,5 +1,5 @@ import { useUser } from "@clerk/react"; -import { useMutation, useQuery } from "convex/react"; +import { useQuery } from "@tanstack/react-query"; import type React from "react"; import { useCallback, useRef, useState } from "react"; @@ -9,11 +9,14 @@ import { useWatchlistStore, type WatchlistItem, } from "@/hooks/use-watchlist"; +import { queryKeys } from "@/lib/query/keys"; +import type { AllEpisodeProgressRow } from "@/lib/server-types"; import { normalizeProgressStatus } from "@/lib/utils"; +import { importWatchlist as importWatchlistFn } from "@/server/fns/import-export"; +import { getAllEpisodeProgress } from "@/server/fns/watchlist"; +import { unwrap } from "@/server/schema/common"; import type { ReactionStatus } from "@/types"; -import { api } from "../../convex/_generated/api"; - function isValidWatchlistItem(item: unknown): item is ImportItem { if (typeof item !== "object" || item === null) return false; const obj = item as Record; @@ -43,7 +46,6 @@ export const useWatchlistImportExport = () => { const { watchlist, loading } = useWatchlist(); - const importWatchlistBatch = useMutation(api.watchlist.importWatchlist); const importWatchlistLocal = useWatchlistStore( (state) => state.importWatchlistLocal, ); @@ -52,10 +54,11 @@ export const useWatchlistImportExport = () => { ); const { isSignedIn } = useUser(); - const allEpisodeProgress = useQuery( - api.watchlist.getAllEpisodeProgress, - isSignedIn ? {} : "skip", - ); + const allEpisodeProgress = useQuery({ + queryKey: queryKeys.watchlist.allEpisodes(), + queryFn: () => unwrap(getAllEpisodeProgress()), + enabled: !!isSignedIn, + }); const fileInputRef = useRef(null); const exportWatchlist = useCallback(async () => { @@ -72,15 +75,10 @@ export const useWatchlistImportExport = () => { const itemWatched: Record = {}; if (item.type === "tv") { - if (isSignedIn && allEpisodeProgress) { - allEpisodeProgress + if (isSignedIn && allEpisodeProgress.data) { + allEpisodeProgress.data .filter( - (ep: { - tmdbId: number; - isWatched: boolean; - season: number; - episode: number; - }) => + (ep: AllEpisodeProgressRow) => String(ep.tmdbId) === String(item.external_id) && ep.isWatched, ) @@ -129,7 +127,7 @@ export const useWatchlistImportExport = () => { } finally { setExportLoading(false); } - }, [watchlist, isSignedIn, allEpisodeProgress]); + }, [watchlist, isSignedIn, allEpisodeProgress.data]); const importWatchlist = useCallback( async (event: React.ChangeEvent) => { @@ -229,10 +227,12 @@ export const useWatchlistImportExport = () => { })); if (isSignedIn) { - await importWatchlistBatch({ - // biome-ignore lint/suspicious/noExplicitAny: dynamic reaction item import - items: importItems as any, - watchedEpisodes, + await importWatchlistFn({ + data: { + // biome-ignore lint/suspicious/noExplicitAny: dynamic reaction item import + items: importItems as any, + watchedEpisodes, + }, }); } else { importWatchlistLocal( @@ -286,12 +286,7 @@ export const useWatchlistImportExport = () => { reader.readAsText(file); }, - [ - importWatchlistBatch, - importWatchlistLocal, - isSignedIn, - markEpisodeWatchedLocal, - ], + [importWatchlistLocal, isSignedIn, markEpisodeWatchedLocal], ); const handleImportClick = useCallback(() => { diff --git a/src/hooks/use-watchlist.ts b/src/hooks/use-watchlist.ts index 4eed150d..c753853b 100644 --- a/src/hooks/use-watchlist.ts +++ b/src/hooks/use-watchlist.ts @@ -1,23 +1,37 @@ import { useUser } from "@clerk/react"; -import { useQueryClient } from "@tanstack/react-query"; -import { useMutation, useQuery } from "convex/react"; +import { + type QueryClient, + useMutation, + useQuery, + useQueryClient, +} from "@tanstack/react-query"; import { useCallback, useEffect, useMemo, useRef } from "react"; import { getTvDetails } from "@/lib/queries"; +import { queryKeys } from "@/lib/query/keys"; +import type { EpisodeProgressRow, WatchItemRow } from "@/lib/server-types"; +import { + getWatchlist, + markShowEpisodesAndStatus, + setProgressStatus, + setReaction, + setWatchlistMembership, +} from "@/server/fns/watchlist"; +import { unwrap } from "@/server/schema/common"; import type { ProgressStatus, ReactionStatus } from "@/types"; -import { api } from "../../convex/_generated/api"; -import type { Id } from "../../convex/_generated/dataModel"; -import { createOptimisticUpdater } from "./optimistic-helpers"; +import { + beginOptimistic, + createOptimisticUpdater, + setCached, +} from "./optimistic-helpers"; import { useLocalProgressStore } from "./use-local-progress-store"; import { type MediaMetadata, type MediaType, - mapConvexItemToWatchlistItem, + mapWatchlistRowToItem, useWatchlistStore, type WatchlistItem, } from "./watchlist-store"; -const QUERY_SKIP = "skip" as const; - export { useWatchlistStore } from "./watchlist-store"; export type { MediaMetadata, MediaType, WatchlistItem }; @@ -27,10 +41,11 @@ function logWatchlistError(action: string, error: unknown) { export function useWatchlist() { const { isSignedIn, isLoaded } = useUser(); - const convexWatchlistData = useQuery( - api.watchlist.getWatchlist, - isSignedIn ? {} : QUERY_SKIP, - ); + const remote = useQuery({ + queryKey: queryKeys.watchlist.list(), + queryFn: () => unwrap(getWatchlist({ data: {} })), + enabled: !!isSignedIn, + }); const localMediaState = useWatchlistStore((state) => state.mediaState); const watchlist: WatchlistItem[] = useMemo(() => { @@ -39,9 +54,9 @@ export function useWatchlist() { } if (isSignedIn) { - if (!convexWatchlistData) return []; - return convexWatchlistData - .map((item) => mapConvexItemToWatchlistItem(item)) + if (!remote.data) return []; + return remote.data + .map((item) => mapWatchlistRowToItem(item)) .filter( (item) => item.inWatchlist || @@ -59,35 +74,34 @@ export function useWatchlist() { (item.progress ?? 0) > 0, ) .sort((a, b) => b.updated_at - a.updated_at); - }, [isLoaded, isSignedIn, convexWatchlistData, localMediaState]); + }, [isLoaded, isSignedIn, remote.data, localMediaState]); - const loading = - !isLoaded || (isSignedIn && convexWatchlistData === undefined); + const loading = !isLoaded || (isSignedIn && remote.isPending); return { watchlist, loading }; } export function useAllMediaStates() { const { isSignedIn, isLoaded } = useUser(); - const convexWatchlistData = useQuery( - api.watchlist.getWatchlist, - isSignedIn ? {} : QUERY_SKIP, - ); + const remote = useQuery({ + queryKey: queryKeys.watchlist.list(), + queryFn: () => unwrap(getWatchlist({ data: {} })), + enabled: !!isSignedIn, + }); const localMediaState = useWatchlistStore((state) => state.mediaState); const allMediaStates: WatchlistItem[] = useMemo(() => { if (isSignedIn) { - if (!convexWatchlistData) return []; - return convexWatchlistData - .map((item) => mapConvexItemToWatchlistItem(item)) + if (!remote.data) return []; + return remote.data + .map((item) => mapWatchlistRowToItem(item)) .sort((a, b) => b.updated_at - a.updated_at); } return [...localMediaState].sort((a, b) => b.updated_at - a.updated_at); - }, [isSignedIn, convexWatchlistData, localMediaState]); + }, [isSignedIn, remote.data, localMediaState]); - const loading = - !isLoaded || (isSignedIn && convexWatchlistData === undefined); + const loading = !isLoaded || (isSignedIn && remote.isPending); return { allMediaStates, loading }; } @@ -95,10 +109,16 @@ export function useAllMediaStates() { export function useMediaState(id: string, mediaType: MediaType) { const { isSignedIn } = useUser(); const localMediaState = useWatchlistStore((state) => state.mediaState); - const remoteState = useQuery( - api.watchlist.getMediaState, - isSignedIn ? { tmdbId: Number(id), mediaType } : QUERY_SKIP, - ); + const tmdbId = Number(id); + // Derive per-item state from the single shared watchlist query instead of + // firing one `getMediaState` RPC per item. A grid of N cards used to trigger + // N backend calls (every WatchlistButton on every card); now they all share + // the one `getWatchlist` fetch, so a 50-card grid is a single request. + const remote = useQuery({ + queryKey: queryKeys.watchlist.list(), + queryFn: () => unwrap(getWatchlist({ data: {} })), + enabled: !!isSignedIn, + }); return useMemo(() => { if (!isSignedIn) { @@ -109,90 +129,119 @@ export function useMediaState(id: string, mediaType: MediaType) { ); } - if (!remoteState) return null; - return mapConvexItemToWatchlistItem(remoteState); - }, [isSignedIn, localMediaState, id, mediaType, remoteState]); + if (!remote.data) return null; + const row = remote.data.find( + (item) => item.tmdbId === tmdbId && item.mediaType === mediaType, + ); + if (!row) return null; + return mapWatchlistRowToItem(row); + }, [isSignedIn, localMediaState, id, mediaType, tmdbId, remote.data]); } -const updateWatchlistMembership = createOptimisticUpdater( - api.watchlist.getWatchlist, - (current: any[], args: any) => { +type WatchlistMembershipArgs = { + tmdbId: number; + mediaType: MediaType; + inWatchlist: boolean; + title?: string; + image?: string; + rating?: number; + release_date?: string; + overview?: string; +}; + +const updateWatchlistMembership = createOptimisticUpdater< + WatchItemRow, + WatchlistMembershipArgs +>( + () => queryKeys.watchlist.list(), + (current, args) => { if (args.inWatchlist) { const existing = current.find( - (i: any) => i.tmdbId === args.tmdbId && i.mediaType === args.mediaType, + (i) => i.tmdbId === args.tmdbId && i.mediaType === args.mediaType, ); if (existing) { - return current.map((i: any) => + return current.map((i) => i === existing ? { ...i, inWatchlist: true, updatedAt: Date.now() } : i, ); - } else { - return [ - ...current, - { - tmdbId: args.tmdbId, - mediaType: args.mediaType, - title: args.title, - image: args.image, - rating: args.rating, - release_date: args.release_date, - overview: args.overview, - inWatchlist: true, - updatedAt: Date.now(), - userId: "optimistic" as unknown as Id<"users">, - _id: `optimistic_${Date.now()}` as unknown as Id<"watch_items">, - _creationTime: Date.now(), - }, - ]; } - } else { - return current.map((i: any) => - i.tmdbId === args.tmdbId && i.mediaType === args.mediaType - ? { ...i, inWatchlist: false } - : i, - ); + return [ + ...current, + { + id: `optimistic_${Date.now()}`, + userId: "optimistic", + tmdbId: args.tmdbId, + mediaType: args.mediaType, + title: args.title ?? null, + image: args.image ?? null, + rating: args.rating ?? null, + releaseDate: args.release_date ?? null, + overview: args.overview ?? null, + inWatchlist: true, + progressStatus: "watch-later", + reaction: null, + progress: 0, + updatedAt: Date.now(), + } as WatchItemRow, + ]; } + return current.map((i) => + i.tmdbId === args.tmdbId && i.mediaType === args.mediaType + ? { ...i, inWatchlist: false } + : i, + ); }, ); -function setWatchlistMembershipOptimisticUpdate(localStore: any, args: any) { - updateWatchlistMembership(localStore, args); - - const mediaStateArgs = { tmdbId: args.tmdbId, mediaType: args.mediaType }; - const currentMediaState = localStore.getQuery( - api.watchlist.getMediaState, - mediaStateArgs, +async function setWatchlistMembershipOptimistic( + queryClient: QueryClient, + args: WatchlistMembershipArgs, +) { + const mediaKey = queryKeys.watchlist.mediaState( + args.tmdbId, + args.mediaType as MediaType, + ); + return beginOptimistic( + queryClient, + [queryKeys.watchlist.list(), mediaKey], + () => { + updateWatchlistMembership(queryClient, args); + setCached(queryClient, mediaKey, (current) => { + if (current) { + return { + ...current, + inWatchlist: args.inWatchlist, + updatedAt: Date.now(), + }; + } + if (args.inWatchlist) { + return { + id: `optimistic_${Date.now()}`, + userId: "optimistic", + tmdbId: args.tmdbId, + mediaType: args.mediaType as WatchItemRow["mediaType"], + title: args.title ?? null, + image: args.image ?? null, + rating: args.rating ?? null, + releaseDate: args.release_date ?? null, + overview: args.overview ?? null, + inWatchlist: true, + progressStatus: "watch-later", + reaction: null, + progress: 0, + updatedAt: Date.now(), + }; + } + return undefined; + }); + }, ); - if (currentMediaState) { - localStore.setQuery(api.watchlist.getMediaState, mediaStateArgs, { - ...currentMediaState, - inWatchlist: args.inWatchlist, - updatedAt: Date.now(), - }); - } else if (args.inWatchlist) { - localStore.setQuery(api.watchlist.getMediaState, mediaStateArgs, { - tmdbId: args.tmdbId, - mediaType: args.mediaType, - title: args.title, - image: args.image, - rating: args.rating, - release_date: args.release_date, - overview: args.overview, - inWatchlist: true, - updatedAt: Date.now(), - userId: "optimistic" as unknown as Id<"users">, - _id: `optimistic_${Date.now()}` as unknown as Id<"watch_items">, - _creationTime: Date.now(), - }); - } } export function useToggleWatchlistItem() { const { isSignedIn } = useUser(); - const setWatchlistMembership = useMutation( - api.watchlist.setWatchlistMembership, - ).withOptimisticUpdate(setWatchlistMembershipOptimisticUpdate); + const queryClient = useQueryClient(); const setLocalWatchlistMembership = useWatchlistStore( (state) => state.setWatchlistMembershipLocal, ); @@ -203,6 +252,21 @@ export function useToggleWatchlistItem() { watchlistRef.current = watchlist; }); + const mutation = useMutation({ + mutationFn: (args: WatchlistMembershipArgs) => + unwrap(setWatchlistMembership({ data: args })), + onMutate: (args) => setWatchlistMembershipOptimistic(queryClient, args), + onError: (error, _args, rollback) => { + logWatchlistError("set watchlist membership", error); + rollback?.(); + }, + onSettled: () => { + void queryClient.invalidateQueries({ + queryKey: queryKeys.watchlist.list(), + }); + }, + }); + return useCallback( async ( item: { @@ -228,7 +292,7 @@ export function useToggleWatchlistItem() { const inWatchlist = !currentlyInWatchlist; if (isSignedIn) { - await setWatchlistMembership({ + await mutation.mutateAsync({ tmdbId: Number(item.id), mediaType: item.media_type, inWatchlist, @@ -249,14 +313,29 @@ export function useToggleWatchlistItem() { overview: item.overview, }); }, - [isSignedIn, setWatchlistMembership, setLocalWatchlistMembership], + [isSignedIn, mutation, setLocalWatchlistMembership], ); } -const updateProgressStatus = createOptimisticUpdater( - api.watchlist.getWatchlist, - (current: any[], args: any) => { - return current.map((i: any) => +type ProgressStatusArgs = { + tmdbId: number; + mediaType: MediaType; + progressStatus: ProgressStatus; + progress?: number; + title?: string; + image?: string; + rating?: number; + release_date?: string; + overview?: string; +}; + +const updateProgressStatus = createOptimisticUpdater< + WatchItemRow, + ProgressStatusArgs +>( + () => queryKeys.watchlist.list(), + (current, args) => { + return current.map((i) => i.tmdbId === args.tmdbId && i.mediaType === args.mediaType ? { ...i, @@ -270,125 +349,160 @@ const updateProgressStatus = createOptimisticUpdater( }, ); -function setProgressStatusOptimisticUpdate(localStore: any, args: any) { - updateProgressStatus(localStore, args); - - const mediaStateArgs = { tmdbId: args.tmdbId, mediaType: args.mediaType }; - const currentMediaState = localStore.getQuery( - api.watchlist.getMediaState, - mediaStateArgs, +async function setProgressStatusOptimistic( + queryClient: QueryClient, + args: ProgressStatusArgs, +) { + const mediaKey = queryKeys.watchlist.mediaState(args.tmdbId, args.mediaType); + return beginOptimistic( + queryClient, + [queryKeys.watchlist.list(), mediaKey], + () => { + updateProgressStatus(queryClient, args); + setCached(queryClient, mediaKey, (current) => { + if (!current) return current; + return { + ...current, + inWatchlist: true, + progressStatus: args.progressStatus, + progress: args.progress ?? current.progress, + updatedAt: Date.now(), + }; + }); + }, ); - if (currentMediaState) { - localStore.setQuery(api.watchlist.getMediaState, mediaStateArgs, { - ...currentMediaState, - inWatchlist: true, - progressStatus: args.progressStatus, - progress: args.progress ?? currentMediaState.progress, - updatedAt: Date.now(), - }); - } } -const updateMarkShowEpisodes = createOptimisticUpdater( - api.watchlist.getAllWatchedEpisodes, - (current: any[], args: any) => { +type MarkShowEpisodesAndStatusArgs = { + tmdbId: number; + mediaType: MediaType; + seasons: Array<{ season: number; episodes: number[] }>; + isWatched: boolean; + clearAllEpisodes?: boolean; + progressStatus?: ProgressStatus; + progress?: number; + title?: string; + image?: string; + rating?: number; + release_date?: string; + overview?: string; +}; + +const updateShowEpisodes = createOptimisticUpdater< + EpisodeProgressRow, + MarkShowEpisodesAndStatusArgs +>( + (args) => queryKeys.watchlist.episodes(args.tmdbId), + (current, args) => { if (args.isWatched) { const now = Date.now(); - const filtered = current.filter( - (e: any) => - !args.seasons.some( - (s: any) => e.season === s.season && s.episodes.includes(e.episode), - ), - ); - - const newEpisodes = args.seasons.flatMap((s: any) => - s.episodes.map((ep: any) => ({ - _id: `optimistic_${now}_${s.season}_${ep}` as Id<"episode_progress">, - _creationTime: now, - userId: "optimistic" as unknown as Id<"users">, - tmdbId: args.tmdbId, - season: s.season, - episode: ep, - isWatched: true as const, - updatedAt: now, - })), + const existingKeys = new Set( + current.map((e) => `${e.season}:${e.episode}`), ); - - return [...filtered, ...newEpisodes]; - } else if (args.clearAllEpisodes || args.seasons.length > 0) { - return []; + const newEpisodes: EpisodeProgressRow[] = []; + for (const s of args.seasons) { + for (const ep of s.episodes) { + if (!existingKeys.has(`${s.season}:${ep}`)) { + newEpisodes.push({ + id: `optimistic_${now}_${s.season}_${ep}`, + userId: "optimistic", + tmdbId: args.tmdbId, + season: s.season, + episode: ep, + isWatched: true, + updatedAt: now, + }); + } + } + } + return [...current, ...newEpisodes]; + } + if (args.clearAllEpisodes || args.seasons.length > 0) { + return current.filter((e) => { + if (args.clearAllEpisodes) return false; + return !args.seasons.some( + (s) => s.season === e.season && s.episodes.includes(e.episode), + ); + }); } return current; }, - (args) => ({ tmdbId: args.tmdbId }), ); -function markShowEpisodesAndStatusOptimisticUpdate(localStore: any, args: any) { - if (args.progressStatus !== undefined) { - updateProgressStatus(localStore, args); - - const mediaStateArgs = { tmdbId: args.tmdbId, mediaType: args.mediaType }; - const currentMediaState = localStore.getQuery( - api.watchlist.getMediaState, - mediaStateArgs, - ); - if (currentMediaState) { - localStore.setQuery(api.watchlist.getMediaState, mediaStateArgs, { - ...currentMediaState, - progressStatus: args.progressStatus, - progress: args.progress ?? currentMediaState.progress, - updatedAt: Date.now(), - }); - } - } - - updateMarkShowEpisodes(localStore, args); -} - -function getTrackableTvSeasons(details?: { - seasons?: Array<{ season_number: number; episode_count: number }> | null; -}) { - return ( - details?.seasons?.filter( - (season) => season.season_number >= 0 && season.episode_count > 0, - ) ?? [] - ); -} - -function buildSeasonEpisodeSelections(details?: { - seasons?: Array<{ season_number: number; episode_count: number }> | null; -}) { - return getTrackableTvSeasons(details).map((season) => ({ - season: season.season_number, - episodes: Array.from( - { length: season.episode_count }, - (_, index) => index + 1, - ), - })); -} - export function useSetProgressStatus() { const { isSignedIn } = useUser(); const queryClient = useQueryClient(); - const setProgressStatus = useMutation( - api.watchlist.setProgressStatus, - ).withOptimisticUpdate(setProgressStatusOptimisticUpdate); - - const markShowEpisodesAndStatus = useMutation( - api.watchlist.markShowEpisodesAndStatus, - ).withOptimisticUpdate(markShowEpisodesAndStatusOptimisticUpdate); - - const setProgressStatusLocal = useWatchlistStore( + const setLocalProgressStatus = useWatchlistStore( (state) => state.setProgressStatusLocal, ); const markLocalSeason = useLocalProgressStore( (state) => state.markSeasonWatched, ); - const clearLocalShowProgress = useLocalProgressStore( (state) => state.clearShowProgress, ); + const progressMutation = useMutation({ + mutationFn: (args: ProgressStatusArgs) => + unwrap(setProgressStatus({ data: args })), + onMutate: (args) => setProgressStatusOptimistic(queryClient, args), + onError: (error, _args, rollback) => { + logWatchlistError("set progress status", error); + rollback?.(); + }, + onSettled: () => { + void queryClient.invalidateQueries({ + queryKey: queryKeys.watchlist.list(), + }); + }, + }); + + const markShowMutation = useMutation({ + mutationFn: (args: MarkShowEpisodesAndStatusArgs) => + unwrap(markShowEpisodesAndStatus({ data: args })), + onMutate: async (args) => { + const mediaKey = queryKeys.watchlist.mediaState( + args.tmdbId, + args.mediaType, + ); + const episodeKey = queryKeys.watchlist.episodes(args.tmdbId); + return beginOptimistic( + queryClient, + [queryKeys.watchlist.list(), mediaKey, episodeKey], + () => { + if (args.progressStatus !== undefined) { + updateProgressStatus( + queryClient, + args as unknown as ProgressStatusArgs, + ); + setCached(queryClient, mediaKey, (current) => { + if (!current) return current; + return { + ...current, + progressStatus: args.progressStatus ?? null, + progress: args.progress ?? current.progress, + updatedAt: Date.now(), + }; + }); + } + updateShowEpisodes(queryClient, args); + }, + ); + }, + onError: (error, _args, rollback) => { + logWatchlistError("sync show episode status", error); + rollback?.(); + }, + onSettled: () => { + void queryClient.invalidateQueries({ + queryKey: queryKeys.watchlist.list(), + }); + void queryClient.invalidateQueries({ + queryKey: ["watchlist", "episodes"], + }); + }, + }); + return useCallback( ( id: string, @@ -414,23 +528,24 @@ export function useSetProgressStatus() { : undefined; if (isSignedIn) { + const baseArgs: MarkShowEpisodesAndStatusArgs = { + tmdbId: Number(id), + mediaType, + seasons: [], + isWatched: false, + progressStatus, + progress, + title: metadata?.title, + image: metadata?.image, + rating: metadata?.rating, + release_date: metadata?.release_date, + overview: metadata?.overview, + }; if (isLeavingCompletion && !shouldMarkWatched) { - void markShowEpisodesAndStatus({ - tmdbId: Number(id), - mediaType, - seasons: [], - isWatched: false, + markShowMutation.mutate({ + ...baseArgs, clearAllEpisodes: true, - progressStatus, - progress, - title: metadata?.title, - image: metadata?.image, - rating: metadata?.rating, - release_date: metadata?.release_date, - overview: metadata?.overview, - }).catch((error) => - logWatchlistError("clear remote show episode status", error), - ); + }); } else if (needsEpisodeUpdate) { queryClient .ensureQueryData({ @@ -438,44 +553,20 @@ export function useSetProgressStatus() { queryFn: () => getTvDetails({ id: Number(id) }), }) .then((details) => { - void markShowEpisodesAndStatus({ - tmdbId: Number(id), - mediaType, + markShowMutation.mutate({ + ...baseArgs, seasons: buildSeasonEpisodeSelections(details), isWatched: shouldMarkWatched, - progressStatus, - progress, - title: metadata?.title, - image: metadata?.image, - rating: metadata?.rating, - release_date: metadata?.release_date, - overview: metadata?.overview, - }).catch((error) => - logWatchlistError("sync remote show episode status", error), - ); + }); }) .catch((error) => logWatchlistError("sync remote show episode status", error), ); } else { - void markShowEpisodesAndStatus({ - tmdbId: Number(id), - mediaType, - seasons: [], - isWatched: false, - progressStatus, - progress, - title: metadata?.title, - image: metadata?.image, - rating: metadata?.rating, - release_date: metadata?.release_date, - overview: metadata?.overview, - }).catch((error) => - logWatchlistError("update remote show progress status", error), - ); + markShowMutation.mutate(baseArgs); } } else { - setProgressStatusLocal( + setLocalProgressStatus( id, mediaType, progressStatus, @@ -511,7 +602,7 @@ export function useSetProgressStatus() { } if (isSignedIn) { - setProgressStatus({ + progressMutation.mutate({ tmdbId: Number(id), mediaType, progressStatus, @@ -520,11 +611,9 @@ export function useSetProgressStatus() { rating: metadata?.rating, release_date: metadata?.release_date, overview: metadata?.overview, - }).catch((error) => - logWatchlistError("set remote progress status", error), - ); + }); } else { - setProgressStatusLocal( + setLocalProgressStatus( id, mediaType, progressStatus, @@ -535,9 +624,9 @@ export function useSetProgressStatus() { }, [ isSignedIn, - setProgressStatus, - markShowEpisodesAndStatus, - setProgressStatusLocal, + progressMutation, + markShowMutation, + setLocalProgressStatus, markLocalSeason, clearLocalShowProgress, queryClient.ensureQueryData, @@ -545,14 +634,26 @@ export function useSetProgressStatus() { ); } -const updateReaction = createOptimisticUpdater( - api.watchlist.getWatchlist, - (current: any[], args: any) => { - return current.map((i: any) => +type SetReactionArgs = { + tmdbId: number; + mediaType: MediaType; + reaction?: ReactionStatus; + clearReaction?: boolean; + title?: string; + image?: string; + rating?: number; + release_date?: string; + overview?: string; +}; + +const updateReaction = createOptimisticUpdater( + () => queryKeys.watchlist.list(), + (current, args) => { + return current.map((i) => i.tmdbId === args.tmdbId && i.mediaType === args.mediaType ? { ...i, - reaction: args.clearReaction ? undefined : args.reaction, + reaction: args.clearReaction ? null : (args.reaction ?? null), updatedAt: Date.now(), } : i, @@ -560,30 +661,47 @@ const updateReaction = createOptimisticUpdater( }, ); -function setReactionOptimisticUpdate(localStore: any, args: any) { - updateReaction(localStore, args); - - const mediaStateArgs = { tmdbId: args.tmdbId, mediaType: args.mediaType }; - const currentMediaState = localStore.getQuery( - api.watchlist.getMediaState, - mediaStateArgs, +async function setReactionOptimistic( + queryClient: QueryClient, + args: SetReactionArgs, +) { + const mediaKey = queryKeys.watchlist.mediaState(args.tmdbId, args.mediaType); + return beginOptimistic( + queryClient, + [queryKeys.watchlist.list(), mediaKey], + () => { + updateReaction(queryClient, args); + setCached(queryClient, mediaKey, (current) => { + if (!current) return current; + return { + ...current, + reaction: args.clearReaction ? null : (args.reaction ?? null), + updatedAt: Date.now(), + }; + }); + }, ); - if (currentMediaState) { - localStore.setQuery(api.watchlist.getMediaState, mediaStateArgs, { - ...currentMediaState, - reaction: args.clearReaction ? undefined : args.reaction, - updatedAt: Date.now(), - }); - } } export function useSetReaction() { const { isSignedIn } = useUser(); - const setReaction = useMutation( - api.watchlist.setReaction, - ).withOptimisticUpdate(setReactionOptimisticUpdate); + const queryClient = useQueryClient(); const setReactionLocal = useWatchlistStore((state) => state.setReactionLocal); + const mutation = useMutation({ + mutationFn: (args: SetReactionArgs) => unwrap(setReaction({ data: args })), + onMutate: (args) => setReactionOptimistic(queryClient, args), + onError: (error, _args, rollback) => { + logWatchlistError("set reaction", error); + rollback?.(); + }, + onSettled: () => { + void queryClient.invalidateQueries({ + queryKey: queryKeys.watchlist.list(), + }); + }, + }); + return useCallback( ( id: string, @@ -592,17 +710,7 @@ export function useSetReaction() { metadata?: MediaMetadata, ) => { if (isSignedIn) { - const payload: { - tmdbId: number; - mediaType: MediaType; - reaction?: ReactionStatus; - clearReaction?: boolean; - title?: string; - image?: string; - rating?: number; - release_date?: string; - overview?: string; - } = { + const payload: SetReactionArgs = { tmdbId: Number(id), mediaType, title: metadata?.title, @@ -618,15 +726,13 @@ export function useSetReaction() { payload.clearReaction = true; } - setReaction(payload as Record).catch((error) => - logWatchlistError("set remote reaction", error), - ); + mutation.mutate(payload); return; } setReactionLocal(id, mediaType, reaction, metadata); }, - [isSignedIn, setReaction, setReactionLocal], + [isSignedIn, mutation, setReactionLocal], ); } @@ -658,3 +764,25 @@ export function useWatchlistCount() { const { watchlist } = useWatchlist(); return watchlist.length; } + +function getTrackableTvSeasons(details?: { + seasons?: Array<{ season_number: number; episode_count: number }> | null; +}) { + return ( + details?.seasons?.filter( + (season) => season.season_number >= 0 && season.episode_count > 0, + ) ?? [] + ); +} + +function buildSeasonEpisodeSelections(details?: { + seasons?: Array<{ season_number: number; episode_count: number }> | null; +}) { + return getTrackableTvSeasons(details).map((season) => ({ + season: season.season_number, + episodes: Array.from( + { length: season.episode_count }, + (_, index) => index + 1, + ), + })); +} diff --git a/src/hooks/watchlist-store.ts b/src/hooks/watchlist-store.ts index 6b98fa31..3cffcf9a 100644 --- a/src/hooks/watchlist-store.ts +++ b/src/hooks/watchlist-store.ts @@ -100,21 +100,21 @@ function buildFallbackItem( }; } -export function mapConvexItemToWatchlistItem(item: { +export function mapWatchlistRowToItem(item: { tmdbId: number; mediaType: string; - title?: string; - image?: string; - rating?: number; - release_date?: string; - overview?: string; + title?: string | null; + image?: string | null; + rating?: number | null; + releaseDate?: string | null; + overview?: string | null; updatedAt: number; - progress?: number; - inWatchlist?: boolean; - progressStatus?: string; + progress?: number | null; + inWatchlist?: boolean | null; + progressStatus?: string | null; reaction?: string | null; }): WatchlistItem { - const normStatus = normalizeProgressStatus(item.progressStatus); + const normStatus = normalizeProgressStatus(item.progressStatus ?? undefined); return { title: item.title ?? "Unknown Title", @@ -122,8 +122,8 @@ export function mapConvexItemToWatchlistItem(item: { external_id: String(item.tmdbId), image: item.image ?? "", rating: item.rating ?? 0, - release_date: item.release_date ?? "", - overview: item.overview, + release_date: item.releaseDate ?? "", + overview: item.overview ?? undefined, updated_at: item.updatedAt, created_at: item.updatedAt, inWatchlist: Boolean(item.inWatchlist), diff --git a/src/lib/query/keys.ts b/src/lib/query/keys.ts new file mode 100644 index 00000000..fc79e920 --- /dev/null +++ b/src/lib/query/keys.ts @@ -0,0 +1,32 @@ +import type { MediaType } from "@/types"; + +/** + * Centralized TanStack Query key factory. Every query key is namespaced so + * `invalidateQueries` / `setQueryData` target exactly the right caches, and + * mutations can optimistically patch related queries (watchlist list + + * media-state, lists + list items, etc.). + */ +export const queryKeys = { + watchlist: { + // Full watchlist (signed-in users) — optional status filter for + // "continue watching". + list: (args?: { statusFilter?: string; limit?: number }) => + ["watchlist", "list", args ?? {}] as const, + trackedTmdbIds: () => ["watchlist", "tracked-ids"] as const, + mediaState: (tmdbId: number, mediaType: MediaType) => + ["watchlist", "media-state", tmdbId, mediaType] as const, + episodes: (tmdbId: number) => ["watchlist", "episodes", tmdbId] as const, + allEpisodes: () => ["watchlist", "all-episodes"] as const, + }, + lists: { + all: () => ["lists", "all"] as const, + items: (listId: string) => ["lists", "items", listId] as const, + itemLists: (tmdbId: number, mediaType: MediaType) => + ["lists", "item-lists", tmdbId, mediaType] as const, + }, + permissions: () => ["permissions"] as const, + recommendations: { + history: () => ["recommendations", "history"] as const, + homepage: () => ["recommendations", "homepage"] as const, + }, +} as const; diff --git a/src/lib/server-types.ts b/src/lib/server-types.ts new file mode 100644 index 00000000..c88b530a --- /dev/null +++ b/src/lib/server-types.ts @@ -0,0 +1,36 @@ +import type { + aiRecommendations, + episodeProgress, + listItems, + lists, + watchItems, +} from "@/server/db/schema"; + +/** `watch_items` D1 row (same shape `getWatchlist`/`getMediaState` return). */ +export type WatchItemRow = typeof watchItems.$inferSelect; + +/** `episode_progress` D1 row. */ +export type EpisodeProgressRow = typeof episodeProgress.$inferSelect; + +/** Enriched `lists` row (includes previews + itemCount). */ +export type CustomListRow = typeof lists.$inferSelect & { + previews: string[]; + itemCount: number; +}; + +/** Enriched `list_items` row. */ +export type ListItemRow = typeof listItems.$inferSelect & { + title: string | null; + image: string | null; + rating: number | null; + release_date: string | null; + overview: string | null; + progressStatus: string | null; + reaction: string | null; +}; + +export type AllEpisodeProgressRow = typeof episodeProgress.$inferSelect; + +export type RecommendationHistoryRow = typeof aiRecommendations.$inferSelect; + +export type MediaStateRow = typeof watchItems.$inferSelect; diff --git a/src/routeTree.gen.ts b/src/routeTree.gen.ts index 5117d69c..f015442b 100644 --- a/src/routeTree.gen.ts +++ b/src/routeTree.gen.ts @@ -454,10 +454,11 @@ export const routeTree = rootRouteImport ._addFileTypes() import type { getRouter } from './router.tsx' -import type { createStart } from '@tanstack/react-start' +import type { startInstance } from './start.ts' declare module '@tanstack/react-start' { interface Register { ssr: true router: Awaited> + config: Awaited> } } diff --git a/src/router.tsx b/src/router.tsx index 8f447167..99655acf 100644 --- a/src/router.tsx +++ b/src/router.tsx @@ -1,9 +1,7 @@ -import { ClerkProvider, useAuth } from "@clerk/react"; +import { ClerkProvider } from "@clerk/react"; import { shadcn } from "@clerk/ui/themes"; import { createRouter } from "@tanstack/react-router"; import { setupRouterSsrQueryIntegration } from "@tanstack/react-router-ssr-query"; -import { ConvexReactClient } from "convex/react"; -import { ConvexProviderWithClerk } from "convex/react-clerk"; import { DefaultLoader } from "@/components/default-loader"; import { DefaultErrorComponent, @@ -14,8 +12,6 @@ import { Provider as QueryProvider } from "@/lib/query/root-provider"; import { routeTree } from "@/routeTree.gen"; -const convex = new ConvexReactClient(import.meta.env.VITE_CONVEX_URL as string); - export const getRouter = () => { const rqContext = getContext(); @@ -33,9 +29,7 @@ export const getRouter = () => { theme: shadcn, }} > - - {props.children} - + {props.children} ); }, diff --git a/src/routes/__root.tsx b/src/routes/__root.tsx index e84c15d9..5e54f49e 100644 --- a/src/routes/__root.tsx +++ b/src/routes/__root.tsx @@ -181,11 +181,21 @@ function RootDocument({ children }: { children: React.ReactNode }) { } if (import.meta.env.DEV) { + // Unregister any SW left over from a production build/preview and purge + // its caches, so stale client JS (with old serverFn IDs) can't be served + // against the dev server. navigator.serviceWorker.getRegistrations().then((registrations) => { for (const registration of registrations) { registration.unregister(); } }); + if (typeof caches !== "undefined") { + caches.keys().then((keys) => { + for (const key of keys) { + caches.delete(key); + } + }); + } return; } diff --git a/src/routes/recommendations.lazy.tsx b/src/routes/recommendations.lazy.tsx index ccfa548c..9b9cf441 100644 --- a/src/routes/recommendations.lazy.tsx +++ b/src/routes/recommendations.lazy.tsx @@ -1,5 +1,5 @@ +import { useQuery } from "@tanstack/react-query"; import { createLazyFileRoute, useNavigate } from "@tanstack/react-router"; -import { useQuery as useConvexQuery } from "convex/react"; import { ArrowUpRight, BrainCircuit, @@ -41,6 +41,7 @@ import type { } from "@/hooks/use-recommendations"; import { useRecommendations } from "@/hooks/use-recommendations"; import { useWatchlist } from "@/hooks/use-watchlist"; +import { queryKeys } from "@/lib/query/keys"; import { type AIRecommendation, normalizeTitleKey, @@ -49,7 +50,9 @@ import { useTmdbSearchFallback, } from "@/lib/recommendation-engine"; import { cn } from "@/lib/utils"; -import { api } from "../../convex/_generated/api"; +import { getCustomLists } from "@/server/fns/lists"; +import { getTrackedTmdbIds } from "@/server/fns/watchlist"; +import { unwrap } from "@/server/schema/common"; export const Route = createLazyFileRoute("/recommendations")({ component: RecommendationsPage, @@ -157,13 +160,14 @@ function RecommendationsContent({ const { watchlist, loading: watchlistLoading } = useWatchlist(); - const trackedTmdbIds = useConvexQuery( - api.watchlist.getTrackedTmdbIds, - isSignedIn ? {} : "skip", - ); + const trackedTmdbIdsQuery = useQuery({ + queryKey: queryKeys.watchlist.trackedTmdbIds(), + queryFn: () => unwrap(getTrackedTmdbIds()), + enabled: !!isSignedIn, + }); const trackedIdSet = useMemo>( - () => new Set((trackedTmdbIds ?? []) as number[]), - [trackedTmdbIds], + () => new Set((trackedTmdbIdsQuery.data ?? []) as number[]), + [trackedTmdbIdsQuery.data], ); const trackedTitleSet = useMemo( () => @@ -206,7 +210,7 @@ function RecommendationsContent({ useEffect(() => { if (!activeId && filteredHistory.length > 0) { - setActiveId(filteredHistory[0]._id); + setActiveId(filteredHistory[0].id); } }, [activeId, filteredHistory, setActiveId]); @@ -232,11 +236,12 @@ function RecommendationsContent({ ); }; - const customListsResult = useConvexQuery( - api.watchlist.getCustomLists, - isSignedIn ? {} : "skip", - ); - const customLists = customListsResult ?? []; + const customListsQuery = useQuery({ + queryKey: queryKeys.lists.all(), + queryFn: () => unwrap(getCustomLists()), + enabled: !!isSignedIn, + }); + const customLists = customListsQuery.data ?? []; const handleGenerate = () => { if (genMode === "watchlist" && watchlist.length === 0) return; @@ -309,7 +314,7 @@ function RecommendationsContent({ }; const activeEntry = - (activeId ? filteredHistory.find((h) => h._id === activeId) : null) ?? + (activeId ? filteredHistory.find((h) => h.id === activeId) : null) ?? filteredHistory[0] ?? null; @@ -356,8 +361,8 @@ function RecommendationsContent({ {customLists.map((list) => ( From List: {list.name} @@ -612,11 +617,11 @@ function RecommendationsContent({ {filteredHistory.map((entry) => ( setActiveId(entry._id)} - onDelete={() => handleDelete(entry._id)} + isActive={entry.id === activeEntry?.id} + onSelect={() => setActiveId(entry.id)} + onDelete={() => handleDelete(entry.id)} onGenerateAgain={() => handleGenerateAgain(entry)} onGenerateMore={() => handleGenerateMore(entry)} isGenerating={isGenerating} @@ -661,7 +666,7 @@ function HistoryAccordionItem({ return ( { diff --git a/src/server/auth.ts b/src/server/auth.ts index 53e8ce98..23ee6d19 100644 --- a/src/server/auth.ts +++ b/src/server/auth.ts @@ -1,4 +1,4 @@ -import { verifyToken } from "@clerk/backend"; +import { createClerkClient, verifyToken } from "@clerk/backend"; import { getCookie, getRequestHeader } from "@tanstack/react-start/server"; import { and, eq } from "drizzle-orm"; import { getDb } from "./db/client"; @@ -47,7 +47,11 @@ export async function getSessionClaims(): Promise { if (!secretKey) return null; try { - const claims = await verifyToken(token, { secretKey }); + const claims = await verifyToken(token, { + secretKey, + // Tolerate clock drift / refresh races (Clerk dev JWTs are short-lived). + clockSkewInMs: 300_000, + }); return claims as ClerkSessionClaims; } catch (error) { console.error("Clerk token verification failed:", error); @@ -74,6 +78,51 @@ export function getAdminFromClaims( return null; } +let clerkApiClient: ReturnType | null = null; + +function getClerkApiClient() { + const secretKey = getEnvVar("CLERK_SECRET_KEY"); + if (!secretKey) return null; + if (!clerkApiClient) { + clerkApiClient = createClerkClient({ secretKey }); + } + return clerkApiClient; +} + +const ADMIN_API_CACHE_TTL_MS = 60_000; +const adminApiCache = new Map(); + +/** + * Resolve `isAdmin` from Clerk's public metadata via the backend API. + * + * The Clerk JWT does not carry public metadata unless a custom JWT template / + * session claim adds it, while the client SDK (`useUser`) reads it straight + * from the user resource. This keeps the server in agreement with the client: + * Clerk's public metadata is the source of truth for admin status. Results are + * cached briefly (60s) to avoid an API call on every request. + */ +export async function isAdminFromClerkApi(sub: string): Promise { + const cached = adminApiCache.get(sub); + if (cached && cached.expiresAt > Date.now()) return cached.value; + + const client = getClerkApiClient(); + let isAdmin = false; + if (client) { + try { + const clerkUser = await client.users.getUser(sub); + isAdmin = clerkUser.publicMetadata?.isAdmin === true; + } catch (error) { + console.error("Failed to fetch Clerk user for admin check:", error); + } + } + + adminApiCache.set(sub, { + value: isAdmin, + expiresAt: Date.now() + ADMIN_API_CACHE_TTL_MS, + }); + return isAdmin; +} + /** * Port of `convex/helpers/watch_item.ts` `getCurrentUser` — multi-format * tokenIdentifier matching so users created under any prior format resolve. @@ -145,7 +194,8 @@ export async function requireUser(): Promise { const db = getDb(getEnv()); let user = await findUserByClaims(claims); if (!user) { - const isAdmin = getAdminFromClaims(claims); + const isAdmin = + getAdminFromClaims(claims) ?? (await isAdminFromClerkApi(claims.sub)); const id = crypto.randomUUID(); await db.insert(users).values({ id, diff --git a/src/server/db/client.ts b/src/server/db/client.ts index 2061aaaf..121aa603 100644 --- a/src/server/db/client.ts +++ b/src/server/db/client.ts @@ -12,6 +12,14 @@ import * as schema from "./schema"; * is disabled so hot reads are cached explicitly. */ export function getDb(env: Env) { + if (!env.DB) { + throw new Error( + "D1 binding 'DB' is missing. Full-stack dev needs `pnpm dev:cf` " + + "(wrangler dev, provides D1 + .dev.vars secrets). `pnpm dev:web` is " + + "UI-only — database-backed server functions will fail there.", + ); + } + const url = env.UPSTASH_REDIS_REST_URL; const token = env.UPSTASH_REDIS_REST_TOKEN; diff --git a/src/server/fns/admin.ts b/src/server/fns/admin.ts index c99e2c18..6f2f46d1 100644 --- a/src/server/fns/admin.ts +++ b/src/server/fns/admin.ts @@ -1,6 +1,6 @@ import { createServerFn } from "@tanstack/react-start"; import { and, eq } from "drizzle-orm"; -import { type AuthUser, requireUser } from "../auth"; +import { type AuthUser, isAdminFromClerkApi, requireUser } from "../auth"; import { getDb } from "../db/client"; import { rolePermissions, users } from "../db/schema"; import { getEnv } from "../env"; @@ -25,7 +25,10 @@ async function requireAdmin(): Promise< if (result.error) return { user: null, error: result.error }; const { user, claims } = result; - if (!isClerkAdmin(claims as unknown as Record, user)) { + if ( + !isClerkAdmin(claims as unknown as Record, user) && + !(await isAdminFromClerkApi(claims.sub)) + ) { return { user: null, error: fail("FORBIDDEN", "Forbidden: admin access required"), @@ -202,8 +205,19 @@ export const listUsers = createServerFn({ method: "POST" }) .from(users) .limit(data.limit ?? 200); - return ok( - rows.map((u) => ({ + const results: Array<{ + _id: string; + tokenIdentifier: string; + name: string; + email: string; + image: string | null; + roles: string[]; + isBanned: boolean; + isAdmin: boolean; + }> = []; + for (const u of rows) { + const sub = u.tokenIdentifier.replace(/^clerk\|/, ""); + results.push({ _id: u.id, tokenIdentifier: u.tokenIdentifier, name: u.name ?? "Anonymous", @@ -213,8 +227,12 @@ export const listUsers = createServerFn({ method: "POST" }) DYNAMIC_ROLES.includes(role as (typeof DYNAMIC_ROLES)[number]), ), isBanned: u.isBanned ?? false, - isAdmin: isClerkAdmin(null, { isAdmin: u.isAdmin ?? false }), - })), - ); + isAdmin: + isClerkAdmin(null, { isAdmin: u.isAdmin ?? false }) || + (await isAdminFromClerkApi(sub)), + }); + } + + return ok(results); }, ); diff --git a/src/server/fns/recommendations.ts b/src/server/fns/recommendations.ts index 28d64d7f..8d8ebb20 100644 --- a/src/server/fns/recommendations.ts +++ b/src/server/fns/recommendations.ts @@ -383,6 +383,13 @@ export const getHomepageRecommendations = createServerFn({ method: "POST" }) }); } + // Only request a refresh when the user actually has the feature. + // Otherwise the client would keep firing generateHomepageRecommendations + // (which the server rejects with FORBIDDEN) on every refetch — a loop. + const { claims, user: dbUser, error: authError } = await requireUser(); + const featureEnabled = + !authError && (await hasFeature(claims, dbUser, "ai-recommendations")); + const db = getDb(getEnv()); const entry = await db .select() @@ -444,7 +451,8 @@ export const getHomepageRecommendations = createServerFn({ method: "POST" }) status === "failed" && currentTime > 0 && currentTime - lastAttemptedAt < 1 * 60 * 60 * 1000; - const needsRefresh = !row || (isOlderThan24Hours && !hasFailedRecently); + const needsRefresh = + featureEnabled && (!row || (isOlderThan24Hours && !hasFailedRecently)); return ok({ recommendations: recs, diff --git a/src/server/fns/watchlist.ts b/src/server/fns/watchlist.ts index 8c167c51..634edc49 100644 --- a/src/server/fns/watchlist.ts +++ b/src/server/fns/watchlist.ts @@ -41,7 +41,7 @@ export const getWatchlist = createServerFn({ method: "POST" }) const requestedLimit = data.limit !== undefined && data.limit > 0 ? Math.floor(data.limit) - : 200; + : 500; const boundedLimit = Math.min(requestedLimit, 500); const filters = [eq(watchItems.userId, user.id)]; diff --git a/src/server/rbac.ts b/src/server/rbac.ts index 79346597..18c64289 100644 --- a/src/server/rbac.ts +++ b/src/server/rbac.ts @@ -1,5 +1,9 @@ import { and, eq } from "drizzle-orm"; -import type { AuthUser, ClerkSessionClaims } from "./auth"; +import { + type AuthUser, + type ClerkSessionClaims, + isAdminFromClerkApi, +} from "./auth"; import type { Db } from "./db/client"; import { getDb } from "./db/client"; import { rolePermissions } from "./db/schema"; @@ -128,6 +132,12 @@ export async function hasFeature( if (isClerkAdmin(claims as unknown as Record, user)) { return true; } + // The JWT doesn't carry public metadata (no custom session claim), so fall + // back to Clerk's API — the same source the client `useUser()` reads. This + // keeps the server in agreement with the client's admin/AI feature UI. + if (await isAdminFromClerkApi(claims.sub)) { + return true; + } if (!user) return false; const db = getDb(getEnv()); diff --git a/src/server/schema/common.ts b/src/server/schema/common.ts index 65125327..028096d7 100644 --- a/src/server/schema/common.ts +++ b/src/server/schema/common.ts @@ -68,10 +68,14 @@ export class ApiError extends Error { } /** - * Unwrap a typed result on the client. Throws an `ApiError` on non-ok so + * Unwrap a typed result on the client. Accepts the result directly or the + * promise returned by a server fn, and throws an `ApiError` on non-ok so * TanStack Query's error path (and optimistic rollback) fires. */ -export function unwrap(result: ApiResult): T { - if (result.ok) return result.data; - throw new ApiError(result.code, result.message); +export async function unwrap( + result: ApiResult | Promise>, +): Promise { + const resolved = await result; + if (resolved.ok) return resolved.data; + throw new ApiError(resolved.code, resolved.message); } diff --git a/src/start.ts b/src/start.ts new file mode 100644 index 00000000..54005424 --- /dev/null +++ b/src/start.ts @@ -0,0 +1,31 @@ +import { getToken } from "@clerk/react"; +import { createStart } from "@tanstack/react-start"; + +/** + * Client-side start instance. + * + * `serverFns.fetch` wraps every server-function RPC with a fresh Clerk session + * token (`Authorization: Bearer`). The Clerk SDK mints/rotates short-lived JWTs + * automatically, so the server never sees an expired token — this fixes the + * "JWT is expired" failures in long-lived dev sessions. The server's + * `getSessionToken()` already prefers the Authorization header over cookies. + * + * Note: this only applies on the client. During SSR, server functions are + * called directly in-process. + */ +export const startInstance = createStart(() => ({ + serverFns: { + fetch: async (url, args = {}) => { + const headers = new Headers(args.headers); + try { + const token = await getToken(); + if (token) { + headers.set("Authorization", `Bearer ${token}`); + } + } catch { + // Not signed in / Clerk not loaded — fall through to the cookie. + } + return fetch(url, { ...args, headers }); + }, + }, +})); From 8fe646ffc768df8f4848fc622342faa82e38b6d6 Mon Sep 17 00:00:00 2001 From: Swastik Dan <57379785+Swastikdan@users.noreply.github.com> Date: Sun, 16 Aug 2026 01:18:21 +0530 Subject: [PATCH 03/27] refactor(schema): replace Zod with Valibot across all server schemas and functions --- package.json | 1 - src/server/fns/users.ts | 12 +-- src/server/fns/watchlist.ts | 4 +- src/server/schema/admin.ts | 36 ++++---- src/server/schema/common.ts | 36 ++++---- src/server/schema/import.ts | 44 ++++----- src/server/schema/lists.ts | 85 +++++++++--------- src/server/schema/recommendations.ts | 111 +++++++++++------------ src/server/schema/watchlist.ts | 129 ++++++++++++++------------- 9 files changed, 232 insertions(+), 226 deletions(-) diff --git a/package.json b/package.json index 3ec1cf22..68c4411d 100644 --- a/package.json +++ b/package.json @@ -69,7 +69,6 @@ "tailwindcss": "^4.3.3", "valibot": "^1.4.2", "vite-tsconfig-paths": "^5.1.4", - "zod": "^4.4.3", "zustand": "^5.0.14" }, "devDependencies": { diff --git a/src/server/fns/users.ts b/src/server/fns/users.ts index b621729f..fdc95ea5 100644 --- a/src/server/fns/users.ts +++ b/src/server/fns/users.ts @@ -1,6 +1,6 @@ import { createServerFn } from "@tanstack/react-start"; import { eq } from "drizzle-orm"; -import { z } from "zod"; +import * as v from "valibot"; import { getAdminFromClaims, getCurrentUser, requireUser } from "../auth"; import { getDb } from "../db/client"; import { users } from "../db/schema"; @@ -8,11 +8,11 @@ import { getEnv } from "../env"; import { syncRolePermissions } from "../rbac"; import { type ApiResult, ok } from "../schema/common"; -const storeUserArgsSchema = z.object({ - email: z.string().optional(), - name: z.string().optional(), - image: z.string().optional(), - isAdmin: z.boolean().optional(), +const storeUserArgsSchema = v.object({ + email: v.optional(v.string()), + name: v.optional(v.string()), + image: v.optional(v.string()), + isAdmin: v.optional(v.boolean()), }); /** diff --git a/src/server/fns/watchlist.ts b/src/server/fns/watchlist.ts index 634edc49..dcb2a260 100644 --- a/src/server/fns/watchlist.ts +++ b/src/server/fns/watchlist.ts @@ -1,6 +1,6 @@ import { createServerFn } from "@tanstack/react-start"; import { and, desc, eq } from "drizzle-orm"; -import { z } from "zod"; +import * as v from "valibot"; import { getCurrentUser, requireUser } from "../auth"; import { getDb } from "../db/client"; import { episodeProgress, watchItems } from "../db/schema"; @@ -488,7 +488,7 @@ export const markShowEpisodesAndStatus = createServerFn({ method: "POST" }) export const getAllWatchedEpisodes = createServerFn({ method: "POST" }) .validator( // matches the Convex `getAllWatchedEpisodes({ tmdbId })` signature - z.object({ tmdbId: z.number() }), + v.object({ tmdbId: v.number() }), ) .handler( async ({ diff --git a/src/server/schema/admin.ts b/src/server/schema/admin.ts index 2e159d00..9c8e213f 100644 --- a/src/server/schema/admin.ts +++ b/src/server/schema/admin.ts @@ -1,25 +1,27 @@ -import { z } from "zod"; +import * as v from "valibot"; -export const setRolePermissionArgsSchema = z.object({ - role: z.string(), - feature: z.string(), - enabled: z.boolean(), +export const setRolePermissionArgsSchema = v.object({ + role: v.string(), + feature: v.string(), + enabled: v.boolean(), }); -export type SetRolePermissionArgs = z.infer; +export type SetRolePermissionArgs = v.InferOutput< + typeof setRolePermissionArgsSchema +>; -export const setUserRolesArgsSchema = z.object({ - tokenIdentifier: z.string(), - roles: z.array(z.enum(["video-player", "ai-integrations"])), +export const setUserRolesArgsSchema = v.object({ + tokenIdentifier: v.string(), + roles: v.array(v.picklist(["video-player", "ai-integrations"])), }); -export type SetUserRolesArgs = z.infer; +export type SetUserRolesArgs = v.InferOutput; -export const setUserBannedArgsSchema = z.object({ - tokenIdentifier: z.string(), - banned: z.boolean(), +export const setUserBannedArgsSchema = v.object({ + tokenIdentifier: v.string(), + banned: v.boolean(), }); -export type SetUserBannedArgs = z.infer; +export type SetUserBannedArgs = v.InferOutput; -export const listUsersArgsSchema = z.object({ - limit: z.number().optional(), +export const listUsersArgsSchema = v.object({ + limit: v.optional(v.number()), }); -export type ListUsersArgs = z.infer; +export type ListUsersArgs = v.InferOutput; diff --git a/src/server/schema/common.ts b/src/server/schema/common.ts index 028096d7..2549686a 100644 --- a/src/server/schema/common.ts +++ b/src/server/schema/common.ts @@ -1,42 +1,42 @@ -import { z } from "zod"; +import * as v from "valibot"; -export const mediaTypeSchema = z.enum(["movie", "tv"]); -export type MediaType = z.infer; +export const mediaTypeSchema = v.picklist(["movie", "tv"]); +export type MediaType = v.InferOutput; -export const progressStatusSchema = z.enum([ +export const progressStatusSchema = v.picklist([ "watch-later", "watching", "done", "dropped", ]); -export type ProgressStatus = z.infer; +export type ProgressStatus = v.InferOutput; -export const reactionSchema = z.enum([ +export const reactionSchema = v.picklist([ "loved", "liked", "mixed", "not-for-me", "recommended", ]); -export type Reaction = z.infer; +export type Reaction = v.InferOutput; -export const feedbackSchema = z.enum(["like", "not_interested", "dislike"]); -export type Feedback = z.infer; +export const feedbackSchema = v.picklist(["like", "not_interested", "dislike"]); +export type Feedback = v.InferOutput; -export const metadataSchema = z.object({ - title: z.string().optional(), - image: z.string().optional(), - rating: z.number().optional(), - release_date: z.string().optional(), - overview: z.string().optional(), +export const metadataSchema = v.object({ + title: v.optional(v.string()), + image: v.optional(v.string()), + rating: v.optional(v.number()), + release_date: v.optional(v.string()), + overview: v.optional(v.string()), }); -export type MediaMetadata = z.infer; +export type MediaMetadata = v.InferOutput; // --------------------------------------------------------------------------- // Typed error contract (replaces Convex's bare `throw new Error`) // --------------------------------------------------------------------------- -export const errorCodeSchema = z.enum([ +export const errorCodeSchema = v.picklist([ "UNAUTHORIZED", "FORBIDDEN", "NOT_FOUND", @@ -44,7 +44,7 @@ export const errorCodeSchema = z.enum([ "CONFLICT", "BAD_REQUEST", ]); -export type ErrorCode = z.infer; +export type ErrorCode = v.InferOutput; export type ApiResult = | { ok: true; data: T } diff --git a/src/server/schema/import.ts b/src/server/schema/import.ts index 1e7a91a7..690bba3a 100644 --- a/src/server/schema/import.ts +++ b/src/server/schema/import.ts @@ -1,33 +1,35 @@ -import { z } from "zod"; +import * as v from "valibot"; import { mediaTypeSchema, progressStatusSchema, reactionSchema, } from "./common"; -export const importItemSchema = z.object({ - tmdbId: z.number(), +export const importItemSchema = v.object({ + tmdbId: v.number(), mediaType: mediaTypeSchema, - title: z.string(), - image: z.string().optional(), - rating: z.number().optional(), - release_date: z.string().optional(), - overview: z.string().optional(), - progressStatus: progressStatusSchema.optional(), - progress: z.number().optional(), - reaction: reactionSchema.nullable().optional(), + title: v.string(), + image: v.optional(v.string()), + rating: v.optional(v.number()), + release_date: v.optional(v.string()), + overview: v.optional(v.string()), + progressStatus: v.optional(progressStatusSchema), + progress: v.optional(v.number()), + reaction: v.optional(v.nullable(reactionSchema)), }); -export type ImportItem = z.infer; +export type ImportItem = v.InferOutput; -export const watchedEpisodeSchema = z.object({ - tmdbId: z.number(), - season: z.number(), - episode: z.number(), +export const watchedEpisodeSchema = v.object({ + tmdbId: v.number(), + season: v.number(), + episode: v.number(), }); -export type WatchedEpisode = z.infer; +export type WatchedEpisode = v.InferOutput; -export const importWatchlistArgsSchema = z.object({ - items: z.array(importItemSchema), - watchedEpisodes: z.array(watchedEpisodeSchema), +export const importWatchlistArgsSchema = v.object({ + items: v.array(importItemSchema), + watchedEpisodes: v.array(watchedEpisodeSchema), }); -export type ImportWatchlistArgs = z.infer; +export type ImportWatchlistArgs = v.InferOutput< + typeof importWatchlistArgsSchema +>; diff --git a/src/server/schema/lists.ts b/src/server/schema/lists.ts index ccbf3b1c..43e7d017 100644 --- a/src/server/schema/lists.ts +++ b/src/server/schema/lists.ts @@ -1,56 +1,61 @@ -import { z } from "zod"; +import * as v from "valibot"; import { mediaTypeSchema, metadataSchema } from "./common"; -export const createCustomListArgsSchema = z.object({ - name: z.string(), - color: z.string().optional(), - visibility: z.string().optional(), - listType: z.string().optional(), +export const createCustomListArgsSchema = v.object({ + name: v.string(), + color: v.optional(v.string()), + visibility: v.optional(v.string()), + listType: v.optional(v.string()), }); -export type CreateCustomListArgs = z.infer; +export type CreateCustomListArgs = v.InferOutput< + typeof createCustomListArgsSchema +>; -export const updateCustomListArgsSchema = z.object({ - listId: z.string(), - name: z.string().optional(), - color: z.string().optional(), - visibility: z.string().optional(), - listType: z.string().optional(), +export const updateCustomListArgsSchema = v.object({ + listId: v.string(), + name: v.optional(v.string()), + color: v.optional(v.string()), + visibility: v.optional(v.string()), + listType: v.optional(v.string()), }); -export type UpdateCustomListArgs = z.infer; +export type UpdateCustomListArgs = v.InferOutput< + typeof updateCustomListArgsSchema +>; -export const deleteCustomListArgsSchema = z.object({ - listId: z.string(), +export const deleteCustomListArgsSchema = v.object({ + listId: v.string(), }); -export type DeleteCustomListArgs = z.infer; +export type DeleteCustomListArgs = v.InferOutput< + typeof deleteCustomListArgsSchema +>; -export const getListItemsArgsSchema = z.object({ - listId: z.string(), +export const getListItemsArgsSchema = v.object({ + listId: v.string(), }); -export type GetListItemsArgs = z.infer; +export type GetListItemsArgs = v.InferOutput; -export const getItemListsArgsSchema = z.object({ - tmdbId: z.number(), +export const getItemListsArgsSchema = v.object({ + tmdbId: v.number(), mediaType: mediaTypeSchema, }); -export type GetItemListsArgs = z.infer; +export type GetItemListsArgs = v.InferOutput; -export const toggleListItemArgsSchema = z - .object({ - listId: z.string(), - tmdbId: z.number(), - mediaType: mediaTypeSchema, - backdrop: z.string().optional(), - }) - .merge(metadataSchema); -export type ToggleListItemArgs = z.infer; +export const toggleListItemArgsSchema = v.object({ + ...metadataSchema.entries, + listId: v.string(), + tmdbId: v.number(), + mediaType: mediaTypeSchema, + backdrop: v.optional(v.string()), +}); +export type ToggleListItemArgs = v.InferOutput; -export const createCustomListAndAddItemArgsSchema = createCustomListArgsSchema - .extend({ - tmdbId: z.number(), - mediaType: mediaTypeSchema, - backdrop: z.string().optional(), - }) - .merge(metadataSchema); -export type CreateCustomListAndAddItemArgs = z.infer< +export const createCustomListAndAddItemArgsSchema = v.object({ + ...createCustomListArgsSchema.entries, + ...metadataSchema.entries, + tmdbId: v.number(), + mediaType: mediaTypeSchema, + backdrop: v.optional(v.string()), +}); +export type CreateCustomListAndAddItemArgs = v.InferOutput< typeof createCustomListAndAddItemArgsSchema >; diff --git a/src/server/schema/recommendations.ts b/src/server/schema/recommendations.ts index a3f5693c..64c6c5b1 100644 --- a/src/server/schema/recommendations.ts +++ b/src/server/schema/recommendations.ts @@ -1,34 +1,34 @@ -import { z } from "zod"; +import * as v from "valibot"; import { mediaTypeSchema } from "./common"; -export const recommendationSchema = z.object({ - title: z.string(), - tmdbId: z.number().nullable(), +export const recommendationSchema = v.object({ + title: v.string(), + tmdbId: v.nullable(v.number()), mediaType: mediaTypeSchema, - relevanceScore: z.number(), - reasoning: z.string(), + relevanceScore: v.number(), + reasoning: v.string(), }); -export type Recommendation = z.infer; +export type Recommendation = v.InferOutput; -export const inputStatsSchema = z.object({ - movieCount: z.number(), - tvCount: z.number(), - episodesWatched: z.number(), - totalItems: z.number(), +export const inputStatsSchema = v.object({ + movieCount: v.number(), + tvCount: v.number(), + episodesWatched: v.number(), + totalItems: v.number(), }); -export type InputStats = z.infer; +export type InputStats = v.InferOutput; -export const generateRecommendationsArgsSchema = z.object({ - generationType: z.string().optional(), - listId: z.string().optional(), - mediaTypePreference: mediaTypeSchema.optional(), - genrePreference: z.string().optional(), - excludeTmdbIds: z.array(z.number()).optional(), - yearFrom: z.number().optional(), - yearTo: z.number().optional(), - count: z.number().optional(), +export const generateRecommendationsArgsSchema = v.object({ + generationType: v.optional(v.string()), + listId: v.optional(v.string()), + mediaTypePreference: v.optional(mediaTypeSchema), + genrePreference: v.optional(v.string()), + excludeTmdbIds: v.optional(v.array(v.number())), + yearFrom: v.optional(v.number()), + yearTo: v.optional(v.number()), + count: v.optional(v.number()), }); -export type GenerateRecommendationsArgs = z.infer< +export type GenerateRecommendationsArgs = v.InferOutput< typeof generateRecommendationsArgsSchema >; @@ -41,48 +41,48 @@ export type GenerateResult = } | { error: string }; -export const deleteRecommendationArgsSchema = z.object({ - id: z.string(), +export const deleteRecommendationArgsSchema = v.object({ + id: v.string(), }); -export type DeleteRecommendationArgs = z.infer< +export type DeleteRecommendationArgs = v.InferOutput< typeof deleteRecommendationArgsSchema >; -export const updateVerifiedRecommendationsArgsSchema = z.object({ - id: z.string(), - recommendations: z.string(), +export const updateVerifiedRecommendationsArgsSchema = v.object({ + id: v.string(), + recommendations: v.string(), }); -export type UpdateVerifiedRecommendationsArgs = z.infer< +export type UpdateVerifiedRecommendationsArgs = v.InferOutput< typeof updateVerifiedRecommendationsArgsSchema >; -export const setRecommendationFeedbackArgsSchema = z.object({ - tmdbId: z.number(), +export const setRecommendationFeedbackArgsSchema = v.object({ + tmdbId: v.number(), mediaType: mediaTypeSchema, - title: z.string(), - feedback: z.enum(["not_interested", "like"]), - image: z.string().optional(), - backdrop: z.string().optional(), - rating: z.number().optional(), - release_date: z.string().optional(), - overview: z.string().optional(), + title: v.string(), + feedback: v.picklist(["not_interested", "like"]), + image: v.optional(v.string()), + backdrop: v.optional(v.string()), + rating: v.optional(v.number()), + release_date: v.optional(v.string()), + overview: v.optional(v.string()), }); -export type SetRecommendationFeedbackArgs = z.infer< +export type SetRecommendationFeedbackArgs = v.InferOutput< typeof setRecommendationFeedbackArgsSchema >; -export const removeRecommendationFeedbackArgsSchema = z.object({ - tmdbId: z.number(), +export const removeRecommendationFeedbackArgsSchema = v.object({ + tmdbId: v.number(), mediaType: mediaTypeSchema, }); -export type RemoveRecommendationFeedbackArgs = z.infer< +export type RemoveRecommendationFeedbackArgs = v.InferOutput< typeof removeRecommendationFeedbackArgsSchema >; -export const getHomepageRecommendationsArgsSchema = z.object({ - now: z.number().optional(), +export const getHomepageRecommendationsArgsSchema = v.object({ + now: v.optional(v.number()), }); -export type GetHomepageRecommendationsArgs = z.infer< +export type GetHomepageRecommendationsArgs = v.InferOutput< typeof getHomepageRecommendationsArgsSchema >; @@ -94,16 +94,13 @@ export type HomepageRecommendationsResult = { needsRefresh: boolean; }; -export const getUserRecommendationAccessResultSchema = z.discriminatedUnion( - "hasAccess", - [ - z.object({ hasAccess: z.literal(true) }), - z.object({ - hasAccess: z.literal(false), - reason: z.enum(["not_authenticated", "feature_disabled"]), - }), - ], -); -export type UserRecommendationAccessResult = z.infer< +export const getUserRecommendationAccessResultSchema = v.variant("hasAccess", [ + v.object({ hasAccess: v.literal(true) }), + v.object({ + hasAccess: v.literal(false), + reason: v.picklist(["not_authenticated", "feature_disabled"]), + }), +]); +export type UserRecommendationAccessResult = v.InferOutput< typeof getUserRecommendationAccessResultSchema >; diff --git a/src/server/schema/watchlist.ts b/src/server/schema/watchlist.ts index 502e5368..69d5ea7d 100644 --- a/src/server/schema/watchlist.ts +++ b/src/server/schema/watchlist.ts @@ -1,4 +1,4 @@ -import { z } from "zod"; +import * as v from "valibot"; import { mediaTypeSchema, metadataSchema, @@ -6,87 +6,88 @@ import { reactionSchema, } from "./common"; -export const getWatchlistArgsSchema = z.object({ - limit: z.number().optional(), - statusFilter: z.string().optional(), +export const getWatchlistArgsSchema = v.object({ + limit: v.optional(v.number()), + statusFilter: v.optional(v.string()), }); -export type GetWatchlistArgs = z.infer; +export type GetWatchlistArgs = v.InferOutput; -export const mediaIdentityArgsSchema = z.object({ - tmdbId: z.number(), +export const mediaIdentityArgsSchema = v.object({ + tmdbId: v.number(), mediaType: mediaTypeSchema, }); -export type MediaIdentityArgs = z.infer; +export type MediaIdentityArgs = v.InferOutput; -export const setWatchlistMembershipArgsSchema = mediaIdentityArgsSchema - .extend({ - inWatchlist: z.boolean(), - }) - .merge(metadataSchema); -export type SetWatchlistMembershipArgs = z.infer< +export const setWatchlistMembershipArgsSchema = v.object({ + ...mediaIdentityArgsSchema.entries, + ...metadataSchema.entries, + inWatchlist: v.boolean(), +}); +export type SetWatchlistMembershipArgs = v.InferOutput< typeof setWatchlistMembershipArgsSchema >; -export const setProgressStatusArgsSchema = mediaIdentityArgsSchema - .extend({ - progressStatus: progressStatusSchema, - progress: z.number().optional(), - }) - .merge(metadataSchema); -export type SetProgressStatusArgs = z.infer; +export const setProgressStatusArgsSchema = v.object({ + ...mediaIdentityArgsSchema.entries, + ...metadataSchema.entries, + progressStatus: progressStatusSchema, + progress: v.optional(v.number()), +}); +export type SetProgressStatusArgs = v.InferOutput< + typeof setProgressStatusArgsSchema +>; -export const setReactionArgsSchema = mediaIdentityArgsSchema - .extend({ - reaction: reactionSchema.optional(), - clearReaction: z.boolean().optional(), - }) - .merge(metadataSchema); -export type SetReactionArgs = z.infer; +export const setReactionArgsSchema = v.object({ + ...mediaIdentityArgsSchema.entries, + ...metadataSchema.entries, + reaction: v.optional(reactionSchema), + clearReaction: v.optional(v.boolean()), +}); +export type SetReactionArgs = v.InferOutput; -export const updateProgressArgsSchema = mediaIdentityArgsSchema - .extend({ - progress: z.number().optional(), - isWatched: z.boolean().optional(), - }) - .merge(metadataSchema); -export type UpdateProgressArgs = z.infer; +export const updateProgressArgsSchema = v.object({ + ...mediaIdentityArgsSchema.entries, + ...metadataSchema.entries, + progress: v.optional(v.number()), + isWatched: v.optional(v.boolean()), +}); +export type UpdateProgressArgs = v.InferOutput; -export const markEpisodeWatchedArgsSchema = z.object({ - tmdbId: z.number(), - season: z.number(), - episode: z.number(), - isWatched: z.boolean(), +export const markEpisodeWatchedArgsSchema = v.object({ + tmdbId: v.number(), + season: v.number(), + episode: v.number(), + isWatched: v.boolean(), }); -export type MarkEpisodeWatchedArgs = z.infer< +export type MarkEpisodeWatchedArgs = v.InferOutput< typeof markEpisodeWatchedArgsSchema >; -export const markSeasonEpisodesWatchedArgsSchema = z.object({ - tmdbId: z.number(), - season: z.number(), - episodes: z.array(z.number()), - isWatched: z.boolean(), +export const markSeasonEpisodesWatchedArgsSchema = v.object({ + tmdbId: v.number(), + season: v.number(), + episodes: v.array(v.number()), + isWatched: v.boolean(), }); -export type MarkSeasonEpisodesWatchedArgs = z.infer< +export type MarkSeasonEpisodesWatchedArgs = v.InferOutput< typeof markSeasonEpisodesWatchedArgsSchema >; -export const markShowEpisodesAndStatusArgsSchema = z - .object({ - tmdbId: z.number(), - mediaType: mediaTypeSchema, - seasons: z.array( - z.object({ - season: z.number(), - episodes: z.array(z.number()), - }), - ), - isWatched: z.boolean(), - clearAllEpisodes: z.boolean().optional(), - progressStatus: progressStatusSchema.optional(), - progress: z.number().optional(), - }) - .merge(metadataSchema); -export type MarkShowEpisodesAndStatusArgs = z.infer< +export const markShowEpisodesAndStatusArgsSchema = v.object({ + ...metadataSchema.entries, + tmdbId: v.number(), + mediaType: mediaTypeSchema, + seasons: v.array( + v.object({ + season: v.number(), + episodes: v.array(v.number()), + }), + ), + isWatched: v.boolean(), + clearAllEpisodes: v.optional(v.boolean()), + progressStatus: v.optional(progressStatusSchema), + progress: v.optional(v.number()), +}); +export type MarkShowEpisodesAndStatusArgs = v.InferOutput< typeof markShowEpisodesAndStatusArgsSchema >; From ada5a9dac283c9df5a62e872630ad4929effe792 Mon Sep 17 00:00:00 2001 From: Swastik Dan <57379785+Swastikdan@users.noreply.github.com> Date: Sun, 16 Aug 2026 01:18:45 +0530 Subject: [PATCH 04/27] ci: configure Cloudflare deploy workflow for cloudflare and feature branches --- .github/workflows/deploy.yml | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/.github/workflows/deploy.yml b/.github/workflows/deploy.yml index 3c7e68a6..75ba5ea2 100644 --- a/.github/workflows/deploy.yml +++ b/.github/workflows/deploy.yml @@ -1,7 +1,10 @@ name: Deploy Cloudflare on: push: - branches: [master] + branches: + - cloudflare + - feat/convex-to-traditional-backend + workflow_dispatch: # Allows manual trigger from GitHub Actions UI jobs: deploy: From d5136d6575198e4ca9c95011b31111e77e54a07e Mon Sep 17 00:00:00 2001 From: Swastik Dan <57379785+Swastikdan@users.noreply.github.com> Date: Sun, 16 Aug 2026 01:18:51 +0530 Subject: [PATCH 05/27] chore: update pnpm-lock.yaml after removing zod --- pnpm-lock.yaml | 37 +++---------------------------------- 1 file changed, 3 insertions(+), 34 deletions(-) diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 6ba85ac1..9f1217d9 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -31,7 +31,7 @@ importers: version: 5.3.0 '@google/genai': specifier: ^1.52.0 - version: 1.52.0(@modelcontextprotocol/sdk@1.29.0(supports-color@10.2.2)(zod@4.4.3))(bufferutil@4.1.0)(supports-color@10.2.2)(utf-8-validate@6.0.6) + version: 1.52.0(@modelcontextprotocol/sdk@1.29.0(supports-color@10.2.2)(zod@3.25.76))(bufferutil@4.1.0)(supports-color@10.2.2)(utf-8-validate@6.0.6) '@radix-ui/react-accordion': specifier: ^1.2.20 version: 1.2.20(@types/react-dom@19.2.3(@types/react@19.2.17))(@types/react@19.2.17)(react-dom@19.2.8(react@19.2.8))(react@19.2.8) @@ -143,9 +143,6 @@ importers: vite-tsconfig-paths: specifier: ^5.1.4 version: 5.1.4(supports-color@10.2.2)(typescript@5.9.3)(vite@7.3.6(@types/node@22.20.1)(jiti@2.7.0)(lightningcss@1.32.0)(terser@5.49.0)(tsx@4.23.11)(yaml@2.9.0)) - zod: - specifier: ^4.4.3 - version: 4.4.3 zustand: specifier: ^5.0.14 version: 5.0.14(@types/react@19.2.17)(react@19.2.8)(use-sync-external-store@1.6.0(react@19.2.8)) @@ -8406,14 +8403,14 @@ snapshots: '@formkit/auto-animate@0.8.4': {} - '@google/genai@1.52.0(@modelcontextprotocol/sdk@1.29.0(supports-color@10.2.2)(zod@4.4.3))(bufferutil@4.1.0)(supports-color@10.2.2)(utf-8-validate@6.0.6)': + '@google/genai@1.52.0(@modelcontextprotocol/sdk@1.29.0(supports-color@10.2.2)(zod@3.25.76))(bufferutil@4.1.0)(supports-color@10.2.2)(utf-8-validate@6.0.6)': dependencies: google-auth-library: 10.7.0(supports-color@10.2.2) p-retry: 4.6.2 protobufjs: 7.6.2 ws: 8.21.0(bufferutil@4.1.0)(utf-8-validate@6.0.6) optionalDependencies: - '@modelcontextprotocol/sdk': 1.29.0(supports-color@10.2.2)(zod@4.4.3) + '@modelcontextprotocol/sdk': 1.29.0(supports-color@10.2.2)(zod@3.25.76) transitivePeerDependencies: - bufferutil - supports-color @@ -8623,29 +8620,6 @@ snapshots: transitivePeerDependencies: - supports-color - '@modelcontextprotocol/sdk@1.29.0(supports-color@10.2.2)(zod@4.4.3)': - dependencies: - '@hono/node-server': 1.19.15(hono@4.12.32) - ajv: 8.20.0 - ajv-formats: 3.0.1(ajv@8.20.0) - content-type: 1.0.5 - cors: 2.8.6 - cross-spawn: 7.0.6 - eventsource: 3.0.7 - eventsource-parser: 3.1.0 - express: 5.2.1(supports-color@10.2.2) - express-rate-limit: 8.6.0(express@5.2.1(supports-color@10.2.2))(supports-color@10.2.2) - hono: 4.12.32 - jose: 6.2.4 - json-schema-typed: 8.0.2 - pkce-challenge: 5.0.1 - raw-body: 3.0.2 - zod: 4.4.3 - zod-to-json-schema: 3.25.2(zod@4.4.3) - transitivePeerDependencies: - - supports-color - optional: true - '@noble/curves@1.9.7': dependencies: '@noble/hashes': 1.8.0 @@ -14797,11 +14771,6 @@ snapshots: dependencies: zod: 3.25.76 - zod-to-json-schema@3.25.2(zod@4.4.3): - dependencies: - zod: 4.4.3 - optional: true - zod@3.25.76: {} zod@4.4.3: {} From daaa8c5f9f7757d65c7831d19a54b4cb45242ec3 Mon Sep 17 00:00:00 2001 From: Swastik Dan <57379785+Swastikdan@users.noreply.github.com> Date: Sun, 16 Aug 2026 01:34:00 +0530 Subject: [PATCH 06/27] ci: specify pnpm version for GitHub Actions workflow --- .github/workflows/deploy.yml | 2 ++ package.json | 4 +++- 2 files changed, 5 insertions(+), 1 deletion(-) diff --git a/.github/workflows/deploy.yml b/.github/workflows/deploy.yml index 75ba5ea2..b1773957 100644 --- a/.github/workflows/deploy.yml +++ b/.github/workflows/deploy.yml @@ -12,6 +12,8 @@ jobs: steps: - uses: actions/checkout@v4 - uses: pnpm/action-setup@v4 + with: + version: 10 - uses: actions/setup-node@v4 with: { node-version: 22, cache: pnpm } - run: pnpm install --frozen-lockfile diff --git a/package.json b/package.json index 68c4411d..47e9d850 100644 --- a/package.json +++ b/package.json @@ -1,7 +1,9 @@ { "name": "pebbly", "private": true, - "type": "module", "scripts": { + "type": "module", + "packageManager": "pnpm@10.6.1", + "scripts": { "dev": "vite dev --port 3000", "dev:web": "vite dev --port 3000", "dev:cf": "wrangler dev", From b67efdff58417eba95d9053de5afd9cada906b94 Mon Sep 17 00:00:00 2001 From: Swastik Dan <57379785+Swastikdan@users.noreply.github.com> Date: Sun, 16 Aug 2026 01:36:52 +0530 Subject: [PATCH 07/27] ci: rely on packageManager field in package.json for pnpm version --- .github/workflows/deploy.yml | 2 -- 1 file changed, 2 deletions(-) diff --git a/.github/workflows/deploy.yml b/.github/workflows/deploy.yml index b1773957..75ba5ea2 100644 --- a/.github/workflows/deploy.yml +++ b/.github/workflows/deploy.yml @@ -12,8 +12,6 @@ jobs: steps: - uses: actions/checkout@v4 - uses: pnpm/action-setup@v4 - with: - version: 10 - uses: actions/setup-node@v4 with: { node-version: 22, cache: pnpm } - run: pnpm install --frozen-lockfile From a917bf86dcb1b186a4ebead4f96c45b95fd13b2f Mon Sep 17 00:00:00 2001 From: Swastik Dan <57379785+Swastikdan@users.noreply.github.com> Date: Sun, 16 Aug 2026 01:45:07 +0530 Subject: [PATCH 08/27] fix(import): sanitize reaction, progress, and rating inputs to satisfy D1 database constraints --- src/hooks/use-watchlist-import-export.ts | 7 +++- src/server/fns/import-export.ts | 22 ++++++++---- src/server/helpers/watch-item.ts | 45 ++++++++++++++++++++---- src/server/schema/import.ts | 10 ++---- wrangler.toml | 4 +++ 5 files changed, 67 insertions(+), 21 deletions(-) diff --git a/src/hooks/use-watchlist-import-export.ts b/src/hooks/use-watchlist-import-export.ts index 63313f5b..9acd10e9 100644 --- a/src/hooks/use-watchlist-import-export.ts +++ b/src/hooks/use-watchlist-import-export.ts @@ -223,7 +223,12 @@ export const useWatchlistImportExport = () => { normalizeProgressStatus(item.progressStatus as string) ?? "watch-later", progress: item.progress, - reaction: (item.reaction as ReactionStatus | null) ?? null, + reaction: + item.reaction && + typeof item.reaction === "string" && + item.reaction.trim() !== "" + ? (item.reaction as ReactionStatus) + : null, })); if (isSignedIn) { diff --git a/src/server/fns/import-export.ts b/src/server/fns/import-export.ts index 7486bee9..1ec7ec0e 100644 --- a/src/server/fns/import-export.ts +++ b/src/server/fns/import-export.ts @@ -5,7 +5,11 @@ import { getDb } from "../db/client"; import { watchItems } from "../db/schema"; import { getEnv } from "../env"; import { createWatchlistSnapshot } from "../helpers/snapshots"; -import { buildMetadataPatch } from "../helpers/watch-item"; +import { + buildMetadataPatch, + normalizeProgressStatus, + normalizeReaction, +} from "../helpers/watch-item"; import { type ApiResult, ok } from "../schema/common"; import { importWatchlistArgsSchema } from "../schema/import"; import { syncEpisodeProgressRecord } from "./watchlist"; @@ -36,14 +40,20 @@ export const importWatchlist = createServerFn({ method: "POST" }) for (const item of importedItems.values()) { const existing = existingMap.get(`${item.mediaType}:${item.tmdbId}`); - const progressStatus = item.progressStatus ?? "watch-later"; - const progress = + const progressStatus = + normalizeProgressStatus(item.progressStatus) ?? "watch-later"; + const rawProgress = item.progress ?? (progressStatus === "done" ? 100 : progressStatus === "watch-later" ? 0 - : existing?.progress); + : (existing?.progress ?? 0)); + const progress = Math.min(Math.max(rawProgress, 0), 100); + const reaction = + normalizeReaction(item.reaction) ?? + normalizeReaction(existing?.reaction) ?? + null; const metadata = buildMetadataPatch(item, existing ?? undefined); if (existing) { @@ -53,7 +63,7 @@ export const importWatchlist = createServerFn({ method: "POST" }) inWatchlist: true, progressStatus, progress, - reaction: item.reaction ?? existing.reaction ?? null, + reaction, updatedAt: now, ...metadata, }) @@ -67,7 +77,7 @@ export const importWatchlist = createServerFn({ method: "POST" }) inWatchlist: true, progressStatus, progress, - reaction: item.reaction ?? null, + reaction, updatedAt: now, ...metadata, }); diff --git a/src/server/helpers/watch-item.ts b/src/server/helpers/watch-item.ts index d793a867..a18df82d 100644 --- a/src/server/helpers/watch-item.ts +++ b/src/server/helpers/watch-item.ts @@ -19,6 +19,21 @@ export function normalizeProgressStatus( | undefined; } +const VALID_REACTIONS: ReadonlySet = new Set([ + "loved", + "liked", + "mixed", + "not-for-me", + "recommended", +]); + +export function normalizeReaction(reaction?: string | null): Reaction | null { + if (!reaction || typeof reaction !== "string" || reaction.trim() === "") { + return null; + } + return (VALID_REACTIONS.has(reaction) ? reaction : null) as Reaction | null; +} + export interface MediaIdentity { tmdbId: number; mediaType: MediaType; @@ -65,10 +80,15 @@ export function buildMetadataPatch( metadata: WatchItemMetadata, existing?: WatchItemRow | null, ): MetadataDbPatch { + const rating = + typeof metadata.rating === "number" && !Number.isNaN(metadata.rating) + ? Math.min(Math.max(metadata.rating, 0), 10) + : (existing?.rating ?? undefined); + return { title: metadata.title ?? existing?.title ?? undefined, image: metadata.image ?? existing?.image ?? undefined, - rating: metadata.rating ?? existing?.rating ?? undefined, + rating, releaseDate: metadata.release_date ?? existing?.releaseDate ?? undefined, overview: metadata.overview ?? existing?.overview ?? undefined, }; @@ -109,9 +129,16 @@ export async function upsertWatchItem( if ("inWatchlist" in finalUpdates) patch.inWatchlist = finalUpdates.inWatchlist; if ("progressStatus" in finalUpdates) - patch.progressStatus = finalUpdates.progressStatus; - if ("progress" in finalUpdates) patch.progress = finalUpdates.progress; - if ("reaction" in finalUpdates) patch.reaction = finalUpdates.reaction; + patch.progressStatus = + normalizeProgressStatus(finalUpdates.progressStatus) ?? + existing.progressStatus; + if ("progress" in finalUpdates) + patch.progress = + typeof finalUpdates.progress === "number" + ? Math.min(Math.max(finalUpdates.progress, 0), 100) + : existing.progress; + if ("reaction" in finalUpdates) + patch.reaction = normalizeReaction(finalUpdates.reaction); await db .update(watchItems) @@ -127,9 +154,13 @@ export async function upsertWatchItem( tmdbId, mediaType, inWatchlist: finalUpdates.inWatchlist ?? false, - progressStatus: finalUpdates.progressStatus ?? undefined, - progress: finalUpdates.progress ?? 0, - reaction: (finalUpdates.reaction as Reaction | undefined) ?? undefined, + progressStatus: + normalizeProgressStatus(finalUpdates.progressStatus) ?? undefined, + progress: + typeof finalUpdates.progress === "number" + ? Math.min(Math.max(finalUpdates.progress, 0), 100) + : 0, + reaction: normalizeReaction(finalUpdates.reaction) ?? undefined, updatedAt: now, ...metadataPatch, }); diff --git a/src/server/schema/import.ts b/src/server/schema/import.ts index 690bba3a..f47159b6 100644 --- a/src/server/schema/import.ts +++ b/src/server/schema/import.ts @@ -1,9 +1,5 @@ import * as v from "valibot"; -import { - mediaTypeSchema, - progressStatusSchema, - reactionSchema, -} from "./common"; +import { mediaTypeSchema } from "./common"; export const importItemSchema = v.object({ tmdbId: v.number(), @@ -13,9 +9,9 @@ export const importItemSchema = v.object({ rating: v.optional(v.number()), release_date: v.optional(v.string()), overview: v.optional(v.string()), - progressStatus: v.optional(progressStatusSchema), + progressStatus: v.optional(v.nullable(v.string())), progress: v.optional(v.number()), - reaction: v.optional(v.nullable(reactionSchema)), + reaction: v.optional(v.nullable(v.string())), }); export type ImportItem = v.InferOutput; diff --git a/wrangler.toml b/wrangler.toml index fa7864c9..1e0ae523 100644 --- a/wrangler.toml +++ b/wrangler.toml @@ -21,5 +21,9 @@ migrations_dir = "drizzle" [triggers] crons = ["0 3 * * *"] +[observability.logs] +enabled = true +invocation_logs = true + # Non-secret server vars only. Secrets: wrangler secret put . # Client VITE_* vars are inlined at build time from .env — they do NOT go here. From 8a93a6278f7e3a742d5dcd4581ea9f154862bb07 Mon Sep 17 00:00:00 2001 From: Swastik Dan <57379785+Swastikdan@users.noreply.github.com> Date: Sun, 16 Aug 2026 01:58:30 +0530 Subject: [PATCH 09/27] perf: remove Upstash Redis in favor of direct D1 edge queries and optimize user lookups --- .env.example | 7 +- package.json | 2 - server/routes/api/health.ts | 87 +++++++++---------------- src/server/auth.ts | 104 +++++++++++++++--------------- src/server/db/client.ts | 28 +------- src/server/env.ts | 3 - src/server/fns/lists.ts | 15 ++--- src/server/fns/recommendations.ts | 15 ++--- src/server/fns/watchlist.ts | 15 ++--- wrangler.toml | 3 + 10 files changed, 104 insertions(+), 175 deletions(-) diff --git a/.env.example b/.env.example index 9cda1aca..eaac0241 100644 --- a/.env.example +++ b/.env.example @@ -30,11 +30,6 @@ GEMINI_API_KEY=your_gemini_key CLERK_SECRET_KEY=sk_test_YOUR_CLERK_SECRET_KEY CLERK_ISSUER_URL=https://your-app.clerk.accounts.dev -# Upstash Redis (Drizzle query cache + rate limiting) -UPSTASH_REDIS_REST_URL=https://your-db.upstash.io -UPSTASH_REDIS_REST_TOKEN=your-rest-token -UPSTASH_REDIS_READONLY_REST_TOKEN=your-readonly-rest-token - -# Cloudflare (only needed for `pnpm db:studio` remote dashboard + GitHub Actions) +# Cloudflare (needed for `pnpm db:studio` remote dashboard + GitHub Actions) CLOUDFLARE_API_TOKEN=your-api-token-with-d1-edit CLOUDFLARE_ACCOUNT_ID=your-account-id diff --git a/package.json b/package.json index 47e9d850..96e077de 100644 --- a/package.json +++ b/package.json @@ -51,8 +51,6 @@ "@tanstack/react-start": "^1.168.32", "@tanstack/router-plugin": "^1.168.23", "@unpic/react": "^1.0.2", - "@upstash/ratelimit": "^2.0.8", - "@upstash/redis": "^1.38.2", "@vercel/speed-insights": "^1.3.1", "class-variance-authority": "^0.7.1", "clsx": "^2.1.1", diff --git a/server/routes/api/health.ts b/server/routes/api/health.ts index 27014171..9b2c7346 100644 --- a/server/routes/api/health.ts +++ b/server/routes/api/health.ts @@ -1,68 +1,41 @@ -// GET /api/health — pings D1 (select 1) and Redis (if configured) per §6.8. -import { defineEventHandler } from "h3"; +// GET /api/health — pings D1 (select 1) import { sql } from "drizzle-orm"; +import { defineEventHandler } from "h3"; import { getDb } from "../../../src/server/db/client"; import { getEnv } from "../../../src/server/env"; type CheckResult = { ok: boolean; [key: string]: unknown }; export default defineEventHandler(async () => { - const env = getEnv(); - const started = Date.now(); - - const checks: Record = {}; - let ok = true; + const env = getEnv(); + const started = Date.now(); - // D1 ping — skipped when there's no binding (plain Node `vite dev`); on the - // Worker (`wrangler dev` / deployed) the DB binding is always present. - if (!env.DB) { - checks.db = { ok: true, skipped: "no D1 binding (vite dev)" }; - } else { - try { - const db = getDb(env); - await db.run(sql`select 1`); - checks.db = { ok: true }; - } catch (error) { - ok = false; - checks.db = { - ok: false, - error: error instanceof Error ? error.message : String(error), - }; - } - } + const checks: Record = {}; + let ok = true; - // Upstash ping (REST) — only when configured - const url = env.UPSTASH_REDIS_REST_URL; - const token = env.UPSTASH_REDIS_REST_TOKEN; - if ( - typeof url === "string" && - url.length > 0 && - typeof token === "string" && - token.length > 0 - ) { - try { - const res = await fetch(`${url}/ping`, { - headers: { Authorization: `Bearer ${token}` }, - }); - const body = await res.text(); - checks.redis = { ok: res.ok && body.includes("PONG"), status: res.status }; - if (!res.ok || !body.includes("PONG")) ok = false; - } catch (error) { - ok = false; - checks.redis = { - ok: false, - error: error instanceof Error ? error.message : String(error), - }; - } - } else { - checks.redis = { ok: true, skipped: "not configured" }; - } + // D1 ping — skipped when there's no binding (plain Node `vite dev`); on the + // Worker (`wrangler dev` / deployed) the DB binding is always present. + if (!env.DB) { + checks.db = { ok: true, skipped: "no D1 binding (vite dev)" }; + } else { + try { + const db = getDb(env); + await db.run(sql`select 1`); + checks.db = { ok: true }; + } catch (error) { + ok = false; + checks.db = { + ok: false, + error: error instanceof Error ? error.message : String(error), + }; + } + } - return { - ok, - service: "pebbly", - timestamp: new Date().toISOString(), - checks, - durationMs: Date.now() - started, - }; + return { + ok, + service: "pebbly", + timestamp: new Date().toISOString(), + checks, + durationMs: Date.now() - started, + }; }); diff --git a/src/server/auth.ts b/src/server/auth.ts index 23ee6d19..9b9c136f 100644 --- a/src/server/auth.ts +++ b/src/server/auth.ts @@ -1,6 +1,6 @@ import { createClerkClient, verifyToken } from "@clerk/backend"; import { getCookie, getRequestHeader } from "@tanstack/react-start/server"; -import { and, eq } from "drizzle-orm"; +import { and, eq, like, or } from "drizzle-orm"; import { getDb } from "./db/client"; import { users, watchItems } from "./db/schema"; import { getEnv, getEnvVar } from "./env"; @@ -130,21 +130,21 @@ export async function isAdminFromClerkApi(sub: string): Promise { export async function findUserByClaims(claims: ClerkSessionClaims) { const db = getDb(getEnv()); const subject = claims.sub; + if (!subject) return null; const tokenIdentifier = toTokenIdentifier(subject); - const candidates = new Set([ - tokenIdentifier, - subject, - `clerk|${subject}`, - ]); - const allUsers = await db.select().from(users).limit(500); - - const matches = allUsers.filter( - (u) => - candidates.has(u.tokenIdentifier) || - (subject && u.tokenIdentifier.endsWith(`|${subject}`)) || - (subject && u.tokenIdentifier.endsWith(subject)), - ); + const matches = await db + .select() + .from(users) + .where( + or( + eq(users.tokenIdentifier, tokenIdentifier), + eq(users.tokenIdentifier, subject), + eq(users.tokenIdentifier, `clerk|${subject}`), + like(users.tokenIdentifier, `%|${subject}`), + ), + ) + .limit(10); if (matches.length === 0) return null; if (matches.length === 1) return matches[0]; @@ -211,45 +211,47 @@ export async function requireUser(): Promise { // Auto-consolidate orphaned watch items from duplicate user documents (port // of the Convex `requireCurrentUser` consolidation step). const subject = claims.sub; - const tokenIdentifier = toTokenIdentifier(subject); - const candidates = new Set([ - tokenIdentifier, - subject, - `clerk|${subject}`, - ]); - const allUsers = await db.select().from(users).limit(500); - const userMatches = allUsers.filter( - (u) => - candidates.has(u.tokenIdentifier) || - (subject && u.tokenIdentifier.endsWith(`|${subject}`)) || - (subject && u.tokenIdentifier.endsWith(subject)), - ); + if (subject) { + const tokenIdentifier = toTokenIdentifier(subject); + const userMatches = await db + .select() + .from(users) + .where( + or( + eq(users.tokenIdentifier, tokenIdentifier), + eq(users.tokenIdentifier, subject), + eq(users.tokenIdentifier, `clerk|${subject}`), + like(users.tokenIdentifier, `%|${subject}`), + ), + ) + .limit(10); - if (userMatches.length > 1) { - for (const dup of userMatches) { - if (dup.id === user.id) continue; - const dupItems = await db - .select() - .from(watchItems) - .where(eq(watchItems.userId, dup.id)) - .limit(500); - for (const item of dupItems) { - const existingInMain = await db - .select({ id: watchItems.id }) + if (userMatches.length > 1) { + for (const dup of userMatches) { + if (dup.id === user.id) continue; + const dupItems = await db + .select() .from(watchItems) - .where( - and( - eq(watchItems.userId, user.id), - eq(watchItems.tmdbId, item.tmdbId), - eq(watchItems.mediaType, item.mediaType), - ), - ) - .limit(1); - if (existingInMain.length === 0) { - await db - .update(watchItems) - .set({ userId: user.id }) - .where(eq(watchItems.id, item.id)); + .where(eq(watchItems.userId, dup.id)) + .limit(500); + for (const item of dupItems) { + const existingInMain = await db + .select({ id: watchItems.id }) + .from(watchItems) + .where( + and( + eq(watchItems.userId, user.id), + eq(watchItems.tmdbId, item.tmdbId), + eq(watchItems.mediaType, item.mediaType), + ), + ) + .limit(1); + if (existingInMain.length === 0) { + await db + .update(watchItems) + .set({ userId: user.id }) + .where(eq(watchItems.id, item.id)); + } } } } diff --git a/src/server/db/client.ts b/src/server/db/client.ts index 121aa603..cf8506d7 100644 --- a/src/server/db/client.ts +++ b/src/server/db/client.ts @@ -1,15 +1,10 @@ -import { upstashCache } from "drizzle-orm/cache/upstash"; import { drizzle } from "drizzle-orm/d1"; import type { Env } from "../env"; import * as schema from "./schema"; /** - * Create a Drizzle instance bound to the Worker's D1 database, with an - * optional Upstash Redis cache layer. Cache is only wired up when the - * Upstash env vars are present (local dev without Redis still works). - * - * Opt in per query with `.$withCache({ config: { ex: 15 } })` — global caching - * is disabled so hot reads are cached explicitly. + * Create a Drizzle instance bound directly to the Worker's D1 database. + * Executes queries directly at the Cloudflare edge for single-digit ms latency. */ export function getDb(env: Env) { if (!env.DB) { @@ -20,25 +15,6 @@ export function getDb(env: Env) { ); } - const url = env.UPSTASH_REDIS_REST_URL; - const token = env.UPSTASH_REDIS_REST_TOKEN; - - if ( - typeof url === "string" && - url.length > 0 && - typeof token === "string" && - token.length > 0 - ) { - return drizzle(env.DB, { - schema, - cache: upstashCache({ - url, - token, - // global: false — opt in per query with .$withCache() - }), - }); - } - return drizzle(env.DB, { schema }); } diff --git a/src/server/env.ts b/src/server/env.ts index bcc9ff79..1e2380a0 100644 --- a/src/server/env.ts +++ b/src/server/env.ts @@ -11,9 +11,6 @@ export interface Env { CLERK_SECRET_KEY?: string; CLERK_ISSUER_URL?: string; GEMINI_API_KEY?: string; - UPSTASH_REDIS_REST_URL?: string; - UPSTASH_REDIS_REST_TOKEN?: string; - UPSTASH_REDIS_READONLY_REST_TOKEN?: string; CRON_SECRET?: string; [key: string]: unknown; } diff --git a/src/server/fns/lists.ts b/src/server/fns/lists.ts index 53672814..fa48a4e4 100644 --- a/src/server/fns/lists.ts +++ b/src/server/fns/lists.ts @@ -35,14 +35,12 @@ export const getCustomLists = createServerFn({ method: "POST" }).handler( .select() .from(lists) .where(eq(lists.userId, user.id)) - .orderBy(asc(lists.sortOrder)) - .$withCache({ config: { ex: 15 } }); + .orderBy(asc(lists.sortOrder)); const allUserListItems = await db .select() .from(listItems) - .where(eq(listItems.userId, user.id)) - .$withCache({ config: { ex: 15 } }); + .where(eq(listItems.userId, user.id)); const itemsByList = new Map(); for (const item of allUserListItems) { @@ -93,8 +91,7 @@ export const getListItems = createServerFn({ method: "POST" }) .select() .from(lists) .where(and(eq(lists.id, data.listId), eq(lists.userId, user.id))) - .limit(1) - .$withCache({ config: { ex: 15 } }); + .limit(1); if (list.length === 0) return ok([]); @@ -103,8 +100,7 @@ export const getListItems = createServerFn({ method: "POST" }) .from(listItems) .where( and(eq(listItems.listId, data.listId), eq(listItems.userId, user.id)), - ) - .$withCache({ config: { ex: 15 } }); + ); // Enrich with watch_item metadata (port of the N+1 loop — batch in one query). const watchItemPromises = items.map((item) => @@ -165,8 +161,7 @@ export const getItemLists = createServerFn({ method: "POST" }) eq(listItems.tmdbId, data.tmdbId), eq(listItems.mediaType, data.mediaType), ), - ) - .$withCache({ config: { ex: 15 } }); + ); return ok(items.map((i) => i.listId)); }); diff --git a/src/server/fns/recommendations.ts b/src/server/fns/recommendations.ts index 8d8ebb20..48b0bab1 100644 --- a/src/server/fns/recommendations.ts +++ b/src/server/fns/recommendations.ts @@ -111,8 +111,7 @@ export const getRecommendationHistory = createServerFn({ .from(aiRecommendations) .where(eq(aiRecommendations.userId, user.id)) .orderBy(desc(aiRecommendations.createdAt)) - .limit(20) - .$withCache({ config: { ex: 60 } }); + .limit(20); return ok(rows); }, @@ -189,8 +188,7 @@ export const getRecommendationFeedback = createServerFn({ .select() .from(recommendationFeedback) .where(eq(recommendationFeedback.userId, user.id)) - .limit(100) - .$withCache({ config: { ex: 60 } }); + .limit(100); return ok(rows); }, @@ -395,8 +393,7 @@ export const getHomepageRecommendations = createServerFn({ method: "POST" }) .select() .from(homepageRecommendations) .where(eq(homepageRecommendations.userId, user.id)) - .limit(1) - .$withCache({ config: { ex: 60 } }); + .limit(1); const notInterestedFeedback = await db .select() @@ -406,8 +403,7 @@ export const getHomepageRecommendations = createServerFn({ method: "POST" }) eq(recommendationFeedback.userId, user.id), eq(recommendationFeedback.feedback, "not_interested"), ), - ) - .$withCache({ config: { ex: 60 } }); + ); const dislikeFeedback = await db .select() @@ -417,8 +413,7 @@ export const getHomepageRecommendations = createServerFn({ method: "POST" }) eq(recommendationFeedback.userId, user.id), eq(recommendationFeedback.feedback, "dislike"), ), - ) - .$withCache({ config: { ex: 60 } }); + ); const excludedFeedbackIds = new Set([ ...notInterestedFeedback.map((f) => f.tmdbId), diff --git a/src/server/fns/watchlist.ts b/src/server/fns/watchlist.ts index dcb2a260..eb2cd7cb 100644 --- a/src/server/fns/watchlist.ts +++ b/src/server/fns/watchlist.ts @@ -63,8 +63,7 @@ export const getWatchlist = createServerFn({ method: "POST" }) .from(watchItems) .where(and(...filters)) .orderBy(desc(watchItems.updatedAt)) - .limit(boundedLimit) - .$withCache({ config: { ex: 15 } }); + .limit(boundedLimit); return ok(rows); }, @@ -80,8 +79,7 @@ export const getTrackedTmdbIds = createServerFn({ method: "POST" }).handler( .select({ tmdbId: watchItems.tmdbId }) .from(watchItems) .where(eq(watchItems.userId, user.id)) - .limit(500) - .$withCache({ config: { ex: 15 } }); + .limit(500); return ok(items.map((item) => item.tmdbId)); }, @@ -107,8 +105,7 @@ export const getMediaState = createServerFn({ method: "POST" }) eq(watchItems.mediaType, data.mediaType), ), ) - .limit(1) - .$withCache({ config: { ex: 15 } }); + .limit(1); return ok(rows[0] ?? null); }, @@ -506,8 +503,7 @@ export const getAllWatchedEpisodes = createServerFn({ method: "POST" }) eq(episodeProgress.userId, user.id), eq(episodeProgress.tmdbId, data.tmdbId), ), - ) - .$withCache({ config: { ex: 15 } }); + ); return ok(rows); }, @@ -522,8 +518,7 @@ export const getAllEpisodeProgress = createServerFn({ method: "POST" }).handler( const rows = await db .select() .from(episodeProgress) - .where(eq(episodeProgress.userId, user.id)) - .$withCache({ config: { ex: 15 } }); + .where(eq(episodeProgress.userId, user.id)); return ok(rows); }, diff --git a/wrangler.toml b/wrangler.toml index 1e0ae523..19782a90 100644 --- a/wrangler.toml +++ b/wrangler.toml @@ -25,5 +25,8 @@ crons = ["0 3 * * *"] enabled = true invocation_logs = true +[observability.traces] +enabled = true + # Non-secret server vars only. Secrets: wrangler secret put . # Client VITE_* vars are inlined at build time from .env — they do NOT go here. From 4619230692f0e8db2098f94a48326dcd78d7b224 Mon Sep 17 00:00:00 2001 From: Swastik Dan <57379785+Swastikdan@users.noreply.github.com> Date: Sun, 16 Aug 2026 02:09:05 +0530 Subject: [PATCH 10/27] chore: update pnpm-lock.yaml after dependency removals --- pnpm-lock.yaml | 588 +++++++++++++++++++++---------------------------- 1 file changed, 254 insertions(+), 334 deletions(-) diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 9f1217d9..79424f92 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -22,7 +22,7 @@ importers: version: 6.12.8(react-dom@19.2.8(react@19.2.8))(react@19.2.8) '@clerk/ui': specifier: ^1.26.0 - version: 1.26.0(@solana/web3.js@1.98.4(bufferutil@4.1.0)(typescript@5.9.3)(utf-8-validate@6.0.6))(@types/react@19.2.17)(bs58@6.0.0)(bufferutil@4.1.0)(react-dom@19.2.8(react@19.2.8))(react-native@0.86.0(@babel/core@7.29.7(supports-color@10.2.2))(@types/react@19.2.17)(bufferutil@4.1.0)(react@19.2.8)(supports-color@10.2.2)(utf-8-validate@6.0.6))(react@19.2.8)(supports-color@10.2.2)(typescript@5.9.3)(utf-8-validate@6.0.6) + version: 1.26.0(@solana/web3.js@1.98.4(bufferutil@4.1.0)(typescript@5.9.3)(utf-8-validate@6.0.6))(@types/react@19.2.17)(bs58@6.0.0)(bufferutil@4.1.0)(react-dom@19.2.8(react@19.2.8))(react-native@0.86.0(@babel/core@7.29.7)(@types/react@19.2.17)(bufferutil@4.1.0)(react@19.2.8)(utf-8-validate@6.0.6))(react@19.2.8)(typescript@5.9.3)(utf-8-validate@6.0.6) '@convex-dev/react-query': specifier: ^0.1.0 version: 0.1.0(@tanstack/react-query@5.101.4(react@19.2.8))(convex@1.42.3(@clerk/react@6.12.8(react-dom@19.2.8(react@19.2.8))(react@19.2.8))(bufferutil@4.1.0)(react@19.2.8)(utf-8-validate@6.0.6)) @@ -31,7 +31,7 @@ importers: version: 5.3.0 '@google/genai': specifier: ^1.52.0 - version: 1.52.0(@modelcontextprotocol/sdk@1.29.0(supports-color@10.2.2)(zod@3.25.76))(bufferutil@4.1.0)(supports-color@10.2.2)(utf-8-validate@6.0.6) + version: 1.52.0(@modelcontextprotocol/sdk@1.29.0(zod@3.25.76))(bufferutil@4.1.0)(utf-8-validate@6.0.6) '@radix-ui/react-accordion': specifier: ^1.2.20 version: 1.2.20(@types/react-dom@19.2.3(@types/react@19.2.17))(@types/react@19.2.17)(react-dom@19.2.8(react@19.2.8))(react@19.2.8) @@ -61,7 +61,7 @@ importers: version: 4.3.3(vite@7.3.6(@types/node@22.20.1)(jiti@2.7.0)(lightningcss@1.32.0)(terser@5.49.0)(tsx@4.23.11)(yaml@2.9.0)) '@tanstack/nitro-v2-vite-plugin': specifier: ^1.155.0 - version: 1.155.0(@upstash/redis@1.38.2)(drizzle-orm@0.45.2(@cloudflare/workers-types@5.20260808.1)(@upstash/redis@1.38.2))(rolldown@1.2.3)(srvx@0.11.22)(supports-color@10.2.2)(vite@7.3.6(@types/node@22.20.1)(jiti@2.7.0)(lightningcss@1.32.0)(terser@5.49.0)(tsx@4.23.11)(yaml@2.9.0)) + version: 1.155.0(@upstash/redis@1.38.2)(drizzle-orm@0.45.2(@cloudflare/workers-types@5.20260808.1)(@upstash/redis@1.38.2))(rolldown@1.2.3)(srvx@0.11.22)(vite@7.3.6(@types/node@22.20.1)(jiti@2.7.0)(lightningcss@1.32.0)(terser@5.49.0)(tsx@4.23.11)(yaml@2.9.0)) '@tanstack/react-query': specifier: ^5.101.4 version: 5.101.4(react@19.2.8) @@ -76,19 +76,13 @@ importers: version: 1.130.17(@tanstack/react-query@5.101.4(react@19.2.8))(@tanstack/react-router@1.170.18(react-dom@19.2.8(react@19.2.8))(react@19.2.8))(@tanstack/router-core@1.171.15)(react-dom@19.2.8(react@19.2.8))(react@19.2.8) '@tanstack/react-start': specifier: ^1.168.32 - version: 1.168.32(crossws@0.4.10(srvx@0.11.22))(react-dom@19.2.8(react@19.2.8))(react@19.2.8)(supports-color@10.2.2)(vite@7.3.6(@types/node@22.20.1)(jiti@2.7.0)(lightningcss@1.32.0)(terser@5.49.0)(tsx@4.23.11)(yaml@2.9.0)) + version: 1.168.32(crossws@0.4.10(srvx@0.11.22))(react-dom@19.2.8(react@19.2.8))(react@19.2.8)(vite@7.3.6(@types/node@22.20.1)(jiti@2.7.0)(lightningcss@1.32.0)(terser@5.49.0)(tsx@4.23.11)(yaml@2.9.0)) '@tanstack/router-plugin': specifier: ^1.168.23 - version: 1.168.23(@tanstack/react-router@1.170.18(react-dom@19.2.8(react@19.2.8))(react@19.2.8))(supports-color@10.2.2)(vite@7.3.6(@types/node@22.20.1)(jiti@2.7.0)(lightningcss@1.32.0)(terser@5.49.0)(tsx@4.23.11)(yaml@2.9.0)) + version: 1.168.23(@tanstack/react-router@1.170.18(react-dom@19.2.8(react@19.2.8))(react@19.2.8))(vite@7.3.6(@types/node@22.20.1)(jiti@2.7.0)(lightningcss@1.32.0)(terser@5.49.0)(tsx@4.23.11)(yaml@2.9.0)) '@unpic/react': specifier: ^1.0.2 version: 1.0.2(react-dom@19.2.8(react@19.2.8))(react@19.2.8) - '@upstash/ratelimit': - specifier: ^2.0.8 - version: 2.0.8(@upstash/redis@1.38.2) - '@upstash/redis': - specifier: ^1.38.2 - version: 1.38.2 '@vercel/speed-insights': specifier: ^1.3.1 version: 1.3.1(react@19.2.8) @@ -115,10 +109,10 @@ importers: version: 0.544.0(react@19.2.8) nitro: specifier: npm:nitro-nightly@latest - version: nitro-nightly@3.0.1-20260731-205209-52abde8a(@upstash/redis@1.38.2)(chokidar@5.0.0)(dotenv@17.4.2)(drizzle-orm@0.45.2(@cloudflare/workers-types@5.20260808.1)(@upstash/redis@1.38.2))(giget@3.2.0)(ioredis@5.11.1(supports-color@10.2.2))(jiti@2.7.0)(lru-cache@11.5.1)(rollup@4.61.1)(vite@7.3.6(@types/node@22.20.1)(jiti@2.7.0)(lightningcss@1.32.0)(terser@5.49.0)(tsx@4.23.11)(yaml@2.9.0))(wrangler@4.120.0(@cloudflare/workers-types@5.20260808.1)(bufferutil@4.1.0)(utf-8-validate@6.0.6)) + version: nitro-nightly@3.0.1-20260731-205209-52abde8a(@upstash/redis@1.38.2)(chokidar@5.0.0)(dotenv@17.4.2)(drizzle-orm@0.45.2(@cloudflare/workers-types@5.20260808.1)(@upstash/redis@1.38.2))(giget@3.2.0)(ioredis@5.11.1)(jiti@2.7.0)(lru-cache@11.5.1)(rollup@4.61.1)(vite@7.3.6(@types/node@22.20.1)(jiti@2.7.0)(lightningcss@1.32.0)(terser@5.49.0)(tsx@4.23.11)(yaml@2.9.0))(wrangler@4.120.0(@cloudflare/workers-types@5.20260808.1)(bufferutil@4.1.0)(utf-8-validate@6.0.6)) nitropack: specifier: ^2.13.4 - version: 2.13.4(@upstash/redis@1.38.2)(drizzle-orm@0.45.2(@cloudflare/workers-types@5.20260808.1)(@upstash/redis@1.38.2))(rolldown@1.2.3)(srvx@0.11.22)(supports-color@10.2.2) + version: 2.13.4(@upstash/redis@1.38.2)(drizzle-orm@0.45.2(@cloudflare/workers-types@5.20260808.1)(@upstash/redis@1.38.2))(rolldown@1.2.3)(srvx@0.11.22) postcss: specifier: ^8.5.23 version: 8.5.23 @@ -142,7 +136,7 @@ importers: version: 1.4.2(typescript@5.9.3) vite-tsconfig-paths: specifier: ^5.1.4 - version: 5.1.4(supports-color@10.2.2)(typescript@5.9.3)(vite@7.3.6(@types/node@22.20.1)(jiti@2.7.0)(lightningcss@1.32.0)(terser@5.49.0)(tsx@4.23.11)(yaml@2.9.0)) + version: 5.1.4(typescript@5.9.3)(vite@7.3.6(@types/node@22.20.1)(jiti@2.7.0)(lightningcss@1.32.0)(terser@5.49.0)(tsx@4.23.11)(yaml@2.9.0)) zustand: specifier: ^5.0.14 version: 5.0.14(@types/react@19.2.17)(react@19.2.8)(use-sync-external-store@1.6.0(react@19.2.8)) @@ -176,7 +170,7 @@ importers: version: 19.2.3(@types/react@19.2.17) '@vitejs/plugin-react': specifier: ^5.2.0 - version: 5.2.0(supports-color@10.2.2)(vite@7.3.6(@types/node@22.20.1)(jiti@2.7.0)(lightningcss@1.32.0)(terser@5.49.0)(tsx@4.23.11)(yaml@2.9.0)) + version: 5.2.0(vite@7.3.6(@types/node@22.20.1)(jiti@2.7.0)(lightningcss@1.32.0)(terser@5.49.0)(tsx@4.23.11)(yaml@2.9.0)) babel-plugin-react-compiler: specifier: ^1.0.0 version: 1.0.0 @@ -194,13 +188,13 @@ importers: version: 9.1.7 jsdom: specifier: ^27.4.0 - version: 27.4.0(@noble/hashes@1.8.0)(bufferutil@4.1.0)(supports-color@10.2.2)(utf-8-validate@6.0.6) + version: 27.4.0(@noble/hashes@1.8.0)(bufferutil@4.1.0)(utf-8-validate@6.0.6) lint-staged: specifier: ^17.2.0 version: 17.2.0 shadcn: specifier: ^4.14.1 - version: 4.14.1(babel-plugin-macros@3.1.0)(supports-color@10.2.2)(typescript@5.9.3) + version: 4.14.1(babel-plugin-macros@3.1.0)(typescript@5.9.3) terser: specifier: ^5.49.0 version: 5.49.0 @@ -412,28 +406,24 @@ packages: engines: {node: '>=14.21.3'} cpu: [arm64] os: [linux] - libc: [musl] '@biomejs/cli-linux-arm64@2.4.13': resolution: {integrity: sha512-NzkUDSqfvMBrPplKgVr3aXLHZ2NEELvvF4vZxXulEylKWIGqlvNEcwUcj9OLrn75TD3lJ/GIqCVlBwd1MZCuYQ==} engines: {node: '>=14.21.3'} cpu: [arm64] os: [linux] - libc: [glibc] '@biomejs/cli-linux-x64-musl@2.4.13': resolution: {integrity: sha512-Z601MienRgTBDza/+u2CH3RSrWoXo9rtr8NK6A4KJzqGgfxx+H3VlyLgTJ4sRo40T3pIsqpTmiOQEvYzQvBRvQ==} engines: {node: '>=14.21.3'} cpu: [x64] os: [linux] - libc: [musl] '@biomejs/cli-linux-x64@2.4.13': resolution: {integrity: sha512-Az3ZZedYRBo9EQzNnD9SxFcR1G5QsGo6VEc2hIyVPZ1rdKwee/7E9oeBBZFpE8Z44ekxsDQBqbiWGW5ShOhUSQ==} engines: {node: '>=14.21.3'} cpu: [x64] os: [linux] - libc: [glibc] '@biomejs/cli-win32-arm64@2.4.13': resolution: {integrity: sha512-Px9PS2B5/Q183bUwy/5VHqp3J2lzdOCeVGzMpphYfl8oSa7VDCqenBdqWpy6DCy/en4Rbf/Y1RieZF6dJPcc9A==} @@ -1499,105 +1489,89 @@ packages: resolution: {integrity: sha512-JznefmcK9j1JKPz8AkQDh89kjojubyfOasWBPKfzMIhPwsgDy9evpE/naJTXXXmghS1iFwR8u/kTwh/I2/+GCw==} cpu: [arm64] os: [linux] - libc: [glibc] '@img/sharp-libvips-linux-arm@1.3.1': resolution: {integrity: sha512-aGGy9aWzXgHBG7HNyQPWorZthlp7+x6fDRoPAQbGO3ThcttuTyKIx3NuSHb6zb4gBNq6/yNn9f1cy9nFKS/Vmg==} cpu: [arm] os: [linux] - libc: [glibc] '@img/sharp-libvips-linux-ppc64@1.3.1': resolution: {integrity: sha512-1EkwGNCZk6iWNCMWqrvdJ+r1j0PT1zIz60CNPhYnJlK/zyeWqlsPZIe+ocBVqPF8k/Ssee/NCk+tE9Ryrko6ng==} cpu: [ppc64] os: [linux] - libc: [glibc] '@img/sharp-libvips-linux-riscv64@1.3.1': resolution: {integrity: sha512-Ilays+w2bXdnxzxtQdmXR62u8o8GYa3eL4+Gr+1KiE4xperMZUslRaVPJwwPkzlHEjGfXAfRVAa/7CYCtSqsBw==} cpu: [riscv64] os: [linux] - libc: [glibc] '@img/sharp-libvips-linux-s390x@1.3.1': resolution: {integrity: sha512-VfBwVHQTbRoj4XlpA/KLZ7ltgMpz+4WSejFzQ+GnoImjo1PtEJ59QB2qR1xQEeRPYIkNrPIm2L4cICMvz4C2ew==} cpu: [s390x] os: [linux] - libc: [glibc] '@img/sharp-libvips-linux-x64@1.3.1': resolution: {integrity: sha512-+c8ukgwU62DS54nCAjw7keOfHUkmr0B5QHEdcOqRnodF/MNXJbVI8Eopoj4B/0H8Asr65I+A4Amrn7a85/md6A==} cpu: [x64] os: [linux] - libc: [glibc] '@img/sharp-libvips-linuxmusl-arm64@1.3.1': resolution: {integrity: sha512-qlKb/pwbkAi1WMsJrYHk7CuDrd12s27U2QnRhFYUoJNrRCmkosMTttuRFat/DDB3IlDm5qE1TJgZ4JDnHX8Ldw==} cpu: [arm64] os: [linux] - libc: [musl] '@img/sharp-libvips-linuxmusl-x64@1.3.1': resolution: {integrity: sha512-yO21HwoUVLN8Qa+/SBjQLMYwBWAVJjeGPNe+hc0OUeMeifEtJqu5a1c4HayE1nNpDih9y3/KkoltfkDodmKAlg==} cpu: [x64] os: [linux] - libc: [musl] '@img/sharp-linux-arm64@0.35.2': resolution: {integrity: sha512-af12Pnd0ZGu2HfP8NayB0kk6eC/lrfbQE6HlR4jD+34wdJ1Vw9TF6TMn6ZvffT+WgqVsl0hRbmNvz2u/23VmwA==} engines: {node: '>=20.9.0'} cpu: [arm64] os: [linux] - libc: [glibc] '@img/sharp-linux-arm@0.35.2': resolution: {integrity: sha512-SE4kzF2mepn6z+6E7L6lsV8FzuLL6IPQdyX8ZiwROAG/G8td+hP/m7FsFPwidtrF19gvajuC9l6TxAVcsA4S7A==} engines: {node: '>=20.9.0'} cpu: [arm] os: [linux] - libc: [glibc] '@img/sharp-linux-ppc64@0.35.2': resolution: {integrity: sha512-hYSBm7zcNtDCozCxQHYZJiu63b/bXsgRZuOxCIBZsStMM9Vap47iFHdbX4kCvQsblPB/k+clhELpdQJHQLSHvg==} engines: {node: '>=20.9.0'} cpu: [ppc64] os: [linux] - libc: [glibc] '@img/sharp-linux-riscv64@0.35.2': resolution: {integrity: sha512-qQt0Kc13+Hoan/Awq/qMSQw3L+RI1NCRPgD5cUJ/1WSSmIoysLOc72jlRM3E0OHN9Yr313jgeQ2T+zW+F03QFA==} engines: {node: '>=20.9.0'} cpu: [riscv64] os: [linux] - libc: [glibc] '@img/sharp-linux-s390x@0.35.2': resolution: {integrity: sha512-E4fLLfRPzDLlEeDaTzI98OFLcv++WL5ChLLMwPoVd0CIoZQqupBSNbOisPL5am9XsbQ9T84+iiMpUvbFtkunbA==} engines: {node: '>=20.9.0'} cpu: [s390x] os: [linux] - libc: [glibc] '@img/sharp-linux-x64@0.35.2': resolution: {integrity: sha512-gi0zFJJRLswfCZmHtJdikXPOc5u7qamSOS3NHedLqLd4W8Q0NqjdBr6TTRIgsfFjqfTsHFgdfvJ9LwqSgcHiAA==} engines: {node: '>=20.9.0'} cpu: [x64] os: [linux] - libc: [glibc] '@img/sharp-linuxmusl-arm64@0.35.2': resolution: {integrity: sha512-siWbOW1u6HFnFLrp0waKyW7VEf7jYvcDWdrXEFa8AkdAQgEvuu5Fz8/Y70w9EeqAdwDtfU012BhEHHaDqvQNzg==} engines: {node: '>=20.9.0'} cpu: [arm64] os: [linux] - libc: [musl] '@img/sharp-linuxmusl-x64@0.35.2': resolution: {integrity: sha512-YBqMMcjDi4QGYiSn4vNOYBhmlC4z5AXqkOUUqI2e0AFA4urNv4ESgOgwNl3K+4etQhha0twXlzeF20bbULm9Yg==} engines: {node: '>=20.9.0'} cpu: [x64] os: [linux] - libc: [musl] '@img/sharp-wasm32@0.35.2': resolution: {integrity: sha512-Mrv4JQNYVQ94xH+jzZ9r+gowleN8mv2FTgKT+PI6bx5C0G8TdNYndu161pg2i7uoBwxy2ImPMHrJOM2LZef7Bw==} @@ -1754,42 +1728,36 @@ packages: engines: {node: '>= 10.0.0'} cpu: [arm] os: [linux] - libc: [glibc] '@parcel/watcher-linux-arm-musl@2.5.6': resolution: {integrity: sha512-Ve3gUCG57nuUUSyjBq/MAM0CzArtuIOxsBdQ+ftz6ho8n7s1i9E1Nmk/xmP323r2YL0SONs1EuwqBp2u1k5fxg==} engines: {node: '>= 10.0.0'} cpu: [arm] os: [linux] - libc: [musl] '@parcel/watcher-linux-arm64-glibc@2.5.6': resolution: {integrity: sha512-f2g/DT3NhGPdBmMWYoxixqYr3v/UXcmLOYy16Bx0TM20Tchduwr4EaCbmxh1321TABqPGDpS8D/ggOTaljijOA==} engines: {node: '>= 10.0.0'} cpu: [arm64] os: [linux] - libc: [glibc] '@parcel/watcher-linux-arm64-musl@2.5.6': resolution: {integrity: sha512-qb6naMDGlbCwdhLj6hgoVKJl2odL34z2sqkC7Z6kzir8b5W65WYDpLB6R06KabvZdgoHI/zxke4b3zR0wAbDTA==} engines: {node: '>= 10.0.0'} cpu: [arm64] os: [linux] - libc: [musl] '@parcel/watcher-linux-x64-glibc@2.5.6': resolution: {integrity: sha512-kbT5wvNQlx7NaGjzPFu8nVIW1rWqV780O7ZtkjuWaPUgpv2NMFpjYERVi0UYj1msZNyCzGlaCWEtzc+exjMGbQ==} engines: {node: '>= 10.0.0'} cpu: [x64] os: [linux] - libc: [glibc] '@parcel/watcher-linux-x64-musl@2.5.6': resolution: {integrity: sha512-1JRFeC+h7RdXwldHzTsmdtYR/Ku8SylLgTU/reMuqdVD7CtLwf0VR1FqeprZ0eHQkO0vqsbvFLXUmYm/uNKJBg==} engines: {node: '>= 10.0.0'} cpu: [x64] os: [linux] - libc: [musl] '@parcel/watcher-wasm@2.5.6': resolution: {integrity: sha512-byAiBZ1t3tXQvc8dMD/eoyE7lTXYorhn+6uVW5AC+JGI1KtJC/LvDche5cfUE+qiefH+Ybq0bUCJU0aB1cSHUA==} @@ -2651,42 +2619,36 @@ packages: engines: {node: ^20.19.0 || >=22.12.0} cpu: [arm64] os: [linux] - libc: [glibc] '@rolldown/binding-linux-arm64-musl@1.2.3': resolution: {integrity: sha512-NHqjnxpsndf4MPymxteFAWHHfkTL8HjWh1KB7z23ofZ6QO2euONuxDXjat69dKZRALnGypg8k8SsK8vZJoXv1Q==} engines: {node: ^20.19.0 || >=22.12.0} cpu: [arm64] os: [linux] - libc: [musl] '@rolldown/binding-linux-ppc64-gnu@1.2.3': resolution: {integrity: sha512-6tbrbwfz5GB9DQ4Jwo6hy9v+vR31xZlvzZ6n5Xut6Hhx5PvrA9q/HsK8KMaYQp063iqZGXwNvZtYNLD7EM/x0w==} engines: {node: ^20.19.0 || >=22.12.0} cpu: [ppc64] os: [linux] - libc: [glibc] '@rolldown/binding-linux-s390x-gnu@1.2.3': resolution: {integrity: sha512-oyuXxXmoZHjXC917IAPFAAv4wWAa0cM9afk8nx1+9/jNNOX1uPf8yDA6p7G0RypOfw/X0PQt5IfoquY1um+zSg==} engines: {node: ^20.19.0 || >=22.12.0} cpu: [s390x] os: [linux] - libc: [glibc] '@rolldown/binding-linux-x64-gnu@1.2.3': resolution: {integrity: sha512-TytMwF2KVGqP2tgd0I1OY0PAv78dZRAYcF5ssDzjM34SUXCED3uXvSd5+lHoC0bTD6eEdFz7LdQNCO1y0oVk9w==} engines: {node: ^20.19.0 || >=22.12.0} cpu: [x64] os: [linux] - libc: [glibc] '@rolldown/binding-linux-x64-musl@1.2.3': resolution: {integrity: sha512-/E9m3qstrJFVPoULV25mVQblSNExY2+kBsYe4sy0Tn0yOOgJ8wZbZt3KnRbF/XeU2Gl1STKUQnDNTqhIE5MD4A==} engines: {node: ^20.19.0 || >=22.12.0} cpu: [x64] os: [linux] - libc: [musl] '@rolldown/binding-openharmony-arm64@1.2.3': resolution: {integrity: sha512-Kr0OcsoQI816i6HOl3vFHpd1K0eZyh76zgfj4c1nTyaTsd5r2Mj1lwM4R90y/qaCfmTn9eHy0SKwi98eitRxug==} @@ -2818,79 +2780,66 @@ packages: resolution: {integrity: sha512-Q8CBCCQtDFrYtXoeUXSrnFXKOnyUhx6bz+SkL6A0E7V8kAiCJ5pamq1WtbfpVGhR5TSpXY6ak3avmDc5fHTyJA==} cpu: [arm] os: [linux] - libc: [glibc] '@rollup/rollup-linux-arm-musleabihf@4.61.1': resolution: {integrity: sha512-nwnhk1581l0FBVellGcVCAT0Oi06onEA3WB53sf01VO3I0UPBkMH9sXONYME2K0ovXcNayJfNtHfm6mpJElatQ==} cpu: [arm] os: [linux] - libc: [musl] '@rollup/rollup-linux-arm64-gnu@4.61.1': resolution: {integrity: sha512-x5Xr49hwt3hdW75UOZm3395YwwzPyauktslv29KpWL/T+vVAzoT3azLcTWv0eMciBNrx+DYjH4paehHoLpPvpg==} cpu: [arm64] os: [linux] - libc: [glibc] '@rollup/rollup-linux-arm64-musl@4.61.1': resolution: {integrity: sha512-unMS3H73DpaoPyyEVPjGKleM/s0mkmsauTENpw4INQY8y4+IuLNjkueQ5QCtC0D3N38Y38yhAU8OoZ20S2Tm6w==} cpu: [arm64] os: [linux] - libc: [musl] '@rollup/rollup-linux-loong64-gnu@4.61.1': resolution: {integrity: sha512-zNZzGRnAhwjFEYmvphJRV5XaQGjs62cCmeYYHUT//NbvEnHauw+I85nGG+SiVg5ld4GX8D1IbKIX+ozITQnhMQ==} cpu: [loong64] os: [linux] - libc: [glibc] '@rollup/rollup-linux-loong64-musl@4.61.1': resolution: {integrity: sha512-LdpWGL8X209B2SIvWjqlc8VZgM6PKfontSerGepuldQmHYrAOtnMCXeJkxXGbC+PPZVOuu5czJo7fNV6aeW8rQ==} cpu: [loong64] os: [linux] - libc: [musl] '@rollup/rollup-linux-ppc64-gnu@4.61.1': resolution: {integrity: sha512-EC5kTtNaNGOmbMGqar8dvJy6y/hg99GAwjfBz++pxZhQATXGcRjd6c5en5wcbru0vkRmiMGsQKdMJOOf6sza4g==} cpu: [ppc64] os: [linux] - libc: [glibc] '@rollup/rollup-linux-ppc64-musl@4.61.1': resolution: {integrity: sha512-8hiwp6D4acEcNK78I4rP0/XtS1sknWIAMJBPdR4l6zUtyTm5KiTDr5bXmWt4foY7nAN7AThDHgkLIEZOWKbzWw==} cpu: [ppc64] os: [linux] - libc: [musl] '@rollup/rollup-linux-riscv64-gnu@4.61.1': resolution: {integrity: sha512-10dh/h/BqA7DuMPWSxkR8uks18FRwnwOEqr5zOTEl+NOwP/OMzKX8OFR/Of9xxDA7D5qef1Nzar5WDD2kCCr1g==} cpu: [riscv64] os: [linux] - libc: [glibc] '@rollup/rollup-linux-riscv64-musl@4.61.1': resolution: {integrity: sha512-YKJ5lg35DP17gcAOggnihe+APw9HLyj1Xn7gsmGumBJAUDa6NGXNixJzmkWLhcK9TOuuyQjdamzvJefkO7qHZQ==} cpu: [riscv64] os: [linux] - libc: [musl] '@rollup/rollup-linux-s390x-gnu@4.61.1': resolution: {integrity: sha512-Mlil5G2Jj6a7B3LWGctg+XPL9vdXYuzCtNXfxOQ0nPjc2m6ueUktocPGH9bnAM0bNRKb/bAWTujUU7IJQdQA+g==} cpu: [s390x] os: [linux] - libc: [glibc] '@rollup/rollup-linux-x64-gnu@4.61.1': resolution: {integrity: sha512-bVWIOIk6pV01p4CdUbPP7CJ/434z+OooYjDuFcR+44N35YvKUC66G8MGnvcWx5mWKW3g61J+t74l3Kj15Kwn2Q==} cpu: [x64] os: [linux] - libc: [glibc] '@rollup/rollup-linux-x64-musl@4.61.1': resolution: {integrity: sha512-qy5pBvZbqNFheBz61R1rzsezjm0J7O2oNGoWtGoY89SZYLUfxAJTBAqDChqAIdB4rCiIbi9nF7yZ83GnNiLwSw==} cpu: [x64] os: [linux] - libc: [musl] '@rollup/rollup-openbsd-x64@4.61.1': resolution: {integrity: sha512-E83TXjI4zm0+5f2qO+UOudaCYIhYwpJ5jq6YCZNIZ+6CbfhKrkAGezeiASBL9ElxAxFsRS9ZhESv8mfnj6TKeg==} @@ -3497,28 +3446,24 @@ packages: engines: {node: '>= 20'} cpu: [arm64] os: [linux] - libc: [glibc] '@tailwindcss/oxide-linux-arm64-musl@4.3.3': resolution: {integrity: sha512-Md44bD6veX/PC5iyF8cDVnw4HBIANZepRZZ7a8DQOvkfo5WUBwcp6iAuCUz23u+4SUkhJlD3eL7hNdW8ezd/kA==} engines: {node: '>= 20'} cpu: [arm64] os: [linux] - libc: [musl] '@tailwindcss/oxide-linux-x64-gnu@4.3.3': resolution: {integrity: sha512-tx7us1muwOKAKWao2v/GaafFeQboE6aj88vC6ziN2NCGcRm8gWUhwjzg+YdVB1e4boAtdtma4L43onunI6NS4w==} engines: {node: '>= 20'} cpu: [x64] os: [linux] - libc: [glibc] '@tailwindcss/oxide-linux-x64-musl@4.3.3': resolution: {integrity: sha512-SJxX60smvHgasZoBy11dX6YRjXJFovwWBoedhbQPOBzgFWBHGB+TVPWB9BxzR7TTxU8FQZAI2AyiNCMzFm8Img==} engines: {node: '>= 20'} cpu: [x64] os: [linux] - libc: [musl] '@tailwindcss/oxide-wasm32-wasi@4.3.3': resolution: {integrity: sha512-jx1+rPhY/5Ympkktd656HBWEBLxP7dH06losBLjjf5vgCODXvi9KhtftWcMIwTFIDqBr7cRnQkdLnAG+IOlGvQ==} @@ -3881,15 +3826,6 @@ packages: next: optional: true - '@upstash/core-analytics@0.0.10': - resolution: {integrity: sha512-7qJHGxpQgQr9/vmeS1PktEwvNAF7TI4iJDi8Pu2CFZ9YUGHZH4fOP5TfYlZ4aVxfopnELiE4BS4FBjyK7V1/xQ==} - engines: {node: '>=16.0.0'} - - '@upstash/ratelimit@2.0.8': - resolution: {integrity: sha512-YSTMBJ1YIxsoPkUMX/P4DDks/xV5YYCswWMamU8ZIfK9ly6ppjRnVOyBhMDXBmzjODm4UQKcxsJPvaeFAijp5w==} - peerDependencies: - '@upstash/redis': ^1.34.3 - '@upstash/redis@1.38.2': resolution: {integrity: sha512-RZ+JaRCVIS+ZTGnjOnDMr+/0aqDxsBb5rV6aW+Pys4SGELwr5lwE3UbLHRCHqMQ5Ulxj0b/CFBHfbmE175Otog==} @@ -5626,28 +5562,24 @@ packages: engines: {node: '>= 12.0.0'} cpu: [arm64] os: [linux] - libc: [glibc] lightningcss-linux-arm64-musl@1.32.0: resolution: {integrity: sha512-UpQkoenr4UJEzgVIYpI80lDFvRmPVg6oqboNHfoH4CQIfNA+HOrZ7Mo7KZP02dC6LjghPQJeBsvXhJod/wnIBg==} engines: {node: '>= 12.0.0'} cpu: [arm64] os: [linux] - libc: [musl] lightningcss-linux-x64-gnu@1.32.0: resolution: {integrity: sha512-V7Qr52IhZmdKPVr+Vtw8o+WLsQJYCTd8loIfpDaMRWGUZfBOYEJeyJIkqGIDMZPwPx24pUMfwSxxI8phr/MbOA==} engines: {node: '>= 12.0.0'} cpu: [x64] os: [linux] - libc: [glibc] lightningcss-linux-x64-musl@1.32.0: resolution: {integrity: sha512-bYcLp+Vb0awsiXg/80uCRezCYHNg1/l3mt0gzHnWV9XP1W5sKa5/TCdGWaR/zBM2PeF/HbsQv/j2URNOiVuxWg==} engines: {node: '>= 12.0.0'} cpu: [x64] os: [linux] - libc: [musl] lightningcss-win32-arm64-msvc@1.32.0: resolution: {integrity: sha512-8SbC8BR40pS6baCM8sbtYDSwEVQd4JlFTOlaD3gWGHfThTcABnNDBda6eTZeqbofalIJhFx0qKzgHJmcPTnGdw==} @@ -7520,20 +7452,20 @@ snapshots: '@babel/compat-data@7.29.7': {} - '@babel/core@7.29.7(supports-color@10.2.2)': + '@babel/core@7.29.7': dependencies: '@babel/code-frame': 7.29.7 '@babel/generator': 7.29.7 '@babel/helper-compilation-targets': 7.29.7 - '@babel/helper-module-transforms': 7.29.7(@babel/core@7.29.7(supports-color@10.2.2))(supports-color@10.2.2) + '@babel/helper-module-transforms': 7.29.7(@babel/core@7.29.7) '@babel/helpers': 7.29.7 '@babel/parser': 7.29.7 '@babel/template': 7.29.7 - '@babel/traverse': 7.29.7(supports-color@10.2.2) + '@babel/traverse': 7.29.7 '@babel/types': 7.29.7 '@jridgewell/remapping': 2.3.5 convert-source-map: 2.0.0 - debug: 4.4.3(supports-color@10.2.2) + debug: 4.4.3 gensync: 1.0.0-beta.2 json5: 2.2.3 semver: 6.3.1 @@ -7560,41 +7492,41 @@ snapshots: lru-cache: 5.1.1 semver: 6.3.1 - '@babel/helper-create-class-features-plugin@7.29.7(@babel/core@7.29.7(supports-color@10.2.2))(supports-color@10.2.2)': + '@babel/helper-create-class-features-plugin@7.29.7(@babel/core@7.29.7)': dependencies: - '@babel/core': 7.29.7(supports-color@10.2.2) + '@babel/core': 7.29.7 '@babel/helper-annotate-as-pure': 7.29.7 - '@babel/helper-member-expression-to-functions': 7.29.7(supports-color@10.2.2) + '@babel/helper-member-expression-to-functions': 7.29.7 '@babel/helper-optimise-call-expression': 7.29.7 - '@babel/helper-replace-supers': 7.29.7(@babel/core@7.29.7(supports-color@10.2.2))(supports-color@10.2.2) - '@babel/helper-skip-transparent-expression-wrappers': 7.29.7(supports-color@10.2.2) - '@babel/traverse': 7.29.7(supports-color@10.2.2) + '@babel/helper-replace-supers': 7.29.7(@babel/core@7.29.7) + '@babel/helper-skip-transparent-expression-wrappers': 7.29.7 + '@babel/traverse': 7.29.7 semver: 6.3.1 transitivePeerDependencies: - supports-color '@babel/helper-globals@7.29.7': {} - '@babel/helper-member-expression-to-functions@7.29.7(supports-color@10.2.2)': + '@babel/helper-member-expression-to-functions@7.29.7': dependencies: - '@babel/traverse': 7.29.7(supports-color@10.2.2) + '@babel/traverse': 7.29.7 '@babel/types': 7.29.7 transitivePeerDependencies: - supports-color - '@babel/helper-module-imports@7.29.7(supports-color@10.2.2)': + '@babel/helper-module-imports@7.29.7': dependencies: - '@babel/traverse': 7.29.7(supports-color@10.2.2) + '@babel/traverse': 7.29.7 '@babel/types': 7.29.7 transitivePeerDependencies: - supports-color - '@babel/helper-module-transforms@7.29.7(@babel/core@7.29.7(supports-color@10.2.2))(supports-color@10.2.2)': + '@babel/helper-module-transforms@7.29.7(@babel/core@7.29.7)': dependencies: - '@babel/core': 7.29.7(supports-color@10.2.2) - '@babel/helper-module-imports': 7.29.7(supports-color@10.2.2) + '@babel/core': 7.29.7 + '@babel/helper-module-imports': 7.29.7 '@babel/helper-validator-identifier': 7.29.7 - '@babel/traverse': 7.29.7(supports-color@10.2.2) + '@babel/traverse': 7.29.7 transitivePeerDependencies: - supports-color @@ -7604,18 +7536,18 @@ snapshots: '@babel/helper-plugin-utils@7.29.7': {} - '@babel/helper-replace-supers@7.29.7(@babel/core@7.29.7(supports-color@10.2.2))(supports-color@10.2.2)': + '@babel/helper-replace-supers@7.29.7(@babel/core@7.29.7)': dependencies: - '@babel/core': 7.29.7(supports-color@10.2.2) - '@babel/helper-member-expression-to-functions': 7.29.7(supports-color@10.2.2) + '@babel/core': 7.29.7 + '@babel/helper-member-expression-to-functions': 7.29.7 '@babel/helper-optimise-call-expression': 7.29.7 - '@babel/traverse': 7.29.7(supports-color@10.2.2) + '@babel/traverse': 7.29.7 transitivePeerDependencies: - supports-color - '@babel/helper-skip-transparent-expression-wrappers@7.29.7(supports-color@10.2.2)': + '@babel/helper-skip-transparent-expression-wrappers@7.29.7': dependencies: - '@babel/traverse': 7.29.7(supports-color@10.2.2) + '@babel/traverse': 7.29.7 '@babel/types': 7.29.7 transitivePeerDependencies: - supports-color @@ -7635,53 +7567,53 @@ snapshots: dependencies: '@babel/types': 7.29.7 - '@babel/plugin-syntax-jsx@7.29.7(@babel/core@7.29.7(supports-color@10.2.2))': + '@babel/plugin-syntax-jsx@7.29.7(@babel/core@7.29.7)': dependencies: - '@babel/core': 7.29.7(supports-color@10.2.2) + '@babel/core': 7.29.7 '@babel/helper-plugin-utils': 7.29.7 - '@babel/plugin-syntax-typescript@7.29.7(@babel/core@7.29.7(supports-color@10.2.2))': + '@babel/plugin-syntax-typescript@7.29.7(@babel/core@7.29.7)': dependencies: - '@babel/core': 7.29.7(supports-color@10.2.2) + '@babel/core': 7.29.7 '@babel/helper-plugin-utils': 7.29.7 - '@babel/plugin-transform-modules-commonjs@7.29.7(@babel/core@7.29.7(supports-color@10.2.2))(supports-color@10.2.2)': + '@babel/plugin-transform-modules-commonjs@7.29.7(@babel/core@7.29.7)': dependencies: - '@babel/core': 7.29.7(supports-color@10.2.2) - '@babel/helper-module-transforms': 7.29.7(@babel/core@7.29.7(supports-color@10.2.2))(supports-color@10.2.2) + '@babel/core': 7.29.7 + '@babel/helper-module-transforms': 7.29.7(@babel/core@7.29.7) '@babel/helper-plugin-utils': 7.29.7 transitivePeerDependencies: - supports-color - '@babel/plugin-transform-react-jsx-self@7.29.7(@babel/core@7.29.7(supports-color@10.2.2))': + '@babel/plugin-transform-react-jsx-self@7.29.7(@babel/core@7.29.7)': dependencies: - '@babel/core': 7.29.7(supports-color@10.2.2) + '@babel/core': 7.29.7 '@babel/helper-plugin-utils': 7.29.7 - '@babel/plugin-transform-react-jsx-source@7.29.7(@babel/core@7.29.7(supports-color@10.2.2))': + '@babel/plugin-transform-react-jsx-source@7.29.7(@babel/core@7.29.7)': dependencies: - '@babel/core': 7.29.7(supports-color@10.2.2) + '@babel/core': 7.29.7 '@babel/helper-plugin-utils': 7.29.7 - '@babel/plugin-transform-typescript@7.29.7(@babel/core@7.29.7(supports-color@10.2.2))(supports-color@10.2.2)': + '@babel/plugin-transform-typescript@7.29.7(@babel/core@7.29.7)': dependencies: - '@babel/core': 7.29.7(supports-color@10.2.2) + '@babel/core': 7.29.7 '@babel/helper-annotate-as-pure': 7.29.7 - '@babel/helper-create-class-features-plugin': 7.29.7(@babel/core@7.29.7(supports-color@10.2.2))(supports-color@10.2.2) + '@babel/helper-create-class-features-plugin': 7.29.7(@babel/core@7.29.7) '@babel/helper-plugin-utils': 7.29.7 - '@babel/helper-skip-transparent-expression-wrappers': 7.29.7(supports-color@10.2.2) - '@babel/plugin-syntax-typescript': 7.29.7(@babel/core@7.29.7(supports-color@10.2.2)) + '@babel/helper-skip-transparent-expression-wrappers': 7.29.7 + '@babel/plugin-syntax-typescript': 7.29.7(@babel/core@7.29.7) transitivePeerDependencies: - supports-color - '@babel/preset-typescript@7.29.7(@babel/core@7.29.7(supports-color@10.2.2))(supports-color@10.2.2)': + '@babel/preset-typescript@7.29.7(@babel/core@7.29.7)': dependencies: - '@babel/core': 7.29.7(supports-color@10.2.2) + '@babel/core': 7.29.7 '@babel/helper-plugin-utils': 7.29.7 '@babel/helper-validator-option': 7.29.7 - '@babel/plugin-syntax-jsx': 7.29.7(@babel/core@7.29.7(supports-color@10.2.2)) - '@babel/plugin-transform-modules-commonjs': 7.29.7(@babel/core@7.29.7(supports-color@10.2.2))(supports-color@10.2.2) - '@babel/plugin-transform-typescript': 7.29.7(@babel/core@7.29.7(supports-color@10.2.2))(supports-color@10.2.2) + '@babel/plugin-syntax-jsx': 7.29.7(@babel/core@7.29.7) + '@babel/plugin-transform-modules-commonjs': 7.29.7(@babel/core@7.29.7) + '@babel/plugin-transform-typescript': 7.29.7(@babel/core@7.29.7) transitivePeerDependencies: - supports-color @@ -7693,7 +7625,7 @@ snapshots: '@babel/parser': 7.29.7 '@babel/types': 7.29.7 - '@babel/traverse@7.29.7(supports-color@10.2.2)': + '@babel/traverse@7.29.7': dependencies: '@babel/code-frame': 7.29.7 '@babel/generator': 7.29.7 @@ -7701,7 +7633,7 @@ snapshots: '@babel/parser': 7.29.7 '@babel/template': 7.29.7 '@babel/types': 7.29.7 - debug: 4.4.3(supports-color@10.2.2) + debug: 4.4.3 transitivePeerDependencies: - supports-color @@ -7794,16 +7726,16 @@ snapshots: react: 19.2.8 react-dom: 19.2.8(react@19.2.8) - '@clerk/ui@1.26.0(@solana/web3.js@1.98.4(bufferutil@4.1.0)(typescript@5.9.3)(utf-8-validate@6.0.6))(@types/react@19.2.17)(bs58@6.0.0)(bufferutil@4.1.0)(react-dom@19.2.8(react@19.2.8))(react-native@0.86.0(@babel/core@7.29.7(supports-color@10.2.2))(@types/react@19.2.17)(bufferutil@4.1.0)(react@19.2.8)(supports-color@10.2.2)(utf-8-validate@6.0.6))(react@19.2.8)(supports-color@10.2.2)(typescript@5.9.3)(utf-8-validate@6.0.6)': + '@clerk/ui@1.26.0(@solana/web3.js@1.98.4(bufferutil@4.1.0)(typescript@5.9.3)(utf-8-validate@6.0.6))(@types/react@19.2.17)(bs58@6.0.0)(bufferutil@4.1.0)(react-dom@19.2.8(react@19.2.8))(react-native@0.86.0(@babel/core@7.29.7)(@types/react@19.2.17)(bufferutil@4.1.0)(react@19.2.8)(utf-8-validate@6.0.6))(react@19.2.8)(typescript@5.9.3)(utf-8-validate@6.0.6)': dependencies: '@clerk/localizations': 4.13.8(react-dom@19.2.8(react@19.2.8))(react@19.2.8) '@clerk/shared': 4.25.8(react-dom@19.2.8(react@19.2.8))(react@19.2.8) '@emotion/cache': 11.11.0 - '@emotion/react': 11.11.1(@types/react@19.2.17)(react@19.2.8)(supports-color@10.2.2) + '@emotion/react': 11.11.1(@types/react@19.2.17)(react@19.2.8) '@floating-ui/react': 0.27.12(react-dom@19.2.8(react@19.2.8))(react@19.2.8) '@formkit/auto-animate': 0.8.4 '@solana/wallet-adapter-base': 0.9.27(@solana/web3.js@1.98.4(bufferutil@4.1.0)(typescript@5.9.3)(utf-8-validate@6.0.6)) - '@solana/wallet-adapter-react': 0.15.39(@solana/web3.js@1.98.4(bufferutil@4.1.0)(typescript@5.9.3)(utf-8-validate@6.0.6))(bs58@6.0.0)(bufferutil@4.1.0)(react-native@0.86.0(@babel/core@7.29.7(supports-color@10.2.2))(@types/react@19.2.17)(bufferutil@4.1.0)(react@19.2.8)(supports-color@10.2.2)(utf-8-validate@6.0.6))(react@19.2.8)(typescript@5.9.3)(utf-8-validate@6.0.6) + '@solana/wallet-adapter-react': 0.15.39(@solana/web3.js@1.98.4(bufferutil@4.1.0)(typescript@5.9.3)(utf-8-validate@6.0.6))(bs58@6.0.0)(bufferutil@4.1.0)(react-native@0.86.0(@babel/core@7.29.7)(@types/react@19.2.17)(bufferutil@4.1.0)(react@19.2.8)(utf-8-validate@6.0.6))(react@19.2.8)(typescript@5.9.3)(utf-8-validate@6.0.6) '@solana/wallet-standard': 1.1.4(@solana/wallet-adapter-base@0.9.27(@solana/web3.js@1.98.4(bufferutil@4.1.0)(typescript@5.9.3)(utf-8-validate@6.0.6)))(@solana/web3.js@1.98.4(bufferutil@4.1.0)(typescript@5.9.3)(utf-8-validate@6.0.6))(bs58@6.0.0)(react@19.2.8) '@stylexjs/stylex': 0.19.0 '@swc/helpers': 0.5.21 @@ -7914,9 +7846,9 @@ snapshots: tslib: 2.8.1 optional: true - '@emotion/babel-plugin@11.13.5(supports-color@10.2.2)': + '@emotion/babel-plugin@11.13.5': dependencies: - '@babel/helper-module-imports': 7.29.7(supports-color@10.2.2) + '@babel/helper-module-imports': 7.29.7 '@babel/runtime': 7.29.7 '@emotion/hash': 0.9.2 '@emotion/memoize': 0.9.0 @@ -7944,10 +7876,10 @@ snapshots: '@emotion/memoize@0.9.0': {} - '@emotion/react@11.11.1(@types/react@19.2.17)(react@19.2.8)(supports-color@10.2.2)': + '@emotion/react@11.11.1(@types/react@19.2.17)(react@19.2.8)': dependencies: '@babel/runtime': 7.29.7 - '@emotion/babel-plugin': 11.13.5(supports-color@10.2.2) + '@emotion/babel-plugin': 11.13.5 '@emotion/cache': 11.11.0 '@emotion/serialize': 1.3.3 '@emotion/use-insertion-effect-with-fallbacks': 1.2.0(react@19.2.8) @@ -8403,14 +8335,14 @@ snapshots: '@formkit/auto-animate@0.8.4': {} - '@google/genai@1.52.0(@modelcontextprotocol/sdk@1.29.0(supports-color@10.2.2)(zod@3.25.76))(bufferutil@4.1.0)(supports-color@10.2.2)(utf-8-validate@6.0.6)': + '@google/genai@1.52.0(@modelcontextprotocol/sdk@1.29.0(zod@3.25.76))(bufferutil@4.1.0)(utf-8-validate@6.0.6)': dependencies: - google-auth-library: 10.7.0(supports-color@10.2.2) + google-auth-library: 10.7.0 p-retry: 4.6.2 protobufjs: 7.6.2 ws: 8.21.0(bufferutil@4.1.0)(utf-8-validate@6.0.6) optionalDependencies: - '@modelcontextprotocol/sdk': 1.29.0(supports-color@10.2.2)(zod@3.25.76) + '@modelcontextprotocol/sdk': 1.29.0(zod@3.25.76) transitivePeerDependencies: - bufferutil - supports-color @@ -8585,11 +8517,11 @@ snapshots: '@jridgewell/resolve-uri': 3.1.2 '@jridgewell/sourcemap-codec': 1.5.5 - '@mapbox/node-pre-gyp@2.0.3(supports-color@10.2.2)': + '@mapbox/node-pre-gyp@2.0.3': dependencies: consola: 3.4.2 detect-libc: 2.1.2 - https-proxy-agent: 7.0.6(supports-color@10.2.2) + https-proxy-agent: 7.0.6 node-fetch: 2.7.0 nopt: 8.1.0 semver: 7.8.5 @@ -8598,7 +8530,7 @@ snapshots: - encoding - supports-color - '@modelcontextprotocol/sdk@1.29.0(supports-color@10.2.2)(zod@3.25.76)': + '@modelcontextprotocol/sdk@1.29.0(zod@3.25.76)': dependencies: '@hono/node-server': 1.19.15(hono@4.12.32) ajv: 8.20.0 @@ -8608,8 +8540,8 @@ snapshots: cross-spawn: 7.0.6 eventsource: 3.0.7 eventsource-parser: 3.1.0 - express: 5.2.1(supports-color@10.2.2) - express-rate-limit: 8.6.0(express@5.2.1(supports-color@10.2.2))(supports-color@10.2.2) + express: 5.2.1 + express-rate-limit: 8.6.0(express@5.2.1) hono: 4.12.32 jose: 6.2.4 json-schema-typed: 8.0.2 @@ -9512,17 +9444,17 @@ snapshots: '@radix-ui/rect@1.1.3': {} - '@react-native-async-storage/async-storage@1.24.0(react-native@0.86.0(@babel/core@7.29.7(supports-color@10.2.2))(@types/react@19.2.17)(bufferutil@4.1.0)(react@19.2.8)(supports-color@10.2.2)(utf-8-validate@6.0.6))': + '@react-native-async-storage/async-storage@1.24.0(react-native@0.86.0(@babel/core@7.29.7)(@types/react@19.2.17)(bufferutil@4.1.0)(react@19.2.8)(utf-8-validate@6.0.6))': dependencies: merge-options: 3.0.4 - react-native: 0.86.0(@babel/core@7.29.7(supports-color@10.2.2))(@types/react@19.2.17)(bufferutil@4.1.0)(react@19.2.8)(supports-color@10.2.2)(utf-8-validate@6.0.6) + react-native: 0.86.0(@babel/core@7.29.7)(@types/react@19.2.17)(bufferutil@4.1.0)(react@19.2.8)(utf-8-validate@6.0.6) optional: true '@react-native/assets-registry@0.86.0': {} - '@react-native/codegen@0.86.0(@babel/core@7.29.7(supports-color@10.2.2))': + '@react-native/codegen@0.86.0(@babel/core@7.29.7)': dependencies: - '@babel/core': 7.29.7(supports-color@10.2.2) + '@babel/core': 7.29.7 '@babel/parser': 7.29.7 hermes-parser: 0.36.0 invariant: 2.2.4 @@ -9530,13 +9462,13 @@ snapshots: tinyglobby: 0.2.17 yargs: 17.7.2 - '@react-native/community-cli-plugin@0.86.0(bufferutil@4.1.0)(supports-color@10.2.2)(utf-8-validate@6.0.6)': + '@react-native/community-cli-plugin@0.86.0(bufferutil@4.1.0)(utf-8-validate@6.0.6)': dependencies: - '@react-native/dev-middleware': 0.86.0(bufferutil@4.1.0)(supports-color@10.2.2)(utf-8-validate@6.0.6) - debug: 4.4.3(supports-color@10.2.2) + '@react-native/dev-middleware': 0.86.0(bufferutil@4.1.0)(utf-8-validate@6.0.6) + debug: 4.4.3 invariant: 2.2.4 - metro: 0.84.4(bufferutil@4.1.0)(supports-color@10.2.2)(utf-8-validate@6.0.6) - metro-config: 0.84.4(bufferutil@4.1.0)(supports-color@10.2.2)(utf-8-validate@6.0.6) + metro: 0.84.4(bufferutil@4.1.0)(utf-8-validate@6.0.6) + metro-config: 0.84.4(bufferutil@4.1.0)(utf-8-validate@6.0.6) metro-core: 0.84.4 semver: 7.8.5 transitivePeerDependencies: @@ -9546,27 +9478,27 @@ snapshots: '@react-native/debugger-frontend@0.86.0': {} - '@react-native/debugger-shell@0.86.0(supports-color@10.2.2)': + '@react-native/debugger-shell@0.86.0': dependencies: cross-spawn: 7.0.6 - debug: 4.4.3(supports-color@10.2.2) + debug: 4.4.3 fb-dotslash: 0.5.8 transitivePeerDependencies: - supports-color - '@react-native/dev-middleware@0.86.0(bufferutil@4.1.0)(supports-color@10.2.2)(utf-8-validate@6.0.6)': + '@react-native/dev-middleware@0.86.0(bufferutil@4.1.0)(utf-8-validate@6.0.6)': dependencies: '@isaacs/ttlcache': 1.4.1 '@react-native/debugger-frontend': 0.86.0 - '@react-native/debugger-shell': 0.86.0(supports-color@10.2.2) - chrome-launcher: 0.15.2(supports-color@10.2.2) - chromium-edge-launcher: 0.3.0(supports-color@10.2.2) - connect: 3.7.0(supports-color@10.2.2) - debug: 4.4.3(supports-color@10.2.2) + '@react-native/debugger-shell': 0.86.0 + chrome-launcher: 0.15.2 + chromium-edge-launcher: 0.3.0 + connect: 3.7.0 + debug: 4.4.3 invariant: 2.2.4 nullthrows: 1.1.1 open: 7.4.2 - serve-static: 1.16.3(supports-color@10.2.2) + serve-static: 1.16.3 ws: 7.5.11(bufferutil@4.1.0)(utf-8-validate@6.0.6) transitivePeerDependencies: - bufferutil @@ -9579,12 +9511,12 @@ snapshots: '@react-native/normalize-colors@0.86.0': {} - '@react-native/virtualized-lists@0.86.0(@types/react@19.2.17)(react-native@0.86.0(@babel/core@7.29.7(supports-color@10.2.2))(@types/react@19.2.17)(bufferutil@4.1.0)(react@19.2.8)(supports-color@10.2.2)(utf-8-validate@6.0.6))(react@19.2.8)': + '@react-native/virtualized-lists@0.86.0(@types/react@19.2.17)(react-native@0.86.0(@babel/core@7.29.7)(@types/react@19.2.17)(bufferutil@4.1.0)(react@19.2.8)(utf-8-validate@6.0.6))(react@19.2.8)': dependencies: invariant: 2.2.4 nullthrows: 1.1.1 react: 19.2.8 - react-native: 0.86.0(@babel/core@7.29.7(supports-color@10.2.2))(@types/react@19.2.17)(bufferutil@4.1.0)(react@19.2.8)(supports-color@10.2.2)(utf-8-validate@6.0.6) + react-native: 0.86.0(@babel/core@7.29.7)(@types/react@19.2.17)(bufferutil@4.1.0)(react@19.2.8)(utf-8-validate@6.0.6) optionalDependencies: '@types/react': 19.2.17 @@ -9780,9 +9712,9 @@ snapshots: '@sindresorhus/merge-streams@4.0.0': {} - '@solana-mobile/mobile-wallet-adapter-protocol-web3js@2.2.9(@solana/web3.js@1.98.4(bufferutil@4.1.0)(typescript@5.9.3)(utf-8-validate@6.0.6))(bufferutil@4.1.0)(react-native@0.86.0(@babel/core@7.29.7(supports-color@10.2.2))(@types/react@19.2.17)(bufferutil@4.1.0)(react@19.2.8)(supports-color@10.2.2)(utf-8-validate@6.0.6))(typescript@5.9.3)(utf-8-validate@6.0.6)': + '@solana-mobile/mobile-wallet-adapter-protocol-web3js@2.2.9(@solana/web3.js@1.98.4(bufferutil@4.1.0)(typescript@5.9.3)(utf-8-validate@6.0.6))(bufferutil@4.1.0)(react-native@0.86.0(@babel/core@7.29.7)(@types/react@19.2.17)(bufferutil@4.1.0)(react@19.2.8)(utf-8-validate@6.0.6))(typescript@5.9.3)(utf-8-validate@6.0.6)': dependencies: - '@solana-mobile/mobile-wallet-adapter-protocol': 2.2.9(bufferutil@4.1.0)(react-native@0.86.0(@babel/core@7.29.7(supports-color@10.2.2))(@types/react@19.2.17)(bufferutil@4.1.0)(react@19.2.8)(supports-color@10.2.2)(utf-8-validate@6.0.6))(typescript@5.9.3)(utf-8-validate@6.0.6) + '@solana-mobile/mobile-wallet-adapter-protocol': 2.2.9(bufferutil@4.1.0)(react-native@0.86.0(@babel/core@7.29.7)(@types/react@19.2.17)(bufferutil@4.1.0)(react@19.2.8)(utf-8-validate@6.0.6))(typescript@5.9.3)(utf-8-validate@6.0.6) '@solana/web3.js': 1.98.4(bufferutil@4.1.0)(typescript@5.9.3)(utf-8-validate@6.0.6) transitivePeerDependencies: - bufferutil @@ -9791,41 +9723,41 @@ snapshots: - typescript - utf-8-validate - '@solana-mobile/mobile-wallet-adapter-protocol@2.2.9(bufferutil@4.1.0)(react-native@0.86.0(@babel/core@7.29.7(supports-color@10.2.2))(@types/react@19.2.17)(bufferutil@4.1.0)(react@19.2.8)(supports-color@10.2.2)(utf-8-validate@6.0.6))(typescript@5.9.3)(utf-8-validate@6.0.6)': + '@solana-mobile/mobile-wallet-adapter-protocol@2.2.9(bufferutil@4.1.0)(react-native@0.86.0(@babel/core@7.29.7)(@types/react@19.2.17)(bufferutil@4.1.0)(react@19.2.8)(utf-8-validate@6.0.6))(typescript@5.9.3)(utf-8-validate@6.0.6)': dependencies: '@solana/kit': 6.10.0(bufferutil@4.1.0)(typescript@5.9.3)(utf-8-validate@6.0.6) '@solana/wallet-standard-features': 1.4.0 '@solana/wallet-standard-util': 1.1.3 '@wallet-standard/core': 1.1.2 - react-native: 0.86.0(@babel/core@7.29.7(supports-color@10.2.2))(@types/react@19.2.17)(bufferutil@4.1.0)(react@19.2.8)(supports-color@10.2.2)(utf-8-validate@6.0.6) + react-native: 0.86.0(@babel/core@7.29.7)(@types/react@19.2.17)(bufferutil@4.1.0)(react@19.2.8)(utf-8-validate@6.0.6) transitivePeerDependencies: - bufferutil - fastestsmallesttextencoderdecoder - typescript - utf-8-validate - '@solana-mobile/wallet-adapter-mobile@2.2.9(@solana/web3.js@1.98.4(bufferutil@4.1.0)(typescript@5.9.3)(utf-8-validate@6.0.6))(bufferutil@4.1.0)(react-native@0.86.0(@babel/core@7.29.7(supports-color@10.2.2))(@types/react@19.2.17)(bufferutil@4.1.0)(react@19.2.8)(supports-color@10.2.2)(utf-8-validate@6.0.6))(typescript@5.9.3)(utf-8-validate@6.0.6)': + '@solana-mobile/wallet-adapter-mobile@2.2.9(@solana/web3.js@1.98.4(bufferutil@4.1.0)(typescript@5.9.3)(utf-8-validate@6.0.6))(bufferutil@4.1.0)(react-native@0.86.0(@babel/core@7.29.7)(@types/react@19.2.17)(bufferutil@4.1.0)(react@19.2.8)(utf-8-validate@6.0.6))(typescript@5.9.3)(utf-8-validate@6.0.6)': dependencies: - '@solana-mobile/mobile-wallet-adapter-protocol': 2.2.9(bufferutil@4.1.0)(react-native@0.86.0(@babel/core@7.29.7(supports-color@10.2.2))(@types/react@19.2.17)(bufferutil@4.1.0)(react@19.2.8)(supports-color@10.2.2)(utf-8-validate@6.0.6))(typescript@5.9.3)(utf-8-validate@6.0.6) - '@solana-mobile/mobile-wallet-adapter-protocol-web3js': 2.2.9(@solana/web3.js@1.98.4(bufferutil@4.1.0)(typescript@5.9.3)(utf-8-validate@6.0.6))(bufferutil@4.1.0)(react-native@0.86.0(@babel/core@7.29.7(supports-color@10.2.2))(@types/react@19.2.17)(bufferutil@4.1.0)(react@19.2.8)(supports-color@10.2.2)(utf-8-validate@6.0.6))(typescript@5.9.3)(utf-8-validate@6.0.6) - '@solana-mobile/wallet-standard-mobile': 0.5.3(bufferutil@4.1.0)(react-native@0.86.0(@babel/core@7.29.7(supports-color@10.2.2))(@types/react@19.2.17)(bufferutil@4.1.0)(react@19.2.8)(supports-color@10.2.2)(utf-8-validate@6.0.6))(typescript@5.9.3)(utf-8-validate@6.0.6) + '@solana-mobile/mobile-wallet-adapter-protocol': 2.2.9(bufferutil@4.1.0)(react-native@0.86.0(@babel/core@7.29.7)(@types/react@19.2.17)(bufferutil@4.1.0)(react@19.2.8)(utf-8-validate@6.0.6))(typescript@5.9.3)(utf-8-validate@6.0.6) + '@solana-mobile/mobile-wallet-adapter-protocol-web3js': 2.2.9(@solana/web3.js@1.98.4(bufferutil@4.1.0)(typescript@5.9.3)(utf-8-validate@6.0.6))(bufferutil@4.1.0)(react-native@0.86.0(@babel/core@7.29.7)(@types/react@19.2.17)(bufferutil@4.1.0)(react@19.2.8)(utf-8-validate@6.0.6))(typescript@5.9.3)(utf-8-validate@6.0.6) + '@solana-mobile/wallet-standard-mobile': 0.5.3(bufferutil@4.1.0)(react-native@0.86.0(@babel/core@7.29.7)(@types/react@19.2.17)(bufferutil@4.1.0)(react@19.2.8)(utf-8-validate@6.0.6))(typescript@5.9.3)(utf-8-validate@6.0.6) '@solana/wallet-adapter-base': 0.9.27(@solana/web3.js@1.98.4(bufferutil@4.1.0)(typescript@5.9.3)(utf-8-validate@6.0.6)) '@solana/wallet-standard-features': 1.4.0 '@solana/web3.js': 1.98.4(bufferutil@4.1.0)(typescript@5.9.3)(utf-8-validate@6.0.6) '@wallet-standard/core': 1.1.2 - react-native: 0.86.0(@babel/core@7.29.7(supports-color@10.2.2))(@types/react@19.2.17)(bufferutil@4.1.0)(react@19.2.8)(supports-color@10.2.2)(utf-8-validate@6.0.6) + react-native: 0.86.0(@babel/core@7.29.7)(@types/react@19.2.17)(bufferutil@4.1.0)(react@19.2.8)(utf-8-validate@6.0.6) tslib: 2.8.1 optionalDependencies: - '@react-native-async-storage/async-storage': 1.24.0(react-native@0.86.0(@babel/core@7.29.7(supports-color@10.2.2))(@types/react@19.2.17)(bufferutil@4.1.0)(react@19.2.8)(supports-color@10.2.2)(utf-8-validate@6.0.6)) + '@react-native-async-storage/async-storage': 1.24.0(react-native@0.86.0(@babel/core@7.29.7)(@types/react@19.2.17)(bufferutil@4.1.0)(react@19.2.8)(utf-8-validate@6.0.6)) transitivePeerDependencies: - bufferutil - fastestsmallesttextencoderdecoder - typescript - utf-8-validate - '@solana-mobile/wallet-standard-mobile@0.5.3(bufferutil@4.1.0)(react-native@0.86.0(@babel/core@7.29.7(supports-color@10.2.2))(@types/react@19.2.17)(bufferutil@4.1.0)(react@19.2.8)(supports-color@10.2.2)(utf-8-validate@6.0.6))(typescript@5.9.3)(utf-8-validate@6.0.6)': + '@solana-mobile/wallet-standard-mobile@0.5.3(bufferutil@4.1.0)(react-native@0.86.0(@babel/core@7.29.7)(@types/react@19.2.17)(bufferutil@4.1.0)(react@19.2.8)(utf-8-validate@6.0.6))(typescript@5.9.3)(utf-8-validate@6.0.6)': dependencies: - '@solana-mobile/mobile-wallet-adapter-protocol': 2.2.9(bufferutil@4.1.0)(react-native@0.86.0(@babel/core@7.29.7(supports-color@10.2.2))(@types/react@19.2.17)(bufferutil@4.1.0)(react@19.2.8)(supports-color@10.2.2)(utf-8-validate@6.0.6))(typescript@5.9.3)(utf-8-validate@6.0.6) + '@solana-mobile/mobile-wallet-adapter-protocol': 2.2.9(bufferutil@4.1.0)(react-native@0.86.0(@babel/core@7.29.7)(@types/react@19.2.17)(bufferutil@4.1.0)(react@19.2.8)(utf-8-validate@6.0.6))(typescript@5.9.3)(utf-8-validate@6.0.6) '@solana/wallet-standard-chains': 1.1.2 '@solana/wallet-standard-features': 1.4.0 '@wallet-standard/base': 1.1.1 @@ -9834,7 +9766,7 @@ snapshots: qrcode: 1.5.4 tslib: 2.8.1 optionalDependencies: - '@react-native-async-storage/async-storage': 1.24.0(react-native@0.86.0(@babel/core@7.29.7(supports-color@10.2.2))(@types/react@19.2.17)(bufferutil@4.1.0)(react@19.2.8)(supports-color@10.2.2)(utf-8-validate@6.0.6)) + '@react-native-async-storage/async-storage': 1.24.0(react-native@0.86.0(@babel/core@7.29.7)(@types/react@19.2.17)(bufferutil@4.1.0)(react@19.2.8)(utf-8-validate@6.0.6)) transitivePeerDependencies: - bufferutil - fastestsmallesttextencoderdecoder @@ -10342,9 +10274,9 @@ snapshots: '@wallet-standard/features': 1.1.1 eventemitter3: 5.0.4 - '@solana/wallet-adapter-react@0.15.39(@solana/web3.js@1.98.4(bufferutil@4.1.0)(typescript@5.9.3)(utf-8-validate@6.0.6))(bs58@6.0.0)(bufferutil@4.1.0)(react-native@0.86.0(@babel/core@7.29.7(supports-color@10.2.2))(@types/react@19.2.17)(bufferutil@4.1.0)(react@19.2.8)(supports-color@10.2.2)(utf-8-validate@6.0.6))(react@19.2.8)(typescript@5.9.3)(utf-8-validate@6.0.6)': + '@solana/wallet-adapter-react@0.15.39(@solana/web3.js@1.98.4(bufferutil@4.1.0)(typescript@5.9.3)(utf-8-validate@6.0.6))(bs58@6.0.0)(bufferutil@4.1.0)(react-native@0.86.0(@babel/core@7.29.7)(@types/react@19.2.17)(bufferutil@4.1.0)(react@19.2.8)(utf-8-validate@6.0.6))(react@19.2.8)(typescript@5.9.3)(utf-8-validate@6.0.6)': dependencies: - '@solana-mobile/wallet-adapter-mobile': 2.2.9(@solana/web3.js@1.98.4(bufferutil@4.1.0)(typescript@5.9.3)(utf-8-validate@6.0.6))(bufferutil@4.1.0)(react-native@0.86.0(@babel/core@7.29.7(supports-color@10.2.2))(@types/react@19.2.17)(bufferutil@4.1.0)(react@19.2.8)(supports-color@10.2.2)(utf-8-validate@6.0.6))(typescript@5.9.3)(utf-8-validate@6.0.6) + '@solana-mobile/wallet-adapter-mobile': 2.2.9(@solana/web3.js@1.98.4(bufferutil@4.1.0)(typescript@5.9.3)(utf-8-validate@6.0.6))(bufferutil@4.1.0)(react-native@0.86.0(@babel/core@7.29.7)(@types/react@19.2.17)(bufferutil@4.1.0)(react@19.2.8)(utf-8-validate@6.0.6))(typescript@5.9.3)(utf-8-validate@6.0.6) '@solana/wallet-adapter-base': 0.9.27(@solana/web3.js@1.98.4(bufferutil@4.1.0)(typescript@5.9.3)(utf-8-validate@6.0.6)) '@solana/wallet-standard-wallet-adapter-react': 1.1.5(@solana/wallet-adapter-base@0.9.27(@solana/web3.js@1.98.4(bufferutil@4.1.0)(typescript@5.9.3)(utf-8-validate@6.0.6)))(@solana/web3.js@1.98.4(bufferutil@4.1.0)(typescript@5.9.3)(utf-8-validate@6.0.6))(bs58@6.0.0)(react@19.2.8) '@solana/web3.js': 1.98.4(bufferutil@4.1.0)(typescript@5.9.3)(utf-8-validate@6.0.6) @@ -10612,9 +10544,9 @@ snapshots: '@tanstack/history@1.162.0': {} - '@tanstack/nitro-v2-vite-plugin@1.155.0(@upstash/redis@1.38.2)(drizzle-orm@0.45.2(@cloudflare/workers-types@5.20260808.1)(@upstash/redis@1.38.2))(rolldown@1.2.3)(srvx@0.11.22)(supports-color@10.2.2)(vite@7.3.6(@types/node@22.20.1)(jiti@2.7.0)(lightningcss@1.32.0)(terser@5.49.0)(tsx@4.23.11)(yaml@2.9.0))': + '@tanstack/nitro-v2-vite-plugin@1.155.0(@upstash/redis@1.38.2)(drizzle-orm@0.45.2(@cloudflare/workers-types@5.20260808.1)(@upstash/redis@1.38.2))(rolldown@1.2.3)(srvx@0.11.22)(vite@7.3.6(@types/node@22.20.1)(jiti@2.7.0)(lightningcss@1.32.0)(terser@5.49.0)(tsx@4.23.11)(yaml@2.9.0))': dependencies: - nitropack: 2.13.4(@upstash/redis@1.38.2)(drizzle-orm@0.45.2(@cloudflare/workers-types@5.20260808.1)(@upstash/redis@1.38.2))(rolldown@1.2.3)(srvx@0.11.22)(supports-color@10.2.2) + nitropack: 2.13.4(@upstash/redis@1.38.2)(drizzle-orm@0.45.2(@cloudflare/workers-types@5.20260808.1)(@upstash/redis@1.38.2))(rolldown@1.2.3)(srvx@0.11.22) pathe: 2.0.3 vite: 7.3.6(@types/node@22.20.1)(jiti@2.7.0)(lightningcss@1.32.0)(terser@5.49.0)(tsx@4.23.11)(yaml@2.9.0) transitivePeerDependencies: @@ -10726,14 +10658,14 @@ snapshots: react: 19.2.8 react-dom: 19.2.8(react@19.2.8) - '@tanstack/react-start-rsc@0.1.31(crossws@0.4.10(srvx@0.11.22))(react-dom@19.2.8(react@19.2.8))(react@19.2.8)(supports-color@10.2.2)(vite@7.3.6(@types/node@22.20.1)(jiti@2.7.0)(lightningcss@1.32.0)(terser@5.49.0)(tsx@4.23.11)(yaml@2.9.0))': + '@tanstack/react-start-rsc@0.1.31(crossws@0.4.10(srvx@0.11.22))(react-dom@19.2.8(react@19.2.8))(react@19.2.8)(vite@7.3.6(@types/node@22.20.1)(jiti@2.7.0)(lightningcss@1.32.0)(terser@5.49.0)(tsx@4.23.11)(yaml@2.9.0))': dependencies: '@tanstack/react-router': 1.170.18(react-dom@19.2.8(react@19.2.8))(react@19.2.8) '@tanstack/router-core': 1.171.15 - '@tanstack/router-utils': 1.162.2(supports-color@10.2.2) + '@tanstack/router-utils': 1.162.2 '@tanstack/start-client-core': 1.170.14 '@tanstack/start-fn-stubs': 1.162.0 - '@tanstack/start-plugin-core': 1.171.24(@tanstack/react-router@1.170.18(react-dom@19.2.8(react@19.2.8))(react@19.2.8))(crossws@0.4.10(srvx@0.11.22))(supports-color@10.2.2)(vite@7.3.6(@types/node@22.20.1)(jiti@2.7.0)(lightningcss@1.32.0)(terser@5.49.0)(tsx@4.23.11)(yaml@2.9.0)) + '@tanstack/start-plugin-core': 1.171.24(@tanstack/react-router@1.170.18(react-dom@19.2.8(react@19.2.8))(react@19.2.8))(crossws@0.4.10(srvx@0.11.22))(vite@7.3.6(@types/node@22.20.1)(jiti@2.7.0)(lightningcss@1.32.0)(terser@5.49.0)(tsx@4.23.11)(yaml@2.9.0)) '@tanstack/start-server-core': 1.169.17(crossws@0.4.10(srvx@0.11.22)) '@tanstack/start-storage-context': 1.167.17 pathe: 2.0.3 @@ -10757,15 +10689,15 @@ snapshots: transitivePeerDependencies: - crossws - '@tanstack/react-start@1.168.32(crossws@0.4.10(srvx@0.11.22))(react-dom@19.2.8(react@19.2.8))(react@19.2.8)(supports-color@10.2.2)(vite@7.3.6(@types/node@22.20.1)(jiti@2.7.0)(lightningcss@1.32.0)(terser@5.49.0)(tsx@4.23.11)(yaml@2.9.0))': + '@tanstack/react-start@1.168.32(crossws@0.4.10(srvx@0.11.22))(react-dom@19.2.8(react@19.2.8))(react@19.2.8)(vite@7.3.6(@types/node@22.20.1)(jiti@2.7.0)(lightningcss@1.32.0)(terser@5.49.0)(tsx@4.23.11)(yaml@2.9.0))': dependencies: '@tanstack/react-router': 1.170.18(react-dom@19.2.8(react@19.2.8))(react@19.2.8) '@tanstack/react-start-client': 1.168.16(react-dom@19.2.8(react@19.2.8))(react@19.2.8) - '@tanstack/react-start-rsc': 0.1.31(crossws@0.4.10(srvx@0.11.22))(react-dom@19.2.8(react@19.2.8))(react@19.2.8)(supports-color@10.2.2)(vite@7.3.6(@types/node@22.20.1)(jiti@2.7.0)(lightningcss@1.32.0)(terser@5.49.0)(tsx@4.23.11)(yaml@2.9.0)) + '@tanstack/react-start-rsc': 0.1.31(crossws@0.4.10(srvx@0.11.22))(react-dom@19.2.8(react@19.2.8))(react@19.2.8)(vite@7.3.6(@types/node@22.20.1)(jiti@2.7.0)(lightningcss@1.32.0)(terser@5.49.0)(tsx@4.23.11)(yaml@2.9.0)) '@tanstack/react-start-server': 1.167.22(crossws@0.4.10(srvx@0.11.22))(react-dom@19.2.8(react@19.2.8))(react@19.2.8) - '@tanstack/router-utils': 1.162.2(supports-color@10.2.2) + '@tanstack/router-utils': 1.162.2 '@tanstack/start-client-core': 1.170.14 - '@tanstack/start-plugin-core': 1.171.24(@tanstack/react-router@1.170.18(react-dom@19.2.8(react@19.2.8))(react@19.2.8))(crossws@0.4.10(srvx@0.11.22))(supports-color@10.2.2)(vite@7.3.6(@types/node@22.20.1)(jiti@2.7.0)(lightningcss@1.32.0)(terser@5.49.0)(tsx@4.23.11)(yaml@2.9.0)) + '@tanstack/start-plugin-core': 1.171.24(@tanstack/react-router@1.170.18(react-dom@19.2.8(react@19.2.8))(react@19.2.8))(crossws@0.4.10(srvx@0.11.22))(vite@7.3.6(@types/node@22.20.1)(jiti@2.7.0)(lightningcss@1.32.0)(terser@5.49.0)(tsx@4.23.11)(yaml@2.9.0)) '@tanstack/start-server-core': 1.169.17(crossws@0.4.10(srvx@0.11.22)) pathe: 2.0.3 react: 19.2.8 @@ -10802,11 +10734,11 @@ snapshots: optionalDependencies: csstype: 3.2.3 - '@tanstack/router-generator@1.167.21(supports-color@10.2.2)': + '@tanstack/router-generator@1.167.21': dependencies: '@babel/types': 7.29.7 '@tanstack/router-core': 1.171.15 - '@tanstack/router-utils': 1.162.2(supports-color@10.2.2) + '@tanstack/router-utils': 1.162.2 '@tanstack/virtual-file-routes': 1.162.0 jiti: 2.7.0 magic-string: 0.30.21 @@ -10815,14 +10747,14 @@ snapshots: transitivePeerDependencies: - supports-color - '@tanstack/router-plugin@1.168.23(@tanstack/react-router@1.170.18(react-dom@19.2.8(react@19.2.8))(react@19.2.8))(supports-color@10.2.2)(vite@7.3.6(@types/node@22.20.1)(jiti@2.7.0)(lightningcss@1.32.0)(terser@5.49.0)(tsx@4.23.11)(yaml@2.9.0))': + '@tanstack/router-plugin@1.168.23(@tanstack/react-router@1.170.18(react-dom@19.2.8(react@19.2.8))(react@19.2.8))(vite@7.3.6(@types/node@22.20.1)(jiti@2.7.0)(lightningcss@1.32.0)(terser@5.49.0)(tsx@4.23.11)(yaml@2.9.0))': dependencies: - '@babel/core': 7.29.7(supports-color@10.2.2) + '@babel/core': 7.29.7 '@babel/template': 7.29.7 '@babel/types': 7.29.7 '@tanstack/router-core': 1.171.15 - '@tanstack/router-generator': 1.167.21(supports-color@10.2.2) - '@tanstack/router-utils': 1.162.2(supports-color@10.2.2) + '@tanstack/router-generator': 1.167.21 + '@tanstack/router-utils': 1.162.2 chokidar: 5.0.0 unplugin: 3.0.0 zod: 4.4.3 @@ -10837,13 +10769,13 @@ snapshots: '@tanstack/query-core': 5.101.4 '@tanstack/router-core': 1.171.15 - '@tanstack/router-utils@1.162.2(supports-color@10.2.2)': + '@tanstack/router-utils@1.162.2': dependencies: '@babel/generator': 7.29.7 '@babel/parser': 7.29.7 '@babel/types': 7.29.7 ansis: 4.3.1 - babel-dead-code-elimination: 1.0.12(supports-color@10.2.2) + babel-dead-code-elimination: 1.0.12 diff: 8.0.4 pathe: 2.0.3 tinyglobby: 0.2.17 @@ -10859,15 +10791,15 @@ snapshots: '@tanstack/start-fn-stubs@1.162.0': {} - '@tanstack/start-plugin-core@1.171.24(@tanstack/react-router@1.170.18(react-dom@19.2.8(react@19.2.8))(react@19.2.8))(crossws@0.4.10(srvx@0.11.22))(supports-color@10.2.2)(vite@7.3.6(@types/node@22.20.1)(jiti@2.7.0)(lightningcss@1.32.0)(terser@5.49.0)(tsx@4.23.11)(yaml@2.9.0))': + '@tanstack/start-plugin-core@1.171.24(@tanstack/react-router@1.170.18(react-dom@19.2.8(react@19.2.8))(react@19.2.8))(crossws@0.4.10(srvx@0.11.22))(vite@7.3.6(@types/node@22.20.1)(jiti@2.7.0)(lightningcss@1.32.0)(terser@5.49.0)(tsx@4.23.11)(yaml@2.9.0))': dependencies: '@babel/code-frame': 7.27.1 - '@babel/core': 7.29.7(supports-color@10.2.2) + '@babel/core': 7.29.7 '@babel/types': 7.29.7 '@tanstack/router-core': 1.171.15 - '@tanstack/router-generator': 1.167.21(supports-color@10.2.2) - '@tanstack/router-plugin': 1.168.23(@tanstack/react-router@1.170.18(react-dom@19.2.8(react@19.2.8))(react@19.2.8))(supports-color@10.2.2)(vite@7.3.6(@types/node@22.20.1)(jiti@2.7.0)(lightningcss@1.32.0)(terser@5.49.0)(tsx@4.23.11)(yaml@2.9.0)) - '@tanstack/router-utils': 1.162.2(supports-color@10.2.2) + '@tanstack/router-generator': 1.167.21 + '@tanstack/router-plugin': 1.168.23(@tanstack/react-router@1.170.18(react-dom@19.2.8(react@19.2.8))(react@19.2.8))(vite@7.3.6(@types/node@22.20.1)(jiti@2.7.0)(lightningcss@1.32.0)(terser@5.49.0)(tsx@4.23.11)(yaml@2.9.0)) + '@tanstack/router-utils': 1.162.2 '@tanstack/start-server-core': 1.169.17(crossws@0.4.10(srvx@0.11.22)) exsolve: 1.0.8 lightningcss: 1.32.0 @@ -11005,22 +10937,14 @@ snapshots: react: 19.2.8 react-dom: 19.2.8(react@19.2.8) - '@upstash/core-analytics@0.0.10': - dependencies: - '@upstash/redis': 1.38.2 - - '@upstash/ratelimit@2.0.8(@upstash/redis@1.38.2)': - dependencies: - '@upstash/core-analytics': 0.0.10 - '@upstash/redis': 1.38.2 - '@upstash/redis@1.38.2': dependencies: uncrypto: 0.1.3 + optional: true - '@vercel/nft@1.10.2(rollup@4.61.1)(supports-color@10.2.2)': + '@vercel/nft@1.10.2(rollup@4.61.1)': dependencies: - '@mapbox/node-pre-gyp': 2.0.3(supports-color@10.2.2) + '@mapbox/node-pre-gyp': 2.0.3 '@rollup/pluginutils': 5.4.0(rollup@4.61.1) acorn: 8.16.0 acorn-import-attributes: 1.9.5(acorn@8.16.0) @@ -11041,11 +10965,11 @@ snapshots: optionalDependencies: react: 19.2.8 - '@vitejs/plugin-react@5.2.0(supports-color@10.2.2)(vite@7.3.6(@types/node@22.20.1)(jiti@2.7.0)(lightningcss@1.32.0)(terser@5.49.0)(tsx@4.23.11)(yaml@2.9.0))': + '@vitejs/plugin-react@5.2.0(vite@7.3.6(@types/node@22.20.1)(jiti@2.7.0)(lightningcss@1.32.0)(terser@5.49.0)(tsx@4.23.11)(yaml@2.9.0))': dependencies: - '@babel/core': 7.29.7(supports-color@10.2.2) - '@babel/plugin-transform-react-jsx-self': 7.29.7(@babel/core@7.29.7(supports-color@10.2.2)) - '@babel/plugin-transform-react-jsx-source': 7.29.7(@babel/core@7.29.7(supports-color@10.2.2)) + '@babel/core': 7.29.7 + '@babel/plugin-transform-react-jsx-self': 7.29.7(@babel/core@7.29.7) + '@babel/plugin-transform-react-jsx-source': 7.29.7(@babel/core@7.29.7) '@rolldown/pluginutils': 1.0.0-rc.3 '@types/babel__core': 7.20.5 react-refresh: 0.18.0 @@ -11185,11 +11109,11 @@ snapshots: b4a@1.8.1: {} - babel-dead-code-elimination@1.0.12(supports-color@10.2.2): + babel-dead-code-elimination@1.0.12: dependencies: - '@babel/core': 7.29.7(supports-color@10.2.2) + '@babel/core': 7.29.7 '@babel/parser': 7.29.7 - '@babel/traverse': 7.29.7(supports-color@10.2.2) + '@babel/traverse': 7.29.7 '@babel/types': 7.29.7 transitivePeerDependencies: - supports-color @@ -11270,11 +11194,11 @@ snapshots: bn.js@5.2.5: {} - body-parser@2.3.0(supports-color@10.2.2): + body-parser@2.3.0: dependencies: bytes: 3.1.2 content-type: 2.0.0 - debug: 4.4.3(supports-color@10.2.2) + debug: 4.4.3 http-errors: 2.0.1 iconv-lite: 0.7.3 on-finished: 2.4.1 @@ -11392,21 +11316,21 @@ snapshots: chownr@3.0.0: {} - chrome-launcher@0.15.2(supports-color@10.2.2): + chrome-launcher@0.15.2: dependencies: '@types/node': 22.20.1 escape-string-regexp: 4.0.0 is-wsl: 2.2.0 - lighthouse-logger: 1.4.2(supports-color@10.2.2) + lighthouse-logger: 1.4.2 transitivePeerDependencies: - supports-color - chromium-edge-launcher@0.3.0(supports-color@10.2.2): + chromium-edge-launcher@0.3.0: dependencies: '@types/node': 22.20.1 escape-string-regexp: 4.0.0 is-wsl: 2.2.0 - lighthouse-logger: 1.4.2(supports-color@10.2.2) + lighthouse-logger: 1.4.2 mkdirp: 1.0.4 transitivePeerDependencies: - supports-color @@ -11511,10 +11435,10 @@ snapshots: confbox@0.2.4: {} - connect@3.7.0(supports-color@10.2.2): + connect@3.7.0: dependencies: - debug: 2.6.9(supports-color@10.2.2) - finalhandler: 1.1.2(supports-color@10.2.2) + debug: 2.6.9 + finalhandler: 1.1.2 parseurl: 1.3.3 utils-merge: 1.0.1 transitivePeerDependencies: @@ -11644,17 +11568,13 @@ snapshots: dependencies: mimic-fn: 3.1.0 - debug@2.6.9(supports-color@10.2.2): + debug@2.6.9: dependencies: ms: 2.0.0 - optionalDependencies: - supports-color: 10.2.2 - debug@4.4.3(supports-color@10.2.2): + debug@4.4.3: dependencies: ms: 2.1.3 - optionalDependencies: - supports-color: 10.2.2 decamelize@1.2.0: {} @@ -12002,28 +11922,28 @@ snapshots: exponential-backoff@3.1.3: {} - express-rate-limit@8.6.0(express@5.2.1(supports-color@10.2.2))(supports-color@10.2.2): + express-rate-limit@8.6.0(express@5.2.1): dependencies: - debug: 4.4.3(supports-color@10.2.2) - express: 5.2.1(supports-color@10.2.2) + debug: 4.4.3 + express: 5.2.1 ip-address: 10.3.1 transitivePeerDependencies: - supports-color - express@5.2.1(supports-color@10.2.2): + express@5.2.1: dependencies: accepts: 2.0.0 - body-parser: 2.3.0(supports-color@10.2.2) + body-parser: 2.3.0 content-disposition: 1.1.0 content-type: 1.0.5 cookie: 0.7.2 cookie-signature: 1.2.2 - debug: 4.4.3(supports-color@10.2.2) + debug: 4.4.3 depd: 2.0.0 encodeurl: 2.0.0 escape-html: 1.0.3 etag: 1.8.1 - finalhandler: 2.1.1(supports-color@10.2.2) + finalhandler: 2.1.1 fresh: 2.0.0 http-errors: 2.0.1 merge-descriptors: 2.0.0 @@ -12034,9 +11954,9 @@ snapshots: proxy-addr: 2.0.7 qs: 6.15.3 range-parser: 1.2.1 - router: 2.2.0(supports-color@10.2.2) - send: 1.2.1(supports-color@10.2.2) - serve-static: 2.2.1(supports-color@10.2.2) + router: 2.2.0 + send: 1.2.1 + serve-static: 2.2.1 statuses: 2.0.2 type-is: 2.1.0 vary: 1.1.2 @@ -12104,9 +12024,9 @@ snapshots: dependencies: to-regex-range: 5.0.1 - finalhandler@1.1.2(supports-color@10.2.2): + finalhandler@1.1.2: dependencies: - debug: 2.6.9(supports-color@10.2.2) + debug: 2.6.9 encodeurl: 1.0.2 escape-html: 1.0.3 on-finished: 2.3.0 @@ -12116,9 +12036,9 @@ snapshots: transitivePeerDependencies: - supports-color - finalhandler@2.1.1(supports-color@10.2.2): + finalhandler@2.1.1: dependencies: - debug: 4.4.3(supports-color@10.2.2) + debug: 4.4.3 encodeurl: 2.0.0 escape-html: 1.0.3 on-finished: 2.4.1 @@ -12168,17 +12088,17 @@ snapshots: fuzzysort@3.1.0: {} - gaxios@7.1.5(supports-color@10.2.2): + gaxios@7.1.5: dependencies: extend: 3.0.2 - https-proxy-agent: 7.0.6(supports-color@10.2.2) + https-proxy-agent: 7.0.6 node-fetch: 3.3.2 transitivePeerDependencies: - supports-color - gcp-metadata@8.1.2(supports-color@10.2.2): + gcp-metadata@8.1.2: dependencies: - gaxios: 7.1.5(supports-color@10.2.2) + gaxios: 7.1.5 google-logging-utils: 1.1.3 json-bigint: 1.0.0 transitivePeerDependencies: @@ -12263,12 +12183,12 @@ snapshots: dependencies: csstype: 3.2.3 - google-auth-library@10.7.0(supports-color@10.2.2): + google-auth-library@10.7.0: dependencies: base64-js: 1.5.1 ecdsa-sig-formatter: 1.0.11 - gaxios: 7.1.5(supports-color@10.2.2) - gcp-metadata: 8.1.2(supports-color@10.2.2) + gaxios: 7.1.5 + gcp-metadata: 8.1.2 google-logging-utils: 1.1.3 jws: 4.0.1 transitivePeerDependencies: @@ -12364,19 +12284,19 @@ snapshots: statuses: 2.0.2 toidentifier: 1.0.1 - http-proxy-agent@7.0.2(supports-color@10.2.2): + http-proxy-agent@7.0.2: dependencies: agent-base: 7.1.4 - debug: 4.4.3(supports-color@10.2.2) + debug: 4.4.3 transitivePeerDependencies: - supports-color http-shutdown@1.2.2: {} - https-proxy-agent@7.0.6(supports-color@10.2.2): + https-proxy-agent@7.0.6: dependencies: agent-base: 7.1.4 - debug: 4.4.3(supports-color@10.2.2) + debug: 4.4.3 transitivePeerDependencies: - supports-color @@ -12422,11 +12342,11 @@ snapshots: dependencies: loose-envify: 1.4.0 - ioredis@5.11.1(supports-color@10.2.2): + ioredis@5.11.1: dependencies: '@ioredis/commands': 1.10.0 cluster-key-slot: 1.1.1 - debug: 4.4.3(supports-color@10.2.2) + debug: 4.4.3 denque: 2.1.0 redis-errors: 1.2.0 redis-parser: 3.0.0 @@ -12586,7 +12506,7 @@ snapshots: jsc-safe-url@0.2.4: {} - jsdom@27.4.0(@noble/hashes@1.8.0)(bufferutil@4.1.0)(supports-color@10.2.2)(utf-8-validate@6.0.6): + jsdom@27.4.0(@noble/hashes@1.8.0)(bufferutil@4.1.0)(utf-8-validate@6.0.6): dependencies: '@acemir/cssom': 0.9.31 '@asamuzakjp/dom-selector': 6.8.1 @@ -12595,8 +12515,8 @@ snapshots: data-urls: 6.0.1 decimal.js: 10.6.0 html-encoding-sniffer: 6.0.0(@noble/hashes@1.8.0) - http-proxy-agent: 7.0.2(supports-color@10.2.2) - https-proxy-agent: 7.0.6(supports-color@10.2.2) + http-proxy-agent: 7.0.2 + https-proxy-agent: 7.0.6 is-potential-custom-element-name: 1.0.1 parse5: 8.0.1 saxes: 6.0.0 @@ -12663,9 +12583,9 @@ snapshots: leven@3.1.0: {} - lighthouse-logger@1.4.2(supports-color@10.2.2): + lighthouse-logger@1.4.2: dependencies: - debug: 2.6.9(supports-color@10.2.2) + debug: 2.6.9 marky: 1.3.0 transitivePeerDependencies: - supports-color @@ -12829,9 +12749,9 @@ snapshots: merge2@1.4.1: {} - metro-babel-transformer@0.84.4(supports-color@10.2.2): + metro-babel-transformer@0.84.4: dependencies: - '@babel/core': 7.29.7(supports-color@10.2.2) + '@babel/core': 7.29.7 flow-enums-runtime: 0.0.6 hermes-parser: 0.35.0 metro-cache-key: 0.84.4 @@ -12843,22 +12763,22 @@ snapshots: dependencies: flow-enums-runtime: 0.0.6 - metro-cache@0.84.4(supports-color@10.2.2): + metro-cache@0.84.4: dependencies: exponential-backoff: 3.1.3 flow-enums-runtime: 0.0.6 - https-proxy-agent: 7.0.6(supports-color@10.2.2) + https-proxy-agent: 7.0.6 metro-core: 0.84.4 transitivePeerDependencies: - supports-color - metro-config@0.84.4(bufferutil@4.1.0)(supports-color@10.2.2)(utf-8-validate@6.0.6): + metro-config@0.84.4(bufferutil@4.1.0)(utf-8-validate@6.0.6): dependencies: - connect: 3.7.0(supports-color@10.2.2) + connect: 3.7.0 flow-enums-runtime: 0.0.6 jest-validate: 29.7.0 - metro: 0.84.4(bufferutil@4.1.0)(supports-color@10.2.2)(utf-8-validate@6.0.6) - metro-cache: 0.84.4(supports-color@10.2.2) + metro: 0.84.4(bufferutil@4.1.0)(utf-8-validate@6.0.6) + metro-cache: 0.84.4 metro-core: 0.84.4 metro-runtime: 0.84.4 yaml: 2.9.0 @@ -12873,9 +12793,9 @@ snapshots: lodash.throttle: 4.1.1 metro-resolver: 0.84.4 - metro-file-map@0.84.4(supports-color@10.2.2): + metro-file-map@0.84.4: dependencies: - debug: 4.4.3(supports-color@10.2.2) + debug: 4.4.3 fb-watchman: 2.0.2 flow-enums-runtime: 0.0.6 graceful-fs: 4.2.11 @@ -12901,13 +12821,13 @@ snapshots: '@babel/runtime': 7.29.7 flow-enums-runtime: 0.0.6 - metro-source-map@0.84.4(supports-color@10.2.2): + metro-source-map@0.84.4: dependencies: - '@babel/traverse': 7.29.7(supports-color@10.2.2) + '@babel/traverse': 7.29.7 '@babel/types': 7.29.7 flow-enums-runtime: 0.0.6 invariant: 2.2.4 - metro-symbolicate: 0.84.4(supports-color@10.2.2) + metro-symbolicate: 0.84.4 nullthrows: 1.1.1 ob1: 0.84.4 source-map: 0.5.7 @@ -12915,61 +12835,61 @@ snapshots: transitivePeerDependencies: - supports-color - metro-symbolicate@0.84.4(supports-color@10.2.2): + metro-symbolicate@0.84.4: dependencies: flow-enums-runtime: 0.0.6 invariant: 2.2.4 - metro-source-map: 0.84.4(supports-color@10.2.2) + metro-source-map: 0.84.4 nullthrows: 1.1.1 source-map: 0.5.7 vlq: 1.0.1 transitivePeerDependencies: - supports-color - metro-transform-plugins@0.84.4(supports-color@10.2.2): + metro-transform-plugins@0.84.4: dependencies: - '@babel/core': 7.29.7(supports-color@10.2.2) + '@babel/core': 7.29.7 '@babel/generator': 7.29.7 '@babel/template': 7.29.7 - '@babel/traverse': 7.29.7(supports-color@10.2.2) + '@babel/traverse': 7.29.7 flow-enums-runtime: 0.0.6 nullthrows: 1.1.1 transitivePeerDependencies: - supports-color - metro-transform-worker@0.84.4(bufferutil@4.1.0)(supports-color@10.2.2)(utf-8-validate@6.0.6): + metro-transform-worker@0.84.4(bufferutil@4.1.0)(utf-8-validate@6.0.6): dependencies: - '@babel/core': 7.29.7(supports-color@10.2.2) + '@babel/core': 7.29.7 '@babel/generator': 7.29.7 '@babel/parser': 7.29.7 '@babel/types': 7.29.7 flow-enums-runtime: 0.0.6 - metro: 0.84.4(bufferutil@4.1.0)(supports-color@10.2.2)(utf-8-validate@6.0.6) - metro-babel-transformer: 0.84.4(supports-color@10.2.2) - metro-cache: 0.84.4(supports-color@10.2.2) + metro: 0.84.4(bufferutil@4.1.0)(utf-8-validate@6.0.6) + metro-babel-transformer: 0.84.4 + metro-cache: 0.84.4 metro-cache-key: 0.84.4 metro-minify-terser: 0.84.4 - metro-source-map: 0.84.4(supports-color@10.2.2) - metro-transform-plugins: 0.84.4(supports-color@10.2.2) + metro-source-map: 0.84.4 + metro-transform-plugins: 0.84.4 nullthrows: 1.1.1 transitivePeerDependencies: - bufferutil - supports-color - utf-8-validate - metro@0.84.4(bufferutil@4.1.0)(supports-color@10.2.2)(utf-8-validate@6.0.6): + metro@0.84.4(bufferutil@4.1.0)(utf-8-validate@6.0.6): dependencies: '@babel/code-frame': 7.29.7 - '@babel/core': 7.29.7(supports-color@10.2.2) + '@babel/core': 7.29.7 '@babel/generator': 7.29.7 '@babel/parser': 7.29.7 '@babel/template': 7.29.7 - '@babel/traverse': 7.29.7(supports-color@10.2.2) + '@babel/traverse': 7.29.7 '@babel/types': 7.29.7 accepts: 2.0.0 ci-info: 2.0.0 - connect: 3.7.0(supports-color@10.2.2) - debug: 4.4.3(supports-color@10.2.2) + connect: 3.7.0 + debug: 4.4.3 error-stack-parser: 2.1.4 flow-enums-runtime: 0.0.6 graceful-fs: 4.2.11 @@ -12979,18 +12899,18 @@ snapshots: jest-worker: 29.7.0 jsc-safe-url: 0.2.4 lodash.throttle: 4.1.1 - metro-babel-transformer: 0.84.4(supports-color@10.2.2) - metro-cache: 0.84.4(supports-color@10.2.2) + metro-babel-transformer: 0.84.4 + metro-cache: 0.84.4 metro-cache-key: 0.84.4 - metro-config: 0.84.4(bufferutil@4.1.0)(supports-color@10.2.2)(utf-8-validate@6.0.6) + metro-config: 0.84.4(bufferutil@4.1.0)(utf-8-validate@6.0.6) metro-core: 0.84.4 - metro-file-map: 0.84.4(supports-color@10.2.2) + metro-file-map: 0.84.4 metro-resolver: 0.84.4 metro-runtime: 0.84.4 - metro-source-map: 0.84.4(supports-color@10.2.2) - metro-symbolicate: 0.84.4(supports-color@10.2.2) - metro-transform-plugins: 0.84.4(supports-color@10.2.2) - metro-transform-worker: 0.84.4(bufferutil@4.1.0)(supports-color@10.2.2)(utf-8-validate@6.0.6) + metro-source-map: 0.84.4 + metro-symbolicate: 0.84.4 + metro-transform-plugins: 0.84.4 + metro-transform-worker: 0.84.4(bufferutil@4.1.0)(utf-8-validate@6.0.6) mime-types: 3.0.2 nullthrows: 1.1.1 serialize-error: 2.1.0 @@ -13077,7 +12997,7 @@ snapshots: nf3@0.3.23: {} - nitro-nightly@3.0.1-20260731-205209-52abde8a(@upstash/redis@1.38.2)(chokidar@5.0.0)(dotenv@17.4.2)(drizzle-orm@0.45.2(@cloudflare/workers-types@5.20260808.1)(@upstash/redis@1.38.2))(giget@3.2.0)(ioredis@5.11.1(supports-color@10.2.2))(jiti@2.7.0)(lru-cache@11.5.1)(rollup@4.61.1)(vite@7.3.6(@types/node@22.20.1)(jiti@2.7.0)(lightningcss@1.32.0)(terser@5.49.0)(tsx@4.23.11)(yaml@2.9.0))(wrangler@4.120.0(@cloudflare/workers-types@5.20260808.1)(bufferutil@4.1.0)(utf-8-validate@6.0.6)): + nitro-nightly@3.0.1-20260731-205209-52abde8a(@upstash/redis@1.38.2)(chokidar@5.0.0)(dotenv@17.4.2)(drizzle-orm@0.45.2(@cloudflare/workers-types@5.20260808.1)(@upstash/redis@1.38.2))(giget@3.2.0)(ioredis@5.11.1)(jiti@2.7.0)(lru-cache@11.5.1)(rollup@4.61.1)(vite@7.3.6(@types/node@22.20.1)(jiti@2.7.0)(lightningcss@1.32.0)(terser@5.49.0)(tsx@4.23.11)(yaml@2.9.0))(wrangler@4.120.0(@cloudflare/workers-types@5.20260808.1)(bufferutil@4.1.0)(utf-8-validate@6.0.6)): dependencies: consola: 3.4.2 crossws: 0.4.10(srvx@0.11.22) @@ -13094,7 +13014,7 @@ snapshots: rou3: 0.9.1 srvx: 0.11.22 unenv: 2.0.0-rc.24 - unstorage: 2.0.0-alpha.7(@upstash/redis@1.38.2)(chokidar@5.0.0)(db0@0.3.4(drizzle-orm@0.45.2(@cloudflare/workers-types@5.20260808.1)(@upstash/redis@1.38.2)))(ioredis@5.11.1(supports-color@10.2.2))(lru-cache@11.5.1)(ofetch@2.0.0-alpha.3) + unstorage: 2.0.0-alpha.7(@upstash/redis@1.38.2)(chokidar@5.0.0)(db0@0.3.4(drizzle-orm@0.45.2(@cloudflare/workers-types@5.20260808.1)(@upstash/redis@1.38.2)))(ioredis@5.11.1)(lru-cache@11.5.1)(ofetch@2.0.0-alpha.3) optionalDependencies: dotenv: 17.4.2 giget: 3.2.0 @@ -13133,7 +13053,7 @@ snapshots: - uploadthing - wrangler - nitropack@2.13.4(@upstash/redis@1.38.2)(drizzle-orm@0.45.2(@cloudflare/workers-types@5.20260808.1)(@upstash/redis@1.38.2))(rolldown@1.2.3)(srvx@0.11.22)(supports-color@10.2.2): + nitropack@2.13.4(@upstash/redis@1.38.2)(drizzle-orm@0.45.2(@cloudflare/workers-types@5.20260808.1)(@upstash/redis@1.38.2))(rolldown@1.2.3)(srvx@0.11.22): dependencies: '@cloudflare/kv-asset-handler': 0.4.2 '@rollup/plugin-alias': 6.0.0(rollup@4.61.1) @@ -13143,7 +13063,7 @@ snapshots: '@rollup/plugin-node-resolve': 16.0.3(rollup@4.61.1) '@rollup/plugin-replace': 6.0.3(rollup@4.61.1) '@rollup/plugin-terser': 1.0.0(rollup@4.61.1) - '@vercel/nft': 1.10.2(rollup@4.61.1)(supports-color@10.2.2) + '@vercel/nft': 1.10.2(rollup@4.61.1) archiver: 7.0.1 c12: 3.3.4(magicast@0.5.3) chokidar: 5.0.0 @@ -13167,7 +13087,7 @@ snapshots: h3: 1.15.11 hookable: 5.5.3 httpxy: 0.5.5 - ioredis: 5.11.1(supports-color@10.2.2) + ioredis: 5.11.1 jiti: 2.7.0 klona: 2.0.6 knitwork: 1.3.0 @@ -13190,7 +13110,7 @@ snapshots: scule: 1.3.0 semver: 7.8.5 serve-placeholder: 2.0.2 - serve-static: 2.2.1(supports-color@10.2.2) + serve-static: 2.2.1 source-map: 0.7.6 std-env: 4.1.0 ufo: 1.6.4 @@ -13200,7 +13120,7 @@ snapshots: unenv: 2.0.0-rc.24 unimport: 6.3.0(rolldown@1.2.3) unplugin-utils: 0.3.1 - unstorage: 1.17.5(@upstash/redis@1.38.2)(db0@0.3.4(drizzle-orm@0.45.2(@cloudflare/workers-types@5.20260808.1)(@upstash/redis@1.38.2)))(ioredis@5.11.1(supports-color@10.2.2)) + unstorage: 1.17.5(@upstash/redis@1.38.2)(db0@0.3.4(drizzle-orm@0.45.2(@cloudflare/workers-types@5.20260808.1)(@upstash/redis@1.38.2)))(ioredis@5.11.1) untyped: 2.0.0 unwasm: 0.5.3 youch: 4.1.1 @@ -13646,15 +13566,15 @@ snapshots: react-is@18.3.1: {} - react-native@0.86.0(@babel/core@7.29.7(supports-color@10.2.2))(@types/react@19.2.17)(bufferutil@4.1.0)(react@19.2.8)(supports-color@10.2.2)(utf-8-validate@6.0.6): + react-native@0.86.0(@babel/core@7.29.7)(@types/react@19.2.17)(bufferutil@4.1.0)(react@19.2.8)(utf-8-validate@6.0.6): dependencies: '@react-native/assets-registry': 0.86.0 - '@react-native/codegen': 0.86.0(@babel/core@7.29.7(supports-color@10.2.2)) - '@react-native/community-cli-plugin': 0.86.0(bufferutil@4.1.0)(supports-color@10.2.2)(utf-8-validate@6.0.6) + '@react-native/codegen': 0.86.0(@babel/core@7.29.7) + '@react-native/community-cli-plugin': 0.86.0(bufferutil@4.1.0)(utf-8-validate@6.0.6) '@react-native/gradle-plugin': 0.86.0 '@react-native/js-polyfills': 0.86.0 '@react-native/normalize-colors': 0.86.0 - '@react-native/virtualized-lists': 0.86.0(@types/react@19.2.17)(react-native@0.86.0(@babel/core@7.29.7(supports-color@10.2.2))(@types/react@19.2.17)(bufferutil@4.1.0)(react@19.2.8)(supports-color@10.2.2)(utf-8-validate@6.0.6))(react@19.2.8) + '@react-native/virtualized-lists': 0.86.0(@types/react@19.2.17)(react-native@0.86.0(@babel/core@7.29.7)(@types/react@19.2.17)(bufferutil@4.1.0)(react@19.2.8)(utf-8-validate@6.0.6))(react@19.2.8) abort-controller: 3.0.0 anser: 1.4.10 ansi-regex: 5.0.1 @@ -13666,7 +13586,7 @@ snapshots: invariant: 2.2.4 memoize-one: 5.2.1 metro-runtime: 0.84.4 - metro-source-map: 0.84.4(supports-color@10.2.2) + metro-source-map: 0.84.4 nullthrows: 1.1.1 pretty-format: 29.7.0 promise: 8.3.0 @@ -13857,9 +13777,9 @@ snapshots: rou3@0.9.1: {} - router@2.2.0(supports-color@10.2.2): + router@2.2.0: dependencies: - debug: 4.4.3(supports-color@10.2.2) + debug: 4.4.3 depd: 2.0.0 is-promise: 4.0.0 parseurl: 1.3.3 @@ -13908,9 +13828,9 @@ snapshots: semver@7.8.5: {} - send@0.19.2(supports-color@10.2.2): + send@0.19.2: dependencies: - debug: 2.6.9(supports-color@10.2.2) + debug: 2.6.9 depd: 2.0.0 destroy: 1.2.0 encodeurl: 2.0.0 @@ -13926,9 +13846,9 @@ snapshots: transitivePeerDependencies: - supports-color - send@1.2.1(supports-color@10.2.2): + send@1.2.1: dependencies: - debug: 4.4.3(supports-color@10.2.2) + debug: 4.4.3 encodeurl: 2.0.0 escape-html: 1.0.3 etag: 1.8.1 @@ -13956,21 +13876,21 @@ snapshots: dependencies: defu: 6.1.7 - serve-static@1.16.3(supports-color@10.2.2): + serve-static@1.16.3: dependencies: encodeurl: 2.0.0 escape-html: 1.0.3 parseurl: 1.3.3 - send: 0.19.2(supports-color@10.2.2) + send: 0.19.2 transitivePeerDependencies: - supports-color - serve-static@2.2.1(supports-color@10.2.2): + serve-static@2.2.1: dependencies: encodeurl: 2.0.0 escape-html: 1.0.3 parseurl: 1.3.3 - send: 1.2.1(supports-color@10.2.2) + send: 1.2.1 transitivePeerDependencies: - supports-color @@ -13978,14 +13898,14 @@ snapshots: setprototypeof@1.2.0: {} - shadcn@4.14.1(babel-plugin-macros@3.1.0)(supports-color@10.2.2)(typescript@5.9.3): + shadcn@4.14.1(babel-plugin-macros@3.1.0)(typescript@5.9.3): dependencies: - '@babel/core': 7.29.7(supports-color@10.2.2) + '@babel/core': 7.29.7 '@babel/parser': 7.29.7 - '@babel/plugin-transform-typescript': 7.29.7(@babel/core@7.29.7(supports-color@10.2.2))(supports-color@10.2.2) - '@babel/preset-typescript': 7.29.7(@babel/core@7.29.7(supports-color@10.2.2))(supports-color@10.2.2) + '@babel/plugin-transform-typescript': 7.29.7(@babel/core@7.29.7) + '@babel/preset-typescript': 7.29.7(@babel/core@7.29.7) '@dotenvx/dotenvx': 1.75.1 - '@modelcontextprotocol/sdk': 1.29.0(supports-color@10.2.2)(zod@3.25.76) + '@modelcontextprotocol/sdk': 1.29.0(zod@3.25.76) '@types/validate-npm-package-name': 4.0.2 browserslist: 4.28.2 commander: 14.0.3 @@ -14432,7 +14352,7 @@ snapshots: picomatch: 4.0.4 webpack-virtual-modules: 0.6.2 - unstorage@1.17.5(@upstash/redis@1.38.2)(db0@0.3.4(drizzle-orm@0.45.2(@cloudflare/workers-types@5.20260808.1)(@upstash/redis@1.38.2)))(ioredis@5.11.1(supports-color@10.2.2)): + unstorage@1.17.5(@upstash/redis@1.38.2)(db0@0.3.4(drizzle-orm@0.45.2(@cloudflare/workers-types@5.20260808.1)(@upstash/redis@1.38.2)))(ioredis@5.11.1): dependencies: anymatch: 3.1.3 chokidar: 5.0.0 @@ -14445,14 +14365,14 @@ snapshots: optionalDependencies: '@upstash/redis': 1.38.2 db0: 0.3.4(drizzle-orm@0.45.2(@cloudflare/workers-types@5.20260808.1)(@upstash/redis@1.38.2)) - ioredis: 5.11.1(supports-color@10.2.2) + ioredis: 5.11.1 - unstorage@2.0.0-alpha.7(@upstash/redis@1.38.2)(chokidar@5.0.0)(db0@0.3.4(drizzle-orm@0.45.2(@cloudflare/workers-types@5.20260808.1)(@upstash/redis@1.38.2)))(ioredis@5.11.1(supports-color@10.2.2))(lru-cache@11.5.1)(ofetch@2.0.0-alpha.3): + unstorage@2.0.0-alpha.7(@upstash/redis@1.38.2)(chokidar@5.0.0)(db0@0.3.4(drizzle-orm@0.45.2(@cloudflare/workers-types@5.20260808.1)(@upstash/redis@1.38.2)))(ioredis@5.11.1)(lru-cache@11.5.1)(ofetch@2.0.0-alpha.3): optionalDependencies: '@upstash/redis': 1.38.2 chokidar: 5.0.0 db0: 0.3.4(drizzle-orm@0.45.2(@cloudflare/workers-types@5.20260808.1)(@upstash/redis@1.38.2)) - ioredis: 5.11.1(supports-color@10.2.2) + ioredis: 5.11.1 lru-cache: 11.5.1 ofetch: 2.0.0-alpha.3 @@ -14527,9 +14447,9 @@ snapshots: vary@1.1.2: {} - vite-tsconfig-paths@5.1.4(supports-color@10.2.2)(typescript@5.9.3)(vite@7.3.6(@types/node@22.20.1)(jiti@2.7.0)(lightningcss@1.32.0)(terser@5.49.0)(tsx@4.23.11)(yaml@2.9.0)): + vite-tsconfig-paths@5.1.4(typescript@5.9.3)(vite@7.3.6(@types/node@22.20.1)(jiti@2.7.0)(lightningcss@1.32.0)(terser@5.49.0)(tsx@4.23.11)(yaml@2.9.0)): dependencies: - debug: 4.4.3(supports-color@10.2.2) + debug: 4.4.3 globrex: 0.1.2 tsconfck: 3.1.6(typescript@5.9.3) optionalDependencies: From 75b4d4cb62e8ec39d75462a96b015ae8a6c28567 Mon Sep 17 00:00:00 2001 From: Swastik Dan <57379785+Swastikdan@users.noreply.github.com> Date: Sun, 16 Aug 2026 02:12:31 +0530 Subject: [PATCH 11/27] fix(auth): handle expired/malformed Clerk tokens gracefully without log spam --- src/server/auth.ts | 21 ++++++++++++++++----- 1 file changed, 16 insertions(+), 5 deletions(-) diff --git a/src/server/auth.ts b/src/server/auth.ts index 9b9c136f..2b1310fe 100644 --- a/src/server/auth.ts +++ b/src/server/auth.ts @@ -30,31 +30,42 @@ export interface ClerkSessionClaims { export function getSessionToken(): string | undefined { const authHeader = getRequestHeader("authorization"); if (authHeader && authHeader.toLowerCase().startsWith("bearer ")) { - return authHeader.slice(7); + const bearer = authHeader.slice(7).trim(); + if (bearer.length > 0) return bearer; } - return getCookie("__session") || getCookie("__clerk_db_jwt"); + const cookieToken = getCookie("__session") || getCookie("__clerk_db_jwt"); + if (typeof cookieToken === "string" && cookieToken.trim().length > 0) { + return cookieToken.trim(); + } + return undefined; } /** * Verify the Clerk session token and return the JWT claims, or `null` when - * there is no session / the token is invalid. + * there is no session / the token is invalid or expired. */ export async function getSessionClaims(): Promise { const token = getSessionToken(); if (!token) return null; + // A valid JWT consists of header.payload.signature (3 dot-separated segments) + if (token.split(".").length !== 3) return null; + const secretKey = getEnvVar("CLERK_SECRET_KEY"); if (!secretKey) return null; + const issuer = getEnvVar("CLERK_ISSUER_URL"); + try { const claims = await verifyToken(token, { secretKey, + ...(issuer ? { issuer } : {}), // Tolerate clock drift / refresh races (Clerk dev JWTs are short-lived). clockSkewInMs: 300_000, }); return claims as ClerkSessionClaims; - } catch (error) { - console.error("Clerk token verification failed:", error); + } catch { + // Expired or transitioning token — treated safely as unauthenticated/guest return null; } } From a811412add86f25eda86c1235051fa8f339e7d4d Mon Sep 17 00:00:00 2001 From: Swastik Dan <57379785+Swastikdan@users.noreply.github.com> Date: Sun, 16 Aug 2026 02:19:08 +0530 Subject: [PATCH 12/27] chore: Update public app URL to swastik.workers.dev --- .env.example | 2 +- src/constants.ts | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/.env.example b/.env.example index eaac0241..a9156ba5 100644 --- a/.env.example +++ b/.env.example @@ -9,7 +9,7 @@ VITE_CLERK_ISSUER_URL=https://your-app.clerk.accounts.dev VITE_CLERK_PUBLISHABLE_KEY=pk_test_YOUR_CLERK_PUBLISHABLE_KEY # App URLs -VITE_PUBLIC_APP_URL=https://pebbly.vercel.app +VITE_PUBLIC_APP_URL=https://pebbly.swastik.workers.dev # TMDB API (read-only public API key — safe for client) VITE_PUBLIC_TMDB_ACCESS_TOKEN=your_tmdb_read_access_token diff --git a/src/constants.ts b/src/constants.ts index 54977d5f..1d238196 100644 --- a/src/constants.ts +++ b/src/constants.ts @@ -1,7 +1,7 @@ export const SITE_CONFIG = { name: "Pebbly", description: "Explore a vast collection of movies and TV shows with Pebbly.", - url: "https://pebbly.vercel.app/", + url: "https://pebbly.swastik.workers.dev/", defaultMetaImage: "https://ik.imagekit.io/swastikdan/Film-Fanatic/public/ogimage.webp", navItems: [ From 7e3595d2f4b2e5abc57f889e926ab79c5eb80916 Mon Sep 17 00:00:00 2001 From: Swastik Dan <57379785+Swastikdan@users.noreply.github.com> Date: Sun, 16 Aug 2026 02:22:00 +0530 Subject: [PATCH 13/27] docs: update README with Cloudflare Workers, D1, Drizzle, and Valibot architecture --- README.md | 157 +++++++++++++++++++++++++++++++++++++----------------- 1 file changed, 109 insertions(+), 48 deletions(-) diff --git a/README.md b/README.md index a5e6f7fc..e6dd3e66 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ # Pebbly (Film Fanatic) -Pebbly is a modern, full-stack movie and TV show discovery application built with TanStack Start, Convex, Clerk, Google Gemini AI, and TMDB metadata. It combines rich media browsing with persistent watchlists, granular episode progress tracking, custom user lists, and a personalized AI Recommendation Engine. +Pebbly is a modern, full-stack movie and TV show discovery application built with **TanStack Start**, **Cloudflare Workers**, **Cloudflare D1 (SQLite)**, **Drizzle ORM**, **Valibot**, **Clerk**, **Google Gemini AI**, and **TMDB metadata**. It combines rich media browsing with persistent watchlists, granular episode progress tracking, custom user lists, and a personalized AI Recommendation Engine. --- @@ -10,11 +10,11 @@ Pebbly is a modern, full-stack movie and TV show discovery application built wit - **Comprehensive Browsing**: Explore trending, popular, top-rated, upcoming, and curated movie/TV collections. - **Advanced Search**: Instant cross-media search with genre, media type, and keyword filtering. - **Rich Details & Media Player**: Complete detail pages with cast/crew, trailers, season/episode browsers, and embedded video modal with responsive controls. -- **Smart Watchlist & Progress**: Track progress (`want-to-watch`, `watching`, `caught-up`, `finished`, `dropped`), per-episode watching status, and reaction tags (`loved`, `liked`, `mixed`, `not-for-me`). -- **Custom Lists & Management**: Create custom lists, export/import watchlists in JSON format, and sync seamlessly across devices via Convex. +- **Smart Watchlist & Progress**: Track progress (`watch-later`, `watching`, `done`, `dropped`), per-episode watching status, and reaction tags (`loved`, `liked`, `mixed`, `not-for-me`, `recommended`). +- **Custom Lists & Management**: Create custom lists, export/import watchlists in JSON format, and sync seamlessly across devices via Cloudflare D1. ### AI Recommendation Engine -- **Watchlist & Interaction-Aware AI**: Generates tailored movie and TV recommendations using Google Gemini models (`gemini-3.1-flash-lite-preview`, `gemini-2.5-flash`, etc.). +- **Watchlist & Interaction-Aware AI**: Generates tailored movie and TV recommendations using Google Gemini models (`gemini-2.5-flash`, `gemini-3.1-flash-lite-preview`). - **Homepage "Picks For You"**: Dedicated homepage widget providing twice-daily refreshed recommendations with real-time watchlist exclusion. - **Interaction Feedback Loop**: User interactions (thumbs up / thumbs down) train future recommendations. Liked recommendations are automatically added to your **Pebbly Picks** list, and disliked titles are excluded. - **Advanced Filtering**: Generate recommendations by Watchlist, Custom List, Genre preferences, or Era presets (Classics, 80s, 90s, 2000s, 2010s, 2020s). @@ -27,43 +27,46 @@ Pebbly is a modern, full-stack movie and TV show discovery application built wit | Layer | Technology | | :--- | :--- | | **Framework** | [TanStack Start](https://tanstack.com/start) + [TanStack Router](https://tanstack.com/router) + React 19 | -| **Backend & Realtime** | [Convex](https://www.convex.dev/) | +| **Host & Compute** | [Cloudflare Workers](https://workers.cloudflare.com/) (Nitro `cloudflare_module` preset) | +| **Database** | [Cloudflare D1](https://developers.cloudflare.com/d1/) (SQLite) via [Drizzle ORM](https://orm.drizzle.team/) | +| **Validation** | [Valibot](https://valibot.dev/) (Lightweight, modular schema validation) | +| **Authentication** | [Clerk](https://clerk.com/) (`@clerk/react` + `@clerk/backend` JWT verification) | | **AI Engine** | Google GenAI SDK (`@google/genai` - Gemini Flash models) | -| **Authentication** | [Clerk](https://clerk.com/) | | **Styling** | Tailwind CSS 4, Radix UI, shadcn/ui | | **Data Fetching** | TanStack Query (React Query) | | **State Management** | Zustand | -| **Tooling & Linter** | Vite 7, Biome, TypeScript | +| **Tooling & Linter** | Vite 7, Biome, TypeScript, Wrangler | --- ## Project Structure ``` -├── convex/ # Convex backend schemas, queries, mutations, and actions -│ ├── schema.ts # Database tables (users, watch_items, ai_recommendations, lists, etc.) -│ ├── recommendations.ts # AI recommendation engine actions, prompts, and feedback handling -│ ├── watchlist.ts # Watchlist management, custom lists, and snapshots -│ ├── crons.ts # Scheduled background tasks (e.g. daily watchlist snapshots) -│ └── admin.ts # Feature flags & RBAC permission checks +├── drizzle/ # Drizzle generated SQL migrations for Cloudflare D1 +├── server/ # Nitro server routes and scheduled tasks +│ ├── routes/api/health.ts # /api/health endpoint (D1 status check) +│ └── tasks/snapshots.ts # Daily watchlist snapshots cron task ├── src/ +│ ├── server/ # Co-located backend server functions & database layer +│ │ ├── db/ # D1 database schema & Drizzle client +│ │ ├── fns/ # Type-safe TanStack Start server functions (watchlist, lists, recs, admin) +│ │ ├── schema/ # Valibot schemas & typed API result contracts +│ │ ├── auth.ts # Clerk server-side JWT verification & user resolution +│ │ ├── ai.ts # Gemini AI client with model fallback chain +│ │ ├── prompts.ts # Context-aware prompts for AI recommendations +│ │ └── rbac.ts # Role-based access control & feature flags │ ├── components/ # UI components & domain-specific widgets │ │ ├── homepage-recommendations.tsx # Homepage "Picks For You" row with interaction buttons │ │ ├── video-player-modal.tsx # Fullscreen-capable responsive video player │ │ ├── media-card.tsx # Reusable media grid/carousel card -│ │ └── recommendations/ # Recommendation loading skeletons and UI elements +│ │ └── recommendations/ # Recommendation loading skeletons and UI elements │ ├── hooks/ # Custom hooks (watchlist, watch progress, recommendations, RBAC) -│ │ ├── use-recommendations.ts # Client-side hook for AI recommendation generation & history -│ │ └── use-permissions.ts # RBAC & feature flag access control hook -│ ├── lib/ # Core utility libraries & clients -│ │ ├── recommendation-engine.ts # Shared TMDB resolution engine, fuzzy matching & caching hooks -│ │ ├── queries.ts # TMDB API query functions -│ │ └── media-transform.ts # TMDB payload transformations +│ ├── lib/ # Core utility libraries, query keys, and TMDB queries │ ├── routes/ # TanStack file-based routes -│ │ ├── index.tsx # Homepage route -│ │ ├── recommendations.lazy.tsx # AI Recommendations management & generation page -│ │ └── search.lazy.tsx # Search & discovery page │ └── types.d.ts # TypeScript declarations & domain types +├── wrangler.toml # Cloudflare Workers & D1 configuration +├── drizzle.config.ts # Drizzle Kit migration generator config +└── drizzle.studio.config.ts # Drizzle Studio dashboard config ``` --- @@ -72,72 +75,130 @@ Pebbly is a modern, full-stack movie and TV show discovery application built wit ### Prerequisites -- Node.js 20+ -- `pnpm` (or `npm`/`yarn`) +- Node.js 22+ +- `pnpm` (v10+) - A TMDB API Read Access Token - A Clerk Application -- A Convex Deployment - A Google Gemini API Key +- A Cloudflare Account (with D1 database enabled) ### Environment Setup -1. Clone the repository: +1. **Clone the repository:** ```bash git clone https://github.com/Swastikdan/Pebbly.git cd Pebbly ``` -2. Install dependencies: +2. **Install dependencies:** ```bash pnpm install ``` -3. Create a `.env.local` file in the project root: +3. **Configure environment variables:** + Create a `.env` or `.env.local` file in the project root: ```env + # TMDB API (read-only public API key — safe for client) VITE_PUBLIC_TMDB_ACCESS_TOKEN=your_tmdb_read_access_token VITE_PUBLIC_TMDB_API_URL=https://api.themoviedb.org/3 - VITE_CLERK_PUBLISHABLE_KEY=your_clerk_publishable_key - CLERK_SECRET_KEY=your_clerk_secret_key - CONVEX_CLERK_ISSUER_URL=https://your-clerk-domain + # Clerk Auth + VITE_CLERK_PUBLISHABLE_KEY=pk_test_YOUR_CLERK_PUBLISHABLE_KEY + CLERK_SECRET_KEY=sk_test_YOUR_CLERK_SECRET_KEY + CLERK_ISSUER_URL=https://your-app.clerk.accounts.dev - VITE_CONVEX_URL=your_convex_url + # App URLs VITE_PUBLIC_APP_URL=http://localhost:3000 VITE_PUBLIC_VIDEO_URL=your_video_provider_base_url + + # AI Providers + GEMINI_API_KEY=your_gemini_key + + # Cloudflare (needed for `pnpm db:studio` dashboard & GitHub Actions) + CLOUDFLARE_API_TOKEN=your_cloudflare_api_token + CLOUDFLARE_ACCOUNT_ID=your_cloudflare_account_id ``` -4. Set the Gemini API key in your Convex deployment environment variables: +4. **Initialize the local database:** ```bash - npx convex env set GEMINI_API_KEY your_gemini_api_key + pnpm db:migrate:local ``` -### Running Locally +--- + +## Running Locally -- Run frontend & Convex dev server concurrently: +- **Run frontend dev server (Vite + Node SSR):** ```bash pnpm dev ``` -- Run typecheck and Biome validation: +- **Run full Cloudflare Workers + Miniflare D1 emulator locally:** ```bash - pnpm check + pnpm preview:cf ``` -- Build for production: +- **Run TypeScript validation & Biome linting:** ```bash - pnpm build + pnpm typecheck + pnpm lint ``` --- +## Database & Migrations + +- **Generate new SQL migration after editing `src/server/db/schema.ts`:** + ```bash + pnpm db:generate + ``` + +- **Apply migrations to local database (`.wrangler` emulator):** + ```bash + pnpm db:migrate:local + ``` + +- **Apply migrations to remote Cloudflare D1 database (Production):** + ```bash + pnpm db:migrate:prod + ``` + +- **Open Drizzle Studio to view/edit database tables in your browser:** + ```bash + pnpm db:studio + ``` + +--- + +## Deploying to Cloudflare + +Deploying to Cloudflare Workers is automated via GitHub Actions CI/CD whenever you push to the deployment branch, or you can deploy manually: + +```bash +# 1. Apply any pending migrations to production D1 +pnpm db:migrate:prod + +# 2. Build and publish to Cloudflare Workers +pnpm deploy:cf +``` + +--- + ## Available Scripts -- `pnpm dev` — Run Vite frontend and Convex dev server in parallel -- `pnpm dev:vite` — Run frontend dev server only -- `pnpm dev:convex` — Run Convex local dev server only -- `pnpm build` — Type-check and build production bundle -- `pnpm check` — Biome linter check + TypeScript validation -- `pnpm format` — Format code with Biome +| Script | Description | +| :--- | :--- | +| `pnpm dev` | Run Vite development server | +| `pnpm preview:cf` | Build and run full app on local Cloudflare Worker & D1 emulator | +| `pnpm build` | Build production bundle (Nitro Cloudflare preset) | +| `pnpm db:generate` | Generate SQL migrations from `src/server/db/schema.ts` | +| `pnpm db:migrate:local` | Apply migrations to local Miniflare D1 database | +| `pnpm db:migrate:prod` | Apply migrations to Cloudflare production D1 database | +| `pnpm db:studio` | Launch Drizzle Studio database explorer | +| `pnpm deploy:cf` | Build and deploy directly to Cloudflare Workers | +| `pnpm typecheck` | Run TypeScript compiler type-checking | +| `pnpm lint` | Run Biome linter | +| `pnpm format` | Auto-format codebase with Biome | --- @@ -145,4 +206,4 @@ Pebbly is a modern, full-stack movie and TV show discovery application built wit - Movie and TV metadata provided by [TMDB](https://www.themoviedb.org/). - AI Recommendations powered by [Google Gemini](https://ai.google.dev/). -- Built with TanStack, Convex, Clerk, and Tailwind CSS. +- Built with TanStack Start, Cloudflare Workers, D1, Drizzle ORM, Valibot, Clerk, and Tailwind CSS. From 1b5c62928d722332e1997a24340e41bc712f6903 Mon Sep 17 00:00:00 2001 From: Swastik Dan <57379785+Swastikdan@users.noreply.github.com> Date: Sun, 16 Aug 2026 02:37:04 +0530 Subject: [PATCH 14/27] feat: implement RequestBatcher utility and batch watchlist membership updates to optimize database performance --- src/components/homepage-recommendations.tsx | 36 +++- .../media/media-title-container.tsx | 26 ++- src/hooks/use-watchlist.ts | 163 +++++++++++++--- src/hooks/watchlist-store.ts | 8 +- src/lib/batcher.ts | 131 +++++++++++++ src/routes/watchlist.lazy.tsx | 21 ++- src/server/fns/watchlist.ts | 178 +++++++++++++++--- src/server/schema/watchlist.ts | 7 + 8 files changed, 480 insertions(+), 90 deletions(-) create mode 100644 src/lib/batcher.ts diff --git a/src/components/homepage-recommendations.tsx b/src/components/homepage-recommendations.tsx index 18fdee0e..f4d7f4fe 100644 --- a/src/components/homepage-recommendations.tsx +++ b/src/components/homepage-recommendations.tsx @@ -359,16 +359,32 @@ export function HomepageRecommendations() { } // Toggle watchlist item if liking or unliking - if (feedback === "like" || feedback === "unlike") { - toggleWatchlist({ - id: String(resolvedId), - title: rec.title, - media_type: rec.mediaType, - rating: metadata?.rating ?? 0, - image: metadata?.image ?? "", - release_date: metadata?.release_date ?? "", - overview: metadata?.overview, - }).catch(console.error); + if (feedback === "like") { + toggleWatchlist( + { + id: String(resolvedId), + title: rec.title, + media_type: rec.mediaType, + rating: metadata?.rating ?? 0, + image: metadata?.image ?? "", + release_date: metadata?.release_date ?? "", + overview: metadata?.overview, + }, + false, + ).catch(console.error); + } else if (feedback === "unlike") { + toggleWatchlist( + { + id: String(resolvedId), + title: rec.title, + media_type: rec.mediaType, + rating: metadata?.rating ?? 0, + image: metadata?.image ?? "", + release_date: metadata?.release_date ?? "", + overview: metadata?.overview, + }, + true, + ).catch(console.error); } try { diff --git a/src/components/media/media-title-container.tsx b/src/components/media/media-title-container.tsx index 9ec78858..346804b0 100644 --- a/src/components/media/media-title-container.tsx +++ b/src/components/media/media-title-container.tsx @@ -98,11 +98,14 @@ export const MediaTitleContainer = (props: { ]); const handleAdd = () => { - toggleWatchlist({ - ...metadata, - id: String(id), - media_type, - }).catch(console.error); + toggleWatchlist( + { + ...metadata, + id: String(id), + media_type, + }, + false, + ).catch(console.error); }; const handleStatusChange = (status: ProgressStatus) => { @@ -114,11 +117,14 @@ export const MediaTitleContainer = (props: { }; const handleRemove = () => { - toggleWatchlist({ - ...metadata, - id: String(id), - media_type, - }).catch(console.error); + toggleWatchlist( + { + ...metadata, + id: String(id), + media_type, + }, + true, + ).catch(console.error); }; const renderWatchListSection = (className?: string) => ( diff --git a/src/hooks/use-watchlist.ts b/src/hooks/use-watchlist.ts index c753853b..afdf160f 100644 --- a/src/hooks/use-watchlist.ts +++ b/src/hooks/use-watchlist.ts @@ -6,10 +6,12 @@ import { useQueryClient, } from "@tanstack/react-query"; import { useCallback, useEffect, useMemo, useRef } from "react"; +import { createBatcher } from "@/lib/batcher"; import { getTvDetails } from "@/lib/queries"; import { queryKeys } from "@/lib/query/keys"; import type { EpisodeProgressRow, WatchItemRow } from "@/lib/server-types"; import { + batchSetWatchlistMembership, getWatchlist, markShowEpisodesAndStatus, setProgressStatus, @@ -57,22 +59,12 @@ export function useWatchlist() { if (!remote.data) return []; return remote.data .map((item) => mapWatchlistRowToItem(item)) - .filter( - (item) => - item.inWatchlist || - item.progressStatus === "watching" || - (item.progress ?? 0) > 0, - ) + .filter((item) => item.inWatchlist) .sort((a, b) => b.updated_at - a.updated_at); } return [...localMediaState] - .filter( - (item) => - item.inWatchlist || - item.progressStatus === "watching" || - (item.progress ?? 0) > 0, - ) + .filter((item) => item.inWatchlist) .sort((a, b) => b.updated_at - a.updated_at); }, [isLoaded, isSignedIn, remote.data, localMediaState]); @@ -188,7 +180,12 @@ const updateWatchlistMembership = createOptimisticUpdater< } return current.map((i) => i.tmdbId === args.tmdbId && i.mediaType === args.mediaType - ? { ...i, inWatchlist: false } + ? { + ...i, + inWatchlist: false, + progressStatus: + i.progressStatus === "watch-later" ? null : i.progressStatus, + } : i, ); }, @@ -239,6 +236,50 @@ async function setWatchlistMembershipOptimistic( ); } +type BatchedWatchlistMembershipTask = { + args: WatchlistMembershipArgs; + rollback?: () => void; + queryClient: QueryClient; +}; + +const watchlistMembershipBatcher = createBatcher< + BatchedWatchlistMembershipTask, + { ok: true } | { count: number } +>( + async (tasks) => { + const queryClient = tasks[0]?.queryClient; + const items = tasks.map((t) => t.args); + + try { + let result: { ok: true } | { count: number }; + if (items.length === 1) { + result = await unwrap(setWatchlistMembership({ data: items[0] })); + } else { + result = await unwrap(batchSetWatchlistMembership({ data: { items } })); + } + + if (queryClient) { + void queryClient.invalidateQueries({ + queryKey: queryKeys.watchlist.list(), + }); + } + + return result; + } catch (error) { + logWatchlistError("batch set watchlist membership", error); + for (const task of tasks) { + task.rollback?.(); + } + throw error; + } + }, + { + delayMs: 60, + maxBatchSize: 100, + getKey: (task) => `${task.args.mediaType}:${task.args.tmdbId}`, + }, +); + export function useToggleWatchlistItem() { const { isSignedIn } = useUser(); const queryClient = useQueryClient(); @@ -252,21 +293,6 @@ export function useToggleWatchlistItem() { watchlistRef.current = watchlist; }); - const mutation = useMutation({ - mutationFn: (args: WatchlistMembershipArgs) => - unwrap(setWatchlistMembership({ data: args })), - onMutate: (args) => setWatchlistMembershipOptimistic(queryClient, args), - onError: (error, _args, rollback) => { - logWatchlistError("set watchlist membership", error); - rollback?.(); - }, - onSettled: () => { - void queryClient.invalidateQueries({ - queryKey: queryKeys.watchlist.list(), - }); - }, - }); - return useCallback( async ( item: { @@ -292,7 +318,7 @@ export function useToggleWatchlistItem() { const inWatchlist = !currentlyInWatchlist; if (isSignedIn) { - await mutation.mutateAsync({ + const args: WatchlistMembershipArgs = { tmdbId: Number(item.id), mediaType: item.media_type, inWatchlist, @@ -301,8 +327,17 @@ export function useToggleWatchlistItem() { rating: item.rating, release_date: item.release_date || undefined, overview: item.overview || undefined, + }; + + const rollback = await setWatchlistMembershipOptimistic( + queryClient, + args, + ); + return await watchlistMembershipBatcher.schedule({ + args, + rollback, + queryClient, }); - return; } setLocalWatchlistMembership(item.id, item.media_type, inWatchlist, { @@ -313,7 +348,73 @@ export function useToggleWatchlistItem() { overview: item.overview, }); }, - [isSignedIn, mutation, setLocalWatchlistMembership], + [isSignedIn, queryClient, setLocalWatchlistMembership], + ); +} + +export function useBatchToggleWatchlist() { + const { isSignedIn } = useUser(); + const queryClient = useQueryClient(); + const setLocalWatchlistMembership = useWatchlistStore( + (state) => state.setWatchlistMembershipLocal, + ); + + return useCallback( + async ( + items: Array<{ + id: string; + media_type: MediaType; + inWatchlist: boolean; + title?: string; + image?: string; + rating?: number; + release_date?: string; + overview?: string; + }>, + ) => { + if (items.length === 0) return; + + if (isSignedIn) { + const tasks: BatchedWatchlistMembershipTask[] = []; + for (const item of items) { + const args: WatchlistMembershipArgs = { + tmdbId: Number(item.id), + mediaType: item.media_type, + inWatchlist: item.inWatchlist, + title: item.title, + image: item.image, + rating: item.rating, + release_date: item.release_date || undefined, + overview: item.overview || undefined, + }; + const rollback = await setWatchlistMembershipOptimistic( + queryClient, + args, + ); + tasks.push({ args, rollback, queryClient }); + } + + return await Promise.all( + tasks.map((task) => watchlistMembershipBatcher.schedule(task)), + ); + } + + for (const item of items) { + setLocalWatchlistMembership( + item.id, + item.media_type, + item.inWatchlist, + { + title: item.title, + image: item.image, + rating: item.rating, + release_date: item.release_date, + overview: item.overview, + }, + ); + } + }, + [isSignedIn, queryClient, setLocalWatchlistMembership], ); } diff --git a/src/hooks/watchlist-store.ts b/src/hooks/watchlist-store.ts index 3cffcf9a..dc0b0887 100644 --- a/src/hooks/watchlist-store.ts +++ b/src/hooks/watchlist-store.ts @@ -194,9 +194,11 @@ export const useWatchlistStore = create()( (current) => ({ ...current, inWatchlist, - progressStatus: - current.progressStatus ?? - (inWatchlist ? "watch-later" : null), + progressStatus: inWatchlist + ? (current.progressStatus ?? "watch-later") + : current.progressStatus === "watch-later" + ? null + : current.progressStatus, }), ), }; diff --git a/src/lib/batcher.ts b/src/lib/batcher.ts new file mode 100644 index 00000000..bb9007ee --- /dev/null +++ b/src/lib/batcher.ts @@ -0,0 +1,131 @@ +/** + * Generic request batching utility that collects multiple rapid calls within a + * configurable time window (debounce/microtask buffer) and executes them in a + * single batch request. + */ + +export type BatcherOptions = { + /** Max time to wait (ms) before flushing the batch (default: 50ms) */ + delayMs?: number; + /** Max number of items before triggering an immediate flush (default: 100) */ + maxBatchSize?: number; + /** Optional key function to deduplicate requests in the same batch window (latest state wins) */ + getKey?: (item: TItem) => string; +}; + +export class RequestBatcher { + private queue: Array<{ + item: TItem; + resolve: (val: TResult) => void; + reject: (err: unknown) => void; + }> = []; + private timer: ReturnType | null = null; + private batchFn: (items: TItem[]) => Promise; + private delayMs: number; + private maxBatchSize: number; + private getKey?: (item: TItem) => string; + + constructor( + batchFn: (items: TItem[]) => Promise, + options?: BatcherOptions, + ) { + this.batchFn = batchFn; + this.delayMs = options?.delayMs ?? 50; + this.maxBatchSize = options?.maxBatchSize ?? 100; + this.getKey = options?.getKey; + } + + /** + * Schedule an item to be processed in the next batch. + * Returns a Promise that resolves when the entire batch completes. + */ + schedule(item: TItem): Promise { + return new Promise((resolve, reject) => { + if (this.getKey) { + const getKeyFn = this.getKey; + const key = getKeyFn(item); + const existingIndex = this.queue.findIndex( + (entry) => getKeyFn(entry.item) === key, + ); + if (existingIndex !== -1) { + // Replace with latest payload, and chain resolvers + const prev = this.queue[existingIndex]; + this.queue[existingIndex] = { + item, + resolve: (val) => { + prev.resolve(val); + resolve(val); + }, + reject: (err) => { + prev.reject(err); + reject(err); + }, + }; + return; + } + } + + this.queue.push({ item, resolve, reject }); + + if (this.queue.length >= this.maxBatchSize) { + void this.flush(); + } else if (!this.timer) { + this.timer = setTimeout(() => { + void this.flush(); + }, this.delayMs); + } + }); + } + + /** + * Immediately flush any currently queued items. + */ + async flush(): Promise { + if (this.timer) { + clearTimeout(this.timer); + this.timer = null; + } + + if (this.queue.length === 0) return; + + const currentBatch = this.queue; + this.queue = []; + + const items = currentBatch.map((entry) => entry.item); + + try { + const result = await this.batchFn(items); + if (Array.isArray(result) && result.length === currentBatch.length) { + for (let i = 0; i < currentBatch.length; i++) { + currentBatch[i].resolve(result[i]); + } + } else { + for (const entry of currentBatch) { + entry.resolve(result as TResult); + } + } + } catch (error) { + for (const entry of currentBatch) { + entry.reject(error); + } + } + } + + /** + * Clear any pending items in the queue without processing them. + */ + clear(): void { + if (this.timer) { + clearTimeout(this.timer); + this.timer = null; + } + this.queue = []; + } +} + +export function createBatcher( + batchFn: (items: TItem[]) => Promise, + options?: BatcherOptions, +): RequestBatcher { + return new RequestBatcher(batchFn, options); +} diff --git a/src/routes/watchlist.lazy.tsx b/src/routes/watchlist.lazy.tsx index 761b260c..76b5542a 100644 --- a/src/routes/watchlist.lazy.tsx +++ b/src/routes/watchlist.lazy.tsx @@ -258,15 +258,18 @@ function WatchlistTabContent() { const handleRemoveFromWatchlist = useCallback( (item: WatchlistItem) => { - toggleWatchlist({ - title: item.title, - rating: item.rating, - image: item.image, - id: item.external_id, - media_type: item.type, - release_date: item.release_date ?? "", - overview: item.overview, - }).catch(console.error); + toggleWatchlist( + { + title: item.title, + rating: item.rating, + image: item.image, + id: item.external_id, + media_type: item.type, + release_date: item.release_date ?? "", + overview: item.overview, + }, + true, + ).catch(console.error); }, [toggleWatchlist], ); diff --git a/src/server/fns/watchlist.ts b/src/server/fns/watchlist.ts index eb2cd7cb..b637fe94 100644 --- a/src/server/fns/watchlist.ts +++ b/src/server/fns/watchlist.ts @@ -5,6 +5,7 @@ import { getCurrentUser, requireUser } from "../auth"; import { getDb } from "../db/client"; import { episodeProgress, watchItems } from "../db/schema"; import { getEnv } from "../env"; +import { createWatchlistSnapshot } from "../helpers/snapshots"; import { buildMetadataPatch, getWatchItem, @@ -13,6 +14,7 @@ import { } from "../helpers/watch-item"; import { type ApiResult, ok } from "../schema/common"; import { + batchSetWatchlistMembershipArgsSchema, getWatchlistArgsSchema, markEpisodeWatchedArgsSchema, markSeasonEpisodesWatchedArgsSchema, @@ -78,7 +80,9 @@ export const getTrackedTmdbIds = createServerFn({ method: "POST" }).handler( const items = await db .select({ tmdbId: watchItems.tmdbId }) .from(watchItems) - .where(eq(watchItems.userId, user.id)) + .where( + and(eq(watchItems.userId, user.id), eq(watchItems.inWatchlist, true)), + ) .limit(500); return ok(items.map((item) => item.tmdbId)); @@ -205,38 +209,158 @@ export const setWatchlistMembership = createServerFn({ method: "POST" }) if (error) return error; const db = getDb(getEnv()); - await upsertWatchItem( - db, - user.id, - data.tmdbId, - data.mediaType, - (existing) => { - if (!existing && !data.inWatchlist) return null; + const existing = await getWatchItem(db, user.id, { + tmdbId: data.tmdbId, + mediaType: data.mediaType, + }); - const normalizedExisting = existing - ? normalizeProgressStatus(existing.progressStatus) - : undefined; - const progressStatus = existing - ? (normalizedExisting ?? - (data.inWatchlist ? "watch-later" : undefined)) - : "watch-later"; + if (!data.inWatchlist) { + if (!existing) return ok({ ok: true }); - return { - inWatchlist: data.inWatchlist, - progressStatus, - ...(existing ? {} : { progress: 0 }), - title: data.title, - image: data.image, - rating: data.rating, - release_date: data.release_date, - overview: data.overview, - }; - }, - ); + // If the user has a reaction or non-default progress, keep row with inWatchlist: false + if ( + existing.reaction || + (existing.progress && + existing.progress > 0 && + existing.progressStatus !== "watch-later") + ) { + await db + .update(watchItems) + .set({ + inWatchlist: false, + progressStatus: + existing.progressStatus === "watch-later" + ? null + : existing.progressStatus, + updatedAt: Date.now(), + }) + .where(eq(watchItems.id, existing.id)); + } else { + // Otherwise, delete the row entirely + await db.delete(watchItems).where(eq(watchItems.id, existing.id)); + } + return ok({ ok: true }); + } + + await upsertWatchItem(db, user.id, data.tmdbId, data.mediaType, (curr) => { + const normalizedExisting = curr + ? normalizeProgressStatus(curr.progressStatus) + : undefined; + const progressStatus = curr + ? (normalizedExisting ?? "watch-later") + : "watch-later"; + + return { + inWatchlist: true, + progressStatus, + ...(curr ? {} : { progress: 0 }), + title: data.title, + image: data.image, + rating: data.rating, + release_date: data.release_date, + overview: data.overview, + }; + }); return ok({ ok: true }); }); +export const batchSetWatchlistMembership = createServerFn({ method: "POST" }) + .validator(batchSetWatchlistMembershipArgsSchema) + .handler(async ({ data }): Promise> => { + const { user, error } = await requireUser(); + if (error) return error; + + if (!data.items || data.items.length === 0) { + return ok({ count: 0 }); + } + + const db = getDb(getEnv()); + const now = Date.now(); + + // Fetch existing watch items for this user in 1 fast query + const userWatchItems = await db + .select() + .from(watchItems) + .where(eq(watchItems.userId, user.id)); + + const existingMap = new Map(); + for (const item of userWatchItems) { + existingMap.set(`${item.mediaType}:${item.tmdbId}`, item); + } + + // Deduplicate items in the incoming batch taking the latest state + const batchMap = new Map(); + for (const item of data.items) { + batchMap.set(`${item.mediaType}:${item.tmdbId}`, item); + } + + for (const item of batchMap.values()) { + const existing = existingMap.get(`${item.mediaType}:${item.tmdbId}`); + + if (!item.inWatchlist) { + if (!existing) continue; + + if ( + existing.reaction || + (existing.progress && + existing.progress > 0 && + existing.progressStatus !== "watch-later") + ) { + await db + .update(watchItems) + .set({ + inWatchlist: false, + progressStatus: + existing.progressStatus === "watch-later" + ? null + : existing.progressStatus, + updatedAt: now, + }) + .where(eq(watchItems.id, existing.id)); + } else { + await db.delete(watchItems).where(eq(watchItems.id, existing.id)); + } + continue; + } + + const normalizedExisting = existing + ? normalizeProgressStatus(existing.progressStatus) + : undefined; + const progressStatus = existing + ? (normalizedExisting ?? "watch-later") + : "watch-later"; + const metadataPatch = buildMetadataPatch(item, existing ?? undefined); + + if (existing) { + await db + .update(watchItems) + .set({ + inWatchlist: true, + progressStatus, + updatedAt: now, + ...metadataPatch, + }) + .where(eq(watchItems.id, existing.id)); + } else { + await db.insert(watchItems).values({ + id: crypto.randomUUID(), + userId: user.id, + tmdbId: item.tmdbId, + mediaType: item.mediaType, + inWatchlist: true, + progressStatus, + progress: 0, + updatedAt: now, + ...metadataPatch, + }); + } + } + + await createWatchlistSnapshot(db, user.id); + return ok({ count: batchMap.size }); + }); + export const setProgressStatus = createServerFn({ method: "POST" }) .validator(setProgressStatusArgsSchema) .handler(async ({ data }): Promise> => { diff --git a/src/server/schema/watchlist.ts b/src/server/schema/watchlist.ts index 69d5ea7d..75ee45f3 100644 --- a/src/server/schema/watchlist.ts +++ b/src/server/schema/watchlist.ts @@ -27,6 +27,13 @@ export type SetWatchlistMembershipArgs = v.InferOutput< typeof setWatchlistMembershipArgsSchema >; +export const batchSetWatchlistMembershipArgsSchema = v.object({ + items: v.array(setWatchlistMembershipArgsSchema), +}); +export type BatchSetWatchlistMembershipArgs = v.InferOutput< + typeof batchSetWatchlistMembershipArgsSchema +>; + export const setProgressStatusArgsSchema = v.object({ ...mediaIdentityArgsSchema.entries, ...metadataSchema.entries, From 1bb75c66104e30a4d12ec55eb1c3d815268765b0 Mon Sep 17 00:00:00 2001 From: Swastik Dan <57379785+Swastikdan@users.noreply.github.com> Date: Sun, 16 Aug 2026 02:46:15 +0530 Subject: [PATCH 15/27] feat: implement upsert logic for watch items and episode progress, update rating schema to real, and enhance batcher with maxWaitMs support --- src/hooks/use-watchlist.ts | 3 +- src/lib/batcher.ts | 38 ++++++++-- src/server/db/schema.ts | 5 +- src/server/fns/import-export.ts | 121 ++++++++++++++++++++++++++----- src/server/fns/watchlist.ts | 32 +++++--- src/server/helpers/watch-item.ts | 51 +++++++++---- 6 files changed, 197 insertions(+), 53 deletions(-) diff --git a/src/hooks/use-watchlist.ts b/src/hooks/use-watchlist.ts index afdf160f..43e5575f 100644 --- a/src/hooks/use-watchlist.ts +++ b/src/hooks/use-watchlist.ts @@ -274,7 +274,8 @@ const watchlistMembershipBatcher = createBatcher< } }, { - delayMs: 60, + delayMs: 300, + maxWaitMs: 1200, maxBatchSize: 100, getKey: (task) => `${task.args.mediaType}:${task.args.tmdbId}`, }, diff --git a/src/lib/batcher.ts b/src/lib/batcher.ts index bb9007ee..0687e866 100644 --- a/src/lib/batcher.ts +++ b/src/lib/batcher.ts @@ -5,8 +5,10 @@ */ export type BatcherOptions = { - /** Max time to wait (ms) before flushing the batch (default: 50ms) */ + /** Debounce wait time (ms) after the last item is queued before flushing (default: 300ms) */ delayMs?: number; + /** Max wait time (ms) since the first queued item before forcing a flush (default: 1200ms) */ + maxWaitMs?: number; /** Max number of items before triggering an immediate flush (default: 100) */ maxBatchSize?: number; /** Optional key function to deduplicate requests in the same batch window (latest state wins) */ @@ -20,8 +22,10 @@ export class RequestBatcher { reject: (err: unknown) => void; }> = []; private timer: ReturnType | null = null; + private firstItemTime: number | null = null; private batchFn: (items: TItem[]) => Promise; private delayMs: number; + private maxWaitMs: number; private maxBatchSize: number; private getKey?: (item: TItem) => string; @@ -30,7 +34,8 @@ export class RequestBatcher { options?: BatcherOptions, ) { this.batchFn = batchFn; - this.delayMs = options?.delayMs ?? 50; + this.delayMs = options?.delayMs ?? 300; + this.maxWaitMs = options?.maxWaitMs ?? 1200; this.maxBatchSize = options?.maxBatchSize ?? 100; this.getKey = options?.getKey; } @@ -61,6 +66,7 @@ export class RequestBatcher { reject(err); }, }; + this.scheduleTimer(); return; } } @@ -69,14 +75,32 @@ export class RequestBatcher { if (this.queue.length >= this.maxBatchSize) { void this.flush(); - } else if (!this.timer) { - this.timer = setTimeout(() => { - void this.flush(); - }, this.delayMs); + } else { + this.scheduleTimer(); } }); } + private scheduleTimer(): void { + if (this.timer) { + clearTimeout(this.timer); + this.timer = null; + } + + const now = Date.now(); + if (!this.firstItemTime) { + this.firstItemTime = now; + } + + const timeSinceFirst = now - this.firstItemTime; + const remainingMaxWait = Math.max(0, this.maxWaitMs - timeSinceFirst); + const waitTime = Math.min(this.delayMs, remainingMaxWait); + + this.timer = setTimeout(() => { + void this.flush(); + }, waitTime); + } + /** * Immediately flush any currently queued items. */ @@ -85,6 +109,7 @@ export class RequestBatcher { clearTimeout(this.timer); this.timer = null; } + this.firstItemTime = null; if (this.queue.length === 0) return; @@ -119,6 +144,7 @@ export class RequestBatcher { clearTimeout(this.timer); this.timer = null; } + this.firstItemTime = null; this.queue = []; } } diff --git a/src/server/db/schema.ts b/src/server/db/schema.ts index 4bf89398..46cfc4fd 100644 --- a/src/server/db/schema.ts +++ b/src/server/db/schema.ts @@ -3,6 +3,7 @@ import { check, index, integer, + real, sqliteTable, text, uniqueIndex, @@ -38,7 +39,7 @@ export const watchItems = sqliteTable( progress: integer("progress").default(0), // 0..100 title: text("title"), image: text("image"), - rating: integer("rating"), + rating: real("rating"), releaseDate: text("release_date"), overview: text("overview"), updatedAt: integer("updated_at").notNull(), // ms epoch @@ -108,7 +109,7 @@ export const listItems = sqliteTable( title: text("title"), image: text("image"), backdrop: text("backdrop"), - rating: integer("rating"), + rating: real("rating"), releaseDate: text("release_date"), overview: text("overview"), }, diff --git a/src/server/fns/import-export.ts b/src/server/fns/import-export.ts index 1ec7ec0e..6b151bb6 100644 --- a/src/server/fns/import-export.ts +++ b/src/server/fns/import-export.ts @@ -2,7 +2,7 @@ import { createServerFn } from "@tanstack/react-start"; import { eq } from "drizzle-orm"; import { requireUser } from "../auth"; import { getDb } from "../db/client"; -import { watchItems } from "../db/schema"; +import { episodeProgress, watchItems } from "../db/schema"; import { getEnv } from "../env"; import { createWatchlistSnapshot } from "../helpers/snapshots"; import { @@ -12,7 +12,6 @@ import { } from "../helpers/watch-item"; import { type ApiResult, ok } from "../schema/common"; import { importWatchlistArgsSchema } from "../schema/import"; -import { syncEpisodeProgressRecord } from "./watchlist"; export const importWatchlist = createServerFn({ method: "POST" }) .validator(importWatchlistArgsSchema) @@ -69,18 +68,35 @@ export const importWatchlist = createServerFn({ method: "POST" }) }) .where(eq(watchItems.id, existing.id)); } else { - await db.insert(watchItems).values({ - id: crypto.randomUUID(), - userId: user.id, - tmdbId: item.tmdbId, - mediaType: item.mediaType, - inWatchlist: true, - progressStatus, - progress, - reaction, - updatedAt: now, - ...metadata, - }); + await db + .insert(watchItems) + .values({ + id: crypto.randomUUID(), + userId: user.id, + tmdbId: item.tmdbId, + mediaType: item.mediaType, + inWatchlist: true, + progressStatus, + progress, + reaction, + updatedAt: now, + ...metadata, + }) + .onConflictDoUpdate({ + target: [ + watchItems.userId, + watchItems.tmdbId, + watchItems.mediaType, + ], + set: { + inWatchlist: true, + progressStatus, + progress, + reaction, + updatedAt: now, + ...metadata, + }, + }); } } @@ -89,17 +105,84 @@ export const importWatchlist = createServerFn({ method: "POST" }) .filter((item) => item.mediaType === "tv") .map((item) => item.tmdbId), ); + + const userEpisodes = await db + .select() + .from(episodeProgress) + .where(eq(episodeProgress.userId, user.id)); + + const existingEpisodeMap = new Map< + string, + typeof episodeProgress.$inferSelect + >(); + for (const ep of userEpisodes) { + existingEpisodeMap.set(`${ep.tmdbId}:${ep.season}:${ep.episode}`, ep); + } + const episodeKeys = new Set(); + const episodesToUpsert: Array<{ + id: string; + userId: string; + tmdbId: number; + season: number; + episode: number; + isWatched: boolean; + updatedAt: number; + }> = []; + for (const episode of data.watchedEpisodes) { if (!importedTvIds.has(episode.tmdbId)) continue; const key = `${episode.tmdbId}:${episode.season}:${episode.episode}`; if (episodeKeys.has(key)) continue; episodeKeys.add(key); - await syncEpisodeProgressRecord( - user.id, - { ...episode, isWatched: true }, - now, - ); + + const existingEp = existingEpisodeMap.get(key); + if (existingEp) { + if (!existingEp.isWatched) { + episodesToUpsert.push({ + id: existingEp.id, + userId: user.id, + tmdbId: episode.tmdbId, + season: episode.season, + episode: episode.episode, + isWatched: true, + updatedAt: now, + }); + } + } else { + episodesToUpsert.push({ + id: crypto.randomUUID(), + userId: user.id, + tmdbId: episode.tmdbId, + season: episode.season, + episode: episode.episode, + isWatched: true, + updatedAt: now, + }); + } + } + + // Insert/upsert episodes in chunks of 50 rows (each row has 7 params => 350 params, well within SQLite limits) + const CHUNK_SIZE = 50; + for (let i = 0; i < episodesToUpsert.length; i += CHUNK_SIZE) { + const chunk = episodesToUpsert.slice(i, i + CHUNK_SIZE); + if (chunk.length > 0) { + await db + .insert(episodeProgress) + .values(chunk) + .onConflictDoUpdate({ + target: [ + episodeProgress.userId, + episodeProgress.tmdbId, + episodeProgress.season, + episodeProgress.episode, + ], + set: { + isWatched: true, + updatedAt: now, + }, + }); + } } await createWatchlistSnapshot(db, user.id); diff --git a/src/server/fns/watchlist.ts b/src/server/fns/watchlist.ts index b637fe94..f7861e0e 100644 --- a/src/server/fns/watchlist.ts +++ b/src/server/fns/watchlist.ts @@ -474,15 +474,29 @@ export async function syncEpisodeProgressRecord( return; } - await db.insert(episodeProgress).values({ - id: crypto.randomUUID(), - userId, - tmdbId: args.tmdbId, - season: args.season, - episode: args.episode, - isWatched: args.isWatched, - updatedAt: now, - }); + await db + .insert(episodeProgress) + .values({ + id: crypto.randomUUID(), + userId, + tmdbId: args.tmdbId, + season: args.season, + episode: args.episode, + isWatched: args.isWatched, + updatedAt: now, + }) + .onConflictDoUpdate({ + target: [ + episodeProgress.userId, + episodeProgress.tmdbId, + episodeProgress.season, + episodeProgress.episode, + ], + set: { + isWatched: args.isWatched, + updatedAt: now, + }, + }); } export const markEpisodeWatched = createServerFn({ method: "POST" }) diff --git a/src/server/helpers/watch-item.ts b/src/server/helpers/watch-item.ts index a18df82d..83c629a0 100644 --- a/src/server/helpers/watch-item.ts +++ b/src/server/helpers/watch-item.ts @@ -148,21 +148,40 @@ export async function upsertWatchItem( } const id = crypto.randomUUID(); - await db.insert(watchItems).values({ - id, - userId, - tmdbId, - mediaType, - inWatchlist: finalUpdates.inWatchlist ?? false, - progressStatus: - normalizeProgressStatus(finalUpdates.progressStatus) ?? undefined, - progress: - typeof finalUpdates.progress === "number" - ? Math.min(Math.max(finalUpdates.progress, 0), 100) - : 0, - reaction: normalizeReaction(finalUpdates.reaction) ?? undefined, - updatedAt: now, - ...metadataPatch, - }); + const progressStatus = + normalizeProgressStatus(finalUpdates.progressStatus) ?? undefined; + const progress = + typeof finalUpdates.progress === "number" + ? Math.min(Math.max(finalUpdates.progress, 0), 100) + : 0; + const reaction = normalizeReaction(finalUpdates.reaction) ?? undefined; + + await db + .insert(watchItems) + .values({ + id, + userId, + tmdbId, + mediaType, + inWatchlist: finalUpdates.inWatchlist ?? false, + progressStatus, + progress, + reaction, + updatedAt: now, + ...metadataPatch, + }) + .onConflictDoUpdate({ + target: [watchItems.userId, watchItems.tmdbId, watchItems.mediaType], + set: { + ...(finalUpdates.inWatchlist !== undefined && { + inWatchlist: finalUpdates.inWatchlist, + }), + ...(progressStatus !== undefined && { progressStatus }), + ...(typeof finalUpdates.progress === "number" && { progress }), + ...(reaction !== undefined && { reaction }), + updatedAt: now, + ...metadataPatch, + }, + }); return undefined; } From a81daa29fbaefd8233239523b3c8078ae1c9dbc2 Mon Sep 17 00:00:00 2001 From: Swastik Dan <57379785+Swastikdan@users.noreply.github.com> Date: Sun, 16 Aug 2026 02:52:52 +0530 Subject: [PATCH 16/27] refactor: improve watchlist import schema and validation logic for robust data parsing --- src/hooks/use-watchlist-import-export.ts | 282 ++++++++++++++++------- src/server/fns/import-export.ts | 64 ++--- src/server/fns/watchlist.ts | 13 +- src/server/helpers/watch-item.ts | 14 +- src/server/schema/import.ts | 11 +- 5 files changed, 225 insertions(+), 159 deletions(-) diff --git a/src/hooks/use-watchlist-import-export.ts b/src/hooks/use-watchlist-import-export.ts index 9acd10e9..ac358b2c 100644 --- a/src/hooks/use-watchlist-import-export.ts +++ b/src/hooks/use-watchlist-import-export.ts @@ -1,42 +1,52 @@ import { useUser } from "@clerk/react"; -import { useQuery } from "@tanstack/react-query"; +import { useQuery, useQueryClient } from "@tanstack/react-query"; import type React from "react"; - import { useCallback, useRef, useState } from "react"; +import * as v from "valibot"; import { useLocalProgressStore } from "@/hooks/use-local-progress-store"; -import { - useWatchlist, - useWatchlistStore, - type WatchlistItem, -} from "@/hooks/use-watchlist"; +import { useWatchlist, useWatchlistStore } from "@/hooks/use-watchlist"; import { queryKeys } from "@/lib/query/keys"; import type { AllEpisodeProgressRow } from "@/lib/server-types"; import { normalizeProgressStatus } from "@/lib/utils"; import { importWatchlist as importWatchlistFn } from "@/server/fns/import-export"; import { getAllEpisodeProgress } from "@/server/fns/watchlist"; import { unwrap } from "@/server/schema/common"; +import { + importWatchlistArgsSchema, + type ImportItem as ServerImportItem, + type WatchedEpisode, +} from "@/server/schema/import"; import type { ReactionStatus } from "@/types"; -function isValidWatchlistItem(item: unknown): item is ImportItem { - if (typeof item !== "object" || item === null) return false; - const obj = item as Record; - return ( - typeof obj.title === "string" && - typeof obj.external_id === "string" && - (obj.type === "tv" || obj.type === "movie") - ); -} - type ImportError = { message: string; invalidItems?: number; }; -type ImportItem = Pick & - Partial> & { - status?: string; - watchedEpisodes?: Record; - }; +type RawImportItem = { + title?: unknown; + name?: unknown; + external_id?: unknown; + id?: unknown; + tmdbId?: unknown; + type?: unknown; + media_type?: unknown; + mediaType?: unknown; + image?: unknown; + poster_path?: unknown; + rating?: unknown; + vote_average?: unknown; + release_date?: unknown; + releaseDate?: unknown; + first_air_date?: unknown; + overview?: unknown; + inWatchlist?: unknown; + progressStatus?: unknown; + status?: unknown; + progress?: unknown; + reaction?: unknown; + watchedEpisodes?: unknown; +}; export const useWatchlistImportExport = () => { const [importLoading, setImportLoading] = useState(false); @@ -44,6 +54,7 @@ export const useWatchlistImportExport = () => { const [exportLoading, setExportLoading] = useState(false); const [error, setError] = useState(null); + const queryClient = useQueryClient(); const { watchlist, loading } = useWatchlist(); const importWatchlistLocal = useWatchlistStore( @@ -135,7 +146,7 @@ export const useWatchlistImportExport = () => { if (!file) return; if (!file.name.endsWith(".json")) { - setError({ message: "Please select a valid JSON file." }); + setError({ message: "Please select a valid JSON (.json) file." }); return; } @@ -155,44 +166,140 @@ export const useWatchlistImportExport = () => { try { const content = e.target?.result as string; if (!content || content.trim().length === 0) { - throw new Error("File is empty."); + throw new Error("The selected file is empty."); + } + + let importedData: unknown; + try { + importedData = JSON.parse(content); + } catch { + throw new Error( + "Invalid JSON format: Unable to parse file content. Please check the file for syntax errors.", + ); } - const importedData = JSON.parse(content) as unknown; if (!Array.isArray(importedData)) { - throw new Error("Invalid file format: Expected a JSON array."); + throw new Error( + "Invalid file structure: Expected a JSON array of items at the root level.", + ); + } + + if (importedData.length === 0) { + throw new Error( + "The uploaded JSON array is empty. No items found to import.", + ); } let invalidItemCount = 0; - const validatedList: ImportItem[] = []; + const validationErrors: string[] = []; + const validItems: ServerImportItem[] = []; + const watchedEpisodes: WatchedEpisode[] = []; - for (const item of importedData) { - if ( - isValidWatchlistItem(item) && - Number.isFinite(Number(item.external_id)) - ) { - validatedList.push(item); - } else { + for (let i = 0; i < importedData.length; i++) { + const raw = importedData[i] as RawImportItem; + if (typeof raw !== "object" || raw === null) { invalidItemCount++; + validationErrors.push(`Item #${i + 1}: Not a valid JSON object.`); + continue; } - } - if (validatedList.length === 0) { - throw new Error("No valid items found in the watchlist file."); - } + const rawTitle = raw.title ?? raw.name; + if (typeof rawTitle !== "string" || rawTitle.trim() === "") { + invalidItemCount++; + validationErrors.push(`Item #${i + 1}: Missing title name.`); + continue; + } + const title = rawTitle.trim(); + + const rawId = raw.external_id ?? raw.tmdbId ?? raw.id; + const tmdbId = Number(rawId); + if (!Number.isFinite(tmdbId) || tmdbId <= 0) { + invalidItemCount++; + validationErrors.push( + `Item #${i + 1} ("${title}"): Invalid TMDB ID (${String(rawId)}).`, + ); + continue; + } + + const rawType = raw.type ?? raw.mediaType ?? raw.media_type; + const mediaType = + rawType === "tv" || rawType === "movie" ? rawType : null; + if (!mediaType) { + invalidItemCount++; + validationErrors.push( + `Item #${i + 1} ("${title}"): Invalid media type (${String(rawType)}). Must be "tv" or "movie".`, + ); + continue; + } + + const rawImage = raw.image ?? raw.poster_path; + const image = + typeof rawImage === "string" && rawImage.trim() !== "" + ? rawImage.trim() + : null; + + const rawRating = raw.rating ?? raw.vote_average; + const rating = + typeof rawRating === "number" && !Number.isNaN(rawRating) + ? Math.min(Math.max(rawRating, 0), 10) + : null; + + const rawDate = + raw.release_date ?? raw.releaseDate ?? raw.first_air_date; + const release_date = + typeof rawDate === "string" && rawDate.trim() !== "" + ? rawDate.trim() + : null; + + const overview = + typeof raw.overview === "string" && raw.overview.trim() !== "" + ? raw.overview.trim() + : null; + + const inWatchlist = + raw.inWatchlist !== undefined && raw.inWatchlist !== null + ? Boolean(raw.inWatchlist) + : true; + + const rawStatus = raw.progressStatus ?? raw.status; + const progressStatus = + normalizeProgressStatus( + typeof rawStatus === "string" ? rawStatus : undefined, + ) ?? "watch-later"; + + const rawProgress = raw.progress; + const progress = + typeof rawProgress === "number" && !Number.isNaN(rawProgress) + ? Math.min(Math.max(rawProgress, 0), 100) + : null; + + const rawReaction = raw.reaction; + const reaction = + typeof rawReaction === "string" && rawReaction.trim() !== "" + ? (rawReaction.trim() as ReactionStatus) + : null; + + validItems.push({ + tmdbId, + mediaType, + title, + image, + rating, + release_date, + overview, + inWatchlist, + progressStatus, + progress, + reaction, + }); - const watchedEpisodes: Array<{ - tmdbId: number; - season: number; - episode: number; - }> = []; - for (const item of validatedList) { if ( - item.watchedEpisodes && - typeof item.watchedEpisodes === "object" + mediaType === "tv" && + raw.watchedEpisodes && + typeof raw.watchedEpisodes === "object" ) { for (const [key, isWatched] of Object.entries( - item.watchedEpisodes, + raw.watchedEpisodes as Record, )) { if (!isWatched) continue; const [seasonStr, episodeStr] = key.split(":"); @@ -201,7 +308,7 @@ export const useWatchlistImportExport = () => { if (!Number.isNaN(season) && !Number.isNaN(episode)) { watchedEpisodes.push({ - tmdbId: Number(item.external_id), + tmdbId, season, episode, }); @@ -210,48 +317,57 @@ export const useWatchlistImportExport = () => { } } - setImportTotal(validatedList.length); - const importItems = validatedList.map((item) => ({ - tmdbId: Number(item.external_id), - mediaType: item.type, - title: item.title, - image: item.image, - rating: item.rating, - release_date: item.release_date, - overview: item.overview, - progressStatus: - normalizeProgressStatus(item.progressStatus as string) ?? - "watch-later", - progress: item.progress, - reaction: - item.reaction && - typeof item.reaction === "string" && - item.reaction.trim() !== "" - ? (item.reaction as ReactionStatus) - : null, - })); + if (validItems.length === 0) { + const sampleErrors = validationErrors.slice(0, 3).join(" "); + throw new Error( + `No valid items found in the watchlist file. ${sampleErrors}`, + ); + } + + // Pre-validate full payload on the client with Valibot schema + const payload = { + items: validItems, + watchedEpisodes, + }; + + const validationResult = v.safeParse( + importWatchlistArgsSchema, + payload, + ); + if (!validationResult.success) { + const firstIssue = validationResult.issues[0]; + const issuePath = + firstIssue.path?.map((p) => p.key).join(".") ?? "root"; + throw new Error( + `Validation error in ${issuePath}: ${firstIssue.message}`, + ); + } + + setImportTotal(validItems.length); if (isSignedIn) { await importWatchlistFn({ - data: { - // biome-ignore lint/suspicious/noExplicitAny: dynamic reaction item import - items: importItems as any, - watchedEpisodes, - }, + data: validationResult.output, + }); + await queryClient.invalidateQueries({ + queryKey: queryKeys.watchlist.list(), + }); + await queryClient.invalidateQueries({ + queryKey: queryKeys.watchlist.allEpisodes(), }); } else { importWatchlistLocal( - importItems.map((item) => ({ + validItems.map((item) => ({ id: String(item.tmdbId), type: item.mediaType, title: item.title, - image: item.image, - rating: item.rating, - release_date: item.release_date, - overview: item.overview, - progressStatus: item.progressStatus, - progress: item.progress, - reaction: item.reaction, + image: item.image ?? "", + rating: item.rating ?? 0, + release_date: item.release_date ?? "", + overview: item.overview ?? undefined, + progressStatus: item.progressStatus ?? undefined, + progress: item.progress ?? 0, + reaction: item.reaction ?? null, })), ); for (const episode of watchedEpisodes) { @@ -266,7 +382,7 @@ export const useWatchlistImportExport = () => { if (invalidItemCount > 0) { setError({ - message: `Successfully imported ${validatedList.length} items. ${invalidItemCount} invalid items were skipped.`, + message: `Successfully imported ${validItems.length} titles. ${invalidItemCount} invalid items were skipped.`, invalidItems: invalidItemCount, }); } else { @@ -291,7 +407,7 @@ export const useWatchlistImportExport = () => { reader.readAsText(file); }, - [importWatchlistLocal, isSignedIn, markEpisodeWatchedLocal], + [importWatchlistLocal, isSignedIn, markEpisodeWatchedLocal, queryClient], ); const handleImportClick = useCallback(() => { diff --git a/src/server/fns/import-export.ts b/src/server/fns/import-export.ts index 6b151bb6..ae06bf54 100644 --- a/src/server/fns/import-export.ts +++ b/src/server/fns/import-export.ts @@ -55,11 +55,16 @@ export const importWatchlist = createServerFn({ method: "POST" }) null; const metadata = buildMetadataPatch(item, existing ?? undefined); + const inWatchlist = + item.inWatchlist !== undefined && item.inWatchlist !== null + ? item.inWatchlist + : (existing?.inWatchlist ?? true); + if (existing) { await db .update(watchItems) .set({ - inWatchlist: true, + inWatchlist, progressStatus, progress, reaction, @@ -75,28 +80,14 @@ export const importWatchlist = createServerFn({ method: "POST" }) userId: user.id, tmdbId: item.tmdbId, mediaType: item.mediaType, - inWatchlist: true, + inWatchlist, progressStatus, progress, reaction, updatedAt: now, ...metadata, }) - .onConflictDoUpdate({ - target: [ - watchItems.userId, - watchItems.tmdbId, - watchItems.mediaType, - ], - set: { - inWatchlist: true, - progressStatus, - progress, - reaction, - updatedAt: now, - ...metadata, - }, - }); + .onConflictDoNothing(); } } @@ -120,7 +111,7 @@ export const importWatchlist = createServerFn({ method: "POST" }) } const episodeKeys = new Set(); - const episodesToUpsert: Array<{ + const episodesToInsert: Array<{ id: string; userId: string; tmdbId: number; @@ -139,18 +130,13 @@ export const importWatchlist = createServerFn({ method: "POST" }) const existingEp = existingEpisodeMap.get(key); if (existingEp) { if (!existingEp.isWatched) { - episodesToUpsert.push({ - id: existingEp.id, - userId: user.id, - tmdbId: episode.tmdbId, - season: episode.season, - episode: episode.episode, - isWatched: true, - updatedAt: now, - }); + await db + .update(episodeProgress) + .set({ isWatched: true, updatedAt: now }) + .where(eq(episodeProgress.id, existingEp.id)); } } else { - episodesToUpsert.push({ + episodesToInsert.push({ id: crypto.randomUUID(), userId: user.id, tmdbId: episode.tmdbId, @@ -162,26 +148,12 @@ export const importWatchlist = createServerFn({ method: "POST" }) } } - // Insert/upsert episodes in chunks of 50 rows (each row has 7 params => 350 params, well within SQLite limits) + // Insert new episodes in chunks of 50 rows const CHUNK_SIZE = 50; - for (let i = 0; i < episodesToUpsert.length; i += CHUNK_SIZE) { - const chunk = episodesToUpsert.slice(i, i + CHUNK_SIZE); + for (let i = 0; i < episodesToInsert.length; i += CHUNK_SIZE) { + const chunk = episodesToInsert.slice(i, i + CHUNK_SIZE); if (chunk.length > 0) { - await db - .insert(episodeProgress) - .values(chunk) - .onConflictDoUpdate({ - target: [ - episodeProgress.userId, - episodeProgress.tmdbId, - episodeProgress.season, - episodeProgress.episode, - ], - set: { - isWatched: true, - updatedAt: now, - }, - }); + await db.insert(episodeProgress).values(chunk).onConflictDoNothing(); } } diff --git a/src/server/fns/watchlist.ts b/src/server/fns/watchlist.ts index f7861e0e..db4868e9 100644 --- a/src/server/fns/watchlist.ts +++ b/src/server/fns/watchlist.ts @@ -485,18 +485,7 @@ export async function syncEpisodeProgressRecord( isWatched: args.isWatched, updatedAt: now, }) - .onConflictDoUpdate({ - target: [ - episodeProgress.userId, - episodeProgress.tmdbId, - episodeProgress.season, - episodeProgress.episode, - ], - set: { - isWatched: args.isWatched, - updatedAt: now, - }, - }); + .onConflictDoNothing(); } export const markEpisodeWatched = createServerFn({ method: "POST" }) diff --git a/src/server/helpers/watch-item.ts b/src/server/helpers/watch-item.ts index 83c629a0..22e6afee 100644 --- a/src/server/helpers/watch-item.ts +++ b/src/server/helpers/watch-item.ts @@ -170,18 +170,6 @@ export async function upsertWatchItem( updatedAt: now, ...metadataPatch, }) - .onConflictDoUpdate({ - target: [watchItems.userId, watchItems.tmdbId, watchItems.mediaType], - set: { - ...(finalUpdates.inWatchlist !== undefined && { - inWatchlist: finalUpdates.inWatchlist, - }), - ...(progressStatus !== undefined && { progressStatus }), - ...(typeof finalUpdates.progress === "number" && { progress }), - ...(reaction !== undefined && { reaction }), - updatedAt: now, - ...metadataPatch, - }, - }); + .onConflictDoNothing(); return undefined; } diff --git a/src/server/schema/import.ts b/src/server/schema/import.ts index f47159b6..e84872c0 100644 --- a/src/server/schema/import.ts +++ b/src/server/schema/import.ts @@ -5,12 +5,13 @@ export const importItemSchema = v.object({ tmdbId: v.number(), mediaType: mediaTypeSchema, title: v.string(), - image: v.optional(v.string()), - rating: v.optional(v.number()), - release_date: v.optional(v.string()), - overview: v.optional(v.string()), + image: v.optional(v.nullable(v.string())), + rating: v.optional(v.nullable(v.number())), + release_date: v.optional(v.nullable(v.string())), + overview: v.optional(v.nullable(v.string())), + inWatchlist: v.optional(v.nullable(v.boolean())), progressStatus: v.optional(v.nullable(v.string())), - progress: v.optional(v.number()), + progress: v.optional(v.nullable(v.number())), reaction: v.optional(v.nullable(v.string())), }); export type ImportItem = v.InferOutput; From 66f6f08c54e503677b0fac80c80d8cf6092aec82 Mon Sep 17 00:00:00 2001 From: Swastik Dan <57379785+Swastikdan@users.noreply.github.com> Date: Sun, 16 Aug 2026 02:58:49 +0530 Subject: [PATCH 17/27] refactor: update watchlist metadata types to handle nullability and improve progress status tracking during imports --- src/hooks/use-watchlist-import-export.ts | 7 ++++--- src/hooks/watchlist-store.ts | 12 +++++++++--- src/server/helpers/watch-item.ts | 10 +++++----- 3 files changed, 18 insertions(+), 11 deletions(-) diff --git a/src/hooks/use-watchlist-import-export.ts b/src/hooks/use-watchlist-import-export.ts index ac358b2c..af5cdc66 100644 --- a/src/hooks/use-watchlist-import-export.ts +++ b/src/hooks/use-watchlist-import-export.ts @@ -16,7 +16,7 @@ import { type ImportItem as ServerImportItem, type WatchedEpisode, } from "@/server/schema/import"; -import type { ReactionStatus } from "@/types"; +import type { ProgressStatus, ReactionStatus } from "@/types"; type ImportError = { message: string; @@ -365,9 +365,10 @@ export const useWatchlistImportExport = () => { rating: item.rating ?? 0, release_date: item.release_date ?? "", overview: item.overview ?? undefined, - progressStatus: item.progressStatus ?? undefined, + inWatchlist: item.inWatchlist ?? true, + progressStatus: (item.progressStatus as ProgressStatus) ?? null, progress: item.progress ?? 0, - reaction: item.reaction ?? null, + reaction: item.reaction as ReactionStatus | null, })), ); for (const episode of watchedEpisodes) { diff --git a/src/hooks/watchlist-store.ts b/src/hooks/watchlist-store.ts index dc0b0887..88c123b9 100644 --- a/src/hooks/watchlist-store.ts +++ b/src/hooks/watchlist-store.ts @@ -36,7 +36,8 @@ export type WatchlistItem = { export type LocalWatchlistImportItem = MediaMetadata & { id: string; type: MediaType; - progressStatus: ProgressStatus; + progressStatus?: ProgressStatus | null; + inWatchlist?: boolean; progress?: number; reaction?: ReactionStatus | null; }; @@ -313,8 +314,13 @@ export const useWatchlistStore = create()( release_date: imported.release_date ?? existing?.release_date ?? "", overview: imported.overview ?? existing?.overview, - inWatchlist: true, - progressStatus: imported.progressStatus, + inWatchlist: + imported.inWatchlist !== undefined + ? imported.inWatchlist + : (existing?.inWatchlist ?? true), + progressStatus: + imported.progressStatus ?? + (imported.inWatchlist === false ? null : "watch-later"), progress, reaction: imported.reaction ?? existing?.reaction ?? null, updated_at: now, diff --git a/src/server/helpers/watch-item.ts b/src/server/helpers/watch-item.ts index 22e6afee..8df8f2e9 100644 --- a/src/server/helpers/watch-item.ts +++ b/src/server/helpers/watch-item.ts @@ -40,11 +40,11 @@ export interface MediaIdentity { } export type WatchItemMetadata = { - title?: string; - image?: string; - rating?: number; - release_date?: string; - overview?: string; + title?: string | null; + image?: string | null; + rating?: number | null; + release_date?: string | null; + overview?: string | null; }; type MetadataDbPatch = { From 253774a1b0a91c92b612396a49689cfbf75e09c6 Mon Sep 17 00:00:00 2001 From: Swastik Dan <57379785+Swastikdan@users.noreply.github.com> Date: Sun, 16 Aug 2026 10:35:07 +0530 Subject: [PATCH 18/27] refactor: update watchlist mutation handlers to return authoritative row state for improved cache consistency --- .gitignore | 1 + src/components/default-loader.tsx | 2 +- src/components/user-sync.tsx | 9 + src/hooks/pending-ops.ts | 267 +++++++++++ src/hooks/use-custom-lists.ts | 585 +++++++++++++++-------- src/hooks/use-watch-progress.ts | 204 ++++---- src/hooks/use-watchlist-import-export.ts | 10 +- src/hooks/use-watchlist.ts | 492 +++++++++---------- src/hooks/watchlist-queries.ts | 48 ++ src/server/db/client.ts | 24 +- src/server/fns/watchlist.ts | 272 ++++++----- src/server/helpers/watch-item.ts | 45 +- 12 files changed, 1248 insertions(+), 711 deletions(-) create mode 100644 src/hooks/pending-ops.ts create mode 100644 src/hooks/watchlist-queries.ts diff --git a/.gitignore b/.gitignore index be7721f6..ef8568d1 100644 --- a/.gitignore +++ b/.gitignore @@ -25,3 +25,4 @@ skills-lock.json .wrangler/ convex-export/ +TODO.md diff --git a/src/components/default-loader.tsx b/src/components/default-loader.tsx index 8fd91706..062c8a4a 100644 --- a/src/components/default-loader.tsx +++ b/src/components/default-loader.tsx @@ -7,7 +7,7 @@ export function DefaultLoader(props: React.ComponentProps<"output">) { aria-label="Loading content" aria-busy="true" className={cn( - "grid min-h-[calc(100dvh-var(--navbar-height,4rem)-var(--mobile-nav-height,4.75rem))] md:min-h-[calc(100dvh-5rem)] min-w-[320px] w-full animate-fade-in place-items-center py-8", + "grid min-h-[100dvh] md:min-h-[calc(100dvh-5rem)] min-w-[320px] w-full animate-fade-in place-items-center py-8", props.className, )} {...props} diff --git a/src/components/user-sync.tsx b/src/components/user-sync.tsx index be8c78bb..18fa91f5 100644 --- a/src/components/user-sync.tsx +++ b/src/components/user-sync.tsx @@ -1,5 +1,6 @@ import { useClerk, useUser } from "@clerk/react"; import { useEffect } from "react"; +import { clearPendingOps } from "@/hooks/pending-ops"; import { usePermissions } from "@/hooks/use-permissions"; import { storeUser } from "@/server/fns/users"; @@ -32,5 +33,13 @@ export const UserSync = () => { } }, [isBanned, isSignedIn, loading, signOut]); + // Drop journal state (pending optimistic ops, server bases, sync timers) + // when the session ends so nothing leaks into the next signed-in user. + useEffect(() => { + if (isLoaded && !user) { + clearPendingOps(); + } + }, [isLoaded, user]); + return null; }; diff --git a/src/hooks/pending-ops.ts b/src/hooks/pending-ops.ts new file mode 100644 index 00000000..a96c3048 --- /dev/null +++ b/src/hooks/pending-ops.ts @@ -0,0 +1,267 @@ +import type { QueryClient } from "@tanstack/react-query"; + +/** + * Pending-op journal + reconcile for array-shaped query caches (watchlist, + * custom lists, ...). + * + * Every optimistic update is registered as a *replayable* op. Server snapshots + * (full-list refetches, write responses) are merged back through the journal: + * still-pending ops are re-applied on top of fresh server data, so a snapshot + * taken before a write committed can never clobber newer optimistic state (the + * "UI flicker" race). Ops are dropped once their write succeeds (`resolve`), + * and a failed write rolls back just its own op — rebuilding from the last + * known server state + remaining ops — instead of restoring an all-or-nothing + * whole-array snapshot (which used to wipe concurrent ops). + * + * Ops that touch the same rows supersede each other (latest intent wins), + * mirroring the server's per-item deduplication semantics. + */ + +export type PendingOpEntry = { + /** Query key the patch applies to (e.g. `["watchlist","list",{}]`). */ + key: readonly unknown[]; + /** Identity strings of the rows this op touches (e.g. `"movie:123"`). */ + touchedIds: string[]; + /** Extracts an identity string from a row; defaults to `mediaType:tmdbId`. */ + idOf?: (row: T) => string; + /** Pure patch applied to the array cache. Must be safe to re-run. */ + apply: (rows: T[]) => T[]; +}; + +export type OpHandle = { + /** Write succeeded: drop the op, folding its state into the server base. */ + resolve: () => void; + /** Write failed: drop the op and rebuild from base + remaining ops. */ + remove: () => void; +}; + +type RegisteredEntry = { + key: readonly unknown[]; + keyString: string; + touchedIds: string[]; + idOf: (row: unknown) => string; + apply: (rows: unknown[]) => unknown[]; +}; + +type RegisteredOp = { + seq: number; + entries: RegisteredEntry[]; +}; + +const keyString = (key: readonly unknown[]) => JSON.stringify(key); + +/** Pending ops per key, in registration order (= seq order). */ +const pendingByKey = new Map(); +/** Last known server truth per key; used to rebuild after a rollback. */ +const baseByKey = new Map(); +/** Reverse lookup: keyString -> key array (for `setQueryData`). */ +const keyByString = new Map(); +let seqCounter = 0; + +const defaultIdOf = (row: unknown) => { + const r = row as { mediaType?: unknown; tmdbId?: unknown }; + return `${String(r.mediaType)}:${String(r.tmdbId)}`; +}; + +function dropOp(keyString_: string, op: RegisteredOp) { + const list = pendingByKey.get(keyString_); + if (!list) return; + const next = list.filter((o) => o !== op); + if (next.length === 0) pendingByKey.delete(keyString_); + else pendingByKey.set(keyString_, next); +} + +/** True while `op` is still registered (i.e. not superseded by a newer op). */ +function isRegistered(op: RegisteredOp) { + return op.entries.some((entry) => + (pendingByKey.get(entry.keyString) ?? []).includes(op), + ); +} + +function replay(keyString_: string, base: unknown[]): unknown[] { + let rows = base; + for (const op of pendingByKey.get(keyString_) ?? []) { + for (const entry of op.entries) { + if (entry.keyString === keyString_) rows = entry.apply(rows); + } + } + return rows; +} + +/** + * Register one or more optimistic patches and apply them to the cache + * immediately. Returns a handle used to resolve (success) or remove (error) + * the op later. + */ +export function beginOp( + queryClient: QueryClient, + entries: PendingOpEntry[], +): OpHandle { + const seq = ++seqCounter; + const op: RegisteredOp = { + seq, + entries: entries.map((entry) => { + const keyString_ = keyString(entry.key); + keyByString.set(keyString_, entry.key); + return { + key: entry.key, + keyString: keyString_, + touchedIds: entry.touchedIds, + idOf: + (entry.idOf as ((row: unknown) => string) | undefined) ?? defaultIdOf, + apply: entry.apply as (rows: unknown[]) => unknown[], + }; + }), + }; + + for (const entry of op.entries) { + // Supersede older pending ops that touch any of the same rows — the + // latest user intent wins, matching the server batcher's dedupe. + const existing = pendingByKey.get(entry.keyString) ?? []; + const touched = new Set(entry.touchedIds); + for (const candidate of [...existing]) { + const overlaps = candidate.entries.some( + (cEntry) => + cEntry.keyString === entry.keyString && + cEntry.touchedIds.some((id) => touched.has(id)), + ); + if (overlaps) { + for (const cEntry of candidate.entries) + dropOp(cEntry.keyString, candidate); + } + } + + const list = pendingByKey.get(entry.keyString) ?? []; + list.push(op); + pendingByKey.set(entry.keyString, list); + + // First op for a key: snapshot the current (server-loaded) cache as the + // base used to rebuild after a rollback. + if (!baseByKey.has(entry.keyString)) { + const current = + (queryClient.getQueryData(entry.key) as unknown[] | undefined) ?? []; + baseByKey.set(entry.keyString, current); + } + + const current = + (queryClient.getQueryData(entry.key) as unknown[] | undefined) ?? []; + queryClient.setQueryData(entry.key, entry.apply(current)); + } + + return { + resolve: () => resolveOp(queryClient, op), + remove: () => removeOp(queryClient, op), + }; +} + +function resolveOp(queryClient: QueryClient, op: RegisteredOp) { + if (!isRegistered(op)) return; + for (const entry of op.entries) { + dropOp(entry.keyString, op); + // The optimistic state is now server-confirmed, so fold it into the + // base so a later rollback rebuild doesn't lose it. + const base = baseByKey.get(entry.keyString); + if (!base || entry.touchedIds.length === 0) continue; + const current = + (queryClient.getQueryData(entry.key) as unknown[] | undefined) ?? []; + const touched = new Set(entry.touchedIds); + const nextBase = base.filter((row) => !touched.has(entry.idOf(row))); + for (const row of current) { + if (touched.has(entry.idOf(row))) nextBase.push(row); + } + baseByKey.set(entry.keyString, nextBase); + } +} + +function removeOp(queryClient: QueryClient, op: RegisteredOp) { + if (!isRegistered(op)) return; + const affected = new Set(); + for (const entry of op.entries) { + dropOp(entry.keyString, op); + affected.add(entry.keyString); + } + for (const keyString_ of affected) { + const base = baseByKey.get(keyString_); + const key = keyByString.get(keyString_); + if (!base || !key) continue; + queryClient.setQueryData(key, replay(keyString_, base)); + } +} + +/** + * Wrap a watchlist fetch: remember the server snapshot as the new base and + * re-apply still-pending optimistic ops on top before returning. This makes + * refetches safe even when a response was computed before a write committed. + */ +export function reconcileListFetch( + key: readonly unknown[], + fetchedRows: T[], +): T[] { + const keyString_ = keyString(key); + keyByString.set(keyString_, key); + baseByKey.set(keyString_, fetchedRows as unknown[]); + return replay(keyString_, fetchedRows) as T[]; +} + +/** + * Merge rows returned by a write (e.g. a batched membership mutation) into the + * cache. Touched items come from the server; touched items missing from the + * response were deleted. Pending ops for other items are re-applied on top, so + * the UI never regresses behind in-flight optimistic updates. + */ +export function applyServerState( + queryClient: QueryClient, + key: readonly unknown[], + serverRows: T[], + touchedIds: string[], + idOf?: (row: T) => string, +) { + const keyString_ = keyString(key); + keyByString.set(keyString_, key); + const current = (queryClient.getQueryData(key) as T[] | undefined) ?? []; + const id = idOf ?? (defaultIdOf as (row: T) => string); + const touched = new Set(touchedIds); + + const truth = current.filter((row) => !touched.has(id(row))); + for (const row of serverRows) { + const idx = truth.findIndex((r) => id(r) === id(row)); + if (idx === -1) truth.push(row); + else truth[idx] = row; + } + + baseByKey.set(keyString_, truth as unknown[]); + queryClient.setQueryData(key, replay(keyString_, truth) as T[]); +} + +const syncTimers = new Map>(); + +/** + * Debounce cache invalidations so N rapid mutations produce a single refetch + * (which itself reconciles pending ops). Keys are matched as prefixes, so + * `["watchlist","list"]` refreshes both the full list and filtered variants. + */ +export function scheduleSync( + queryClient: QueryClient, + keys: readonly (readonly unknown[])[], + delayMs = 250, +) { + for (const key of keys) { + const keyString_ = keyString(key); + const existing = syncTimers.get(keyString_); + if (existing) clearTimeout(existing); + const timer = setTimeout(() => { + syncTimers.delete(keyString_); + queryClient.invalidateQueries({ queryKey: key, exact: false }); + }, delayMs); + syncTimers.set(keyString_, timer); + } +} + +/** Forget all journal state (used when a user signs out). */ +export function clearPendingOps() { + pendingByKey.clear(); + baseByKey.clear(); + keyByString.clear(); + for (const timer of syncTimers.values()) clearTimeout(timer); + syncTimers.clear(); +} diff --git a/src/hooks/use-custom-lists.ts b/src/hooks/use-custom-lists.ts index 6cc6b7e3..1f5a1c04 100644 --- a/src/hooks/use-custom-lists.ts +++ b/src/hooks/use-custom-lists.ts @@ -1,10 +1,5 @@ import { useUser } from "@clerk/react"; -import { - type QueryClient, - useMutation, - useQuery, - useQueryClient, -} from "@tanstack/react-query"; +import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query"; import { useCallback, useMemo } from "react"; import { queryKeys } from "@/lib/query/keys"; import type { CustomListRow, ListItemRow } from "@/lib/server-types"; @@ -20,17 +15,51 @@ import { } from "@/server/fns/lists"; import { unwrap } from "@/server/schema/common"; import type { ProgressStatus, ReactionStatus } from "@/types"; -import { beginOptimistic } from "./optimistic-helpers"; +import { + beginOp, + type OpHandle, + type PendingOpEntry, + reconcileListFetch, + scheduleSync, +} from "./pending-ops"; import { useLocalListsStore } from "./use-local-lists-store"; import { useWatchlistStore } from "./watchlist-store"; +// --------------------------------------------------------------------------- +// Reads (routed through the reconciler so refetches can't clobber pending ops) +// --------------------------------------------------------------------------- + +async function fetchCustomLists(): Promise { + return reconcileListFetch( + queryKeys.lists.all(), + await unwrap(getCustomLists()), + ); +} + +async function fetchListItems(listId: string): Promise { + return reconcileListFetch( + queryKeys.lists.items(listId), + await unwrap(getListItems({ data: { listId } })), + ); +} + +async function fetchItemLists( + tmdbId: number, + mediaType: "movie" | "tv", +): Promise { + return reconcileListFetch( + queryKeys.lists.itemLists(tmdbId, mediaType), + await unwrap(getItemLists({ data: { tmdbId, mediaType } })), + ); +} + export function useCustomLists() { const { isSignedIn } = useUser(); const localLists = useLocalListsStore((state) => state.lists); const localItems = useLocalListsStore((state) => state.listItems); const remote = useQuery({ queryKey: queryKeys.lists.all(), - queryFn: () => unwrap(getCustomLists()), + queryFn: fetchCustomLists, enabled: !!isSignedIn, }); @@ -75,7 +104,7 @@ export function useCustomListItems(listId: string | null) { const localMediaState = useWatchlistStore((state) => state.mediaState); const remote = useQuery({ queryKey: queryKeys.lists.items(listId ?? ""), - queryFn: () => unwrap(getListItems({ data: { listId: listId! } })), + queryFn: () => fetchListItems(listId!), enabled: !!isSignedIn && !!listId, }); @@ -122,7 +151,7 @@ export function useItemLists(tmdbId: number, mediaType: "movie" | "tv") { const localItems = useLocalListsStore((state) => state.listItems); const remote = useQuery({ queryKey: queryKeys.lists.itemLists(tmdbId, mediaType), - queryFn: () => unwrap(getItemLists({ data: { tmdbId, mediaType } })), + queryFn: () => fetchItemLists(tmdbId, mediaType), enabled: !!isSignedIn, }); @@ -134,20 +163,58 @@ export function useItemLists(tmdbId: number, mediaType: "movie" | "tv") { }, [isSignedIn, remote.data, tmdbId, mediaType, localItems]); } -async function deleteCustomListOptimistic( - queryClient: QueryClient, - listId: string, +// --------------------------------------------------------------------------- +// Journal helpers +// --------------------------------------------------------------------------- + +const listIdOf = (list: CustomListRow) => list.id; +const stringIdOf = (id: string) => id; +const itemTmdbIdOf = (item: ListItemRow) => String(item.tmdbId); + +type MixedListRow = CustomListRow | ListItemRow | string; + +/** Swap an optimistic list id for the server-assigned id across affected caches. */ +function swapListId( + queryClient: ReturnType, + optimisticId: string, + realId: string, + itemListsKey?: readonly unknown[], ) { - return beginOptimistic(queryClient, [queryKeys.lists.all()], () => { - const current = - (queryClient.getQueryData(queryKeys.lists.all()) as - | CustomListRow[] - | undefined) ?? []; + const key = queryKeys.lists.all(); + const rows = queryClient.getQueryData(key); + if (rows) { queryClient.setQueryData( - queryKeys.lists.all(), - current.filter((l) => l.id !== listId), + key, + rows.map((l) => (l.id === optimisticId ? { ...l, id: realId } : l)), ); - }); + } + if (itemListsKey) { + const itemLists = queryClient.getQueryData(itemListsKey); + if (itemLists) { + queryClient.setQueryData( + itemListsKey, + itemLists.map((id) => (id === optimisticId ? realId : id)), + ); + } + } +} + +// --------------------------------------------------------------------------- +// Delete +// --------------------------------------------------------------------------- + +function beginDeleteListOp( + queryClient: ReturnType, + listId: string, +): OpHandle { + return beginOp(queryClient, [ + { + key: queryKeys.lists.all(), + touchedIds: [listId], + idOf: listIdOf, + apply: (rows: CustomListRow[]) => rows.filter((l) => l.id !== listId), + }, + ]); } export function useDeleteCustomList() { @@ -158,13 +225,19 @@ export function useDeleteCustomList() { const mutation = useMutation({ mutationFn: (listId: string) => unwrap(deleteCustomList({ data: { listId } })), - onMutate: (listId) => deleteCustomListOptimistic(queryClient, listId), - onError: (error, _listId, rollback) => { + onMutate: (listId) => beginDeleteListOp(queryClient, listId), + onSuccess: (_data, _listId, handle) => handle?.resolve(), + onError: (error, _listId, handle) => { console.error("Failed to delete custom list", error); - rollback?.(); + handle?.remove(); }, onSettled: () => { - void queryClient.invalidateQueries({ queryKey: queryKeys.lists.all() }); + // Deleting a list orphans its items and their item-lists entries. + scheduleSync(queryClient, [ + queryKeys.lists.all(), + ["lists", "items"], + ["lists", "item-lists"], + ]); }, }); @@ -180,6 +253,10 @@ export function useDeleteCustomList() { ); } +// --------------------------------------------------------------------------- +// Create +// --------------------------------------------------------------------------- + type CreateListArgs = { name: string; color?: string; @@ -187,33 +264,35 @@ type CreateListArgs = { listType?: string; }; -async function createCustomListOptimistic( - queryClient: QueryClient, +function beginCreateListOp( + queryClient: ReturnType, args: CreateListArgs, -) { - return beginOptimistic(queryClient, [queryKeys.lists.all()], () => { - const current = - (queryClient.getQueryData(queryKeys.lists.all()) as - | CustomListRow[] - | undefined) ?? []; - const now = Date.now(); - queryClient.setQueryData(queryKeys.lists.all(), [ - ...current, - { - id: `optimistic_${now}`, - userId: "optimistic", - name: args.name, - color: args.color ?? null, - visibility: args.visibility ?? null, - listType: args.listType ?? null, - sortOrder: current.length, - createdAt: now, - updatedAt: now, - previews: [], - itemCount: 0, - }, - ]); - }); + optimisticId: string, +): OpHandle { + const now = Date.now(); + return beginOp(queryClient, [ + { + key: queryKeys.lists.all(), + touchedIds: [optimisticId], + idOf: listIdOf, + apply: (rows: CustomListRow[]) => [ + ...rows, + { + id: optimisticId, + userId: "optimistic", + name: args.name, + color: args.color ?? null, + visibility: args.visibility ?? null, + listType: args.listType ?? null, + sortOrder: rows.length, + createdAt: now, + updatedAt: now, + previews: [], + itemCount: 0, + }, + ], + }, + ]); } export function useCreateCustomList() { @@ -224,13 +303,25 @@ export function useCreateCustomList() { const mutation = useMutation({ mutationFn: (args: CreateListArgs) => unwrap(createCustomList({ data: args })), - onMutate: (args) => createCustomListOptimistic(queryClient, args), - onError: (error, _args, rollback) => { + onMutate: (args) => { + const optimisticId = `optimistic_${Date.now()}`; + return { + handle: beginCreateListOp(queryClient, args, optimisticId), + optimisticId, + }; + }, + onSuccess: (realId, _args, context) => { + if (context?.optimisticId) { + swapListId(queryClient, context.optimisticId, realId); + } + context?.handle?.resolve(); + }, + onError: (error, _args, context) => { console.error("Failed to create custom list", error); - rollback?.(); + context?.handle?.remove(); }, onSettled: () => { - void queryClient.invalidateQueries({ queryKey: queryKeys.lists.all() }); + scheduleSync(queryClient, [queryKeys.lists.all()]); }, }); @@ -250,6 +341,10 @@ export function useCreateCustomList() { ); } +// --------------------------------------------------------------------------- +// Create + add item +// --------------------------------------------------------------------------- + type CreateListAndAddArgs = CreateListArgs & { tmdbId: number; mediaType: "movie" | "tv"; @@ -261,26 +356,20 @@ type CreateListAndAddArgs = CreateListArgs & { overview?: string; }; -async function createListAndAddOptimistic( - queryClient: QueryClient, +function beginCreateListAndAddOp( + queryClient: ReturnType, args: CreateListAndAddArgs, -) { + optimisticId: string, +): OpHandle { const now = Date.now(); - const optimisticId = `optimistic_${now}`; - return beginOptimistic( - queryClient, - [ - queryKeys.lists.all(), - queryKeys.lists.items(optimisticId), - queryKeys.lists.itemLists(args.tmdbId, args.mediaType), - ], - () => { - const current = - (queryClient.getQueryData(queryKeys.lists.all()) as - | CustomListRow[] - | undefined) ?? []; - queryClient.setQueryData(queryKeys.lists.all(), [ - ...current, + const itemListsKey = queryKeys.lists.itemLists(args.tmdbId, args.mediaType); + const entries: PendingOpEntry[] = [ + { + key: queryKeys.lists.all(), + touchedIds: [optimisticId], + idOf: listIdOf as (row: MixedListRow) => string, + apply: (rows) => [ + ...(rows as CustomListRow[]), { id: optimisticId, userId: "optimistic", @@ -288,28 +377,27 @@ async function createListAndAddOptimistic( color: args.color ?? null, visibility: args.visibility ?? null, listType: args.listType ?? null, - sortOrder: current.length, + sortOrder: (rows as CustomListRow[]).length, createdAt: now, updatedAt: now, previews: [args.backdrop ?? args.image].filter(Boolean) as string[], itemCount: 1, }, - ]); - - const itemListsKey = queryKeys.lists.itemLists( - args.tmdbId, - args.mediaType, - ); - const currentItemLists = - (queryClient.getQueryData(itemListsKey) as - | string[] - | undefined) ?? []; - queryClient.setQueryData(itemListsKey, [ - ...currentItemLists, - optimisticId, - ]); + ], }, - ); + { + key: itemListsKey, + touchedIds: [optimisticId], + idOf: stringIdOf as (row: MixedListRow) => string, + apply: (rows) => { + const current = rows as string[]; + return current.includes(optimisticId) + ? current + : [...current, optimisticId]; + }, + }, + ]; + return beginOp(queryClient, entries); } export function useCreateCustomListAndAddItem() { @@ -322,15 +410,34 @@ export function useCreateCustomListAndAddItem() { const mutation = useMutation({ mutationFn: (args: CreateListAndAddArgs) => unwrap(createCustomListAndAddItem({ data: args })), - onMutate: (args) => createListAndAddOptimistic(queryClient, args), - onError: (error, _args, rollback) => { + onMutate: (args) => { + const optimisticId = `optimistic_${Date.now()}`; + return { + handle: beginCreateListAndAddOp(queryClient, args, optimisticId), + optimisticId, + }; + }, + onSuccess: (realId, args, context) => { + if (context?.optimisticId) { + swapListId( + queryClient, + context.optimisticId, + realId, + queryKeys.lists.itemLists(args.tmdbId, args.mediaType), + ); + } + context?.handle?.resolve(); + }, + onError: (error, _args, context) => { console.error("Failed to create list and add item", error); - rollback?.(); + context?.handle?.remove(); }, onSettled: () => { - void queryClient.invalidateQueries({ queryKey: queryKeys.lists.all() }); - void queryClient.invalidateQueries({ queryKey: ["lists", "items"] }); - void queryClient.invalidateQueries({ queryKey: ["lists", "item-lists"] }); + scheduleSync(queryClient, [ + queryKeys.lists.all(), + ["lists", "items"], + ["lists", "item-lists"], + ]); }, }); @@ -345,35 +452,40 @@ export function useCreateCustomListAndAddItem() { ); } +// --------------------------------------------------------------------------- +// Update +// --------------------------------------------------------------------------- + type UpdateListArgs = CreateListArgs & { listId: string }; -async function updateCustomListOptimistic( - queryClient: QueryClient, +function beginUpdateListOp( + queryClient: ReturnType, args: UpdateListArgs, -) { - return beginOptimistic(queryClient, [queryKeys.lists.all()], () => { - const current = - (queryClient.getQueryData(queryKeys.lists.all()) as - | CustomListRow[] - | undefined) ?? []; - queryClient.setQueryData( - queryKeys.lists.all(), - current.map((l) => - l.id === args.listId - ? { - ...l, - ...(args.name !== undefined && { name: args.name }), - ...(args.color !== undefined && { color: args.color }), - ...(args.visibility !== undefined && { - visibility: args.visibility, - }), - ...(args.listType !== undefined && { listType: args.listType }), - updatedAt: Date.now(), - } - : l, - ), - ); - }); +): OpHandle { + return beginOp(queryClient, [ + { + key: queryKeys.lists.all(), + touchedIds: [args.listId], + idOf: listIdOf, + apply: (rows: CustomListRow[]) => + rows.map((l) => + l.id === args.listId + ? { + ...l, + ...(args.name !== undefined && { name: args.name }), + ...(args.color !== undefined && { color: args.color }), + ...(args.visibility !== undefined && { + visibility: args.visibility, + }), + ...(args.listType !== undefined && { + listType: args.listType, + }), + updatedAt: Date.now(), + } + : l, + ), + }, + ]); } export function useUpdateCustomList() { @@ -384,13 +496,14 @@ export function useUpdateCustomList() { const mutation = useMutation({ mutationFn: (args: UpdateListArgs) => unwrap(updateCustomList({ data: args })), - onMutate: (args) => updateCustomListOptimistic(queryClient, args), - onError: (error, _args, rollback) => { + onMutate: (args) => beginUpdateListOp(queryClient, args), + onSuccess: (_data, _args, handle) => handle?.resolve(), + onError: (error, _args, handle) => { console.error("Failed to update custom list", error); - rollback?.(); + handle?.remove(); }, onSettled: () => { - void queryClient.invalidateQueries({ queryKey: queryKeys.lists.all() }); + scheduleSync(queryClient, [queryKeys.lists.all()]); }, }); @@ -412,6 +525,10 @@ export function useUpdateCustomList() { ); } +// --------------------------------------------------------------------------- +// Toggle list item +// --------------------------------------------------------------------------- + type ToggleListItemArgs = { listId: string; tmdbId: number; @@ -424,85 +541,139 @@ type ToggleListItemArgs = { overview?: string; }; -async function toggleListItemOptimistic( - queryClient: QueryClient, +type ToggleMedia = { + listId: string; + tmdbId: number; + mediaType: "movie" | "tv"; +}; + +function buildOptimisticListItem(args: ToggleListItemArgs): ListItemRow { + return { + id: `optimistic_${Date.now()}`, + userId: "optimistic", + listId: args.listId, + tmdbId: args.tmdbId, + mediaType: args.mediaType, + addedAt: Date.now(), + title: args.title ?? null, + image: args.image ?? null, + backdrop: args.backdrop ?? null, + rating: args.rating ?? null, + releaseDate: args.release_date ?? null, + overview: args.overview ?? null, + progressStatus: null, + reaction: null, + } as ListItemRow; +} + +function applyItemListsToggle( + rows: string[], + args: ToggleMedia, + adding: boolean, +): string[] { + return adding + ? rows.includes(args.listId) + ? rows + : [...rows, args.listId] + : rows.filter((id) => id !== args.listId); +} + +function applyItemsToggle( + rows: ListItemRow[], + args: ToggleListItemArgs, + adding: boolean, +): ListItemRow[] { + if (!adding) return rows.filter((i) => i.tmdbId !== args.tmdbId); + if (rows.some((i) => i.tmdbId === args.tmdbId)) return rows; + return [...rows, buildOptimisticListItem(args)]; +} + +function applyListCountToggle( + rows: CustomListRow[], + args: ToggleMedia, + adding: boolean, +): CustomListRow[] { + return rows.map((l) => + l.id === args.listId + ? { + ...l, + itemCount: adding + ? (l.itemCount ?? 0) + 1 + : Math.max(0, (l.itemCount ?? 1) - 1), + updatedAt: Date.now(), + } + : l, + ); +} + +function beginToggleListItemOp( + queryClient: ReturnType, + args: ToggleListItemArgs, +): { handle: OpHandle; adding: boolean } { + const itemListsKey = queryKeys.lists.itemLists(args.tmdbId, args.mediaType); + const itemsKey = queryKeys.lists.items(args.listId); + const currentItemLists = (queryClient.getQueryData(itemListsKey) ?? + []) as string[]; + const adding = !currentItemLists.includes(args.listId); + + const entries: PendingOpEntry[] = [ + { + key: itemListsKey, + touchedIds: [args.listId], + idOf: stringIdOf as (row: MixedListRow) => string, + apply: (rows) => applyItemListsToggle(rows as string[], args, adding), + }, + { + key: itemsKey, + touchedIds: [String(args.tmdbId)], + idOf: itemTmdbIdOf as (row: MixedListRow) => string, + apply: (rows) => applyItemsToggle(rows as ListItemRow[], args, adding), + }, + { + key: queryKeys.lists.all(), + touchedIds: [args.listId], + idOf: listIdOf as (row: MixedListRow) => string, + apply: (rows) => + applyListCountToggle(rows as CustomListRow[], args, adding), + }, + ]; + + return { handle: beginOp(queryClient, entries), adding }; +} + +/** The server returned the authoritative new state; flip the optimistic patch if it disagreed. */ +function applyToggleInverse( + queryClient: ReturnType, args: ToggleListItemArgs, + adding: boolean, ) { + const inverse = !adding; const itemListsKey = queryKeys.lists.itemLists(args.tmdbId, args.mediaType); const itemsKey = queryKeys.lists.items(args.listId); - return beginOptimistic( - queryClient, - [itemListsKey, itemsKey, queryKeys.lists.all()], - () => { - const currentItemLists = - (queryClient.getQueryData(itemListsKey) as - | string[] - | undefined) ?? []; - const exists = currentItemLists.includes(args.listId); - - if (exists) { - queryClient.setQueryData( - itemListsKey, - currentItemLists.filter((id) => id !== args.listId), - ); - } else { - queryClient.setQueryData(itemListsKey, [ - ...currentItemLists, - args.listId, - ]); - } - const currentItems = - (queryClient.getQueryData(itemsKey) as - | ListItemRow[] - | undefined) ?? []; - if (exists) { - queryClient.setQueryData( - itemsKey, - currentItems.filter((i) => i.tmdbId !== args.tmdbId), - ); - } else { - queryClient.setQueryData(itemsKey, [ - ...currentItems, - { - id: `optimistic_${Date.now()}`, - userId: "optimistic", - listId: args.listId, - tmdbId: args.tmdbId, - mediaType: args.mediaType, - addedAt: Date.now(), - title: args.title ?? null, - image: args.image ?? null, - backdrop: args.backdrop ?? null, - rating: args.rating ?? null, - releaseDate: args.release_date ?? null, - overview: args.overview ?? null, - progressStatus: null, - reaction: null, - } as ListItemRow, - ]); - } + const itemLists = (queryClient.getQueryData(itemListsKey) ?? + []) as string[]; + queryClient.setQueryData( + itemListsKey, + applyItemListsToggle(itemLists, args, inverse), + ); - const lists = - (queryClient.getQueryData(queryKeys.lists.all()) as - | CustomListRow[] - | undefined) ?? []; - queryClient.setQueryData( - queryKeys.lists.all(), - lists.map((l) => - l.id === args.listId - ? { - ...l, - itemCount: exists - ? Math.max(0, (l.itemCount ?? 1) - 1) - : (l.itemCount ?? 0) + 1, - updatedAt: Date.now(), - } - : l, - ), - ); - }, + const items = (queryClient.getQueryData(itemsKey) ?? + []) as ListItemRow[]; + queryClient.setQueryData( + itemsKey, + applyItemsToggle(items, args, inverse), ); + + const lists = (queryClient.getQueryData( + queryKeys.lists.all(), + ) ?? []) as CustomListRow[] | undefined; + if (lists) { + queryClient.setQueryData( + queryKeys.lists.all(), + applyListCountToggle(lists, args, inverse), + ); + } } export function useToggleListItem() { @@ -515,15 +686,23 @@ export function useToggleListItem() { const mutation = useMutation({ mutationFn: (args: ToggleListItemArgs) => unwrap(toggleListItem({ data: args })), - onMutate: (args) => toggleListItemOptimistic(queryClient, args), - onError: (error, _args, rollback) => { + onMutate: (args) => beginToggleListItemOp(queryClient, args), + onSuccess: (result, args, context) => { + if (context && result !== context.adding) { + applyToggleInverse(queryClient, args, context.adding); + } + context?.handle?.resolve(); + }, + onError: (error, _args, context) => { console.error("Failed to toggle list item", error); - rollback?.(); + context?.handle?.remove(); }, onSettled: () => { - void queryClient.invalidateQueries({ queryKey: queryKeys.lists.all() }); - void queryClient.invalidateQueries({ queryKey: ["lists", "items"] }); - void queryClient.invalidateQueries({ queryKey: ["lists", "item-lists"] }); + scheduleSync(queryClient, [ + queryKeys.lists.all(), + ["lists", "items"], + ["lists", "item-lists"], + ]); }, }); diff --git a/src/hooks/use-watch-progress.ts b/src/hooks/use-watch-progress.ts index c86037a7..d69b8d6d 100644 --- a/src/hooks/use-watch-progress.ts +++ b/src/hooks/use-watch-progress.ts @@ -4,17 +4,19 @@ import { useCallback, useEffect, useMemo, useState } from "react"; import { queryKeys } from "@/lib/query/keys"; import type { EpisodeProgressRow } from "@/lib/server-types"; import { - getAllWatchedEpisodes, - getWatchlist, markEpisodeWatched, markSeasonEpisodesWatched, setProgressStatus, updateProgress, } from "@/server/fns/watchlist"; import { unwrap } from "@/server/schema/common"; -import { beginOptimistic } from "./optimistic-helpers"; +import { beginOp, scheduleSync } from "./pending-ops"; import { useLocalProgressStore } from "./use-local-progress-store"; import { useMediaState, useWatchlistStore } from "./use-watchlist"; +import { + fetchWatchedEpisodes, + fetchWatchlistListFiltered, +} from "./watchlist-queries"; export interface WatchProgressData { id: string; @@ -154,6 +156,67 @@ function createOptimisticEpisodeProgress( }; } +const episodeRowIdOf = (row: EpisodeProgressRow) => + `${row.tmdbId}:${row.season}:${row.episode}`; + +function toggleEpisodeRows( + rows: EpisodeProgressRow[], + args: { tmdbId: number; season: number; episode: number; isWatched: boolean }, +): EpisodeProgressRow[] { + if (!args.isWatched) { + return rows.filter( + (episode) => + !(episode.season === args.season && episode.episode === args.episode), + ); + } + const already = rows.some( + (episode) => + episode.season === args.season && episode.episode === args.episode, + ); + if (already) return rows; + const now = Date.now(); + return [ + ...rows, + createOptimisticEpisodeProgress( + args.tmdbId, + args.season, + args.episode, + String(now), + now, + ), + ]; +} + +function toggleSeasonRows( + rows: EpisodeProgressRow[], + args: { + tmdbId: number; + season: number; + episodes: number[]; + isWatched: boolean; + }, +): EpisodeProgressRow[] { + const filtered = rows.filter( + (episode) => + !( + episode.season === args.season && + args.episodes.includes(episode.episode) + ), + ); + if (!args.isWatched) return filtered; + const now = Date.now(); + const newEpisodes = args.episodes.map((episode) => + createOptimisticEpisodeProgress( + args.tmdbId, + args.season, + episode, + `${now}_${episode}`, + now, + ), + ); + return [...filtered, ...newEpisodes]; +} + export function usePlayerProgressListener(activeContext?: { tmdbId: number; mediaType: "movie" | "tv"; @@ -166,6 +229,7 @@ export function usePlayerProgressListener(activeContext?: { overview?: string; }) { const { isSignedIn } = useUser(); + const queryClient = useQueryClient(); const setLocalProgress = useWatchlistStore((state) => state.setProgressLocal); const markLocalEpisode = useLocalProgressStore( (state) => state.markEpisodeWatched, @@ -182,6 +246,9 @@ export function usePlayerProgressListener(activeContext?: { release_date?: string; overview?: string; }) => unwrap(updateProgress({ data: args })), + onSettled: () => { + scheduleSync(queryClient, [queryKeys.watchlist.list()]); + }, }); const markEpisodeMutation = useMutation({ @@ -191,6 +258,9 @@ export function usePlayerProgressListener(activeContext?: { episode: number; isWatched: boolean; }) => unwrap(markEpisodeWatched({ data: args })), + onSettled: (_data, _error, args) => { + scheduleSync(queryClient, [queryKeys.watchlist.episodes(args.tmdbId)]); + }, }); useEffect(() => { @@ -370,7 +440,7 @@ export function useWatchProgress( const watchedEpisodesQuery = useQuery({ queryKey: queryKeys.watchlist.episodes(tmdbId), - queryFn: () => unwrap(getAllWatchedEpisodes({ data: { tmdbId } })), + queryFn: () => fetchWatchedEpisodes(tmdbId), enabled: !!isSignedIn && mediaType === "tv", }); const watchedEpisodes = watchedEpisodesQuery.data ?? []; @@ -503,11 +573,7 @@ export function useContinueWatching() { const remote = useQuery({ queryKey: queryKeys.watchlist.list({ statusFilter: "watching", limit: 50 }), queryFn: () => - unwrap( - getWatchlist({ - data: { statusFilter: "watching", limit: 50 }, - }), - ), + fetchWatchlistListFiltered({ statusFilter: "watching", limit: 50 }), enabled: !!isSignedIn, }); const localMediaState = useWatchlistStore((state) => state.mediaState); @@ -576,9 +642,7 @@ export function useRemoveFromContinueWatching() { }), ), onSettled: () => { - void queryClient.invalidateQueries({ - queryKey: queryKeys.watchlist.list(), - }); + scheduleSync(queryClient, [queryKeys.watchlist.list()]); }, }); @@ -611,7 +675,7 @@ export function useEpisodeWatched( const mediaState = useMediaState(String(tvId), "tv"); const watchedEpisodesQuery = useQuery({ queryKey: queryKeys.watchlist.episodes(tmdbId), - queryFn: () => unwrap(getAllWatchedEpisodes({ data: { tmdbId } })), + queryFn: () => fetchWatchedEpisodes(tmdbId), enabled: !!isSignedIn, }); const watchedEpisodes = watchedEpisodesQuery.data ?? []; @@ -672,50 +736,24 @@ export function useEpisodeWatched( episode: number; isWatched: boolean; }) => unwrap(markEpisodeWatched({ data: args })), - onMutate: async (args) => { + onMutate: (args) => { const key = queryKeys.watchlist.episodes(args.tmdbId); - return beginOptimistic(queryClient, [key], () => { - const current = (queryClient.getQueryData(key) ?? - []) as EpisodeProgressRow[]; - if (!args.isWatched) { - queryClient.setQueryData( - key, - current.filter( - (episode) => - !( - episode.season === args.season && - episode.episode === args.episode - ), - ), - ); - return; - } - const already = current.some( - (episode) => - episode.season === args.season && episode.episode === args.episode, - ); - if (already) return; - const now = Date.now(); - queryClient.setQueryData(key, [ - ...current, - createOptimisticEpisodeProgress( - args.tmdbId, - args.season, - args.episode, - String(now), - now, - ), - ]); - }); + return beginOp(queryClient, [ + { + key, + touchedIds: [`${args.tmdbId}:${args.season}:${args.episode}`], + idOf: episodeRowIdOf, + apply: (rows: EpisodeProgressRow[]) => toggleEpisodeRows(rows, args), + }, + ]); }, - onError: (error, _args, rollback) => { + onSuccess: (_data, _args, handle) => handle?.resolve(), + onError: (error, _args, handle) => { logWatchProgressError("toggle episode watched", error); - rollback?.(); + handle?.remove(); }, - onSettled: () => { - void queryClient.invalidateQueries({ - queryKey: ["watchlist", "episodes"], - }); + onSettled: (_data, _error, args) => { + scheduleSync(queryClient, [queryKeys.watchlist.episodes(args.tmdbId)]); }, }); @@ -726,46 +764,26 @@ export function useEpisodeWatched( episodes: number[]; isWatched: boolean; }) => unwrap(markSeasonEpisodesWatched({ data: args })), - onMutate: async (args) => { + onMutate: (args) => { const key = queryKeys.watchlist.episodes(args.tmdbId); - return beginOptimistic(queryClient, [key], () => { - const current = (queryClient.getQueryData(key) ?? - []) as EpisodeProgressRow[]; - const filtered = current.filter( - (episode) => - !( - episode.season === args.season && - args.episodes.includes(episode.episode) - ), - ); - if (!args.isWatched) { - queryClient.setQueryData(key, filtered); - return; - } - const now = Date.now(); - const newEpisodes = args.episodes.map((episode) => - createOptimisticEpisodeProgress( - args.tmdbId, - args.season, - episode, - `${now}_${episode}`, - now, + return beginOp(queryClient, [ + { + key, + touchedIds: args.episodes.map( + (episode) => `${args.tmdbId}:${args.season}:${episode}`, ), - ); - queryClient.setQueryData(key, [ - ...filtered, - ...newEpisodes, - ]); - }); + idOf: episodeRowIdOf, + apply: (rows: EpisodeProgressRow[]) => toggleSeasonRows(rows, args), + }, + ]); }, - onError: (error, _args, rollback) => { + onSuccess: (_data, _args, handle) => handle?.resolve(), + onError: (error, _args, handle) => { logWatchProgressError("mark season episodes watched", error); - rollback?.(); + handle?.remove(); }, - onSettled: () => { - void queryClient.invalidateQueries({ - queryKey: ["watchlist", "episodes"], - }); + onSettled: (_data, _error, args) => { + scheduleSync(queryClient, [queryKeys.watchlist.episodes(args.tmdbId)]); }, }); @@ -775,6 +793,9 @@ export function useEpisodeWatched( mediaType: "movie" | "tv"; progress?: number; }) => unwrap(updateProgress({ data: args })), + onSettled: () => { + scheduleSync(queryClient, [queryKeys.watchlist.list()]); + }, }); const setProgressStatusMutation = useMutation({ @@ -790,9 +811,7 @@ export function useEpisodeWatched( overview?: string; }) => unwrap(setProgressStatus({ data: args })), onSettled: () => { - void queryClient.invalidateQueries({ - queryKey: queryKeys.watchlist.list(), - }); + scheduleSync(queryClient, [queryKeys.watchlist.list()]); }, }); @@ -1068,8 +1087,7 @@ export function useEpisodeProgress( const data = useQuery({ queryKey: queryKeys.watchlist.episodes(Number(tvId)), - queryFn: () => - unwrap(getAllWatchedEpisodes({ data: { tmdbId: Number(tvId) } })), + queryFn: () => fetchWatchedEpisodes(Number(tvId)), enabled: !!isSignedIn, }); diff --git a/src/hooks/use-watchlist-import-export.ts b/src/hooks/use-watchlist-import-export.ts index af5cdc66..20714cc2 100644 --- a/src/hooks/use-watchlist-import-export.ts +++ b/src/hooks/use-watchlist-import-export.ts @@ -5,12 +5,11 @@ import { useCallback, useRef, useState } from "react"; import * as v from "valibot"; import { useLocalProgressStore } from "@/hooks/use-local-progress-store"; import { useWatchlist, useWatchlistStore } from "@/hooks/use-watchlist"; +import { fetchAllEpisodeProgress } from "@/hooks/watchlist-queries"; import { queryKeys } from "@/lib/query/keys"; import type { AllEpisodeProgressRow } from "@/lib/server-types"; import { normalizeProgressStatus } from "@/lib/utils"; import { importWatchlist as importWatchlistFn } from "@/server/fns/import-export"; -import { getAllEpisodeProgress } from "@/server/fns/watchlist"; -import { unwrap } from "@/server/schema/common"; import { importWatchlistArgsSchema, type ImportItem as ServerImportItem, @@ -67,7 +66,7 @@ export const useWatchlistImportExport = () => { const { isSignedIn } = useUser(); const allEpisodeProgress = useQuery({ queryKey: queryKeys.watchlist.allEpisodes(), - queryFn: () => unwrap(getAllEpisodeProgress()), + queryFn: fetchAllEpisodeProgress, enabled: !!isSignedIn, }); const fileInputRef = useRef(null); @@ -355,6 +354,11 @@ export const useWatchlistImportExport = () => { await queryClient.invalidateQueries({ queryKey: queryKeys.watchlist.allEpisodes(), }); + // Imported shows also write episode progress — refresh any + // per-show episode caches. + await queryClient.invalidateQueries({ + queryKey: ["watchlist", "episodes"], + }); } else { importWatchlistLocal( validItems.map((item) => ({ diff --git a/src/hooks/use-watchlist.ts b/src/hooks/use-watchlist.ts index 43e5575f..cffed767 100644 --- a/src/hooks/use-watchlist.ts +++ b/src/hooks/use-watchlist.ts @@ -12,7 +12,6 @@ import { queryKeys } from "@/lib/query/keys"; import type { EpisodeProgressRow, WatchItemRow } from "@/lib/server-types"; import { batchSetWatchlistMembership, - getWatchlist, markShowEpisodesAndStatus, setProgressStatus, setReaction, @@ -21,11 +20,14 @@ import { import { unwrap } from "@/server/schema/common"; import type { ProgressStatus, ReactionStatus } from "@/types"; import { - beginOptimistic, - createOptimisticUpdater, - setCached, -} from "./optimistic-helpers"; + applyServerState, + beginOp, + type OpHandle, + type PendingOpEntry, + scheduleSync, +} from "./pending-ops"; import { useLocalProgressStore } from "./use-local-progress-store"; +import { fetchWatchlistList } from "./watchlist-queries"; import { type MediaMetadata, type MediaType, @@ -45,7 +47,7 @@ export function useWatchlist() { const { isSignedIn, isLoaded } = useUser(); const remote = useQuery({ queryKey: queryKeys.watchlist.list(), - queryFn: () => unwrap(getWatchlist({ data: {} })), + queryFn: fetchWatchlistList, enabled: !!isSignedIn, }); const localMediaState = useWatchlistStore((state) => state.mediaState); @@ -77,7 +79,7 @@ export function useAllMediaStates() { const { isSignedIn, isLoaded } = useUser(); const remote = useQuery({ queryKey: queryKeys.watchlist.list(), - queryFn: () => unwrap(getWatchlist({ data: {} })), + queryFn: fetchWatchlistList, enabled: !!isSignedIn, }); const localMediaState = useWatchlistStore((state) => state.mediaState); @@ -108,7 +110,7 @@ export function useMediaState(id: string, mediaType: MediaType) { // the one `getWatchlist` fetch, so a 50-card grid is a single request. const remote = useQuery({ queryKey: queryKeys.watchlist.list(), - queryFn: () => unwrap(getWatchlist({ data: {} })), + queryFn: fetchWatchlistList, enabled: !!isSignedIn, }); @@ -141,134 +143,110 @@ type WatchlistMembershipArgs = { overview?: string; }; -const updateWatchlistMembership = createOptimisticUpdater< - WatchItemRow, - WatchlistMembershipArgs ->( - () => queryKeys.watchlist.list(), - (current, args) => { - if (args.inWatchlist) { - const existing = current.find( - (i) => i.tmdbId === args.tmdbId && i.mediaType === args.mediaType, +function applyMembershipRows( + rows: WatchItemRow[], + args: WatchlistMembershipArgs, +): WatchItemRow[] { + if (args.inWatchlist) { + const existing = rows.find( + (i) => i.tmdbId === args.tmdbId && i.mediaType === args.mediaType, + ); + if (existing) { + return rows.map((i) => + i === existing ? { ...i, inWatchlist: true, updatedAt: Date.now() } : i, ); - if (existing) { - return current.map((i) => - i === existing - ? { ...i, inWatchlist: true, updatedAt: Date.now() } - : i, - ); - } - return [ - ...current, - { - id: `optimistic_${Date.now()}`, - userId: "optimistic", - tmdbId: args.tmdbId, - mediaType: args.mediaType, - title: args.title ?? null, - image: args.image ?? null, - rating: args.rating ?? null, - releaseDate: args.release_date ?? null, - overview: args.overview ?? null, - inWatchlist: true, - progressStatus: "watch-later", - reaction: null, - progress: 0, - updatedAt: Date.now(), - } as WatchItemRow, - ]; } - return current.map((i) => - i.tmdbId === args.tmdbId && i.mediaType === args.mediaType - ? { - ...i, - inWatchlist: false, - progressStatus: - i.progressStatus === "watch-later" ? null : i.progressStatus, - } - : i, - ); - }, -); + return [ + ...rows, + { + id: `optimistic_${Date.now()}`, + userId: "optimistic", + tmdbId: args.tmdbId, + mediaType: args.mediaType, + title: args.title ?? null, + image: args.image ?? null, + rating: args.rating ?? null, + releaseDate: args.release_date ?? null, + overview: args.overview ?? null, + inWatchlist: true, + progressStatus: "watch-later", + reaction: null, + progress: 0, + updatedAt: Date.now(), + } as WatchItemRow, + ]; + } + return rows.map((i) => + i.tmdbId === args.tmdbId && i.mediaType === args.mediaType + ? { + ...i, + inWatchlist: false, + progressStatus: + i.progressStatus === "watch-later" ? null : i.progressStatus, + } + : i, + ); +} -async function setWatchlistMembershipOptimistic( +function beginMembershipOp( queryClient: QueryClient, args: WatchlistMembershipArgs, -) { - const mediaKey = queryKeys.watchlist.mediaState( - args.tmdbId, - args.mediaType as MediaType, - ); - return beginOptimistic( - queryClient, - [queryKeys.watchlist.list(), mediaKey], - () => { - updateWatchlistMembership(queryClient, args); - setCached(queryClient, mediaKey, (current) => { - if (current) { - return { - ...current, - inWatchlist: args.inWatchlist, - updatedAt: Date.now(), - }; - } - if (args.inWatchlist) { - return { - id: `optimistic_${Date.now()}`, - userId: "optimistic", - tmdbId: args.tmdbId, - mediaType: args.mediaType as WatchItemRow["mediaType"], - title: args.title ?? null, - image: args.image ?? null, - rating: args.rating ?? null, - releaseDate: args.release_date ?? null, - overview: args.overview ?? null, - inWatchlist: true, - progressStatus: "watch-later", - reaction: null, - progress: 0, - updatedAt: Date.now(), - }; - } - return undefined; - }); +): OpHandle { + return beginOp(queryClient, [ + { + key: queryKeys.watchlist.list(), + touchedIds: [`${args.mediaType}:${args.tmdbId}`], + apply: (rows: WatchItemRow[]) => applyMembershipRows(rows, args), }, - ); + ]); } type BatchedWatchlistMembershipTask = { args: WatchlistMembershipArgs; - rollback?: () => void; + handle?: OpHandle; queryClient: QueryClient; }; const watchlistMembershipBatcher = createBatcher< BatchedWatchlistMembershipTask, - { ok: true } | { count: number } + WatchItemRow[] >( async (tasks) => { const queryClient = tasks[0]?.queryClient; const items = tasks.map((t) => t.args); try { - let result: { ok: true } | { count: number }; + let rows: WatchItemRow[]; if (items.length === 1) { - result = await unwrap(setWatchlistMembership({ data: items[0] })); + const row = await unwrap(setWatchlistMembership({ data: items[0] })); + rows = row ? [row] : []; } else { - result = await unwrap(batchSetWatchlistMembership({ data: { items } })); + rows = await unwrap(batchSetWatchlistMembership({ data: { items } })); } + // Merge the authoritative rows into the cache (no full refetch — the + // server response already reflects this batch). Touched items missing + // from the response were deleted. if (queryClient) { - void queryClient.invalidateQueries({ - queryKey: queryKeys.watchlist.list(), - }); + applyServerState( + queryClient, + queryKeys.watchlist.list(), + rows, + items.map((i) => `${i.mediaType}:${i.tmdbId}`), + ); } - - return result; + for (const task of tasks) { + task.handle?.resolve(); + } + // The tracked-ids query derives from the watchlist, so keep it fresh. + if (queryClient) { + scheduleSync(queryClient, [queryKeys.watchlist.trackedTmdbIds()]); + } + return rows; } catch (error) { logWatchlistError("batch set watchlist membership", error); for (const task of tasks) { - task.rollback?.(); + task.handle?.remove(); } throw error; } @@ -330,13 +308,10 @@ export function useToggleWatchlistItem() { overview: item.overview || undefined, }; - const rollback = await setWatchlistMembershipOptimistic( - queryClient, - args, - ); + const handle = beginMembershipOp(queryClient, args); return await watchlistMembershipBatcher.schedule({ args, - rollback, + handle, queryClient, }); } @@ -388,11 +363,8 @@ export function useBatchToggleWatchlist() { release_date: item.release_date || undefined, overview: item.overview || undefined, }; - const rollback = await setWatchlistMembershipOptimistic( - queryClient, - args, - ); - tasks.push({ args, rollback, queryClient }); + const handle = beginMembershipOp(queryClient, args); + tasks.push({ args, handle, queryClient }); } return await Promise.all( @@ -431,50 +403,36 @@ type ProgressStatusArgs = { overview?: string; }; -const updateProgressStatus = createOptimisticUpdater< - WatchItemRow, - ProgressStatusArgs ->( - () => queryKeys.watchlist.list(), - (current, args) => { - return current.map((i) => - i.tmdbId === args.tmdbId && i.mediaType === args.mediaType - ? { - ...i, - inWatchlist: true, - progressStatus: args.progressStatus, - progress: args.progress ?? i.progress, - updatedAt: Date.now(), - } - : i, - ); - }, -); - -async function setProgressStatusOptimistic( - queryClient: QueryClient, +function applyProgressStatusRows( + rows: WatchItemRow[], args: ProgressStatusArgs, -) { - const mediaKey = queryKeys.watchlist.mediaState(args.tmdbId, args.mediaType); - return beginOptimistic( - queryClient, - [queryKeys.watchlist.list(), mediaKey], - () => { - updateProgressStatus(queryClient, args); - setCached(queryClient, mediaKey, (current) => { - if (!current) return current; - return { - ...current, +): WatchItemRow[] { + return rows.map((i) => + i.tmdbId === args.tmdbId && i.mediaType === args.mediaType + ? { + ...i, inWatchlist: true, progressStatus: args.progressStatus, - progress: args.progress ?? current.progress, + progress: args.progress ?? i.progress, updatedAt: Date.now(), - }; - }); - }, + } + : i, ); } +function beginProgressStatusOp( + queryClient: QueryClient, + args: ProgressStatusArgs, +): OpHandle { + return beginOp(queryClient, [ + { + key: queryKeys.watchlist.list(), + touchedIds: [`${args.mediaType}:${args.tmdbId}`], + apply: (rows: WatchItemRow[]) => applyProgressStatusRows(rows, args), + }, + ]); +} + type MarkShowEpisodesAndStatusArgs = { tmdbId: number; mediaType: MediaType; @@ -490,46 +448,78 @@ type MarkShowEpisodesAndStatusArgs = { overview?: string; }; -const updateShowEpisodes = createOptimisticUpdater< - EpisodeProgressRow, - MarkShowEpisodesAndStatusArgs ->( - (args) => queryKeys.watchlist.episodes(args.tmdbId), - (current, args) => { - if (args.isWatched) { - const now = Date.now(); - const existingKeys = new Set( - current.map((e) => `${e.season}:${e.episode}`), - ); - const newEpisodes: EpisodeProgressRow[] = []; - for (const s of args.seasons) { - for (const ep of s.episodes) { - if (!existingKeys.has(`${s.season}:${ep}`)) { - newEpisodes.push({ - id: `optimistic_${now}_${s.season}_${ep}`, - userId: "optimistic", - tmdbId: args.tmdbId, - season: s.season, - episode: ep, - isWatched: true, - updatedAt: now, - }); - } +const episodeIdOf = (row: EpisodeProgressRow) => + `${row.tmdbId}:${row.season}:${row.episode}`; + +function applyShowEpisodesRows( + rows: EpisodeProgressRow[], + args: MarkShowEpisodesAndStatusArgs, +): EpisodeProgressRow[] { + if (args.isWatched) { + const now = Date.now(); + const existingKeys = new Set(rows.map((e) => `${e.season}:${e.episode}`)); + const newEpisodes: EpisodeProgressRow[] = []; + for (const s of args.seasons) { + for (const ep of s.episodes) { + if (!existingKeys.has(`${s.season}:${ep}`)) { + newEpisodes.push({ + id: `optimistic_${now}_${s.season}_${ep}`, + userId: "optimistic", + tmdbId: args.tmdbId, + season: s.season, + episode: ep, + isWatched: true, + updatedAt: now, + }); } } - return [...current, ...newEpisodes]; - } - if (args.clearAllEpisodes || args.seasons.length > 0) { - return current.filter((e) => { - if (args.clearAllEpisodes) return false; - return !args.seasons.some( - (s) => s.season === e.season && s.episodes.includes(e.episode), - ); - }); } - return current; - }, -); + return [...rows, ...newEpisodes]; + } + if (args.clearAllEpisodes || args.seasons.length > 0) { + return rows.filter((e) => { + if (args.clearAllEpisodes) return false; + return !args.seasons.some( + (s) => s.season === e.season && s.episodes.includes(e.episode), + ); + }); + } + return rows; +} + +function beginMarkShowOp( + queryClient: QueryClient, + args: MarkShowEpisodesAndStatusArgs, +): OpHandle { + const entries: PendingOpEntry[] = []; + if (args.progressStatus !== undefined) { + entries.push({ + key: queryKeys.watchlist.list(), + touchedIds: [`${args.mediaType}:${args.tmdbId}`], + apply: (rows) => + applyProgressStatusRows( + rows as WatchItemRow[], + args as unknown as ProgressStatusArgs, + ), + }); + } + const episodeKey = queryKeys.watchlist.episodes(args.tmdbId); + const currentEpisodes = (queryClient.getQueryData( + episodeKey, + ) ?? []) as EpisodeProgressRow[]; + const episodeIds = args.clearAllEpisodes + ? currentEpisodes.map(episodeIdOf) + : args.seasons.flatMap((s) => + s.episodes.map((ep) => `${args.tmdbId}:${s.season}:${ep}`), + ); + entries.push({ + key: episodeKey, + touchedIds: episodeIds, + idOf: episodeIdOf as (row: WatchItemRow | EpisodeProgressRow) => string, + apply: (rows) => applyShowEpisodesRows(rows as EpisodeProgressRow[], args), + }); + return beginOp(queryClient, entries); +} export function useSetProgressStatus() { const { isSignedIn } = useUser(); @@ -547,61 +537,31 @@ export function useSetProgressStatus() { const progressMutation = useMutation({ mutationFn: (args: ProgressStatusArgs) => unwrap(setProgressStatus({ data: args })), - onMutate: (args) => setProgressStatusOptimistic(queryClient, args), - onError: (error, _args, rollback) => { + onMutate: (args) => beginProgressStatusOp(queryClient, args), + onSuccess: (_data, _args, handle) => handle?.resolve(), + onError: (error, _args, handle) => { logWatchlistError("set progress status", error); - rollback?.(); + handle?.remove(); }, onSettled: () => { - void queryClient.invalidateQueries({ - queryKey: queryKeys.watchlist.list(), - }); + scheduleSync(queryClient, [queryKeys.watchlist.list()]); }, }); const markShowMutation = useMutation({ mutationFn: (args: MarkShowEpisodesAndStatusArgs) => unwrap(markShowEpisodesAndStatus({ data: args })), - onMutate: async (args) => { - const mediaKey = queryKeys.watchlist.mediaState( - args.tmdbId, - args.mediaType, - ); - const episodeKey = queryKeys.watchlist.episodes(args.tmdbId); - return beginOptimistic( - queryClient, - [queryKeys.watchlist.list(), mediaKey, episodeKey], - () => { - if (args.progressStatus !== undefined) { - updateProgressStatus( - queryClient, - args as unknown as ProgressStatusArgs, - ); - setCached(queryClient, mediaKey, (current) => { - if (!current) return current; - return { - ...current, - progressStatus: args.progressStatus ?? null, - progress: args.progress ?? current.progress, - updatedAt: Date.now(), - }; - }); - } - updateShowEpisodes(queryClient, args); - }, - ); - }, - onError: (error, _args, rollback) => { + onMutate: (args) => beginMarkShowOp(queryClient, args), + onSuccess: (_data, _args, handle) => handle?.resolve(), + onError: (error, _args, handle) => { logWatchlistError("sync show episode status", error); - rollback?.(); + handle?.remove(); }, - onSettled: () => { - void queryClient.invalidateQueries({ - queryKey: queryKeys.watchlist.list(), - }); - void queryClient.invalidateQueries({ - queryKey: ["watchlist", "episodes"], - }); + onSettled: (_data, _error, args) => { + scheduleSync(queryClient, [ + queryKeys.watchlist.list(), + queryKeys.watchlist.episodes(args.tmdbId), + ]); }, }); @@ -748,43 +708,34 @@ type SetReactionArgs = { overview?: string; }; -const updateReaction = createOptimisticUpdater( - () => queryKeys.watchlist.list(), - (current, args) => { - return current.map((i) => - i.tmdbId === args.tmdbId && i.mediaType === args.mediaType - ? { - ...i, - reaction: args.clearReaction ? null : (args.reaction ?? null), - updatedAt: Date.now(), - } - : i, - ); - }, -); - -async function setReactionOptimistic( - queryClient: QueryClient, +function applyReactionRows( + rows: WatchItemRow[], args: SetReactionArgs, -) { - const mediaKey = queryKeys.watchlist.mediaState(args.tmdbId, args.mediaType); - return beginOptimistic( - queryClient, - [queryKeys.watchlist.list(), mediaKey], - () => { - updateReaction(queryClient, args); - setCached(queryClient, mediaKey, (current) => { - if (!current) return current; - return { - ...current, +): WatchItemRow[] { + return rows.map((i) => + i.tmdbId === args.tmdbId && i.mediaType === args.mediaType + ? { + ...i, reaction: args.clearReaction ? null : (args.reaction ?? null), updatedAt: Date.now(), - }; - }); - }, + } + : i, ); } +function beginReactionOp( + queryClient: QueryClient, + args: SetReactionArgs, +): OpHandle { + return beginOp(queryClient, [ + { + key: queryKeys.watchlist.list(), + touchedIds: [`${args.mediaType}:${args.tmdbId}`], + apply: (rows: WatchItemRow[]) => applyReactionRows(rows, args), + }, + ]); +} + export function useSetReaction() { const { isSignedIn } = useUser(); const queryClient = useQueryClient(); @@ -792,15 +743,14 @@ export function useSetReaction() { const mutation = useMutation({ mutationFn: (args: SetReactionArgs) => unwrap(setReaction({ data: args })), - onMutate: (args) => setReactionOptimistic(queryClient, args), - onError: (error, _args, rollback) => { + onMutate: (args) => beginReactionOp(queryClient, args), + onSuccess: (_data, _args, handle) => handle?.resolve(), + onError: (error, _args, handle) => { logWatchlistError("set reaction", error); - rollback?.(); + handle?.remove(); }, onSettled: () => { - void queryClient.invalidateQueries({ - queryKey: queryKeys.watchlist.list(), - }); + scheduleSync(queryClient, [queryKeys.watchlist.list()]); }, }); diff --git a/src/hooks/watchlist-queries.ts b/src/hooks/watchlist-queries.ts new file mode 100644 index 00000000..cce33ff3 --- /dev/null +++ b/src/hooks/watchlist-queries.ts @@ -0,0 +1,48 @@ +import { queryKeys } from "@/lib/query/keys"; +import type { EpisodeProgressRow, WatchItemRow } from "@/lib/server-types"; +import { + getAllEpisodeProgress, + getAllWatchedEpisodes, + getWatchlist, +} from "@/server/fns/watchlist"; +import { unwrap } from "@/server/schema/common"; +import { reconcileListFetch } from "./pending-ops"; + +/** + * Query functions for watchlist caches. Each one routes its server response + * through the pending-op reconciler so a refetch can never clobber optimistic + * state that is still in flight. + */ + +export async function fetchWatchlistList(): Promise { + return reconcileListFetch( + queryKeys.watchlist.list(), + await unwrap(getWatchlist({ data: {} })), + ); +} + +export async function fetchWatchlistListFiltered(args: { + statusFilter?: string; + limit?: number; +}): Promise { + return reconcileListFetch( + queryKeys.watchlist.list(args), + await unwrap(getWatchlist({ data: args })), + ); +} + +export async function fetchWatchedEpisodes( + tmdbId: number, +): Promise { + return reconcileListFetch( + queryKeys.watchlist.episodes(tmdbId), + await unwrap(getAllWatchedEpisodes({ data: { tmdbId } })), + ); +} + +export async function fetchAllEpisodeProgress(): Promise { + return reconcileListFetch( + queryKeys.watchlist.allEpisodes(), + await unwrap(getAllEpisodeProgress()), + ); +} diff --git a/src/server/db/client.ts b/src/server/db/client.ts index cf8506d7..faa4ea82 100644 --- a/src/server/db/client.ts +++ b/src/server/db/client.ts @@ -1,11 +1,22 @@ -import { drizzle } from "drizzle-orm/d1"; +import { type DrizzleD1Database, drizzle } from "drizzle-orm/d1"; import type { Env } from "../env"; import * as schema from "./schema"; /** - * Create a Drizzle instance bound directly to the Worker's D1 database. - * Executes queries directly at the Cloudflare edge for single-digit ms latency. + * Drizzle instances are lightweight, stateless query builders over the D1 + * binding — there is no connection pool to manage (D1 is serverless). Each + * `drizzle()` call still re-processes the schema, so we cache one instance per + * D1 binding instead of rebuilding it on every request. Bindings are stable + * for the lifetime of a Workers isolate, so warm requests reuse the instance; + * new isolates (deploys, hot reloads) naturally restart module state. + * + * The cache is keyed by the binding object itself (WeakMap): if a request ever + * carries a different binding — e.g. in tests or unusual setups — it gets its + * own instance rather than a stale one. Never cache `getEnv()` itself: on the + * Workers runtime Nitro sets `globalThis.__env__` per request. */ +const dbCache = new WeakMap>(); + export function getDb(env: Env) { if (!env.DB) { throw new Error( @@ -15,7 +26,12 @@ export function getDb(env: Env) { ); } - return drizzle(env.DB, { schema }); + let db = dbCache.get(env.DB); + if (!db) { + db = drizzle(env.DB, { schema }); + dbCache.set(env.DB, db); + } + return db; } export type Db = ReturnType; diff --git a/src/server/fns/watchlist.ts b/src/server/fns/watchlist.ts index db4868e9..e75b84af 100644 --- a/src/server/fns/watchlist.ts +++ b/src/server/fns/watchlist.ts @@ -204,162 +204,202 @@ export const removeFromContinueWatching = createServerFn({ method: "POST" }) export const setWatchlistMembership = createServerFn({ method: "POST" }) .validator(setWatchlistMembershipArgsSchema) - .handler(async ({ data }): Promise> => { - const { user, error } = await requireUser(); - if (error) return error; + .handler( + async ({ + data, + }): Promise> => { + const { user, error } = await requireUser(); + if (error) return error; - const db = getDb(getEnv()); - const existing = await getWatchItem(db, user.id, { - tmdbId: data.tmdbId, - mediaType: data.mediaType, - }); + const db = getDb(getEnv()); + const existing = await getWatchItem(db, user.id, { + tmdbId: data.tmdbId, + mediaType: data.mediaType, + }); - if (!data.inWatchlist) { - if (!existing) return ok({ ok: true }); + if (!data.inWatchlist) { + if (!existing) return ok(null); - // If the user has a reaction or non-default progress, keep row with inWatchlist: false - if ( - existing.reaction || - (existing.progress && - existing.progress > 0 && - existing.progressStatus !== "watch-later") - ) { - await db - .update(watchItems) - .set({ + // If the user has a reaction or non-default progress, keep row with inWatchlist: false + if ( + existing.reaction || + (existing.progress && + existing.progress > 0 && + existing.progressStatus !== "watch-later") + ) { + const next = { + ...existing, inWatchlist: false, progressStatus: existing.progressStatus === "watch-later" ? null : existing.progressStatus, updatedAt: Date.now(), - }) - .where(eq(watchItems.id, existing.id)); - } else { + }; + await db + .update(watchItems) + .set({ + inWatchlist: false, + progressStatus: next.progressStatus, + updatedAt: next.updatedAt, + }) + .where(eq(watchItems.id, existing.id)); + return ok(next); + } // Otherwise, delete the row entirely await db.delete(watchItems).where(eq(watchItems.id, existing.id)); + return ok(null); } - return ok({ ok: true }); - } - await upsertWatchItem(db, user.id, data.tmdbId, data.mediaType, (curr) => { - const normalizedExisting = curr - ? normalizeProgressStatus(curr.progressStatus) - : undefined; - const progressStatus = curr - ? (normalizedExisting ?? "watch-later") - : "watch-later"; - - return { - inWatchlist: true, - progressStatus, - ...(curr ? {} : { progress: 0 }), - title: data.title, - image: data.image, - rating: data.rating, - release_date: data.release_date, - overview: data.overview, - }; - }); + const row = await upsertWatchItem( + db, + user.id, + data.tmdbId, + data.mediaType, + (curr) => { + const normalizedExisting = curr + ? normalizeProgressStatus(curr.progressStatus) + : undefined; + const progressStatus = curr + ? (normalizedExisting ?? "watch-later") + : "watch-later"; - return ok({ ok: true }); - }); + return { + inWatchlist: true, + progressStatus, + ...(curr ? {} : { progress: 0 }), + title: data.title, + image: data.image, + rating: data.rating, + release_date: data.release_date, + overview: data.overview, + }; + }, + ); + + return ok(row ?? null); + }, + ); export const batchSetWatchlistMembership = createServerFn({ method: "POST" }) .validator(batchSetWatchlistMembershipArgsSchema) - .handler(async ({ data }): Promise> => { - const { user, error } = await requireUser(); - if (error) return error; + .handler( + async ({ + data, + }): Promise> => { + const { user, error } = await requireUser(); + if (error) return error; - if (!data.items || data.items.length === 0) { - return ok({ count: 0 }); - } + if (!data.items || data.items.length === 0) { + return ok([]); + } - const db = getDb(getEnv()); - const now = Date.now(); + const db = getDb(getEnv()); + const now = Date.now(); - // Fetch existing watch items for this user in 1 fast query - const userWatchItems = await db - .select() - .from(watchItems) - .where(eq(watchItems.userId, user.id)); + // Fetch existing watch items for this user in 1 fast query + const userWatchItems = await db + .select() + .from(watchItems) + .where(eq(watchItems.userId, user.id)); - const existingMap = new Map(); - for (const item of userWatchItems) { - existingMap.set(`${item.mediaType}:${item.tmdbId}`, item); - } + const existingMap = new Map(); + for (const item of userWatchItems) { + existingMap.set(`${item.mediaType}:${item.tmdbId}`, item); + } - // Deduplicate items in the incoming batch taking the latest state - const batchMap = new Map(); - for (const item of data.items) { - batchMap.set(`${item.mediaType}:${item.tmdbId}`, item); - } + // Deduplicate items in the incoming batch taking the latest state + const batchMap = new Map(); + for (const item of data.items) { + batchMap.set(`${item.mediaType}:${item.tmdbId}`, item); + } - for (const item of batchMap.values()) { - const existing = existingMap.get(`${item.mediaType}:${item.tmdbId}`); + // Rows that still exist after the write — the client merges these + // directly into its cache (missing identities were deleted). + const resultRows: (typeof watchItems.$inferSelect)[] = []; - if (!item.inWatchlist) { - if (!existing) continue; + for (const item of batchMap.values()) { + const existing = existingMap.get(`${item.mediaType}:${item.tmdbId}`); - if ( - existing.reaction || - (existing.progress && - existing.progress > 0 && - existing.progressStatus !== "watch-later") - ) { - await db - .update(watchItems) - .set({ + if (!item.inWatchlist) { + if (!existing) continue; + + if ( + existing.reaction || + (existing.progress && + existing.progress > 0 && + existing.progressStatus !== "watch-later") + ) { + const next = { + ...existing, inWatchlist: false, progressStatus: existing.progressStatus === "watch-later" ? null : existing.progressStatus, updatedAt: now, - }) - .where(eq(watchItems.id, existing.id)); - } else { - await db.delete(watchItems).where(eq(watchItems.id, existing.id)); + }; + await db + .update(watchItems) + .set({ + inWatchlist: false, + progressStatus: next.progressStatus, + updatedAt: now, + }) + .where(eq(watchItems.id, existing.id)); + resultRows.push(next); + } else { + await db.delete(watchItems).where(eq(watchItems.id, existing.id)); + } + continue; } - continue; - } - const normalizedExisting = existing - ? normalizeProgressStatus(existing.progressStatus) - : undefined; - const progressStatus = existing - ? (normalizedExisting ?? "watch-later") - : "watch-later"; - const metadataPatch = buildMetadataPatch(item, existing ?? undefined); + const normalizedExisting = existing + ? normalizeProgressStatus(existing.progressStatus) + : undefined; + const progressStatus = existing + ? (normalizedExisting ?? "watch-later") + : "watch-later"; + const metadataPatch = buildMetadataPatch(item, existing ?? undefined); - if (existing) { - await db - .update(watchItems) - .set({ + if (existing) { + const patch = { inWatchlist: true, progressStatus, updatedAt: now, ...metadataPatch, - }) - .where(eq(watchItems.id, existing.id)); - } else { - await db.insert(watchItems).values({ - id: crypto.randomUUID(), - userId: user.id, - tmdbId: item.tmdbId, - mediaType: item.mediaType, - inWatchlist: true, - progressStatus, - progress: 0, - updatedAt: now, - ...metadataPatch, - }); + }; + await db + .update(watchItems) + .set(patch) + .where(eq(watchItems.id, existing.id)); + resultRows.push({ ...existing, ...patch }); + } else { + const row: typeof watchItems.$inferSelect = { + id: crypto.randomUUID(), + userId: user.id, + tmdbId: item.tmdbId, + mediaType: item.mediaType, + inWatchlist: true, + progressStatus: progressStatus ?? null, + progress: 0, + reaction: null, + title: metadataPatch.title ?? null, + image: metadataPatch.image ?? null, + rating: metadataPatch.rating ?? null, + releaseDate: metadataPatch.releaseDate ?? null, + overview: metadataPatch.overview ?? null, + updatedAt: now, + }; + await db.insert(watchItems).values(row).onConflictDoNothing(); + resultRows.push(row); + } } - } - await createWatchlistSnapshot(db, user.id); - return ok({ count: batchMap.size }); - }); + await createWatchlistSnapshot(db, user.id); + return ok(resultRows); + }, + ); export const setProgressStatus = createServerFn({ method: "POST" }) .validator(setProgressStatusArgsSchema) diff --git a/src/server/helpers/watch-item.ts b/src/server/helpers/watch-item.ts index 8df8f2e9..c2da9a56 100644 --- a/src/server/helpers/watch-item.ts +++ b/src/server/helpers/watch-item.ts @@ -104,7 +104,9 @@ export type UpsertUpdate = /** * Port of `upsertWatchItem` — insert or patch the unique (user, tmdb, media) - * watch item row. Timestamps are always set here (`updatedAt`). + * watch item row. Timestamps are always set here (`updatedAt`). Returns the + * final row so callers can echo the authoritative state back to the client + * without an extra read. */ export async function upsertWatchItem( db: Db, @@ -112,11 +114,11 @@ export async function upsertWatchItem( tmdbId: number, mediaType: MediaType, updates: UpsertUpdate, -) { +): Promise { const existing = await getWatchItem(db, userId, { tmdbId, mediaType }); const finalUpdates = typeof updates === "function" ? updates(existing ?? null) : updates; - if (!finalUpdates) return; + if (!finalUpdates) return undefined; const now = Date.now(); const metadataPatch = buildMetadataPatch(finalUpdates, existing); @@ -144,7 +146,7 @@ export async function upsertWatchItem( .update(watchItems) .set(patch) .where(eq(watchItems.id, existing.id)); - return existing; + return { ...existing, ...patch }; } const id = crypto.randomUUID(); @@ -156,20 +158,23 @@ export async function upsertWatchItem( : 0; const reaction = normalizeReaction(finalUpdates.reaction) ?? undefined; - await db - .insert(watchItems) - .values({ - id, - userId, - tmdbId, - mediaType, - inWatchlist: finalUpdates.inWatchlist ?? false, - progressStatus, - progress, - reaction, - updatedAt: now, - ...metadataPatch, - }) - .onConflictDoNothing(); - return undefined; + const row: WatchItemRow = { + id, + userId, + tmdbId, + mediaType, + inWatchlist: finalUpdates.inWatchlist ?? false, + progressStatus: progressStatus ?? null, + progress, + reaction: reaction ?? null, + title: metadataPatch.title ?? null, + image: metadataPatch.image ?? null, + rating: metadataPatch.rating ?? null, + releaseDate: metadataPatch.releaseDate ?? null, + overview: metadataPatch.overview ?? null, + updatedAt: now, + }; + + await db.insert(watchItems).values(row).onConflictDoNothing(); + return row; } From dc6ca8057c69dcc4ccd71b15295a017ffc5a4dd1 Mon Sep 17 00:00:00 2001 From: Swastik Dan <57379785+Swastikdan@users.noreply.github.com> Date: Sun, 16 Aug 2026 11:17:25 +0530 Subject: [PATCH 19/27] refactor: add lifecycle-managed flush to RequestBatcher, introduce DailyPick offline storage, and unify database schema types --- .github/workflows/deploy.yml | 20 +- README.md | 6 +- drizzle.studio.config.ts | 80 +- drizzle/0001_slippery_cammi.sql | 60 + drizzle/0002_cute_bloodstrike.sql | 5 + drizzle/meta/0001_snapshot.json | 979 ++++++++++++++++ drizzle/meta/0002_snapshot.json | 1010 +++++++++++++++++ drizzle/meta/_journal.json | 14 + package.json | 2 +- server/routes/api/health.ts | 8 +- server/tasks/snapshots.ts | 59 +- .../admin/admin-permission-toggles.tsx | 50 +- src/components/admin/admin-user-table.tsx | 21 +- src/components/custom-list-dialog.tsx | 3 - src/components/custom-list-picker.tsx | 18 +- src/components/daily-pick.tsx | 82 +- src/components/homepage-recommendations.tsx | 36 +- src/components/user-sync.tsx | 19 +- src/hooks/optimistic-helpers.ts | 15 +- src/hooks/use-custom-lists.ts | 140 ++- src/hooks/use-daily-pick-store.ts | 92 ++ src/hooks/use-permissions.ts | 4 +- src/hooks/use-recommendations.ts | 16 +- src/hooks/use-watch-progress.ts | 4 +- src/hooks/use-watchlist-import-export.ts | 9 +- src/hooks/use-watchlist.ts | 59 +- src/hooks/watchlist-queries.ts | 4 +- src/lib/batcher.ts | 66 +- src/lib/query/keys.ts | 41 +- src/lib/server-types.ts | 11 +- src/routes/recommendations.lazy.tsx | 16 +- src/server/ai.ts | 74 +- src/server/auth.ts | 213 +++- src/server/db/client.ts | 15 + src/server/db/schema.ts | 9 +- src/server/fns/admin.ts | 59 +- src/server/fns/import-export.ts | 88 +- src/server/fns/lists.ts | 192 ++-- src/server/fns/recommendations.ts | 622 +++++----- src/server/fns/users.ts | 16 +- src/server/fns/watchlist.ts | 272 +++-- src/server/helpers/snapshots.ts | 38 +- src/server/helpers/watch-item.ts | 33 +- src/server/prompts.ts | 73 +- src/server/rbac.ts | 105 +- src/server/schema/admin.ts | 15 +- src/server/schema/import.ts | 42 +- src/server/schema/lists.ts | 32 +- src/server/schema/recommendations.ts | 20 +- src/server/schema/watchlist.ts | 54 +- src/start.ts | 32 +- 51 files changed, 4019 insertions(+), 934 deletions(-) create mode 100644 drizzle/0001_slippery_cammi.sql create mode 100644 drizzle/0002_cute_bloodstrike.sql create mode 100644 drizzle/meta/0001_snapshot.json create mode 100644 drizzle/meta/0002_snapshot.json create mode 100644 src/hooks/use-daily-pick-store.ts diff --git a/.github/workflows/deploy.yml b/.github/workflows/deploy.yml index 75ba5ea2..9a5daf70 100644 --- a/.github/workflows/deploy.yml +++ b/.github/workflows/deploy.yml @@ -6,19 +6,29 @@ on: - feat/convex-to-traditional-backend workflow_dispatch: # Allows manual trigger from GitHub Actions UI +# Serialize production jobs across both deployment branches so migrations and +# deploys targeting the same D1 database / Worker never run concurrently. +concurrency: + group: deploy-cloudflare-prod + cancel-in-progress: false + jobs: deploy: runs-on: ubuntu-latest + permissions: + contents: read steps: - - uses: actions/checkout@v4 - - uses: pnpm/action-setup@v4 - - uses: actions/setup-node@v4 + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4 + with: + persist-credentials: false + - uses: pnpm/action-setup@b906affcce14559ad1aafd4ab0e942779e9f58b1 # v4 + - uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4 with: { node-version: 22, cache: pnpm } - run: pnpm install --frozen-lockfile - run: pnpm typecheck - name: Apply D1 migrations (prod) - uses: cloudflare/wrangler-action@v3 + uses: cloudflare/wrangler-action@9acf94ace14e7dc412b076f2c5c20b8ce93c79cd # v3 with: apiToken: ${{ secrets.CLOUDFLARE_API_TOKEN }} accountId: ${{ secrets.CLOUDFLARE_ACCOUNT_ID }} @@ -34,7 +44,7 @@ jobs: VITE_PUBLIC_VIDEO_URL: ${{ secrets.VITE_PUBLIC_VIDEO_URL }} - name: Deploy Worker - uses: cloudflare/wrangler-action@v3 + uses: cloudflare/wrangler-action@9acf94ace14e7dc412b076f2c5c20b8ce93c79cd # v3 with: apiToken: ${{ secrets.CLOUDFLARE_API_TOKEN }} accountId: ${{ secrets.CLOUDFLARE_ACCOUNT_ID }} diff --git a/README.md b/README.md index e6dd3e66..4074e11d 100644 --- a/README.md +++ b/README.md @@ -14,7 +14,7 @@ Pebbly is a modern, full-stack movie and TV show discovery application built wit - **Custom Lists & Management**: Create custom lists, export/import watchlists in JSON format, and sync seamlessly across devices via Cloudflare D1. ### AI Recommendation Engine -- **Watchlist & Interaction-Aware AI**: Generates tailored movie and TV recommendations using Google Gemini models (`gemini-2.5-flash`, `gemini-3.1-flash-lite-preview`). +- **Watchlist & Interaction-Aware AI**: Generates tailored movie and TV recommendations using Google Gemini models (`gemini-3.1-flash-lite`, `gemini-2.5-flash`). - **Homepage "Picks For You"**: Dedicated homepage widget providing twice-daily refreshed recommendations with real-time watchlist exclusion. - **Interaction Feedback Loop**: User interactions (thumbs up / thumbs down) train future recommendations. Liked recommendations are automatically added to your **Pebbly Picks** list, and disliked titles are excluded. - **Advanced Filtering**: Generate recommendations by Watchlist, Custom List, Genre preferences, or Era presets (Classics, 80s, 90s, 2000s, 2010s, 2020s). @@ -31,7 +31,7 @@ Pebbly is a modern, full-stack movie and TV show discovery application built wit | **Database** | [Cloudflare D1](https://developers.cloudflare.com/d1/) (SQLite) via [Drizzle ORM](https://orm.drizzle.team/) | | **Validation** | [Valibot](https://valibot.dev/) (Lightweight, modular schema validation) | | **Authentication** | [Clerk](https://clerk.com/) (`@clerk/react` + `@clerk/backend` JWT verification) | -| **AI Engine** | Google GenAI SDK (`@google/genai` - Gemini Flash models) | +| **AI Engine** | Google Gemini REST API (`generativelanguage.googleapis.com` via `fetch` — `gemini-3.1-flash-lite` + `gemini-2.5-flash` fallback chain) | | **Styling** | Tailwind CSS 4, Radix UI, shadcn/ui | | **Data Fetching** | TanStack Query (React Query) | | **State Management** | Zustand | @@ -41,7 +41,7 @@ Pebbly is a modern, full-stack movie and TV show discovery application built wit ## Project Structure -``` +```text ├── drizzle/ # Drizzle generated SQL migrations for Cloudflare D1 ├── server/ # Nitro server routes and scheduled tasks │ ├── routes/api/health.ts # /api/health endpoint (D1 status check) diff --git a/drizzle.studio.config.ts b/drizzle.studio.config.ts index 9dca7715..3e8932cf 100644 --- a/drizzle.studio.config.ts +++ b/drizzle.studio.config.ts @@ -1,5 +1,5 @@ import { defineConfig } from "drizzle-kit"; -import fs from "node:fs"; +import { readFileSync } from "node:fs"; /** * Drizzle Studio dashboard for the remote (production) D1 database. @@ -15,27 +15,83 @@ import fs from "node:fs"; * For the local D1 database use: * wrangler d1 execute pebbly --local --command "SELECT * FROM watch_items;" */ -function readWranglerTomlValue(key: string): string | undefined { + +function fail(message: string): never { + console.error(`[drizzle.studio.config.ts] ${message}`); + console.error( + "Set the missing values (see .env.example) and re-run `pnpm db:studio`.", + ); + process.exit(1); +} + +/** + * Read the top-level `database_id` from wrangler.toml. + * + * wrangler.toml is TOML, so we parse the top-level `d1_databases` array and + * take the `database_id` of the entry named `pebbly` (falling back to the + * first entry). Regex extraction is deliberately avoided so environment + * blocks (`[env.production]`) cannot shadow the top-level database id. + */ +function readWranglerDatabaseId(): string { + const raw = readWranglerToml(); + + // wrangler.toml uses TOML array-of-tables syntax (`[[d1_databases]]`). + // Split the file on each `[[d1_databases]]` header and parse only the + // top-level section — `[env.*]` blocks are ignored entirely, so an + // environment-specific D1 cannot shadow the intended database id. + const sections = raw.split(/^\[\[d1_databases\]\]/m).slice(1); + if (sections.length === 0) { + fail("Could not find a top-level `[[d1_databases]]` table in wrangler.toml."); + } + + const parseSection = (section: string): Record => { + const values: Record = {}; + for (const line of section.split("\n")) { + // Stop at the next top-level table/array header. + if (/^\[|^\[\[/.test(line.trim())) break; + const kv = line.match(/^\s*(\w+)\s*=\s*"([^"]+)"/); + if (kv) values[kv[1]] = kv[2]; + } + return values; + }; + + // Take the first top-level `[[d1_databases]]` entry that binds `DB`. + const d1 = sections.map(parseSection).find((entry) => entry.binding === "DB"); + const databaseId = d1?.database_id; + if (!databaseId) { + fail("No `database_id` found in the top-level `[[d1_databases]]` table."); + } + return databaseId; +} + +function readWranglerToml(): string { try { - const raw = fs.readFileSync( - new URL("./wrangler.toml", import.meta.url), - "utf8", + return readFileSync(new URL("./wrangler.toml", import.meta.url), "utf8"); + } catch (error) { + fail( + `Could not read wrangler.toml (${error instanceof Error ? error.message : String(error)}). Run this from the project root.`, ); - const match = raw.match(new RegExp(`^${key}\\s*=\\s*"([^"]+)"`, "m")); - return match?.[1]; - } catch { - return undefined; } } +const accountId = process.env.CLOUDFLARE_ACCOUNT_ID; +const apiToken = process.env.CLOUDFLARE_API_TOKEN; + +if (!accountId) { + fail("CLOUDFLARE_ACCOUNT_ID is not set."); +} +if (!apiToken) { + fail("CLOUDFLARE_API_TOKEN is not set."); +} + export default defineConfig({ dialect: "sqlite", schema: "./src/server/db/schema.ts", out: "./drizzle", driver: "d1-http", dbCredentials: { - accountId: process.env.CLOUDFLARE_ACCOUNT_ID ?? "", - databaseId: readWranglerTomlValue("database_id") ?? "", - token: process.env.CLOUDFLARE_API_TOKEN ?? "", + accountId, + databaseId: readWranglerDatabaseId(), + token: apiToken, }, }); diff --git a/drizzle/0001_slippery_cammi.sql b/drizzle/0001_slippery_cammi.sql new file mode 100644 index 00000000..a38466f1 --- /dev/null +++ b/drizzle/0001_slippery_cammi.sql @@ -0,0 +1,60 @@ +PRAGMA foreign_keys=OFF;--> statement-breakpoint +CREATE TABLE `__new_role_permissions` ( + `role` text NOT NULL, + `feature` text NOT NULL, + `enabled` integer DEFAULT true NOT NULL, + PRIMARY KEY(`role`, `feature`) +); +--> statement-breakpoint +INSERT INTO `__new_role_permissions`("role", "feature", "enabled") SELECT "role", "feature", "enabled" FROM `role_permissions`;--> statement-breakpoint +DROP TABLE `role_permissions`;--> statement-breakpoint +ALTER TABLE `__new_role_permissions` RENAME TO `role_permissions`;--> statement-breakpoint +PRAGMA foreign_keys=ON;--> statement-breakpoint +CREATE TABLE `__new_list_items` ( + `id` text PRIMARY KEY NOT NULL, + `user_id` text NOT NULL, + `list_id` text NOT NULL, + `tmdb_id` integer NOT NULL, + `media_type` text NOT NULL, + `added_at` integer NOT NULL, + `title` text, + `image` text, + `backdrop` text, + `rating` real, + `release_date` text, + `overview` text, + FOREIGN KEY (`user_id`) REFERENCES `users`(`id`) ON UPDATE no action ON DELETE cascade, + FOREIGN KEY (`list_id`) REFERENCES `lists`(`id`) ON UPDATE no action ON DELETE cascade +); +--> statement-breakpoint +INSERT INTO `__new_list_items`("id", "user_id", "list_id", "tmdb_id", "media_type", "added_at", "title", "image", "backdrop", "rating", "release_date", "overview") SELECT "id", "user_id", "list_id", "tmdb_id", "media_type", "added_at", "title", "image", "backdrop", "rating", "release_date", "overview" FROM `list_items`;--> statement-breakpoint +DROP TABLE `list_items`;--> statement-breakpoint +ALTER TABLE `__new_list_items` RENAME TO `list_items`;--> statement-breakpoint +CREATE UNIQUE INDEX `list_items_list_media_uq` ON `list_items` (`list_id`,`tmdb_id`,`media_type`);--> statement-breakpoint +CREATE INDEX `list_items_user_media_idx` ON `list_items` (`user_id`,`tmdb_id`,`media_type`);--> statement-breakpoint +CREATE TABLE `__new_watch_items` ( + `id` text PRIMARY KEY NOT NULL, + `user_id` text NOT NULL, + `tmdb_id` integer NOT NULL, + `media_type` text NOT NULL, + `in_watchlist` integer DEFAULT false, + `progress_status` text, + `reaction` text, + `progress` integer DEFAULT 0, + `title` text, + `image` text, + `rating` real, + `release_date` text, + `overview` text, + `updated_at` integer NOT NULL, + FOREIGN KEY (`user_id`) REFERENCES `users`(`id`) ON UPDATE no action ON DELETE cascade, + CONSTRAINT "watch_items_progress_range" CHECK("__new_watch_items"."progress" between 0 and 100), + CONSTRAINT "watch_items_rating_range" CHECK("__new_watch_items"."rating" between 0 and 10) +); +--> statement-breakpoint +INSERT INTO `__new_watch_items`("id", "user_id", "tmdb_id", "media_type", "in_watchlist", "progress_status", "reaction", "progress", "title", "image", "rating", "release_date", "overview", "updated_at") SELECT "id", "user_id", "tmdb_id", "media_type", "in_watchlist", "progress_status", "reaction", "progress", "title", "image", "rating", "release_date", "overview", "updated_at" FROM `watch_items`;--> statement-breakpoint +DROP TABLE `watch_items`;--> statement-breakpoint +ALTER TABLE `__new_watch_items` RENAME TO `watch_items`;--> statement-breakpoint +CREATE UNIQUE INDEX `watch_items_user_media_uq` ON `watch_items` (`user_id`,`tmdb_id`,`media_type`);--> statement-breakpoint +CREATE INDEX `watch_items_user_status_idx` ON `watch_items` (`user_id`,`progress_status`);--> statement-breakpoint +CREATE INDEX `watch_items_user_updated_idx` ON `watch_items` (`user_id`,`updated_at`); \ No newline at end of file diff --git a/drizzle/0002_cute_bloodstrike.sql b/drizzle/0002_cute_bloodstrike.sql new file mode 100644 index 00000000..5220e290 --- /dev/null +++ b/drizzle/0002_cute_bloodstrike.sql @@ -0,0 +1,5 @@ +CREATE TABLE `snapshot_cursors` ( + `key` text PRIMARY KEY NOT NULL, + `value` text, + `updated_at` integer NOT NULL +); diff --git a/drizzle/meta/0001_snapshot.json b/drizzle/meta/0001_snapshot.json new file mode 100644 index 00000000..2c8d88c7 --- /dev/null +++ b/drizzle/meta/0001_snapshot.json @@ -0,0 +1,979 @@ +{ + "version": "6", + "dialect": "sqlite", + "id": "0ec3406a-5890-4507-8acd-7188c8f94a0c", + "prevId": "28c96ef3-0b1e-4128-8d3d-a6f1a1b5c209", + "tables": { + "ai_recommendations": { + "name": "ai_recommendations", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "recommendations": { + "name": "recommendations", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "original_recommendations": { + "name": "original_recommendations", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "watchlist_hash": { + "name": "watchlist_hash", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "''" + }, + "input_stats": { + "name": "input_stats", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "model": { + "name": "model", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "media_type_preference": { + "name": "media_type_preference", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "genre_preference": { + "name": "genre_preference", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "generation_type": { + "name": "generation_type", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "verified": { + "name": "verified", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false, + "default": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": { + "ai_recs_user_created_idx": { + "name": "ai_recs_user_created_idx", + "columns": [ + "user_id", + "created_at" + ], + "isUnique": false + } + }, + "foreignKeys": { + "ai_recommendations_user_id_users_id_fk": { + "name": "ai_recommendations_user_id_users_id_fk", + "tableFrom": "ai_recommendations", + "tableTo": "users", + "columnsFrom": [ + "user_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "episode_progress": { + "name": "episode_progress", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "tmdb_id": { + "name": "tmdb_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "season": { + "name": "season", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "episode": { + "name": "episode", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "is_watched": { + "name": "is_watched", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": false + }, + "updated_at": { + "name": "updated_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": { + "episode_user_season_ep_uq": { + "name": "episode_user_season_ep_uq", + "columns": [ + "user_id", + "tmdb_id", + "season", + "episode" + ], + "isUnique": true + } + }, + "foreignKeys": { + "episode_progress_user_id_users_id_fk": { + "name": "episode_progress_user_id_users_id_fk", + "tableFrom": "episode_progress", + "tableTo": "users", + "columnsFrom": [ + "user_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "homepage_recommendations": { + "name": "homepage_recommendations", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "recommendations": { + "name": "recommendations", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "previous_recommendations": { + "name": "previous_recommendations", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "last_attempted_at": { + "name": "last_attempted_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 0 + }, + "last_updated_at": { + "name": "last_updated_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 0 + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'none'" + } + }, + "indexes": { + "homepage_recommendations_user_id_unique": { + "name": "homepage_recommendations_user_id_unique", + "columns": [ + "user_id" + ], + "isUnique": true + } + }, + "foreignKeys": { + "homepage_recommendations_user_id_users_id_fk": { + "name": "homepage_recommendations_user_id_users_id_fk", + "tableFrom": "homepage_recommendations", + "tableTo": "users", + "columnsFrom": [ + "user_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "list_items": { + "name": "list_items", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "list_id": { + "name": "list_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "tmdb_id": { + "name": "tmdb_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "media_type": { + "name": "media_type", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "added_at": { + "name": "added_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "title": { + "name": "title", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "image": { + "name": "image", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "backdrop": { + "name": "backdrop", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "rating": { + "name": "rating", + "type": "real", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "release_date": { + "name": "release_date", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "overview": { + "name": "overview", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": { + "list_items_list_media_uq": { + "name": "list_items_list_media_uq", + "columns": [ + "list_id", + "tmdb_id", + "media_type" + ], + "isUnique": true + }, + "list_items_user_media_idx": { + "name": "list_items_user_media_idx", + "columns": [ + "user_id", + "tmdb_id", + "media_type" + ], + "isUnique": false + } + }, + "foreignKeys": { + "list_items_user_id_users_id_fk": { + "name": "list_items_user_id_users_id_fk", + "tableFrom": "list_items", + "tableTo": "users", + "columnsFrom": [ + "user_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "list_items_list_id_lists_id_fk": { + "name": "list_items_list_id_lists_id_fk", + "tableFrom": "list_items", + "tableTo": "lists", + "columnsFrom": [ + "list_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "lists": { + "name": "lists", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "color": { + "name": "color", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "visibility": { + "name": "visibility", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "list_type": { + "name": "list_type", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "sort_order": { + "name": "sort_order", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 0 + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "updated_at": { + "name": "updated_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": { + "lists_user_name_uq": { + "name": "lists_user_name_uq", + "columns": [ + "user_id", + "name" + ], + "isUnique": true + }, + "lists_user_sort_idx": { + "name": "lists_user_sort_idx", + "columns": [ + "user_id", + "sort_order" + ], + "isUnique": false + } + }, + "foreignKeys": { + "lists_user_id_users_id_fk": { + "name": "lists_user_id_users_id_fk", + "tableFrom": "lists", + "tableTo": "users", + "columnsFrom": [ + "user_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "recommendation_feedback": { + "name": "recommendation_feedback", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "tmdb_id": { + "name": "tmdb_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "media_type": { + "name": "media_type", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "title": { + "name": "title", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "feedback": { + "name": "feedback", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "updated_at": { + "name": "updated_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": { + "feedback_user_media_uq": { + "name": "feedback_user_media_uq", + "columns": [ + "user_id", + "tmdb_id", + "media_type" + ], + "isUnique": true + }, + "feedback_user_feedback_idx": { + "name": "feedback_user_feedback_idx", + "columns": [ + "user_id", + "feedback" + ], + "isUnique": false + } + }, + "foreignKeys": { + "recommendation_feedback_user_id_users_id_fk": { + "name": "recommendation_feedback_user_id_users_id_fk", + "tableFrom": "recommendation_feedback", + "tableTo": "users", + "columnsFrom": [ + "user_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "role_permissions": { + "name": "role_permissions", + "columns": { + "role": { + "name": "role", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "feature": { + "name": "feature", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "enabled": { + "name": "enabled", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": true + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": { + "role_permissions_role_feature_pk": { + "columns": [ + "role", + "feature" + ], + "name": "role_permissions_role_feature_pk" + } + }, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "users": { + "name": "users", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "token_identifier": { + "name": "token_identifier", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "image": { + "name": "image", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "email": { + "name": "email", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "roles": { + "name": "roles", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false, + "default": "'[]'" + }, + "is_admin": { + "name": "is_admin", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false, + "default": false + }, + "is_banned": { + "name": "is_banned", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false, + "default": false + } + }, + "indexes": { + "users_token_identifier_unique": { + "name": "users_token_identifier_unique", + "columns": [ + "token_identifier" + ], + "isUnique": true + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "watch_items": { + "name": "watch_items", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "tmdb_id": { + "name": "tmdb_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "media_type": { + "name": "media_type", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "in_watchlist": { + "name": "in_watchlist", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false, + "default": false + }, + "progress_status": { + "name": "progress_status", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "reaction": { + "name": "reaction", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "progress": { + "name": "progress", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false, + "default": 0 + }, + "title": { + "name": "title", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "image": { + "name": "image", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "rating": { + "name": "rating", + "type": "real", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "release_date": { + "name": "release_date", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "overview": { + "name": "overview", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "updated_at": { + "name": "updated_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": { + "watch_items_user_media_uq": { + "name": "watch_items_user_media_uq", + "columns": [ + "user_id", + "tmdb_id", + "media_type" + ], + "isUnique": true + }, + "watch_items_user_status_idx": { + "name": "watch_items_user_status_idx", + "columns": [ + "user_id", + "progress_status" + ], + "isUnique": false + }, + "watch_items_user_updated_idx": { + "name": "watch_items_user_updated_idx", + "columns": [ + "user_id", + "updated_at" + ], + "isUnique": false + } + }, + "foreignKeys": { + "watch_items_user_id_users_id_fk": { + "name": "watch_items_user_id_users_id_fk", + "tableFrom": "watch_items", + "tableTo": "users", + "columnsFrom": [ + "user_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": { + "watch_items_progress_range": { + "name": "watch_items_progress_range", + "value": "\"watch_items\".\"progress\" between 0 and 100" + }, + "watch_items_rating_range": { + "name": "watch_items_rating_range", + "value": "\"watch_items\".\"rating\" between 0 and 10" + } + } + }, + "watchlist_snapshots": { + "name": "watchlist_snapshots", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "items": { + "name": "items", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": { + "snapshots_user_created_idx": { + "name": "snapshots_user_created_idx", + "columns": [ + "user_id", + "created_at" + ], + "isUnique": false + } + }, + "foreignKeys": { + "watchlist_snapshots_user_id_users_id_fk": { + "name": "watchlist_snapshots_user_id_users_id_fk", + "tableFrom": "watchlist_snapshots", + "tableTo": "users", + "columnsFrom": [ + "user_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + } + }, + "views": {}, + "enums": {}, + "_meta": { + "schemas": {}, + "tables": {}, + "columns": {} + }, + "internal": { + "indexes": {} + } +} \ No newline at end of file diff --git a/drizzle/meta/0002_snapshot.json b/drizzle/meta/0002_snapshot.json new file mode 100644 index 00000000..5463d906 --- /dev/null +++ b/drizzle/meta/0002_snapshot.json @@ -0,0 +1,1010 @@ +{ + "version": "6", + "dialect": "sqlite", + "id": "4f1071d8-52ee-4b21-8fe0-be2e23794be7", + "prevId": "0ec3406a-5890-4507-8acd-7188c8f94a0c", + "tables": { + "ai_recommendations": { + "name": "ai_recommendations", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "recommendations": { + "name": "recommendations", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "original_recommendations": { + "name": "original_recommendations", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "watchlist_hash": { + "name": "watchlist_hash", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "''" + }, + "input_stats": { + "name": "input_stats", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "model": { + "name": "model", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "media_type_preference": { + "name": "media_type_preference", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "genre_preference": { + "name": "genre_preference", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "generation_type": { + "name": "generation_type", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "verified": { + "name": "verified", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false, + "default": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": { + "ai_recs_user_created_idx": { + "name": "ai_recs_user_created_idx", + "columns": [ + "user_id", + "created_at" + ], + "isUnique": false + } + }, + "foreignKeys": { + "ai_recommendations_user_id_users_id_fk": { + "name": "ai_recommendations_user_id_users_id_fk", + "tableFrom": "ai_recommendations", + "tableTo": "users", + "columnsFrom": [ + "user_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "episode_progress": { + "name": "episode_progress", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "tmdb_id": { + "name": "tmdb_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "season": { + "name": "season", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "episode": { + "name": "episode", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "is_watched": { + "name": "is_watched", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": false + }, + "updated_at": { + "name": "updated_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": { + "episode_user_season_ep_uq": { + "name": "episode_user_season_ep_uq", + "columns": [ + "user_id", + "tmdb_id", + "season", + "episode" + ], + "isUnique": true + } + }, + "foreignKeys": { + "episode_progress_user_id_users_id_fk": { + "name": "episode_progress_user_id_users_id_fk", + "tableFrom": "episode_progress", + "tableTo": "users", + "columnsFrom": [ + "user_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "homepage_recommendations": { + "name": "homepage_recommendations", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "recommendations": { + "name": "recommendations", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "previous_recommendations": { + "name": "previous_recommendations", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "last_attempted_at": { + "name": "last_attempted_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 0 + }, + "last_updated_at": { + "name": "last_updated_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 0 + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'none'" + } + }, + "indexes": { + "homepage_recommendations_user_id_unique": { + "name": "homepage_recommendations_user_id_unique", + "columns": [ + "user_id" + ], + "isUnique": true + } + }, + "foreignKeys": { + "homepage_recommendations_user_id_users_id_fk": { + "name": "homepage_recommendations_user_id_users_id_fk", + "tableFrom": "homepage_recommendations", + "tableTo": "users", + "columnsFrom": [ + "user_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "list_items": { + "name": "list_items", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "list_id": { + "name": "list_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "tmdb_id": { + "name": "tmdb_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "media_type": { + "name": "media_type", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "added_at": { + "name": "added_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "title": { + "name": "title", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "image": { + "name": "image", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "backdrop": { + "name": "backdrop", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "rating": { + "name": "rating", + "type": "real", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "release_date": { + "name": "release_date", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "overview": { + "name": "overview", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": { + "list_items_list_media_uq": { + "name": "list_items_list_media_uq", + "columns": [ + "list_id", + "tmdb_id", + "media_type" + ], + "isUnique": true + }, + "list_items_user_media_idx": { + "name": "list_items_user_media_idx", + "columns": [ + "user_id", + "tmdb_id", + "media_type" + ], + "isUnique": false + } + }, + "foreignKeys": { + "list_items_user_id_users_id_fk": { + "name": "list_items_user_id_users_id_fk", + "tableFrom": "list_items", + "tableTo": "users", + "columnsFrom": [ + "user_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "list_items_list_id_lists_id_fk": { + "name": "list_items_list_id_lists_id_fk", + "tableFrom": "list_items", + "tableTo": "lists", + "columnsFrom": [ + "list_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "lists": { + "name": "lists", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "color": { + "name": "color", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "visibility": { + "name": "visibility", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "list_type": { + "name": "list_type", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "sort_order": { + "name": "sort_order", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 0 + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "updated_at": { + "name": "updated_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": { + "lists_user_name_uq": { + "name": "lists_user_name_uq", + "columns": [ + "user_id", + "name" + ], + "isUnique": true + }, + "lists_user_sort_idx": { + "name": "lists_user_sort_idx", + "columns": [ + "user_id", + "sort_order" + ], + "isUnique": false + } + }, + "foreignKeys": { + "lists_user_id_users_id_fk": { + "name": "lists_user_id_users_id_fk", + "tableFrom": "lists", + "tableTo": "users", + "columnsFrom": [ + "user_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "recommendation_feedback": { + "name": "recommendation_feedback", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "tmdb_id": { + "name": "tmdb_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "media_type": { + "name": "media_type", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "title": { + "name": "title", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "feedback": { + "name": "feedback", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "updated_at": { + "name": "updated_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": { + "feedback_user_media_uq": { + "name": "feedback_user_media_uq", + "columns": [ + "user_id", + "tmdb_id", + "media_type" + ], + "isUnique": true + }, + "feedback_user_feedback_idx": { + "name": "feedback_user_feedback_idx", + "columns": [ + "user_id", + "feedback" + ], + "isUnique": false + } + }, + "foreignKeys": { + "recommendation_feedback_user_id_users_id_fk": { + "name": "recommendation_feedback_user_id_users_id_fk", + "tableFrom": "recommendation_feedback", + "tableTo": "users", + "columnsFrom": [ + "user_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "role_permissions": { + "name": "role_permissions", + "columns": { + "role": { + "name": "role", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "feature": { + "name": "feature", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "enabled": { + "name": "enabled", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": true + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": { + "role_permissions_role_feature_pk": { + "columns": [ + "role", + "feature" + ], + "name": "role_permissions_role_feature_pk" + } + }, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "snapshot_cursors": { + "name": "snapshot_cursors", + "columns": { + "key": { + "name": "key", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "value": { + "name": "value", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "updated_at": { + "name": "updated_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "users": { + "name": "users", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "token_identifier": { + "name": "token_identifier", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "image": { + "name": "image", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "email": { + "name": "email", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "roles": { + "name": "roles", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false, + "default": "'[]'" + }, + "is_admin": { + "name": "is_admin", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false, + "default": false + }, + "is_banned": { + "name": "is_banned", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false, + "default": false + } + }, + "indexes": { + "users_token_identifier_unique": { + "name": "users_token_identifier_unique", + "columns": [ + "token_identifier" + ], + "isUnique": true + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "watch_items": { + "name": "watch_items", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "tmdb_id": { + "name": "tmdb_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "media_type": { + "name": "media_type", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "in_watchlist": { + "name": "in_watchlist", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false, + "default": false + }, + "progress_status": { + "name": "progress_status", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "reaction": { + "name": "reaction", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "progress": { + "name": "progress", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false, + "default": 0 + }, + "title": { + "name": "title", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "image": { + "name": "image", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "rating": { + "name": "rating", + "type": "real", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "release_date": { + "name": "release_date", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "overview": { + "name": "overview", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "updated_at": { + "name": "updated_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": { + "watch_items_user_media_uq": { + "name": "watch_items_user_media_uq", + "columns": [ + "user_id", + "tmdb_id", + "media_type" + ], + "isUnique": true + }, + "watch_items_user_status_idx": { + "name": "watch_items_user_status_idx", + "columns": [ + "user_id", + "progress_status" + ], + "isUnique": false + }, + "watch_items_user_updated_idx": { + "name": "watch_items_user_updated_idx", + "columns": [ + "user_id", + "updated_at" + ], + "isUnique": false + } + }, + "foreignKeys": { + "watch_items_user_id_users_id_fk": { + "name": "watch_items_user_id_users_id_fk", + "tableFrom": "watch_items", + "tableTo": "users", + "columnsFrom": [ + "user_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": { + "watch_items_progress_range": { + "name": "watch_items_progress_range", + "value": "\"watch_items\".\"progress\" between 0 and 100" + }, + "watch_items_rating_range": { + "name": "watch_items_rating_range", + "value": "\"watch_items\".\"rating\" between 0 and 10" + } + } + }, + "watchlist_snapshots": { + "name": "watchlist_snapshots", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "items": { + "name": "items", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": { + "snapshots_user_created_idx": { + "name": "snapshots_user_created_idx", + "columns": [ + "user_id", + "created_at" + ], + "isUnique": false + } + }, + "foreignKeys": { + "watchlist_snapshots_user_id_users_id_fk": { + "name": "watchlist_snapshots_user_id_users_id_fk", + "tableFrom": "watchlist_snapshots", + "tableTo": "users", + "columnsFrom": [ + "user_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + } + }, + "views": {}, + "enums": {}, + "_meta": { + "schemas": {}, + "tables": {}, + "columns": {} + }, + "internal": { + "indexes": {} + } +} \ No newline at end of file diff --git a/drizzle/meta/_journal.json b/drizzle/meta/_journal.json index a9e10b59..99d23f8d 100644 --- a/drizzle/meta/_journal.json +++ b/drizzle/meta/_journal.json @@ -8,6 +8,20 @@ "when": 1786817243575, "tag": "0000_dear_warbound", "breakpoints": true + }, + { + "idx": 1, + "version": "6", + "when": 1786857065846, + "tag": "0001_slippery_cammi", + "breakpoints": true + }, + { + "idx": 2, + "version": "6", + "when": 1786857611132, + "tag": "0002_cute_bloodstrike", + "breakpoints": true } ] } \ No newline at end of file diff --git a/package.json b/package.json index 96e077de..0ef1e905 100644 --- a/package.json +++ b/package.json @@ -6,7 +6,7 @@ "scripts": { "dev": "vite dev --port 3000", "dev:web": "vite dev --port 3000", - "dev:cf": "wrangler dev", + "dev:cf": "pnpm build && wrangler dev", "preview:cf": "pnpm build && wrangler dev", "build": "vite build", "start": "vite preview --port 5296", diff --git a/server/routes/api/health.ts b/server/routes/api/health.ts index 9b2c7346..a3fac4d3 100644 --- a/server/routes/api/health.ts +++ b/server/routes/api/health.ts @@ -1,12 +1,12 @@ // GET /api/health — pings D1 (select 1) import { sql } from "drizzle-orm"; -import { defineEventHandler } from "h3"; +import { defineEventHandler, setResponseStatus } from "h3"; import { getDb } from "../../../src/server/db/client"; import { getEnv } from "../../../src/server/env"; type CheckResult = { ok: boolean; [key: string]: unknown }; -export default defineEventHandler(async () => { +export default defineEventHandler(async (event) => { const env = getEnv(); const started = Date.now(); @@ -31,6 +31,10 @@ export default defineEventHandler(async () => { } } + if (!ok) { + setResponseStatus(event, 503); + } + return { ok, service: "pebbly", diff --git a/server/tasks/snapshots.ts b/server/tasks/snapshots.ts index 5a7410c4..74d8dc7b 100644 --- a/server/tasks/snapshots.ts +++ b/server/tasks/snapshots.ts @@ -4,16 +4,69 @@ // Nitro's task system: the cron expression in wrangler.toml // (`[triggers] crons = ["0 3 * * *"]`) is dispatched here via the // `scheduledTasks` mapping in nitro.config.ts. +// +// Each invocation is bounded: createDailySnapshots processes at most +// MAX_USERS_PER_RUN users, resuming from the last-processed user id persisted +// in D1 (snapshot_cursors). Users skipped by one invocation are processed by +// the next cron run, so coverage is eventual and complete without exceeding +// the Worker execution budget. +import { eq } from "drizzle-orm"; import { defineTask } from "nitro/task"; +import { getDb } from "../../src/server/db/client"; +import { snapshotCursors } from "../../src/server/db/schema"; +import { getEnv } from "../../src/server/env"; import { createDailySnapshots } from "../../src/server/helpers/snapshots"; +const CURSOR_KEY = "watchlist_snapshot_cursor"; +const MAX_USERS_PER_RUN = 200; + +async function readCursor(): Promise { + try { + const db = getDb(getEnv()); + const row = await db + .select({ value: snapshotCursors.value }) + .from(snapshotCursors) + .where(eq(snapshotCursors.key, CURSOR_KEY)) + .limit(1); + return row[0]?.value ?? ""; + } catch (error) { + console.error("Failed to read snapshot cursor:", error); + return ""; + } +} + +async function writeCursor(cursor: string) { + try { + const db = getDb(getEnv()); + await db + .insert(snapshotCursors) + .values({ key: CURSOR_KEY, value: cursor, updatedAt: Date.now() }) + .onConflictDoUpdate({ + target: snapshotCursors.key, + set: { value: cursor, updatedAt: Date.now() }, + }); + } catch (error) { + console.error("Failed to persist snapshot cursor:", error); + } +} + export default defineTask({ meta: { name: "snapshots", - description: "Create daily watchlist snapshots for all users", + description: "Create daily watchlist snapshots for all users (bounded per run)", }, async run() { - await createDailySnapshots(); - return { result: "daily snapshots created" }; + const cursor = await readCursor(); + const { lastProcessedId, processed } = await createDailySnapshots( + cursor, + MAX_USERS_PER_RUN, + ); + await writeCursor(lastProcessedId); + + return { + result: `daily snapshots created (${processed} users)`, + processed, + lastProcessedId, + }; }, }); diff --git a/src/components/admin/admin-permission-toggles.tsx b/src/components/admin/admin-permission-toggles.tsx index a9f7574a..f2571b45 100644 --- a/src/components/admin/admin-permission-toggles.tsx +++ b/src/components/admin/admin-permission-toggles.tsx @@ -1,5 +1,6 @@ -import { useMutation, useQuery } from "@tanstack/react-query"; +import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query"; import { Activity, AlertTriangle, Zap } from "lucide-react"; +import { useState } from "react"; import { Skeleton } from "@/components/ui/skeleton"; import { type PermissionRole, @@ -57,6 +58,21 @@ function featurePermissions( return permissionsByRole[role]?.[feature] ?? false; } +function FeatureError({ onRetry }: { onRetry: () => void }) { + return ( +
+ Failed to load permission settings. + +
+ ); +} + function FeatureRow({ feature, featureLabel, @@ -101,17 +117,35 @@ function FeatureRow({ } export function AdminPermissionToggles() { + const queryClient = useQueryClient(); + const [toggleError, setToggleError] = useState(null); const rawPermissions = useQuery({ queryKey: ["admin", "role-permissions"], queryFn: () => unwrap(getRolePermissions()), }); const setRolePermissionMutation = useMutation({ - mutationFn: (args: { role: string; feature: string; enabled: boolean }) => + mutationFn: (args: { feature: RbacFeature; enabled: boolean }) => unwrap(setRolePermission({ data: args })), + onSuccess: () => { + setToggleError(null); + // Keep the table in sync with the persisted permission state. + queryClient.invalidateQueries({ + queryKey: ["admin", "role-permissions"], + }); + }, + onError: (error) => { + setToggleError( + error instanceof Error ? error.message : "Failed to update permission", + ); + }, }); const rawPermissionsData = rawPermissions.data; + if (rawPermissions.isError) { + return rawPermissions.refetch()} />; + } + if (rawPermissionsData === undefined) { return (
@@ -128,6 +162,11 @@ export function AdminPermissionToggles() { return (
+ {toggleError && ( +
+ {toggleError} +
+ )}
{Object.entries(RBAC_FEATURES).map(([feature, config]) => ( - setRolePermissionMutation.mutate({ role, feature, enabled }) + onToggle={(_role, enabled) => + setRolePermissionMutation.mutate({ + feature: feature as RbacFeature, + enabled, + }) } /> ))} diff --git a/src/components/admin/admin-user-table.tsx b/src/components/admin/admin-user-table.tsx index 843ae33e..761d4a7f 100644 --- a/src/components/admin/admin-user-table.tsx +++ b/src/components/admin/admin-user-table.tsx @@ -1,5 +1,5 @@ import { useUser } from "@clerk/react"; -import { useMutation, useQuery } from "@tanstack/react-query"; +import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query"; import { AlertCircle, Ban, @@ -25,6 +25,7 @@ import { import { Input } from "@/components/ui/input"; import { Skeleton } from "@/components/ui/skeleton"; import type { RbacRole } from "@/constants"; +import { queryKeys } from "@/lib/query/keys"; import { listUsers, setUserBanned, setUserRoles } from "@/server/fns/admin"; import { unwrap } from "@/server/schema/common"; @@ -44,20 +45,27 @@ interface UserTarget { } type FilterTab = "all" | "active" | "banned"; - export function AdminUserTable() { const { user: currentUser } = useUser(); + const queryClient = useQueryClient(); const usersQuery = useQuery({ - queryKey: ["admin", "users"], + queryKey: queryKeys.admin.users(currentUser?.id), queryFn: () => unwrap(listUsers({ data: {} })), }); + const refreshUsers = () => { + void queryClient.invalidateQueries({ + queryKey: queryKeys.admin.users(currentUser?.id), + }); + }; const setUserRolesMutation = useMutation({ mutationFn: (args: { tokenIdentifier: string; roles: DynamicRbacRole[] }) => unwrap(setUserRoles({ data: args })), + onSuccess: refreshUsers, }); const setUserBannedMutation = useMutation({ mutationFn: (args: { tokenIdentifier: string; banned: boolean }) => unwrap(setUserBanned({ data: args })), + onSuccess: refreshUsers, }); const [selectedUser, setSelectedUser] = useState(null); @@ -321,13 +329,14 @@ export function AdminUserTable() { ); }); }; - return ( ); @@ -559,13 +559,13 @@ export function DailyPickButton() { setIsOpen(false)} - className="relative aspect-[2/3] w-20 sm:w-24 shrink-0 overflow-hidden rounded-xl border-2 border-background/60 shadow-xl bg-muted group/poster hover:opacity-90 transition-opacity" + className="relative aspect-[2/3] w-20 sm:w-24 shrink-0 overflow-hidden rounded-xl border-2 border-background/60 shadow-xl bg-muted group/poster [@media(hover:hover)]:hover:opacity-90 transition-opacity" title={`View ${title}`} > {title} diff --git a/src/components/homepage-recommendations.tsx b/src/components/homepage-recommendations.tsx index 7f16c23f..6ad5859f 100644 --- a/src/components/homepage-recommendations.tsx +++ b/src/components/homepage-recommendations.tsx @@ -110,12 +110,12 @@ const HomepageRecommendationCard = memo( /> {/* Top-right solid action buttons overlay */} -
+
@@ -344,7 +345,7 @@ const PersonCard = memo((props: PersonCardSpecificProps) => { {name} {