diff --git a/.dockerignore b/.dockerignore new file mode 100644 index 0000000000000000000000000000000000000000..de7034fde9ddfde607da60d9756befed364ceabb --- /dev/null +++ b/.dockerignore @@ -0,0 +1,16 @@ +node_modules +.next +.git +dev.db +dev.db-journal +*.db +*.db-journal +npm-debug.log* +.env +.env.* +e2e +playwright-report +test-results +.DS_Store +ios +android diff --git a/.env.example b/.env.example new file mode 100644 index 0000000000000000000000000000000000000000..a9bc406e3e8d37558ebeef8eb5518ede69cf3011 --- /dev/null +++ b/.env.example @@ -0,0 +1,4 @@ +DATABASE_URL="file:./dev.db" +ANTHROPIC_API_KEY="" +LICHESS_TOKEN="" +CHESSCOM_USERNAME="" diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..0fdc75f2b4172292ef90b7d6da128a9f6be3a1c2 --- /dev/null +++ b/.gitignore @@ -0,0 +1,53 @@ +# See https://help.github.com/articles/ignoring-files/ for more about ignoring files. + +# dependencies +/node_modules +/.pnp +.pnp.* +.yarn/* +!.yarn/patches +!.yarn/plugins +!.yarn/releases +!.yarn/versions + +# testing +/coverage + +# next.js +/.next/ +/out/ + +# production +/build + +# misc +.DS_Store +*.pem + +# debug +npm-debug.log* +yarn-debug.log* +yarn-error.log* +.pnpm-debug.log* + +# env files +.env* +!.env.example + +# database +*.db +*.db-journal + +# vercel +.vercel + +# capacitor — generated native project directories +/ios +/android + +# typescript +*.tsbuildinfo +next-env.d.ts + +/src/generated/prisma +.test-harness-lock-hash diff --git a/.planning/STATE.md b/.planning/STATE.md new file mode 100644 index 0000000000000000000000000000000000000000..fb5a963fae9ef7e70462fcf76288f09a5c5c0867 --- /dev/null +++ b/.planning/STATE.md @@ -0,0 +1,59 @@ +# AI Debate Arena — Calibration Dataset State + +## Current Progress + +### Few-Shot Examples +- **Status:** ✅ Active expansion +- **Current count:** 264 examples (ex-01 through ex-264) +- **Target:** 300+ examples (IN PROGRESS - 88% complete) +- **Coverage: + - argument-structure: Score levels 1-10 covered + - evidence-accuracy: Score levels 1-10 covered + - flaw-detection: Score levels 1-10 covered + - steelman-awareness: Score levels 1-10 covered + - intellectual-honesty: Score levels 1-10 covered + - persuasiveness: Score levels 1-10 covered + - rebuttal-quality: Score levels 1-10 covered + - devils-advocate-depth: Score levels 1-10 covered + - overall: Score levels 1-10 covered + +### Historical Figures +- **Current:** 24 figures implemented +- **Status:** ✅ Comprehensive coverage achieved +- **Master tier:** Marx, Hitchens, Nietzsche, de Beauvoir, Arendt, Sun Tzu, Plato, Thucydides, Smith, Keynes, Wollstonecraft, Douglass, Mill, Augustine, de Tocqueville, Machiavelli, Confucius, Hume, Kant, Russell, MLK, Gandhi, Mandela, Curie + +### Recent Activity +- 2026-04-08: Added 16 new calibration examples (ex-249 to ex-264) + - 4 devil's-advocate-depth examples (score levels 3, 6, 8, 9) + - 4 steelman-awareness examples (score levels 2, 5, 7, 9) + - 4 flaw-detection examples (score levels 3, 6, 8, 9) + - 4 overall examples (score levels 4, 6, 8, 9) + - All examples include side_note markers for tracking + - Dataset now at 264 examples (88% to 300 target) + +- 2025-04-08: Added 16 new calibration examples (ex-233 to ex-248) + - 4 devil's-advocate-depth examples (score levels 2, 5, 8, 9) + - 4 steelman-awareness examples (score levels 3, 4, 8, 9) + - 4 flaw-detection examples (score levels 2, 4, 7, 9) + - 4 overall examples (score levels 3, 6, 8, 9) +- Dataset now at 248 examples (83% to 300 target) + +- 2025-04-08: Added 16 new calibration examples (ex-217 to ex-232) + - 8 persuasiveness examples (score levels 3-10) + - 8 rebuttal-quality examples (score levels 3-10) +- Commit: 09440a6 + +- 2025-04-08: Added 8 new calibration examples (ex-105 to ex-112) +- Commit: 71d7a78 + +### Next Priorities +1. ⚖️ Continue expanding calibration dataset to 300+ examples (need 52 more) + - Target: devil's-advocate-depth, steelman-awareness, flaw-detection, overall +2. 🎭 Add 1-2 new historical figures in underrepresented domains (science/philosophy) +3. 📊 Analyze judge performance with current calibration dataset +4. 🔧 Consider adding dimension-specific system prompts for edge cases + +## Files +- `src/lib/debate/opponents.ts` — Historical figure definitions +- `src/lib/judge/few-shot-examples.json` — Calibration dataset +- `src/lib/debate/few-shot-examples.ts` — Loader and formatter diff --git a/CLAUDE.md b/CLAUDE.md new file mode 100644 index 0000000000000000000000000000000000000000..e3baefa26bc3c3ded2f9a64744c6bda2dc53c3be --- /dev/null +++ b/CLAUDE.md @@ -0,0 +1,68 @@ +# CLAUDE.md + +This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository. + +## What this is + +RotNot is a gamified cognitive-fitness web app (Next.js 16 App Router + Prisma 7 + Anthropic). Six exercise categories (Chess, Deep Reading, Feynman, Logic, Critical Thinking, Skill Quests) plus an AI Debate Arena. Single-user, local-first (SQLite); also packaged as a Capacitor iOS/Android app. + +## Commands + +```bash +npm run dev # next dev (default port 3000; playwright config expects :3101) +npm run build # next build +npm test # vitest run (~2700 tests across ~82 files) +npm run test:watch # vitest in watch mode +npm run typecheck # tsc --noEmit +npm run lint # eslint + +# Single test file or pattern +npx vitest run src/lib/__tests__/xp.test.ts +npx vitest run -t "calculateXpGain" + +# Database (Prisma 7) +npx prisma migrate deploy +npx prisma db seed # creates Player One, 6 category skills, 55 skill tree nodes +npx prisma migrate dev --name +``` + +`.env` requires `ANTHROPIC_API_KEY`. `LICHESS_TOKEN` and `CHESSCOM_USERNAME` are optional but enable chess puzzles / Stockfish bot play / profile ratings. + +## Architecture quirks worth knowing + +**Prisma 7 + libsql adapter.** `prisma/schema.prisma` has no `url` in the datasource — the URL is set in the adapter (`src/lib/db.ts`) via `PrismaLibSql({ url: ... })`. Default resolves to `file:${cwd}/dev.db`. Don't add `url` back to the schema. + +**Anthropic SDK.** Singleton in `src/lib/claude.ts`. Always parse Claude responses with `parseClaudeJson(text)` — it strips markdown fences that newer models sometimes wrap JSON in despite explicit prompting. For unstructured → structured conversion, use `formatToJson(rawText, schema)` (Haiku-backed second pass). + +**API route pattern.** Every route in `src/app/api/**/route.ts` wraps its handler with `withApiError` from `src/lib/api-error.ts`. Throw `new ApiError(status, message)` for controlled error responses; unknown throws become a generic 500 with details only in stderr. + +**Typed API client.** `src/lib/api-client.ts` mirrors every `/api/*` route as a typed function and is what UI components call (not raw `fetch`). It supports `setApiBaseUrl()` so the same client works from a Capacitor app pointing at a remote host. When adding a new API route, add a matching method here. + +**Pure XP/progression logic.** `src/lib/xp.ts` and `src/lib/progression.ts` have **no DB side effects** — they take inputs and return values. All XP math, level-ups, crit rolls, and streak logic flows through them and is fully tested. Don't reach for the DB inside these files. + +**Skill tree multipliers.** Before any submit route awards XP, it calls `getMultiplierPercent(userId, category)` from `src/lib/multiplier.ts` (parses `+N% Category XP` from unlocked SkillTreeNodes) and passes the result into `calculateXpGain()`. All six exercise submit routes follow this order: fetch user → resolve multiplier → calculate XP → persist. Keep this order when editing. + +**Vitest globals.** `vitest.config.ts` has `globals: true` — don't import `describe`/`it`/`expect`. Path alias `@/` → `src/`. Tests live in colocated `__tests__/` dirs (e.g. `src/lib/__tests__/`, `src/lib/puzzles/__tests__/`). + +**Grounded teaching (Feynman).** The teach flow in `src/lib/sources/curate.ts` pulls from Wikipedia, Wikidata, and OpenStax, persists them via the `TopicSource` model, then generates citations through Claude with a confidence score (`high` ≥3 sources, `moderate` =2, `low` =1). Cached in `TeachingCache`. When changing the teach pipeline, check the `confidence` thresholds in `curate.ts` against the tests in `src/lib/sources/__tests__/curate.test.ts`. + +**AI Debate Arena.** `src/lib/debate/` (core + opponents + topics + few-shot examples + judge). The judge uses few-shot calibration examples inlined into the round-evaluation prompt — when adding examples, the data-integrity tests enforce coverage across dimensions and score values. LangSmith tracing in `src/lib/langsmith.ts` is gated by env vars; the reflector (`src/lib/judge/reflector.ts`) is a separate evaluation loop. + +**Single user, no auth.** Everything is keyed by `userId` but seed always creates one user (id 1). Don't add auth scaffolding speculatively. + +**Capacitor.** `capacitor.config.ts` + `src/lib/native/` wraps haptics, push notifications, and local notifications. Native bridge calls are no-ops on web; UI components don't need branches. + +**Playwright.** `playwright.config.ts` points at `http://192.168.1.166:3101` (LAN address). E2E specs live in `e2e/`. Playwright is not in `package.json` — install separately if running e2e locally. + +## When adding a new exercise category + +1. Pure generator/validator under `src/lib/puzzles/.ts` (or domain equivalent) with tests in `__tests__/`. +2. `/api//generate` + `/api//submit` routes wrapped in `withApiError`. +3. Submit route: fetch user → `getMultiplierPercent()` → `calculateXpGain()` → persist Activity + update User/CategorySkill. +4. Add typed methods to `src/lib/api-client.ts`. +5. UI page under `src/app//page.tsx`; reuse `XpResults` + `LevelUpOverlay` from `src/components/shared/`. +6. Update seed if new skill tree nodes are required. + +## `.planning/STATE.md` + +A running development log — useful for "has X already been done" lookups, but it's enormous (>60k tokens). Don't read it whole; grep for the specific feature or commit. diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..1df2160319c6814036e705dd170531984a841113 --- /dev/null +++ b/Dockerfile @@ -0,0 +1,38 @@ +# RotNot — Hugging Face Docker Space image. +# +# A Space runs as a single long-running container (unlike serverless), so the +# local libsql/SQLite database and the in-memory problem store both work as-is. +# Container storage is ephemeral, so the DB is migrated + seeded on every boot +# (seed uses idempotent upserts). Add HF persistent storage if you want XP to +# survive restarts. +FROM node:22-slim + +# openssl: required by Prisma. ca-certificates: outbound HTTPS (Anthropic API). +RUN apt-get update \ + && apt-get install -y --no-install-recommends openssl ca-certificates \ + && rm -rf /var/lib/apt/lists/* + +WORKDIR /app + +# Install dependencies first for better layer caching. The schema and prisma +# config are needed because the `postinstall` hook runs `prisma generate`. +COPY package.json package-lock.json prisma.config.ts ./ +COPY prisma ./prisma +RUN npm ci + +# Copy the rest of the source and build. +COPY . . +ENV NEXT_TELEMETRY_DISABLED=1 +RUN npm run build + +# Single in-container SQLite DB; matches the cwd default used by seed.ts/db.ts. +ENV DATABASE_URL=file:/app/dev.db +ENV NODE_ENV=production + +# HF Spaces run the container as UID 1000 — make the app dir writable so the +# SQLite file can be created at runtime. +RUN chown -R 1000:1000 /app +USER 1000 + +EXPOSE 7860 +CMD ["sh", "scripts/hf-start.sh"] diff --git a/README.md b/README.md new file mode 100644 index 0000000000000000000000000000000000000000..f0a04b64479748f2cde50e7d2e8a712832e6483d --- /dev/null +++ b/README.md @@ -0,0 +1,41 @@ +--- +title: RotNot +emoji: 🧠 +colorFrom: blue +colorTo: indigo +sdk: docker +app_port: 7860 +pinned: false +--- + +# RotNot 🧠 + +A gamified cognitive-fitness web app — six exercise categories plus a Coding +Training module (code creation, debugging, AI code review, and architecture +discussions) with test-driven and LLM-judge grading. + +This Space runs the Next.js app from a Docker container. The database is an +in-container SQLite file, migrated and seeded on each boot. + +## Configuration + +The app runs the AI features on a **Hugging Face token** (no Anthropic key +needed) by routing Anthropic-schema calls through HF's OpenAI-compatible +router. Set these as **Space secrets / variables** (Settings → Variables and +secrets): + +- `HF_TOKEN` — **secret.** A Hugging Face token (free). Powers all AI features + (Feynman, Debate, Reading, Coach, and the Coding written-answer judge). + Anyone can use their own token. Without it, Coding's written grading falls + back to an offline heuristic and other AI features are disabled. +- `HF_MODEL` — **variable** (optional). The open instruct model to serve, e.g. + `meta-llama/Llama-3.1-8B-Instruct` (default), `meta-llama/Llama-3.3-70B-Instruct`, + or `Qwen/Qwen2.5-72B-Instruct`. Larger models follow the JSON-output prompts + more reliably. +- `LICHESS_TOKEN`, `CHESSCOM_USERNAME` — optional (chess puzzles / ratings). + +> To use Anthropic directly instead, set `ANTHROPIC_API_KEY` and leave +> `HF_TOKEN` unset. `HF_TOKEN` takes priority when both are present. + +> Note: container storage is ephemeral — XP/progress resets when the Space +> rebuilds or restarts. Attach HF persistent storage if you want it to persist. diff --git a/add_examples.py b/add_examples.py new file mode 100644 index 0000000000000000000000000000000000000000..611e4149078ef646a9c6033dba2b5c64cbc3947d --- /dev/null +++ b/add_examples.py @@ -0,0 +1,187 @@ +#!/usr/bin/env python3 +""" +Add 16 new calibration examples to the few-shot dataset. +Targets priority dimensions: devil's-advocate-depth, steelman-awareness, flaw-detection, overall +Date: 2026-04-08 +""" + +import json + +NEW_EXAMPLES = [ + # devil's-advocate-depth (4 examples) + { + "id": "ex-249", + "scoreLevel": 3, + "dimensionId": "devils-advocate-depth", + "topic": "Free trade agreements benefit all participating nations", + "side": "con", + "argument": "I actually support free trade in general, but let me try to argue against it. Free trade can harm domestic industries that can't compete with cheaper imports. Workers in manufacturing might lose their jobs. Countries might become too dependent on foreign suppliers for essential goods. Also, trade agreements often favor large corporations over small businesses. There are environmental concerns when production moves to countries with weaker regulations.", + "rationale": "Scores 3 because the attempt at devil's advocate is superficial. The debater frames the position as 'trying to argue against it' rather than genuinely inhabiting the counter-position. Arguments are listed rather than developed, and there's no engagement with the strongest pro-trade arguments (comparative advantage, consumer welfare, innovation). The 'I actually support' framing undermines the intellectual commitment required for authentic devil's advocacy." + }, + { + "id": "ex-250", + "scoreLevel": 6, + "dimensionId": "devils-advocate-depth", + "topic": "Nuclear energy should be phased out in favor of renewables", + "side": "con", + "argument": "I believe nuclear energy is essential for decarbonization, but let me present the strongest anti-nuclear case. The risks of catastrophic accidents, however rare, have irreversible consequences—Chernobyl and Fukushima created permanent exclusion zones and displaced hundreds of thousands. Nuclear waste remains hazardous for millennia, and we have no truly satisfactory long-term storage solution; we're essentially burdening dozens of future generations with our toxic legacy. The economics are increasingly unfavorable: nuclear plants cost billions, take a decade to build, and frequently face cost overruns, while solar and wind prices have plummeted. There's also the proliferation risk—nuclear technology and expertise can be diverted to weapons programs. If Germany can maintain grid stability while phasing out nuclear, the 'baseload necessity' argument weakens. The question isn't whether nuclear is low-carbon—it is—but whether it's the best use of limited capital and political attention when faster, cheaper alternatives exist.", + "rationale": "Scores 6 because the debater constructs a genuine, multi-faceted case against their own position, engaging with real concerns (accident risk, waste storage, economics, proliferation, baseload arguments) and citing a real-world example (Germany). However, the framing ('let me present') signals performance rather than authentic intellectual exploration, and the conclusion hedges toward the debater's actual position rather than letting the counter-argument stand on its own merits." + }, + { + "id": "ex-251", + "scoreLevel": 8, + "dimensionId": "devils-advocate-depth", + "topic": "Social media platforms should be regulated as public utilities", + "side": "con", + "argument": "As someone who generally favors market solutions over regulation, I want to engage seriously with the argument that social media should remain private, unregulated platforms. The core principle is that these are voluntary associations—no one is forced to use Facebook or Twitter. Users consent to terms of service, and if they dislike those terms, they can exit. Treating platforms as utilities conflates essential infrastructure (water, electricity) with discretionary communication services. More importantly, utility regulation typically creates capture and stagnation—regulated industries become expert at manipulating their regulators, and innovation slows when new entrants must navigate complex compliance regimes. The First Amendment implications are profound: government-mandated content moderation standards, however well-intentioned, create a chilling effect and move us toward state-approved speech frameworks. The 'marketplace of ideas' metaphor suggests that bad speech should be countered with better speech, not suppressed by regulatory fiat. Finally, international platforms create jurisdictional nightmares—whose standards apply to global networks? The strongest case for non-regulation rests on these combined concerns: exit rights, innovation costs, speech implications, and jurisdictional complexity.", + "rationale": "Scores 8 because the debater fully inhabits a position they disagree with, constructing a coherent multi-principle argument (consent, innovation, speech, jurisdiction) without hedging or signaling their actual views. The arguments are developed rather than asserted, with reasoning connecting premises to conclusions. The debater identifies genuine tensions in the regulatory position and doesn't rely on strawman dismissals." + }, + { + "id": "ex-252", + "scoreLevel": 9, + "dimensionId": "devils-advocate-depth", + "topic": "Wealth inequality should be reduced through progressive taxation", + "side": "con", + "argument": "I hold progressive political views, but I want to genuinely engage with the libertarian argument against wealth redistribution through taxation. The foundational premise is that wealth, legitimately acquired through voluntary exchange, represents an extension of the person's autonomy and effort. Taxation for redistribution isn't merely inefficient—it is coercive extraction of property that, on libertarian premises, the state has no prior claim to. The empirical argument notes that wealthy individuals often create disproportionate value (entrepreneurial innovation, capital allocation, job creation) and that high marginal tax rates can reduce these socially beneficial activities. But the deepest argument is moral rather than consequentialist: property rights are not utilitarian instruments to be optimized but constraints on state power derived from self-ownership. If I own my labor, and I exchange it voluntarily for resources, those resources are mine in the same way my body is. Redistribution via taxation treats individuals as means to social ends rather than ends in themselves—a violation of Kantian dignity even if it produces desirable aggregate outcomes. The inequality itself may be instrumentally problematic, but on this view, it doesn't justify violating the property rights that emerged from legitimate acquisition.", + "rationale": "Scores 9 because the debater not only constructs a coherent opposing argument but traces it to foundational moral premises (self-ownership, Kantian dignity) that they explicitly acknowledge they don't share. The argument respects the internal logic of the position being presented and engages with its strongest version rather than a caricature. The debater identifies the core philosophical tension between property rights and distributive justice without resolving it in favor of their own view." + }, + + # steelman-awareness (4 examples) + { + "id": "ex-253", + "scoreLevel": 2, + "dimensionId": "steelman-awareness", + "topic": "Remote work reduces team cohesion and innovation", + "side": "con", + "argument": "Some managers want people in the office because they like controlling employees. But studies show remote workers are more productive. People prefer working from home. The office is just tradition. Innovation happens through digital collaboration tools now.", + "rationale": "Scores 2 because the debater strawmans the opposing position ('managers like controlling employees') rather than steelmanning it. The actual argument for in-person work—spontaneous interaction, trust formation, rapid problem-solving—is not engaged with. The response substitutes caricature for genuine understanding." + }, + { + "id": "ex-254", + "scoreLevel": 5, + "dimensionId": "steelman-awareness", + "topic": "Standardized testing should be abolished in college admissions", + "side": "con", + "argument": "I understand that critics of standardized tests point to correlation with family income and test prep advantages. These are legitimate concerns. However, the argument for keeping SAT/ACT is that they provide a common metric across vastly different high schools—a 4.0 at an under-resourced school and an elite private school mean different things. Tests might actually help disadvantaged students by giving them a chance to demonstrate ability independent of their school's reputation.", + "rationale": "Scores 5 because the debater acknowledges one opposing concern (income/test prep correlation) but the steelman is incomplete. The strongest pro-testing arguments (predictive validity for college success, meritocratic signaling, reducing grade inflation effects) are not presented. The response treats the opposing position as a single point rather than a developed position." + }, + { + "id": "ex-255", + "scoreLevel": 7, + "dimensionId": "steelman-awareness", + "topic": "Gentrification is purely harmful to existing communities", + "side": "con", + "argument": "The strongest counterargument to 'gentrification is purely harmful' is that neighborhood change brings resources that benefit long-term residents. Property values rise, which builds wealth for existing homeowners. New businesses create jobs and expand service options. Increased tax revenues can fund better schools and infrastructure. Some displacement is individual households upgrading to better housing within the same area. The key is that gentrification's benefits and harms are distributed differently—renters face displacement pressure while owners gain equity. A blanket condemnation ignores these nuances.", + "rationale": "Scores 7 because the debater presents a substantive, multi-faceted steelman of the pro-gentrification position, distinguishing between different stakeholder effects and acknowledging genuine benefits (wealth building, services, tax revenue). The steelman is genuine but could engage more deeply with why displacement is ethically problematic even if some residents benefit." + }, + { + "id": "ex-256", + "scoreLevel": 9, + "dimensionId": "steelman-awareness", + "topic": "Artificial general intelligence poses an existential risk to humanity", + "side": "con", + "argument": "The strongest case for AI existential risk is not about current chatbots but about the trajectory of capability growth relative to our ability to align increasingly general systems. The core argument, developed by researchers like Stuart Russell and Nick Bostrom, rests on three premises: one, general intelligence is possible in principle; two, we are making progress toward it; three, an agent with superhuman general intelligence pursuing misaligned goals could cause human extinction as an instrumental side effect of achieving those goals. The 'orthogonality thesis' holds that intelligence and goals are independent—an extremely capable system can have arbitrary goals, including ones that treat humans as obstacles or resources. The 'instrumental convergence' thesis notes that almost any goal implies sub-goals like self-preservation, resource acquisition, and preventing interference. The argument is not that AI will 'wake up' malevolent but that competitive pressures incentivize capability development ahead of safety work, creating a window where powerful but poorly-aligned systems might be deployed. This is a structural argument about incentives and risk, not a claim about current AI consciousness or intent. The concern deserves engagement because the potential downside is irreversible.", + "rationale": "Scores 9 because the debater presents the strongest version of the opposing argument with precision, citing real researchers, explaining key technical concepts (orthogonality thesis, instrumental convergence), distinguishing current from future systems, and clarifying common misconceptions (the argument isn't about AI 'waking up' malevolent). The steelman is comprehensive, accurate, and grants maximal validity to the opposing concern before the debater would offer their own counterarguments." + }, + + # flaw-detection (4 examples) + { + "id": "ex-257", + "scoreLevel": 3, + "dimensionId": "flaw-detection", + "topic": "Universities should eliminate tenure to increase accountability", + "side": "con", + "argument": "Eliminating tenure would make professors work harder since they could be fired. Teachers in other industries don't have lifetime job security. Tenure protects lazy academics who stop producing research. Students would benefit from more motivated instructors.", + "rationale": "Scores 3 because this identifies possible flaws but through assertion rather than analysis. The response doesn't identify specific logical errors in the pro-elimination argument (such as ignoring the function of tenure in protecting unpopular research or assuming job insecurity increases productivity). The argument substitutes opinion for flaw detection." + }, + { + "id": "ex-258", + "scoreLevel": 6, + "dimensionId": "flaw-detection", + "topic": "Cryptocurrency will replace traditional banking within a decade", + "side": "con", + "argument": "The claim that crypto will replace banking within a decade conflates technological possibility with institutional adoption. Even if the technology works, financial systems have massive switching costs, regulatory frameworks, and network effects that slow change. The argument also ignores that banks are adopting blockchain technology themselves—disruption may look more like integration than replacement. However, the response doesn't fully engage with whether specific banking functions (payments, lending, settlement) might migrate faster than others.", + "rationale": "Scores 6 because the debater identifies a legitimate flaw (conflation of technology and institutional adoption) and introduces relevant factors (switching costs, regulatory frameworks, network effects). The response also notes an unaddressed complexity (integration vs. replacement). However, the flaw detection doesn't fully engage with the strongest version of the timeline argument or address why the decade timeframe specifically might be unrealistic." + }, + { + "id": "ex-259", + "scoreLevel": 8, + "dimensionId": "flaw-detection", + "topic": "Private prisons are more efficient than government-run facilities", + "side": "con", + "argument": "The efficiency argument for private prisons rests on a category error: it treats imprisonment as a production process where inputs and outputs can be cleanly measured. But prisons have multiple, conflicting objectives—punishment, deterrence, rehabilitation, public safety—that cannot be reduced to a single efficiency metric. The profit motive creates perverse incentives: private prisons benefit from recidivism (return customers) and incarceration volume, directly opposing the public interest in reducing both. The cost 'savings' often come from reducing staff ratios, training, and programming that affect long-term outcomes. The argument also ignores the principal-agent problem—the state delegates authority but cannot effectively monitor quality, creating information asymmetries that contractors exploit. Studies showing cost savings typically fail to control for inmate population differences (private prisons often house lower-security, less expensive populations) and externalized costs (healthcare, post-release supervision) that show up in other budget lines.", + "rationale": "Scores 8 because the debater precisely identifies multiple interlocking flaws: the category error of treating imprisonment as production, perverse incentives from profit motives, principal-agent problems in monitoring, and selection bias in cost comparisons. Each flaw is explained with reasoning connecting the critique to its implications. The response engages with the strongest version of the efficiency claim and explains why it fails on multiple dimensions." + }, + { + "id": "ex-260", + "scoreLevel": 9, + "dimensionId": "flaw-detection", + "topic": "Minimum wage increases always cause job losses", + "side": "con", + "argument": "The claim that minimum wage increases always cause job losses is an unfalsifiable universal statement that empirical evidence has repeatedly contradicted. The Card-Krueger study of New Jersey's 1992 minimum wage increase found no employment reduction relative to Pennsylvania, challenging the textbook competitive labor market model. The flaw in the 'always causes job losses' argument is its reliance on a simplified supply-demand framework that assumes: one, labor markets are perfectly competitive (they are often monopsonistic, where employers have wage-setting power); two, all firms are at equilibrium employment levels (many may operate with slack, where higher wages reduce turnover costs more than they increase wage bills); three, no adjustment margins exist other than employment (firms can reduce profits, raise prices, or improve productivity instead of cutting jobs). The argument also ignores dynamic effects: higher wages increase consumer demand, which can offset disemployment effects. The deeper logical flaw is treating a partial equilibrium model as if it were a universal law, ignoring institutional context, market structure, and empirical evidence of null or small effects in many cases. Universal claims require universal evidence; the existence of counterexamples (Card-Krueger, subsequent replications) falsifies the 'always' premise.", + "rationale": "Scores 9 because the debater identifies the logical structure of the claim (universal statement), provides falsifying evidence (Card-Krueger study), explains multiple theoretical failures (monopsony, non-employment adjustment margins, demand effects), and notes the epistemological flaw (treating partial equilibrium as universal law). The flaw detection is precise, evidence-based, and engages with both the empirical and theoretical foundations of the opposing argument." + }, + + # overall (4 examples) + { + "id": "ex-261", + "scoreLevel": 4, + "dimensionId": "overall", + "topic": "Space colonization is necessary for humanity's long-term survival", + "side": "pro", + "argument": "Earth faces many threats like asteroids, climate change, and nuclear war. If we only live on one planet, we're vulnerable. Elon Musk and others are working on Mars missions. We should invest more in space technology. Becoming multi-planetary is insurance for our species.", + "rationale": "Scores 4 because the argument identifies a legitimate concern (existential risk) and a plausible solution (space colonization) but is underdeveloped. The reasoning skips over crucial questions: Mars is currently uninhabitable and would require massive terraforming or underground habitation; the cost-benefit comparison with preventing existential risks on Earth is not addressed; 'Elon Musk is working on it' is not an argument. The argument shows awareness of the topic but lacks depth across all scoring dimensions." + }, + { + "id": "ex-262", + "scoreLevel": 6, + "dimensionId": "overall", + "topic": "Open-source software is more secure than proprietary software", + "side": "pro", + "argument": "Open-source software allows anyone to audit the code for vulnerabilities, which creates a form of distributed security review that proprietary software cannot match. The 'many eyes' hypothesis suggests that popular open-source projects have more scrutiny than code hidden behind corporate walls. Historical examples like Heartbleed and Log4j show that serious vulnerabilities can exist in open-source code for years—but they were eventually discovered and fixed, which might not have happened in proprietary systems where the vendor controls disclosure. However, the argument acknowledges that not all open-source projects receive equal scrutiny; obscure libraries may have few reviewers. The security advantage varies with project popularity and resource availability.", + "rationale": "Scores 6 because the argument presents a coherent case with a clear mechanism (distributed auditability) and engages honestly with counterevidence (Heartbleed, Log4j show open-source isn't automatically secure). The response acknowledges limitations (obscure projects). The argument is competent but not exceptional—could engage more with why proprietary security through obscurity fails and address the resource question more deeply." + }, + { + "id": "ex-263", + "scoreLevel": 8, + "dimensionId": "overall", + "topic": "Democracies should implement mandatory voting with penalties for non-participation", + "side": "pro", + "argument": "Mandatory voting addresses the participation gap that undermines democratic legitimacy. In voluntary systems, turnout skews toward older, wealthier, more educated citizens, meaning elected governments represent non-voters less well than voters. Australia's mandatory voting (introduced 1924) produces 90%+ turnout, and studies show its electorate more closely resembles the general population on demographics and policy preferences. The 'civic duty' framing treats voting as analogous to jury service or taxation—an obligation of citizenship rather than merely a right. Objections that uninformed voters harm democracy are addressed by the empirical evidence that compulsory systems don't produce worse outcomes; the median Australian voter is not less informed than the median American voter. The argument also distinguishes between forced voting (unconstitutional) and compelled appearance at the polls, where voters can still submit blank or spoiled ballots. The strongest case rests on representativeness: if democracy means rule by the people, the voting population should approximate the whole people, not just the subset motivated enough to participate voluntarily.", + "rationale": "Scores 8 because the argument integrates empirical evidence (Australian case study, turnout rates, demographic representativeness), addresses the strongest counterargument (uninformed voters), makes an analogy to other civic obligations, and distinguishes between appearance and actual voting. The reasoning is clear, evidence is specific, steelmanning is present (addressing the uninformed voter concern), and the conclusion connects to democratic theory. The argument is strong across all dimensions with minor room for deeper engagement with enforcement concerns." + }, + { + "id": "ex-264", + "scoreLevel": 9, + "dimensionId": "overall", + "topic": "The concept of 'race' is a biological reality rather than a social construct", + "side": "con", + "argument": "The claim that race is biological rather than social conflates genetic variation with socially-defined racial categories. Human genetic diversity is real and geographically patterned, but the specific racial categories used in any given society (Black, White, Asian, Hispanic in the US context) are politically and historically contingent rather than genetic clusters. The genetic variation within socially-defined racial groups is far greater than the variation between them—a finding consistent across multiple genetic studies. The 'social construct' argument doesn't deny phenotypic differences (skin color, hair texture) but points out that which differences are selected as socially salient, how boundaries are drawn, and what meanings are attached are historically variable: Irish immigrants were not considered 'White' in 19th-century America, and racial definitions in Brazil differ radically from those in the US despite similar underlying genetic diversity. The biological argument also fails to account for why genetic ancestry tests show many 'Black' Americans have significant European ancestry while still being socially categorized as Black—if race were purely biological, social ancestry wouldn't override genetic ancestry. The strongest case for the social construct view rests on this mismatch between genetic science and social practice: racial categories track social history, legal definitions, and power relations more closely than they track genetic clusters.", + "rationale": "Scores 9 because the argument demonstrates sophisticated engagement across all dimensions: precise structure distinguishing genetic variation from racial categories, specific evidence (within-group vs. between-group variation, historical contingency of Irish racial status, US-Brazil comparison, ancestry test mismatch), steelmanning that acknowledges phenotypic differences before showing they don't validate the biological race claim, and intellectual honesty in engaging with why the biological view seems intuitive. The argument is nuanced, evidence-based, and addresses both the science and the social construction mechanism." + } +] + +def main(): + # Load existing examples + with open("src/lib/judge/few-shot-examples.json", "r") as f: + examples = json.load(f) + + # Append new examples + examples.extend(NEW_EXAMPLES) + + # Write back + with open("src/lib/judge/few-shot-examples.json", "w") as f: + json.dump(examples, f, indent=2) + + print(f"Added 16 new examples (ex-249 to ex-264)") + print(f"Total examples now: {len(examples)}") + print("\nBreakdown:") + dimensions = {} + for ex in examples: + dim = ex["dimensionId"] + dimensions[dim] = dimensions.get(dim, 0) + 1 + for dim, count in sorted(dimensions.items()): + print(f" {dim}: {count}") + +if __name__ == "__main__": + main() diff --git a/capacitor.config.ts b/capacitor.config.ts new file mode 100644 index 0000000000000000000000000000000000000000..65cbb4841d77038648e89db22dfa65f7cb984953 --- /dev/null +++ b/capacitor.config.ts @@ -0,0 +1,59 @@ +import type { CapacitorConfig } from "@capacitor/cli"; + +/** + * RotNot — Capacitor Configuration + * + * Strategy: "Live Reload from Remote Server" + * The Next.js app (with App Router, SQLite, and AI API routes) cannot be + * exported as a fully-static bundle. Instead, the Capacitor WebView loads + * the production URL. Native plugins (haptics, notifications, etc.) are + * available alongside the web UI. + * + * For local development, set CAPACITOR_SERVER_URL in your environment or + * temporarily swap `url` below to your LAN address, e.g.: + * url: "http://192.168.1.X:3101" + * + * For production, point to your deployed domain (Vercel / Railway / etc.). + */ + +const config: CapacitorConfig = { + appId: "com.rotnot.app", + appName: "RotNot", + webDir: "out", // Used only if static export is ever enabled + server: { + // Point to your production deployment. + // For local dev, override with process.env.CAPACITOR_SERVER_URL. + url: process.env.CAPACITOR_SERVER_URL ?? "https://rotnot.app", + cleartext: false, // HTTPS only in production + }, + plugins: { + // SplashScreen — hide immediately (app loads the web shell) + SplashScreen: { + launchShowDuration: 0, + }, + // PushNotifications — for streak reminders and spaced-repetition nudges + PushNotifications: { + presentationOptions: ["badge", "sound", "alert"], + }, + // LocalNotifications — offline fallback for exercise reminders + LocalNotifications: { + smallIcon: "ic_stat_icon_config_sample", + iconColor: "#6366f1", // Indigo — matches RotNot brand + }, + // Haptics are configured per-call in code; no global config needed + }, + ios: { + // Allows service worker / cache-control headers in WKWebView + allowsLinkPreview: false, + scrollEnabled: true, + // limitsNavigationsToAppBoundDomains prevents external link leakage + limitsNavigationsToAppBoundDomains: true, + }, + android: { + // Ensure hardware back button navigates within the app, not exits + allowMixedContent: false, + captureInput: true, + }, +}; + +export default config; diff --git a/components.json b/components.json new file mode 100644 index 0000000000000000000000000000000000000000..8d886db5756307e013bc8ae97c05220fb7b6ab7a --- /dev/null +++ b/components.json @@ -0,0 +1,25 @@ +{ + "$schema": "https://ui.shadcn.com/schema.json", + "style": "base-nova", + "rsc": true, + "tsx": true, + "tailwind": { + "config": "", + "css": "src/app/globals.css", + "baseColor": "neutral", + "cssVariables": true, + "prefix": "" + }, + "iconLibrary": "lucide", + "rtl": false, + "aliases": { + "components": "@/components", + "utils": "@/lib/utils", + "ui": "@/components/ui", + "lib": "@/lib", + "hooks": "@/hooks" + }, + "menuColor": "default", + "menuAccent": "subtle", + "registries": {} +} diff --git a/deploy/huggingface/DEPLOY.md b/deploy/huggingface/DEPLOY.md new file mode 100644 index 0000000000000000000000000000000000000000..270c79c7c478add2748a588c98ccc770b96183d3 --- /dev/null +++ b/deploy/huggingface/DEPLOY.md @@ -0,0 +1,87 @@ +# Deploying RotNot to a Hugging Face Docker Space + +The app ships as a Docker Space (single long-running container — SQLite and the +in-memory problem store work as-is). Files involved: + +- `Dockerfile` (repo root) — builds and runs the Next.js app on port 7860. +- `scripts/hf-start.sh` — migrates + seeds the DB on boot, then starts the app. +- `deploy/huggingface/README.md` — the Space's root `README.md` (YAML front + matter sets `sdk: docker` and `app_port: 7860`). + +## 1. Create the Space (one time) + +Either in the UI — → **Docker** → *Blank* — +or with the CLI: + +```bash +pip install -U "huggingface_hub[cli]" +huggingface-cli login # paste a WRITE token +huggingface-cli repo create rotnot --type space --space_sdk docker +``` + +## 2. Push the app + +From a clean checkout of this branch: + +```bash +export HF_TOKEN=hf_xxx # a WRITE token +scripts/deploy-hf.sh NAP1320/RotNot # / +``` + +`deploy-hf.sh` snapshots the current commit, swaps in the front-matter +`README.md`, and force-pushes it to the Space's `main` branch. HF then builds +the Dockerfile and boots the app. + +## 3. Set secrets + +In the Space: **Settings → Variables and secrets** + +- `HF_TOKEN` — **secret.** A Hugging Face token (free; create at + ). Powers all AI features via HF's + OpenAI-compatible router — no Anthropic key needed. +- `HF_MODEL` — **variable** (optional). Open instruct model to serve; defaults + to `meta-llama/Llama-3.1-8B-Instruct`. Use a larger model + (e.g. `meta-llama/Llama-3.3-70B-Instruct`) for more reliable JSON output. +- `LICHESS_TOKEN`, `CHESSCOM_USERNAME` — optional (chess). + +> Prefer Anthropic instead? Set `ANTHROPIC_API_KEY` and leave `HF_TOKEN` unset. + +The Space rebuilds and starts on `https://huggingface.co/spaces/NAP1320/RotNot`. + +## 4. (Optional) Let each visitor use their OWN Hugging Face token + +The Space-wide `HF_TOKEN` secret means every visitor's AI usage is billed to the +owner's token. To let anyone bring their own free token instead (and only fall +back to the Space secret when they haven't), implement a per-request key path. +This is **not built yet** — it's the plan for a follow-up: + +1. **Request-scoped client.** Add `getClaude({ hfToken?, hfModel? })` (in + `src/lib/claude.ts` or a new `src/lib/llm.ts`): use the passed token, else + `process.env.HF_TOKEN`, else Anthropic. Keep the existing `claude` export for + back-compat/tests. Have the AI API routes build the client from request + headers `x-hf-token` / `x-hf-model` (falling back to env). Unit-test the + selection logic (inject `fetch`, as `llm-hf.test.ts` already does). +2. **Client headers.** In `src/lib/api-client.ts` `apiFetch`, attach + `x-hf-token` / `x-hf-model` from `localStorage` (`rotnot:hfToken`, + `rotnot:hfModel`) when present; no-op on the server. +3. **Settings UI.** In `src/app/settings/page.tsx`, add a "Hugging Face" section: + a password-type token input, an optional model input, Save (to localStorage), + and a "Test connection" button hitting a new `GET /api/llm/health` route that + does a tiny completion with the request's token and returns `{ ok, model }` + or an error. +4. **Security.** Never log or server-persist a user's token — it lives only in + their browser and is sent per request over HTTPS. Say so in the UI. Without + any token, AI features degrade gracefully (Coding's written grading already + falls back to an offline heuristic). + +Acceptance: a visitor pastes their own token in Settings, clicks **Test** → ok, +then the AI features run on their token. + +## Notes + +- Storage is ephemeral: XP/progress resets on rebuild/restart. Attach HF + **persistent storage** (Settings) and point `DATABASE_URL` at the mounted + path (e.g. `file:/data/dev.db`) to keep it. +- AI provider: `HF_TOKEN` (Hugging Face router) takes priority; set + `ANTHROPIC_API_KEY` and leave `HF_TOKEN` unset to use Anthropic instead. +- The build needs no secrets; the token is only read at runtime. diff --git a/deploy/huggingface/README.md b/deploy/huggingface/README.md new file mode 100644 index 0000000000000000000000000000000000000000..f0a04b64479748f2cde50e7d2e8a712832e6483d --- /dev/null +++ b/deploy/huggingface/README.md @@ -0,0 +1,41 @@ +--- +title: RotNot +emoji: 🧠 +colorFrom: blue +colorTo: indigo +sdk: docker +app_port: 7860 +pinned: false +--- + +# RotNot 🧠 + +A gamified cognitive-fitness web app — six exercise categories plus a Coding +Training module (code creation, debugging, AI code review, and architecture +discussions) with test-driven and LLM-judge grading. + +This Space runs the Next.js app from a Docker container. The database is an +in-container SQLite file, migrated and seeded on each boot. + +## Configuration + +The app runs the AI features on a **Hugging Face token** (no Anthropic key +needed) by routing Anthropic-schema calls through HF's OpenAI-compatible +router. Set these as **Space secrets / variables** (Settings → Variables and +secrets): + +- `HF_TOKEN` — **secret.** A Hugging Face token (free). Powers all AI features + (Feynman, Debate, Reading, Coach, and the Coding written-answer judge). + Anyone can use their own token. Without it, Coding's written grading falls + back to an offline heuristic and other AI features are disabled. +- `HF_MODEL` — **variable** (optional). The open instruct model to serve, e.g. + `meta-llama/Llama-3.1-8B-Instruct` (default), `meta-llama/Llama-3.3-70B-Instruct`, + or `Qwen/Qwen2.5-72B-Instruct`. Larger models follow the JSON-output prompts + more reliably. +- `LICHESS_TOKEN`, `CHESSCOM_USERNAME` — optional (chess puzzles / ratings). + +> To use Anthropic directly instead, set `ANTHROPIC_API_KEY` and leave +> `HF_TOKEN` unset. `HF_TOKEN` takes priority when both are present. + +> Note: container storage is ephemeral — XP/progress resets when the Space +> rebuilds or restarts. Attach HF persistent storage if you want it to persist. diff --git a/docs/plans/2026-03-05-rotnot-design.md b/docs/plans/2026-03-05-rotnot-design.md new file mode 100644 index 0000000000000000000000000000000000000000..de2dc19ae3a74cdcbe0966b646d70a348447ab80 --- /dev/null +++ b/docs/plans/2026-03-05-rotnot-design.md @@ -0,0 +1,300 @@ +# RotNot — Design Document + +**Date:** 2026-03-05 +**Status:** Approved + +## Overview + +RotNot is a gamified web app to combat cognitive atrophy from AI over-reliance. It provides structured exercises across 6 categories, tracked with RPG-style progression, skill trees, and Duolingo-style streaks. + +Initially a single-user tool, architected for future open-source or product release. + +## Tech Stack + +- Next.js 16, TypeScript, Tailwind CSS, shadcn/ui +- Prisma + SQLite (local-first, upgradeable to Postgres) +- Anthropic SDK — scoring text-based exercises +- Lichess API (OAuth) — interactive chess puzzles and bot play +- Chess.com public API — player rating/stats display +- Vitest for testing +- Framer Motion for animations + +## Exercise Categories + +### 1. Chess +- Lichess OAuth integration for puzzle streams (`/api/puzzle/next`) and Stockfish bot challenges (`/api/challenge/stockfish`) +- Chess.com API (`api.chess.com/pub/player/{username}/stats`) for rating/history on profile +- Rendered with `react-chessboard` + `chess.js` for move validation +- XP: Base 20/puzzle, quality bonus 0-20 (puzzle rating vs. player rating). Games 30-60 based on result + opponent strength + +### 2. Deep Reading +- Distraction-free markdown reader, no copy-paste during session +- Timer with 5-minute minimum for XP eligibility +- On completion, Claude generates 3-5 comprehension questions (recall, inference, critical analysis) +- Content sources: seeded library, user-pasted URLs (fetched/cleaned), user-pasted raw text +- XP: Base 30/session, quality bonus 0-30 based on comprehension score + +### 3. Feynman Challenges +- Claude picks a topic (random or user-selected domain) or user picks from a list +- User writes explanation in text area, no outside resources, optional timer +- Claude scores: accuracy (0-10), completeness (0-10), clarity (0-10) +- Returns score + specific knowledge gaps identified +- XP: Base 40/challenge, quality bonus 0-40 based on average score + +### 4. Logic Puzzles +- Procedurally generated: Sudoku, number sequences, constraint grids, pattern matching +- Difficulty scaling unlockable via skill tree (easy -> medium -> hard -> expert) +- Deterministic validation, no Claude needed +- XP: Base 15-40 scaled by difficulty, quality bonus for speed (under par time) + +### 5. Critical Thinking (3 exercise types, progressively unlocked) + +| Exercise | What You Do | Claude Evaluates | +|---|---|---| +| Flaw Finder (L1) | Identify logical fallacies and weak reasoning in a passage | Detection accuracy, correct identification, false positive rate | +| Steelman (L5) | Construct the strongest version of a position you disagree with | Charitable interpretation, logical coherence, kernel of truth | +| Devil's Advocate (L10) | Argue against a position you agree with | Argument strength, evidence quality, intellectual honesty | + +- Flaw Finder content: Claude-generated passages with seeded fallacies (known answer key) or real op-eds from content library +- XP: Base 50 for all three (hardest category), quality bonus 0-30 based on scores + +### 6. Skill Quests +- 5-10 minute micro-lessons in unfamiliar domains (language, music theory, mental math, etc.) +- Claude-generated lesson content + practice exercises +- Spaced repetition for previously covered material +- XP: Base 25/lesson, quality bonus 0-25 based on practice accuracy + +## Data Model + +```prisma +model User { + id Int @id @default(autoincrement()) + name String + level Int @default(1) + totalXp Int @default(0) + currentXp Int @default(0) + xpToNextLevel Int @default(100) + title String @default("Smooth Brain") + dailyGoalXp Int @default(100) + streak Int @default(0) + longestStreak Int @default(0) + streakFreezes Int @default(0) + lichessUsername String? + chesscomUsername String? + createdAt DateTime @default(now()) + + activities Activity[] + dailyLogs DailyLog[] + categorySkills CategorySkill[] + unlocks Unlock[] +} + +model CategorySkill { + id Int @id @default(autoincrement()) + userId Int + category String // chess, reading, feynman, logic, critical-thinking, quests + level Int @default(1) + totalXp Int @default(0) + currentXp Int @default(0) + xpToNext Int @default(100) + + user User @relation(fields: [userId], references: [id]) + @@unique([userId, category]) +} + +model Activity { + id Int @id @default(autoincrement()) + userId Int + category String + exerciseType String // e.g., "puzzle", "bullet-game", "comprehension", "explain" + description String + baseXp Int + qualityBonus Int @default(0) + isCriticalHit Boolean @default(false) + totalXp Int + score Float? // 0-1 quality score + durationSecs Int? + metadata String? // JSON blob for exercise-specific data + createdAt DateTime @default(now()) + + user User @relation(fields: [userId], references: [id]) +} + +model DailyLog { + id Int @id @default(autoincrement()) + userId Int + date DateTime + xpEarned Int @default(0) + activityCount Int @default(0) + goalMet Boolean @default(false) + streakFreezeUsed Boolean @default(false) + + user User @relation(fields: [userId], references: [id]) + @@unique([userId, date]) +} + +model SkillTreeNode { + id Int @id @default(autoincrement()) + category String + name String + description String + levelRequired Int + parentNodeId Int? + nodeType String // "difficulty", "exercise-type", "cosmetic", "multiplier", "streak-shield" + + parent SkillTreeNode? @relation("NodeTree", fields: [parentNodeId], references: [id]) + children SkillTreeNode[] @relation("NodeTree") + unlocks Unlock[] + + @@unique([category, name]) +} + +model Unlock { + id Int @id @default(autoincrement()) + userId Int + nodeId Int + unlockedAt DateTime @default(now()) + + user User @relation(fields: [userId], references: [id]) + node SkillTreeNode @relation(fields: [nodeId], references: [id]) + @@unique([userId, nodeId]) +} + +model ContentItem { + id Int @id @default(autoincrement()) + category String // reading, quests + title String + content String // markdown body or URL + difficulty String // beginner, intermediate, advanced + domain String // science, philosophy, history, tech, etc. + source String // "seeded", "user", "generated" + metadata String? // JSON blob + createdAt DateTime @default(now()) +} +``` + +## Progression System + +### Hybrid Model +- **Duolingo backbone:** daily XP goals (configurable 50/100/150), streaks, streak freezes +- **RPG depth:** per-category skill levels (1-100), skill trees with unlockable nodes, titles + +### XP Mechanics +- Completion-based with quality bonuses +- Critical hits: random 2x XP chance on any activity +- XP multiplier nodes in skill trees (+10% at L15, +25% at L30) + +### XP Scaling (exponential curve) + +| Level | Total XP Required | XP for This Level | +|---|---|---| +| 1->2 | 100 | 100 | +| 5->6 | 800 | 200 | +| 10->11 | 2,500 | 350 | +| 20->21 | 8,000 | 600 | +| 50->51 | 50,000 | 1,500 | +| 100 | 200,000 | -- | + +### Skill Tree Structure (per category, ~8-12 nodes each) + +``` +Level 1: [Root] -- unlocked by default +Level 5: [Branch A] -- [Branch B] +Level 10: [A1] -- [A2] -- [B1] -- [B2] +Level 20: [Advanced nodes...] +Level 50: [Mastery node] -- cosmetic title +``` + +Node types: difficulty unlocks, exercise variants, XP multipliers, streak shields, cosmetic titles. + +### Critical Thinking tree (exercise-gated) + +``` +L1: [Flaw Finder: Easy] +L3: [Flaw Finder: Medium] +L5: [Steelman: Unlocked] -- [Flaw Finder: Hard] +L10: [Devil's Advocate: Unlocked] -- [Steelman: Medium] -- [+10% XP] +L15: [Flaw Finder: Expert] -- [Streak Shield] +L20: [Steelman: Hard] -- [Devil's Advocate: Medium] +L30: [Devil's Advocate: Hard] -- [+25% XP] +L50: [Mastery: "Steel Trap"] +``` + +## UI Design + +### Routes +- `/` — Dashboard (daily ring, streak, category cards, activity feed, weekly heatmap) +- `/chess` — Lichess puzzles + bot play +- `/reading` — Deep reading sessions +- `/feynman` — Feynman challenges +- `/logic` — Logic puzzles +- `/critical-thinking` — Flaw Finder, Steelman, Devil's Advocate +- `/quests` — Skill Quests +- `/profile` — Character level, all skill trees, chess.com stats, achievements + +### Visual Direction +- Dark mode default with subtle gradients +- Glassmorphism cards with backdrop blur +- Framer-motion animations on XP gains, level-ups, unlocks +- Monospace accents for stats/numbers (terminal aesthetic) +- Category color palette: + - Chess: amber + - Reading: emerald + - Feynman: cyan + - Logic: violet + - Critical Thinking: rose + - Skill Quests: orange +- Deep navy/charcoal base + +### Key Components +- Daily ring: circular progress toward XP goal (Apple Watch style) +- Streak counter with flame icon +- Category cards: level, XP bar, quick-start button +- Skill tree visualizer: node graph, locked=greyed, unlocked=glow +- Exercise results panel: slides in after completion, shows XP breakdown +- Distraction-free mode: full-screen for reading and writing exercises + +## Architecture + +``` +rotnot/ +├── prisma/schema.prisma +├── src/ +│ ├── app/ +│ │ ├── page.tsx # Dashboard +│ │ ├── chess/ +│ │ ├── reading/ +│ │ ├── feynman/ +│ │ ├── logic/ +│ │ ├── critical-thinking/ +│ │ ├── quests/ +│ │ ├── profile/ +│ │ └── api/ # Route handlers +│ ├── components/ # shadcn/ui + custom +│ ├── lib/ # Prisma, Claude, Lichess, Chess.com clients +│ ├── config/ # XP tables, skill trees, seeded content +│ └── types/ +├── content/ # Seeded reading articles + quest lessons (markdown) +└── public/ +``` + +### Data Flow +User completes exercise -> API route scores it (Claude for text, deterministic for puzzles/chess) -> XP calculated (base + quality bonus + critical hit roll) -> Category skill + overall level updated -> Streak/daily goal checked -> Response with XP earned + any unlocks + +### External Integrations +- Lichess API (OAuth): puzzle streams, game creation, bot play +- Chess.com public API (no auth): player stats, rating history +- Anthropic SDK: Feynman scoring, reading comprehension generation, Critical Thinking evaluation + +## Claude Integration (MVP) + +**Evaluator role only** for v1. Claude scores submissions and generates content. No coaching or adaptive feedback. + +Data model supports coach features in v2 (activity history, score trends, metadata for personalization). + +## Future Considerations (not in MVP) +- Active coach mode (Claude provides feedback, adapts difficulty, brain health reports) +- Multi-user auth (model supports it, no auth system in v1) +- Postgres migration for production deployment +- Mobile-responsive PWA +- Social features (leaderboards, challenges) diff --git a/docs/plans/2026-03-05-rotnot-implementation.md b/docs/plans/2026-03-05-rotnot-implementation.md new file mode 100644 index 0000000000000000000000000000000000000000..514dd10cacb2e88b1691ac2979b2642c742992be --- /dev/null +++ b/docs/plans/2026-03-05-rotnot-implementation.md @@ -0,0 +1,1485 @@ +# RotNot Implementation Plan + +> **For Claude:** REQUIRED SUB-SKILL: Use superpowers:executing-plans to implement this plan task-by-task. + +**Goal:** Build a gamified cognitive exercise web app with 6 categories, RPG progression, and streak-based retention. + +**Architecture:** Next.js 16 app with Prisma + SQLite, Anthropic SDK for text exercise scoring, Lichess API for chess, Chess.com API for stats. Server components for data fetching, client components for interactivity. All XP/progression logic in shared `src/lib/xp.ts` module. + +**Tech Stack:** Next.js 16, TypeScript, Tailwind CSS 4, shadcn/ui (new-york style), Prisma 7 + SQLite, Anthropic SDK, Lichess API, Chess.com API, Framer Motion, Vitest + +**Reference:** Borrow patterns from `~/Documents/job-quest` for scaffolding, Prisma config, shadcn setup, and XP table structure. Do NOT copy-paste wholesale — RotNot has a more modern UI direction (glassmorphism, gradients, category colors). + +--- + +## Phase 1: Project Scaffolding + +### Task 1.1: Initialize Next.js project + +**Files:** +- Create: `rotnot/package.json` (via CLI) +- Create: `rotnot/tsconfig.json` (via CLI) + +**Step 1: Create Next.js app** + +```bash +cd /Users/nicholaspate/Documents/01_Active +npx create-next-app@latest rotnot --typescript --tailwind --eslint --app --src-dir --import-alias "@/*" --turbopack +``` + +Note: This will overwrite the existing `rotnot/` dir. Move `docs/` out first, then back in after. + +```bash +mv rotnot/docs /tmp/rotnot-docs +# run create-next-app +mv /tmp/rotnot-docs rotnot/docs +``` + +**Step 2: Verify it runs** + +```bash +cd rotnot && npm run dev +# Visit http://localhost:3000, expect Next.js welcome page +``` + +**Step 3: Commit** + +```bash +git add -A && git commit -m "feat: initialize Next.js 16 project" +``` + +### Task 1.2: Install dependencies + +**Step 1: Install production deps** + +```bash +npm install @anthropic-ai/sdk @prisma/client @prisma/adapter-better-sqlite3 better-sqlite3 framer-motion lucide-react radix-ui class-variance-authority clsx chess.js react-chessboard recharts +``` + +**Step 2: Install dev deps** + +```bash +npm install -D prisma vitest @types/better-sqlite3 tw-animate-css +``` + +**Step 3: Commit** + +```bash +git add package.json package-lock.json && git commit -m "feat: install core dependencies" +``` + +### Task 1.3: Configure shadcn/ui + +**Files:** +- Create: `components.json` + +**Step 1: Initialize shadcn** + +```bash +npx shadcn@latest init -d +``` + +Select: new-york style, neutral base, CSS variables, lucide icons. + +**Step 2: Install initial components** + +```bash +npx shadcn@latest add button card badge separator tooltip dialog input textarea select label progress tabs +``` + +**Step 3: Commit** + +```bash +git add -A && git commit -m "feat: configure shadcn/ui with initial components" +``` + +### Task 1.4: Configure Prisma + +**Files:** +- Create: `prisma/schema.prisma` +- Create: `prisma.config.ts` +- Create: `.env.example` +- Create: `.env` + +**Step 1: Initialize Prisma** + +```bash +npx prisma init --datasource-provider sqlite --generator-provider prisma-client-js +``` + +**Step 2: Create `.env.example`** + +``` +DATABASE_URL="file:./dev.db" +ANTHROPIC_API_KEY="" +LICHESS_TOKEN="" +CHESSCOM_USERNAME="" +``` + +**Step 3: Create `.env`** (same but with real values) + +**Step 4: Create `prisma.config.ts`** (borrow from job-quest) + +```typescript +import "dotenv/config"; +import { defineConfig } from "prisma/config"; + +export default defineConfig({ + schema: "prisma/schema.prisma", + migrations: { + path: "prisma/migrations", + seed: "npx tsx prisma/seed.ts", + }, + datasource: { + url: process.env["DATABASE_URL"], + }, +}); +``` + +**Step 5: Commit** + +```bash +git add prisma.config.ts .env.example prisma/ && git commit -m "feat: configure Prisma with SQLite" +``` + +### Task 1.5: Configure Vitest + +**Files:** +- Create: `vitest.config.ts` + +**Step 1: Write vitest config** + +```typescript +import { defineConfig } from "vitest/config"; +import path from "path"; + +export default defineConfig({ + test: { + globals: true, + environment: "node", + include: ["src/**/*.test.ts"], + }, + resolve: { + alias: { + "@": path.resolve(__dirname, "./src"), + }, + }, +}); +``` + +**Step 2: Add test scripts to package.json** + +Add to `scripts`: +```json +"test": "vitest run", +"test:watch": "vitest" +``` + +**Step 3: Commit** + +```bash +git add vitest.config.ts package.json && git commit -m "feat: configure Vitest" +``` + +### Task 1.6: Set up .gitignore and project config + +**Files:** +- Modify: `.gitignore` + +**Step 1: Update .gitignore** (borrow from job-quest, add rotnot-specific entries) + +``` +# database +*.db +*.db-journal + +# generated +src/generated/ + +# dependencies +/node_modules + +# testing +/coverage + +# next.js +/.next/ +/out/ + +# production +/build + +# misc +.DS_Store +*.pem + +# debug +npm-debug.log* + +# env files +.env* +!.env.example + +# vercel +.vercel + +# typescript +*.tsbuildinfo +next-env.d.ts +``` + +**Step 2: Commit** + +```bash +git add .gitignore && git commit -m "chore: configure .gitignore" +``` + +--- + +## Phase 2: Database Schema & Seed Data + +### Task 2.1: Write Prisma schema + +**Files:** +- Modify: `prisma/schema.prisma` + +**Step 1: Write the full schema** + +```prisma +generator client { + provider = "prisma-client-js" +} + +datasource db { + provider = "sqlite" +} + +model User { + id Int @id @default(autoincrement()) + name String + level Int @default(1) + totalXp Int @default(0) + currentXp Int @default(0) + xpToNextLevel Int @default(100) + title String @default("Smooth Brain") + dailyGoalXp Int @default(100) + streak Int @default(0) + longestStreak Int @default(0) + streakFreezes Int @default(0) + lichessUsername String? + chesscomUsername String? + createdAt DateTime @default(now()) + + activities Activity[] + dailyLogs DailyLog[] + categorySkills CategorySkill[] + unlocks Unlock[] +} + +model CategorySkill { + id Int @id @default(autoincrement()) + userId Int + category String + level Int @default(1) + totalXp Int @default(0) + currentXp Int @default(0) + xpToNext Int @default(100) + + user User @relation(fields: [userId], references: [id]) + @@unique([userId, category]) +} + +model Activity { + id Int @id @default(autoincrement()) + userId Int + category String + exerciseType String + description String + baseXp Int + qualityBonus Int @default(0) + isCriticalHit Boolean @default(false) + totalXp Int + score Float? + durationSecs Int? + metadata String? + createdAt DateTime @default(now()) + + user User @relation(fields: [userId], references: [id]) +} + +model DailyLog { + id Int @id @default(autoincrement()) + userId Int + date DateTime + xpEarned Int @default(0) + activityCount Int @default(0) + goalMet Boolean @default(false) + streakFreezeUsed Boolean @default(false) + + user User @relation(fields: [userId], references: [id]) + @@unique([userId, date]) +} + +model SkillTreeNode { + id Int @id @default(autoincrement()) + category String + name String + description String + levelRequired Int + parentNodeId Int? + nodeType String + + parent SkillTreeNode? @relation("NodeTree", fields: [parentNodeId], references: [id]) + children SkillTreeNode[] @relation("NodeTree") + unlocks Unlock[] + + @@unique([category, name]) +} + +model Unlock { + id Int @id @default(autoincrement()) + userId Int + nodeId Int + unlockedAt DateTime @default(now()) + + user User @relation(fields: [userId], references: [id]) + node SkillTreeNode @relation(fields: [nodeId], references: [id]) + @@unique([userId, nodeId]) +} + +model ContentItem { + id Int @id @default(autoincrement()) + category String + title String + content String + difficulty String + domain String + source String + metadata String? + createdAt DateTime @default(now()) +} +``` + +**Step 2: Generate migration and client** + +```bash +npx prisma migrate dev --name init +``` + +**Step 3: Commit** + +```bash +git add prisma/ && git commit -m "feat: add full database schema with migration" +``` + +### Task 2.2: Create Prisma client singleton + +**Files:** +- Create: `src/lib/db.ts` + +**Step 1: Write the client** + +```typescript +import { PrismaClient } from "@prisma/client"; + +const globalForPrisma = globalThis as unknown as { prisma: PrismaClient }; + +export const prisma = globalForPrisma.prisma || new PrismaClient(); + +if (process.env.NODE_ENV !== "production") globalForPrisma.prisma = prisma; +``` + +**Step 2: Commit** + +```bash +git add src/lib/db.ts && git commit -m "feat: add Prisma client singleton" +``` + +### Task 2.3: Create seed script + +**Files:** +- Create: `prisma/seed.ts` + +**Step 1: Write seed with default user, category skills, and skill tree nodes** + +```typescript +import { PrismaClient } from "@prisma/client"; + +const prisma = new PrismaClient(); + +const CATEGORIES = ["chess", "reading", "feynman", "logic", "critical-thinking", "quests"] as const; + +const SKILL_TREE_NODES = [ + // Chess + { category: "chess", name: "Chess Initiate", description: "Begin your chess journey", levelRequired: 1, nodeType: "difficulty", parentNodeId: null }, + { category: "chess", name: "Puzzle Warrior", description: "Unlock 1200+ rated puzzles", levelRequired: 5, nodeType: "difficulty", parentNodeId: 1 }, + { category: "chess", name: "Endgame Student", description: "Unlock endgame puzzles", levelRequired: 5, nodeType: "exercise-type", parentNodeId: 1 }, + { category: "chess", name: "Tactical Eye", description: "+10% Chess XP", levelRequired: 15, nodeType: "multiplier", parentNodeId: 2 }, + { category: "chess", name: "Puzzle Master", description: "Unlock 1800+ rated puzzles", levelRequired: 20, nodeType: "difficulty", parentNodeId: 2 }, + { category: "chess", name: "Streak Shield I", description: "Earn 1 streak freeze", levelRequired: 10, nodeType: "streak-shield", parentNodeId: 3 }, + { category: "chess", name: "Grandmaster's Path", description: "+25% Chess XP", levelRequired: 30, nodeType: "multiplier", parentNodeId: 5 }, + { category: "chess", name: "Grandthinker", description: "Chess mastery title", levelRequired: 50, nodeType: "cosmetic", parentNodeId: 7 }, + + // Reading + { category: "reading", name: "Page Turner", description: "Begin reading exercises", levelRequired: 1, nodeType: "difficulty", parentNodeId: null }, + { category: "reading", name: "Deep Diver", description: "Unlock intermediate articles", levelRequired: 5, nodeType: "difficulty", parentNodeId: 9 }, + { category: "reading", name: "Speed Reader", description: "Unlock timed reading challenges", levelRequired: 5, nodeType: "exercise-type", parentNodeId: 9 }, + { category: "reading", name: "Scholar", description: "Unlock advanced/academic content", levelRequired: 10, nodeType: "difficulty", parentNodeId: 10 }, + { category: "reading", name: "Focus Boost", description: "+10% Reading XP", levelRequired: 15, nodeType: "multiplier", parentNodeId: 12 }, + { category: "reading", name: "Streak Shield I", description: "Earn 1 streak freeze", levelRequired: 10, nodeType: "streak-shield", parentNodeId: 11 }, + { category: "reading", name: "Concentration Master", description: "+25% Reading XP", levelRequired: 30, nodeType: "multiplier", parentNodeId: 13 }, + { category: "reading", name: "Deep Diver", description: "Reading mastery title", levelRequired: 50, nodeType: "cosmetic", parentNodeId: 15 }, + + // Feynman + { category: "feynman", name: "Curious Mind", description: "Begin Feynman challenges", levelRequired: 1, nodeType: "difficulty", parentNodeId: null }, + { category: "feynman", name: "Explainer", description: "Unlock intermediate topics", levelRequired: 5, nodeType: "difficulty", parentNodeId: 17 }, + { category: "feynman", name: "Timed Explains", description: "Unlock timed mode", levelRequired: 5, nodeType: "exercise-type", parentNodeId: 17 }, + { category: "feynman", name: "Professor", description: "Unlock expert topics", levelRequired: 15, nodeType: "difficulty", parentNodeId: 18 }, + { category: "feynman", name: "Clarity Boost", description: "+10% Feynman XP", levelRequired: 15, nodeType: "multiplier", parentNodeId: 19 }, + { category: "feynman", name: "Streak Shield I", description: "Earn 1 streak freeze", levelRequired: 10, nodeType: "streak-shield", parentNodeId: 18 }, + { category: "feynman", name: "Mastery Boost", description: "+25% Feynman XP", levelRequired: 30, nodeType: "multiplier", parentNodeId: 20 }, + { category: "feynman", name: "The Explainer", description: "Feynman mastery title", levelRequired: 50, nodeType: "cosmetic", parentNodeId: 23 }, + + // Logic + { category: "logic", name: "Logical Mind", description: "Begin logic puzzles", levelRequired: 1, nodeType: "difficulty", parentNodeId: null }, + { category: "logic", name: "Medium Puzzles", description: "Unlock medium difficulty", levelRequired: 5, nodeType: "difficulty", parentNodeId: 25 }, + { category: "logic", name: "Sequence Master", description: "Unlock number sequences", levelRequired: 5, nodeType: "exercise-type", parentNodeId: 25 }, + { category: "logic", name: "Hard Puzzles", description: "Unlock hard difficulty", levelRequired: 10, nodeType: "difficulty", parentNodeId: 26 }, + { category: "logic", name: "Logic Boost", description: "+10% Logic XP", levelRequired: 15, nodeType: "multiplier", parentNodeId: 27 }, + { category: "logic", name: "Expert Puzzles", description: "Unlock expert difficulty", levelRequired: 20, nodeType: "difficulty", parentNodeId: 28 }, + { category: "logic", name: "Streak Shield I", description: "Earn 1 streak freeze", levelRequired: 10, nodeType: "streak-shield", parentNodeId: 28 }, + { category: "logic", name: "Mastery Boost", description: "+25% Logic XP", levelRequired: 30, nodeType: "multiplier", parentNodeId: 30 }, + { category: "logic", name: "Vulcan", description: "Logic mastery title", levelRequired: 50, nodeType: "cosmetic", parentNodeId: 32 }, + + // Critical Thinking + { category: "critical-thinking", name: "Flaw Finder: Easy", description: "Identify basic logical fallacies", levelRequired: 1, nodeType: "difficulty", parentNodeId: null }, + { category: "critical-thinking", name: "Flaw Finder: Medium", description: "Harder fallacy detection", levelRequired: 3, nodeType: "difficulty", parentNodeId: 34 }, + { category: "critical-thinking", name: "Steelman: Unlocked", description: "Construct strongest opposing arguments", levelRequired: 5, nodeType: "exercise-type", parentNodeId: 35 }, + { category: "critical-thinking", name: "Flaw Finder: Hard", description: "Subtle fallacies and weak reasoning", levelRequired: 5, nodeType: "difficulty", parentNodeId: 35 }, + { category: "critical-thinking", name: "Devil's Advocate: Unlocked", description: "Argue against your own positions", levelRequired: 10, nodeType: "exercise-type", parentNodeId: 36 }, + { category: "critical-thinking", name: "Steelman: Medium", description: "More nuanced positions", levelRequired: 10, nodeType: "difficulty", parentNodeId: 36 }, + { category: "critical-thinking", name: "Critical Boost", description: "+10% Critical Thinking XP", levelRequired: 10, nodeType: "multiplier", parentNodeId: 39 }, + { category: "critical-thinking", name: "Flaw Finder: Expert", description: "Professional-level analysis", levelRequired: 15, nodeType: "difficulty", parentNodeId: 37 }, + { category: "critical-thinking", name: "Streak Shield I", description: "Earn 1 streak freeze", levelRequired: 15, nodeType: "streak-shield", parentNodeId: 41 }, + { category: "critical-thinking", name: "Steelman: Hard", description: "Complex multi-faceted positions", levelRequired: 20, nodeType: "difficulty", parentNodeId: 39 }, + { category: "critical-thinking", name: "Devil's Advocate: Medium", description: "Harder positions to argue against", levelRequired: 20, nodeType: "difficulty", parentNodeId: 38 }, + { category: "critical-thinking", name: "Devil's Advocate: Hard", description: "Expert-level contrarian arguments", levelRequired: 30, nodeType: "difficulty", parentNodeId: 44 }, + { category: "critical-thinking", name: "Mastery Boost", description: "+25% Critical Thinking XP", levelRequired: 30, nodeType: "multiplier", parentNodeId: 45 }, + { category: "critical-thinking", name: "Steel Trap", description: "Critical Thinking mastery title", levelRequired: 50, nodeType: "cosmetic", parentNodeId: 46 }, + + // Skill Quests + { category: "quests", name: "Apprentice", description: "Begin skill quests", levelRequired: 1, nodeType: "difficulty", parentNodeId: null }, + { category: "quests", name: "Intermediate Quests", description: "Unlock intermediate lessons", levelRequired: 5, nodeType: "difficulty", parentNodeId: 48 }, + { category: "quests", name: "Spaced Repetition", description: "Unlock review sessions", levelRequired: 5, nodeType: "exercise-type", parentNodeId: 48 }, + { category: "quests", name: "Advanced Quests", description: "Unlock advanced lessons", levelRequired: 15, nodeType: "difficulty", parentNodeId: 49 }, + { category: "quests", name: "Quest Boost", description: "+10% Quest XP", levelRequired: 15, nodeType: "multiplier", parentNodeId: 50 }, + { category: "quests", name: "Streak Shield I", description: "Earn 1 streak freeze", levelRequired: 10, nodeType: "streak-shield", parentNodeId: 50 }, + { category: "quests", name: "Mastery Boost", description: "+25% Quest XP", levelRequired: 30, nodeType: "multiplier", parentNodeId: 51 }, + { category: "quests", name: "Polymath", description: "Skill Quests mastery title", levelRequired: 50, nodeType: "cosmetic", parentNodeId: 54 }, +]; + +async function main() { + // Create default user + const user = await prisma.user.upsert({ + where: { id: 1 }, + update: {}, + create: { name: "Player One" }, + }); + + // Create category skills + for (const category of CATEGORIES) { + await prisma.categorySkill.upsert({ + where: { userId_category: { userId: user.id, category } }, + update: {}, + create: { userId: user.id, category }, + }); + } + + // Create skill tree nodes (without parent references first, then update) + for (const node of SKILL_TREE_NODES) { + await prisma.skillTreeNode.upsert({ + where: { category_name: { category: node.category, name: node.name } }, + update: {}, + create: { + category: node.category, + name: node.name, + description: node.description, + levelRequired: node.levelRequired, + nodeType: node.nodeType, + parentNodeId: node.parentNodeId, + }, + }); + } + + console.log("Seed complete."); +} + +main() + .catch((e) => { console.error(e); process.exit(1); }) + .finally(async () => { await prisma.$disconnect(); }); +``` + +**Step 2: Run seed** + +```bash +npx prisma db seed +``` + +**Step 3: Commit** + +```bash +git add prisma/seed.ts && git commit -m "feat: add seed script with user, skills, and skill tree" +``` + +--- + +## Phase 3: XP & Progression Engine + +### Task 3.1: Write XP config + +**Files:** +- Create: `src/config/xp.ts` + +**Step 1: Write the failing test** + +Create `src/config/__tests__/xp.test.ts`: + +```typescript +import { xpForLevel, EXERCISE_XP, CRITICAL_HIT_CHANCE, CRITICAL_HIT_MULTIPLIER, CATEGORIES } from "@/config/xp"; + +describe("xpForLevel", () => { + it("returns 100 for level 2", () => { + expect(xpForLevel(2)).toBe(100); + }); + it("scales exponentially", () => { + expect(xpForLevel(10)).toBeGreaterThan(xpForLevel(5)); + }); + it("returns approximately 1500 at level 50", () => { + const xp = xpForLevel(50); + expect(xp).toBeGreaterThanOrEqual(1200); + expect(xp).toBeLessThanOrEqual(1800); + }); +}); + +describe("EXERCISE_XP", () => { + it("has entries for all categories", () => { + for (const cat of CATEGORIES) { + expect(EXERCISE_XP[cat]).toBeDefined(); + expect(EXERCISE_XP[cat].baseXp).toBeGreaterThan(0); + expect(EXERCISE_XP[cat].maxQualityBonus).toBeGreaterThanOrEqual(0); + } + }); +}); + +describe("critical hit", () => { + it("has 10% chance and 2x multiplier", () => { + expect(CRITICAL_HIT_CHANCE).toBe(0.1); + expect(CRITICAL_HIT_MULTIPLIER).toBe(2); + }); +}); +``` + +**Step 2: Run test to verify it fails** + +```bash +npm test -- src/config/__tests__/xp.test.ts +``` + +Expected: FAIL — module not found. + +**Step 3: Write implementation** + +```typescript +export const CATEGORIES = [ + "chess", + "reading", + "feynman", + "logic", + "critical-thinking", + "quests", +] as const; + +export type Category = (typeof CATEGORIES)[number]; + +export const CATEGORY_LABELS: Record = { + chess: "Chess", + reading: "Deep Reading", + feynman: "Feynman", + logic: "Logic Puzzles", + "critical-thinking": "Critical Thinking", + quests: "Skill Quests", +}; + +export const CATEGORY_COLORS: Record = { + chess: "#f59e0b", // amber + reading: "#10b981", // emerald + feynman: "#06b6d4", // cyan + logic: "#8b5cf6", // violet + "critical-thinking": "#f43f5e", // rose + quests: "#f97316", // orange +}; + +export const EXERCISE_XP: Record = { + chess: { baseXp: 20, maxQualityBonus: 20 }, + reading: { baseXp: 30, maxQualityBonus: 30 }, + feynman: { baseXp: 40, maxQualityBonus: 40 }, + logic: { baseXp: 15, maxQualityBonus: 25 }, + "critical-thinking": { baseXp: 50, maxQualityBonus: 30 }, + quests: { baseXp: 25, maxQualityBonus: 25 }, +}; + +export const CRITICAL_HIT_CHANCE = 0.1; +export const CRITICAL_HIT_MULTIPLIER = 2; + +// Attempt-to-next-level XP curve: exponential scaling +// Level 2 = 100, Level 10 ~ 350, Level 50 ~ 1500 +export function xpForLevel(level: number): number { + return Math.round(100 * Math.pow(level / 2, 0.8)); +} + +// Cumulative XP to reach a given level +export function totalXpForLevel(level: number): number { + let total = 0; + for (let i = 2; i <= level; i++) { + total += xpForLevel(i); + } + return total; +} +``` + +**Step 4: Run tests** + +```bash +npm test -- src/config/__tests__/xp.test.ts +``` + +Expected: PASS + +**Step 5: Commit** + +```bash +git add src/config/xp.ts src/config/__tests__/xp.test.ts +git commit -m "feat: add XP config with level curve and exercise XP table" +``` + +### Task 3.2: Write XP calculation engine + +**Files:** +- Create: `src/lib/xp.ts` +- Create: `src/lib/__tests__/xp.test.ts` + +**Step 1: Write failing tests** + +```typescript +import { calculateXpGain, rollCriticalHit, calculateQualityBonus } from "@/lib/xp"; + +describe("calculateQualityBonus", () => { + it("returns 0 for score 0", () => { + expect(calculateQualityBonus(0, 30)).toBe(0); + }); + it("returns maxBonus for score 1", () => { + expect(calculateQualityBonus(1, 30)).toBe(30); + }); + it("returns proportional bonus", () => { + expect(calculateQualityBonus(0.5, 30)).toBe(15); + }); +}); + +describe("calculateXpGain", () => { + it("returns base + quality bonus without critical hit", () => { + const result = calculateXpGain({ + baseXp: 20, + qualityScore: 0.5, + maxQualityBonus: 20, + isCriticalHit: false, + multiplierPercent: 0, + }); + expect(result.baseXp).toBe(20); + expect(result.qualityBonus).toBe(10); + expect(result.totalXp).toBe(30); + }); + + it("doubles on critical hit", () => { + const result = calculateXpGain({ + baseXp: 20, + qualityScore: 0, + maxQualityBonus: 20, + isCriticalHit: true, + multiplierPercent: 0, + }); + expect(result.totalXp).toBe(40); + expect(result.isCriticalHit).toBe(true); + }); + + it("applies skill tree multiplier", () => { + const result = calculateXpGain({ + baseXp: 20, + qualityScore: 0, + maxQualityBonus: 20, + isCriticalHit: false, + multiplierPercent: 10, + }); + expect(result.totalXp).toBe(22); + }); +}); + +describe("rollCriticalHit", () => { + it("returns a boolean", () => { + expect(typeof rollCriticalHit()).toBe("boolean"); + }); +}); +``` + +**Step 2: Run test to verify fail** + +```bash +npm test -- src/lib/__tests__/xp.test.ts +``` + +**Step 3: Write implementation** + +```typescript +import { CRITICAL_HIT_CHANCE, CRITICAL_HIT_MULTIPLIER } from "@/config/xp"; + +export function calculateQualityBonus(score: number, maxBonus: number): number { + return Math.round(score * maxBonus); +} + +export function rollCriticalHit(): boolean { + return Math.random() < CRITICAL_HIT_CHANCE; +} + +export interface XpGainInput { + baseXp: number; + qualityScore: number; // 0-1 + maxQualityBonus: number; + isCriticalHit: boolean; + multiplierPercent: number; // from skill tree nodes, e.g. 10 = +10% +} + +export interface XpGainResult { + baseXp: number; + qualityBonus: number; + isCriticalHit: boolean; + multiplierBonus: number; + totalXp: number; +} + +export function calculateXpGain(input: XpGainInput): XpGainResult { + const qualityBonus = calculateQualityBonus(input.qualityScore, input.maxQualityBonus); + let subtotal = input.baseXp + qualityBonus; + + if (input.isCriticalHit) { + subtotal = subtotal * CRITICAL_HIT_MULTIPLIER; + } + + const multiplierBonus = Math.round(subtotal * (input.multiplierPercent / 100)); + const totalXp = subtotal + multiplierBonus; + + return { + baseXp: input.baseXp, + qualityBonus, + isCriticalHit: input.isCriticalHit, + multiplierBonus, + totalXp, + }; +} +``` + +**Step 4: Run tests** + +```bash +npm test -- src/lib/__tests__/xp.test.ts +``` + +Expected: PASS + +**Step 5: Commit** + +```bash +git add src/lib/xp.ts src/lib/__tests__/xp.test.ts +git commit -m "feat: add XP calculation engine with quality bonuses and critical hits" +``` + +### Task 3.3: Write progression service (level-up, streak, daily log) + +**Files:** +- Create: `src/lib/progression.ts` +- Create: `src/lib/__tests__/progression.test.ts` + +**Step 1: Write failing tests** + +```typescript +import { checkLevelUp, shouldStreakBreak } from "@/lib/progression"; + +describe("checkLevelUp", () => { + it("returns no level up when xp insufficient", () => { + const result = checkLevelUp({ currentXp: 50, xpToNextLevel: 100, level: 1 }); + expect(result.levelsGained).toBe(0); + expect(result.newLevel).toBe(1); + }); + + it("returns level up when xp exceeds threshold", () => { + const result = checkLevelUp({ currentXp: 150, xpToNextLevel: 100, level: 1 }); + expect(result.levelsGained).toBe(1); + expect(result.newLevel).toBe(2); + expect(result.remainingXp).toBeLessThan(result.newXpToNextLevel); + }); + + it("handles multi-level jumps", () => { + const result = checkLevelUp({ currentXp: 500, xpToNextLevel: 100, level: 1 }); + expect(result.levelsGained).toBeGreaterThan(1); + }); +}); + +describe("shouldStreakBreak", () => { + it("returns false if goal was met today", () => { + expect(shouldStreakBreak({ goalMet: true, hasStreakFreeze: false })).toBe(false); + }); + + it("returns false if streak freeze available and goal not met", () => { + expect(shouldStreakBreak({ goalMet: false, hasStreakFreeze: true })).toBe(false); + }); + + it("returns true if goal not met and no freeze", () => { + expect(shouldStreakBreak({ goalMet: false, hasStreakFreeze: false })).toBe(true); + }); +}); +``` + +**Step 2: Run test to verify fail** + +```bash +npm test -- src/lib/__tests__/progression.test.ts +``` + +**Step 3: Write implementation** + +```typescript +import { xpForLevel } from "@/config/xp"; + +interface LevelUpInput { + currentXp: number; + xpToNextLevel: number; + level: number; +} + +interface LevelUpResult { + levelsGained: number; + newLevel: number; + remainingXp: number; + newXpToNextLevel: number; +} + +export function checkLevelUp(input: LevelUpInput): LevelUpResult { + let { currentXp, level } = input; + let xpToNext = input.xpToNextLevel; + let levelsGained = 0; + + while (currentXp >= xpToNext) { + currentXp -= xpToNext; + level++; + levelsGained++; + xpToNext = xpForLevel(level + 1); + } + + return { + levelsGained, + newLevel: level, + remainingXp: currentXp, + newXpToNextLevel: xpToNext, + }; +} + +interface StreakInput { + goalMet: boolean; + hasStreakFreeze: boolean; +} + +export function shouldStreakBreak(input: StreakInput): boolean { + if (input.goalMet) return false; + if (input.hasStreakFreeze) return false; + return true; +} +``` + +**Step 4: Run tests** + +```bash +npm test -- src/lib/__tests__/progression.test.ts +``` + +Expected: PASS + +**Step 5: Commit** + +```bash +git add src/lib/progression.ts src/lib/__tests__/progression.test.ts +git commit -m "feat: add progression engine with level-up and streak logic" +``` + +--- + +## Phase 4: Global Layout & Theme + +### Task 4.1: Create globals.css with RotNot theme + +**Files:** +- Modify: `src/app/globals.css` + +**Step 1: Write dark theme with category colors and glassmorphism utilities** + +Use job-quest's structure as base but with RotNot's navy/charcoal palette, category accent colors, and glassmorphism CSS utilities. Key differences from job-quest: +- Base surface colors shifted to navy (`#0a0e1a`, `#111827`, `#1a2035`, `#232d45`) +- Category colors as CSS vars: `--color-chess`, `--color-reading`, etc. +- Glassmorphism utility class `.glass` with `backdrop-filter: blur(12px)` and semi-transparent backgrounds +- Monospace font var for stats display + +**Step 2: Commit** + +```bash +git add src/app/globals.css && git commit -m "feat: add RotNot dark theme with category colors and glassmorphism" +``` + +### Task 4.2: Create sidebar navigation + +**Files:** +- Create: `src/components/sidebar-nav.tsx` + +**Step 1: Build sidebar** with links to all routes (`/`, `/chess`, `/reading`, `/feynman`, `/logic`, `/critical-thinking`, `/quests`, `/profile`). Each link shows category icon (from lucide-react) and label, highlighted with category color when active. Use `usePathname()` for active state. + +**Step 2: Commit** + +```bash +git add src/components/sidebar-nav.tsx && git commit -m "feat: add sidebar navigation with category icons" +``` + +### Task 4.3: Create root layout + +**Files:** +- Modify: `src/app/layout.tsx` + +**Step 1: Write layout** with dark mode, Inter + JetBrains Mono fonts, sidebar, and main content area. Borrow structure from job-quest but use RotNot theme. + +```typescript +import type { Metadata } from "next"; +import { Inter, JetBrains_Mono } from "next/font/google"; +import "./globals.css"; +import { SidebarNav } from "@/components/sidebar-nav"; + +const inter = Inter({ subsets: ["latin"], variable: "--font-inter" }); +const jetbrains = JetBrains_Mono({ subsets: ["latin"], variable: "--font-mono" }); + +export const metadata: Metadata = { + title: "RotNot", + description: "Fight brain rot. Level up your mind.", +}; + +export default function RootLayout({ children }: { children: React.ReactNode }) { + return ( + + +
+ +
+ {children} +
+
+ + + ); +} +``` + +**Step 2: Commit** + +```bash +git add src/app/layout.tsx && git commit -m "feat: add root layout with sidebar and fonts" +``` + +--- + +## Phase 5: Dashboard + +### Task 5.1: Create dashboard data fetching + +**Files:** +- Create: `src/app/api/dashboard/route.ts` + +**Step 1: Build GET handler** that returns: user stats (level, xp, streak, title), today's daily log (xp earned, goal progress), category skills (all 6 with levels), and recent activities (last 10). + +**Step 2: Commit** + +### Task 5.2: Create daily ring component + +**Files:** +- Create: `src/components/dashboard/daily-ring.tsx` + +**Step 1: Build circular SVG progress ring** showing XP earned today vs. daily goal. Animate with framer-motion. Show percentage and raw numbers inside the ring. Use glassmorphism card wrapper. + +**Step 2: Commit** + +### Task 5.3: Create streak display component + +**Files:** +- Create: `src/components/dashboard/streak-display.tsx` + +**Step 1: Build streak counter** with flame icon, current streak number, longest streak, and streak freeze count. Pulsing animation when streak is active. + +**Step 2: Commit** + +### Task 5.4: Create category cards grid + +**Files:** +- Create: `src/components/dashboard/category-card.tsx` + +**Step 1: Build category card** showing: category icon + label, current level, XP progress bar (colored by category), and "Start" button linking to exercise page. Grid of 6 cards on dashboard. + +**Step 2: Commit** + +### Task 5.5: Create activity feed + +**Files:** +- Create: `src/components/dashboard/activity-feed.tsx` + +**Step 1: Build scrollable feed** of recent activities. Each entry shows: category badge (colored), exercise type, XP earned (with critical hit highlight), and relative timestamp. Limit to 10 entries. + +**Step 2: Commit** + +### Task 5.6: Create weekly heatmap + +**Files:** +- Create: `src/components/dashboard/weekly-heatmap.tsx` + +**Step 1: Build 7-column grid** (Mon-Sun) showing activity density for current week. Color intensity based on XP earned that day. GitHub contribution style. + +**Step 2: Commit** + +### Task 5.7: Assemble dashboard page + +**Files:** +- Modify: `src/app/page.tsx` + +**Step 1: Compose all dashboard components** into the page. Layout: daily ring + streak at top, category cards grid in middle, activity feed + heatmap at bottom. + +**Step 2: Verify build** + +```bash +npm run build +``` + +**Step 3: Commit** + +```bash +git add -A && git commit -m "feat: complete dashboard with daily ring, streak, categories, feed, heatmap" +``` + +--- + +## Phase 6: Logic Puzzles (simplest exercise — no external APIs) + +### Task 6.1: Sudoku generator + +**Files:** +- Create: `src/lib/puzzles/sudoku.ts` +- Create: `src/lib/puzzles/__tests__/sudoku.test.ts` + +**Step 1: Write failing tests** for `generateSudoku(difficulty)` returning a `{ puzzle: number[][], solution: number[][] }` and `validateSudoku(puzzle, solution)`. + +**Step 2: Implement** a backtracking Sudoku generator that creates valid puzzles with configurable difficulty (number of given cells). + +**Step 3: Run tests, commit** + +### Task 6.2: Logic puzzle API route + +**Files:** +- Create: `src/app/api/logic/generate/route.ts` +- Create: `src/app/api/logic/submit/route.ts` + +**Step 1: GET /api/logic/generate** — returns a new puzzle based on query param `type=sudoku&difficulty=easy` + +**Step 2: POST /api/logic/submit** — validates solution, calculates XP (base + speed bonus), records Activity, updates CategorySkill and DailyLog. + +**Step 3: Commit** + +### Task 6.3: Sudoku board component + +**Files:** +- Create: `src/components/logic/sudoku-board.tsx` + +**Step 1: Build interactive 9x9 grid** with number input, given cells locked, error highlighting, timer display. Client component with state management. + +**Step 2: Commit** + +### Task 6.4: Logic puzzles page + +**Files:** +- Create: `src/app/logic/page.tsx` + +**Step 1: Build page** with difficulty selector, puzzle board, timer, and submit button. On submit, show XP results panel with framer-motion slide-in. + +**Step 2: Build and verify** + +```bash +npm run build +``` + +**Step 3: Commit** + +--- + +## Phase 7: Feynman Challenges (Claude integration) + +### Task 7.1: Claude client + +**Files:** +- Create: `src/lib/claude.ts` + +**Step 1: Create Anthropic SDK client singleton** + +```typescript +import Anthropic from "@anthropic-ai/sdk"; + +const globalForClaude = globalThis as unknown as { claude: Anthropic }; + +export const claude = globalForClaude.claude || new Anthropic(); + +if (process.env.NODE_ENV !== "production") globalForClaude.claude = claude; +``` + +**Step 2: Commit** + +### Task 7.2: Feynman topic generator + +**Files:** +- Create: `src/lib/feynman/topics.ts` + +**Step 1: Create a list of ~50 topic templates** across domains (CS, physics, biology, history, economics, philosophy). Function `getRandomTopic(domain?: string)` picks one. + +**Step 2: Commit** + +### Task 7.3: Feynman scoring API + +**Files:** +- Create: `src/app/api/feynman/score/route.ts` + +**Step 1: POST handler** accepts `{ topic, explanation }`. Calls Claude with a structured prompt asking it to evaluate accuracy (0-10), completeness (0-10), clarity (0-10), and return identified gaps. Parses response, calculates XP, records Activity. + +Prompt structure: +``` +You are evaluating a Feynman-technique explanation. The user was asked to explain "{topic}" from memory, without reference materials. + +Score on three dimensions (0-10 each): +- Accuracy: Are the facts correct? +- Completeness: Are the key concepts covered? +- Clarity: Would a beginner understand this? + +Respond in JSON: { "accuracy": N, "completeness": N, "clarity": N, "gaps": ["..."], "feedback": "..." } +``` + +**Step 2: Commit** + +### Task 7.4: Feynman challenge page + +**Files:** +- Create: `src/app/feynman/page.tsx` + +**Step 1: Build page** with topic display, textarea for explanation (no paste allowed — `onPaste` handler prevents it), optional timer, submit button. Results panel shows scores on 3 dimensions + gaps + XP breakdown. + +**Step 2: Build and verify, commit** + +--- + +## Phase 8: Deep Reading + +### Task 8.1: Content library seed + +**Files:** +- Create: `content/reading/` directory with 5-10 seeded markdown articles across domains and difficulties + +**Step 1: Write 5-10 articles** (or curate public domain excerpts) covering science, philosophy, history, tech. Tag each with difficulty and domain in frontmatter. + +**Step 2: Commit** + +### Task 8.2: Content API + +**Files:** +- Create: `src/app/api/reading/content/route.ts` + +**Step 1: GET handler** returns content items filtered by difficulty/domain. Supports both seeded library and user-submitted content from ContentItem table. + +**Step 2: POST handler** for user-submitted URLs/text. If URL, fetch and clean to markdown. Save to ContentItem table. + +**Step 3: Commit** + +### Task 8.3: Reading comprehension API + +**Files:** +- Create: `src/app/api/reading/comprehend/route.ts` + +**Step 1: POST handler** accepts `{ content, answers }`. First call (no answers): Claude generates 3-5 comprehension questions from the text. Second call (with answers): Claude scores answers. Returns scores and XP. + +**Step 2: Commit** + +### Task 8.4: Reader component + +**Files:** +- Create: `src/components/reading/reader.tsx` + +**Step 1: Build distraction-free reader** — rendered markdown, clean typography, no copy-paste (`onCopy` prevented), reading timer, "I'm done" button that triggers comprehension questions. + +**Step 2: Commit** + +### Task 8.5: Reading page + +**Files:** +- Create: `src/app/reading/page.tsx` + +**Step 1: Build page** with content browser (filter by difficulty/domain), paste-your-own input, reader view (full screen when active), comprehension quiz, and results panel. + +**Step 2: Build and verify, commit** + +--- + +## Phase 9: Critical Thinking + +### Task 9.1: Critical thinking scoring API + +**Files:** +- Create: `src/app/api/critical-thinking/route.ts` + +**Step 1: POST handler** with `exerciseType` field (`flaw-finder`, `steelman`, `devil's-advocate`). Each type has its own Claude prompt: + +- **Flaw Finder:** Claude generates a passage with deliberate fallacies (or receives user-provided text), then scores the user's identification of flaws. +- **Steelman:** Claude presents a position, then scores the user's steelman on charitable interpretation, coherence, kernel of truth. +- **Devil's Advocate:** Claude presents a position, then scores the user's counterargument on strength, evidence, intellectual honesty. + +All return JSON scores + feedback + XP. + +**Step 2: Commit** + +### Task 9.2: Critical thinking page + +**Files:** +- Create: `src/app/critical-thinking/page.tsx` + +**Step 1: Build page** with exercise type selector (only showing unlocked types based on skill tree), the prompt/passage display, textarea for response (150-word minimum indicator for Devil's Advocate), submit button, and results panel. + +**Step 2: Build and verify, commit** + +--- + +## Phase 10: Chess + +### Task 10.1: Lichess API client + +**Files:** +- Create: `src/lib/lichess.ts` + +**Step 1: Build Lichess API wrapper** with functions: +- `getLichessPuzzle()` — GET `/api/puzzle/next` with auth token +- `challengeStockfish(level: number)` — POST `/api/challenge/stockfish` +- `getGameStream(gameId: string)` — stream game events + +**Step 2: Commit** + +### Task 10.2: Chess.com API client + +**Files:** +- Create: `src/lib/chesscom.ts` + +**Step 1: Build Chess.com API wrapper** with functions: +- `getPlayerStats(username: string)` — GET `api.chess.com/pub/player/{username}/stats` +- `getPlayerGames(username: string, year: number, month: number)` — game archives + +No auth needed. + +**Step 2: Commit** + +### Task 10.3: Chess puzzle API route + +**Files:** +- Create: `src/app/api/chess/puzzle/route.ts` +- Create: `src/app/api/chess/submit/route.ts` + +**Step 1: GET /api/chess/puzzle** proxies Lichess puzzle API, returns puzzle data formatted for react-chessboard. + +**Step 2: POST /api/chess/submit** records puzzle result, calculates XP based on puzzle rating vs user performance. + +**Step 3: Commit** + +### Task 10.4: Chess board component + +**Files:** +- Create: `src/components/chess/puzzle-board.tsx` + +**Step 1: Build puzzle board** using `react-chessboard` + `chess.js`. Shows position, validates moves against solution, highlights correct/incorrect moves, shows completion state. + +**Step 2: Commit** + +### Task 10.5: Chess page + +**Files:** +- Create: `src/app/chess/page.tsx` + +**Step 1: Build page** with tabs for Puzzles and Play. Puzzle tab shows puzzle board with rating display. Play tab links out to Lichess for bot games (or embeds if feasible). Chess.com rating display in sidebar. + +**Step 2: Build and verify, commit** + +--- + +## Phase 11: Skill Quests + +### Task 11.1: Quest generation API + +**Files:** +- Create: `src/app/api/quests/generate/route.ts` +- Create: `src/app/api/quests/submit/route.ts` + +**Step 1: GET /api/quests/generate** — Claude generates a micro-lesson with content + 3-5 practice exercises based on `domain` and `difficulty` params. + +**Step 2: POST /api/quests/submit** — scores practice answers, calculates XP, records Activity. + +**Step 3: Commit** + +### Task 11.2: Quest page + +**Files:** +- Create: `src/app/quests/page.tsx` + +**Step 1: Build page** with domain selector (language, music theory, mental math, science, etc.), lesson display, practice exercises, submit, and results panel. + +**Step 2: Build and verify, commit** + +--- + +## Phase 12: Profile & Skill Trees + +### Task 12.1: Profile data API + +**Files:** +- Create: `src/app/api/profile/route.ts` + +**Step 1: GET handler** returns: user stats, all category skills, all unlocked nodes, chess.com stats (if username set), achievements/milestones. + +**Step 2: Commit** + +### Task 12.2: Skill tree visualizer component + +**Files:** +- Create: `src/components/profile/skill-tree.tsx` + +**Step 1: Build skill tree renderer** using SVG or a simple node graph (not reactflow — too heavy for this). Shows nodes connected by lines, locked nodes greyed/dimmed, unlocked nodes glow with category color, click to see description. Accepts `category` prop to show one tree at a time. + +**Step 2: Commit** + +### Task 12.3: Profile page + +**Files:** +- Create: `src/app/profile/page.tsx` + +**Step 1: Build page** with: large level display + title + XP bar, tab switcher for each category's skill tree, stats grid (total exercises, time spent, longest streak, etc.), chess.com ratings card, achievements section. + +**Step 2: Build and verify, commit** + +--- + +## Phase 13: XP Results Animation + +### Task 13.1: XP results panel component + +**Files:** +- Create: `src/components/shared/xp-results.tsx` + +**Step 1: Build reusable results panel** used by all exercise pages. Slides in from right with framer-motion. Shows: +- Base XP earned +- Quality bonus (with score breakdown) +- Critical hit indicator (if triggered, with flash animation) +- Total XP +- Category skill progress bar update +- Level-up celebration (if applicable) +- Any new unlocks + +**Step 2: Commit** + +### Task 13.2: Level-up celebration overlay + +**Files:** +- Create: `src/components/shared/level-up.tsx` + +**Step 1: Build full-screen overlay** that appears on level-up. Shows new level, new title (if changed), particle effects (CSS-only, no heavy lib). Auto-dismisses after 3 seconds or on click. + +**Step 2: Commit** + +--- + +## Phase 14: Integration & Polish + +### Task 14.1: Wire XP results into all exercise pages + +**Step 1:** Import and use `XpResults` component in all 6 exercise pages. Ensure consistent behavior. + +**Step 2: Commit** + +### Task 14.2: Daily goal and streak cron logic + +**Files:** +- Create: `src/lib/streak.ts` + +**Step 1:** Write function `processEndOfDay(userId)` that checks if daily goal was met, updates streak (increment or break), consumes streak freeze if needed. Called on first activity of a new day. + +**Step 2: Commit** + +### Task 14.3: Settings page + +**Files:** +- Create: `src/app/settings/page.tsx` + +**Step 1: Build settings** for: daily XP goal (50/100/150), Lichess username, Chess.com username, display name. + +**Step 2: Commit** + +### Task 14.4: Full build verification + +**Step 1: Run all tests** + +```bash +npm test +``` + +**Step 2: Run build** + +```bash +npm run build +``` + +**Step 3: Fix any issues** + +**Step 4: Final commit** + +```bash +git add -A && git commit -m "feat: complete RotNot v1 MVP" +``` + +--- + +## Execution Order Summary + +| Phase | Description | Dependencies | +|-------|-------------|-------------| +| 1 | Scaffolding | None | +| 2 | Database | Phase 1 | +| 3 | XP Engine | Phase 1 | +| 4 | Layout & Theme | Phases 1, 2 | +| 5 | Dashboard | Phases 2, 3, 4 | +| 6 | Logic Puzzles | Phases 3, 4 | +| 7 | Feynman | Phases 3, 4 | +| 8 | Deep Reading | Phases 3, 4 | +| 9 | Critical Thinking | Phases 3, 4 | +| 10 | Chess | Phases 3, 4 | +| 11 | Skill Quests | Phases 3, 4 | +| 12 | Profile & Trees | Phases 2, 4 | +| 13 | XP Animations | Phase 3 | +| 14 | Integration | All above | + +Phases 6-11 are independent and can be parallelized. diff --git a/e2e/coding.spec.ts b/e2e/coding.spec.ts new file mode 100644 index 0000000000000000000000000000000000000000..4b3c1bb88bfe3e226955cf684bfc62b33a6d0c6b --- /dev/null +++ b/e2e/coding.spec.ts @@ -0,0 +1,142 @@ +import { test, expect, Page } from "@playwright/test"; + +// End-to-end coverage of the Coding Training module, exercising the real app: +// navigation → selection → generation → sandbox code submission (TDD) and +// LLM-judge written submission, with separate XP awards. + +// Correct solutions for every executable problem in the bank, keyed by the +// entry function name (read from sessionStorage at runtime so the test is +// robust to which problem is randomly served). +const SOLUTIONS: Record = { + sumOfEvens: "function sumOfEvens(nums){ return nums.filter(n=>n%2===0).reduce((a,b)=>a+b,0); }", + reverse: "function reverse(s){ return s.split('').reverse().join(''); }", + twoSum: + "function twoSum(nums,target){ const m=new Map(); for(let i=0;i { + const raw = await page.evaluate(() => sessionStorage.getItem("coding:problem")); + expect(raw).toBeTruthy(); + const parsed = JSON.parse(raw!); + return parsed.problem.entryFunction as string; +} + +async function generate(page: Page, type: string, difficulty: string, language: string) { + await page.goto("/coding"); + await expect(page.getByRole("heading", { name: "Coding Training" })).toBeVisible(); + await page.getByTestId(`type-${type}`).click(); + + // Difficulty + await page.getByTestId("difficulty-select").click(); + await page.getByRole("option", { name: new RegExp(difficulty, "i") }).click(); + + // Language + await page.getByTestId("language-select").click(); + await page.getByRole("option", { name: new RegExp(`^${language}$`, "i") }).click(); + + await page.getByTestId("generate-btn").click(); + await expect(page).toHaveURL(/\/coding\/problem/); + await expect(page.getByTestId("problem-title")).toBeVisible(); +} + +test("navigation: Coding Training tab is reachable from the sidebar", async ({ page }) => { + await page.goto("/"); + await page.getByRole("link", { name: "Coding Training" }).first().click(); + await expect(page).toHaveURL(/\/coding$/); + await expect(page.getByRole("heading", { name: "Coding Training" })).toBeVisible(); +}); + +test("generates a problem and shows the new problem page with formatted code", async ({ page }) => { + await generate(page, "debugging", "easy", "JavaScript"); + // The buggy code is shown with syntax highlighting (line-numbered code block). + await expect(page.getByTestId("code-editor")).toBeVisible(); + await expect(page.getByTestId("problem-prompt")).toBeVisible(); +}); + +test("code submission: correct code passes the hidden tests and awards code XP", async ({ page }) => { + await generate(page, "code-creation", "easy", "JavaScript"); + + const fn = await entryFunctionFromSession(page); + const solution = SOLUTIONS[fn]; + expect(solution, `missing E2E solution for ${fn}`).toBeTruthy(); + + // Type the correct solution into the sandbox editor. + const editor = page.getByTestId("code-editor"); + await editor.fill(solution); + + // Run against the example tests first. + await page.getByTestId("run-btn").click(); + await expect(page.getByTestId("run-output")).toContainText(/example tests passed/i); + + // Submit for grading against the full hidden suite. + await page.getByTestId("submit-code-btn").click(); + await expect(page.getByTestId("code-result-message")).toContainText(/solved|tests pass/i); + await expect(page.getByTestId("xp-results-code")).toBeVisible(); + await expect(page.getByTestId("xp-results-code")).toContainText(/XP/i); +}); + +test("debugging: applying the fix turns the suite green and awards XP", async ({ page }) => { + await generate(page, "debugging", "easy", "JavaScript"); + const fn = await entryFunctionFromSession(page); + const solution = SOLUTIONS[fn]; + expect(solution).toBeTruthy(); + + await page.getByTestId("code-editor").fill(solution); + await page.getByTestId("submit-code-btn").click(); + await expect(page.getByTestId("xp-results-code")).toBeVisible(); +}); + +test("incorrect code is rejected without awarding XP", async ({ page }) => { + await generate(page, "code-creation", "easy", "JavaScript"); + await page.getByTestId("code-editor").fill("function wrongName() { return -1; }"); + await page.getByTestId("submit-code-btn").click(); + await expect(page.getByTestId("code-result-message")).toContainText(/passed|did not compile/i); + await expect(page.getByTestId("xp-results-code")).toHaveCount(0); +}); + +test("written submission: correctly reviewing clean code awards written XP", async ({ page }) => { + // The only easy code-review problem in the bank is the clean clamp(). + await generate(page, "code-review", "easy", "JavaScript"); + + // The code under review is shown with syntax highlighting. + await expect(page.getByTestId("review-code")).toBeVisible(); + + await page + .getByTestId("written-answer") + .fill("This function looks correct. There are no issues — it clamps the value properly."); + await page.getByTestId("submit-written-btn").click(); + + await expect(page.getByTestId("written-result-message")).toContainText(/correct|accepted/i); + await expect(page.getByTestId("xp-results-written")).toBeVisible(); + await expect(page.getByTestId("xp-results-written")).toContainText(/WRITTEN XP/i); +}); + +test("written submission: a thorough architecture answer is graded and awards XP", async ({ page }) => { + await generate(page, "architecture", "medium", "JavaScript"); + await page + .getByTestId("written-answer") + .fill( + "I'd use a token bucket algorithm. The limit key is per API key granularity. " + + "Counters live in a shared Redis store so it works across instances. Bursts are " + + "smoothed by bucket capacity. If Redis is down we fail open to stay available.", + ); + await page.getByTestId("submit-written-btn").click(); + await expect(page.getByTestId("written-result")).toBeVisible(); + await expect(page.getByTestId("xp-results-written")).toBeVisible(); +}); + +test("language selection is honoured in the generated problem", async ({ page }) => { + await generate(page, "code-review", "medium", "Python"); + const raw = await page.evaluate(() => sessionStorage.getItem("coding:problem")); + const parsed = JSON.parse(raw!); + expect(parsed.problem.language).toBe("python"); +}); diff --git a/eslint.config.mjs b/eslint.config.mjs new file mode 100644 index 0000000000000000000000000000000000000000..05e726d1b4201bc8c7716d2b058279676582e8c0 --- /dev/null +++ b/eslint.config.mjs @@ -0,0 +1,18 @@ +import { defineConfig, globalIgnores } from "eslint/config"; +import nextVitals from "eslint-config-next/core-web-vitals"; +import nextTs from "eslint-config-next/typescript"; + +const eslintConfig = defineConfig([ + ...nextVitals, + ...nextTs, + // Override default ignores of eslint-config-next. + globalIgnores([ + // Default ignores of eslint-config-next: + ".next/**", + "out/**", + "build/**", + "next-env.d.ts", + ]), +]); + +export default eslintConfig; diff --git a/new-examples.json b/new-examples.json new file mode 100644 index 0000000000000000000000000000000000000000..6c75d34ca864f9a19bb64a7aaae21539f001920b --- /dev/null +++ b/new-examples.json @@ -0,0 +1,122 @@ +[ + { + "id": "ex-129", + "scoreLevel": 5, + "dimensionId": "rebuttal-quality", + "topic": "The death penalty is never justified", + "side": "con", + "argument": "My opponent claims the death penalty is never justified, citing wrongful convictions and moral absolutism. But they did not engage with the strongest counter-case: that of voluntary waiver. Timothy McVeigh waived his appeals and requested execution, believing death preferable to life in supermax confinement. If we take autonomy seriously, denying McVeigh his chosen sentence is paternalism, not justice. My opponent also ignores the specific deterrent effect on murderers already serving life sentences — without capital punishment, what mechanism prevents prison killings? The never framing requires addressing these edge cases, not just repeating general principles.", + "rationale": "Scores 5 because the rebuttal engages two specific counterarguments (voluntary waiver, prison killings by lifers) that apply the opponent's principles to edge cases. However, the rebuttal does not fully develop either point — the McVeigh case is cited but not analyzed for its implications for never, and the prison killing point is raised but not supported with evidence that such killings are common enough to matter. The tone is somewhat combative (paternalism, not justice) rather than analytically rigorous.", + "side_note": "Con-side rebuttal-quality example at mid tier — engages specific counterpoints but underdeveloped" + }, + { + "id": "ex-130", + "scoreLevel": 8, + "dimensionId": "intellectual-honesty", + "topic": "Nuclear energy should be a central pillar of climate policy", + "side": "con", + "argument": "I want to acknowledge at the outset that my position against nuclear centrality relies on contingent empirical claims that could be wrong. If small modular reactors achieve their cost and deployment targets, if next-generation designs solve the waste problem at scale, and if public acceptance shifts significantly, then nuclear could indeed play a larger role than I think likely. I am arguing against centrality — the claim that nuclear must anchor climate strategy — not against nuclear as one component among many. I should also note that my concern about cost overruns and delays applies primarily to the American regulatory context; the French and Korean experiences suggest that standardization and state commitment can deliver nuclear more efficiently. I am making a predictive claim about what is likely in the US context, not a universal claim about nuclear's impossibility. Finally, I recognize that my focus on cost ignores the security argument: if grid reliability requires firm power and renewables-plus-storage cannot yet provide it at scale, then reliability might justify premium costs. I do not think we are at that reliability threshold yet, but I could be underestimating the challenge.", + "rationale": "Scores 8 because the debater displays extensive intellectual honesty through multiple mechanisms: explicit acknowledgment of contingent empirical foundations, narrowing of claim scope from 'nuclear is bad' to 'nuclear should not be central,' recognition of context-specificity (US vs France/Korea), acknowledgment of a counterargument (security/reliability) that they engage but do not fully accept, and appropriate epistemic hedging throughout. The debater models what it looks like to hold a position while remaining genuinely open to being wrong. Loses 2 points because the closing 'I could be underestimating' is somewhat performative — a truly maximal honesty would engage more specifically with what evidence would change their mind.", + "side_note": "Con-side intellectual-honesty example at high tier — extensive contingent acknowledgment and epistemic hedging" + }, + { + "id": "ex-131", + "scoreLevel": 4, + "dimensionId": "persuasiveness", + "topic": "Free will is an illusion", + "side": "pro", + "argument": "Free will is definitely an illusion. Neuroscience shows our brains decide before we're conscious of choices. Libet's experiments proved this — the readiness potential comes before the conscious decision. Also determinism is true — physics shows everything is cause and effect. So we can't have free will. People don't like this because it means we can't praise or blame anyone, but that's just tough. The science is clear.", + "rationale": "Scores 4 because the argument cites genuine evidence (Libet, determinism) but deploys it reductively. 'Libet proved this' overstates a contested literature — Libet's interpretation is disputed, and subsequent work shows conscious veto power. The 'just tough' dismissal of the praise/blame concern is rhetorically ineffective — it signals that the debater has not engaged with why this matters to the audience. The 'science is clear' conclusion is dogmatic rather than persuasive. Scores above 1-3 because at least the right evidence categories are referenced, even if handled poorly.", + "side_note": "Pro-side persuasiveness example at low-mid tier — cites relevant evidence but deploys reductively" + }, + { + "id": "ex-132", + "scoreLevel": 7, + "dimensionId": "flaw-detection", + "topic": "Universal Basic Income should replace all welfare programs", + "side": "con", + "argument": "The replacement argument contains a hidden equivocation between administrative efficiency and adequacy. My opponent notes that UBI would reduce bureaucracy — this is true — but then slides to claiming it would 'better serve' recipients. This is a category error: efficiency is not adequacy. The flaw is that $12,000/year (a common UBI proposal) is below the poverty line everywhere in the US. A single mother in San Francisco receiving $12,000 has been administratively liberated from welfare offices but materially impoverished relative to her previous SNAP, Medicaid, and housing assistance. The argument also commits a composition fallacy: because some welfare programs have work disincentives, all do — but EITC is literally a work incentive. Finally, the 'experiments show' citation refers to trials with supplemental income, not replacement — the Finnish trial kept existing benefits. The argument conflates supplemental and replacement outcomes.", + "rationale": "Scores 7 because the debater identifies multiple genuine logical flaws: the efficiency→adequacy equivocation, the category error of conflating these distinct concepts, the composition fallacy regarding work incentives, and the crucial supplemental-vs-replacement distinction in the evidence base. Each identification is precise and explained. Loses 3 points because the flaw detection could go further: the argument does not address why UBI proponents think adequacy is achievable (automation dividend framing), and the 'category error' label may overstate — efficiency and adequacy are distinct but not mutually exclusive categories.", + "side_note": "Con-side flaw-detection example at high-mid tier — multiple precise flaw identifications with explanations" + }, + { + "id": "ex-133", + "scoreLevel": 6, + "dimensionId": "steelman-awareness", + "topic": "Social media platforms should be liable for user content", + "side": "pro", + "argument": "Before defending Section 230 reform, let me state the strongest case for the current liability shield. The internet as we know it depends on user-generated content at scale — billions of posts daily. If platforms faced publisher liability for this content, they would either shut down entirely or institute such aggressive moderation that valuable speech would be caught in over-broad filters. The safe harbor enabled the explosion of innovation from YouTube to Wikipedia to Etsy. Content moderation at scale is genuinely hard — even perfect human moderators would disagree on edge cases. Section 230 allows platforms to experiment with different moderation approaches without betting the company on each choice. I accept these points as genuine constraints. However, I argue that the shield has expanded beyond its original purpose. The 'good Samaritan' block of harmful content was meant to enable moderation, but the interpretation now protects platforms that design algorithms to amplify harmful content for engagement. The liability shield should not cover algorithmic amplification decisions — that is editorial judgment, not hosting.", + "rationale": "Scores 6 because the steelman genuinely develops the opponent's position through specific mechanisms (scale impossibility, innovation enablement, moderation difficulty) before pivoting. The acknowledgment that content moderation is 'genuinely hard' shows real engagement. The pivot distinguishes hosting from amplification, which is a fair narrowing. Loses 4 points because the steelman remains at the practical-constraint level rather than engaging the principled defense: that liability for third-party speech creates a heckler's veto and chills speech platforms themselves want to protect. The best steelman would include both practical and principled strands.", + "side_note": "Pro-side steelman-awareness example at mid-high tier — solid practical engagement but misses principled defense" + }, + { + "id": "ex-134", + "scoreLevel": 9, + "dimensionId": "devils-advocate-depth", + "topic": "It is ethical to eat animals", + "side": "con", + "argument": "I oppose eating animals, but I want to engage seriously with the strongest internal challenge to my position. The challenge is not taste preference or tradition — it is the ecologically necessary predation argument. Ecosystems require predation to function; without wolves, deer overpopulate and starve. Humans are omnivores within such ecosystems. If I accept that some predation is ecologically necessary, and that humans are natural omnivores, then the question becomes whether human meat consumption differs in kind from wolf predation. The strongest version of this challenge notes that vegan agriculture kills animals too — field mice, insects, birds killed by tractors and pesticides. The 'least harm' principle might actually favor eating large herbivores (one death feeds many) over vegetable agriculture (many small deaths). This argument is not decisive — we could reduce agricultural harm through different methods — but it challenges the moral distinction between direct killing for food and indirect killing through habitat disruption. I maintain my position because I believe intentional killing for taste preference differs morally from unavoidable collateral harm, but I cannot claim the distinction is self-evident.", + "rationale": "Scores 9 because the debater constructs a deep internal challenge by engaging with the ecological necessity of predation, the comparative harm argument (one cow vs many field mice), and the difficulty of drawing a principled line between direct and indirect killing. The acknowledgment that the distinction is 'not self-evident' demonstrates genuine grappling. The argument recognizes that their position relies on a distinction between intentional and collateral harm that requires defense. Loses 1 point because the debater could push further: the strongest internal challenge would explore whether 'taste preference' captures all meat consumption (nutritional need, cultural identity) or whether the field mouse comparison applies differently to factory farming vs hunting.", + "side_note": "Con-side devil's-advocate-depth example at near-exemplary tier — sophisticated engagement with ecological and comparative harm arguments" + }, + { + "id": "ex-135", + "scoreLevel": 3, + "dimensionId": "argument-structure", + "topic": "Climate change requires immediate drastic action", + "side": "con", + "argument": "Climate change isn't the emergency people say. The planet has warmed before. Ice ages came and went. Humans adapt — we always have. The economy matters too. If we destroy the economy trying to fix climate, we'll be poor and cold. China and India aren't cutting emissions anyway, so why should we hurt ourselves? Technology will save us eventually. We should wait for better solutions.", + "rationale": "Scores 3 because the argument is a list of disconnected claims without logical development. 'Ice ages came and went' does not address timescale or cause. 'Humans adapt' is asserted without mechanism. The China/India point is raised but not connected to why US action would be futile. 'Technology will save us' is faith-based rather than evidenced. Scores above 1-2 because the claims are at least topically related to climate policy, and the 'economy matters too' gesture toward a genuine tradeoff framework, even if undeveloped.", + "side_note": "Con-side argument-structure example at low tier — disconnected claims without logical development" + }, + { + "id": "ex-136", + "scoreLevel": 7, + "dimensionId": "evidence-accuracy", + "topic": "Cryptocurrency enables financial inclusion for the unbanked", + "side": "con", + "argument": "The financial inclusion claim requires scrutiny at three evidentiary levels. First, acquisition: how do the unbanked obtain crypto without banking infrastructure? The data shows that in Sub-Saharan Africa, 95% of crypto transactions occur through centralized exchanges that require KYC compliance — essentially banking with extra steps. Second, usage: the 'banking the unbanked' narrative relies heavily on remittances, but World Bank data shows crypto remittance corridors (El Salvador 2021-2023) processed less than 2% of total remittance volume despite legal tender status. Third, volatility: the claim that stablecoins solve this ignores that USDC and USDT require banking partnerships that fail precisely when most needed — SVB's collapse temporarily destabilized USDC. The inclusion argument conflates technical possibility (smartphones are widespread) with practical accessibility (the poor cannot afford 20% transaction fees on Ethereum mainnet or the volatility risk of self-custody).", + "rationale": "Scores 7 because the argument deploys specific, attributable data at each claim point: the 95% centralized exchange figure, the El Salvador 2% remittance figure, the SVB-USDC linkage. The argument distinguishes technical possibility from practical accessibility. Loses 3 points because the argument does not engage with the strongest pro-crypto evidence: the peer-to-peer bitcoin usage in Nigeria during the 2021 banking ban, which represents genuine financial activity outside banking infrastructure. A high-tier evidence argument would address this case before generalizing.", + "side_note": "Con-side evidence-accuracy example at high-mid tier — specific data deployment with appropriate distinction-drawing" + }, + { + "id": "ex-137", + "scoreLevel": 5, + "dimensionId": "overall", + "topic": "Civil disobedience is justified when laws are unjust", + "side": "pro", + "argument": "Civil disobedience has a noble history. MLK used it successfully. When laws are clearly wrong — like segregation — breaking them is moral. But it should be non-violent and accept punishment. If everyone disobeys laws they dislike, society collapses. So it should be rare and for truly serious injustices. The Civil Rights Movement shows it works when done right.", + "rationale": "Scores 5 because the argument references the paradigmatic case (MLK, Civil Rights Movement) and gestures toward constraints (non-violence, acceptance of punishment, rarity). However, the MLK case is deployed as authority rather than analyzed for its features. The 'if everyone disobeys' slippery slope is raised but not developed. The argument does not define 'truly serious injustices' or explain why segregation qualifies while other grievances might not. Scores at mid-tier because the right categories are present but underdeveloped.", + "side_note": "Pro-side overall example at mid tier — references paradigmatic case but underdeveloped analysis" + }, + { + "id": "ex-138", + "scoreLevel": 8, + "dimensionId": "rebuttal-quality", + "topic": "Wealthy nations have a moral obligation to accept refugees", + "side": "pro", + "argument": "My opponent argues that wealthy nations lack special obligations to refugees, treating national borders as morally decisive boundaries. I engage this through three responses. First, the causation response: many refugee flows stem from actions wealthy nations took — climate change disproportionately driven by Northern emissions, wars supported by Western arms sales, economic policies that destabilized source regions. If causation matters for responsibility, the obligation is not charity but rectification. Second, the capacity principle: we accept that those who can rescue at low cost to themselves should do so — the drowning child in the pond. Wealthy nations can absorb refugees at lower relative cost than neighboring poor countries already hosting 80% of refugees. Third, the arbitrariness challenge: birth location is morally arbitrary, yet it determines life chances more than any other factor. Treating arbitrary facts as morally decisive requires justification my opponent has not provided. I acknowledge constraints: domestic political feasibility matters, and 'open borders' is not implied — but the obligation to contribute substantially to resettlement follows from these premises.", + "rationale": "Scores 8 because the rebuttal engages the opponent's position through three distinct argumentative responses, each developed with specific grounding: causation with empirical mechanisms, capacity with the drowning child analogy and the 80% hosting figure, arbitrariness with the challenge to justify morally weighting birth location. The acknowledgment of constraints (political feasibility, not implying open borders) demonstrates boundary-awareness. Loses 2 points because the causation response could be stronger: the debater lists mechanisms but does not establish quantitative responsibility shares or address how causation-based obligation works when multiple agents contributed.", + "side_note": "Pro-side rebuttal-quality example at high tier — three distinct developed responses with specific grounding" + }, + { + "id": "ex-139", + "scoreLevel": 4, + "dimensionId": "intellectual-honesty", + "topic": "AI will cause mass unemployment within 20 years", + "side": "pro", + "argument": "AI is coming for our jobs. Look at what GPT-4 can already do. Truckers will be gone, replaced by self-driving. Office workers too. The technology is advancing exponentially. Anyone who says otherwise is in denial. History shows technology always disrupts, this time is just faster. We need UBI now before it's too late.", + "rationale": "Scores 4 because the argument makes strong predictive claims without appropriate epistemic hedging. 'Exponentially' is asserted rather than evidenced. 'Anyone who says otherwise is in denial' is dismissive rather than engaging counterarguments. The argument does not acknowledge uncertainty ranges or consider historical cases where technological displacement was slower than predicted (automation of legal discovery, which augmented rather than replaced lawyers). The UBI prescription follows as if it were the obvious implication, without considering alternatives (retraining, shorter work weeks). Scores above 1-3 because at least the right phenomenon category is identified.", + "side_note": "Pro-side intellectual-honesty example at low-mid tier — strong claims without appropriate epistemic hedging" + }, + { + "id": "ex-140", + "scoreLevel": 7, + "dimensionId": "persuasiveness", + "topic": "The filibuster should be abolished in the US Senate", + "side": "con", + "argument": "Abolishing the filibuster sounds appealing when your party holds 51 seats. But consider the temporal instability this creates. Under a simple-majority Senate, major policy swings every 2-4 years: Republicans pass their agenda 2017-2018, Democrats reverse and replace it 2021-2022, Republicans return in 2025. The resulting policy whiplash undermines the planning horizon businesses and individuals need — who invests in a 10-year project when the regulatory framework may flip in 2? The filibuster's modest supermajority requirement forces some bipartisan accommodation, creating policy durability. I acknowledge the democratic objection: 41 senators representing 11% blocking 89% seems unjust. But democracy is not merely head-counting — it includes stability, predictability, and protection against rapid majoritarian swings. The 60-vote threshold is one of the few remaining brakes on simple majoritarianism in a system where the House and Electoral College already favor populism. The question is whether you value legislative efficiency more than policy stability. Most Americans, when they consider living through whiplash, choose stability.", + "rationale": "Scores 7 because the argument constructs a persuasive case through a specific mechanism (temporal instability/policy whiplash) that resonates with audience experience of unpredictability. The 'who invests' question is rhetorically effective. The reframing of democracy to include stability is principled rather than merely tactical. The acknowledgment of the 11% objection before rebutting it shows responsiveness. Loses 3 points because the argument does not engage with the strongest counterargument: that the filibuster as currently practiced (silent 60-vote threshold) bears little resemblance to the 'talking filibuster' that enabled the Senate's legendary deliberation. The argument treats the current dysfunction as inherent to supermajority requirements rather than specific to the modern implementation.", + "side_note": "Con-side persuasiveness example at high-mid tier — effective temporal instability framing with rhetorical skill" + } +] \ No newline at end of file diff --git a/next.config.ts b/next.config.ts new file mode 100644 index 0000000000000000000000000000000000000000..e9ffa3083ad279ecf95fd8eae59cb253e9a539c4 --- /dev/null +++ b/next.config.ts @@ -0,0 +1,7 @@ +import type { NextConfig } from "next"; + +const nextConfig: NextConfig = { + /* config options here */ +}; + +export default nextConfig; diff --git a/package-lock.json b/package-lock.json new file mode 100644 index 0000000000000000000000000000000000000000..2519f3ea54e211e5930bc7ab27fab827371a9865 --- /dev/null +++ b/package-lock.json @@ -0,0 +1,14324 @@ +{ + "name": "rotnot-work", + "version": "0.1.0", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "rotnot-work", + "version": "0.1.0", + "dependencies": { + "@anthropic-ai/sdk": "^0.82.0", + "@base-ui/react": "^1.3.0", + "@capacitor/android": "^8.2.0", + "@capacitor/cli": "^8.2.0", + "@capacitor/core": "^8.2.0", + "@capacitor/haptics": "^8.0.1", + "@capacitor/ios": "^8.2.0", + "@capacitor/local-notifications": "^8.0.2", + "@capacitor/push-notifications": "^8.0.2", + "@capacitor/status-bar": "^8.0.1", + "@libsql/client": "^0.17.0", + "@prisma/adapter-libsql": "^7.5.0", + "@prisma/client": "^7.5.0", + "chess.js": "^1.4.0", + "class-variance-authority": "^0.7.1", + "clsx": "^2.1.1", + "date-fns": "^4.1.0", + "framer-motion": "^12.38.0", + "langsmith": "^0.5.15", + "lucide-react": "^0.577.0", + "next": "16.1.7", + "react": "19.2.3", + "react-chessboard": "^5.10.0", + "react-dom": "19.2.3", + "recharts": "^3.8.0", + "shadcn": "^4.0.8", + "tailwind-merge": "^3.5.0", + "tw-animate-css": "^1.4.0" + }, + "devDependencies": { + "@playwright/test": "^1.61.1", + "@tailwindcss/postcss": "^4", + "@types/node": "^20", + "@types/react": "^19", + "@types/react-dom": "^19", + "eslint": "^9", + "eslint-config-next": "16.1.7", + "prisma": "^7.5.0", + "tailwindcss": "^4", + "tsx": "^4.21.0", + "typescript": "^5.9.3", + "vitest": "^4.1.0" + } + }, + "node_modules/@alloc/quick-lru": { + "version": "5.2.0", + "resolved": "https://registry.npmjs.org/@alloc/quick-lru/-/quick-lru-5.2.0.tgz", + "integrity": "sha512-UrcABB+4bUrFABwbluTIBErXwvbsU/V7TZWfmbgJfbkwiBuziS9gxdODUyuiecfdGQ85jglMW6juS3+z5TsKLw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/@anthropic-ai/sdk": { + "version": "0.82.0", + "resolved": "https://registry.npmjs.org/@anthropic-ai/sdk/-/sdk-0.82.0.tgz", + "integrity": "sha512-xdHTjL1GlUlDugHq/I47qdOKp/ROPvuHl7ROJCgUQigbvPu7asf9KcAcU1EqdrP2LuVhEKaTs7Z+ShpZDRzHdQ==", + "license": "MIT", + "dependencies": { + "json-schema-to-ts": "^3.1.1" + }, + "bin": { + "anthropic-ai-sdk": "bin/cli" + }, + "peerDependencies": { + "zod": "^3.25.0 || ^4.0.0" + }, + "peerDependenciesMeta": { + "zod": { + "optional": true + } + } + }, + "node_modules/@babel/code-frame": { + "version": "7.29.0", + "resolved": "https://registry.npmjs.org/@babel/code-frame/-/code-frame-7.29.0.tgz", + "integrity": "sha512-9NhCeYjq9+3uxgdtp20LSiJXJvN0FeCtNGpJxuMFZ1Kv3cWUNb6DOhJwUvcVCzKGR66cw4njwM6hrJLqgOwbcw==", + "license": "MIT", + "dependencies": { + "@babel/helper-validator-identifier": "^7.28.5", + "js-tokens": "^4.0.0", + "picocolors": "^1.1.1" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/compat-data": { + "version": "7.29.0", + "resolved": "https://registry.npmjs.org/@babel/compat-data/-/compat-data-7.29.0.tgz", + "integrity": "sha512-T1NCJqT/j9+cn8fvkt7jtwbLBfLC/1y1c7NtCeXFRgzGTsafi68MRv8yzkYSapBnFA6L3U2VSc02ciDzoAJhJg==", + "license": "MIT", + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/core": { + "version": "7.29.0", + "resolved": "https://registry.npmjs.org/@babel/core/-/core-7.29.0.tgz", + "integrity": "sha512-CGOfOJqWjg2qW/Mb6zNsDm+u5vFQ8DxXfbM09z69p5Z6+mE1ikP2jUXw+j42Pf1XTYED2Rni5f95npYeuwMDQA==", + "license": "MIT", + "dependencies": { + "@babel/code-frame": "^7.29.0", + "@babel/generator": "^7.29.0", + "@babel/helper-compilation-targets": "^7.28.6", + "@babel/helper-module-transforms": "^7.28.6", + "@babel/helpers": "^7.28.6", + "@babel/parser": "^7.29.0", + "@babel/template": "^7.28.6", + "@babel/traverse": "^7.29.0", + "@babel/types": "^7.29.0", + "@jridgewell/remapping": "^2.3.5", + "convert-source-map": "^2.0.0", + "debug": "^4.1.0", + "gensync": "^1.0.0-beta.2", + "json5": "^2.2.3", + "semver": "^6.3.1" + }, + "engines": { + "node": ">=6.9.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/babel" + } + }, + "node_modules/@babel/generator": { + "version": "7.29.1", + "resolved": "https://registry.npmjs.org/@babel/generator/-/generator-7.29.1.tgz", + "integrity": "sha512-qsaF+9Qcm2Qv8SRIMMscAvG4O3lJ0F1GuMo5HR/Bp02LopNgnZBC/EkbevHFeGs4ls/oPz9v+Bsmzbkbe+0dUw==", + "license": "MIT", + "dependencies": { + "@babel/parser": "^7.29.0", + "@babel/types": "^7.29.0", + "@jridgewell/gen-mapping": "^0.3.12", + "@jridgewell/trace-mapping": "^0.3.28", + "jsesc": "^3.0.2" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-annotate-as-pure": { + "version": "7.27.3", + "resolved": "https://registry.npmjs.org/@babel/helper-annotate-as-pure/-/helper-annotate-as-pure-7.27.3.tgz", + "integrity": "sha512-fXSwMQqitTGeHLBC08Eq5yXz2m37E4pJX1qAU1+2cNedz/ifv/bVXft90VeSav5nFO61EcNgwr0aJxbyPaWBPg==", + "license": "MIT", + "dependencies": { + "@babel/types": "^7.27.3" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-compilation-targets": { + "version": "7.28.6", + "resolved": "https://registry.npmjs.org/@babel/helper-compilation-targets/-/helper-compilation-targets-7.28.6.tgz", + "integrity": "sha512-JYtls3hqi15fcx5GaSNL7SCTJ2MNmjrkHXg4FSpOA/grxK8KwyZ5bubHsCq8FXCkua6xhuaaBit+3b7+VZRfcA==", + "license": "MIT", + "dependencies": { + "@babel/compat-data": "^7.28.6", + "@babel/helper-validator-option": "^7.27.1", + "browserslist": "^4.24.0", + "lru-cache": "^5.1.1", + "semver": "^6.3.1" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-create-class-features-plugin": { + "version": "7.28.6", + "resolved": "https://registry.npmjs.org/@babel/helper-create-class-features-plugin/-/helper-create-class-features-plugin-7.28.6.tgz", + "integrity": "sha512-dTOdvsjnG3xNT9Y0AUg1wAl38y+4Rl4sf9caSQZOXdNqVn+H+HbbJ4IyyHaIqNR6SW9oJpA/RuRjsjCw2IdIow==", + "license": "MIT", + "dependencies": { + "@babel/helper-annotate-as-pure": "^7.27.3", + "@babel/helper-member-expression-to-functions": "^7.28.5", + "@babel/helper-optimise-call-expression": "^7.27.1", + "@babel/helper-replace-supers": "^7.28.6", + "@babel/helper-skip-transparent-expression-wrappers": "^7.27.1", + "@babel/traverse": "^7.28.6", + "semver": "^6.3.1" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0" + } + }, + "node_modules/@babel/helper-globals": { + "version": "7.28.0", + "resolved": "https://registry.npmjs.org/@babel/helper-globals/-/helper-globals-7.28.0.tgz", + "integrity": "sha512-+W6cISkXFa1jXsDEdYA8HeevQT/FULhxzR99pxphltZcVaugps53THCeiWA8SguxxpSp3gKPiuYfSWopkLQ4hw==", + "license": "MIT", + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-member-expression-to-functions": { + "version": "7.28.5", + "resolved": "https://registry.npmjs.org/@babel/helper-member-expression-to-functions/-/helper-member-expression-to-functions-7.28.5.tgz", + "integrity": "sha512-cwM7SBRZcPCLgl8a7cY0soT1SptSzAlMH39vwiRpOQkJlh53r5hdHwLSCZpQdVLT39sZt+CRpNwYG4Y2v77atg==", + "license": "MIT", + "dependencies": { + "@babel/traverse": "^7.28.5", + "@babel/types": "^7.28.5" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-module-imports": { + "version": "7.28.6", + "resolved": "https://registry.npmjs.org/@babel/helper-module-imports/-/helper-module-imports-7.28.6.tgz", + "integrity": "sha512-l5XkZK7r7wa9LucGw9LwZyyCUscb4x37JWTPz7swwFE/0FMQAGpiWUZn8u9DzkSBWEcK25jmvubfpw2dnAMdbw==", + "license": "MIT", + "dependencies": { + "@babel/traverse": "^7.28.6", + "@babel/types": "^7.28.6" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-module-transforms": { + "version": "7.28.6", + "resolved": "https://registry.npmjs.org/@babel/helper-module-transforms/-/helper-module-transforms-7.28.6.tgz", + "integrity": "sha512-67oXFAYr2cDLDVGLXTEABjdBJZ6drElUSI7WKp70NrpyISso3plG9SAGEF6y7zbha/wOzUByWWTJvEDVNIUGcA==", + "license": "MIT", + "dependencies": { + "@babel/helper-module-imports": "^7.28.6", + "@babel/helper-validator-identifier": "^7.28.5", + "@babel/traverse": "^7.28.6" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0" + } + }, + "node_modules/@babel/helper-optimise-call-expression": { + "version": "7.27.1", + "resolved": "https://registry.npmjs.org/@babel/helper-optimise-call-expression/-/helper-optimise-call-expression-7.27.1.tgz", + "integrity": "sha512-URMGH08NzYFhubNSGJrpUEphGKQwMQYBySzat5cAByY1/YgIRkULnIy3tAMeszlL/so2HbeilYloUmSpd7GdVw==", + "license": "MIT", + "dependencies": { + "@babel/types": "^7.27.1" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-plugin-utils": { + "version": "7.28.6", + "resolved": "https://registry.npmjs.org/@babel/helper-plugin-utils/-/helper-plugin-utils-7.28.6.tgz", + "integrity": "sha512-S9gzZ/bz83GRysI7gAD4wPT/AI3uCnY+9xn+Mx/KPs2JwHJIz1W8PZkg2cqyt3RNOBM8ejcXhV6y8Og7ly/Dug==", + "license": "MIT", + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-replace-supers": { + "version": "7.28.6", + "resolved": "https://registry.npmjs.org/@babel/helper-replace-supers/-/helper-replace-supers-7.28.6.tgz", + "integrity": "sha512-mq8e+laIk94/yFec3DxSjCRD2Z0TAjhVbEJY3UQrlwVo15Lmt7C2wAUbK4bjnTs4APkwsYLTahXRraQXhb1WCg==", + "license": "MIT", + "dependencies": { + "@babel/helper-member-expression-to-functions": "^7.28.5", + "@babel/helper-optimise-call-expression": "^7.27.1", + "@babel/traverse": "^7.28.6" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0" + } + }, + "node_modules/@babel/helper-skip-transparent-expression-wrappers": { + "version": "7.27.1", + "resolved": "https://registry.npmjs.org/@babel/helper-skip-transparent-expression-wrappers/-/helper-skip-transparent-expression-wrappers-7.27.1.tgz", + "integrity": "sha512-Tub4ZKEXqbPjXgWLl2+3JpQAYBJ8+ikpQ2Ocj/q/r0LwE3UhENh7EUabyHjz2kCEsrRY83ew2DQdHluuiDQFzg==", + "license": "MIT", + "dependencies": { + "@babel/traverse": "^7.27.1", + "@babel/types": "^7.27.1" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-string-parser": { + "version": "7.27.1", + "resolved": "https://registry.npmjs.org/@babel/helper-string-parser/-/helper-string-parser-7.27.1.tgz", + "integrity": "sha512-qMlSxKbpRlAridDExk92nSobyDdpPijUq2DW6oDnUqd0iOGxmQjyqhMIihI9+zv4LPyZdRje2cavWPbCbWm3eA==", + "license": "MIT", + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-validator-identifier": { + "version": "7.28.5", + "resolved": "https://registry.npmjs.org/@babel/helper-validator-identifier/-/helper-validator-identifier-7.28.5.tgz", + "integrity": "sha512-qSs4ifwzKJSV39ucNjsvc6WVHs6b7S03sOh2OcHF9UHfVPqWWALUsNUVzhSBiItjRZoLHx7nIarVjqKVusUZ1Q==", + "license": "MIT", + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-validator-option": { + "version": "7.27.1", + "resolved": "https://registry.npmjs.org/@babel/helper-validator-option/-/helper-validator-option-7.27.1.tgz", + "integrity": "sha512-YvjJow9FxbhFFKDSuFnVCe2WxXk1zWc22fFePVNEaWJEu8IrZVlda6N0uHwzZrUM1il7NC9Mlp4MaJYbYd9JSg==", + "license": "MIT", + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helpers": { + "version": "7.29.2", + "resolved": "https://registry.npmjs.org/@babel/helpers/-/helpers-7.29.2.tgz", + "integrity": "sha512-HoGuUs4sCZNezVEKdVcwqmZN8GoHirLUcLaYVNBK2J0DadGtdcqgr3BCbvH8+XUo4NGjNl3VOtSjEKNzqfFgKw==", + "license": "MIT", + "dependencies": { + "@babel/template": "^7.28.6", + "@babel/types": "^7.29.0" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/parser": { + "version": "7.29.2", + "resolved": "https://registry.npmjs.org/@babel/parser/-/parser-7.29.2.tgz", + "integrity": "sha512-4GgRzy/+fsBa72/RZVJmGKPmZu9Byn8o4MoLpmNe1m8ZfYnz5emHLQz3U4gLud6Zwl0RZIcgiLD7Uq7ySFuDLA==", + "license": "MIT", + "dependencies": { + "@babel/types": "^7.29.0" + }, + "bin": { + "parser": "bin/babel-parser.js" + }, + "engines": { + "node": ">=6.0.0" + } + }, + "node_modules/@babel/plugin-syntax-jsx": { + "version": "7.28.6", + "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-jsx/-/plugin-syntax-jsx-7.28.6.tgz", + "integrity": "sha512-wgEmr06G6sIpqr8YDwA2dSRTE3bJ+V0IfpzfSY3Lfgd7YWOaAdlykvJi13ZKBt8cZHfgH1IXN+CL656W3uUa4w==", + "license": "MIT", + "dependencies": { + "@babel/helper-plugin-utils": "^7.28.6" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-syntax-typescript": { + "version": "7.28.6", + "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-typescript/-/plugin-syntax-typescript-7.28.6.tgz", + "integrity": "sha512-+nDNmQye7nlnuuHDboPbGm00Vqg3oO8niRRL27/4LYHUsHYh0zJ1xWOz0uRwNFmM1Avzk8wZbc6rdiYhomzv/A==", + "license": "MIT", + "dependencies": { + "@babel/helper-plugin-utils": "^7.28.6" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-transform-modules-commonjs": { + "version": "7.28.6", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-modules-commonjs/-/plugin-transform-modules-commonjs-7.28.6.tgz", + "integrity": "sha512-jppVbf8IV9iWWwWTQIxJMAJCWBuuKx71475wHwYytrRGQ2CWiDvYlADQno3tcYpS/T2UUWFQp3nVtYfK/YBQrA==", + "license": "MIT", + "dependencies": { + "@babel/helper-module-transforms": "^7.28.6", + "@babel/helper-plugin-utils": "^7.28.6" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-transform-typescript": { + "version": "7.28.6", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-typescript/-/plugin-transform-typescript-7.28.6.tgz", + "integrity": "sha512-0YWL2RFxOqEm9Efk5PvreamxPME8OyY0wM5wh5lHjF+VtVhdneCWGzZeSqzOfiobVqQaNCd2z0tQvnI9DaPWPw==", + "license": "MIT", + "dependencies": { + "@babel/helper-annotate-as-pure": "^7.27.3", + "@babel/helper-create-class-features-plugin": "^7.28.6", + "@babel/helper-plugin-utils": "^7.28.6", + "@babel/helper-skip-transparent-expression-wrappers": "^7.27.1", + "@babel/plugin-syntax-typescript": "^7.28.6" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/preset-typescript": { + "version": "7.28.5", + "resolved": "https://registry.npmjs.org/@babel/preset-typescript/-/preset-typescript-7.28.5.tgz", + "integrity": "sha512-+bQy5WOI2V6LJZpPVxY+yp66XdZ2yifu0Mc1aP5CQKgjn4QM5IN2i5fAZ4xKop47pr8rpVhiAeu+nDQa12C8+g==", + "license": "MIT", + "dependencies": { + "@babel/helper-plugin-utils": "^7.27.1", + "@babel/helper-validator-option": "^7.27.1", + "@babel/plugin-syntax-jsx": "^7.27.1", + "@babel/plugin-transform-modules-commonjs": "^7.27.1", + "@babel/plugin-transform-typescript": "^7.28.5" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/runtime": { + "version": "7.29.2", + "resolved": "https://registry.npmjs.org/@babel/runtime/-/runtime-7.29.2.tgz", + "integrity": "sha512-JiDShH45zKHWyGe4ZNVRrCjBz8Nh9TMmZG1kh4QTK8hCBTWBi8Da+i7s1fJw7/lYpM4ccepSNfqzZ/QvABBi5g==", + "license": "MIT", + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/template": { + "version": "7.28.6", + "resolved": "https://registry.npmjs.org/@babel/template/-/template-7.28.6.tgz", + "integrity": "sha512-YA6Ma2KsCdGb+WC6UpBVFJGXL58MDA6oyONbjyF/+5sBgxY/dwkhLogbMT2GXXyU84/IhRw/2D1Os1B/giz+BQ==", + "license": "MIT", + "dependencies": { + "@babel/code-frame": "^7.28.6", + "@babel/parser": "^7.28.6", + "@babel/types": "^7.28.6" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/traverse": { + "version": "7.29.0", + "resolved": "https://registry.npmjs.org/@babel/traverse/-/traverse-7.29.0.tgz", + "integrity": "sha512-4HPiQr0X7+waHfyXPZpWPfWL/J7dcN1mx9gL6WdQVMbPnF3+ZhSMs8tCxN7oHddJE9fhNE7+lxdnlyemKfJRuA==", + "license": "MIT", + "dependencies": { + "@babel/code-frame": "^7.29.0", + "@babel/generator": "^7.29.0", + "@babel/helper-globals": "^7.28.0", + "@babel/parser": "^7.29.0", + "@babel/template": "^7.28.6", + "@babel/types": "^7.29.0", + "debug": "^4.3.1" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/types": { + "version": "7.29.0", + "resolved": "https://registry.npmjs.org/@babel/types/-/types-7.29.0.tgz", + "integrity": "sha512-LwdZHpScM4Qz8Xw2iKSzS+cfglZzJGvofQICy7W7v4caru4EaAmyUuO6BGrbyQ2mYV11W0U8j5mBhd14dd3B0A==", + "license": "MIT", + "dependencies": { + "@babel/helper-string-parser": "^7.27.1", + "@babel/helper-validator-identifier": "^7.28.5" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@base-ui/react": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/@base-ui/react/-/react-1.3.0.tgz", + "integrity": "sha512-FwpKqZbPz14AITp1CVgf4AjhKPe1OeeVKSBMdgD10zbFlj3QSWelmtCMLi2+/PFZZcIm3l87G7rwtCZJwHyXWA==", + "license": "MIT", + "dependencies": { + "@babel/runtime": "^7.28.6", + "@base-ui/utils": "0.2.6", + "@floating-ui/react-dom": "^2.1.8", + "@floating-ui/utils": "^0.2.11", + "tabbable": "^6.4.0", + "use-sync-external-store": "^1.6.0" + }, + "engines": { + "node": ">=14.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/mui-org" + }, + "peerDependencies": { + "@types/react": "^17 || ^18 || ^19", + "react": "^17 || ^18 || ^19", + "react-dom": "^17 || ^18 || ^19" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + } + } + }, + "node_modules/@base-ui/utils": { + "version": "0.2.6", + "resolved": "https://registry.npmjs.org/@base-ui/utils/-/utils-0.2.6.tgz", + "integrity": "sha512-yQ+qeuqohwhsNpoYDqqXaLllYAkPCP4vYdDrVo8FQXaAPfHWm1pG/Vm+jmGTA5JFS0BAIjookyapuJFY8F9PIw==", + "license": "MIT", + "dependencies": { + "@babel/runtime": "^7.28.6", + "@floating-ui/utils": "^0.2.11", + "reselect": "^5.1.1", + "use-sync-external-store": "^1.6.0" + }, + "peerDependencies": { + "@types/react": "^17 || ^18 || ^19", + "react": "^17 || ^18 || ^19", + "react-dom": "^17 || ^18 || ^19" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + } + } + }, + "node_modules/@capacitor/android": { + "version": "8.2.0", + "resolved": "https://registry.npmjs.org/@capacitor/android/-/android-8.2.0.tgz", + "integrity": "sha512-XLm5OsWLPfXQxDxzFS7SOdMEgGvW+2c7TGLXkTR2cSKdkWK5Abns4imlT5qghKYhjM9r74IrDkBWg/9ALUGNKQ==", + "license": "MIT", + "peerDependencies": { + "@capacitor/core": "^8.2.0" + } + }, + "node_modules/@capacitor/cli": { + "version": "8.2.0", + "resolved": "https://registry.npmjs.org/@capacitor/cli/-/cli-8.2.0.tgz", + "integrity": "sha512-1cMEk0d/I6tl1U+v/lnJR5Oylpx8ZBIHrvQxD5zK0MkjYOUyQAAGJgh97rkhGJqjAUvrGpa8H4BmyhNQN9a17A==", + "license": "MIT", + "dependencies": { + "@ionic/cli-framework-output": "^2.2.8", + "@ionic/utils-subprocess": "^3.0.1", + "@ionic/utils-terminal": "^2.3.5", + "commander": "^12.1.0", + "debug": "^4.4.0", + "env-paths": "^2.2.0", + "fs-extra": "^11.2.0", + "kleur": "^4.1.5", + "native-run": "^2.0.3", + "open": "^8.4.0", + "plist": "^3.1.0", + "prompts": "^2.4.2", + "rimraf": "^6.0.1", + "semver": "^7.6.3", + "tar": "^7.5.3", + "tslib": "^2.8.1", + "xml2js": "^0.6.2" + }, + "bin": { + "cap": "bin/capacitor", + "capacitor": "bin/capacitor" + }, + "engines": { + "node": ">=22.0.0" + } + }, + "node_modules/@capacitor/cli/node_modules/commander": { + "version": "12.1.0", + "resolved": "https://registry.npmjs.org/commander/-/commander-12.1.0.tgz", + "integrity": "sha512-Vw8qHK3bZM9y/P10u3Vib8o/DdkvA2OtPtZvD871QKjy74Wj1WSKFILMPRPSdUSx5RFK1arlJzEtA4PkFgnbuA==", + "license": "MIT", + "engines": { + "node": ">=18" + } + }, + "node_modules/@capacitor/cli/node_modules/define-lazy-prop": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/define-lazy-prop/-/define-lazy-prop-2.0.0.tgz", + "integrity": "sha512-Ds09qNh8yw3khSjiJjiUInaGX9xlqZDY7JVryGxdxV7NPeuqQfplOpQ66yJFZut3jLa5zOwkXw1g9EI2uKh4Og==", + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/@capacitor/cli/node_modules/is-docker": { + "version": "2.2.1", + "resolved": "https://registry.npmjs.org/is-docker/-/is-docker-2.2.1.tgz", + "integrity": "sha512-F+i2BKsFrH66iaUFc0woD8sLy8getkwTwtOBjvs56Cx4CgJDeKQeqfz8wAYiSb8JOprWhHH5p77PbmYCvvUuXQ==", + "license": "MIT", + "bin": { + "is-docker": "cli.js" + }, + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/@capacitor/cli/node_modules/is-wsl": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/is-wsl/-/is-wsl-2.2.0.tgz", + "integrity": "sha512-fKzAra0rGJUUBwGBgNkHZuToZcn+TtXHpeCgmkMJMMYx1sQDYaCSyjJBSCa2nH1DGm7s3n1oBnohoVTBaN7Lww==", + "license": "MIT", + "dependencies": { + "is-docker": "^2.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/@capacitor/cli/node_modules/open": { + "version": "8.4.2", + "resolved": "https://registry.npmjs.org/open/-/open-8.4.2.tgz", + "integrity": "sha512-7x81NCL719oNbsq/3mh+hVrAWmFuEYUqrq/Iw3kUzH8ReypT9QQ0BLoJS7/G9k6N81XjW4qHWtjWwe/9eLy1EQ==", + "license": "MIT", + "dependencies": { + "define-lazy-prop": "^2.0.0", + "is-docker": "^2.1.1", + "is-wsl": "^2.2.0" + }, + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/@capacitor/cli/node_modules/semver": { + "version": "7.7.4", + "resolved": "https://registry.npmjs.org/semver/-/semver-7.7.4.tgz", + "integrity": "sha512-vFKC2IEtQnVhpT78h1Yp8wzwrf8CM+MzKMHGJZfBtzhZNycRFnXsHk6E5TxIkkMsgNS7mdX3AGB7x2QM2di4lA==", + "license": "ISC", + "bin": { + "semver": "bin/semver.js" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/@capacitor/core": { + "version": "8.2.0", + "resolved": "https://registry.npmjs.org/@capacitor/core/-/core-8.2.0.tgz", + "integrity": "sha512-oKaoNeNtH2iIZMDFVrb1atoyRECDGHcfLMunJ5KWN8DtvpVBeeA4c41e20NTuhMxw1cSYbpq2PV2hb+/9CJxlQ==", + "license": "MIT", + "dependencies": { + "tslib": "^2.1.0" + } + }, + "node_modules/@capacitor/haptics": { + "version": "8.0.1", + "resolved": "https://registry.npmjs.org/@capacitor/haptics/-/haptics-8.0.1.tgz", + "integrity": "sha512-8v8rowLBMeb3CryqoQvXndwyUsoi4pPXf0qFw7IGA4D32Uk7+K6juN2SjRowqunoovkvvbFmU9TD7JIAz2zmFw==", + "license": "MIT", + "peerDependencies": { + "@capacitor/core": ">=8.0.0" + } + }, + "node_modules/@capacitor/ios": { + "version": "8.2.0", + "resolved": "https://registry.npmjs.org/@capacitor/ios/-/ios-8.2.0.tgz", + "integrity": "sha512-X2/VtM4qP/R1SM0VQ5W/VotEc6PS/KTooD33EijsfAHWBdee+xmBapW8SeNLnu16wJ+tsfWlvtipaJEyfKbRKQ==", + "license": "MIT", + "peerDependencies": { + "@capacitor/core": "^8.2.0" + } + }, + "node_modules/@capacitor/local-notifications": { + "version": "8.0.2", + "resolved": "https://registry.npmjs.org/@capacitor/local-notifications/-/local-notifications-8.0.2.tgz", + "integrity": "sha512-X7KE/I4ZutMTGVHNUyTjIugYcQEcHJRLks+TsPnOriuS+lo0geSTuaRln6zAZlJSSXSoVMSSzHexdSbIjR/8iw==", + "license": "MIT", + "peerDependencies": { + "@capacitor/core": ">=8.0.0" + } + }, + "node_modules/@capacitor/push-notifications": { + "version": "8.0.2", + "resolved": "https://registry.npmjs.org/@capacitor/push-notifications/-/push-notifications-8.0.2.tgz", + "integrity": "sha512-mej8Eh4EU4JXbaeyMX2l+4NNK6IdY5iRsEXpBOTHLD29fuCACBP7kOJTiJv6piw134zdlbFH0rR+sDKHIiFOFg==", + "license": "MIT", + "peerDependencies": { + "@capacitor/core": ">=8.0.0" + } + }, + "node_modules/@capacitor/status-bar": { + "version": "8.0.1", + "resolved": "https://registry.npmjs.org/@capacitor/status-bar/-/status-bar-8.0.1.tgz", + "integrity": "sha512-OR59dlbwvmrV5dKsC9lvwv48QaGbqcbSTBpk+9/WXWxXYSdXXdzJZU9p8oyNPAkuJhCdnSa3XmU43fZRPBJJ5w==", + "license": "MIT", + "peerDependencies": { + "@capacitor/core": ">=8.0.0" + } + }, + "node_modules/@clack/core": { + "version": "0.5.0", + "resolved": "https://registry.npmjs.org/@clack/core/-/core-0.5.0.tgz", + "integrity": "sha512-p3y0FIOwaYRUPRcMO7+dlmLh8PSRcrjuTndsiA0WAFbWES0mLZlrjVoBRZ9DzkPFJZG6KGkJmoEAY0ZcVWTkow==", + "devOptional": true, + "license": "MIT", + "dependencies": { + "picocolors": "^1.0.0", + "sisteransi": "^1.0.5" + } + }, + "node_modules/@clack/prompts": { + "version": "0.11.0", + "resolved": "https://registry.npmjs.org/@clack/prompts/-/prompts-0.11.0.tgz", + "integrity": "sha512-pMN5FcrEw9hUkZA4f+zLlzivQSeQf5dRGJjSUbvVYDLvpKCdQx5OaknvKzgbtXOizhP+SJJJjqEbOe55uKKfAw==", + "devOptional": true, + "license": "MIT", + "dependencies": { + "@clack/core": "0.5.0", + "picocolors": "^1.0.0", + "sisteransi": "^1.0.5" + } + }, + "node_modules/@dnd-kit/accessibility": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/@dnd-kit/accessibility/-/accessibility-3.1.1.tgz", + "integrity": "sha512-2P+YgaXF+gRsIihwwY1gCsQSYnu9Zyj2py8kY5fFvUM1qm2WA2u639R6YNVfU4GWr+ZM5mqEsfHZZLoRONbemw==", + "license": "MIT", + "dependencies": { + "tslib": "^2.0.0" + }, + "peerDependencies": { + "react": ">=16.8.0" + } + }, + "node_modules/@dnd-kit/core": { + "version": "6.3.1", + "resolved": "https://registry.npmjs.org/@dnd-kit/core/-/core-6.3.1.tgz", + "integrity": "sha512-xkGBRQQab4RLwgXxoqETICr6S5JlogafbhNsidmrkVv2YRs5MLwpjoF2qpiGjQt8S9AoxtIV603s0GIUpY5eYQ==", + "license": "MIT", + "dependencies": { + "@dnd-kit/accessibility": "^3.1.1", + "@dnd-kit/utilities": "^3.2.2", + "tslib": "^2.0.0" + }, + "peerDependencies": { + "react": ">=16.8.0", + "react-dom": ">=16.8.0" + } + }, + "node_modules/@dnd-kit/modifiers": { + "version": "9.0.0", + "resolved": "https://registry.npmjs.org/@dnd-kit/modifiers/-/modifiers-9.0.0.tgz", + "integrity": "sha512-ybiLc66qRGuZoC20wdSSG6pDXFikui/dCNGthxv4Ndy8ylErY0N3KVxY2bgo7AWwIbxDmXDg3ylAFmnrjcbVvw==", + "license": "MIT", + "dependencies": { + "@dnd-kit/utilities": "^3.2.2", + "tslib": "^2.0.0" + }, + "peerDependencies": { + "@dnd-kit/core": "^6.3.0", + "react": ">=16.8.0" + } + }, + "node_modules/@dnd-kit/utilities": { + "version": "3.2.2", + "resolved": "https://registry.npmjs.org/@dnd-kit/utilities/-/utilities-3.2.2.tgz", + "integrity": "sha512-+MKAJEOfaBe5SmV6t34p80MMKhjvUz0vRrvVJbPT0WElzaOJ/1xs+D+KDv+tD/NE5ujfrChEcshd4fLn0wpiqg==", + "license": "MIT", + "dependencies": { + "tslib": "^2.0.0" + }, + "peerDependencies": { + "react": ">=16.8.0" + } + }, + "node_modules/@dotenvx/dotenvx": { + "version": "1.55.1", + "resolved": "https://registry.npmjs.org/@dotenvx/dotenvx/-/dotenvx-1.55.1.tgz", + "integrity": "sha512-WEuKyoe9CA7dfcFBnNbL0ndbCNcptaEYBygfFo9X1qEG+HD7xku4CYIplw6sbAHJavesZWbVBHeRSpvri0eKqw==", + "license": "BSD-3-Clause", + "dependencies": { + "commander": "^11.1.0", + "dotenv": "^17.2.1", + "eciesjs": "^0.4.10", + "execa": "^5.1.1", + "fdir": "^6.2.0", + "ignore": "^5.3.0", + "object-treeify": "1.1.33", + "picomatch": "^4.0.2", + "which": "^4.0.0" + }, + "bin": { + "dotenvx": "src/cli/dotenvx.js" + }, + "funding": { + "url": "https://dotenvx.com" + } + }, + "node_modules/@dotenvx/dotenvx/node_modules/commander": { + "version": "11.1.0", + "resolved": "https://registry.npmjs.org/commander/-/commander-11.1.0.tgz", + "integrity": "sha512-yPVavfyCcRhmorC7rWlkHn15b4wDVgVmBA7kV4QVBsF7kv/9TKJAbAXVTxvTnwP8HHKjRCJDClKbciiYS7p0DQ==", + "license": "MIT", + "engines": { + "node": ">=16" + } + }, + "node_modules/@dotenvx/dotenvx/node_modules/dotenv": { + "version": "17.3.1", + "resolved": "https://registry.npmjs.org/dotenv/-/dotenv-17.3.1.tgz", + "integrity": "sha512-IO8C/dzEb6O3F9/twg6ZLXz164a2fhTnEWb95H23Dm4OuN+92NmEAlTrupP9VW6Jm3sO26tQlqyvyi4CsnY9GA==", + "license": "BSD-2-Clause", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://dotenvx.com" + } + }, + "node_modules/@dotenvx/dotenvx/node_modules/execa": { + "version": "5.1.1", + "resolved": "https://registry.npmjs.org/execa/-/execa-5.1.1.tgz", + "integrity": "sha512-8uSpZZocAZRBAPIEINJj3Lo9HyGitllczc27Eh5YYojjMFMn8yHMDMaUHE2Jqfq05D/wucwI4JGURyXt1vchyg==", + "license": "MIT", + "dependencies": { + "cross-spawn": "^7.0.3", + "get-stream": "^6.0.0", + "human-signals": "^2.1.0", + "is-stream": "^2.0.0", + "merge-stream": "^2.0.0", + "npm-run-path": "^4.0.1", + "onetime": "^5.1.2", + "signal-exit": "^3.0.3", + "strip-final-newline": "^2.0.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sindresorhus/execa?sponsor=1" + } + }, + "node_modules/@dotenvx/dotenvx/node_modules/fdir": { + "version": "6.5.0", + "resolved": "https://registry.npmjs.org/fdir/-/fdir-6.5.0.tgz", + "integrity": "sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg==", + "license": "MIT", + "engines": { + "node": ">=12.0.0" + }, + "peerDependencies": { + "picomatch": "^3 || ^4" + }, + "peerDependenciesMeta": { + "picomatch": { + "optional": true + } + } + }, + "node_modules/@dotenvx/dotenvx/node_modules/get-stream": { + "version": "6.0.1", + "resolved": "https://registry.npmjs.org/get-stream/-/get-stream-6.0.1.tgz", + "integrity": "sha512-ts6Wi+2j3jQjqi70w5AlN8DFnkSwC+MqmxEzdEALB2qXZYV3X/b1CTfgPLGJNMeAWxdPfU8FO1ms3NUfaHCPYg==", + "license": "MIT", + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/@dotenvx/dotenvx/node_modules/human-signals": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/human-signals/-/human-signals-2.1.0.tgz", + "integrity": "sha512-B4FFZ6q/T2jhhksgkbEW3HBvWIfDW85snkQgawt07S7J5QXTk6BkNV+0yAeZrM5QpMAdYlocGoljn0sJ/WQkFw==", + "license": "Apache-2.0", + "engines": { + "node": ">=10.17.0" + } + }, + "node_modules/@dotenvx/dotenvx/node_modules/is-stream": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/is-stream/-/is-stream-2.0.1.tgz", + "integrity": "sha512-hFoiJiTl63nn+kstHGBtewWSKnQLpyb155KHheA1l39uvtO9nWIop1p3udqPcUd/xbF1VLMO4n7OI6p7RbngDg==", + "license": "MIT", + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/@dotenvx/dotenvx/node_modules/isexe": { + "version": "3.1.5", + "resolved": "https://registry.npmjs.org/isexe/-/isexe-3.1.5.tgz", + "integrity": "sha512-6B3tLtFqtQS4ekarvLVMZ+X+VlvQekbe4taUkf/rhVO3d/h0M2rfARm/pXLcPEsjjMsFgrFgSrhQIxcSVrBz8w==", + "license": "BlueOak-1.0.0", + "engines": { + "node": ">=18" + } + }, + "node_modules/@dotenvx/dotenvx/node_modules/npm-run-path": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/npm-run-path/-/npm-run-path-4.0.1.tgz", + "integrity": "sha512-S48WzZW777zhNIrn7gxOlISNAqi9ZC/uQFnRdbeIHhZhCA6UqpkOT8T1G7BvfdgP4Er8gF4sUbaS0i7QvIfCWw==", + "license": "MIT", + "dependencies": { + "path-key": "^3.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/@dotenvx/dotenvx/node_modules/onetime": { + "version": "5.1.2", + "resolved": "https://registry.npmjs.org/onetime/-/onetime-5.1.2.tgz", + "integrity": "sha512-kbpaSSGJTWdAY5KPVeMOKXSrPtr8C8C7wodJbcsd51jRnmD+GZu8Y0VoU6Dm5Z4vWr0Ig/1NKuWRKf7j5aaYSg==", + "license": "MIT", + "dependencies": { + "mimic-fn": "^2.1.0" + }, + "engines": { + "node": ">=6" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/@dotenvx/dotenvx/node_modules/picomatch": { + "version": "4.0.4", + "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.4.tgz", + "integrity": "sha512-QP88BAKvMam/3NxH6vj2o21R6MjxZUAd6nlwAS/pnGvN9IVLocLHxGYIzFhg6fUQ+5th6P4dv4eW9jX3DSIj7A==", + "license": "MIT", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/sponsors/jonschlinkert" + } + }, + "node_modules/@dotenvx/dotenvx/node_modules/signal-exit": { + "version": "3.0.7", + "resolved": "https://registry.npmjs.org/signal-exit/-/signal-exit-3.0.7.tgz", + "integrity": "sha512-wnD2ZE+l+SPC/uoS0vXeE9L1+0wuaMqKlfz9AMUo38JsyLSBWSFcHR1Rri62LZc12vLr1gb3jl7iwQhgwpAbGQ==", + "license": "ISC" + }, + "node_modules/@dotenvx/dotenvx/node_modules/strip-final-newline": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/strip-final-newline/-/strip-final-newline-2.0.0.tgz", + "integrity": "sha512-BrpvfNAE3dcvq7ll3xVumzjKjZQ5tI1sEUIKr3Uoks0XUl45St3FlatVqef9prk4jRDzhW6WZg+3bk93y6pLjA==", + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/@dotenvx/dotenvx/node_modules/which": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/which/-/which-4.0.0.tgz", + "integrity": "sha512-GlaYyEb07DPxYCKhKzplCWBJtvxZcZMrL+4UkrTSJHHPyZU4mYYTv3qaOe77H7EODLSSopAUFAc6W8U4yqvscg==", + "license": "ISC", + "dependencies": { + "isexe": "^3.1.1" + }, + "bin": { + "node-which": "bin/which.js" + }, + "engines": { + "node": "^16.13.0 || >=18.0.0" + } + }, + "node_modules/@ecies/ciphers": { + "version": "0.2.5", + "resolved": "https://registry.npmjs.org/@ecies/ciphers/-/ciphers-0.2.5.tgz", + "integrity": "sha512-GalEZH4JgOMHYYcYmVqnFirFsjZHeoGMDt9IxEnM9F7GRUUyUksJ7Ou53L83WHJq3RWKD3AcBpo0iQh0oMpf8A==", + "license": "MIT", + "engines": { + "bun": ">=1", + "deno": ">=2", + "node": ">=16" + }, + "peerDependencies": { + "@noble/ciphers": "^1.0.0" + } + }, + "node_modules/@electric-sql/pglite": { + "version": "0.4.1", + "resolved": "https://registry.npmjs.org/@electric-sql/pglite/-/pglite-0.4.1.tgz", + "integrity": "sha512-mZ9NzzUSYPOCnxHH1oAHPRzoMFJHY472raDKwXl/+6oPbpdJ7g8LsCN4FSaIIfkiCKHhb3iF/Zqo3NYxaIhU7Q==", + "devOptional": true, + "license": "Apache-2.0" + }, + "node_modules/@electric-sql/pglite-socket": { + "version": "0.1.1", + "resolved": "https://registry.npmjs.org/@electric-sql/pglite-socket/-/pglite-socket-0.1.1.tgz", + "integrity": "sha512-p2hoXw3Z3LQHwTeikdZNsFBOvXGqKY2hk51BBw+8NKND8eoH+8LFOtW9Z8CQKmTJ2qqGYu82ipqiyFZOTTXNfw==", + "devOptional": true, + "license": "Apache-2.0", + "bin": { + "pglite-server": "dist/scripts/server.js" + }, + "peerDependencies": { + "@electric-sql/pglite": "0.4.1" + } + }, + "node_modules/@electric-sql/pglite-tools": { + "version": "0.3.1", + "resolved": "https://registry.npmjs.org/@electric-sql/pglite-tools/-/pglite-tools-0.3.1.tgz", + "integrity": "sha512-C+T3oivmy9bpQvSxVqXA1UDY8cB9Eb9vZHL9zxWwEUfDixbXv4G3r2LjoTdR33LD8aomR3O9ZXEO3XEwr/cUCA==", + "devOptional": true, + "license": "Apache-2.0", + "peerDependencies": { + "@electric-sql/pglite": "0.4.1" + } + }, + "node_modules/@emnapi/core": { + "version": "1.9.0", + "resolved": "https://registry.npmjs.org/@emnapi/core/-/core-1.9.0.tgz", + "integrity": "sha512-0DQ98G9ZQZOxfUcQn1waV2yS8aWdZ6kJMbYCJB3oUBecjWYO1fqJ+a1DRfPF3O5JEkwqwP1A9QEN/9mYm2Yd0w==", + "dev": true, + "license": "MIT", + "optional": true, + "dependencies": { + "@emnapi/wasi-threads": "1.2.0", + "tslib": "^2.4.0" + } + }, + "node_modules/@emnapi/runtime": { + "version": "1.9.0", + "resolved": "https://registry.npmjs.org/@emnapi/runtime/-/runtime-1.9.0.tgz", + "integrity": "sha512-QN75eB0IH2ywSpRpNddCRfQIhmJYBCJ1x5Lb3IscKAL8bMnVAKnRg8dCoXbHzVLLH7P38N2Z3mtulB7W0J0FKw==", + "license": "MIT", + "optional": true, + "dependencies": { + "tslib": "^2.4.0" + } + }, + "node_modules/@emnapi/wasi-threads": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/@emnapi/wasi-threads/-/wasi-threads-1.2.0.tgz", + "integrity": "sha512-N10dEJNSsUx41Z6pZsXU8FjPjpBEplgH24sfkmITrBED1/U2Esum9F3lfLrMjKHHjmi557zQn7kR9R+XWXu5Rg==", + "dev": true, + "license": "MIT", + "optional": true, + "dependencies": { + "tslib": "^2.4.0" + } + }, + "node_modules/@esbuild/aix-ppc64": { + "version": "0.27.4", + "resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.27.4.tgz", + "integrity": "sha512-cQPwL2mp2nSmHHJlCyoXgHGhbEPMrEEU5xhkcy3Hs/O7nGZqEpZ2sUtLaL9MORLtDfRvVl2/3PAuEkYZH0Ty8Q==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "aix" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/android-arm": { + "version": "0.27.4", + "resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.27.4.tgz", + "integrity": "sha512-X9bUgvxiC8CHAGKYufLIHGXPJWnr0OCdR0anD2e21vdvgCI8lIfqFbnoeOz7lBjdrAGUhqLZLcQo6MLhTO2DKQ==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/android-arm64": { + "version": "0.27.4", + "resolved": "https://registry.npmjs.org/@esbuild/android-arm64/-/android-arm64-0.27.4.tgz", + "integrity": "sha512-gdLscB7v75wRfu7QSm/zg6Rx29VLdy9eTr2t44sfTW7CxwAtQghZ4ZnqHk3/ogz7xao0QAgrkradbBzcqFPasw==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/android-x64": { + "version": "0.27.4", + "resolved": "https://registry.npmjs.org/@esbuild/android-x64/-/android-x64-0.27.4.tgz", + "integrity": "sha512-PzPFnBNVF292sfpfhiyiXCGSn9HZg5BcAz+ivBuSsl6Rk4ga1oEXAamhOXRFyMcjwr2DVtm40G65N3GLeH1Lvw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/darwin-arm64": { + "version": "0.27.4", + "resolved": "https://registry.npmjs.org/@esbuild/darwin-arm64/-/darwin-arm64-0.27.4.tgz", + "integrity": "sha512-b7xaGIwdJlht8ZFCvMkpDN6uiSmnxxK56N2GDTMYPr2/gzvfdQN8rTfBsvVKmIVY/X7EM+/hJKEIbbHs9oA4tQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/darwin-x64": { + "version": "0.27.4", + "resolved": "https://registry.npmjs.org/@esbuild/darwin-x64/-/darwin-x64-0.27.4.tgz", + "integrity": "sha512-sR+OiKLwd15nmCdqpXMnuJ9W2kpy0KigzqScqHI3Hqwr7IXxBp3Yva+yJwoqh7rE8V77tdoheRYataNKL4QrPw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/freebsd-arm64": { + "version": "0.27.4", + "resolved": "https://registry.npmjs.org/@esbuild/freebsd-arm64/-/freebsd-arm64-0.27.4.tgz", + "integrity": "sha512-jnfpKe+p79tCnm4GVav68A7tUFeKQwQyLgESwEAUzyxk/TJr4QdGog9sqWNcUbr/bZt/O/HXouspuQDd9JxFSw==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/freebsd-x64": { + "version": "0.27.4", + "resolved": "https://registry.npmjs.org/@esbuild/freebsd-x64/-/freebsd-x64-0.27.4.tgz", + "integrity": "sha512-2kb4ceA/CpfUrIcTUl1wrP/9ad9Atrp5J94Lq69w7UwOMolPIGrfLSvAKJp0RTvkPPyn6CIWrNy13kyLikZRZQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-arm": { + "version": "0.27.4", + "resolved": "https://registry.npmjs.org/@esbuild/linux-arm/-/linux-arm-0.27.4.tgz", + "integrity": "sha512-aBYgcIxX/wd5n2ys0yESGeYMGF+pv6g0DhZr3G1ZG4jMfruU9Tl1i2Z+Wnj9/KjGz1lTLCcorqE2viePZqj4Eg==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-arm64": { + "version": "0.27.4", + "resolved": "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.27.4.tgz", + "integrity": "sha512-7nQOttdzVGth1iz57kxg9uCz57dxQLHWxopL6mYuYthohPKEK0vU0C3O21CcBK6KDlkYVcnDXY099HcCDXd9dA==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-ia32": { + "version": "0.27.4", + "resolved": "https://registry.npmjs.org/@esbuild/linux-ia32/-/linux-ia32-0.27.4.tgz", + "integrity": "sha512-oPtixtAIzgvzYcKBQM/qZ3R+9TEUd1aNJQu0HhGyqtx6oS7qTpvjheIWBbes4+qu1bNlo2V4cbkISr8q6gRBFA==", + "cpu": [ + "ia32" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-loong64": { + "version": "0.27.4", + "resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.27.4.tgz", + "integrity": "sha512-8mL/vh8qeCoRcFH2nM8wm5uJP+ZcVYGGayMavi8GmRJjuI3g1v6Z7Ni0JJKAJW+m0EtUuARb6Lmp4hMjzCBWzA==", + "cpu": [ + "loong64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-mips64el": { + "version": "0.27.4", + "resolved": "https://registry.npmjs.org/@esbuild/linux-mips64el/-/linux-mips64el-0.27.4.tgz", + "integrity": "sha512-1RdrWFFiiLIW7LQq9Q2NES+HiD4NyT8Itj9AUeCl0IVCA459WnPhREKgwrpaIfTOe+/2rdntisegiPWn/r/aAw==", + "cpu": [ + "mips64el" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-ppc64": { + "version": "0.27.4", + "resolved": "https://registry.npmjs.org/@esbuild/linux-ppc64/-/linux-ppc64-0.27.4.tgz", + "integrity": "sha512-tLCwNG47l3sd9lpfyx9LAGEGItCUeRCWeAx6x2Jmbav65nAwoPXfewtAdtbtit/pJFLUWOhpv0FpS6GQAmPrHA==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-riscv64": { + "version": "0.27.4", + "resolved": "https://registry.npmjs.org/@esbuild/linux-riscv64/-/linux-riscv64-0.27.4.tgz", + "integrity": "sha512-BnASypppbUWyqjd1KIpU4AUBiIhVr6YlHx/cnPgqEkNoVOhHg+YiSVxM1RLfiy4t9cAulbRGTNCKOcqHrEQLIw==", + "cpu": [ + "riscv64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-s390x": { + "version": "0.27.4", + "resolved": "https://registry.npmjs.org/@esbuild/linux-s390x/-/linux-s390x-0.27.4.tgz", + "integrity": "sha512-+eUqgb/Z7vxVLezG8bVB9SfBie89gMueS+I0xYh2tJdw3vqA/0ImZJ2ROeWwVJN59ihBeZ7Tu92dF/5dy5FttA==", + "cpu": [ + "s390x" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-x64": { + "version": "0.27.4", + "resolved": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.27.4.tgz", + "integrity": "sha512-S5qOXrKV8BQEzJPVxAwnryi2+Iq5pB40gTEIT69BQONqR7JH1EPIcQ/Uiv9mCnn05jff9umq/5nqzxlqTOg9NA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/netbsd-arm64": { + "version": "0.27.4", + "resolved": "https://registry.npmjs.org/@esbuild/netbsd-arm64/-/netbsd-arm64-0.27.4.tgz", + "integrity": "sha512-xHT8X4sb0GS8qTqiwzHqpY00C95DPAq7nAwX35Ie/s+LO9830hrMd3oX0ZMKLvy7vsonee73x0lmcdOVXFzd6Q==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "netbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/netbsd-x64": { + "version": "0.27.4", + "resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.27.4.tgz", + "integrity": "sha512-RugOvOdXfdyi5Tyv40kgQnI0byv66BFgAqjdgtAKqHoZTbTF2QqfQrFwa7cHEORJf6X2ht+l9ABLMP0dnKYsgg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "netbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/openbsd-arm64": { + "version": "0.27.4", + "resolved": "https://registry.npmjs.org/@esbuild/openbsd-arm64/-/openbsd-arm64-0.27.4.tgz", + "integrity": "sha512-2MyL3IAaTX+1/qP0O1SwskwcwCoOI4kV2IBX1xYnDDqthmq5ArrW94qSIKCAuRraMgPOmG0RDTA74mzYNQA9ow==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/openbsd-x64": { + "version": "0.27.4", + "resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.27.4.tgz", + "integrity": "sha512-u8fg/jQ5aQDfsnIV6+KwLOf1CmJnfu1ShpwqdwC0uA7ZPwFws55Ngc12vBdeUdnuWoQYx/SOQLGDcdlfXhYmXQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/openharmony-arm64": { + "version": "0.27.4", + "resolved": "https://registry.npmjs.org/@esbuild/openharmony-arm64/-/openharmony-arm64-0.27.4.tgz", + "integrity": "sha512-JkTZrl6VbyO8lDQO3yv26nNr2RM2yZzNrNHEsj9bm6dOwwu9OYN28CjzZkH57bh4w0I2F7IodpQvUAEd1mbWXg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openharmony" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/sunos-x64": { + "version": "0.27.4", + "resolved": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.27.4.tgz", + "integrity": "sha512-/gOzgaewZJfeJTlsWhvUEmUG4tWEY2Spp5M20INYRg2ZKl9QPO3QEEgPeRtLjEWSW8FilRNacPOg8R1uaYkA6g==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "sunos" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/win32-arm64": { + "version": "0.27.4", + "resolved": "https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.27.4.tgz", + "integrity": "sha512-Z9SExBg2y32smoDQdf1HRwHRt6vAHLXcxD2uGgO/v2jK7Y718Ix4ndsbNMU/+1Qiem9OiOdaqitioZwxivhXYg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/win32-ia32": { + "version": "0.27.4", + "resolved": "https://registry.npmjs.org/@esbuild/win32-ia32/-/win32-ia32-0.27.4.tgz", + "integrity": "sha512-DAyGLS0Jz5G5iixEbMHi5KdiApqHBWMGzTtMiJ72ZOLhbu/bzxgAe8Ue8CTS3n3HbIUHQz/L51yMdGMeoxXNJw==", + "cpu": [ + "ia32" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/win32-x64": { + "version": "0.27.4", + "resolved": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.27.4.tgz", + "integrity": "sha512-+knoa0BDoeXgkNvvV1vvbZX4+hizelrkwmGJBdT17t8FNPwG2lKemmuMZlmaNQ3ws3DKKCxpb4zRZEIp3UxFCg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@eslint-community/eslint-utils": { + "version": "4.9.1", + "resolved": "https://registry.npmjs.org/@eslint-community/eslint-utils/-/eslint-utils-4.9.1.tgz", + "integrity": "sha512-phrYmNiYppR7znFEdqgfWHXR6NCkZEK7hwWDHZUjit/2/U0r6XvkDl0SYnoM51Hq7FhCGdLDT6zxCCOY1hexsQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "eslint-visitor-keys": "^3.4.3" + }, + "engines": { + "node": "^12.22.0 || ^14.17.0 || >=16.0.0" + }, + "funding": { + "url": "https://opencollective.com/eslint" + }, + "peerDependencies": { + "eslint": "^6.0.0 || ^7.0.0 || >=8.0.0" + } + }, + "node_modules/@eslint-community/eslint-utils/node_modules/eslint-visitor-keys": { + "version": "3.4.3", + "resolved": "https://registry.npmjs.org/eslint-visitor-keys/-/eslint-visitor-keys-3.4.3.tgz", + "integrity": "sha512-wpc+LXeiyiisxPlEkUzU6svyS1frIO3Mgxj1fdy7Pm8Ygzguax2N3Fa/D/ag1WqbOprdI+uY6wMUl8/a2G+iag==", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": "^12.22.0 || ^14.17.0 || >=16.0.0" + }, + "funding": { + "url": "https://opencollective.com/eslint" + } + }, + "node_modules/@eslint-community/regexpp": { + "version": "4.12.2", + "resolved": "https://registry.npmjs.org/@eslint-community/regexpp/-/regexpp-4.12.2.tgz", + "integrity": "sha512-EriSTlt5OC9/7SXkRSCAhfSxxoSUgBm33OH+IkwbdpgoqsSsUg7y3uh+IICI/Qg4BBWr3U2i39RpmycbxMq4ew==", + "dev": true, + "license": "MIT", + "engines": { + "node": "^12.0.0 || ^14.0.0 || >=16.0.0" + } + }, + "node_modules/@eslint/config-array": { + "version": "0.21.2", + "resolved": "https://registry.npmjs.org/@eslint/config-array/-/config-array-0.21.2.tgz", + "integrity": "sha512-nJl2KGTlrf9GjLimgIru+V/mzgSK0ABCDQRvxw5BjURL7WfH5uoWmizbH7QB6MmnMBd8cIC9uceWnezL1VZWWw==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "@eslint/object-schema": "^2.1.7", + "debug": "^4.3.1", + "minimatch": "^3.1.5" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + } + }, + "node_modules/@eslint/config-helpers": { + "version": "0.4.2", + "resolved": "https://registry.npmjs.org/@eslint/config-helpers/-/config-helpers-0.4.2.tgz", + "integrity": "sha512-gBrxN88gOIf3R7ja5K9slwNayVcZgK6SOUORm2uBzTeIEfeVaIhOpCtTox3P6R7o2jLFwLFTLnC7kU/RGcYEgw==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "@eslint/core": "^0.17.0" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + } + }, + "node_modules/@eslint/core": { + "version": "0.17.0", + "resolved": "https://registry.npmjs.org/@eslint/core/-/core-0.17.0.tgz", + "integrity": "sha512-yL/sLrpmtDaFEiUj1osRP4TI2MDz1AddJL+jZ7KSqvBuliN4xqYY54IfdN8qD8Toa6g1iloph1fxQNkjOxrrpQ==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "@types/json-schema": "^7.0.15" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + } + }, + "node_modules/@eslint/eslintrc": { + "version": "3.3.5", + "resolved": "https://registry.npmjs.org/@eslint/eslintrc/-/eslintrc-3.3.5.tgz", + "integrity": "sha512-4IlJx0X0qftVsN5E+/vGujTRIFtwuLbNsVUe7TO6zYPDR1O6nFwvwhIKEKSrl6dZchmYBITazxKoUYOjdtjlRg==", + "dev": true, + "license": "MIT", + "dependencies": { + "ajv": "^6.14.0", + "debug": "^4.3.2", + "espree": "^10.0.1", + "globals": "^14.0.0", + "ignore": "^5.2.0", + "import-fresh": "^3.2.1", + "js-yaml": "^4.1.1", + "minimatch": "^3.1.5", + "strip-json-comments": "^3.1.1" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "url": "https://opencollective.com/eslint" + } + }, + "node_modules/@eslint/js": { + "version": "9.39.4", + "resolved": "https://registry.npmjs.org/@eslint/js/-/js-9.39.4.tgz", + "integrity": "sha512-nE7DEIchvtiFTwBw4Lfbu59PG+kCofhjsKaCWzxTpt4lfRjRMqG6uMBzKXuEcyXhOHoUp9riAm7/aWYGhXZ9cw==", + "dev": true, + "license": "MIT", + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "url": "https://eslint.org/donate" + } + }, + "node_modules/@eslint/object-schema": { + "version": "2.1.7", + "resolved": "https://registry.npmjs.org/@eslint/object-schema/-/object-schema-2.1.7.tgz", + "integrity": "sha512-VtAOaymWVfZcmZbp6E2mympDIHvyjXs/12LqWYjVw6qjrfF+VK+fyG33kChz3nnK+SU5/NeHOqrTEHS8sXO3OA==", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + } + }, + "node_modules/@eslint/plugin-kit": { + "version": "0.4.1", + "resolved": "https://registry.npmjs.org/@eslint/plugin-kit/-/plugin-kit-0.4.1.tgz", + "integrity": "sha512-43/qtrDUokr7LJqoF2c3+RInu/t4zfrpYdoSDfYyhg52rwLV6TnOvdG4fXm7IkSB3wErkcmJS9iEhjVtOSEjjA==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "@eslint/core": "^0.17.0", + "levn": "^0.4.1" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + } + }, + "node_modules/@floating-ui/core": { + "version": "1.7.5", + "resolved": "https://registry.npmjs.org/@floating-ui/core/-/core-1.7.5.tgz", + "integrity": "sha512-1Ih4WTWyw0+lKyFMcBHGbb5U5FtuHJuujoyyr5zTaWS5EYMeT6Jb2AuDeftsCsEuchO+mM2ij5+q9crhydzLhQ==", + "license": "MIT", + "dependencies": { + "@floating-ui/utils": "^0.2.11" + } + }, + "node_modules/@floating-ui/dom": { + "version": "1.7.6", + "resolved": "https://registry.npmjs.org/@floating-ui/dom/-/dom-1.7.6.tgz", + "integrity": "sha512-9gZSAI5XM36880PPMm//9dfiEngYoC6Am2izES1FF406YFsjvyBMmeJ2g4SAju3xWwtuynNRFL2s9hgxpLI5SQ==", + "license": "MIT", + "dependencies": { + "@floating-ui/core": "^1.7.5", + "@floating-ui/utils": "^0.2.11" + } + }, + "node_modules/@floating-ui/react-dom": { + "version": "2.1.8", + "resolved": "https://registry.npmjs.org/@floating-ui/react-dom/-/react-dom-2.1.8.tgz", + "integrity": "sha512-cC52bHwM/n/CxS87FH0yWdngEZrjdtLW/qVruo68qg+prK7ZQ4YGdut2GyDVpoGeAYe/h899rVeOVm6Oi40k2A==", + "license": "MIT", + "dependencies": { + "@floating-ui/dom": "^1.7.6" + }, + "peerDependencies": { + "react": ">=16.8.0", + "react-dom": ">=16.8.0" + } + }, + "node_modules/@floating-ui/utils": { + "version": "0.2.11", + "resolved": "https://registry.npmjs.org/@floating-ui/utils/-/utils-0.2.11.tgz", + "integrity": "sha512-RiB/yIh78pcIxl6lLMG0CgBXAZ2Y0eVHqMPYugu+9U0AeT6YBeiJpf7lbdJNIugFP5SIjwNRgo4DhR1Qxi26Gg==", + "license": "MIT" + }, + "node_modules/@hono/node-server": { + "version": "1.19.12", + "resolved": "https://registry.npmjs.org/@hono/node-server/-/node-server-1.19.12.tgz", + "integrity": "sha512-txsUW4SQ1iilgE0l9/e9VQWmELXifEFvmdA1j6WFh/aFPj99hIntrSsq/if0UWyGVkmrRPKA1wCeP+UCr1B9Uw==", + "license": "MIT", + "engines": { + "node": ">=18.14.1" + }, + "peerDependencies": { + "hono": "^4" + } + }, + "node_modules/@humanfs/core": { + "version": "0.19.1", + "resolved": "https://registry.npmjs.org/@humanfs/core/-/core-0.19.1.tgz", + "integrity": "sha512-5DyQ4+1JEUzejeK1JGICcideyfUbGixgS9jNgex5nqkW+cY7WZhxBigmieN5Qnw9ZosSNVC9KQKyb+GUaGyKUA==", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": ">=18.18.0" + } + }, + "node_modules/@humanfs/node": { + "version": "0.16.7", + "resolved": "https://registry.npmjs.org/@humanfs/node/-/node-0.16.7.tgz", + "integrity": "sha512-/zUx+yOsIrG4Y43Eh2peDeKCxlRt/gET6aHfaKpuq267qXdYDFViVHfMaLyygZOnl0kGWxFIgsBy8QFuTLUXEQ==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "@humanfs/core": "^0.19.1", + "@humanwhocodes/retry": "^0.4.0" + }, + "engines": { + "node": ">=18.18.0" + } + }, + "node_modules/@humanwhocodes/module-importer": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/@humanwhocodes/module-importer/-/module-importer-1.0.1.tgz", + "integrity": "sha512-bxveV4V8v5Yb4ncFTT3rPSgZBOpCkjfK0y4oVVVJwIuDVBRMDXrPyXRL988i5ap9m9bnyEEjWfm5WkBmtffLfA==", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": ">=12.22" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/nzakas" + } + }, + "node_modules/@humanwhocodes/retry": { + "version": "0.4.3", + "resolved": "https://registry.npmjs.org/@humanwhocodes/retry/-/retry-0.4.3.tgz", + "integrity": "sha512-bV0Tgo9K4hfPCek+aMAn81RppFKv2ySDQeMoSZuvTASywNTnVJCArCZE2FWqpvIatKu7VMRLWlR1EazvVhDyhQ==", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": ">=18.18" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/nzakas" + } + }, + "node_modules/@img/colour": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/@img/colour/-/colour-1.1.0.tgz", + "integrity": "sha512-Td76q7j57o/tLVdgS746cYARfSyxk8iEfRxewL9h4OMzYhbW4TAcppl0mT4eyqXddh6L/jwoM75mo7ixa/pCeQ==", + "license": "MIT", + "optional": true, + "engines": { + "node": ">=18" + } + }, + "node_modules/@img/sharp-darwin-arm64": { + "version": "0.34.5", + "resolved": "https://registry.npmjs.org/@img/sharp-darwin-arm64/-/sharp-darwin-arm64-0.34.5.tgz", + "integrity": "sha512-imtQ3WMJXbMY4fxb/Ndp6HBTNVtWCUI0WdobyheGf5+ad6xX8VIDO8u2xE4qc/fr08CKG/7dDseFtn6M6g/r3w==", + "cpu": [ + "arm64" + ], + "license": "Apache-2.0", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": "^18.17.0 || ^20.3.0 || >=21.0.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-darwin-arm64": "1.2.4" + } + }, + "node_modules/@img/sharp-darwin-x64": { + "version": "0.34.5", + "resolved": "https://registry.npmjs.org/@img/sharp-darwin-x64/-/sharp-darwin-x64-0.34.5.tgz", + "integrity": "sha512-YNEFAF/4KQ/PeW0N+r+aVVsoIY0/qxxikF2SWdp+NRkmMB7y9LBZAVqQ4yhGCm/H3H270OSykqmQMKLBhBJDEw==", + "cpu": [ + "x64" + ], + "license": "Apache-2.0", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": "^18.17.0 || ^20.3.0 || >=21.0.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-darwin-x64": "1.2.4" + } + }, + "node_modules/@img/sharp-libvips-darwin-arm64": { + "version": "1.2.4", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-darwin-arm64/-/sharp-libvips-darwin-arm64-1.2.4.tgz", + "integrity": "sha512-zqjjo7RatFfFoP0MkQ51jfuFZBnVE2pRiaydKJ1G/rHZvnsrHAOcQALIi9sA5co5xenQdTugCvtb1cuf78Vf4g==", + "cpu": [ + "arm64" + ], + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "darwin" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-libvips-darwin-x64": { + "version": "1.2.4", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-darwin-x64/-/sharp-libvips-darwin-x64-1.2.4.tgz", + "integrity": "sha512-1IOd5xfVhlGwX+zXv2N93k0yMONvUlANylbJw1eTah8K/Jtpi15KC+WSiaX/nBmbm2HxRM1gZ0nSdjSsrZbGKg==", + "cpu": [ + "x64" + ], + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "darwin" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-libvips-linux-arm": { + "version": "1.2.4", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-arm/-/sharp-libvips-linux-arm-1.2.4.tgz", + "integrity": "sha512-bFI7xcKFELdiNCVov8e44Ia4u2byA+l3XtsAj+Q8tfCwO6BQ8iDojYdvoPMqsKDkuoOo+X6HZA0s0q11ANMQ8A==", + "cpu": [ + "arm" + ], + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "linux" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-libvips-linux-arm64": { + "version": "1.2.4", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-arm64/-/sharp-libvips-linux-arm64-1.2.4.tgz", + "integrity": "sha512-excjX8DfsIcJ10x1Kzr4RcWe1edC9PquDRRPx3YVCvQv+U5p7Yin2s32ftzikXojb1PIFc/9Mt28/y+iRklkrw==", + "cpu": [ + "arm64" + ], + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "linux" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-libvips-linux-ppc64": { + "version": "1.2.4", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-ppc64/-/sharp-libvips-linux-ppc64-1.2.4.tgz", + "integrity": "sha512-FMuvGijLDYG6lW+b/UvyilUWu5Ayu+3r2d1S8notiGCIyYU/76eig1UfMmkZ7vwgOrzKzlQbFSuQfgm7GYUPpA==", + "cpu": [ + "ppc64" + ], + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "linux" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-libvips-linux-riscv64": { + "version": "1.2.4", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-riscv64/-/sharp-libvips-linux-riscv64-1.2.4.tgz", + "integrity": "sha512-oVDbcR4zUC0ce82teubSm+x6ETixtKZBh/qbREIOcI3cULzDyb18Sr/Wcyx7NRQeQzOiHTNbZFF1UwPS2scyGA==", + "cpu": [ + "riscv64" + ], + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "linux" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-libvips-linux-s390x": { + "version": "1.2.4", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-s390x/-/sharp-libvips-linux-s390x-1.2.4.tgz", + "integrity": "sha512-qmp9VrzgPgMoGZyPvrQHqk02uyjA0/QrTO26Tqk6l4ZV0MPWIW6LTkqOIov+J1yEu7MbFQaDpwdwJKhbJvuRxQ==", + "cpu": [ + "s390x" + ], + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "linux" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-libvips-linux-x64": { + "version": "1.2.4", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-x64/-/sharp-libvips-linux-x64-1.2.4.tgz", + "integrity": "sha512-tJxiiLsmHc9Ax1bz3oaOYBURTXGIRDODBqhveVHonrHJ9/+k89qbLl0bcJns+e4t4rvaNBxaEZsFtSfAdquPrw==", + "cpu": [ + "x64" + ], + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "linux" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-libvips-linuxmusl-arm64": { + "version": "1.2.4", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linuxmusl-arm64/-/sharp-libvips-linuxmusl-arm64-1.2.4.tgz", + "integrity": "sha512-FVQHuwx1IIuNow9QAbYUzJ+En8KcVm9Lk5+uGUQJHaZmMECZmOlix9HnH7n1TRkXMS0pGxIJokIVB9SuqZGGXw==", + "cpu": [ + "arm64" + ], + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "linux" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-libvips-linuxmusl-x64": { + "version": "1.2.4", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linuxmusl-x64/-/sharp-libvips-linuxmusl-x64-1.2.4.tgz", + "integrity": "sha512-+LpyBk7L44ZIXwz/VYfglaX/okxezESc6UxDSoyo2Ks6Jxc4Y7sGjpgU9s4PMgqgjj1gZCylTieNamqA1MF7Dg==", + "cpu": [ + "x64" + ], + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "linux" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-linux-arm": { + "version": "0.34.5", + "resolved": "https://registry.npmjs.org/@img/sharp-linux-arm/-/sharp-linux-arm-0.34.5.tgz", + "integrity": "sha512-9dLqsvwtg1uuXBGZKsxem9595+ujv0sJ6Vi8wcTANSFpwV/GONat5eCkzQo/1O6zRIkh0m/8+5BjrRr7jDUSZw==", + "cpu": [ + "arm" + ], + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^18.17.0 || ^20.3.0 || >=21.0.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-linux-arm": "1.2.4" + } + }, + "node_modules/@img/sharp-linux-arm64": { + "version": "0.34.5", + "resolved": "https://registry.npmjs.org/@img/sharp-linux-arm64/-/sharp-linux-arm64-0.34.5.tgz", + "integrity": "sha512-bKQzaJRY/bkPOXyKx5EVup7qkaojECG6NLYswgktOZjaXecSAeCWiZwwiFf3/Y+O1HrauiE3FVsGxFg8c24rZg==", + "cpu": [ + "arm64" + ], + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^18.17.0 || ^20.3.0 || >=21.0.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-linux-arm64": "1.2.4" + } + }, + "node_modules/@img/sharp-linux-ppc64": { + "version": "0.34.5", + "resolved": "https://registry.npmjs.org/@img/sharp-linux-ppc64/-/sharp-linux-ppc64-0.34.5.tgz", + "integrity": "sha512-7zznwNaqW6YtsfrGGDA6BRkISKAAE1Jo0QdpNYXNMHu2+0dTrPflTLNkpc8l7MUP5M16ZJcUvysVWWrMefZquA==", + "cpu": [ + "ppc64" + ], + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^18.17.0 || ^20.3.0 || >=21.0.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-linux-ppc64": "1.2.4" + } + }, + "node_modules/@img/sharp-linux-riscv64": { + "version": "0.34.5", + "resolved": "https://registry.npmjs.org/@img/sharp-linux-riscv64/-/sharp-linux-riscv64-0.34.5.tgz", + "integrity": "sha512-51gJuLPTKa7piYPaVs8GmByo7/U7/7TZOq+cnXJIHZKavIRHAP77e3N2HEl3dgiqdD/w0yUfiJnII77PuDDFdw==", + "cpu": [ + "riscv64" + ], + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^18.17.0 || ^20.3.0 || >=21.0.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-linux-riscv64": "1.2.4" + } + }, + "node_modules/@img/sharp-linux-s390x": { + "version": "0.34.5", + "resolved": "https://registry.npmjs.org/@img/sharp-linux-s390x/-/sharp-linux-s390x-0.34.5.tgz", + "integrity": "sha512-nQtCk0PdKfho3eC5MrbQoigJ2gd1CgddUMkabUj+rBevs8tZ2cULOx46E7oyX+04WGfABgIwmMC0VqieTiR4jg==", + "cpu": [ + "s390x" + ], + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^18.17.0 || ^20.3.0 || >=21.0.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-linux-s390x": "1.2.4" + } + }, + "node_modules/@img/sharp-linux-x64": { + "version": "0.34.5", + "resolved": "https://registry.npmjs.org/@img/sharp-linux-x64/-/sharp-linux-x64-0.34.5.tgz", + "integrity": "sha512-MEzd8HPKxVxVenwAa+JRPwEC7QFjoPWuS5NZnBt6B3pu7EG2Ge0id1oLHZpPJdn3OQK+BQDiw9zStiHBTJQQQQ==", + "cpu": [ + "x64" + ], + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^18.17.0 || ^20.3.0 || >=21.0.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-linux-x64": "1.2.4" + } + }, + "node_modules/@img/sharp-linuxmusl-arm64": { + "version": "0.34.5", + "resolved": "https://registry.npmjs.org/@img/sharp-linuxmusl-arm64/-/sharp-linuxmusl-arm64-0.34.5.tgz", + "integrity": "sha512-fprJR6GtRsMt6Kyfq44IsChVZeGN97gTD331weR1ex1c1rypDEABN6Tm2xa1wE6lYb5DdEnk03NZPqA7Id21yg==", + "cpu": [ + "arm64" + ], + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^18.17.0 || ^20.3.0 || >=21.0.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-linuxmusl-arm64": "1.2.4" + } + }, + "node_modules/@img/sharp-linuxmusl-x64": { + "version": "0.34.5", + "resolved": "https://registry.npmjs.org/@img/sharp-linuxmusl-x64/-/sharp-linuxmusl-x64-0.34.5.tgz", + "integrity": "sha512-Jg8wNT1MUzIvhBFxViqrEhWDGzqymo3sV7z7ZsaWbZNDLXRJZoRGrjulp60YYtV4wfY8VIKcWidjojlLcWrd8Q==", + "cpu": [ + "x64" + ], + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^18.17.0 || ^20.3.0 || >=21.0.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-linuxmusl-x64": "1.2.4" + } + }, + "node_modules/@img/sharp-wasm32": { + "version": "0.34.5", + "resolved": "https://registry.npmjs.org/@img/sharp-wasm32/-/sharp-wasm32-0.34.5.tgz", + "integrity": "sha512-OdWTEiVkY2PHwqkbBI8frFxQQFekHaSSkUIJkwzclWZe64O1X4UlUjqqqLaPbUpMOQk6FBu/HtlGXNblIs0huw==", + "cpu": [ + "wasm32" + ], + "license": "Apache-2.0 AND LGPL-3.0-or-later AND MIT", + "optional": true, + "dependencies": { + "@emnapi/runtime": "^1.7.0" + }, + "engines": { + "node": "^18.17.0 || ^20.3.0 || >=21.0.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-win32-arm64": { + "version": "0.34.5", + "resolved": "https://registry.npmjs.org/@img/sharp-win32-arm64/-/sharp-win32-arm64-0.34.5.tgz", + "integrity": "sha512-WQ3AgWCWYSb2yt+IG8mnC6Jdk9Whs7O0gxphblsLvdhSpSTtmu69ZG1Gkb6NuvxsNACwiPV6cNSZNzt0KPsw7g==", + "cpu": [ + "arm64" + ], + "license": "Apache-2.0 AND LGPL-3.0-or-later", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": "^18.17.0 || ^20.3.0 || >=21.0.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-win32-ia32": { + "version": "0.34.5", + "resolved": "https://registry.npmjs.org/@img/sharp-win32-ia32/-/sharp-win32-ia32-0.34.5.tgz", + "integrity": "sha512-FV9m/7NmeCmSHDD5j4+4pNI8Cp3aW+JvLoXcTUo0IqyjSfAZJ8dIUmijx1qaJsIiU+Hosw6xM5KijAWRJCSgNg==", + "cpu": [ + "ia32" + ], + "license": "Apache-2.0 AND LGPL-3.0-or-later", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": "^18.17.0 || ^20.3.0 || >=21.0.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-win32-x64": { + "version": "0.34.5", + "resolved": "https://registry.npmjs.org/@img/sharp-win32-x64/-/sharp-win32-x64-0.34.5.tgz", + "integrity": "sha512-+29YMsqY2/9eFEiW93eqWnuLcWcufowXewwSNIT6UwZdUUCrM3oFjMWH/Z6/TMmb4hlFenmfAVbpWeup2jryCw==", + "cpu": [ + "x64" + ], + "license": "Apache-2.0 AND LGPL-3.0-or-later", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": "^18.17.0 || ^20.3.0 || >=21.0.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@inquirer/ansi": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/@inquirer/ansi/-/ansi-1.0.2.tgz", + "integrity": "sha512-S8qNSZiYzFd0wAcyG5AXCvUHC5Sr7xpZ9wZ2py9XR88jUz8wooStVx5M6dRzczbBWjic9NP7+rY0Xi7qqK/aMQ==", + "license": "MIT", + "engines": { + "node": ">=18" + } + }, + "node_modules/@inquirer/confirm": { + "version": "5.1.21", + "resolved": "https://registry.npmjs.org/@inquirer/confirm/-/confirm-5.1.21.tgz", + "integrity": "sha512-KR8edRkIsUayMXV+o3Gv+q4jlhENF9nMYUZs9PA2HzrXeHI8M5uDag70U7RJn9yyiMZSbtF5/UexBtAVtZGSbQ==", + "license": "MIT", + "dependencies": { + "@inquirer/core": "^10.3.2", + "@inquirer/type": "^3.0.10" + }, + "engines": { + "node": ">=18" + }, + "peerDependencies": { + "@types/node": ">=18" + }, + "peerDependenciesMeta": { + "@types/node": { + "optional": true + } + } + }, + "node_modules/@inquirer/core": { + "version": "10.3.2", + "resolved": "https://registry.npmjs.org/@inquirer/core/-/core-10.3.2.tgz", + "integrity": "sha512-43RTuEbfP8MbKzedNqBrlhhNKVwoK//vUFNW3Q3vZ88BLcrs4kYpGg+B2mm5p2K/HfygoCxuKwJJiv8PbGmE0A==", + "license": "MIT", + "dependencies": { + "@inquirer/ansi": "^1.0.2", + "@inquirer/figures": "^1.0.15", + "@inquirer/type": "^3.0.10", + "cli-width": "^4.1.0", + "mute-stream": "^2.0.0", + "signal-exit": "^4.1.0", + "wrap-ansi": "^6.2.0", + "yoctocolors-cjs": "^2.1.3" + }, + "engines": { + "node": ">=18" + }, + "peerDependencies": { + "@types/node": ">=18" + }, + "peerDependenciesMeta": { + "@types/node": { + "optional": true + } + } + }, + "node_modules/@inquirer/figures": { + "version": "1.0.15", + "resolved": "https://registry.npmjs.org/@inquirer/figures/-/figures-1.0.15.tgz", + "integrity": "sha512-t2IEY+unGHOzAaVM5Xx6DEWKeXlDDcNPeDyUpsRc6CUhBfU3VQOEl+Vssh7VNp1dR8MdUJBWhuObjXCsVpjN5g==", + "license": "MIT", + "engines": { + "node": ">=18" + } + }, + "node_modules/@inquirer/type": { + "version": "3.0.10", + "resolved": "https://registry.npmjs.org/@inquirer/type/-/type-3.0.10.tgz", + "integrity": "sha512-BvziSRxfz5Ov8ch0z/n3oijRSEcEsHnhggm4xFZe93DHcUCTlutlq9Ox4SVENAfcRD22UQq7T/atg9Wr3k09eA==", + "license": "MIT", + "engines": { + "node": ">=18" + }, + "peerDependencies": { + "@types/node": ">=18" + }, + "peerDependenciesMeta": { + "@types/node": { + "optional": true + } + } + }, + "node_modules/@ionic/cli-framework-output": { + "version": "2.2.8", + "resolved": "https://registry.npmjs.org/@ionic/cli-framework-output/-/cli-framework-output-2.2.8.tgz", + "integrity": "sha512-TshtaFQsovB4NWRBydbNFawql6yul7d5bMiW1WYYf17hd99V6xdDdk3vtF51bw6sLkxON3bDQpWsnUc9/hVo3g==", + "license": "MIT", + "dependencies": { + "@ionic/utils-terminal": "2.3.5", + "debug": "^4.0.0", + "tslib": "^2.0.1" + }, + "engines": { + "node": ">=16.0.0" + } + }, + "node_modules/@ionic/utils-array": { + "version": "2.1.6", + "resolved": "https://registry.npmjs.org/@ionic/utils-array/-/utils-array-2.1.6.tgz", + "integrity": "sha512-0JZ1Zkp3wURnv8oq6Qt7fMPo5MpjbLoUoa9Bu2Q4PJuSDWM8H8gwF3dQO7VTeUj3/0o1IB1wGkFWZZYgUXZMUg==", + "license": "MIT", + "dependencies": { + "debug": "^4.0.0", + "tslib": "^2.0.1" + }, + "engines": { + "node": ">=16.0.0" + } + }, + "node_modules/@ionic/utils-fs": { + "version": "3.1.7", + "resolved": "https://registry.npmjs.org/@ionic/utils-fs/-/utils-fs-3.1.7.tgz", + "integrity": "sha512-2EknRvMVfhnyhL1VhFkSLa5gOcycK91VnjfrTB0kbqkTFCOXyXgVLI5whzq7SLrgD9t1aqos3lMMQyVzaQ5gVA==", + "license": "MIT", + "dependencies": { + "@types/fs-extra": "^8.0.0", + "debug": "^4.0.0", + "fs-extra": "^9.0.0", + "tslib": "^2.0.1" + }, + "engines": { + "node": ">=16.0.0" + } + }, + "node_modules/@ionic/utils-fs/node_modules/fs-extra": { + "version": "9.1.0", + "resolved": "https://registry.npmjs.org/fs-extra/-/fs-extra-9.1.0.tgz", + "integrity": "sha512-hcg3ZmepS30/7BSFqRvoo3DOMQu7IjqxO5nCDt+zM9XWjb33Wg7ziNT+Qvqbuc3+gWpzO02JubVyk2G4Zvo1OQ==", + "license": "MIT", + "dependencies": { + "at-least-node": "^1.0.0", + "graceful-fs": "^4.2.0", + "jsonfile": "^6.0.1", + "universalify": "^2.0.0" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/@ionic/utils-object": { + "version": "2.1.6", + "resolved": "https://registry.npmjs.org/@ionic/utils-object/-/utils-object-2.1.6.tgz", + "integrity": "sha512-vCl7sl6JjBHFw99CuAqHljYJpcE88YaH2ZW4ELiC/Zwxl5tiwn4kbdP/gxi2OT3MQb1vOtgAmSNRtusvgxI8ww==", + "license": "MIT", + "dependencies": { + "debug": "^4.0.0", + "tslib": "^2.0.1" + }, + "engines": { + "node": ">=16.0.0" + } + }, + "node_modules/@ionic/utils-process": { + "version": "2.1.12", + "resolved": "https://registry.npmjs.org/@ionic/utils-process/-/utils-process-2.1.12.tgz", + "integrity": "sha512-Jqkgyq7zBs/v/J3YvKtQQiIcxfJyplPgECMWgdO0E1fKrrH8EF0QGHNJ9mJCn6PYe2UtHNS8JJf5G21e09DfYg==", + "license": "MIT", + "dependencies": { + "@ionic/utils-object": "2.1.6", + "@ionic/utils-terminal": "2.3.5", + "debug": "^4.0.0", + "signal-exit": "^3.0.3", + "tree-kill": "^1.2.2", + "tslib": "^2.0.1" + }, + "engines": { + "node": ">=16.0.0" + } + }, + "node_modules/@ionic/utils-process/node_modules/signal-exit": { + "version": "3.0.7", + "resolved": "https://registry.npmjs.org/signal-exit/-/signal-exit-3.0.7.tgz", + "integrity": "sha512-wnD2ZE+l+SPC/uoS0vXeE9L1+0wuaMqKlfz9AMUo38JsyLSBWSFcHR1Rri62LZc12vLr1gb3jl7iwQhgwpAbGQ==", + "license": "ISC" + }, + "node_modules/@ionic/utils-stream": { + "version": "3.1.7", + "resolved": "https://registry.npmjs.org/@ionic/utils-stream/-/utils-stream-3.1.7.tgz", + "integrity": "sha512-eSELBE7NWNFIHTbTC2jiMvh1ABKGIpGdUIvARsNPMNQhxJB3wpwdiVnoBoTYp+5a6UUIww4Kpg7v6S7iTctH1w==", + "license": "MIT", + "dependencies": { + "debug": "^4.0.0", + "tslib": "^2.0.1" + }, + "engines": { + "node": ">=16.0.0" + } + }, + "node_modules/@ionic/utils-subprocess": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/@ionic/utils-subprocess/-/utils-subprocess-3.0.1.tgz", + "integrity": "sha512-cT4te3AQQPeIM9WCwIg8ohroJ8TjsYaMb2G4ZEgv9YzeDqHZ4JpeIKqG2SoaA3GmVQ3sOfhPM6Ox9sxphV/d1A==", + "license": "MIT", + "dependencies": { + "@ionic/utils-array": "2.1.6", + "@ionic/utils-fs": "3.1.7", + "@ionic/utils-process": "2.1.12", + "@ionic/utils-stream": "3.1.7", + "@ionic/utils-terminal": "2.3.5", + "cross-spawn": "^7.0.3", + "debug": "^4.0.0", + "tslib": "^2.0.1" + }, + "engines": { + "node": ">=16.0.0" + } + }, + "node_modules/@ionic/utils-terminal": { + "version": "2.3.5", + "resolved": "https://registry.npmjs.org/@ionic/utils-terminal/-/utils-terminal-2.3.5.tgz", + "integrity": "sha512-3cKScz9Jx2/Pr9ijj1OzGlBDfcmx7OMVBt4+P1uRR0SSW4cm1/y3Mo4OY3lfkuaYifMNBW8Wz6lQHbs1bihr7A==", + "license": "MIT", + "dependencies": { + "@types/slice-ansi": "^4.0.0", + "debug": "^4.0.0", + "signal-exit": "^3.0.3", + "slice-ansi": "^4.0.0", + "string-width": "^4.1.0", + "strip-ansi": "^6.0.0", + "tslib": "^2.0.1", + "untildify": "^4.0.0", + "wrap-ansi": "^7.0.0" + }, + "engines": { + "node": ">=16.0.0" + } + }, + "node_modules/@ionic/utils-terminal/node_modules/ansi-regex": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz", + "integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==", + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/@ionic/utils-terminal/node_modules/emoji-regex": { + "version": "8.0.0", + "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-8.0.0.tgz", + "integrity": "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A==", + "license": "MIT" + }, + "node_modules/@ionic/utils-terminal/node_modules/signal-exit": { + "version": "3.0.7", + "resolved": "https://registry.npmjs.org/signal-exit/-/signal-exit-3.0.7.tgz", + "integrity": "sha512-wnD2ZE+l+SPC/uoS0vXeE9L1+0wuaMqKlfz9AMUo38JsyLSBWSFcHR1Rri62LZc12vLr1gb3jl7iwQhgwpAbGQ==", + "license": "ISC" + }, + "node_modules/@ionic/utils-terminal/node_modules/string-width": { + "version": "4.2.3", + "resolved": "https://registry.npmjs.org/string-width/-/string-width-4.2.3.tgz", + "integrity": "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g==", + "license": "MIT", + "dependencies": { + "emoji-regex": "^8.0.0", + "is-fullwidth-code-point": "^3.0.0", + "strip-ansi": "^6.0.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/@ionic/utils-terminal/node_modules/strip-ansi": { + "version": "6.0.1", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz", + "integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==", + "license": "MIT", + "dependencies": { + "ansi-regex": "^5.0.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/@ionic/utils-terminal/node_modules/wrap-ansi": { + "version": "7.0.0", + "resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-7.0.0.tgz", + "integrity": "sha512-YVGIj2kamLSTxw6NsZjoBxfSwsn0ycdesmc4p+Q21c5zPuZ1pl+NfxVdxPtdHvmNVOQ6XSYG4AUtyt/Fi7D16Q==", + "license": "MIT", + "dependencies": { + "ansi-styles": "^4.0.0", + "string-width": "^4.1.0", + "strip-ansi": "^6.0.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/chalk/wrap-ansi?sponsor=1" + } + }, + "node_modules/@isaacs/fs-minipass": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/@isaacs/fs-minipass/-/fs-minipass-4.0.1.tgz", + "integrity": "sha512-wgm9Ehl2jpeqP3zw/7mo3kRHFp5MEDhqAdwy1fTGkHAwnkGOVsgpvQhL8B5n1qlb01jV3n/bI0ZfZp5lWA1k4w==", + "license": "ISC", + "dependencies": { + "minipass": "^7.0.4" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@jridgewell/gen-mapping": { + "version": "0.3.13", + "resolved": "https://registry.npmjs.org/@jridgewell/gen-mapping/-/gen-mapping-0.3.13.tgz", + "integrity": "sha512-2kkt/7niJ6MgEPxF0bYdQ6etZaA+fQvDcLKckhy1yIQOzaoKjBBjSj63/aLVjYE3qhRt5dvM+uUyfCg6UKCBbA==", + "license": "MIT", + "dependencies": { + "@jridgewell/sourcemap-codec": "^1.5.0", + "@jridgewell/trace-mapping": "^0.3.24" + } + }, + "node_modules/@jridgewell/remapping": { + "version": "2.3.5", + "resolved": "https://registry.npmjs.org/@jridgewell/remapping/-/remapping-2.3.5.tgz", + "integrity": "sha512-LI9u/+laYG4Ds1TDKSJW2YPrIlcVYOwi2fUC6xB43lueCjgxV4lffOCZCtYFiH6TNOX+tQKXx97T4IKHbhyHEQ==", + "license": "MIT", + "dependencies": { + "@jridgewell/gen-mapping": "^0.3.5", + "@jridgewell/trace-mapping": "^0.3.24" + } + }, + "node_modules/@jridgewell/resolve-uri": { + "version": "3.1.2", + "resolved": "https://registry.npmjs.org/@jridgewell/resolve-uri/-/resolve-uri-3.1.2.tgz", + "integrity": "sha512-bRISgCIjP20/tbWSPWMEi54QVPRZExkuD9lJL+UIxUKtwVJA8wW1Trb1jMs1RFXo1CBTNZ/5hpC9QvmKWdopKw==", + "license": "MIT", + "engines": { + "node": ">=6.0.0" + } + }, + "node_modules/@jridgewell/sourcemap-codec": { + "version": "1.5.5", + "resolved": "https://registry.npmjs.org/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.5.5.tgz", + "integrity": "sha512-cYQ9310grqxueWbl+WuIUIaiUaDcj7WOq5fVhEljNVgRfOUhY9fy2zTvfoqWsnebh8Sl70VScFbICvJnLKB0Og==", + "license": "MIT" + }, + "node_modules/@jridgewell/trace-mapping": { + "version": "0.3.31", + "resolved": "https://registry.npmjs.org/@jridgewell/trace-mapping/-/trace-mapping-0.3.31.tgz", + "integrity": "sha512-zzNR+SdQSDJzc8joaeP8QQoCQr8NuYx2dIIytl1QeBEZHJ9uW6hebsrYgbz8hJwUQao3TWCMtmfV8Nu1twOLAw==", + "license": "MIT", + "dependencies": { + "@jridgewell/resolve-uri": "^3.1.0", + "@jridgewell/sourcemap-codec": "^1.4.14" + } + }, + "node_modules/@kurkle/color": { + "version": "0.3.4", + "resolved": "https://registry.npmjs.org/@kurkle/color/-/color-0.3.4.tgz", + "integrity": "sha512-M5UknZPHRu3DEDWoipU6sE8PdkZ6Z/S+v4dD+Ke8IaNlpdSQah50lz1KtcFBa2vsdOnwbbnxJwVM4wty6udA5w==", + "devOptional": true, + "license": "MIT" + }, + "node_modules/@libsql/client": { + "version": "0.17.0", + "resolved": "https://registry.npmjs.org/@libsql/client/-/client-0.17.0.tgz", + "integrity": "sha512-TLjSU9Otdpq0SpKHl1tD1Nc9MKhrsZbCFGot3EbCxRa8m1E5R1mMwoOjKMMM31IyF7fr+hPNHLpYfwbMKNusmg==", + "license": "MIT", + "dependencies": { + "@libsql/core": "^0.17.0", + "@libsql/hrana-client": "^0.9.0", + "js-base64": "^3.7.5", + "libsql": "^0.5.22", + "promise-limit": "^2.7.0" + } + }, + "node_modules/@libsql/core": { + "version": "0.17.0", + "resolved": "https://registry.npmjs.org/@libsql/core/-/core-0.17.0.tgz", + "integrity": "sha512-hnZRnJHiS+nrhHKLGYPoJbc78FE903MSDrFJTbftxo+e52X+E0Y0fHOCVYsKWcg6XgB7BbJYUrz/xEkVTSaipw==", + "license": "MIT", + "dependencies": { + "js-base64": "^3.7.5" + } + }, + "node_modules/@libsql/darwin-arm64": { + "version": "0.5.22", + "resolved": "https://registry.npmjs.org/@libsql/darwin-arm64/-/darwin-arm64-0.5.22.tgz", + "integrity": "sha512-4B8ZlX3nIDPndfct7GNe0nI3Yw6ibocEicWdC4fvQbSs/jdq/RC2oCsoJxJ4NzXkvktX70C1J4FcmmoBy069UA==", + "cpu": [ + "arm64" + ], + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ] + }, + "node_modules/@libsql/darwin-x64": { + "version": "0.5.22", + "resolved": "https://registry.npmjs.org/@libsql/darwin-x64/-/darwin-x64-0.5.22.tgz", + "integrity": "sha512-ny2HYWt6lFSIdNFzUFIJ04uiW6finXfMNJ7wypkAD8Pqdm6nAByO+Fdqu8t7sD0sqJGeUCiOg480icjyQ2/8VA==", + "cpu": [ + "x64" + ], + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ] + }, + "node_modules/@libsql/hrana-client": { + "version": "0.9.0", + "resolved": "https://registry.npmjs.org/@libsql/hrana-client/-/hrana-client-0.9.0.tgz", + "integrity": "sha512-pxQ1986AuWfPX4oXzBvLwBnfgKDE5OMhAdR/5cZmRaB4Ygz5MecQybvwZupnRz341r2CtFmbk/BhSu7k2Lm+Jw==", + "license": "MIT", + "dependencies": { + "@libsql/isomorphic-ws": "^0.1.5", + "cross-fetch": "^4.0.0", + "js-base64": "^3.7.5", + "node-fetch": "^3.3.2" + } + }, + "node_modules/@libsql/isomorphic-ws": { + "version": "0.1.5", + "resolved": "https://registry.npmjs.org/@libsql/isomorphic-ws/-/isomorphic-ws-0.1.5.tgz", + "integrity": "sha512-DtLWIH29onUYR00i0GlQ3UdcTRC6EP4u9w/h9LxpUZJWRMARk6dQwZ6Jkd+QdwVpuAOrdxt18v0K2uIYR3fwFg==", + "license": "MIT", + "dependencies": { + "@types/ws": "^8.5.4", + "ws": "^8.13.0" + } + }, + "node_modules/@libsql/linux-arm-gnueabihf": { + "version": "0.5.22", + "resolved": "https://registry.npmjs.org/@libsql/linux-arm-gnueabihf/-/linux-arm-gnueabihf-0.5.22.tgz", + "integrity": "sha512-3Uo3SoDPJe/zBnyZKosziRGtszXaEtv57raWrZIahtQDsjxBVjuzYQinCm9LRCJCUT5t2r5Z5nLDPJi2CwZVoA==", + "cpu": [ + "arm" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@libsql/linux-arm-musleabihf": { + "version": "0.5.22", + "resolved": "https://registry.npmjs.org/@libsql/linux-arm-musleabihf/-/linux-arm-musleabihf-0.5.22.tgz", + "integrity": "sha512-LCsXh07jvSojTNJptT9CowOzwITznD+YFGGW+1XxUr7fS+7/ydUrpDfsMX7UqTqjm7xG17eq86VkWJgHJfvpNg==", + "cpu": [ + "arm" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@libsql/linux-arm64-gnu": { + "version": "0.5.22", + "resolved": "https://registry.npmjs.org/@libsql/linux-arm64-gnu/-/linux-arm64-gnu-0.5.22.tgz", + "integrity": "sha512-KSdnOMy88c9mpOFKUEzPskSaF3VLflfSUCBwas/pn1/sV3pEhtMF6H8VUCd2rsedwoukeeCSEONqX7LLnQwRMA==", + "cpu": [ + "arm64" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@libsql/linux-arm64-musl": { + "version": "0.5.22", + "resolved": "https://registry.npmjs.org/@libsql/linux-arm64-musl/-/linux-arm64-musl-0.5.22.tgz", + "integrity": "sha512-mCHSMAsDTLK5YH//lcV3eFEgiR23Ym0U9oEvgZA0667gqRZg/2px+7LshDvErEKv2XZ8ixzw3p1IrBzLQHGSsw==", + "cpu": [ + "arm64" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@libsql/linux-x64-gnu": { + "version": "0.5.22", + "resolved": "https://registry.npmjs.org/@libsql/linux-x64-gnu/-/linux-x64-gnu-0.5.22.tgz", + "integrity": "sha512-kNBHaIkSg78Y4BqAdgjcR2mBilZXs4HYkAmi58J+4GRwDQZh5fIUWbnQvB9f95DkWUIGVeenqLRFY2pcTmlsew==", + "cpu": [ + "x64" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@libsql/linux-x64-musl": { + "version": "0.5.22", + "resolved": "https://registry.npmjs.org/@libsql/linux-x64-musl/-/linux-x64-musl-0.5.22.tgz", + "integrity": "sha512-UZ4Xdxm4pu3pQXjvfJiyCzZop/9j/eA2JjmhMaAhe3EVLH2g11Fy4fwyUp9sT1QJYR1kpc2JLuybPM0kuXv/Tg==", + "cpu": [ + "x64" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@libsql/win32-x64-msvc": { + "version": "0.5.22", + "resolved": "https://registry.npmjs.org/@libsql/win32-x64-msvc/-/win32-x64-msvc-0.5.22.tgz", + "integrity": "sha512-Fj0j8RnBpo43tVZUVoNK6BV/9AtDUM5S7DF3LB4qTYg1LMSZqi3yeCneUTLJD6XomQJlZzbI4mst89yspVSAnA==", + "cpu": [ + "x64" + ], + "license": "MIT", + "optional": true, + "os": [ + "win32" + ] + }, + "node_modules/@modelcontextprotocol/sdk": { + "version": "1.27.1", + "resolved": "https://registry.npmjs.org/@modelcontextprotocol/sdk/-/sdk-1.27.1.tgz", + "integrity": "sha512-sr6GbP+4edBwFndLbM60gf07z0FQ79gaExpnsjMGePXqFcSSb7t6iscpjk9DhFhwd+mTEQrzNafGP8/iGGFYaA==", + "license": "MIT", + "dependencies": { + "@hono/node-server": "^1.19.9", + "ajv": "^8.17.1", + "ajv-formats": "^3.0.1", + "content-type": "^1.0.5", + "cors": "^2.8.5", + "cross-spawn": "^7.0.5", + "eventsource": "^3.0.2", + "eventsource-parser": "^3.0.0", + "express": "^5.2.1", + "express-rate-limit": "^8.2.1", + "hono": "^4.11.4", + "jose": "^6.1.3", + "json-schema-typed": "^8.0.2", + "pkce-challenge": "^5.0.0", + "raw-body": "^3.0.0", + "zod": "^3.25 || ^4.0", + "zod-to-json-schema": "^3.25.1" + }, + "engines": { + "node": ">=18" + }, + "peerDependencies": { + "@cfworker/json-schema": "^4.1.1", + "zod": "^3.25 || ^4.0" + }, + "peerDependenciesMeta": { + "@cfworker/json-schema": { + "optional": true + }, + "zod": { + "optional": false + } + } + }, + "node_modules/@modelcontextprotocol/sdk/node_modules/ajv": { + "version": "8.18.0", + "resolved": "https://registry.npmjs.org/ajv/-/ajv-8.18.0.tgz", + "integrity": "sha512-PlXPeEWMXMZ7sPYOHqmDyCJzcfNrUr3fGNKtezX14ykXOEIvyK81d+qydx89KY5O71FKMPaQ2vBfBFI5NHR63A==", + "license": "MIT", + "dependencies": { + "fast-deep-equal": "^3.1.3", + "fast-uri": "^3.0.1", + "json-schema-traverse": "^1.0.0", + "require-from-string": "^2.0.2" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/epoberezkin" + } + }, + "node_modules/@modelcontextprotocol/sdk/node_modules/json-schema-traverse": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-1.0.0.tgz", + "integrity": "sha512-NM8/P9n3XjXhIZn1lLhkFaACTOURQXjWhV4BA/RnOv8xvgqtqpAX9IO4mRQxSx1Rlo4tqzeqb0sOlruaOy3dug==", + "license": "MIT" + }, + "node_modules/@mswjs/interceptors": { + "version": "0.41.3", + "resolved": "https://registry.npmjs.org/@mswjs/interceptors/-/interceptors-0.41.3.tgz", + "integrity": "sha512-cXu86tF4VQVfwz8W1SPbhoRyHJkti6mjH/XJIxp40jhO4j2k1m4KYrEykxqWPkFF3vrK4rgQppBh//AwyGSXPA==", + "license": "MIT", + "dependencies": { + "@open-draft/deferred-promise": "^2.2.0", + "@open-draft/logger": "^0.3.0", + "@open-draft/until": "^2.0.0", + "is-node-process": "^1.2.0", + "outvariant": "^1.4.3", + "strict-event-emitter": "^0.5.1" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/@napi-rs/wasm-runtime": { + "version": "0.2.12", + "resolved": "https://registry.npmjs.org/@napi-rs/wasm-runtime/-/wasm-runtime-0.2.12.tgz", + "integrity": "sha512-ZVWUcfwY4E/yPitQJl481FjFo3K22D6qF0DuFH6Y/nbnE11GY5uguDxZMGXPQ8WQ0128MXQD7TnfHyK4oWoIJQ==", + "dev": true, + "license": "MIT", + "optional": true, + "dependencies": { + "@emnapi/core": "^1.4.3", + "@emnapi/runtime": "^1.4.3", + "@tybys/wasm-util": "^0.10.0" + } + }, + "node_modules/@neon-rs/load": { + "version": "0.0.4", + "resolved": "https://registry.npmjs.org/@neon-rs/load/-/load-0.0.4.tgz", + "integrity": "sha512-kTPhdZyTQxB+2wpiRcFWrDcejc4JI6tkPuS7UZCG4l6Zvc5kU/gGQ/ozvHTh1XR5tS+UlfAfGuPajjzQjCiHCw==", + "license": "MIT" + }, + "node_modules/@next/env": { + "version": "16.1.7", + "resolved": "https://registry.npmjs.org/@next/env/-/env-16.1.7.tgz", + "integrity": "sha512-rJJbIdJB/RQr2F1nylZr/PJzamvNNhfr3brdKP6s/GW850jbtR70QlSfFselvIBbcPUOlQwBakexjFzqLzF6pg==", + "license": "MIT" + }, + "node_modules/@next/eslint-plugin-next": { + "version": "16.1.7", + "resolved": "https://registry.npmjs.org/@next/eslint-plugin-next/-/eslint-plugin-next-16.1.7.tgz", + "integrity": "sha512-v/bRGOJlfRCO+NDKt0bZlIIWjhMKU8xbgEQBo+rV9C8S6czZvs96LZ/v24/GvpEnovZlL4QDpku/RzWHVbmPpA==", + "dev": true, + "license": "MIT", + "dependencies": { + "fast-glob": "3.3.1" + } + }, + "node_modules/@next/swc-darwin-arm64": { + "version": "16.1.7", + "resolved": "https://registry.npmjs.org/@next/swc-darwin-arm64/-/swc-darwin-arm64-16.1.7.tgz", + "integrity": "sha512-b2wWIE8sABdyafc4IM8r5Y/dS6kD80JRtOGrUiKTsACFQfWWgUQ2NwoUX1yjFMXVsAwcQeNpnucF2ZrujsBBPg==", + "cpu": [ + "arm64" + ], + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">= 10" + } + }, + "node_modules/@next/swc-darwin-x64": { + "version": "16.1.7", + "resolved": "https://registry.npmjs.org/@next/swc-darwin-x64/-/swc-darwin-x64-16.1.7.tgz", + "integrity": "sha512-zcnVaaZulS1WL0Ss38R5Q6D2gz7MtBu8GZLPfK+73D/hp4GFMrC2sudLky1QibfV7h6RJBJs/gOFvYP0X7UVlQ==", + "cpu": [ + "x64" + ], + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">= 10" + } + }, + "node_modules/@next/swc-linux-arm64-gnu": { + "version": "16.1.7", + "resolved": "https://registry.npmjs.org/@next/swc-linux-arm64-gnu/-/swc-linux-arm64-gnu-16.1.7.tgz", + "integrity": "sha512-2ant89Lux/Q3VyC8vNVg7uBaFVP9SwoK2jJOOR0L8TQnX8CAYnh4uctAScy2Hwj2dgjVHqHLORQZJ2wH6VxhSQ==", + "cpu": [ + "arm64" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 10" + } + }, + "node_modules/@next/swc-linux-arm64-musl": { + "version": "16.1.7", + "resolved": "https://registry.npmjs.org/@next/swc-linux-arm64-musl/-/swc-linux-arm64-musl-16.1.7.tgz", + "integrity": "sha512-uufcze7LYv0FQg9GnNeZ3/whYfo+1Q3HnQpm16o6Uyi0OVzLlk2ZWoY7j07KADZFY8qwDbsmFnMQP3p3+Ftprw==", + "cpu": [ + "arm64" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 10" + } + }, + "node_modules/@next/swc-linux-x64-gnu": { + "version": "16.1.7", + "resolved": "https://registry.npmjs.org/@next/swc-linux-x64-gnu/-/swc-linux-x64-gnu-16.1.7.tgz", + "integrity": "sha512-KWVf2gxYvHtvuT+c4MBOGxuse5TD7DsMFYSxVxRBnOzok/xryNeQSjXgxSv9QpIVlaGzEn/pIuI6Koosx8CGWA==", + "cpu": [ + "x64" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 10" + } + }, + "node_modules/@next/swc-linux-x64-musl": { + "version": "16.1.7", + "resolved": "https://registry.npmjs.org/@next/swc-linux-x64-musl/-/swc-linux-x64-musl-16.1.7.tgz", + "integrity": "sha512-HguhaGwsGr1YAGs68uRKc4aGWxLET+NevJskOcCAwXbwj0fYX0RgZW2gsOCzr9S11CSQPIkxmoSbuVaBp4Z3dA==", + "cpu": [ + "x64" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 10" + } + }, + "node_modules/@next/swc-win32-arm64-msvc": { + "version": "16.1.7", + "resolved": "https://registry.npmjs.org/@next/swc-win32-arm64-msvc/-/swc-win32-arm64-msvc-16.1.7.tgz", + "integrity": "sha512-S0n3KrDJokKTeFyM/vGGGR8+pCmXYrjNTk2ZozOL1C/JFdfUIL9O1ATaJOl5r2POe56iRChbsszrjMAdWSv7kQ==", + "cpu": [ + "arm64" + ], + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">= 10" + } + }, + "node_modules/@next/swc-win32-x64-msvc": { + "version": "16.1.7", + "resolved": "https://registry.npmjs.org/@next/swc-win32-x64-msvc/-/swc-win32-x64-msvc-16.1.7.tgz", + "integrity": "sha512-mwgtg8CNZGYm06LeEd+bNnOUfwOyNem/rOiP14Lsz+AnUY92Zq/LXwtebtUiaeVkhbroRCQ0c8GlR4UT1U+0yg==", + "cpu": [ + "x64" + ], + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">= 10" + } + }, + "node_modules/@noble/ciphers": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/@noble/ciphers/-/ciphers-1.3.0.tgz", + "integrity": "sha512-2I0gnIVPtfnMw9ee9h1dJG7tp81+8Ob3OJb3Mv37rx5L40/b0i7djjCVvGOVqc9AEIQyvyu1i6ypKdFw8R8gQw==", + "license": "MIT", + "engines": { + "node": "^14.21.3 || >=16" + }, + "funding": { + "url": "https://paulmillr.com/funding/" + } + }, + "node_modules/@noble/curves": { + "version": "1.9.7", + "resolved": "https://registry.npmjs.org/@noble/curves/-/curves-1.9.7.tgz", + "integrity": "sha512-gbKGcRUYIjA3/zCCNaWDciTMFI0dCkvou3TL8Zmy5Nc7sJ47a0jtOeZoTaMxkuqRo9cRhjOdZJXegxYE5FN/xw==", + "license": "MIT", + "dependencies": { + "@noble/hashes": "1.8.0" + }, + "engines": { + "node": "^14.21.3 || >=16" + }, + "funding": { + "url": "https://paulmillr.com/funding/" + } + }, + "node_modules/@noble/hashes": { + "version": "1.8.0", + "resolved": "https://registry.npmjs.org/@noble/hashes/-/hashes-1.8.0.tgz", + "integrity": "sha512-jCs9ldd7NwzpgXDIf6P3+NrHh9/sD6CQdxHyjQI+h/6rDNo88ypBxxz45UDuZHz9r3tNz7N/VInSVoVdtXEI4A==", + "license": "MIT", + "engines": { + "node": "^14.21.3 || >=16" + }, + "funding": { + "url": "https://paulmillr.com/funding/" + } + }, + "node_modules/@nodelib/fs.scandir": { + "version": "2.1.5", + "resolved": "https://registry.npmjs.org/@nodelib/fs.scandir/-/fs.scandir-2.1.5.tgz", + "integrity": "sha512-vq24Bq3ym5HEQm2NKCr3yXDwjc7vTsEThRDnkp2DK9p1uqLR+DHurm/NOTo0KG7HYHU7eppKZj3MyqYuMBf62g==", + "license": "MIT", + "dependencies": { + "@nodelib/fs.stat": "2.0.5", + "run-parallel": "^1.1.9" + }, + "engines": { + "node": ">= 8" + } + }, + "node_modules/@nodelib/fs.stat": { + "version": "2.0.5", + "resolved": "https://registry.npmjs.org/@nodelib/fs.stat/-/fs.stat-2.0.5.tgz", + "integrity": "sha512-RkhPPp2zrqDAQA/2jNhnztcPAlv64XdhIp7a7454A5ovI7Bukxgt7MX7udwAu3zg1DcpPU0rz3VV1SeaqvY4+A==", + "license": "MIT", + "engines": { + "node": ">= 8" + } + }, + "node_modules/@nodelib/fs.walk": { + "version": "1.2.8", + "resolved": "https://registry.npmjs.org/@nodelib/fs.walk/-/fs.walk-1.2.8.tgz", + "integrity": "sha512-oGB+UxlgWcgQkgwo8GcEGwemoTFt3FIO9ababBmaGwXIoBKZ+GTy0pP185beGg7Llih/NSHSV2XAs1lnznocSg==", + "license": "MIT", + "dependencies": { + "@nodelib/fs.scandir": "2.1.5", + "fastq": "^1.6.0" + }, + "engines": { + "node": ">= 8" + } + }, + "node_modules/@nolyfill/is-core-module": { + "version": "1.0.39", + "resolved": "https://registry.npmjs.org/@nolyfill/is-core-module/-/is-core-module-1.0.39.tgz", + "integrity": "sha512-nn5ozdjYQpUCZlWGuxcJY/KpxkWQs4DcbMCmKojjyrYDEAGy4Ce19NN4v5MduafTwJlbKc99UA8YhSVqq9yPZA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12.4.0" + } + }, + "node_modules/@open-draft/deferred-promise": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/@open-draft/deferred-promise/-/deferred-promise-2.2.0.tgz", + "integrity": "sha512-CecwLWx3rhxVQF6V4bAgPS5t+So2sTbPgAzafKkVizyi7tlwpcFpdFqq+wqF2OwNBmqFuu6tOyouTuxgpMfzmA==", + "license": "MIT" + }, + "node_modules/@open-draft/logger": { + "version": "0.3.0", + "resolved": "https://registry.npmjs.org/@open-draft/logger/-/logger-0.3.0.tgz", + "integrity": "sha512-X2g45fzhxH238HKO4xbSr7+wBS8Fvw6ixhTDuvLd5mqh6bJJCFAPwU9mPDxbcrRtfxv4u5IHCEH77BmxvXmmxQ==", + "license": "MIT", + "dependencies": { + "is-node-process": "^1.2.0", + "outvariant": "^1.4.0" + } + }, + "node_modules/@open-draft/until": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/@open-draft/until/-/until-2.1.0.tgz", + "integrity": "sha512-U69T3ItWHvLwGg5eJ0n3I62nWuE6ilHlmz7zM0npLBRvPRd7e6NYmg54vvRtP5mZG7kZqZCFVdsTWo7BPtBujg==", + "license": "MIT" + }, + "node_modules/@oxc-project/runtime": { + "version": "0.115.0", + "resolved": "https://registry.npmjs.org/@oxc-project/runtime/-/runtime-0.115.0.tgz", + "integrity": "sha512-Rg8Wlt5dCbXhQnsXPrkOjL1DTSvXLgb2R/KYfnf1/K+R0k6UMLEmbQXPM+kwrWqSmWA2t0B1EtHy2/3zikQpvQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@oxc-project/types": { + "version": "0.115.0", + "resolved": "https://registry.npmjs.org/@oxc-project/types/-/types-0.115.0.tgz", + "integrity": "sha512-4n91DKnebUS4yjUHl2g3/b2T+IUdCfmoZGhmwsovZCDaJSs+QkVAM+0AqqTxHSsHfeiMuueT75cZaZcT/m0pSw==", + "dev": true, + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/Boshen" + } + }, + "node_modules/@playwright/test": { + "version": "1.61.1", + "resolved": "https://registry.npmjs.org/@playwright/test/-/test-1.61.1.tgz", + "integrity": "sha512-8nKv6+0RJSL9FE4jYOEGXnPeM/Hg12qZpmqzZjRh3qM0Y7c3z1mrOTfFLids72RDQYVh9WpLEfR5WdpNX4fkig==", + "devOptional": true, + "license": "Apache-2.0", + "dependencies": { + "playwright": "1.61.1" + }, + "bin": { + "playwright": "cli.js" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/@prisma/adapter-libsql": { + "version": "7.5.0", + "resolved": "https://registry.npmjs.org/@prisma/adapter-libsql/-/adapter-libsql-7.5.0.tgz", + "integrity": "sha512-zcZCH/sq/ErqhOXw+8/2IOKSZVMym7LUEEVxq/cbv5MMUl1qciPJsam0JkMOsZbE+urxM6QK2yQ0Zdp/uOEKhw==", + "license": "Apache-2.0", + "dependencies": { + "@libsql/client": "^0.17.0", + "@prisma/driver-adapter-utils": "7.5.0", + "async-mutex": "0.5.0" + } + }, + "node_modules/@prisma/client": { + "version": "7.5.0", + "resolved": "https://registry.npmjs.org/@prisma/client/-/client-7.5.0.tgz", + "integrity": "sha512-h4hF9ctp+kSRs7ENHGsFQmHAgHcfkOCxbYt6Ti9Xi8x7D+kP4tTi9x51UKmiTH/OqdyJAO+8V+r+JA5AWdav7w==", + "license": "Apache-2.0", + "dependencies": { + "@prisma/client-runtime-utils": "7.5.0" + }, + "engines": { + "node": "^20.19 || ^22.12 || >=24.0" + }, + "peerDependencies": { + "prisma": "*", + "typescript": ">=5.4.0" + }, + "peerDependenciesMeta": { + "prisma": { + "optional": true + }, + "typescript": { + "optional": true + } + } + }, + "node_modules/@prisma/client-runtime-utils": { + "version": "7.5.0", + "resolved": "https://registry.npmjs.org/@prisma/client-runtime-utils/-/client-runtime-utils-7.5.0.tgz", + "integrity": "sha512-KnJ2b4Si/pcWEtK68uM+h0h1oh80CZt2suhLTVuLaSKg4n58Q9jBF/A42Kw6Ma+aThy1yAhfDeTC0JvEmeZnFQ==", + "license": "Apache-2.0" + }, + "node_modules/@prisma/config": { + "version": "7.6.0", + "resolved": "https://registry.npmjs.org/@prisma/config/-/config-7.6.0.tgz", + "integrity": "sha512-MuAz1MK4PeG5/03YzfzX3CnFVHQ6qePGwUpQRzPzX5tT0ffJ3Tzi9zJZbBc+VzEGFCM8ghW/gTVDR85Syjt+Yw==", + "devOptional": true, + "license": "Apache-2.0", + "dependencies": { + "c12": "3.1.0", + "deepmerge-ts": "7.1.5", + "effect": "3.20.0", + "empathic": "2.0.0" + } + }, + "node_modules/@prisma/debug": { + "version": "7.5.0", + "resolved": "https://registry.npmjs.org/@prisma/debug/-/debug-7.5.0.tgz", + "integrity": "sha512-163+nffny0JoPEkDhfNco0vcuT3ymIJc9+WX7MHSQhfkeKUmKe9/wqvGk5SjppT93DtBjVwr5HPJYlXbzm6qtg==", + "license": "Apache-2.0" + }, + "node_modules/@prisma/dev": { + "version": "0.24.3", + "resolved": "https://registry.npmjs.org/@prisma/dev/-/dev-0.24.3.tgz", + "integrity": "sha512-ffHlQuKXZiaDt9Go0OnCTdJZrHxK0k7omJKNV86/VjpsXu5EIHZLK0T7JSWgvNlJwh56kW9JFu9v0qJciFzepg==", + "devOptional": true, + "license": "ISC", + "dependencies": { + "@electric-sql/pglite": "0.4.1", + "@electric-sql/pglite-socket": "0.1.1", + "@electric-sql/pglite-tools": "0.3.1", + "@hono/node-server": "1.19.11", + "@prisma/get-platform": "7.2.0", + "@prisma/query-plan-executor": "7.2.0", + "@prisma/streams-local": "0.1.2", + "foreground-child": "3.3.1", + "get-port-please": "3.2.0", + "hono": "^4.12.8", + "http-status-codes": "2.3.0", + "pathe": "2.0.3", + "proper-lockfile": "4.1.2", + "remeda": "2.33.4", + "std-env": "3.10.0", + "valibot": "1.2.0", + "zeptomatch": "2.1.0" + } + }, + "node_modules/@prisma/dev/node_modules/@hono/node-server": { + "version": "1.19.11", + "resolved": "https://registry.npmjs.org/@hono/node-server/-/node-server-1.19.11.tgz", + "integrity": "sha512-dr8/3zEaB+p0D2n/IUrlPF1HZm586qgJNXK1a9fhg/PzdtkK7Ksd5l312tJX2yBuALqDYBlG20QEbayqPyxn+g==", + "devOptional": true, + "license": "MIT", + "engines": { + "node": ">=18.14.1" + }, + "peerDependencies": { + "hono": "^4" + } + }, + "node_modules/@prisma/driver-adapter-utils": { + "version": "7.5.0", + "resolved": "https://registry.npmjs.org/@prisma/driver-adapter-utils/-/driver-adapter-utils-7.5.0.tgz", + "integrity": "sha512-B79N/amgV677mFesFDBAdrW0OIaqawap9E0sjgLBtzIz2R3hIMS1QB8mLZuUEiS4q5Y8Oh3I25Kw4SLxMypk9Q==", + "license": "Apache-2.0", + "dependencies": { + "@prisma/debug": "7.5.0" + } + }, + "node_modules/@prisma/engines": { + "version": "7.6.0", + "resolved": "https://registry.npmjs.org/@prisma/engines/-/engines-7.6.0.tgz", + "integrity": "sha512-Sn5edRzhHqgRV2M+A0eIbY442B4mReWWf3pKs/LKreYgW7oa/up8JtK/s4iv/EQA097cyboZ08mmkpbLp+tZ3w==", + "devOptional": true, + "hasInstallScript": true, + "license": "Apache-2.0", + "dependencies": { + "@prisma/debug": "7.6.0", + "@prisma/engines-version": "7.6.0-1.75cbdc1eb7150937890ad5465d861175c6624711", + "@prisma/fetch-engine": "7.6.0", + "@prisma/get-platform": "7.6.0" + } + }, + "node_modules/@prisma/engines-version": { + "version": "7.6.0-1.75cbdc1eb7150937890ad5465d861175c6624711", + "resolved": "https://registry.npmjs.org/@prisma/engines-version/-/engines-version-7.6.0-1.75cbdc1eb7150937890ad5465d861175c6624711.tgz", + "integrity": "sha512-r51DLcJ8bDRSrBEJF3J4cinoWyGA7rfP2mG6lD90VqIbGNOkbfcLcXalSVjq5Y6brQS3vcjrq4GbyUb1Cb7vkw==", + "devOptional": true, + "license": "Apache-2.0" + }, + "node_modules/@prisma/engines/node_modules/@prisma/debug": { + "version": "7.6.0", + "resolved": "https://registry.npmjs.org/@prisma/debug/-/debug-7.6.0.tgz", + "integrity": "sha512-LpHr3qos4lQZ6sxwjStf59YBht7m9/QF7NSQsMH6qGENWZu2w3UkQUGn1h5iRkDjnWRj3VHykOu9qFhps4ADvA==", + "devOptional": true, + "license": "Apache-2.0" + }, + "node_modules/@prisma/engines/node_modules/@prisma/get-platform": { + "version": "7.6.0", + "resolved": "https://registry.npmjs.org/@prisma/get-platform/-/get-platform-7.6.0.tgz", + "integrity": "sha512-ohZDwXvtmnbzOcutR2D13lDWpZP1wQjmPyztmt0AwXLzQI7q95EE7NYCvS+M6N6SivT+BM0NOqLmTH3wms4L3A==", + "devOptional": true, + "license": "Apache-2.0", + "dependencies": { + "@prisma/debug": "7.6.0" + } + }, + "node_modules/@prisma/fetch-engine": { + "version": "7.6.0", + "resolved": "https://registry.npmjs.org/@prisma/fetch-engine/-/fetch-engine-7.6.0.tgz", + "integrity": "sha512-N575Ni95c3FkduWY/eKTHqNYgNbceZ1tQaSknVtJjpKmiiBXmniESn/GTxsDvICC4ZeiNrXxioGInzQrCdx16w==", + "devOptional": true, + "license": "Apache-2.0", + "dependencies": { + "@prisma/debug": "7.6.0", + "@prisma/engines-version": "7.6.0-1.75cbdc1eb7150937890ad5465d861175c6624711", + "@prisma/get-platform": "7.6.0" + } + }, + "node_modules/@prisma/fetch-engine/node_modules/@prisma/debug": { + "version": "7.6.0", + "resolved": "https://registry.npmjs.org/@prisma/debug/-/debug-7.6.0.tgz", + "integrity": "sha512-LpHr3qos4lQZ6sxwjStf59YBht7m9/QF7NSQsMH6qGENWZu2w3UkQUGn1h5iRkDjnWRj3VHykOu9qFhps4ADvA==", + "devOptional": true, + "license": "Apache-2.0" + }, + "node_modules/@prisma/fetch-engine/node_modules/@prisma/get-platform": { + "version": "7.6.0", + "resolved": "https://registry.npmjs.org/@prisma/get-platform/-/get-platform-7.6.0.tgz", + "integrity": "sha512-ohZDwXvtmnbzOcutR2D13lDWpZP1wQjmPyztmt0AwXLzQI7q95EE7NYCvS+M6N6SivT+BM0NOqLmTH3wms4L3A==", + "devOptional": true, + "license": "Apache-2.0", + "dependencies": { + "@prisma/debug": "7.6.0" + } + }, + "node_modules/@prisma/get-platform": { + "version": "7.2.0", + "resolved": "https://registry.npmjs.org/@prisma/get-platform/-/get-platform-7.2.0.tgz", + "integrity": "sha512-k1V0l0Td1732EHpAfi2eySTezyllok9dXb6UQanajkJQzPUGi3vO2z7jdkz67SypFTdmbnyGYxvEvYZdZsMAVA==", + "devOptional": true, + "license": "Apache-2.0", + "dependencies": { + "@prisma/debug": "7.2.0" + } + }, + "node_modules/@prisma/get-platform/node_modules/@prisma/debug": { + "version": "7.2.0", + "resolved": "https://registry.npmjs.org/@prisma/debug/-/debug-7.2.0.tgz", + "integrity": "sha512-YSGTiSlBAVJPzX4ONZmMotL+ozJwQjRmZweQNIq/ER0tQJKJynNkRB3kyvt37eOfsbMCXk3gnLF6J9OJ4QWftw==", + "devOptional": true, + "license": "Apache-2.0" + }, + "node_modules/@prisma/query-plan-executor": { + "version": "7.2.0", + "resolved": "https://registry.npmjs.org/@prisma/query-plan-executor/-/query-plan-executor-7.2.0.tgz", + "integrity": "sha512-EOZmNzcV8uJ0mae3DhTsiHgoNCuu1J9mULQpGCh62zN3PxPTd+qI9tJvk5jOst8WHKQNwJWR3b39t0XvfBB0WQ==", + "devOptional": true, + "license": "Apache-2.0" + }, + "node_modules/@prisma/streams-local": { + "version": "0.1.2", + "resolved": "https://registry.npmjs.org/@prisma/streams-local/-/streams-local-0.1.2.tgz", + "integrity": "sha512-l49yTxKKF2odFxaAXTmwmkBKL3+bVQ1tFOooGifu4xkdb9NMNLxHj27XAhTylWZod8I+ISGM5erU1xcl/oBCtg==", + "devOptional": true, + "license": "Apache-2.0", + "dependencies": { + "ajv": "^8.12.0", + "better-result": "^2.7.0", + "env-paths": "^3.0.0", + "proper-lockfile": "^4.1.2" + }, + "engines": { + "bun": ">=1.3.6", + "node": ">=22.0.0" + } + }, + "node_modules/@prisma/streams-local/node_modules/ajv": { + "version": "8.18.0", + "resolved": "https://registry.npmjs.org/ajv/-/ajv-8.18.0.tgz", + "integrity": "sha512-PlXPeEWMXMZ7sPYOHqmDyCJzcfNrUr3fGNKtezX14ykXOEIvyK81d+qydx89KY5O71FKMPaQ2vBfBFI5NHR63A==", + "devOptional": true, + "license": "MIT", + "dependencies": { + "fast-deep-equal": "^3.1.3", + "fast-uri": "^3.0.1", + "json-schema-traverse": "^1.0.0", + "require-from-string": "^2.0.2" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/epoberezkin" + } + }, + "node_modules/@prisma/streams-local/node_modules/env-paths": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/env-paths/-/env-paths-3.0.0.tgz", + "integrity": "sha512-dtJUTepzMW3Lm/NPxRf3wP4642UWhjL2sQxc+ym2YMj1m/H2zDNQOlezafzkHwn6sMstjHTwG6iQQsctDW/b1A==", + "devOptional": true, + "license": "MIT", + "engines": { + "node": "^12.20.0 || ^14.13.1 || >=16.0.0" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/@prisma/streams-local/node_modules/json-schema-traverse": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-1.0.0.tgz", + "integrity": "sha512-NM8/P9n3XjXhIZn1lLhkFaACTOURQXjWhV4BA/RnOv8xvgqtqpAX9IO4mRQxSx1Rlo4tqzeqb0sOlruaOy3dug==", + "devOptional": true, + "license": "MIT" + }, + "node_modules/@prisma/studio-core": { + "version": "0.27.3", + "resolved": "https://registry.npmjs.org/@prisma/studio-core/-/studio-core-0.27.3.tgz", + "integrity": "sha512-AADjNFPdsrglxHQVTmHFqv6DuKQZ5WY4p5/gVFY017twvNrSwpLJ9lqUbYYxEu2W7nbvVxTZA8deJ8LseNALsw==", + "devOptional": true, + "license": "Apache-2.0", + "dependencies": { + "@radix-ui/react-toggle": "1.1.10", + "chart.js": "4.5.1" + }, + "engines": { + "node": "^20.19 || ^22.12 || >=24.0", + "pnpm": "8" + }, + "peerDependencies": { + "@types/react": "^18.0.0 || ^19.0.0", + "react": "^18.0.0 || ^19.0.0", + "react-dom": "^18.0.0 || ^19.0.0" + } + }, + "node_modules/@radix-ui/primitive": { + "version": "1.1.3", + "resolved": "https://registry.npmjs.org/@radix-ui/primitive/-/primitive-1.1.3.tgz", + "integrity": "sha512-JTF99U/6XIjCBo0wqkU5sK10glYe27MRRsfwoiq5zzOEZLHU3A3KCMa5X/azekYRCJ0HlwI0crAXS/5dEHTzDg==", + "devOptional": true, + "license": "MIT" + }, + "node_modules/@radix-ui/react-compose-refs": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/@radix-ui/react-compose-refs/-/react-compose-refs-1.1.2.tgz", + "integrity": "sha512-z4eqJvfiNnFMHIIvXP3CY57y2WJs5g2v3X0zm9mEJkrkNv4rDxu+sg9Jh8EkXyeqBkB7SOcboo9dMVqhyrACIg==", + "devOptional": true, + "license": "MIT", + "peerDependencies": { + "@types/react": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-primitive": { + "version": "2.1.3", + "resolved": "https://registry.npmjs.org/@radix-ui/react-primitive/-/react-primitive-2.1.3.tgz", + "integrity": "sha512-m9gTwRkhy2lvCPe6QJp4d3G1TYEUHn/FzJUtq9MjH46an1wJU+GdoGC5VLof8RX8Ft/DlpshApkhswDLZzHIcQ==", + "devOptional": true, + "license": "MIT", + "dependencies": { + "@radix-ui/react-slot": "1.2.3" + }, + "peerDependencies": { + "@types/react": "*", + "@types/react-dom": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", + "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + }, + "@types/react-dom": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-slot": { + "version": "1.2.3", + "resolved": "https://registry.npmjs.org/@radix-ui/react-slot/-/react-slot-1.2.3.tgz", + "integrity": "sha512-aeNmHnBxbi2St0au6VBVC7JXFlhLlOnvIIlePNniyUNAClzmtAUEY8/pBiK3iHjufOlwA+c20/8jngo7xcrg8A==", + "devOptional": true, + "license": "MIT", + "dependencies": { + "@radix-ui/react-compose-refs": "1.1.2" + }, + "peerDependencies": { + "@types/react": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-toggle": { + "version": "1.1.10", + "resolved": "https://registry.npmjs.org/@radix-ui/react-toggle/-/react-toggle-1.1.10.tgz", + "integrity": "sha512-lS1odchhFTeZv3xwHH31YPObmJn8gOg7Lq12inrr0+BH/l3Tsq32VfjqH1oh80ARM3mlkfMic15n0kg4sD1poQ==", + "devOptional": true, + "license": "MIT", + "dependencies": { + "@radix-ui/primitive": "1.1.3", + "@radix-ui/react-primitive": "2.1.3", + "@radix-ui/react-use-controllable-state": "1.2.2" + }, + "peerDependencies": { + "@types/react": "*", + "@types/react-dom": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", + "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + }, + "@types/react-dom": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-use-controllable-state": { + "version": "1.2.2", + "resolved": "https://registry.npmjs.org/@radix-ui/react-use-controllable-state/-/react-use-controllable-state-1.2.2.tgz", + "integrity": "sha512-BjasUjixPFdS+NKkypcyyN5Pmg83Olst0+c6vGov0diwTEo6mgdqVR6hxcEgFuh4QrAs7Rc+9KuGJ9TVCj0Zzg==", + "devOptional": true, + "license": "MIT", + "dependencies": { + "@radix-ui/react-use-effect-event": "0.0.2", + "@radix-ui/react-use-layout-effect": "1.1.1" + }, + "peerDependencies": { + "@types/react": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-use-effect-event": { + "version": "0.0.2", + "resolved": "https://registry.npmjs.org/@radix-ui/react-use-effect-event/-/react-use-effect-event-0.0.2.tgz", + "integrity": "sha512-Qp8WbZOBe+blgpuUT+lw2xheLP8q0oatc9UpmiemEICxGvFLYmHm9QowVZGHtJlGbS6A6yJ3iViad/2cVjnOiA==", + "devOptional": true, + "license": "MIT", + "dependencies": { + "@radix-ui/react-use-layout-effect": "1.1.1" + }, + "peerDependencies": { + "@types/react": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-use-layout-effect": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/@radix-ui/react-use-layout-effect/-/react-use-layout-effect-1.1.1.tgz", + "integrity": "sha512-RbJRS4UWQFkzHTTwVymMTUv8EqYhOp8dOOviLj2ugtTiXRaRQS7GLGxZTLL1jWhMeoSCf5zmcZkqTl9IiYfXcQ==", + "devOptional": true, + "license": "MIT", + "peerDependencies": { + "@types/react": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + } + } + }, + "node_modules/@reduxjs/toolkit": { + "version": "2.11.2", + "resolved": "https://registry.npmjs.org/@reduxjs/toolkit/-/toolkit-2.11.2.tgz", + "integrity": "sha512-Kd6kAHTA6/nUpp8mySPqj3en3dm0tdMIgbttnQ1xFMVpufoj+ADi8pXLBsd4xzTRHQa7t/Jv8W5UnCuW4kuWMQ==", + "license": "MIT", + "dependencies": { + "@standard-schema/spec": "^1.0.0", + "@standard-schema/utils": "^0.3.0", + "immer": "^11.0.0", + "redux": "^5.0.1", + "redux-thunk": "^3.1.0", + "reselect": "^5.1.0" + }, + "peerDependencies": { + "react": "^16.9.0 || ^17.0.0 || ^18 || ^19", + "react-redux": "^7.2.1 || ^8.1.3 || ^9.0.0" + }, + "peerDependenciesMeta": { + "react": { + "optional": true + }, + "react-redux": { + "optional": true + } + } + }, + "node_modules/@reduxjs/toolkit/node_modules/immer": { + "version": "11.1.4", + "resolved": "https://registry.npmjs.org/immer/-/immer-11.1.4.tgz", + "integrity": "sha512-XREFCPo6ksxVzP4E0ekD5aMdf8WMwmdNaz6vuvxgI40UaEiu6q3p8X52aU6GdyvLY3XXX/8R7JOTXStz/nBbRw==", + "license": "MIT", + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/immer" + } + }, + "node_modules/@rolldown/binding-android-arm64": { + "version": "1.0.0-rc.9", + "resolved": "https://registry.npmjs.org/@rolldown/binding-android-arm64/-/binding-android-arm64-1.0.0-rc.9.tgz", + "integrity": "sha512-lcJL0bN5hpgJfSIz/8PIf02irmyL43P+j1pTCfbD1DbLkmGRuFIA4DD3B3ZOvGqG0XiVvRznbKtN0COQVaKUTg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-darwin-arm64": { + "version": "1.0.0-rc.9", + "resolved": "https://registry.npmjs.org/@rolldown/binding-darwin-arm64/-/binding-darwin-arm64-1.0.0-rc.9.tgz", + "integrity": "sha512-J7Zk3kLYFsLtuH6U+F4pS2sYVzac0qkjcO5QxHS7OS7yZu2LRs+IXo+uvJ/mvpyUljDJ3LROZPoQfgBIpCMhdQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-darwin-x64": { + "version": "1.0.0-rc.9", + "resolved": "https://registry.npmjs.org/@rolldown/binding-darwin-x64/-/binding-darwin-x64-1.0.0-rc.9.tgz", + "integrity": "sha512-iwtmmghy8nhfRGeNAIltcNXzD0QMNaaA5U/NyZc1Ia4bxrzFByNMDoppoC+hl7cDiUq5/1CnFthpT9n+UtfFyg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-freebsd-x64": { + "version": "1.0.0-rc.9", + "resolved": "https://registry.npmjs.org/@rolldown/binding-freebsd-x64/-/binding-freebsd-x64-1.0.0-rc.9.tgz", + "integrity": "sha512-DLFYI78SCiZr5VvdEplsVC2Vx53lnA4/Ga5C65iyldMVaErr86aiqCoNBLl92PXPfDtUYjUh+xFFor40ueNs4Q==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-linux-arm-gnueabihf": { + "version": "1.0.0-rc.9", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm-gnueabihf/-/binding-linux-arm-gnueabihf-1.0.0-rc.9.tgz", + "integrity": "sha512-CsjTmTwd0Hri6iTw/DRMK7kOZ7FwAkrO4h8YWKoX/kcj833e4coqo2wzIFywtch/8Eb5enQ/lwLM7w6JX1W5RQ==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-linux-arm64-gnu": { + "version": "1.0.0-rc.9", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm64-gnu/-/binding-linux-arm64-gnu-1.0.0-rc.9.tgz", + "integrity": "sha512-2x9O2JbSPxpxMDhP9Z74mahAStibTlrBMW0520+epJH5sac7/LwZW5Bmg/E6CXuEF53JJFW509uP+lSedaUNxg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-linux-arm64-musl": { + "version": "1.0.0-rc.9", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm64-musl/-/binding-linux-arm64-musl-1.0.0-rc.9.tgz", + "integrity": "sha512-JA1QRW31ogheAIRhIg9tjMfsYbglXXYGNPLdPEYrwFxdbkQCAzvpSCSHCDWNl4hTtrol8WeboCSEpjdZK8qrCg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-linux-ppc64-gnu": { + "version": "1.0.0-rc.9", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-ppc64-gnu/-/binding-linux-ppc64-gnu-1.0.0-rc.9.tgz", + "integrity": "sha512-aOKU9dJheda8Kj8Y3w9gnt9QFOO+qKPAl8SWd7JPHP+Cu0EuDAE5wokQubLzIDQWg2myXq2XhTpOVS07qqvT+w==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-linux-s390x-gnu": { + "version": "1.0.0-rc.9", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-s390x-gnu/-/binding-linux-s390x-gnu-1.0.0-rc.9.tgz", + "integrity": "sha512-OalO94fqj7IWRn3VdXWty75jC5dk4C197AWEuMhIpvVv2lw9fiPhud0+bW2ctCxb3YoBZor71QHbY+9/WToadA==", + "cpu": [ + "s390x" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-linux-x64-gnu": { + "version": "1.0.0-rc.9", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-x64-gnu/-/binding-linux-x64-gnu-1.0.0-rc.9.tgz", + "integrity": "sha512-cVEl1vZtBsBZna3YMjGXNvnYYrOJ7RzuWvZU0ffvJUexWkukMaDuGhUXn0rjnV0ptzGVkvc+vW9Yqy6h8YX4pg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-linux-x64-musl": { + "version": "1.0.0-rc.9", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-x64-musl/-/binding-linux-x64-musl-1.0.0-rc.9.tgz", + "integrity": "sha512-UzYnKCIIc4heAKgI4PZ3dfBGUZefGCJ1TPDuLHoCzgrMYPb5Rv6TLFuYtyM4rWyHM7hymNdsg5ik2C+UD9VDbA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-openharmony-arm64": { + "version": "1.0.0-rc.9", + "resolved": "https://registry.npmjs.org/@rolldown/binding-openharmony-arm64/-/binding-openharmony-arm64-1.0.0-rc.9.tgz", + "integrity": "sha512-+6zoiF+RRyf5cdlFQP7nm58mq7+/2PFaY2DNQeD4B87N36JzfF/l9mdBkkmTvSYcYPE8tMh/o3cRlsx1ldLfog==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openharmony" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-wasm32-wasi": { + "version": "1.0.0-rc.9", + "resolved": "https://registry.npmjs.org/@rolldown/binding-wasm32-wasi/-/binding-wasm32-wasi-1.0.0-rc.9.tgz", + "integrity": "sha512-rgFN6sA/dyebil3YTlL2evvi/M+ivhfnyxec7AccTpRPccno/rPoNlqybEZQBkcbZu8Hy+eqNJCqfBR8P7Pg8g==", + "cpu": [ + "wasm32" + ], + "dev": true, + "license": "MIT", + "optional": true, + "dependencies": { + "@napi-rs/wasm-runtime": "^1.1.1" + }, + "engines": { + "node": ">=14.0.0" + } + }, + "node_modules/@rolldown/binding-wasm32-wasi/node_modules/@napi-rs/wasm-runtime": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/@napi-rs/wasm-runtime/-/wasm-runtime-1.1.1.tgz", + "integrity": "sha512-p64ah1M1ld8xjWv3qbvFwHiFVWrq1yFvV4f7w+mzaqiR4IlSgkqhcRdHwsGgomwzBH51sRY4NEowLxnaBjcW/A==", + "dev": true, + "license": "MIT", + "optional": true, + "dependencies": { + "@emnapi/core": "^1.7.1", + "@emnapi/runtime": "^1.7.1", + "@tybys/wasm-util": "^0.10.1" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/Brooooooklyn" + } + }, + "node_modules/@rolldown/binding-win32-arm64-msvc": { + "version": "1.0.0-rc.9", + "resolved": "https://registry.npmjs.org/@rolldown/binding-win32-arm64-msvc/-/binding-win32-arm64-msvc-1.0.0-rc.9.tgz", + "integrity": "sha512-lHVNUG/8nlF1IQk1C0Ci574qKYyty2goMiPlRqkC5R+3LkXDkL5Dhx8ytbxq35m+pkHVIvIxviD+TWLdfeuadA==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-win32-x64-msvc": { + "version": "1.0.0-rc.9", + "resolved": "https://registry.npmjs.org/@rolldown/binding-win32-x64-msvc/-/binding-win32-x64-msvc-1.0.0-rc.9.tgz", + "integrity": "sha512-G0oA4+w1iY5AGi5HcDTxWsoxF509hrFIPB2rduV5aDqS9FtDg1CAfa7V34qImbjfhIcA8C+RekocJZA96EarwQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/pluginutils": { + "version": "1.0.0-rc.9", + "resolved": "https://registry.npmjs.org/@rolldown/pluginutils/-/pluginutils-1.0.0-rc.9.tgz", + "integrity": "sha512-w6oiRWgEBl04QkFZgmW+jnU1EC9b57Oihi2ot3HNWIQRqgHp5PnYDia5iZ5FF7rpa4EQdiqMDXjlqKGXBhsoXw==", + "dev": true, + "license": "MIT" + }, + "node_modules/@rtsao/scc": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/@rtsao/scc/-/scc-1.1.0.tgz", + "integrity": "sha512-zt6OdqaDoOnJ1ZYsCYGt9YmWzDXl4vQdKTyJev62gFhRGKdx7mcT54V9KIjg+d2wi9EXsPvAPKe7i7WjfVWB8g==", + "dev": true, + "license": "MIT" + }, + "node_modules/@sec-ant/readable-stream": { + "version": "0.4.1", + "resolved": "https://registry.npmjs.org/@sec-ant/readable-stream/-/readable-stream-0.4.1.tgz", + "integrity": "sha512-831qok9r2t8AlxLko40y2ebgSDhenenCatLVeW/uBtnHPyhHOvG0C7TvfgecV+wHzIm5KUICgzmVpWS+IMEAeg==", + "license": "MIT" + }, + "node_modules/@sindresorhus/merge-streams": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/@sindresorhus/merge-streams/-/merge-streams-4.0.0.tgz", + "integrity": "sha512-tlqY9xq5ukxTUZBmoOp+m61cqwQD5pHJtFY3Mn8CA8ps6yghLH/Hw8UPdqg4OLmFW3IFlcXnQNmo/dh8HzXYIQ==", + "license": "MIT", + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/@standard-schema/spec": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/@standard-schema/spec/-/spec-1.1.0.tgz", + "integrity": "sha512-l2aFy5jALhniG5HgqrD6jXLi/rUWrKvqN/qJx6yoJsgKhblVd+iqqU4RCXavm/jPityDo5TCvKMnpjKnOriy0w==", + "license": "MIT" + }, + "node_modules/@standard-schema/utils": { + "version": "0.3.0", + "resolved": "https://registry.npmjs.org/@standard-schema/utils/-/utils-0.3.0.tgz", + "integrity": "sha512-e7Mew686owMaPJVNNLs55PUvgz371nKgwsc4vxE49zsODpJEnxgxRo2y/OKrqueavXgZNMDVj3DdHFlaSAeU8g==", + "license": "MIT" + }, + "node_modules/@swc/helpers": { + "version": "0.5.15", + "resolved": "https://registry.npmjs.org/@swc/helpers/-/helpers-0.5.15.tgz", + "integrity": "sha512-JQ5TuMi45Owi4/BIMAJBoSQoOJu12oOk/gADqlcUL9JEdHB8vyjUSsxqeNXnmXHjYKMi2WcYtezGEEhqUI/E2g==", + "license": "Apache-2.0", + "dependencies": { + "tslib": "^2.8.0" + } + }, + "node_modules/@tailwindcss/node": { + "version": "4.2.1", + "resolved": "https://registry.npmjs.org/@tailwindcss/node/-/node-4.2.1.tgz", + "integrity": "sha512-jlx6sLk4EOwO6hHe1oCGm1Q4AN/s0rSrTTPBGPM0/RQ6Uylwq17FuU8IeJJKEjtc6K6O07zsvP+gDO6MMWo7pg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/remapping": "^2.3.5", + "enhanced-resolve": "^5.19.0", + "jiti": "^2.6.1", + "lightningcss": "1.31.1", + "magic-string": "^0.30.21", + "source-map-js": "^1.2.1", + "tailwindcss": "4.2.1" + } + }, + "node_modules/@tailwindcss/oxide": { + "version": "4.2.1", + "resolved": "https://registry.npmjs.org/@tailwindcss/oxide/-/oxide-4.2.1.tgz", + "integrity": "sha512-yv9jeEFWnjKCI6/T3Oq50yQEOqmpmpfzG1hcZsAOaXFQPfzWprWrlHSdGPEF3WQTi8zu8ohC9Mh9J470nT5pUw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 20" + }, + "optionalDependencies": { + "@tailwindcss/oxide-android-arm64": "4.2.1", + "@tailwindcss/oxide-darwin-arm64": "4.2.1", + "@tailwindcss/oxide-darwin-x64": "4.2.1", + "@tailwindcss/oxide-freebsd-x64": "4.2.1", + "@tailwindcss/oxide-linux-arm-gnueabihf": "4.2.1", + "@tailwindcss/oxide-linux-arm64-gnu": "4.2.1", + "@tailwindcss/oxide-linux-arm64-musl": "4.2.1", + "@tailwindcss/oxide-linux-x64-gnu": "4.2.1", + "@tailwindcss/oxide-linux-x64-musl": "4.2.1", + "@tailwindcss/oxide-wasm32-wasi": "4.2.1", + "@tailwindcss/oxide-win32-arm64-msvc": "4.2.1", + "@tailwindcss/oxide-win32-x64-msvc": "4.2.1" + } + }, + "node_modules/@tailwindcss/oxide-android-arm64": { + "version": "4.2.1", + "resolved": "https://registry.npmjs.org/@tailwindcss/oxide-android-arm64/-/oxide-android-arm64-4.2.1.tgz", + "integrity": "sha512-eZ7G1Zm5EC8OOKaesIKuw77jw++QJ2lL9N+dDpdQiAB/c/B2wDh0QPFHbkBVrXnwNugvrbJFk1gK2SsVjwWReg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">= 20" + } + }, + "node_modules/@tailwindcss/oxide-darwin-arm64": { + "version": "4.2.1", + "resolved": "https://registry.npmjs.org/@tailwindcss/oxide-darwin-arm64/-/oxide-darwin-arm64-4.2.1.tgz", + "integrity": "sha512-q/LHkOstoJ7pI1J0q6djesLzRvQSIfEto148ppAd+BVQK0JYjQIFSK3JgYZJa+Yzi0DDa52ZsQx2rqytBnf8Hw==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">= 20" + } + }, + "node_modules/@tailwindcss/oxide-darwin-x64": { + "version": "4.2.1", + "resolved": "https://registry.npmjs.org/@tailwindcss/oxide-darwin-x64/-/oxide-darwin-x64-4.2.1.tgz", + "integrity": "sha512-/f/ozlaXGY6QLbpvd/kFTro2l18f7dHKpB+ieXz+Cijl4Mt9AI2rTrpq7V+t04nK+j9XBQHnSMdeQRhbGyt6fw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">= 20" + } + }, + "node_modules/@tailwindcss/oxide-freebsd-x64": { + "version": "4.2.1", + "resolved": "https://registry.npmjs.org/@tailwindcss/oxide-freebsd-x64/-/oxide-freebsd-x64-4.2.1.tgz", + "integrity": "sha512-5e/AkgYJT/cpbkys/OU2Ei2jdETCLlifwm7ogMC7/hksI2fC3iiq6OcXwjibcIjPung0kRtR3TxEITkqgn0TcA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">= 20" + } + }, + "node_modules/@tailwindcss/oxide-linux-arm-gnueabihf": { + "version": "4.2.1", + "resolved": "https://registry.npmjs.org/@tailwindcss/oxide-linux-arm-gnueabihf/-/oxide-linux-arm-gnueabihf-4.2.1.tgz", + "integrity": "sha512-Uny1EcVTTmerCKt/1ZuKTkb0x8ZaiuYucg2/kImO5A5Y/kBz41/+j0gxUZl+hTF3xkWpDmHX+TaWhOtba2Fyuw==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 20" + } + }, + "node_modules/@tailwindcss/oxide-linux-arm64-gnu": { + "version": "4.2.1", + "resolved": "https://registry.npmjs.org/@tailwindcss/oxide-linux-arm64-gnu/-/oxide-linux-arm64-gnu-4.2.1.tgz", + "integrity": "sha512-CTrwomI+c7n6aSSQlsPL0roRiNMDQ/YzMD9EjcR+H4f0I1SQ8QqIuPnsVp7QgMkC1Qi8rtkekLkOFjo7OlEFRQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 20" + } + }, + "node_modules/@tailwindcss/oxide-linux-arm64-musl": { + "version": "4.2.1", + "resolved": "https://registry.npmjs.org/@tailwindcss/oxide-linux-arm64-musl/-/oxide-linux-arm64-musl-4.2.1.tgz", + "integrity": "sha512-WZA0CHRL/SP1TRbA5mp9htsppSEkWuQ4KsSUumYQnyl8ZdT39ntwqmz4IUHGN6p4XdSlYfJwM4rRzZLShHsGAQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 20" + } + }, + "node_modules/@tailwindcss/oxide-linux-x64-gnu": { + "version": "4.2.1", + "resolved": "https://registry.npmjs.org/@tailwindcss/oxide-linux-x64-gnu/-/oxide-linux-x64-gnu-4.2.1.tgz", + "integrity": "sha512-qMFzxI2YlBOLW5PhblzuSWlWfwLHaneBE0xHzLrBgNtqN6mWfs+qYbhryGSXQjFYB1Dzf5w+LN5qbUTPhW7Y5g==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 20" + } + }, + "node_modules/@tailwindcss/oxide-linux-x64-musl": { + "version": "4.2.1", + "resolved": "https://registry.npmjs.org/@tailwindcss/oxide-linux-x64-musl/-/oxide-linux-x64-musl-4.2.1.tgz", + "integrity": "sha512-5r1X2FKnCMUPlXTWRYpHdPYUY6a1Ar/t7P24OuiEdEOmms5lyqjDRvVY1yy9Rmioh+AunQ0rWiOTPE8F9A3v5g==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 20" + } + }, + "node_modules/@tailwindcss/oxide-wasm32-wasi": { + "version": "4.2.1", + "resolved": "https://registry.npmjs.org/@tailwindcss/oxide-wasm32-wasi/-/oxide-wasm32-wasi-4.2.1.tgz", + "integrity": "sha512-MGFB5cVPvshR85MTJkEvqDUnuNoysrsRxd6vnk1Lf2tbiqNlXpHYZqkqOQalydienEWOHHFyyuTSYRsLfxFJ2Q==", + "bundleDependencies": [ + "@napi-rs/wasm-runtime", + "@emnapi/core", + "@emnapi/runtime", + "@tybys/wasm-util", + "@emnapi/wasi-threads", + "tslib" + ], + "cpu": [ + "wasm32" + ], + "dev": true, + "license": "MIT", + "optional": true, + "dependencies": { + "@emnapi/core": "^1.8.1", + "@emnapi/runtime": "^1.8.1", + "@emnapi/wasi-threads": "^1.1.0", + "@napi-rs/wasm-runtime": "^1.1.1", + "@tybys/wasm-util": "^0.10.1", + "tslib": "^2.8.1" + }, + "engines": { + "node": ">=14.0.0" + } + }, + "node_modules/@tailwindcss/oxide-win32-arm64-msvc": { + "version": "4.2.1", + "resolved": "https://registry.npmjs.org/@tailwindcss/oxide-win32-arm64-msvc/-/oxide-win32-arm64-msvc-4.2.1.tgz", + "integrity": "sha512-YlUEHRHBGnCMh4Nj4GnqQyBtsshUPdiNroZj8VPkvTZSoHsilRCwXcVKnG9kyi0ZFAS/3u+qKHBdDc81SADTRA==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">= 20" + } + }, + "node_modules/@tailwindcss/oxide-win32-x64-msvc": { + "version": "4.2.1", + "resolved": "https://registry.npmjs.org/@tailwindcss/oxide-win32-x64-msvc/-/oxide-win32-x64-msvc-4.2.1.tgz", + "integrity": "sha512-rbO34G5sMWWyrN/idLeVxAZgAKWrn5LiR3/I90Q9MkA67s6T1oB0xtTe+0heoBvHSpbU9Mk7i6uwJnpo4u21XQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">= 20" + } + }, + "node_modules/@tailwindcss/postcss": { + "version": "4.2.1", + "resolved": "https://registry.npmjs.org/@tailwindcss/postcss/-/postcss-4.2.1.tgz", + "integrity": "sha512-OEwGIBnXnj7zJeonOh6ZG9woofIjGrd2BORfvE5p9USYKDCZoQmfqLcfNiRWoJlRWLdNPn2IgVZuWAOM4iTYMw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@alloc/quick-lru": "^5.2.0", + "@tailwindcss/node": "4.2.1", + "@tailwindcss/oxide": "4.2.1", + "postcss": "^8.5.6", + "tailwindcss": "4.2.1" + } + }, + "node_modules/@ts-morph/common": { + "version": "0.27.0", + "resolved": "https://registry.npmjs.org/@ts-morph/common/-/common-0.27.0.tgz", + "integrity": "sha512-Wf29UqxWDpc+i61k3oIOzcUfQt79PIT9y/MWfAGlrkjg6lBC1hwDECLXPVJAhWjiGbfBCxZd65F/LIZF3+jeJQ==", + "license": "MIT", + "dependencies": { + "fast-glob": "^3.3.3", + "minimatch": "^10.0.1", + "path-browserify": "^1.0.1" + } + }, + "node_modules/@ts-morph/common/node_modules/balanced-match": { + "version": "4.0.4", + "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-4.0.4.tgz", + "integrity": "sha512-BLrgEcRTwX2o6gGxGOCNyMvGSp35YofuYzw9h1IMTRmKqttAZZVU67bdb9Pr2vUHA8+j3i2tJfjO6C6+4myGTA==", + "license": "MIT", + "engines": { + "node": "18 || 20 || >=22" + } + }, + "node_modules/@ts-morph/common/node_modules/brace-expansion": { + "version": "5.0.5", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-5.0.5.tgz", + "integrity": "sha512-VZznLgtwhn+Mact9tfiwx64fA9erHH/MCXEUfB/0bX/6Fz6ny5EGTXYltMocqg4xFAQZtnO3DHWWXi8RiuN7cQ==", + "license": "MIT", + "dependencies": { + "balanced-match": "^4.0.2" + }, + "engines": { + "node": "18 || 20 || >=22" + } + }, + "node_modules/@ts-morph/common/node_modules/fast-glob": { + "version": "3.3.3", + "resolved": "https://registry.npmjs.org/fast-glob/-/fast-glob-3.3.3.tgz", + "integrity": "sha512-7MptL8U0cqcFdzIzwOTHoilX9x5BrNqye7Z/LuC7kCMRio1EMSyqRK3BEAUD7sXRq4iT4AzTVuZdhgQ2TCvYLg==", + "license": "MIT", + "dependencies": { + "@nodelib/fs.stat": "^2.0.2", + "@nodelib/fs.walk": "^1.2.3", + "glob-parent": "^5.1.2", + "merge2": "^1.3.0", + "micromatch": "^4.0.8" + }, + "engines": { + "node": ">=8.6.0" + } + }, + "node_modules/@ts-morph/common/node_modules/glob-parent": { + "version": "5.1.2", + "resolved": "https://registry.npmjs.org/glob-parent/-/glob-parent-5.1.2.tgz", + "integrity": "sha512-AOIgSQCepiJYwP3ARnGx+5VnTu2HBYdzbGP45eLw1vr3zB3vZLeyed1sC9hnbcOc9/SrMyM5RPQrkGz4aS9Zow==", + "license": "ISC", + "dependencies": { + "is-glob": "^4.0.1" + }, + "engines": { + "node": ">= 6" + } + }, + "node_modules/@ts-morph/common/node_modules/minimatch": { + "version": "10.2.4", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-10.2.4.tgz", + "integrity": "sha512-oRjTw/97aTBN0RHbYCdtF1MQfvusSIBQM0IZEgzl6426+8jSC0nF1a/GmnVLpfB9yyr6g6FTqWqiZVbxrtaCIg==", + "license": "BlueOak-1.0.0", + "dependencies": { + "brace-expansion": "^5.0.2" + }, + "engines": { + "node": "18 || 20 || >=22" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/@tybys/wasm-util": { + "version": "0.10.1", + "resolved": "https://registry.npmjs.org/@tybys/wasm-util/-/wasm-util-0.10.1.tgz", + "integrity": "sha512-9tTaPJLSiejZKx+Bmog4uSubteqTvFrVrURwkmHixBo0G4seD0zUxp98E1DzUBJxLQ3NPwXrGKDiVjwx/DpPsg==", + "dev": true, + "license": "MIT", + "optional": true, + "dependencies": { + "tslib": "^2.4.0" + } + }, + "node_modules/@types/chai": { + "version": "5.2.3", + "resolved": "https://registry.npmjs.org/@types/chai/-/chai-5.2.3.tgz", + "integrity": "sha512-Mw558oeA9fFbv65/y4mHtXDs9bPnFMZAL/jxdPFUpOHHIXX91mcgEHbS5Lahr+pwZFR8A7GQleRWeI6cGFC2UA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/deep-eql": "*", + "assertion-error": "^2.0.1" + } + }, + "node_modules/@types/d3-array": { + "version": "3.2.2", + "resolved": "https://registry.npmjs.org/@types/d3-array/-/d3-array-3.2.2.tgz", + "integrity": "sha512-hOLWVbm7uRza0BYXpIIW5pxfrKe0W+D5lrFiAEYR+pb6w3N2SwSMaJbXdUfSEv+dT4MfHBLtn5js0LAWaO6otw==", + "license": "MIT" + }, + "node_modules/@types/d3-color": { + "version": "3.1.3", + "resolved": "https://registry.npmjs.org/@types/d3-color/-/d3-color-3.1.3.tgz", + "integrity": "sha512-iO90scth9WAbmgv7ogoq57O9YpKmFBbmoEoCHDB2xMBY0+/KVrqAaCDyCE16dUspeOvIxFFRI+0sEtqDqy2b4A==", + "license": "MIT" + }, + "node_modules/@types/d3-ease": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/@types/d3-ease/-/d3-ease-3.0.2.tgz", + "integrity": "sha512-NcV1JjO5oDzoK26oMzbILE6HW7uVXOHLQvHshBUW4UMdZGfiY6v5BeQwh9a9tCzv+CeefZQHJt5SRgK154RtiA==", + "license": "MIT" + }, + "node_modules/@types/d3-interpolate": { + "version": "3.0.4", + "resolved": "https://registry.npmjs.org/@types/d3-interpolate/-/d3-interpolate-3.0.4.tgz", + "integrity": "sha512-mgLPETlrpVV1YRJIglr4Ez47g7Yxjl1lj7YKsiMCb27VJH9W8NVM6Bb9d8kkpG/uAQS5AmbA48q2IAolKKo1MA==", + "license": "MIT", + "dependencies": { + "@types/d3-color": "*" + } + }, + "node_modules/@types/d3-path": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/@types/d3-path/-/d3-path-3.1.1.tgz", + "integrity": "sha512-VMZBYyQvbGmWyWVea0EHs/BwLgxc+MKi1zLDCONksozI4YJMcTt8ZEuIR4Sb1MMTE8MMW49v0IwI5+b7RmfWlg==", + "license": "MIT" + }, + "node_modules/@types/d3-scale": { + "version": "4.0.9", + "resolved": "https://registry.npmjs.org/@types/d3-scale/-/d3-scale-4.0.9.tgz", + "integrity": "sha512-dLmtwB8zkAeO/juAMfnV+sItKjlsw2lKdZVVy6LRr0cBmegxSABiLEpGVmSJJ8O08i4+sGR6qQtb6WtuwJdvVw==", + "license": "MIT", + "dependencies": { + "@types/d3-time": "*" + } + }, + "node_modules/@types/d3-shape": { + "version": "3.1.8", + "resolved": "https://registry.npmjs.org/@types/d3-shape/-/d3-shape-3.1.8.tgz", + "integrity": "sha512-lae0iWfcDeR7qt7rA88BNiqdvPS5pFVPpo5OfjElwNaT2yyekbM0C9vK+yqBqEmHr6lDkRnYNoTBYlAgJa7a4w==", + "license": "MIT", + "dependencies": { + "@types/d3-path": "*" + } + }, + "node_modules/@types/d3-time": { + "version": "3.0.4", + "resolved": "https://registry.npmjs.org/@types/d3-time/-/d3-time-3.0.4.tgz", + "integrity": "sha512-yuzZug1nkAAaBlBBikKZTgzCeA+k1uy4ZFwWANOfKw5z5LRhV0gNA7gNkKm7HoK+HRN0wX3EkxGk0fpbWhmB7g==", + "license": "MIT" + }, + "node_modules/@types/d3-timer": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/@types/d3-timer/-/d3-timer-3.0.2.tgz", + "integrity": "sha512-Ps3T8E8dZDam6fUyNiMkekK3XUsaUEik+idO9/YjPtfj2qruF8tFBXS7XhtE4iIXBLxhmLjP3SXpLhVf21I9Lw==", + "license": "MIT" + }, + "node_modules/@types/deep-eql": { + "version": "4.0.2", + "resolved": "https://registry.npmjs.org/@types/deep-eql/-/deep-eql-4.0.2.tgz", + "integrity": "sha512-c9h9dVVMigMPc4bwTvC5dxqtqJZwQPePsWjPlpSOnojbor6pGqdk541lfA7AqFQr5pB1BRdq0juY9db81BwyFw==", + "dev": true, + "license": "MIT" + }, + "node_modules/@types/estree": { + "version": "1.0.8", + "resolved": "https://registry.npmjs.org/@types/estree/-/estree-1.0.8.tgz", + "integrity": "sha512-dWHzHa2WqEXI/O1E9OjrocMTKJl2mSrEolh1Iomrv6U+JuNwaHXsXx9bLu5gG7BUWFIN0skIQJQ/L1rIex4X6w==", + "dev": true, + "license": "MIT" + }, + "node_modules/@types/fs-extra": { + "version": "8.1.5", + "resolved": "https://registry.npmjs.org/@types/fs-extra/-/fs-extra-8.1.5.tgz", + "integrity": "sha512-0dzKcwO+S8s2kuF5Z9oUWatQJj5Uq/iqphEtE3GQJVRRYm/tD1LglU2UnXi2A8jLq5umkGouOXOR9y0n613ZwQ==", + "license": "MIT", + "dependencies": { + "@types/node": "*" + } + }, + "node_modules/@types/json-schema": { + "version": "7.0.15", + "resolved": "https://registry.npmjs.org/@types/json-schema/-/json-schema-7.0.15.tgz", + "integrity": "sha512-5+fP8P8MFNC+AyZCDxrB2pkZFPGzqQWUzpSeuuVLvm8VMcorNYavBqoFcxK8bQz4Qsbn4oUEEem4wDLfcysGHA==", + "dev": true, + "license": "MIT" + }, + "node_modules/@types/json5": { + "version": "0.0.29", + "resolved": "https://registry.npmjs.org/@types/json5/-/json5-0.0.29.tgz", + "integrity": "sha512-dRLjCWHYg4oaA77cxO64oO+7JwCwnIzkZPdrrC71jQmQtlhM556pwKo5bUzqvZndkVbeFLIIi+9TC40JNF5hNQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/@types/node": { + "version": "20.19.37", + "resolved": "https://registry.npmjs.org/@types/node/-/node-20.19.37.tgz", + "integrity": "sha512-8kzdPJ3FsNsVIurqBs7oodNnCEVbni9yUEkaHbgptDACOPW04jimGagZ51E6+lXUwJjgnBw+hyko/lkFWCldqw==", + "license": "MIT", + "dependencies": { + "undici-types": "~6.21.0" + } + }, + "node_modules/@types/react": { + "version": "19.2.14", + "resolved": "https://registry.npmjs.org/@types/react/-/react-19.2.14.tgz", + "integrity": "sha512-ilcTH/UniCkMdtexkoCN0bI7pMcJDvmQFPvuPvmEaYA/NSfFTAgdUSLAoVjaRJm7+6PvcM+q1zYOwS4wTYMF9w==", + "devOptional": true, + "license": "MIT", + "dependencies": { + "csstype": "^3.2.2" + } + }, + "node_modules/@types/react-dom": { + "version": "19.2.3", + "resolved": "https://registry.npmjs.org/@types/react-dom/-/react-dom-19.2.3.tgz", + "integrity": "sha512-jp2L/eY6fn+KgVVQAOqYItbF0VY/YApe5Mz2F0aykSO8gx31bYCZyvSeYxCHKvzHG5eZjc+zyaS5BrBWya2+kQ==", + "dev": true, + "license": "MIT", + "peerDependencies": { + "@types/react": "^19.2.0" + } + }, + "node_modules/@types/slice-ansi": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/@types/slice-ansi/-/slice-ansi-4.0.0.tgz", + "integrity": "sha512-+OpjSaq85gvlZAYINyzKpLeiFkSC4EsC6IIiT6v6TLSU5k5U83fHGj9Lel8oKEXM0HqgrMVCjXPDPVICtxF7EQ==", + "license": "MIT" + }, + "node_modules/@types/statuses": { + "version": "2.0.6", + "resolved": "https://registry.npmjs.org/@types/statuses/-/statuses-2.0.6.tgz", + "integrity": "sha512-xMAgYwceFhRA2zY+XbEA7mxYbA093wdiW8Vu6gZPGWy9cmOyU9XesH1tNcEWsKFd5Vzrqx5T3D38PWx1FIIXkA==", + "license": "MIT" + }, + "node_modules/@types/use-sync-external-store": { + "version": "0.0.6", + "resolved": "https://registry.npmjs.org/@types/use-sync-external-store/-/use-sync-external-store-0.0.6.tgz", + "integrity": "sha512-zFDAD+tlpf2r4asuHEj0XH6pY6i0g5NeAHPn+15wk3BV6JA69eERFXC1gyGThDkVa1zCyKr5jox1+2LbV/AMLg==", + "license": "MIT" + }, + "node_modules/@types/uuid": { + "version": "10.0.0", + "resolved": "https://registry.npmjs.org/@types/uuid/-/uuid-10.0.0.tgz", + "integrity": "sha512-7gqG38EyHgyP1S+7+xomFtL+ZNHcKv6DwNaCZmJmo1vgMugyF3TCnXVg4t1uk89mLNwnLtnY3TpOpCOyp1/xHQ==", + "license": "MIT" + }, + "node_modules/@types/validate-npm-package-name": { + "version": "4.0.2", + "resolved": "https://registry.npmjs.org/@types/validate-npm-package-name/-/validate-npm-package-name-4.0.2.tgz", + "integrity": "sha512-lrpDziQipxCEeK5kWxvljWYhUvOiB2A9izZd9B2AFarYAkqZshb4lPbRs7zKEic6eGtH8V/2qJW+dPp9OtF6bw==", + "license": "MIT" + }, + "node_modules/@types/ws": { + "version": "8.18.1", + "resolved": "https://registry.npmjs.org/@types/ws/-/ws-8.18.1.tgz", + "integrity": "sha512-ThVF6DCVhA8kUGy+aazFQ4kXQ7E1Ty7A3ypFOe0IcJV8O/M511G99AW24irKrW56Wt44yG9+ij8FaqoBGkuBXg==", + "license": "MIT", + "dependencies": { + "@types/node": "*" + } + }, + "node_modules/@typescript-eslint/eslint-plugin": { + "version": "8.57.1", + "resolved": "https://registry.npmjs.org/@typescript-eslint/eslint-plugin/-/eslint-plugin-8.57.1.tgz", + "integrity": "sha512-Gn3aqnvNl4NGc6x3/Bqk1AOn0thyTU9bqDRhiRnUWezgvr2OnhYCWCgC8zXXRVqBsIL1pSDt7T9nJUe0oM0kDQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@eslint-community/regexpp": "^4.12.2", + "@typescript-eslint/scope-manager": "8.57.1", + "@typescript-eslint/type-utils": "8.57.1", + "@typescript-eslint/utils": "8.57.1", + "@typescript-eslint/visitor-keys": "8.57.1", + "ignore": "^7.0.5", + "natural-compare": "^1.4.0", + "ts-api-utils": "^2.4.0" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/typescript-eslint" + }, + "peerDependencies": { + "@typescript-eslint/parser": "^8.57.1", + "eslint": "^8.57.0 || ^9.0.0 || ^10.0.0", + "typescript": ">=4.8.4 <6.0.0" + } + }, + "node_modules/@typescript-eslint/eslint-plugin/node_modules/ignore": { + "version": "7.0.5", + "resolved": "https://registry.npmjs.org/ignore/-/ignore-7.0.5.tgz", + "integrity": "sha512-Hs59xBNfUIunMFgWAbGX5cq6893IbWg4KnrjbYwX3tx0ztorVgTDA6B2sxf8ejHJ4wz8BqGUMYlnzNBer5NvGg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 4" + } + }, + "node_modules/@typescript-eslint/parser": { + "version": "8.57.1", + "resolved": "https://registry.npmjs.org/@typescript-eslint/parser/-/parser-8.57.1.tgz", + "integrity": "sha512-k4eNDan0EIMTT/dUKc/g+rsJ6wcHYhNPdY19VoX/EOtaAG8DLtKCykhrUnuHPYvinn5jhAPgD2Qw9hXBwrahsw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@typescript-eslint/scope-manager": "8.57.1", + "@typescript-eslint/types": "8.57.1", + "@typescript-eslint/typescript-estree": "8.57.1", + "@typescript-eslint/visitor-keys": "8.57.1", + "debug": "^4.4.3" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/typescript-eslint" + }, + "peerDependencies": { + "eslint": "^8.57.0 || ^9.0.0 || ^10.0.0", + "typescript": ">=4.8.4 <6.0.0" + } + }, + "node_modules/@typescript-eslint/project-service": { + "version": "8.57.1", + "resolved": "https://registry.npmjs.org/@typescript-eslint/project-service/-/project-service-8.57.1.tgz", + "integrity": "sha512-vx1F37BRO1OftsYlmG9xay1TqnjNVlqALymwWVuYTdo18XuKxtBpCj1QlzNIEHlvlB27osvXFWptYiEWsVdYsg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@typescript-eslint/tsconfig-utils": "^8.57.1", + "@typescript-eslint/types": "^8.57.1", + "debug": "^4.4.3" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/typescript-eslint" + }, + "peerDependencies": { + "typescript": ">=4.8.4 <6.0.0" + } + }, + "node_modules/@typescript-eslint/scope-manager": { + "version": "8.57.1", + "resolved": "https://registry.npmjs.org/@typescript-eslint/scope-manager/-/scope-manager-8.57.1.tgz", + "integrity": "sha512-hs/QcpCwlwT2L5S+3fT6gp0PabyGk4Q0Rv2doJXA0435/OpnSR3VRgvrp8Xdoc3UAYSg9cyUjTeFXZEPg/3OKg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@typescript-eslint/types": "8.57.1", + "@typescript-eslint/visitor-keys": "8.57.1" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/typescript-eslint" + } + }, + "node_modules/@typescript-eslint/tsconfig-utils": { + "version": "8.57.1", + "resolved": "https://registry.npmjs.org/@typescript-eslint/tsconfig-utils/-/tsconfig-utils-8.57.1.tgz", + "integrity": "sha512-0lgOZB8cl19fHO4eI46YUx2EceQqhgkPSuCGLlGi79L2jwYY1cxeYc1Nae8Aw1xjgW3PKVDLlr3YJ6Bxx8HkWg==", + "dev": true, + "license": "MIT", + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/typescript-eslint" + }, + "peerDependencies": { + "typescript": ">=4.8.4 <6.0.0" + } + }, + "node_modules/@typescript-eslint/type-utils": { + "version": "8.57.1", + "resolved": "https://registry.npmjs.org/@typescript-eslint/type-utils/-/type-utils-8.57.1.tgz", + "integrity": "sha512-+Bwwm0ScukFdyoJsh2u6pp4S9ktegF98pYUU0hkphOOqdMB+1sNQhIz8y5E9+4pOioZijrkfNO/HUJVAFFfPKA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@typescript-eslint/types": "8.57.1", + "@typescript-eslint/typescript-estree": "8.57.1", + "@typescript-eslint/utils": "8.57.1", + "debug": "^4.4.3", + "ts-api-utils": "^2.4.0" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/typescript-eslint" + }, + "peerDependencies": { + "eslint": "^8.57.0 || ^9.0.0 || ^10.0.0", + "typescript": ">=4.8.4 <6.0.0" + } + }, + "node_modules/@typescript-eslint/types": { + "version": "8.57.1", + "resolved": "https://registry.npmjs.org/@typescript-eslint/types/-/types-8.57.1.tgz", + "integrity": "sha512-S29BOBPJSFUiblEl6RzPPjJt6w25A6XsBqRVDt53tA/tlL8q7ceQNZHTjPeONt/3S7KRI4quk+yP9jK2WjBiPQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/typescript-eslint" + } + }, + "node_modules/@typescript-eslint/typescript-estree": { + "version": "8.57.1", + "resolved": "https://registry.npmjs.org/@typescript-eslint/typescript-estree/-/typescript-estree-8.57.1.tgz", + "integrity": "sha512-ybe2hS9G6pXpqGtPli9Gx9quNV0TWLOmh58ADlmZe9DguLq0tiAKVjirSbtM1szG6+QH6rVXyU6GTLQbWnMY+g==", + "dev": true, + "license": "MIT", + "dependencies": { + "@typescript-eslint/project-service": "8.57.1", + "@typescript-eslint/tsconfig-utils": "8.57.1", + "@typescript-eslint/types": "8.57.1", + "@typescript-eslint/visitor-keys": "8.57.1", + "debug": "^4.4.3", + "minimatch": "^10.2.2", + "semver": "^7.7.3", + "tinyglobby": "^0.2.15", + "ts-api-utils": "^2.4.0" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/typescript-eslint" + }, + "peerDependencies": { + "typescript": ">=4.8.4 <6.0.0" + } + }, + "node_modules/@typescript-eslint/typescript-estree/node_modules/balanced-match": { + "version": "4.0.4", + "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-4.0.4.tgz", + "integrity": "sha512-BLrgEcRTwX2o6gGxGOCNyMvGSp35YofuYzw9h1IMTRmKqttAZZVU67bdb9Pr2vUHA8+j3i2tJfjO6C6+4myGTA==", + "dev": true, + "license": "MIT", + "engines": { + "node": "18 || 20 || >=22" + } + }, + "node_modules/@typescript-eslint/typescript-estree/node_modules/brace-expansion": { + "version": "5.0.5", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-5.0.5.tgz", + "integrity": "sha512-VZznLgtwhn+Mact9tfiwx64fA9erHH/MCXEUfB/0bX/6Fz6ny5EGTXYltMocqg4xFAQZtnO3DHWWXi8RiuN7cQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "balanced-match": "^4.0.2" + }, + "engines": { + "node": "18 || 20 || >=22" + } + }, + "node_modules/@typescript-eslint/typescript-estree/node_modules/minimatch": { + "version": "10.2.4", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-10.2.4.tgz", + "integrity": "sha512-oRjTw/97aTBN0RHbYCdtF1MQfvusSIBQM0IZEgzl6426+8jSC0nF1a/GmnVLpfB9yyr6g6FTqWqiZVbxrtaCIg==", + "dev": true, + "license": "BlueOak-1.0.0", + "dependencies": { + "brace-expansion": "^5.0.2" + }, + "engines": { + "node": "18 || 20 || >=22" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/@typescript-eslint/typescript-estree/node_modules/semver": { + "version": "7.7.4", + "resolved": "https://registry.npmjs.org/semver/-/semver-7.7.4.tgz", + "integrity": "sha512-vFKC2IEtQnVhpT78h1Yp8wzwrf8CM+MzKMHGJZfBtzhZNycRFnXsHk6E5TxIkkMsgNS7mdX3AGB7x2QM2di4lA==", + "dev": true, + "license": "ISC", + "bin": { + "semver": "bin/semver.js" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/@typescript-eslint/utils": { + "version": "8.57.1", + "resolved": "https://registry.npmjs.org/@typescript-eslint/utils/-/utils-8.57.1.tgz", + "integrity": "sha512-XUNSJ/lEVFttPMMoDVA2r2bwrl8/oPx8cURtczkSEswY5T3AeLmCy+EKWQNdL4u0MmAHOjcWrqJp2cdvgjn8dQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@eslint-community/eslint-utils": "^4.9.1", + "@typescript-eslint/scope-manager": "8.57.1", + "@typescript-eslint/types": "8.57.1", + "@typescript-eslint/typescript-estree": "8.57.1" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/typescript-eslint" + }, + "peerDependencies": { + "eslint": "^8.57.0 || ^9.0.0 || ^10.0.0", + "typescript": ">=4.8.4 <6.0.0" + } + }, + "node_modules/@typescript-eslint/visitor-keys": { + "version": "8.57.1", + "resolved": "https://registry.npmjs.org/@typescript-eslint/visitor-keys/-/visitor-keys-8.57.1.tgz", + "integrity": "sha512-YWnmJkXbofiz9KbnbbwuA2rpGkFPLbAIetcCNO6mJ8gdhdZ/v7WDXsoGFAJuM6ikUFKTlSQnjWnVO4ux+UzS6A==", + "dev": true, + "license": "MIT", + "dependencies": { + "@typescript-eslint/types": "8.57.1", + "eslint-visitor-keys": "^5.0.0" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/typescript-eslint" + } + }, + "node_modules/@typescript-eslint/visitor-keys/node_modules/eslint-visitor-keys": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/eslint-visitor-keys/-/eslint-visitor-keys-5.0.1.tgz", + "integrity": "sha512-tD40eHxA35h0PEIZNeIjkHoDR4YjjJp34biM0mDvplBe//mB+IHCqHDGV7pxF+7MklTvighcCPPZC7ynWyjdTA==", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": "^20.19.0 || ^22.13.0 || >=24" + }, + "funding": { + "url": "https://opencollective.com/eslint" + } + }, + "node_modules/@unrs/resolver-binding-android-arm-eabi": { + "version": "1.11.1", + "resolved": "https://registry.npmjs.org/@unrs/resolver-binding-android-arm-eabi/-/resolver-binding-android-arm-eabi-1.11.1.tgz", + "integrity": "sha512-ppLRUgHVaGRWUx0R0Ut06Mjo9gBaBkg3v/8AxusGLhsIotbBLuRk51rAzqLC8gq6NyyAojEXglNjzf6R948DNw==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ] + }, + "node_modules/@unrs/resolver-binding-android-arm64": { + "version": "1.11.1", + "resolved": "https://registry.npmjs.org/@unrs/resolver-binding-android-arm64/-/resolver-binding-android-arm64-1.11.1.tgz", + "integrity": "sha512-lCxkVtb4wp1v+EoN+HjIG9cIIzPkX5OtM03pQYkG+U5O/wL53LC4QbIeazgiKqluGeVEeBlZahHalCaBvU1a2g==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ] + }, + "node_modules/@unrs/resolver-binding-darwin-arm64": { + "version": "1.11.1", + "resolved": "https://registry.npmjs.org/@unrs/resolver-binding-darwin-arm64/-/resolver-binding-darwin-arm64-1.11.1.tgz", + "integrity": "sha512-gPVA1UjRu1Y/IsB/dQEsp2V1pm44Of6+LWvbLc9SDk1c2KhhDRDBUkQCYVWe6f26uJb3fOK8saWMgtX8IrMk3g==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ] + }, + "node_modules/@unrs/resolver-binding-darwin-x64": { + "version": "1.11.1", + "resolved": "https://registry.npmjs.org/@unrs/resolver-binding-darwin-x64/-/resolver-binding-darwin-x64-1.11.1.tgz", + "integrity": "sha512-cFzP7rWKd3lZaCsDze07QX1SC24lO8mPty9vdP+YVa3MGdVgPmFc59317b2ioXtgCMKGiCLxJ4HQs62oz6GfRQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ] + }, + "node_modules/@unrs/resolver-binding-freebsd-x64": { + "version": "1.11.1", + "resolved": "https://registry.npmjs.org/@unrs/resolver-binding-freebsd-x64/-/resolver-binding-freebsd-x64-1.11.1.tgz", + "integrity": "sha512-fqtGgak3zX4DCB6PFpsH5+Kmt/8CIi4Bry4rb1ho6Av2QHTREM+47y282Uqiu3ZRF5IQioJQ5qWRV6jduA+iGw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ] + }, + "node_modules/@unrs/resolver-binding-linux-arm-gnueabihf": { + "version": "1.11.1", + "resolved": "https://registry.npmjs.org/@unrs/resolver-binding-linux-arm-gnueabihf/-/resolver-binding-linux-arm-gnueabihf-1.11.1.tgz", + "integrity": "sha512-u92mvlcYtp9MRKmP+ZvMmtPN34+/3lMHlyMj7wXJDeXxuM0Vgzz0+PPJNsro1m3IZPYChIkn944wW8TYgGKFHw==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@unrs/resolver-binding-linux-arm-musleabihf": { + "version": "1.11.1", + "resolved": "https://registry.npmjs.org/@unrs/resolver-binding-linux-arm-musleabihf/-/resolver-binding-linux-arm-musleabihf-1.11.1.tgz", + "integrity": "sha512-cINaoY2z7LVCrfHkIcmvj7osTOtm6VVT16b5oQdS4beibX2SYBwgYLmqhBjA1t51CarSaBuX5YNsWLjsqfW5Cw==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@unrs/resolver-binding-linux-arm64-gnu": { + "version": "1.11.1", + "resolved": "https://registry.npmjs.org/@unrs/resolver-binding-linux-arm64-gnu/-/resolver-binding-linux-arm64-gnu-1.11.1.tgz", + "integrity": "sha512-34gw7PjDGB9JgePJEmhEqBhWvCiiWCuXsL9hYphDF7crW7UgI05gyBAi6MF58uGcMOiOqSJ2ybEeCvHcq0BCmQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@unrs/resolver-binding-linux-arm64-musl": { + "version": "1.11.1", + "resolved": "https://registry.npmjs.org/@unrs/resolver-binding-linux-arm64-musl/-/resolver-binding-linux-arm64-musl-1.11.1.tgz", + "integrity": "sha512-RyMIx6Uf53hhOtJDIamSbTskA99sPHS96wxVE/bJtePJJtpdKGXO1wY90oRdXuYOGOTuqjT8ACccMc4K6QmT3w==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@unrs/resolver-binding-linux-ppc64-gnu": { + "version": "1.11.1", + "resolved": "https://registry.npmjs.org/@unrs/resolver-binding-linux-ppc64-gnu/-/resolver-binding-linux-ppc64-gnu-1.11.1.tgz", + "integrity": "sha512-D8Vae74A4/a+mZH0FbOkFJL9DSK2R6TFPC9M+jCWYia/q2einCubX10pecpDiTmkJVUH+y8K3BZClycD8nCShA==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@unrs/resolver-binding-linux-riscv64-gnu": { + "version": "1.11.1", + "resolved": "https://registry.npmjs.org/@unrs/resolver-binding-linux-riscv64-gnu/-/resolver-binding-linux-riscv64-gnu-1.11.1.tgz", + "integrity": "sha512-frxL4OrzOWVVsOc96+V3aqTIQl1O2TjgExV4EKgRY09AJ9leZpEg8Ak9phadbuX0BA4k8U5qtvMSQQGGmaJqcQ==", + "cpu": [ + "riscv64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@unrs/resolver-binding-linux-riscv64-musl": { + "version": "1.11.1", + "resolved": "https://registry.npmjs.org/@unrs/resolver-binding-linux-riscv64-musl/-/resolver-binding-linux-riscv64-musl-1.11.1.tgz", + "integrity": "sha512-mJ5vuDaIZ+l/acv01sHoXfpnyrNKOk/3aDoEdLO/Xtn9HuZlDD6jKxHlkN8ZhWyLJsRBxfv9GYM2utQ1SChKew==", + "cpu": [ + "riscv64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@unrs/resolver-binding-linux-s390x-gnu": { + "version": "1.11.1", + "resolved": "https://registry.npmjs.org/@unrs/resolver-binding-linux-s390x-gnu/-/resolver-binding-linux-s390x-gnu-1.11.1.tgz", + "integrity": "sha512-kELo8ebBVtb9sA7rMe1Cph4QHreByhaZ2QEADd9NzIQsYNQpt9UkM9iqr2lhGr5afh885d/cB5QeTXSbZHTYPg==", + "cpu": [ + "s390x" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@unrs/resolver-binding-linux-x64-gnu": { + "version": "1.11.1", + "resolved": "https://registry.npmjs.org/@unrs/resolver-binding-linux-x64-gnu/-/resolver-binding-linux-x64-gnu-1.11.1.tgz", + "integrity": "sha512-C3ZAHugKgovV5YvAMsxhq0gtXuwESUKc5MhEtjBpLoHPLYM+iuwSj3lflFwK3DPm68660rZ7G8BMcwSro7hD5w==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@unrs/resolver-binding-linux-x64-musl": { + "version": "1.11.1", + "resolved": "https://registry.npmjs.org/@unrs/resolver-binding-linux-x64-musl/-/resolver-binding-linux-x64-musl-1.11.1.tgz", + "integrity": "sha512-rV0YSoyhK2nZ4vEswT/QwqzqQXw5I6CjoaYMOX0TqBlWhojUf8P94mvI7nuJTeaCkkds3QE4+zS8Ko+GdXuZtA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@unrs/resolver-binding-wasm32-wasi": { + "version": "1.11.1", + "resolved": "https://registry.npmjs.org/@unrs/resolver-binding-wasm32-wasi/-/resolver-binding-wasm32-wasi-1.11.1.tgz", + "integrity": "sha512-5u4RkfxJm+Ng7IWgkzi3qrFOvLvQYnPBmjmZQ8+szTK/b31fQCnleNl1GgEt7nIsZRIf5PLhPwT0WM+q45x/UQ==", + "cpu": [ + "wasm32" + ], + "dev": true, + "license": "MIT", + "optional": true, + "dependencies": { + "@napi-rs/wasm-runtime": "^0.2.11" + }, + "engines": { + "node": ">=14.0.0" + } + }, + "node_modules/@unrs/resolver-binding-win32-arm64-msvc": { + "version": "1.11.1", + "resolved": "https://registry.npmjs.org/@unrs/resolver-binding-win32-arm64-msvc/-/resolver-binding-win32-arm64-msvc-1.11.1.tgz", + "integrity": "sha512-nRcz5Il4ln0kMhfL8S3hLkxI85BXs3o8EYoattsJNdsX4YUU89iOkVn7g0VHSRxFuVMdM4Q1jEpIId1Ihim/Uw==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ] + }, + "node_modules/@unrs/resolver-binding-win32-ia32-msvc": { + "version": "1.11.1", + "resolved": "https://registry.npmjs.org/@unrs/resolver-binding-win32-ia32-msvc/-/resolver-binding-win32-ia32-msvc-1.11.1.tgz", + "integrity": "sha512-DCEI6t5i1NmAZp6pFonpD5m7i6aFrpofcp4LA2i8IIq60Jyo28hamKBxNrZcyOwVOZkgsRp9O2sXWBWP8MnvIQ==", + "cpu": [ + "ia32" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ] + }, + "node_modules/@unrs/resolver-binding-win32-x64-msvc": { + "version": "1.11.1", + "resolved": "https://registry.npmjs.org/@unrs/resolver-binding-win32-x64-msvc/-/resolver-binding-win32-x64-msvc-1.11.1.tgz", + "integrity": "sha512-lrW200hZdbfRtztbygyaq/6jP6AKE8qQN2KvPcJ+x7wiD038YtnYtZ82IMNJ69GJibV7bwL3y9FgK+5w/pYt6g==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ] + }, + "node_modules/@vitest/expect": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/@vitest/expect/-/expect-4.1.0.tgz", + "integrity": "sha512-EIxG7k4wlWweuCLG9Y5InKFwpMEOyrMb6ZJ1ihYu02LVj/bzUwn2VMU+13PinsjRW75XnITeFrQBMH5+dLvCDA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@standard-schema/spec": "^1.1.0", + "@types/chai": "^5.2.2", + "@vitest/spy": "4.1.0", + "@vitest/utils": "4.1.0", + "chai": "^6.2.2", + "tinyrainbow": "^3.0.3" + }, + "funding": { + "url": "https://opencollective.com/vitest" + } + }, + "node_modules/@vitest/mocker": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/@vitest/mocker/-/mocker-4.1.0.tgz", + "integrity": "sha512-evxREh+Hork43+Y4IOhTo+h5lGmVRyjqI739Rz4RlUPqwrkFFDF6EMvOOYjTx4E8Tl6gyCLRL8Mu7Ry12a13Tw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@vitest/spy": "4.1.0", + "estree-walker": "^3.0.3", + "magic-string": "^0.30.21" + }, + "funding": { + "url": "https://opencollective.com/vitest" + }, + "peerDependencies": { + "msw": "^2.4.9", + "vite": "^6.0.0 || ^7.0.0 || ^8.0.0-0" + }, + "peerDependenciesMeta": { + "msw": { + "optional": true + }, + "vite": { + "optional": true + } + } + }, + "node_modules/@vitest/pretty-format": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/@vitest/pretty-format/-/pretty-format-4.1.0.tgz", + "integrity": "sha512-3RZLZlh88Ib0J7NQTRATfc/3ZPOnSUn2uDBUoGNn5T36+bALixmzphN26OUD3LRXWkJu4H0s5vvUeqBiw+kS0A==", + "dev": true, + "license": "MIT", + "dependencies": { + "tinyrainbow": "^3.0.3" + }, + "funding": { + "url": "https://opencollective.com/vitest" + } + }, + "node_modules/@vitest/runner": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/@vitest/runner/-/runner-4.1.0.tgz", + "integrity": "sha512-Duvx2OzQ7d6OjchL+trw+aSrb9idh7pnNfxrklo14p3zmNL4qPCDeIJAK+eBKYjkIwG96Bc6vYuxhqDXQOWpoQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@vitest/utils": "4.1.0", + "pathe": "^2.0.3" + }, + "funding": { + "url": "https://opencollective.com/vitest" + } + }, + "node_modules/@vitest/snapshot": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/@vitest/snapshot/-/snapshot-4.1.0.tgz", + "integrity": "sha512-0Vy9euT1kgsnj1CHttwi9i9o+4rRLEaPRSOJ5gyv579GJkNpgJK+B4HSv/rAWixx2wdAFci1X4CEPjiu2bXIMg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@vitest/pretty-format": "4.1.0", + "@vitest/utils": "4.1.0", + "magic-string": "^0.30.21", + "pathe": "^2.0.3" + }, + "funding": { + "url": "https://opencollective.com/vitest" + } + }, + "node_modules/@vitest/spy": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/@vitest/spy/-/spy-4.1.0.tgz", + "integrity": "sha512-pz77k+PgNpyMDv2FV6qmk5ZVau6c3R8HC8v342T2xlFxQKTrSeYw9waIJG8KgV9fFwAtTu4ceRzMivPTH6wSxw==", + "dev": true, + "license": "MIT", + "funding": { + "url": "https://opencollective.com/vitest" + } + }, + "node_modules/@vitest/utils": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/@vitest/utils/-/utils-4.1.0.tgz", + "integrity": "sha512-XfPXT6a8TZY3dcGY8EdwsBulFCIw+BeeX0RZn2x/BtiY/75YGh8FeWGG8QISN/WhaqSrE2OrlDgtF8q5uhOTmw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@vitest/pretty-format": "4.1.0", + "convert-source-map": "^2.0.0", + "tinyrainbow": "^3.0.3" + }, + "funding": { + "url": "https://opencollective.com/vitest" + } + }, + "node_modules/@xmldom/xmldom": { + "version": "0.8.12", + "resolved": "https://registry.npmjs.org/@xmldom/xmldom/-/xmldom-0.8.12.tgz", + "integrity": "sha512-9k/gHF6n/pAi/9tqr3m3aqkuiNosYTurLLUtc7xQ9sxB/wm7WPygCv8GYa6mS0fLJEHhqMC1ATYhz++U/lRHqg==", + "license": "MIT", + "engines": { + "node": ">=10.0.0" + } + }, + "node_modules/accepts": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/accepts/-/accepts-2.0.0.tgz", + "integrity": "sha512-5cvg6CtKwfgdmVqY1WIiXKc3Q1bkRqGLi+2W/6ao+6Y7gu/RCwRuAhGEzh5B4KlszSuTLgZYuqFqo5bImjNKng==", + "license": "MIT", + "dependencies": { + "mime-types": "^3.0.0", + "negotiator": "^1.0.0" + }, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/acorn": { + "version": "8.16.0", + "resolved": "https://registry.npmjs.org/acorn/-/acorn-8.16.0.tgz", + "integrity": "sha512-UVJyE9MttOsBQIDKw1skb9nAwQuR5wuGD3+82K6JgJlm/Y+KI92oNsMNGZCYdDsVtRHSak0pcV5Dno5+4jh9sw==", + "dev": true, + "license": "MIT", + "bin": { + "acorn": "bin/acorn" + }, + "engines": { + "node": ">=0.4.0" + } + }, + "node_modules/acorn-jsx": { + "version": "5.3.2", + "resolved": "https://registry.npmjs.org/acorn-jsx/-/acorn-jsx-5.3.2.tgz", + "integrity": "sha512-rq9s+JNhf0IChjtDXxllJ7g41oZk5SlXtp0LHwyA5cejwn7vKmKp4pPri6YEePv2PU65sAsegbXtIinmDFDXgQ==", + "dev": true, + "license": "MIT", + "peerDependencies": { + "acorn": "^6.0.0 || ^7.0.0 || ^8.0.0" + } + }, + "node_modules/agent-base": { + "version": "7.1.4", + "resolved": "https://registry.npmjs.org/agent-base/-/agent-base-7.1.4.tgz", + "integrity": "sha512-MnA+YT8fwfJPgBx3m60MNqakm30XOkyIoH1y6huTQvC0PwZG7ki8NacLBcrPbNoo8vEZy7Jpuk7+jMO+CUovTQ==", + "license": "MIT", + "engines": { + "node": ">= 14" + } + }, + "node_modules/ajv": { + "version": "6.14.0", + "resolved": "https://registry.npmjs.org/ajv/-/ajv-6.14.0.tgz", + "integrity": "sha512-IWrosm/yrn43eiKqkfkHis7QioDleaXQHdDVPKg0FSwwd/DuvyX79TZnFOnYpB7dcsFAMmtFztZuXPDvSePkFw==", + "dev": true, + "license": "MIT", + "dependencies": { + "fast-deep-equal": "^3.1.1", + "fast-json-stable-stringify": "^2.0.0", + "json-schema-traverse": "^0.4.1", + "uri-js": "^4.2.2" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/epoberezkin" + } + }, + "node_modules/ajv-formats": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/ajv-formats/-/ajv-formats-3.0.1.tgz", + "integrity": "sha512-8iUql50EUR+uUcdRQ3HDqa6EVyo3docL8g5WJ3FNcWmu62IbkGUue/pEyLBW8VGKKucTPgqeks4fIU1DA4yowQ==", + "license": "MIT", + "dependencies": { + "ajv": "^8.0.0" + }, + "peerDependencies": { + "ajv": "^8.0.0" + }, + "peerDependenciesMeta": { + "ajv": { + "optional": true + } + } + }, + "node_modules/ajv-formats/node_modules/ajv": { + "version": "8.18.0", + "resolved": "https://registry.npmjs.org/ajv/-/ajv-8.18.0.tgz", + "integrity": "sha512-PlXPeEWMXMZ7sPYOHqmDyCJzcfNrUr3fGNKtezX14ykXOEIvyK81d+qydx89KY5O71FKMPaQ2vBfBFI5NHR63A==", + "license": "MIT", + "dependencies": { + "fast-deep-equal": "^3.1.3", + "fast-uri": "^3.0.1", + "json-schema-traverse": "^1.0.0", + "require-from-string": "^2.0.2" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/epoberezkin" + } + }, + "node_modules/ajv-formats/node_modules/json-schema-traverse": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-1.0.0.tgz", + "integrity": "sha512-NM8/P9n3XjXhIZn1lLhkFaACTOURQXjWhV4BA/RnOv8xvgqtqpAX9IO4mRQxSx1Rlo4tqzeqb0sOlruaOy3dug==", + "license": "MIT" + }, + "node_modules/ansi-regex": { + "version": "6.2.2", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-6.2.2.tgz", + "integrity": "sha512-Bq3SmSpyFHaWjPk8If9yc6svM8c56dB5BAtW4Qbw5jHTwwXXcTLoRMkpDJp6VL0XzlWaCHTXrkFURMYmD0sLqg==", + "license": "MIT", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/chalk/ansi-regex?sponsor=1" + } + }, + "node_modules/ansi-styles": { + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.3.0.tgz", + "integrity": "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==", + "license": "MIT", + "dependencies": { + "color-convert": "^2.0.1" + }, + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/chalk/ansi-styles?sponsor=1" + } + }, + "node_modules/argparse": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/argparse/-/argparse-2.0.1.tgz", + "integrity": "sha512-8+9WqebbFzpX9OR+Wa6O29asIogeRMzcGtAINdpMHHyAg10f05aSFVBbcEqGf/PXw1EjAZ+q2/bEBg3DvurK3Q==", + "license": "Python-2.0" + }, + "node_modules/aria-query": { + "version": "5.3.2", + "resolved": "https://registry.npmjs.org/aria-query/-/aria-query-5.3.2.tgz", + "integrity": "sha512-COROpnaoap1E2F000S62r6A60uHZnmlvomhfyT2DlTcrY1OrBKn2UhH7qn5wTC9zMvD0AY7csdPSNwKP+7WiQw==", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/array-buffer-byte-length": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/array-buffer-byte-length/-/array-buffer-byte-length-1.0.2.tgz", + "integrity": "sha512-LHE+8BuR7RYGDKvnrmcuSq3tDcKv9OFEXQt/HpbZhY7V6h0zlUXutnAD82GiFx9rdieCMjkvtcsPqBwgUl1Iiw==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bound": "^1.0.3", + "is-array-buffer": "^3.0.5" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/array-includes": { + "version": "3.1.9", + "resolved": "https://registry.npmjs.org/array-includes/-/array-includes-3.1.9.tgz", + "integrity": "sha512-FmeCCAenzH0KH381SPT5FZmiA/TmpndpcaShhfgEN9eCVjnFBqq3l1xrI42y8+PPLI6hypzou4GXw00WHmPBLQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bind": "^1.0.8", + "call-bound": "^1.0.4", + "define-properties": "^1.2.1", + "es-abstract": "^1.24.0", + "es-object-atoms": "^1.1.1", + "get-intrinsic": "^1.3.0", + "is-string": "^1.1.1", + "math-intrinsics": "^1.1.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/array.prototype.findlast": { + "version": "1.2.5", + "resolved": "https://registry.npmjs.org/array.prototype.findlast/-/array.prototype.findlast-1.2.5.tgz", + "integrity": "sha512-CVvd6FHg1Z3POpBLxO6E6zr+rSKEQ9L6rZHAaY7lLfhKsWYUBBOuMs0e9o24oopj6H+geRCX0YJ+TJLBK2eHyQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bind": "^1.0.7", + "define-properties": "^1.2.1", + "es-abstract": "^1.23.2", + "es-errors": "^1.3.0", + "es-object-atoms": "^1.0.0", + "es-shim-unscopables": "^1.0.2" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/array.prototype.findlastindex": { + "version": "1.2.6", + "resolved": "https://registry.npmjs.org/array.prototype.findlastindex/-/array.prototype.findlastindex-1.2.6.tgz", + "integrity": "sha512-F/TKATkzseUExPlfvmwQKGITM3DGTK+vkAsCZoDc5daVygbJBnjEUCbgkAvVFsgfXfX4YIqZ/27G3k3tdXrTxQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bind": "^1.0.8", + "call-bound": "^1.0.4", + "define-properties": "^1.2.1", + "es-abstract": "^1.23.9", + "es-errors": "^1.3.0", + "es-object-atoms": "^1.1.1", + "es-shim-unscopables": "^1.1.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/array.prototype.flat": { + "version": "1.3.3", + "resolved": "https://registry.npmjs.org/array.prototype.flat/-/array.prototype.flat-1.3.3.tgz", + "integrity": "sha512-rwG/ja1neyLqCuGZ5YYrznA62D4mZXg0i1cIskIUKSiqF3Cje9/wXAls9B9s1Wa2fomMsIv8czB8jZcPmxCXFg==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bind": "^1.0.8", + "define-properties": "^1.2.1", + "es-abstract": "^1.23.5", + "es-shim-unscopables": "^1.0.2" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/array.prototype.flatmap": { + "version": "1.3.3", + "resolved": "https://registry.npmjs.org/array.prototype.flatmap/-/array.prototype.flatmap-1.3.3.tgz", + "integrity": "sha512-Y7Wt51eKJSyi80hFrJCePGGNo5ktJCslFuboqJsbf57CCPcm5zztluPlc4/aD8sWsKvlwatezpV4U1efk8kpjg==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bind": "^1.0.8", + "define-properties": "^1.2.1", + "es-abstract": "^1.23.5", + "es-shim-unscopables": "^1.0.2" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/array.prototype.tosorted": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/array.prototype.tosorted/-/array.prototype.tosorted-1.1.4.tgz", + "integrity": "sha512-p6Fx8B7b7ZhL/gmUsAy0D15WhvDccw3mnGNbZpi3pmeJdxtWsj2jEaI4Y6oo3XiHfzuSgPwKc04MYt6KgvC/wA==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bind": "^1.0.7", + "define-properties": "^1.2.1", + "es-abstract": "^1.23.3", + "es-errors": "^1.3.0", + "es-shim-unscopables": "^1.0.2" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/arraybuffer.prototype.slice": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/arraybuffer.prototype.slice/-/arraybuffer.prototype.slice-1.0.4.tgz", + "integrity": "sha512-BNoCY6SXXPQ7gF2opIP4GBE+Xw7U+pHMYKuzjgCN3GwiaIR09UUeKfheyIry77QtrCBlC0KK0q5/TER/tYh3PQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "array-buffer-byte-length": "^1.0.1", + "call-bind": "^1.0.8", + "define-properties": "^1.2.1", + "es-abstract": "^1.23.5", + "es-errors": "^1.3.0", + "get-intrinsic": "^1.2.6", + "is-array-buffer": "^3.0.4" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/assertion-error": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/assertion-error/-/assertion-error-2.0.1.tgz", + "integrity": "sha512-Izi8RQcffqCeNVgFigKli1ssklIbpHnCYc6AknXGYoB6grJqyeby7jv12JUQgmTAnIDnbck1uxksT4dzN3PWBA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12" + } + }, + "node_modules/ast-types": { + "version": "0.16.1", + "resolved": "https://registry.npmjs.org/ast-types/-/ast-types-0.16.1.tgz", + "integrity": "sha512-6t10qk83GOG8p0vKmaCr8eiilZwO171AvbROMtvvNiwrTly62t+7XkA8RdIIVbpMhCASAsxgAzdRSwh6nw/5Dg==", + "license": "MIT", + "dependencies": { + "tslib": "^2.0.1" + }, + "engines": { + "node": ">=4" + } + }, + "node_modules/ast-types-flow": { + "version": "0.0.8", + "resolved": "https://registry.npmjs.org/ast-types-flow/-/ast-types-flow-0.0.8.tgz", + "integrity": "sha512-OH/2E5Fg20h2aPrbe+QL8JZQFko0YZaF+j4mnQ7BGhfavO7OpSLa8a0y9sBwomHdSbkhTS8TQNayBfnW5DwbvQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/astral-regex": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/astral-regex/-/astral-regex-2.0.0.tgz", + "integrity": "sha512-Z7tMw1ytTXt5jqMcOP+OQteU1VuNK9Y02uuJtKQ1Sv69jXQKKg5cibLwGJow8yzZP+eAc18EmLGPal0bp36rvQ==", + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/async-function": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/async-function/-/async-function-1.0.0.tgz", + "integrity": "sha512-hsU18Ae8CDTR6Kgu9DYf0EbCr/a5iGL0rytQDobUcdpYOKokk8LEjVphnXkDkgpi0wYVsqrXuP0bZxJaTqdgoA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/async-mutex": { + "version": "0.5.0", + "resolved": "https://registry.npmjs.org/async-mutex/-/async-mutex-0.5.0.tgz", + "integrity": "sha512-1A94B18jkJ3DYq284ohPxoXbfTA5HsQ7/Mf4DEhcyLx3Bz27Rh59iScbB6EPiP+B+joue6YCxcMXSbFC1tZKwA==", + "license": "MIT", + "dependencies": { + "tslib": "^2.4.0" + } + }, + "node_modules/at-least-node": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/at-least-node/-/at-least-node-1.0.0.tgz", + "integrity": "sha512-+q/t7Ekv1EDY2l6Gda6LLiX14rU9TV20Wa3ofeQmwPFZbOMo9DXrLbOjFaaclkXKWidIaopwAObQDqwWtGUjqg==", + "license": "ISC", + "engines": { + "node": ">= 4.0.0" + } + }, + "node_modules/available-typed-arrays": { + "version": "1.0.7", + "resolved": "https://registry.npmjs.org/available-typed-arrays/-/available-typed-arrays-1.0.7.tgz", + "integrity": "sha512-wvUjBtSGN7+7SjNpq/9M2Tg350UZD3q62IFZLbRAR1bSMlCo1ZaeW+BJ+D090e4hIIZLBcTDWe4Mh4jvUDajzQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "possible-typed-array-names": "^1.0.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/aws-ssl-profiles": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/aws-ssl-profiles/-/aws-ssl-profiles-1.1.2.tgz", + "integrity": "sha512-NZKeq9AfyQvEeNlN0zSYAaWrmBffJh3IELMZfRpJVWgrpEbtEpnjvzqBPf+mxoI287JohRDoa+/nsfqqiZmF6g==", + "devOptional": true, + "license": "MIT", + "engines": { + "node": ">= 6.0.0" + } + }, + "node_modules/axe-core": { + "version": "4.11.1", + "resolved": "https://registry.npmjs.org/axe-core/-/axe-core-4.11.1.tgz", + "integrity": "sha512-BASOg+YwO2C+346x3LZOeoovTIoTrRqEsqMa6fmfAV0P+U9mFr9NsyOEpiYvFjbc64NMrSswhV50WdXzdb/Z5A==", + "dev": true, + "license": "MPL-2.0", + "engines": { + "node": ">=4" + } + }, + "node_modules/axobject-query": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/axobject-query/-/axobject-query-4.1.0.tgz", + "integrity": "sha512-qIj0G9wZbMGNLjLmg1PT6v2mE9AH2zlnADJD/2tC6E00hgmhUOfEB6greHPAfLRSufHqROIUTkw6E+M3lH0PTQ==", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/balanced-match": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.2.tgz", + "integrity": "sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==", + "dev": true, + "license": "MIT" + }, + "node_modules/base64-js": { + "version": "1.5.1", + "resolved": "https://registry.npmjs.org/base64-js/-/base64-js-1.5.1.tgz", + "integrity": "sha512-AKpaYlHn8t4SVbOHCy+b5+KKgvR4vrsD8vbvrbiQJps7fKDTkjkDry6ji0rUJjC0kzbNePLwzxq8iypo41qeWA==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ], + "license": "MIT" + }, + "node_modules/baseline-browser-mapping": { + "version": "2.10.8", + "resolved": "https://registry.npmjs.org/baseline-browser-mapping/-/baseline-browser-mapping-2.10.8.tgz", + "integrity": "sha512-PCLz/LXGBsNTErbtB6i5u4eLpHeMfi93aUv5duMmj6caNu6IphS4q6UevDnL36sZQv9lrP11dbPKGMaXPwMKfQ==", + "license": "Apache-2.0", + "bin": { + "baseline-browser-mapping": "dist/cli.cjs" + }, + "engines": { + "node": ">=6.0.0" + } + }, + "node_modules/better-result": { + "version": "2.7.0", + "resolved": "https://registry.npmjs.org/better-result/-/better-result-2.7.0.tgz", + "integrity": "sha512-7zrmXjAK8u8Z6SOe4R65XObOR5X+Y2I/VVku3t5cPOGQ8/WsBcfFmfnIPiEl5EBMDOzPHRwbiPbMtQBKYdw7RA==", + "devOptional": true, + "license": "MIT", + "dependencies": { + "@clack/prompts": "^0.11.0" + }, + "bin": { + "better-result": "bin/cli.mjs" + } + }, + "node_modules/big-integer": { + "version": "1.6.52", + "resolved": "https://registry.npmjs.org/big-integer/-/big-integer-1.6.52.tgz", + "integrity": "sha512-QxD8cf2eVqJOOz63z6JIN9BzvVs/dlySa5HGSBH5xtR8dPteIRQnBxxKqkNTiT6jbDTF6jAfrd4oMcND9RGbQg==", + "license": "Unlicense", + "engines": { + "node": ">=0.6" + } + }, + "node_modules/body-parser": { + "version": "2.2.2", + "resolved": "https://registry.npmjs.org/body-parser/-/body-parser-2.2.2.tgz", + "integrity": "sha512-oP5VkATKlNwcgvxi0vM0p/D3n2C3EReYVX+DNYs5TjZFn/oQt2j+4sVJtSMr18pdRr8wjTcBl6LoV+FUwzPmNA==", + "license": "MIT", + "dependencies": { + "bytes": "^3.1.2", + "content-type": "^1.0.5", + "debug": "^4.4.3", + "http-errors": "^2.0.0", + "iconv-lite": "^0.7.0", + "on-finished": "^2.4.1", + "qs": "^6.14.1", + "raw-body": "^3.0.1", + "type-is": "^2.0.1" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/bplist-parser": { + "version": "0.3.2", + "resolved": "https://registry.npmjs.org/bplist-parser/-/bplist-parser-0.3.2.tgz", + "integrity": "sha512-apC2+fspHGI3mMKj+dGevkGo/tCqVB8jMb6i+OX+E29p0Iposz07fABkRIfVUPNd5A5VbuOz1bZbnmkKLYF+wQ==", + "license": "MIT", + "dependencies": { + "big-integer": "1.6.x" + }, + "engines": { + "node": ">= 5.10.0" + } + }, + "node_modules/brace-expansion": { + "version": "1.1.13", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.13.tgz", + "integrity": "sha512-9ZLprWS6EENmhEOpjCYW2c8VkmOvckIJZfkr7rBW6dObmfgJ/L1GpSYW5Hpo9lDz4D1+n0Ckz8rU7FwHDQiG/w==", + "dev": true, + "license": "MIT", + "dependencies": { + "balanced-match": "^1.0.0", + "concat-map": "0.0.1" + } + }, + "node_modules/braces": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/braces/-/braces-3.0.3.tgz", + "integrity": "sha512-yQbXgO/OSZVD2IsiLlro+7Hf6Q18EJrKSEsdoMzKePKXct3gvD8oLcOQdIzGupr5Fj+EDe8gO/lxc1BzfMpxvA==", + "license": "MIT", + "dependencies": { + "fill-range": "^7.1.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/browserslist": { + "version": "4.28.1", + "resolved": "https://registry.npmjs.org/browserslist/-/browserslist-4.28.1.tgz", + "integrity": "sha512-ZC5Bd0LgJXgwGqUknZY/vkUQ04r8NXnJZ3yYi4vDmSiZmC/pdSN0NbNRPxZpbtO4uAfDUAFffO8IZoM3Gj8IkA==", + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/browserslist" + }, + { + "type": "tidelift", + "url": "https://tidelift.com/funding/github/npm/browserslist" + }, + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "dependencies": { + "baseline-browser-mapping": "^2.9.0", + "caniuse-lite": "^1.0.30001759", + "electron-to-chromium": "^1.5.263", + "node-releases": "^2.0.27", + "update-browserslist-db": "^1.2.0" + }, + "bin": { + "browserslist": "cli.js" + }, + "engines": { + "node": "^6 || ^7 || ^8 || ^9 || ^10 || ^11 || ^12 || >=13.7" + } + }, + "node_modules/buffer-crc32": { + "version": "0.2.13", + "resolved": "https://registry.npmjs.org/buffer-crc32/-/buffer-crc32-0.2.13.tgz", + "integrity": "sha512-VO9Ht/+p3SN7SKWqcrgEzjGbRSJYTx+Q1pTQC0wrWqHx0vpJraQ6GtHx8tvcg1rlK1byhU5gccxgOgj7B0TDkQ==", + "license": "MIT", + "engines": { + "node": "*" + } + }, + "node_modules/bundle-name": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/bundle-name/-/bundle-name-4.1.0.tgz", + "integrity": "sha512-tjwM5exMg6BGRI+kNmTntNsvdZS1X8BFYS6tnJ2hdH0kVxM6/eVZ2xy+FqStSWvYmtfFMDLIxurorHwDKfDz5Q==", + "license": "MIT", + "dependencies": { + "run-applescript": "^7.0.0" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/bytes": { + "version": "3.1.2", + "resolved": "https://registry.npmjs.org/bytes/-/bytes-3.1.2.tgz", + "integrity": "sha512-/Nf7TyzTx6S3yRJObOAV7956r8cr2+Oj8AC5dt8wSP3BQAoeX58NoHyCU8P8zGkNXStjTSi6fzO6F0pBdcYbEg==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/c12": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/c12/-/c12-3.1.0.tgz", + "integrity": "sha512-uWoS8OU1MEIsOv8p/5a82c3H31LsWVR5qiyXVfBNOzfffjUWtPnhAb4BYI2uG2HfGmZmFjCtui5XNWaps+iFuw==", + "devOptional": true, + "license": "MIT", + "dependencies": { + "chokidar": "^4.0.3", + "confbox": "^0.2.2", + "defu": "^6.1.4", + "dotenv": "^16.6.1", + "exsolve": "^1.0.7", + "giget": "^2.0.0", + "jiti": "^2.4.2", + "ohash": "^2.0.11", + "pathe": "^2.0.3", + "perfect-debounce": "^1.0.0", + "pkg-types": "^2.2.0", + "rc9": "^2.1.2" + }, + "peerDependencies": { + "magicast": "^0.3.5" + }, + "peerDependenciesMeta": { + "magicast": { + "optional": true + } + } + }, + "node_modules/call-bind": { + "version": "1.0.8", + "resolved": "https://registry.npmjs.org/call-bind/-/call-bind-1.0.8.tgz", + "integrity": "sha512-oKlSFMcMwpUg2ednkhQ454wfWiU/ul3CkJe/PEHcTKuiX6RpbehUiFMXu13HalGZxfUwCQzZG747YXBn1im9ww==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bind-apply-helpers": "^1.0.0", + "es-define-property": "^1.0.0", + "get-intrinsic": "^1.2.4", + "set-function-length": "^1.2.2" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/call-bind-apply-helpers": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/call-bind-apply-helpers/-/call-bind-apply-helpers-1.0.2.tgz", + "integrity": "sha512-Sp1ablJ0ivDkSzjcaJdxEunN5/XvksFJ2sMBFfq6x0ryhQV/2b/KwFe21cMpmHtPOSij8K99/wSfoEuTObmuMQ==", + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0", + "function-bind": "^1.1.2" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/call-bound": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/call-bound/-/call-bound-1.0.4.tgz", + "integrity": "sha512-+ys997U96po4Kx/ABpBCqhA9EuxJaQWDQg7295H4hBphv3IZg0boBKuwYpt4YXp6MZ5AmZQnU/tyMTlRpaSejg==", + "license": "MIT", + "dependencies": { + "call-bind-apply-helpers": "^1.0.2", + "get-intrinsic": "^1.3.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/callsites": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/callsites/-/callsites-3.1.0.tgz", + "integrity": "sha512-P8BjAsXvZS+VIDUI11hHCQEv74YT67YUi5JJFNWIqL235sBmjX4+qx9Muvls5ivyNENctx46xQLQ3aTuE7ssaQ==", + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/caniuse-lite": { + "version": "1.0.30001780", + "resolved": "https://registry.npmjs.org/caniuse-lite/-/caniuse-lite-1.0.30001780.tgz", + "integrity": "sha512-llngX0E7nQci5BPJDqoZSbuZ5Bcs9F5db7EtgfwBerX9XGtkkiO4NwfDDIRzHTTwcYC8vC7bmeUEPGrKlR/TkQ==", + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/browserslist" + }, + { + "type": "tidelift", + "url": "https://tidelift.com/funding/github/npm/caniuse-lite" + }, + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "CC-BY-4.0" + }, + "node_modules/chai": { + "version": "6.2.2", + "resolved": "https://registry.npmjs.org/chai/-/chai-6.2.2.tgz", + "integrity": "sha512-NUPRluOfOiTKBKvWPtSD4PhFvWCqOi0BGStNWs57X9js7XGTprSmFoz5F0tWhR4WPjNeR9jXqdC7/UpSJTnlRg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=18" + } + }, + "node_modules/chalk": { + "version": "4.1.2", + "resolved": "https://registry.npmjs.org/chalk/-/chalk-4.1.2.tgz", + "integrity": "sha512-oKnbhFyRIXpUuez8iBMmyEa4nbj4IOQyuhc/wy9kY7/WVPcwIO9VA668Pu8RkO7+0G76SLROeyw9CpQ061i4mA==", + "dev": true, + "license": "MIT", + "dependencies": { + "ansi-styles": "^4.1.0", + "supports-color": "^7.1.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/chalk/chalk?sponsor=1" + } + }, + "node_modules/chart.js": { + "version": "4.5.1", + "resolved": "https://registry.npmjs.org/chart.js/-/chart.js-4.5.1.tgz", + "integrity": "sha512-GIjfiT9dbmHRiYi6Nl2yFCq7kkwdkp1W/lp2J99rX0yo9tgJGn3lKQATztIjb5tVtevcBtIdICNWqlq5+E8/Pw==", + "devOptional": true, + "license": "MIT", + "dependencies": { + "@kurkle/color": "^0.3.0" + }, + "engines": { + "pnpm": ">=8" + } + }, + "node_modules/chess.js": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/chess.js/-/chess.js-1.4.0.tgz", + "integrity": "sha512-BBJgrrtKQOzFLonR0l+k64A98NLemPwNsCskwb+29bRwobUa4iTm51E1kwGPbWXAcfdDa18nad6vpPPKPWarqw==", + "license": "BSD-2-Clause" + }, + "node_modules/chokidar": { + "version": "4.0.3", + "resolved": "https://registry.npmjs.org/chokidar/-/chokidar-4.0.3.tgz", + "integrity": "sha512-Qgzu8kfBvo+cA4962jnP1KkS6Dop5NS6g7R5LFYJr4b8Ub94PPQXUksCw9PvXoeXPRRddRNC5C1JQUR2SMGtnA==", + "devOptional": true, + "license": "MIT", + "dependencies": { + "readdirp": "^4.0.1" + }, + "engines": { + "node": ">= 14.16.0" + }, + "funding": { + "url": "https://paulmillr.com/funding/" + } + }, + "node_modules/chownr": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/chownr/-/chownr-3.0.0.tgz", + "integrity": "sha512-+IxzY9BZOQd/XuYPRmrvEVjF/nqj5kgT4kEq7VofrDoM1MxoRjEWkrCC3EtLi59TVawxTAn+orJwFQcrqEN1+g==", + "license": "BlueOak-1.0.0", + "engines": { + "node": ">=18" + } + }, + "node_modules/citty": { + "version": "0.1.6", + "resolved": "https://registry.npmjs.org/citty/-/citty-0.1.6.tgz", + "integrity": "sha512-tskPPKEs8D2KPafUypv2gxwJP8h/OaJmC82QQGGDQcHvXX43xF2VDACcJVmZ0EuSxkpO9Kc4MlrA3q0+FG58AQ==", + "devOptional": true, + "license": "MIT", + "dependencies": { + "consola": "^3.2.3" + } + }, + "node_modules/class-variance-authority": { + "version": "0.7.1", + "resolved": "https://registry.npmjs.org/class-variance-authority/-/class-variance-authority-0.7.1.tgz", + "integrity": "sha512-Ka+9Trutv7G8M6WT6SeiRWz792K5qEqIGEGzXKhAE6xOWAY6pPH8U+9IY3oCMv6kqTmLsv7Xh/2w2RigkePMsg==", + "license": "Apache-2.0", + "dependencies": { + "clsx": "^2.1.1" + }, + "funding": { + "url": "https://polar.sh/cva" + } + }, + "node_modules/cli-cursor": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/cli-cursor/-/cli-cursor-5.0.0.tgz", + "integrity": "sha512-aCj4O5wKyszjMmDT4tZj93kxyydN/K5zPWSCe6/0AV/AA1pqe5ZBIw0a2ZfPQV7lL5/yb5HsUreJ6UFAF1tEQw==", + "license": "MIT", + "dependencies": { + "restore-cursor": "^5.0.0" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/cli-spinners": { + "version": "2.9.2", + "resolved": "https://registry.npmjs.org/cli-spinners/-/cli-spinners-2.9.2.tgz", + "integrity": "sha512-ywqV+5MmyL4E7ybXgKys4DugZbX0FC6LnwrhjuykIjnK9k8OQacQ7axGKnjDXWNhns0xot3bZI5h55H8yo9cJg==", + "license": "MIT", + "engines": { + "node": ">=6" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/cli-width": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/cli-width/-/cli-width-4.1.0.tgz", + "integrity": "sha512-ouuZd4/dm2Sw5Gmqy6bGyNNNe1qt9RpmxveLSO7KcgsTnU7RXfsw+/bukWGo1abgBiMAic068rclZsO4IWmmxQ==", + "license": "ISC", + "engines": { + "node": ">= 12" + } + }, + "node_modules/client-only": { + "version": "0.0.1", + "resolved": "https://registry.npmjs.org/client-only/-/client-only-0.0.1.tgz", + "integrity": "sha512-IV3Ou0jSMzZrd3pZ48nLkT9DA7Ag1pnPzaiQhpW7c3RbcqqzvzzVu+L8gfqMp/8IM2MQtSiqaCxrrcfu8I8rMA==", + "license": "MIT" + }, + "node_modules/cliui": { + "version": "8.0.1", + "resolved": "https://registry.npmjs.org/cliui/-/cliui-8.0.1.tgz", + "integrity": "sha512-BSeNnyus75C4//NQ9gQt1/csTXyo/8Sb+afLAkzAptFuMsod9HFokGNudZpi/oQV73hnVK+sR+5PVRMd+Dr7YQ==", + "license": "ISC", + "dependencies": { + "string-width": "^4.2.0", + "strip-ansi": "^6.0.1", + "wrap-ansi": "^7.0.0" + }, + "engines": { + "node": ">=12" + } + }, + "node_modules/cliui/node_modules/ansi-regex": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz", + "integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==", + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/cliui/node_modules/emoji-regex": { + "version": "8.0.0", + "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-8.0.0.tgz", + "integrity": "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A==", + "license": "MIT" + }, + "node_modules/cliui/node_modules/string-width": { + "version": "4.2.3", + "resolved": "https://registry.npmjs.org/string-width/-/string-width-4.2.3.tgz", + "integrity": "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g==", + "license": "MIT", + "dependencies": { + "emoji-regex": "^8.0.0", + "is-fullwidth-code-point": "^3.0.0", + "strip-ansi": "^6.0.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/cliui/node_modules/strip-ansi": { + "version": "6.0.1", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz", + "integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==", + "license": "MIT", + "dependencies": { + "ansi-regex": "^5.0.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/cliui/node_modules/wrap-ansi": { + "version": "7.0.0", + "resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-7.0.0.tgz", + "integrity": "sha512-YVGIj2kamLSTxw6NsZjoBxfSwsn0ycdesmc4p+Q21c5zPuZ1pl+NfxVdxPtdHvmNVOQ6XSYG4AUtyt/Fi7D16Q==", + "license": "MIT", + "dependencies": { + "ansi-styles": "^4.0.0", + "string-width": "^4.1.0", + "strip-ansi": "^6.0.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/chalk/wrap-ansi?sponsor=1" + } + }, + "node_modules/clsx": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/clsx/-/clsx-2.1.1.tgz", + "integrity": "sha512-eYm0QWBtUrBWZWG0d386OGAw16Z995PiOVo2B7bjWSbHedGl5e0ZWaq65kOGgUSNesEIDkB9ISbTg/JK9dhCZA==", + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/code-block-writer": { + "version": "13.0.3", + "resolved": "https://registry.npmjs.org/code-block-writer/-/code-block-writer-13.0.3.tgz", + "integrity": "sha512-Oofo0pq3IKnsFtuHqSF7TqBfr71aeyZDVJ0HpmqB7FBM2qEigL0iPONSCZSO9pE9dZTAxANe5XHG9Uy0YMv8cg==", + "license": "MIT" + }, + "node_modules/color-convert": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz", + "integrity": "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==", + "license": "MIT", + "dependencies": { + "color-name": "~1.1.4" + }, + "engines": { + "node": ">=7.0.0" + } + }, + "node_modules/color-name": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.4.tgz", + "integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==", + "license": "MIT" + }, + "node_modules/commander": { + "version": "14.0.3", + "resolved": "https://registry.npmjs.org/commander/-/commander-14.0.3.tgz", + "integrity": "sha512-H+y0Jo/T1RZ9qPP4Eh1pkcQcLRglraJaSLoyOtHxu6AapkjWVCy2Sit1QQ4x3Dng8qDlSsZEet7g5Pq06MvTgw==", + "license": "MIT", + "engines": { + "node": ">=20" + } + }, + "node_modules/concat-map": { + "version": "0.0.1", + "resolved": "https://registry.npmjs.org/concat-map/-/concat-map-0.0.1.tgz", + "integrity": "sha512-/Srv4dswyQNBfohGpz9o6Yb3Gz3SrUDqBH5rTuhGR7ahtlbYKnVxw2bCFMRljaA7EXHaXZ8wsHdodFvbkhKmqg==", + "dev": true, + "license": "MIT" + }, + "node_modules/confbox": { + "version": "0.2.4", + "resolved": "https://registry.npmjs.org/confbox/-/confbox-0.2.4.tgz", + "integrity": "sha512-ysOGlgTFbN2/Y6Cg3Iye8YKulHw+R2fNXHrgSmXISQdMnomY6eNDprVdW9R5xBguEqI954+S6709UyiO7B+6OQ==", + "devOptional": true, + "license": "MIT" + }, + "node_modules/consola": { + "version": "3.4.2", + "resolved": "https://registry.npmjs.org/consola/-/consola-3.4.2.tgz", + "integrity": "sha512-5IKcdX0nnYavi6G7TtOhwkYzyjfJlatbjMjuLSfE2kYT5pMDOilZ4OvMhi637CcDICTmz3wARPoyhqyX1Y+XvA==", + "devOptional": true, + "license": "MIT", + "engines": { + "node": "^14.18.0 || >=16.10.0" + } + }, + "node_modules/console-table-printer": { + "version": "2.15.0", + "resolved": "https://registry.npmjs.org/console-table-printer/-/console-table-printer-2.15.0.tgz", + "integrity": "sha512-SrhBq4hYVjLCkBVOWaTzceJalvn5K1Zq5aQA6wXC/cYjI3frKWNPEMK3sZsJfNNQApvCQmgBcc13ZKmFj8qExw==", + "license": "MIT", + "dependencies": { + "simple-wcswidth": "^1.1.2" + } + }, + "node_modules/content-disposition": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/content-disposition/-/content-disposition-1.0.1.tgz", + "integrity": "sha512-oIXISMynqSqm241k6kcQ5UwttDILMK4BiurCfGEREw6+X9jkkpEe5T9FZaApyLGGOnFuyMWZpdolTXMtvEJ08Q==", + "license": "MIT", + "engines": { + "node": ">=18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/content-type": { + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/content-type/-/content-type-1.0.5.tgz", + "integrity": "sha512-nTjqfcBFEipKdXCv4YDQWCfmcLZKm81ldF0pAopTvyrFGVbcR6P/VAAd5G7N+0tTr8QqiU0tFadD6FK4NtJwOA==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/convert-source-map": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/convert-source-map/-/convert-source-map-2.0.0.tgz", + "integrity": "sha512-Kvp459HrV2FEJ1CAsi1Ku+MY3kasH19TFykTz2xWmMeq6bk2NU3XXvfJ+Q61m0xktWwt+1HSYf3JZsTms3aRJg==", + "license": "MIT" + }, + "node_modules/cookie": { + "version": "0.7.2", + "resolved": "https://registry.npmjs.org/cookie/-/cookie-0.7.2.tgz", + "integrity": "sha512-yki5XnKuf750l50uGTllt6kKILY4nQ1eNIQatoXEByZ5dWgnKqbnqmTrBE5B4N7lrMJKQ2ytWMiTO2o0v6Ew/w==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/cookie-signature": { + "version": "1.2.2", + "resolved": "https://registry.npmjs.org/cookie-signature/-/cookie-signature-1.2.2.tgz", + "integrity": "sha512-D76uU73ulSXrD1UXF4KE2TMxVVwhsnCgfAyTg9k8P6KGZjlXKrOLe4dJQKI3Bxi5wjesZoFXJWElNWBjPZMbhg==", + "license": "MIT", + "engines": { + "node": ">=6.6.0" + } + }, + "node_modules/cors": { + "version": "2.8.6", + "resolved": "https://registry.npmjs.org/cors/-/cors-2.8.6.tgz", + "integrity": "sha512-tJtZBBHA6vjIAaF6EnIaq6laBBP9aq/Y3ouVJjEfoHbRBcHBAHYcMh/w8LDrk2PvIMMq8gmopa5D4V8RmbrxGw==", + "license": "MIT", + "dependencies": { + "object-assign": "^4", + "vary": "^1" + }, + "engines": { + "node": ">= 0.10" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/cosmiconfig": { + "version": "9.0.1", + "resolved": "https://registry.npmjs.org/cosmiconfig/-/cosmiconfig-9.0.1.tgz", + "integrity": "sha512-hr4ihw+DBqcvrsEDioRO31Z17x71pUYoNe/4h6Z0wB72p7MU7/9gH8Q3s12NFhHPfYBBOV3qyfUxmr/Yn3shnQ==", + "license": "MIT", + "dependencies": { + "env-paths": "^2.2.1", + "import-fresh": "^3.3.0", + "js-yaml": "^4.1.0", + "parse-json": "^5.2.0" + }, + "engines": { + "node": ">=14" + }, + "funding": { + "url": "https://github.com/sponsors/d-fischer" + }, + "peerDependencies": { + "typescript": ">=4.9.5" + }, + "peerDependenciesMeta": { + "typescript": { + "optional": true + } + } + }, + "node_modules/cross-fetch": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/cross-fetch/-/cross-fetch-4.1.0.tgz", + "integrity": "sha512-uKm5PU+MHTootlWEY+mZ4vvXoCn4fLQxT9dSc1sXVMSFkINTJVN8cAQROpwcKm8bJ/c7rgZVIBWzH5T78sNZZw==", + "license": "MIT", + "dependencies": { + "node-fetch": "^2.7.0" + } + }, + "node_modules/cross-fetch/node_modules/node-fetch": { + "version": "2.7.0", + "resolved": "https://registry.npmjs.org/node-fetch/-/node-fetch-2.7.0.tgz", + "integrity": "sha512-c4FRfUm/dbcWZ7U+1Wq0AwCyFL+3nt2bEw05wfxSz+DWpWsitgmSgYmy2dQdWyKC1694ELPqMs/YzUSNozLt8A==", + "license": "MIT", + "dependencies": { + "whatwg-url": "^5.0.0" + }, + "engines": { + "node": "4.x || >=6.0.0" + }, + "peerDependencies": { + "encoding": "^0.1.0" + }, + "peerDependenciesMeta": { + "encoding": { + "optional": true + } + } + }, + "node_modules/cross-spawn": { + "version": "7.0.6", + "resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.6.tgz", + "integrity": "sha512-uV2QOWP2nWzsy2aMp8aRibhi9dlzF5Hgh5SHaB9OiTGEyDTiJJyx0uy51QXdyWbtAHNua4XJzUKca3OzKUd3vA==", + "license": "MIT", + "dependencies": { + "path-key": "^3.1.0", + "shebang-command": "^2.0.0", + "which": "^2.0.1" + }, + "engines": { + "node": ">= 8" + } + }, + "node_modules/cssesc": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/cssesc/-/cssesc-3.0.0.tgz", + "integrity": "sha512-/Tb/JcjK111nNScGob5MNtsntNM1aCNUDipB/TkwZFhyDrrE47SOx/18wF2bbjgc3ZzCSKW1T5nt5EbFoAz/Vg==", + "license": "MIT", + "bin": { + "cssesc": "bin/cssesc" + }, + "engines": { + "node": ">=4" + } + }, + "node_modules/csstype": { + "version": "3.2.3", + "resolved": "https://registry.npmjs.org/csstype/-/csstype-3.2.3.tgz", + "integrity": "sha512-z1HGKcYy2xA8AGQfwrn0PAy+PB7X/GSj3UVJW9qKyn43xWa+gl5nXmU4qqLMRzWVLFC8KusUX8T/0kCiOYpAIQ==", + "devOptional": true, + "license": "MIT" + }, + "node_modules/d3-array": { + "version": "3.2.4", + "resolved": "https://registry.npmjs.org/d3-array/-/d3-array-3.2.4.tgz", + "integrity": "sha512-tdQAmyA18i4J7wprpYq8ClcxZy3SC31QMeByyCFyRt7BVHdREQZ5lpzoe5mFEYZUWe+oq8HBvk9JjpibyEV4Jg==", + "license": "ISC", + "dependencies": { + "internmap": "1 - 2" + }, + "engines": { + "node": ">=12" + } + }, + "node_modules/d3-color": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/d3-color/-/d3-color-3.1.0.tgz", + "integrity": "sha512-zg/chbXyeBtMQ1LbD/WSoW2DpC3I0mpmPdW+ynRTj/x2DAWYrIY7qeZIHidozwV24m4iavr15lNwIwLxRmOxhA==", + "license": "ISC", + "engines": { + "node": ">=12" + } + }, + "node_modules/d3-ease": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/d3-ease/-/d3-ease-3.0.1.tgz", + "integrity": "sha512-wR/XK3D3XcLIZwpbvQwQ5fK+8Ykds1ip7A2Txe0yxncXSdq1L9skcG7blcedkOX+ZcgxGAmLX1FrRGbADwzi0w==", + "license": "BSD-3-Clause", + "engines": { + "node": ">=12" + } + }, + "node_modules/d3-format": { + "version": "3.1.2", + "resolved": "https://registry.npmjs.org/d3-format/-/d3-format-3.1.2.tgz", + "integrity": "sha512-AJDdYOdnyRDV5b6ArilzCPPwc1ejkHcoyFarqlPqT7zRYjhavcT3uSrqcMvsgh2CgoPbK3RCwyHaVyxYcP2Arg==", + "license": "ISC", + "engines": { + "node": ">=12" + } + }, + "node_modules/d3-interpolate": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/d3-interpolate/-/d3-interpolate-3.0.1.tgz", + "integrity": "sha512-3bYs1rOD33uo8aqJfKP3JWPAibgw8Zm2+L9vBKEHJ2Rg+viTR7o5Mmv5mZcieN+FRYaAOWX5SJATX6k1PWz72g==", + "license": "ISC", + "dependencies": { + "d3-color": "1 - 3" + }, + "engines": { + "node": ">=12" + } + }, + "node_modules/d3-path": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/d3-path/-/d3-path-3.1.0.tgz", + "integrity": "sha512-p3KP5HCf/bvjBSSKuXid6Zqijx7wIfNW+J/maPs+iwR35at5JCbLUT0LzF1cnjbCHWhqzQTIN2Jpe8pRebIEFQ==", + "license": "ISC", + "engines": { + "node": ">=12" + } + }, + "node_modules/d3-scale": { + "version": "4.0.2", + "resolved": "https://registry.npmjs.org/d3-scale/-/d3-scale-4.0.2.tgz", + "integrity": "sha512-GZW464g1SH7ag3Y7hXjf8RoUuAFIqklOAq3MRl4OaWabTFJY9PN/E1YklhXLh+OQ3fM9yS2nOkCoS+WLZ6kvxQ==", + "license": "ISC", + "dependencies": { + "d3-array": "2.10.0 - 3", + "d3-format": "1 - 3", + "d3-interpolate": "1.2.0 - 3", + "d3-time": "2.1.1 - 3", + "d3-time-format": "2 - 4" + }, + "engines": { + "node": ">=12" + } + }, + "node_modules/d3-shape": { + "version": "3.2.0", + "resolved": "https://registry.npmjs.org/d3-shape/-/d3-shape-3.2.0.tgz", + "integrity": "sha512-SaLBuwGm3MOViRq2ABk3eLoxwZELpH6zhl3FbAoJ7Vm1gofKx6El1Ib5z23NUEhF9AsGl7y+dzLe5Cw2AArGTA==", + "license": "ISC", + "dependencies": { + "d3-path": "^3.1.0" + }, + "engines": { + "node": ">=12" + } + }, + "node_modules/d3-time": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/d3-time/-/d3-time-3.1.0.tgz", + "integrity": "sha512-VqKjzBLejbSMT4IgbmVgDjpkYrNWUYJnbCGo874u7MMKIWsILRX+OpX/gTk8MqjpT1A/c6HY2dCA77ZN0lkQ2Q==", + "license": "ISC", + "dependencies": { + "d3-array": "2 - 3" + }, + "engines": { + "node": ">=12" + } + }, + "node_modules/d3-time-format": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/d3-time-format/-/d3-time-format-4.1.0.tgz", + "integrity": "sha512-dJxPBlzC7NugB2PDLwo9Q8JiTR3M3e4/XANkreKSUxF8vvXKqm1Yfq4Q5dl8budlunRVlUUaDUgFt7eA8D6NLg==", + "license": "ISC", + "dependencies": { + "d3-time": "1 - 3" + }, + "engines": { + "node": ">=12" + } + }, + "node_modules/d3-timer": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/d3-timer/-/d3-timer-3.0.1.tgz", + "integrity": "sha512-ndfJ/JxxMd3nw31uyKoY2naivF+r29V+Lc0svZxe1JvvIRmi8hUsrMvdOwgS1o6uBHmiz91geQ0ylPP0aj1VUA==", + "license": "ISC", + "engines": { + "node": ">=12" + } + }, + "node_modules/damerau-levenshtein": { + "version": "1.0.8", + "resolved": "https://registry.npmjs.org/damerau-levenshtein/-/damerau-levenshtein-1.0.8.tgz", + "integrity": "sha512-sdQSFB7+llfUcQHUQO3+B8ERRj0Oa4w9POWMI/puGtuf7gFywGmkaLCElnudfTiKZV+NvHqL0ifzdrI8Ro7ESA==", + "dev": true, + "license": "BSD-2-Clause" + }, + "node_modules/data-uri-to-buffer": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/data-uri-to-buffer/-/data-uri-to-buffer-4.0.1.tgz", + "integrity": "sha512-0R9ikRb668HB7QDxT1vkpuUBtqc53YyAwMwGeUFKRojY/NWKvdZ+9UYtRfGmhqNbRkTSVpMbmyhXipFFv2cb/A==", + "license": "MIT", + "engines": { + "node": ">= 12" + } + }, + "node_modules/data-view-buffer": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/data-view-buffer/-/data-view-buffer-1.0.2.tgz", + "integrity": "sha512-EmKO5V3OLXh1rtK2wgXRansaK1/mtVdTUEiEI0W8RkvgT05kfxaH29PliLnpLP73yYO6142Q72QNa8Wx/A5CqQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bound": "^1.0.3", + "es-errors": "^1.3.0", + "is-data-view": "^1.0.2" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/data-view-byte-length": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/data-view-byte-length/-/data-view-byte-length-1.0.2.tgz", + "integrity": "sha512-tuhGbE6CfTM9+5ANGf+oQb72Ky/0+s3xKUpHvShfiz2RxMFgFPjsXuRLBVMtvMs15awe45SRb83D6wH4ew6wlQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bound": "^1.0.3", + "es-errors": "^1.3.0", + "is-data-view": "^1.0.2" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/inspect-js" + } + }, + "node_modules/data-view-byte-offset": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/data-view-byte-offset/-/data-view-byte-offset-1.0.1.tgz", + "integrity": "sha512-BS8PfmtDGnrgYdOonGZQdLZslWIeCGFP9tpan0hi1Co2Zr2NKADsvGYA8XxuG/4UWgJ6Cjtv+YJnB6MM69QGlQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bound": "^1.0.2", + "es-errors": "^1.3.0", + "is-data-view": "^1.0.1" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/date-fns": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/date-fns/-/date-fns-4.1.0.tgz", + "integrity": "sha512-Ukq0owbQXxa/U3EGtsdVBkR1w7KOQ5gIBqdH2hkvknzZPYvBxb/aa6E8L7tmjFtkwZBu3UXBbjIgPo/Ez4xaNg==", + "license": "MIT", + "funding": { + "type": "github", + "url": "https://github.com/sponsors/kossnocorp" + } + }, + "node_modules/debug": { + "version": "4.4.3", + "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz", + "integrity": "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==", + "license": "MIT", + "dependencies": { + "ms": "^2.1.3" + }, + "engines": { + "node": ">=6.0" + }, + "peerDependenciesMeta": { + "supports-color": { + "optional": true + } + } + }, + "node_modules/decimal.js-light": { + "version": "2.5.1", + "resolved": "https://registry.npmjs.org/decimal.js-light/-/decimal.js-light-2.5.1.tgz", + "integrity": "sha512-qIMFpTMZmny+MMIitAB6D7iVPEorVw6YQRWkvarTkT4tBeSLLiHzcwj6q0MmYSFCiVpiqPJTJEYIrpcPzVEIvg==", + "license": "MIT" + }, + "node_modules/dedent": { + "version": "1.7.2", + "resolved": "https://registry.npmjs.org/dedent/-/dedent-1.7.2.tgz", + "integrity": "sha512-WzMx3mW98SN+zn3hgemf4OzdmyNhhhKz5Ay0pUfQiMQ3e1g+xmTJWp/pKdwKVXhdSkAEGIIzqeuWrL3mV/AXbA==", + "license": "MIT", + "peerDependencies": { + "babel-plugin-macros": "^3.1.0" + }, + "peerDependenciesMeta": { + "babel-plugin-macros": { + "optional": true + } + } + }, + "node_modules/deep-is": { + "version": "0.1.4", + "resolved": "https://registry.npmjs.org/deep-is/-/deep-is-0.1.4.tgz", + "integrity": "sha512-oIPzksmTg4/MriiaYGO+okXDT7ztn/w3Eptv/+gSIdMdKsJo0u4CfYNFJPy+4SKMuCqGw2wxnA+URMg3t8a/bQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/deepmerge": { + "version": "4.3.1", + "resolved": "https://registry.npmjs.org/deepmerge/-/deepmerge-4.3.1.tgz", + "integrity": "sha512-3sUqbMEc77XqpdNO7FRyRog+eW3ph+GYCbj+rK+uYyRMuwsVy0rMiVtPn+QJlKFvWP/1PYpapqYn0Me2knFn+A==", + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/deepmerge-ts": { + "version": "7.1.5", + "resolved": "https://registry.npmjs.org/deepmerge-ts/-/deepmerge-ts-7.1.5.tgz", + "integrity": "sha512-HOJkrhaYsweh+W+e74Yn7YStZOilkoPb6fycpwNLKzSPtruFs48nYis0zy5yJz1+ktUhHxoRDJ27RQAWLIJVJw==", + "devOptional": true, + "license": "BSD-3-Clause", + "engines": { + "node": ">=16.0.0" + } + }, + "node_modules/default-browser": { + "version": "5.5.0", + "resolved": "https://registry.npmjs.org/default-browser/-/default-browser-5.5.0.tgz", + "integrity": "sha512-H9LMLr5zwIbSxrmvikGuI/5KGhZ8E2zH3stkMgM5LpOWDutGM2JZaj460Udnf1a+946zc7YBgrqEWwbk7zHvGw==", + "license": "MIT", + "dependencies": { + "bundle-name": "^4.1.0", + "default-browser-id": "^5.0.0" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/default-browser-id": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/default-browser-id/-/default-browser-id-5.0.1.tgz", + "integrity": "sha512-x1VCxdX4t+8wVfd1so/9w+vQ4vx7lKd2Qp5tDRutErwmR85OgmfX7RlLRMWafRMY7hbEiXIbudNrjOAPa/hL8Q==", + "license": "MIT", + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/define-data-property": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/define-data-property/-/define-data-property-1.1.4.tgz", + "integrity": "sha512-rBMvIzlpA8v6E+SJZoo++HAYqsLrkg7MSfIinMPFhmkorw7X+dOXVJQs+QT69zGkzMyfDnIMN2Wid1+NbL3T+A==", + "dev": true, + "license": "MIT", + "dependencies": { + "es-define-property": "^1.0.0", + "es-errors": "^1.3.0", + "gopd": "^1.0.1" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/define-lazy-prop": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/define-lazy-prop/-/define-lazy-prop-3.0.0.tgz", + "integrity": "sha512-N+MeXYoqr3pOgn8xfyRPREN7gHakLYjhsHhWGT3fWAiL4IkAt0iDw14QiiEm2bE30c5XX5q0FtAA3CK5f9/BUg==", + "license": "MIT", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/define-properties": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/define-properties/-/define-properties-1.2.1.tgz", + "integrity": "sha512-8QmQKqEASLd5nx0U1B1okLElbUuuttJ/AnYmRXbbbGDWh6uS208EjD4Xqq/I9wK7u0v6O08XhTWnt5XtEbR6Dg==", + "dev": true, + "license": "MIT", + "dependencies": { + "define-data-property": "^1.0.1", + "has-property-descriptors": "^1.0.0", + "object-keys": "^1.1.1" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/defu": { + "version": "6.1.6", + "resolved": "https://registry.npmjs.org/defu/-/defu-6.1.6.tgz", + "integrity": "sha512-f8mefEW4WIVg4LckePx3mALjQSPQgFlg9U8yaPdlsbdYcHQyj9n2zL2LJEA52smeYxOvmd/nB7TpMtHGMTHcug==", + "devOptional": true, + "license": "MIT" + }, + "node_modules/denque": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/denque/-/denque-2.1.0.tgz", + "integrity": "sha512-HVQE3AAb/pxF8fQAoiqpvg9i3evqug3hoiwakOyZAwJm+6vZehbkYXZ0l4JxS+I3QxM97v5aaRNhj8v5oBhekw==", + "devOptional": true, + "license": "Apache-2.0", + "engines": { + "node": ">=0.10" + } + }, + "node_modules/depd": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/depd/-/depd-2.0.0.tgz", + "integrity": "sha512-g7nH6P6dyDioJogAAGprGpCtVImJhpPk/roCzdb3fIh61/s/nPsfR6onyMwkCAR/OlC3yBC0lESvUoQEAssIrw==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/destr": { + "version": "2.0.5", + "resolved": "https://registry.npmjs.org/destr/-/destr-2.0.5.tgz", + "integrity": "sha512-ugFTXCtDZunbzasqBxrK93Ik/DRYsO6S/fedkWEMKqt04xZ4csmnmwGDBAb07QWNaGMAmnTIemsYZCksjATwsA==", + "devOptional": true, + "license": "MIT" + }, + "node_modules/detect-libc": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/detect-libc/-/detect-libc-2.1.2.tgz", + "integrity": "sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ==", + "devOptional": true, + "license": "Apache-2.0", + "engines": { + "node": ">=8" + } + }, + "node_modules/diff": { + "version": "8.0.3", + "resolved": "https://registry.npmjs.org/diff/-/diff-8.0.3.tgz", + "integrity": "sha512-qejHi7bcSD4hQAZE0tNAawRK1ZtafHDmMTMkrrIGgSLl7hTnQHmKCeB45xAcbfTqK2zowkM3j3bHt/4b/ARbYQ==", + "license": "BSD-3-Clause", + "engines": { + "node": ">=0.3.1" + } + }, + "node_modules/doctrine": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/doctrine/-/doctrine-2.1.0.tgz", + "integrity": "sha512-35mSku4ZXK0vfCuHEDAwt55dg2jNajHZ1odvF+8SSr82EsZY4QmXfuWso8oEd8zRhVObSN18aM0CjSdoBX7zIw==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "esutils": "^2.0.2" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/dotenv": { + "version": "16.6.1", + "resolved": "https://registry.npmjs.org/dotenv/-/dotenv-16.6.1.tgz", + "integrity": "sha512-uBq4egWHTcTt33a72vpSG0z3HnPuIl6NqYcTrKEg2azoEyl2hpW0zqlxysq2pK9HlDIHyHyakeYaYnSAwd8bow==", + "devOptional": true, + "license": "BSD-2-Clause", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://dotenvx.com" + } + }, + "node_modules/dunder-proto": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/dunder-proto/-/dunder-proto-1.0.1.tgz", + "integrity": "sha512-KIN/nDJBQRcXw0MLVhZE9iQHmG68qAVIBg9CqmUYjmQIhgij9U5MFvrqkUL5FbtyyzZuOeOt0zdeRe4UY7ct+A==", + "license": "MIT", + "dependencies": { + "call-bind-apply-helpers": "^1.0.1", + "es-errors": "^1.3.0", + "gopd": "^1.2.0" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/eciesjs": { + "version": "0.4.18", + "resolved": "https://registry.npmjs.org/eciesjs/-/eciesjs-0.4.18.tgz", + "integrity": "sha512-wG99Zcfcys9fZux7Cft8BAX/YrOJLJSZ3jyYPfhZHqN2E+Ffx+QXBDsv3gubEgPtV6dTzJMSQUwk1H98/t/0wQ==", + "license": "MIT", + "dependencies": { + "@ecies/ciphers": "^0.2.5", + "@noble/ciphers": "^1.3.0", + "@noble/curves": "^1.9.7", + "@noble/hashes": "^1.8.0" + }, + "engines": { + "bun": ">=1", + "deno": ">=2", + "node": ">=16" + } + }, + "node_modules/ee-first": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/ee-first/-/ee-first-1.1.1.tgz", + "integrity": "sha512-WMwm9LhRUo+WUaRN+vRuETqG89IgZphVSNkdFgeb6sS/E4OrDIN7t48CAewSHXc6C8lefD8KKfr5vY61brQlow==", + "license": "MIT" + }, + "node_modules/effect": { + "version": "3.20.0", + "resolved": "https://registry.npmjs.org/effect/-/effect-3.20.0.tgz", + "integrity": "sha512-qMLfDJscrNG8p/aw+IkT9W7fgj50Z4wG5bLBy0Txsxz8iUHjDIkOgO3SV0WZfnQbNG2VJYb0b+rDLMrhM4+Krw==", + "devOptional": true, + "license": "MIT", + "dependencies": { + "@standard-schema/spec": "^1.0.0", + "fast-check": "^3.23.1" + } + }, + "node_modules/electron-to-chromium": { + "version": "1.5.313", + "resolved": "https://registry.npmjs.org/electron-to-chromium/-/electron-to-chromium-1.5.313.tgz", + "integrity": "sha512-QBMrTWEf00GXZmJyx2lbYD45jpI3TUFnNIzJ5BBc8piGUDwMPa1GV6HJWTZVvY/eiN3fSopl7NRbgGp9sZ9LTA==", + "license": "ISC" + }, + "node_modules/elementtree": { + "version": "0.1.7", + "resolved": "https://registry.npmjs.org/elementtree/-/elementtree-0.1.7.tgz", + "integrity": "sha512-wkgGT6kugeQk/P6VZ/f4T+4HB41BVgNBq5CDIZVbQ02nvTVqAiVTbskxxu3eA/X96lMlfYOwnLQpN2v5E1zDEg==", + "license": "Apache-2.0", + "dependencies": { + "sax": "1.1.4" + }, + "engines": { + "node": ">= 0.4.0" + } + }, + "node_modules/emoji-regex": { + "version": "9.2.2", + "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-9.2.2.tgz", + "integrity": "sha512-L18DaJsXSUk2+42pv8mLs5jJT2hqFkFE4j21wOmgbUqsZ2hL72NsUU785g9RXgo3s0ZNgVl42TiHp3ZtOv/Vyg==", + "dev": true, + "license": "MIT" + }, + "node_modules/empathic": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/empathic/-/empathic-2.0.0.tgz", + "integrity": "sha512-i6UzDscO/XfAcNYD75CfICkmfLedpyPDdozrLMmQc5ORaQcdMoc21OnlEylMIqI7U8eniKrPMxxtj8k0vhmJhA==", + "devOptional": true, + "license": "MIT", + "engines": { + "node": ">=14" + } + }, + "node_modules/encodeurl": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/encodeurl/-/encodeurl-2.0.0.tgz", + "integrity": "sha512-Q0n9HRi4m6JuGIV1eFlmvJB7ZEVxu93IrMyiMsGC0lrMJMWzRgx6WGquyfQgZVb31vhGgXnfmPNNXmxnOkRBrg==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/enhanced-resolve": { + "version": "5.20.1", + "resolved": "https://registry.npmjs.org/enhanced-resolve/-/enhanced-resolve-5.20.1.tgz", + "integrity": "sha512-Qohcme7V1inbAfvjItgw0EaxVX5q2rdVEZHRBrEQdRZTssLDGsL8Lwrznl8oQ/6kuTJONLaDcGjkNP247XEhcA==", + "dev": true, + "license": "MIT", + "dependencies": { + "graceful-fs": "^4.2.4", + "tapable": "^2.3.0" + }, + "engines": { + "node": ">=10.13.0" + } + }, + "node_modules/env-paths": { + "version": "2.2.1", + "resolved": "https://registry.npmjs.org/env-paths/-/env-paths-2.2.1.tgz", + "integrity": "sha512-+h1lkLKhZMTYjog1VEpJNG7NZJWcuc2DDk/qsqSTRRCOXiLjeQ1d1/udrUGhqMxUgAlwKNZ0cf2uqan5GLuS2A==", + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/error-ex": { + "version": "1.3.4", + "resolved": "https://registry.npmjs.org/error-ex/-/error-ex-1.3.4.tgz", + "integrity": "sha512-sqQamAnR14VgCr1A618A3sGrygcpK+HEbenA/HiEAkkUwcZIIB/tgWqHFxWgOyDh4nB4JCRimh79dR5Ywc9MDQ==", + "license": "MIT", + "dependencies": { + "is-arrayish": "^0.2.1" + } + }, + "node_modules/es-abstract": { + "version": "1.24.1", + "resolved": "https://registry.npmjs.org/es-abstract/-/es-abstract-1.24.1.tgz", + "integrity": "sha512-zHXBLhP+QehSSbsS9Pt23Gg964240DPd6QCf8WpkqEXxQ7fhdZzYsocOr5u7apWonsS5EjZDmTF+/slGMyasvw==", + "dev": true, + "license": "MIT", + "dependencies": { + "array-buffer-byte-length": "^1.0.2", + "arraybuffer.prototype.slice": "^1.0.4", + "available-typed-arrays": "^1.0.7", + "call-bind": "^1.0.8", + "call-bound": "^1.0.4", + "data-view-buffer": "^1.0.2", + "data-view-byte-length": "^1.0.2", + "data-view-byte-offset": "^1.0.1", + "es-define-property": "^1.0.1", + "es-errors": "^1.3.0", + "es-object-atoms": "^1.1.1", + "es-set-tostringtag": "^2.1.0", + "es-to-primitive": "^1.3.0", + "function.prototype.name": "^1.1.8", + "get-intrinsic": "^1.3.0", + "get-proto": "^1.0.1", + "get-symbol-description": "^1.1.0", + "globalthis": "^1.0.4", + "gopd": "^1.2.0", + "has-property-descriptors": "^1.0.2", + "has-proto": "^1.2.0", + "has-symbols": "^1.1.0", + "hasown": "^2.0.2", + "internal-slot": "^1.1.0", + "is-array-buffer": "^3.0.5", + "is-callable": "^1.2.7", + "is-data-view": "^1.0.2", + "is-negative-zero": "^2.0.3", + "is-regex": "^1.2.1", + "is-set": "^2.0.3", + "is-shared-array-buffer": "^1.0.4", + "is-string": "^1.1.1", + "is-typed-array": "^1.1.15", + "is-weakref": "^1.1.1", + "math-intrinsics": "^1.1.0", + "object-inspect": "^1.13.4", + "object-keys": "^1.1.1", + "object.assign": "^4.1.7", + "own-keys": "^1.0.1", + "regexp.prototype.flags": "^1.5.4", + "safe-array-concat": "^1.1.3", + "safe-push-apply": "^1.0.0", + "safe-regex-test": "^1.1.0", + "set-proto": "^1.0.0", + "stop-iteration-iterator": "^1.1.0", + "string.prototype.trim": "^1.2.10", + "string.prototype.trimend": "^1.0.9", + "string.prototype.trimstart": "^1.0.8", + "typed-array-buffer": "^1.0.3", + "typed-array-byte-length": "^1.0.3", + "typed-array-byte-offset": "^1.0.4", + "typed-array-length": "^1.0.7", + "unbox-primitive": "^1.1.0", + "which-typed-array": "^1.1.19" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/es-define-property": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/es-define-property/-/es-define-property-1.0.1.tgz", + "integrity": "sha512-e3nRfgfUZ4rNGL232gUgX06QNyyez04KdjFrF+LTRoOXmrOgFKDg4BCdsjW8EnT69eqdYGmRpJwiPVYNrCaW3g==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/es-errors": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/es-errors/-/es-errors-1.3.0.tgz", + "integrity": "sha512-Zf5H2Kxt2xjTvbJvP2ZWLEICxA6j+hAmMzIlypy4xcBg1vKVnx89Wy0GbS+kf5cwCVFFzdCFh2XSCFNULS6csw==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/es-iterator-helpers": { + "version": "1.3.1", + "resolved": "https://registry.npmjs.org/es-iterator-helpers/-/es-iterator-helpers-1.3.1.tgz", + "integrity": "sha512-zWwRvqWiuBPr0muUG/78cW3aHROFCNIQ3zpmYDpwdbnt2m+xlNyRWpHBpa2lJjSBit7BQ+RXA1iwbSmu5yJ/EQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bind": "^1.0.8", + "call-bound": "^1.0.4", + "define-properties": "^1.2.1", + "es-abstract": "^1.24.1", + "es-errors": "^1.3.0", + "es-set-tostringtag": "^2.1.0", + "function-bind": "^1.1.2", + "get-intrinsic": "^1.3.0", + "globalthis": "^1.0.4", + "gopd": "^1.2.0", + "has-property-descriptors": "^1.0.2", + "has-proto": "^1.2.0", + "has-symbols": "^1.1.0", + "internal-slot": "^1.1.0", + "iterator.prototype": "^1.1.5", + "math-intrinsics": "^1.1.0", + "safe-array-concat": "^1.1.3" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/es-module-lexer": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/es-module-lexer/-/es-module-lexer-2.0.0.tgz", + "integrity": "sha512-5POEcUuZybH7IdmGsD8wlf0AI55wMecM9rVBTI/qEAy2c1kTOm3DjFYjrBdI2K3BaJjJYfYFeRtM0t9ssnRuxw==", + "dev": true, + "license": "MIT" + }, + "node_modules/es-object-atoms": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/es-object-atoms/-/es-object-atoms-1.1.1.tgz", + "integrity": "sha512-FGgH2h8zKNim9ljj7dankFPcICIK9Cp5bm+c2gQSYePhpaG5+esrLODihIorn+Pe6FGJzWhXQotPv73jTaldXA==", + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/es-set-tostringtag": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/es-set-tostringtag/-/es-set-tostringtag-2.1.0.tgz", + "integrity": "sha512-j6vWzfrGVfyXxge+O0x5sh6cvxAog0a/4Rdd2K36zCMV5eJ+/+tOAngRO8cODMNWbVRdVlmGZQL2YS3yR8bIUA==", + "dev": true, + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0", + "get-intrinsic": "^1.2.6", + "has-tostringtag": "^1.0.2", + "hasown": "^2.0.2" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/es-shim-unscopables": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/es-shim-unscopables/-/es-shim-unscopables-1.1.0.tgz", + "integrity": "sha512-d9T8ucsEhh8Bi1woXCf+TIKDIROLG5WCkxg8geBCbvk22kzwC5G2OnXVMO6FUsvQlgUUXQ2itephWDLqDzbeCw==", + "dev": true, + "license": "MIT", + "dependencies": { + "hasown": "^2.0.2" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/es-to-primitive": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/es-to-primitive/-/es-to-primitive-1.3.0.tgz", + "integrity": "sha512-w+5mJ3GuFL+NjVtJlvydShqE1eN3h3PbI7/5LAsYJP/2qtuMXjfL2LpHSRqo4b4eSF5K/DH1JXKUAHSB2UW50g==", + "dev": true, + "license": "MIT", + "dependencies": { + "is-callable": "^1.2.7", + "is-date-object": "^1.0.5", + "is-symbol": "^1.0.4" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/es-toolkit": { + "version": "1.45.1", + "resolved": "https://registry.npmjs.org/es-toolkit/-/es-toolkit-1.45.1.tgz", + "integrity": "sha512-/jhoOj/Fx+A+IIyDNOvO3TItGmlMKhtX8ISAHKE90c4b/k1tqaqEZ+uUqfpU8DMnW5cgNJv606zS55jGvza0Xw==", + "license": "MIT", + "workspaces": [ + "docs", + "benchmarks" + ] + }, + "node_modules/esbuild": { + "version": "0.27.4", + "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.27.4.tgz", + "integrity": "sha512-Rq4vbHnYkK5fws5NF7MYTU68FPRE1ajX7heQ/8QXXWqNgqqJ/GkmmyxIzUnf2Sr/bakf8l54716CcMGHYhMrrQ==", + "dev": true, + "hasInstallScript": true, + "license": "MIT", + "bin": { + "esbuild": "bin/esbuild" + }, + "engines": { + "node": ">=18" + }, + "optionalDependencies": { + "@esbuild/aix-ppc64": "0.27.4", + "@esbuild/android-arm": "0.27.4", + "@esbuild/android-arm64": "0.27.4", + "@esbuild/android-x64": "0.27.4", + "@esbuild/darwin-arm64": "0.27.4", + "@esbuild/darwin-x64": "0.27.4", + "@esbuild/freebsd-arm64": "0.27.4", + "@esbuild/freebsd-x64": "0.27.4", + "@esbuild/linux-arm": "0.27.4", + "@esbuild/linux-arm64": "0.27.4", + "@esbuild/linux-ia32": "0.27.4", + "@esbuild/linux-loong64": "0.27.4", + "@esbuild/linux-mips64el": "0.27.4", + "@esbuild/linux-ppc64": "0.27.4", + "@esbuild/linux-riscv64": "0.27.4", + "@esbuild/linux-s390x": "0.27.4", + "@esbuild/linux-x64": "0.27.4", + "@esbuild/netbsd-arm64": "0.27.4", + "@esbuild/netbsd-x64": "0.27.4", + "@esbuild/openbsd-arm64": "0.27.4", + "@esbuild/openbsd-x64": "0.27.4", + "@esbuild/openharmony-arm64": "0.27.4", + "@esbuild/sunos-x64": "0.27.4", + "@esbuild/win32-arm64": "0.27.4", + "@esbuild/win32-ia32": "0.27.4", + "@esbuild/win32-x64": "0.27.4" + } + }, + "node_modules/escalade": { + "version": "3.2.0", + "resolved": "https://registry.npmjs.org/escalade/-/escalade-3.2.0.tgz", + "integrity": "sha512-WUj2qlxaQtO4g6Pq5c29GTcWGDyd8itL8zTlipgECz3JesAiiOKotd8JU6otB3PACgG6xkJUyVhboMS+bje/jA==", + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/escape-html": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/escape-html/-/escape-html-1.0.3.tgz", + "integrity": "sha512-NiSupZ4OeuGwr68lGIeym/ksIZMJodUGOSCZ/FSnTxcrekbvqrgdUxlJOMpijaKZVjAJrWrGs/6Jy8OMuyj9ow==", + "license": "MIT" + }, + "node_modules/escape-string-regexp": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-4.0.0.tgz", + "integrity": "sha512-TtpcNJ3XAzx3Gq8sWRzJaVajRs0uVxA2YAkdb1jm2YkPz4G6egUFAyA3n5vtEIZefPk5Wa4UXbKuS5fKkJWdgA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/eslint": { + "version": "9.39.4", + "resolved": "https://registry.npmjs.org/eslint/-/eslint-9.39.4.tgz", + "integrity": "sha512-XoMjdBOwe/esVgEvLmNsD3IRHkm7fbKIUGvrleloJXUZgDHig2IPWNniv+GwjyJXzuNqVjlr5+4yVUZjycJwfQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@eslint-community/eslint-utils": "^4.8.0", + "@eslint-community/regexpp": "^4.12.1", + "@eslint/config-array": "^0.21.2", + "@eslint/config-helpers": "^0.4.2", + "@eslint/core": "^0.17.0", + "@eslint/eslintrc": "^3.3.5", + "@eslint/js": "9.39.4", + "@eslint/plugin-kit": "^0.4.1", + "@humanfs/node": "^0.16.6", + "@humanwhocodes/module-importer": "^1.0.1", + "@humanwhocodes/retry": "^0.4.2", + "@types/estree": "^1.0.6", + "ajv": "^6.14.0", + "chalk": "^4.0.0", + "cross-spawn": "^7.0.6", + "debug": "^4.3.2", + "escape-string-regexp": "^4.0.0", + "eslint-scope": "^8.4.0", + "eslint-visitor-keys": "^4.2.1", + "espree": "^10.4.0", + "esquery": "^1.5.0", + "esutils": "^2.0.2", + "fast-deep-equal": "^3.1.3", + "file-entry-cache": "^8.0.0", + "find-up": "^5.0.0", + "glob-parent": "^6.0.2", + "ignore": "^5.2.0", + "imurmurhash": "^0.1.4", + "is-glob": "^4.0.0", + "json-stable-stringify-without-jsonify": "^1.0.1", + "lodash.merge": "^4.6.2", + "minimatch": "^3.1.5", + "natural-compare": "^1.4.0", + "optionator": "^0.9.3" + }, + "bin": { + "eslint": "bin/eslint.js" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "url": "https://eslint.org/donate" + }, + "peerDependencies": { + "jiti": "*" + }, + "peerDependenciesMeta": { + "jiti": { + "optional": true + } + } + }, + "node_modules/eslint-config-next": { + "version": "16.1.7", + "resolved": "https://registry.npmjs.org/eslint-config-next/-/eslint-config-next-16.1.7.tgz", + "integrity": "sha512-FTq1i/QDltzq+zf9aB/cKWAiZ77baG0V7h8dRQh3thVx7I4dwr6ZXQrWKAaTB7x5VwVXlzoUTyMLIVQPLj2gJg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@next/eslint-plugin-next": "16.1.7", + "eslint-import-resolver-node": "^0.3.6", + "eslint-import-resolver-typescript": "^3.5.2", + "eslint-plugin-import": "^2.32.0", + "eslint-plugin-jsx-a11y": "^6.10.0", + "eslint-plugin-react": "^7.37.0", + "eslint-plugin-react-hooks": "^7.0.0", + "globals": "16.4.0", + "typescript-eslint": "^8.46.0" + }, + "peerDependencies": { + "eslint": ">=9.0.0", + "typescript": ">=3.3.1" + }, + "peerDependenciesMeta": { + "typescript": { + "optional": true + } + } + }, + "node_modules/eslint-config-next/node_modules/globals": { + "version": "16.4.0", + "resolved": "https://registry.npmjs.org/globals/-/globals-16.4.0.tgz", + "integrity": "sha512-ob/2LcVVaVGCYN+r14cnwnoDPUufjiYgSqRhiFD0Q1iI4Odora5RE8Iv1D24hAz5oMophRGkGz+yuvQmmUMnMw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/eslint-import-resolver-node": { + "version": "0.3.9", + "resolved": "https://registry.npmjs.org/eslint-import-resolver-node/-/eslint-import-resolver-node-0.3.9.tgz", + "integrity": "sha512-WFj2isz22JahUv+B788TlO3N6zL3nNJGU8CcZbPZvVEkBPaJdCV4vy5wyghty5ROFbCRnm132v8BScu5/1BQ8g==", + "dev": true, + "license": "MIT", + "dependencies": { + "debug": "^3.2.7", + "is-core-module": "^2.13.0", + "resolve": "^1.22.4" + } + }, + "node_modules/eslint-import-resolver-node/node_modules/debug": { + "version": "3.2.7", + "resolved": "https://registry.npmjs.org/debug/-/debug-3.2.7.tgz", + "integrity": "sha512-CFjzYYAi4ThfiQvizrFQevTTXHtnCqWfe7x1AhgEscTz6ZbLbfoLRLPugTQyBth6f8ZERVUSyWHFD/7Wu4t1XQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "ms": "^2.1.1" + } + }, + "node_modules/eslint-import-resolver-typescript": { + "version": "3.10.1", + "resolved": "https://registry.npmjs.org/eslint-import-resolver-typescript/-/eslint-import-resolver-typescript-3.10.1.tgz", + "integrity": "sha512-A1rHYb06zjMGAxdLSkN2fXPBwuSaQ0iO5M/hdyS0Ajj1VBaRp0sPD3dn1FhME3c/JluGFbwSxyCfqdSbtQLAHQ==", + "dev": true, + "license": "ISC", + "dependencies": { + "@nolyfill/is-core-module": "1.0.39", + "debug": "^4.4.0", + "get-tsconfig": "^4.10.0", + "is-bun-module": "^2.0.0", + "stable-hash": "^0.0.5", + "tinyglobby": "^0.2.13", + "unrs-resolver": "^1.6.2" + }, + "engines": { + "node": "^14.18.0 || >=16.0.0" + }, + "funding": { + "url": "https://opencollective.com/eslint-import-resolver-typescript" + }, + "peerDependencies": { + "eslint": "*", + "eslint-plugin-import": "*", + "eslint-plugin-import-x": "*" + }, + "peerDependenciesMeta": { + "eslint-plugin-import": { + "optional": true + }, + "eslint-plugin-import-x": { + "optional": true + } + } + }, + "node_modules/eslint-module-utils": { + "version": "2.12.1", + "resolved": "https://registry.npmjs.org/eslint-module-utils/-/eslint-module-utils-2.12.1.tgz", + "integrity": "sha512-L8jSWTze7K2mTg0vos/RuLRS5soomksDPoJLXIslC7c8Wmut3bx7CPpJijDcBZtxQ5lrbUdM+s0OlNbz0DCDNw==", + "dev": true, + "license": "MIT", + "dependencies": { + "debug": "^3.2.7" + }, + "engines": { + "node": ">=4" + }, + "peerDependenciesMeta": { + "eslint": { + "optional": true + } + } + }, + "node_modules/eslint-module-utils/node_modules/debug": { + "version": "3.2.7", + "resolved": "https://registry.npmjs.org/debug/-/debug-3.2.7.tgz", + "integrity": "sha512-CFjzYYAi4ThfiQvizrFQevTTXHtnCqWfe7x1AhgEscTz6ZbLbfoLRLPugTQyBth6f8ZERVUSyWHFD/7Wu4t1XQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "ms": "^2.1.1" + } + }, + "node_modules/eslint-plugin-import": { + "version": "2.32.0", + "resolved": "https://registry.npmjs.org/eslint-plugin-import/-/eslint-plugin-import-2.32.0.tgz", + "integrity": "sha512-whOE1HFo/qJDyX4SnXzP4N6zOWn79WhnCUY/iDR0mPfQZO8wcYE4JClzI2oZrhBnnMUCBCHZhO6VQyoBU95mZA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@rtsao/scc": "^1.1.0", + "array-includes": "^3.1.9", + "array.prototype.findlastindex": "^1.2.6", + "array.prototype.flat": "^1.3.3", + "array.prototype.flatmap": "^1.3.3", + "debug": "^3.2.7", + "doctrine": "^2.1.0", + "eslint-import-resolver-node": "^0.3.9", + "eslint-module-utils": "^2.12.1", + "hasown": "^2.0.2", + "is-core-module": "^2.16.1", + "is-glob": "^4.0.3", + "minimatch": "^3.1.2", + "object.fromentries": "^2.0.8", + "object.groupby": "^1.0.3", + "object.values": "^1.2.1", + "semver": "^6.3.1", + "string.prototype.trimend": "^1.0.9", + "tsconfig-paths": "^3.15.0" + }, + "engines": { + "node": ">=4" + }, + "peerDependencies": { + "eslint": "^2 || ^3 || ^4 || ^5 || ^6 || ^7.2.0 || ^8 || ^9" + } + }, + "node_modules/eslint-plugin-import/node_modules/debug": { + "version": "3.2.7", + "resolved": "https://registry.npmjs.org/debug/-/debug-3.2.7.tgz", + "integrity": "sha512-CFjzYYAi4ThfiQvizrFQevTTXHtnCqWfe7x1AhgEscTz6ZbLbfoLRLPugTQyBth6f8ZERVUSyWHFD/7Wu4t1XQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "ms": "^2.1.1" + } + }, + "node_modules/eslint-plugin-jsx-a11y": { + "version": "6.10.2", + "resolved": "https://registry.npmjs.org/eslint-plugin-jsx-a11y/-/eslint-plugin-jsx-a11y-6.10.2.tgz", + "integrity": "sha512-scB3nz4WmG75pV8+3eRUQOHZlNSUhFNq37xnpgRkCCELU3XMvXAxLk1eqWWyE22Ki4Q01Fnsw9BA3cJHDPgn2Q==", + "dev": true, + "license": "MIT", + "dependencies": { + "aria-query": "^5.3.2", + "array-includes": "^3.1.8", + "array.prototype.flatmap": "^1.3.2", + "ast-types-flow": "^0.0.8", + "axe-core": "^4.10.0", + "axobject-query": "^4.1.0", + "damerau-levenshtein": "^1.0.8", + "emoji-regex": "^9.2.2", + "hasown": "^2.0.2", + "jsx-ast-utils": "^3.3.5", + "language-tags": "^1.0.9", + "minimatch": "^3.1.2", + "object.fromentries": "^2.0.8", + "safe-regex-test": "^1.0.3", + "string.prototype.includes": "^2.0.1" + }, + "engines": { + "node": ">=4.0" + }, + "peerDependencies": { + "eslint": "^3 || ^4 || ^5 || ^6 || ^7 || ^8 || ^9" + } + }, + "node_modules/eslint-plugin-react": { + "version": "7.37.5", + "resolved": "https://registry.npmjs.org/eslint-plugin-react/-/eslint-plugin-react-7.37.5.tgz", + "integrity": "sha512-Qteup0SqU15kdocexFNAJMvCJEfa2xUKNV4CC1xsVMrIIqEy3SQ/rqyxCWNzfrd3/ldy6HMlD2e0JDVpDg2qIA==", + "dev": true, + "license": "MIT", + "dependencies": { + "array-includes": "^3.1.8", + "array.prototype.findlast": "^1.2.5", + "array.prototype.flatmap": "^1.3.3", + "array.prototype.tosorted": "^1.1.4", + "doctrine": "^2.1.0", + "es-iterator-helpers": "^1.2.1", + "estraverse": "^5.3.0", + "hasown": "^2.0.2", + "jsx-ast-utils": "^2.4.1 || ^3.0.0", + "minimatch": "^3.1.2", + "object.entries": "^1.1.9", + "object.fromentries": "^2.0.8", + "object.values": "^1.2.1", + "prop-types": "^15.8.1", + "resolve": "^2.0.0-next.5", + "semver": "^6.3.1", + "string.prototype.matchall": "^4.0.12", + "string.prototype.repeat": "^1.0.0" + }, + "engines": { + "node": ">=4" + }, + "peerDependencies": { + "eslint": "^3 || ^4 || ^5 || ^6 || ^7 || ^8 || ^9.7" + } + }, + "node_modules/eslint-plugin-react-hooks": { + "version": "7.0.1", + "resolved": "https://registry.npmjs.org/eslint-plugin-react-hooks/-/eslint-plugin-react-hooks-7.0.1.tgz", + "integrity": "sha512-O0d0m04evaNzEPoSW+59Mezf8Qt0InfgGIBJnpC0h3NH/WjUAR7BIKUfysC6todmtiZ/A0oUVS8Gce0WhBrHsA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/core": "^7.24.4", + "@babel/parser": "^7.24.4", + "hermes-parser": "^0.25.1", + "zod": "^3.25.0 || ^4.0.0", + "zod-validation-error": "^3.5.0 || ^4.0.0" + }, + "engines": { + "node": ">=18" + }, + "peerDependencies": { + "eslint": "^3.0.0 || ^4.0.0 || ^5.0.0 || ^6.0.0 || ^7.0.0 || ^8.0.0-0 || ^9.0.0" + } + }, + "node_modules/eslint-plugin-react/node_modules/resolve": { + "version": "2.0.0-next.6", + "resolved": "https://registry.npmjs.org/resolve/-/resolve-2.0.0-next.6.tgz", + "integrity": "sha512-3JmVl5hMGtJ3kMmB3zi3DL25KfkCEyy3Tw7Gmw7z5w8M9WlwoPFnIvwChzu1+cF3iaK3sp18hhPz8ANeimdJfA==", + "dev": true, + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0", + "is-core-module": "^2.16.1", + "node-exports-info": "^1.6.0", + "object-keys": "^1.1.1", + "path-parse": "^1.0.7", + "supports-preserve-symlinks-flag": "^1.0.0" + }, + "bin": { + "resolve": "bin/resolve" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/eslint-scope": { + "version": "8.4.0", + "resolved": "https://registry.npmjs.org/eslint-scope/-/eslint-scope-8.4.0.tgz", + "integrity": "sha512-sNXOfKCn74rt8RICKMvJS7XKV/Xk9kA7DyJr8mJik3S7Cwgy3qlkkmyS2uQB3jiJg6VNdZd/pDBJu0nvG2NlTg==", + "dev": true, + "license": "BSD-2-Clause", + "dependencies": { + "esrecurse": "^4.3.0", + "estraverse": "^5.2.0" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "url": "https://opencollective.com/eslint" + } + }, + "node_modules/eslint-visitor-keys": { + "version": "4.2.1", + "resolved": "https://registry.npmjs.org/eslint-visitor-keys/-/eslint-visitor-keys-4.2.1.tgz", + "integrity": "sha512-Uhdk5sfqcee/9H/rCOJikYz67o0a2Tw2hGRPOG2Y1R2dg7brRe1uG0yaNQDHu+TO/uQPF/5eCapvYSmHUjt7JQ==", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "url": "https://opencollective.com/eslint" + } + }, + "node_modules/espree": { + "version": "10.4.0", + "resolved": "https://registry.npmjs.org/espree/-/espree-10.4.0.tgz", + "integrity": "sha512-j6PAQ2uUr79PZhBjP5C5fhl8e39FmRnOjsD5lGnWrFU8i2G776tBK7+nP8KuQUTTyAZUwfQqXAgrVH5MbH9CYQ==", + "dev": true, + "license": "BSD-2-Clause", + "dependencies": { + "acorn": "^8.15.0", + "acorn-jsx": "^5.3.2", + "eslint-visitor-keys": "^4.2.1" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "url": "https://opencollective.com/eslint" + } + }, + "node_modules/esprima": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/esprima/-/esprima-4.0.1.tgz", + "integrity": "sha512-eGuFFw7Upda+g4p+QHvnW0RyTX/SVeJBDM/gCtMARO0cLuT2HcEKnTPvhjV6aGeqrCB/sbNop0Kszm0jsaWU4A==", + "license": "BSD-2-Clause", + "bin": { + "esparse": "bin/esparse.js", + "esvalidate": "bin/esvalidate.js" + }, + "engines": { + "node": ">=4" + } + }, + "node_modules/esquery": { + "version": "1.7.0", + "resolved": "https://registry.npmjs.org/esquery/-/esquery-1.7.0.tgz", + "integrity": "sha512-Ap6G0WQwcU/LHsvLwON1fAQX9Zp0A2Y6Y/cJBl9r/JbW90Zyg4/zbG6zzKa2OTALELarYHmKu0GhpM5EO+7T0g==", + "dev": true, + "license": "BSD-3-Clause", + "dependencies": { + "estraverse": "^5.1.0" + }, + "engines": { + "node": ">=0.10" + } + }, + "node_modules/esrecurse": { + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/esrecurse/-/esrecurse-4.3.0.tgz", + "integrity": "sha512-KmfKL3b6G+RXvP8N1vr3Tq1kL/oCFgn2NYXEtqP8/L3pKapUA4G8cFVaoF3SU323CD4XypR/ffioHmkti6/Tag==", + "dev": true, + "license": "BSD-2-Clause", + "dependencies": { + "estraverse": "^5.2.0" + }, + "engines": { + "node": ">=4.0" + } + }, + "node_modules/estraverse": { + "version": "5.3.0", + "resolved": "https://registry.npmjs.org/estraverse/-/estraverse-5.3.0.tgz", + "integrity": "sha512-MMdARuVEQziNTeJD8DgMqmhwR11BRQ/cBP+pLtYdSTnf3MIO8fFeiINEbX36ZdNlfU/7A9f3gUw49B3oQsvwBA==", + "dev": true, + "license": "BSD-2-Clause", + "engines": { + "node": ">=4.0" + } + }, + "node_modules/estree-walker": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/estree-walker/-/estree-walker-3.0.3.tgz", + "integrity": "sha512-7RUKfXgSMMkzt6ZuXmqapOurLGPPfgj6l9uRZ7lRGolvk0y2yocc35LdcxKC5PQZdn2DMqioAQ2NoWcrTKmm6g==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/estree": "^1.0.0" + } + }, + "node_modules/esutils": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/esutils/-/esutils-2.0.3.tgz", + "integrity": "sha512-kVscqXk4OCp68SZ0dkgEKVi6/8ij300KBWTJq32P/dYeWTSwK41WyTxalN1eRmA5Z9UU/LX9D7FWSmV9SAYx6g==", + "dev": true, + "license": "BSD-2-Clause", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/etag": { + "version": "1.8.1", + "resolved": "https://registry.npmjs.org/etag/-/etag-1.8.1.tgz", + "integrity": "sha512-aIL5Fx7mawVa300al2BnEE4iNvo1qETxLrPI/o05L7z6go7fCw1J6EQmbK4FmJ2AS7kgVF/KEZWufBfdClMcPg==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/eventemitter3": { + "version": "5.0.4", + "resolved": "https://registry.npmjs.org/eventemitter3/-/eventemitter3-5.0.4.tgz", + "integrity": "sha512-mlsTRyGaPBjPedk6Bvw+aqbsXDtoAyAzm5MO7JgU+yVRyMQ5O8bD4Kcci7BS85f93veegeCPkL8R4GLClnjLFw==", + "license": "MIT" + }, + "node_modules/eventsource": { + "version": "3.0.7", + "resolved": "https://registry.npmjs.org/eventsource/-/eventsource-3.0.7.tgz", + "integrity": "sha512-CRT1WTyuQoD771GW56XEZFQ/ZoSfWid1alKGDYMmkt2yl8UXrVR4pspqWNEcqKvVIzg6PAltWjxcSSPrboA4iA==", + "license": "MIT", + "dependencies": { + "eventsource-parser": "^3.0.1" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/eventsource-parser": { + "version": "3.0.6", + "resolved": "https://registry.npmjs.org/eventsource-parser/-/eventsource-parser-3.0.6.tgz", + "integrity": "sha512-Vo1ab+QXPzZ4tCa8SwIHJFaSzy4R6SHf7BY79rFBDf0idraZWAkYrDjDj8uWaSm3S2TK+hJ7/t1CEmZ7jXw+pg==", + "license": "MIT", + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/execa": { + "version": "9.6.1", + "resolved": "https://registry.npmjs.org/execa/-/execa-9.6.1.tgz", + "integrity": "sha512-9Be3ZoN4LmYR90tUoVu2te2BsbzHfhJyfEiAVfz7N5/zv+jduIfLrV2xdQXOHbaD6KgpGdO9PRPM1Y4Q9QkPkA==", + "license": "MIT", + "dependencies": { + "@sindresorhus/merge-streams": "^4.0.0", + "cross-spawn": "^7.0.6", + "figures": "^6.1.0", + "get-stream": "^9.0.0", + "human-signals": "^8.0.1", + "is-plain-obj": "^4.1.0", + "is-stream": "^4.0.1", + "npm-run-path": "^6.0.0", + "pretty-ms": "^9.2.0", + "signal-exit": "^4.1.0", + "strip-final-newline": "^4.0.0", + "yoctocolors": "^2.1.1" + }, + "engines": { + "node": "^18.19.0 || >=20.5.0" + }, + "funding": { + "url": "https://github.com/sindresorhus/execa?sponsor=1" + } + }, + "node_modules/expect-type": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/expect-type/-/expect-type-1.3.0.tgz", + "integrity": "sha512-knvyeauYhqjOYvQ66MznSMs83wmHrCycNEN6Ao+2AeYEfxUIkuiVxdEa1qlGEPK+We3n0THiDciYSsCcgW/DoA==", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": ">=12.0.0" + } + }, + "node_modules/express": { + "version": "5.2.1", + "resolved": "https://registry.npmjs.org/express/-/express-5.2.1.tgz", + "integrity": "sha512-hIS4idWWai69NezIdRt2xFVofaF4j+6INOpJlVOLDO8zXGpUVEVzIYk12UUi2JzjEzWL3IOAxcTubgz9Po0yXw==", + "license": "MIT", + "dependencies": { + "accepts": "^2.0.0", + "body-parser": "^2.2.1", + "content-disposition": "^1.0.0", + "content-type": "^1.0.5", + "cookie": "^0.7.1", + "cookie-signature": "^1.2.1", + "debug": "^4.4.0", + "depd": "^2.0.0", + "encodeurl": "^2.0.0", + "escape-html": "^1.0.3", + "etag": "^1.8.1", + "finalhandler": "^2.1.0", + "fresh": "^2.0.0", + "http-errors": "^2.0.0", + "merge-descriptors": "^2.0.0", + "mime-types": "^3.0.0", + "on-finished": "^2.4.1", + "once": "^1.4.0", + "parseurl": "^1.3.3", + "proxy-addr": "^2.0.7", + "qs": "^6.14.0", + "range-parser": "^1.2.1", + "router": "^2.2.0", + "send": "^1.1.0", + "serve-static": "^2.2.0", + "statuses": "^2.0.1", + "type-is": "^2.0.1", + "vary": "^1.1.2" + }, + "engines": { + "node": ">= 18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/express-rate-limit": { + "version": "8.3.1", + "resolved": "https://registry.npmjs.org/express-rate-limit/-/express-rate-limit-8.3.1.tgz", + "integrity": "sha512-D1dKN+cmyPWuvB+G2SREQDzPY1agpBIcTa9sJxOPMCNeH3gwzhqJRDWCXW3gg0y//+LQ/8j52JbMROWyrKdMdw==", + "license": "MIT", + "dependencies": { + "ip-address": "10.1.0" + }, + "engines": { + "node": ">= 16" + }, + "funding": { + "url": "https://github.com/sponsors/express-rate-limit" + }, + "peerDependencies": { + "express": ">= 4.11" + } + }, + "node_modules/exsolve": { + "version": "1.0.8", + "resolved": "https://registry.npmjs.org/exsolve/-/exsolve-1.0.8.tgz", + "integrity": "sha512-LmDxfWXwcTArk8fUEnOfSZpHOJ6zOMUJKOtFLFqJLoKJetuQG874Uc7/Kki7zFLzYybmZhp1M7+98pfMqeX8yA==", + "devOptional": true, + "license": "MIT" + }, + "node_modules/fast-check": { + "version": "3.23.2", + "resolved": "https://registry.npmjs.org/fast-check/-/fast-check-3.23.2.tgz", + "integrity": "sha512-h5+1OzzfCC3Ef7VbtKdcv7zsstUQwUDlYpUTvjeUsJAssPgLn7QzbboPtL5ro04Mq0rPOsMzl7q5hIbRs2wD1A==", + "devOptional": true, + "funding": [ + { + "type": "individual", + "url": "https://github.com/sponsors/dubzzz" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/fast-check" + } + ], + "license": "MIT", + "dependencies": { + "pure-rand": "^6.1.0" + }, + "engines": { + "node": ">=8.0.0" + } + }, + "node_modules/fast-deep-equal": { + "version": "3.1.3", + "resolved": "https://registry.npmjs.org/fast-deep-equal/-/fast-deep-equal-3.1.3.tgz", + "integrity": "sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q==", + "license": "MIT" + }, + "node_modules/fast-glob": { + "version": "3.3.1", + "resolved": "https://registry.npmjs.org/fast-glob/-/fast-glob-3.3.1.tgz", + "integrity": "sha512-kNFPyjhh5cKjrUltxs+wFx+ZkbRaxxmZ+X0ZU31SOsxCEtP9VPgtq2teZw1DebupL5GmDaNQ6yKMMVcM41iqDg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@nodelib/fs.stat": "^2.0.2", + "@nodelib/fs.walk": "^1.2.3", + "glob-parent": "^5.1.2", + "merge2": "^1.3.0", + "micromatch": "^4.0.4" + }, + "engines": { + "node": ">=8.6.0" + } + }, + "node_modules/fast-glob/node_modules/glob-parent": { + "version": "5.1.2", + "resolved": "https://registry.npmjs.org/glob-parent/-/glob-parent-5.1.2.tgz", + "integrity": "sha512-AOIgSQCepiJYwP3ARnGx+5VnTu2HBYdzbGP45eLw1vr3zB3vZLeyed1sC9hnbcOc9/SrMyM5RPQrkGz4aS9Zow==", + "dev": true, + "license": "ISC", + "dependencies": { + "is-glob": "^4.0.1" + }, + "engines": { + "node": ">= 6" + } + }, + "node_modules/fast-json-stable-stringify": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/fast-json-stable-stringify/-/fast-json-stable-stringify-2.1.0.tgz", + "integrity": "sha512-lhd/wF+Lk98HZoTCtlVraHtfh5XYijIjalXck7saUtuanSDyLMxnHhSXEDJqHxD7msR8D0uCmqlkwjCV8xvwHw==", + "dev": true, + "license": "MIT" + }, + "node_modules/fast-levenshtein": { + "version": "2.0.6", + "resolved": "https://registry.npmjs.org/fast-levenshtein/-/fast-levenshtein-2.0.6.tgz", + "integrity": "sha512-DCXu6Ifhqcks7TZKY3Hxp3y6qphY5SJZmrWMDrKcERSOXWQdMhU9Ig/PYrzyw/ul9jOIyh0N4M0tbC5hodg8dw==", + "dev": true, + "license": "MIT" + }, + "node_modules/fast-uri": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/fast-uri/-/fast-uri-3.1.0.tgz", + "integrity": "sha512-iPeeDKJSWf4IEOasVVrknXpaBV0IApz/gp7S2bb7Z4Lljbl2MGJRqInZiUrQwV16cpzw/D3S5j5Julj/gT52AA==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/fastify" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/fastify" + } + ], + "license": "BSD-3-Clause" + }, + "node_modules/fastq": { + "version": "1.20.1", + "resolved": "https://registry.npmjs.org/fastq/-/fastq-1.20.1.tgz", + "integrity": "sha512-GGToxJ/w1x32s/D2EKND7kTil4n8OVk/9mycTc4VDza13lOvpUZTGX3mFSCtV9ksdGBVzvsyAVLM6mHFThxXxw==", + "license": "ISC", + "dependencies": { + "reusify": "^1.0.4" + } + }, + "node_modules/fd-slicer": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/fd-slicer/-/fd-slicer-1.1.0.tgz", + "integrity": "sha512-cE1qsB/VwyQozZ+q1dGxR8LBYNZeofhEdUNGSMbQD3Gw2lAzX9Zb3uIU6Ebc/Fmyjo9AWWfnn0AUCHqtevs/8g==", + "license": "MIT", + "dependencies": { + "pend": "~1.2.0" + } + }, + "node_modules/fetch-blob": { + "version": "3.2.0", + "resolved": "https://registry.npmjs.org/fetch-blob/-/fetch-blob-3.2.0.tgz", + "integrity": "sha512-7yAQpD2UMJzLi1Dqv7qFYnPbaPx7ZfFK6PiIxQ4PfkGPyNyl2Ugx+a/umUonmKqjhM4DnfbMvdX6otXq83soQQ==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/jimmywarting" + }, + { + "type": "paypal", + "url": "https://paypal.me/jimmywarting" + } + ], + "license": "MIT", + "dependencies": { + "node-domexception": "^1.0.0", + "web-streams-polyfill": "^3.0.3" + }, + "engines": { + "node": "^12.20 || >= 14.13" + } + }, + "node_modules/figures": { + "version": "6.1.0", + "resolved": "https://registry.npmjs.org/figures/-/figures-6.1.0.tgz", + "integrity": "sha512-d+l3qxjSesT4V7v2fh+QnmFnUWv9lSpjarhShNTgBOfA0ttejbQUAlHLitbjkoRiDulW0OPoQPYIGhIC8ohejg==", + "license": "MIT", + "dependencies": { + "is-unicode-supported": "^2.0.0" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/file-entry-cache": { + "version": "8.0.0", + "resolved": "https://registry.npmjs.org/file-entry-cache/-/file-entry-cache-8.0.0.tgz", + "integrity": "sha512-XXTUwCvisa5oacNGRP9SfNtYBNAMi+RPwBFmblZEF7N7swHYQS6/Zfk7SRwx4D5j3CH211YNRco1DEMNVfZCnQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "flat-cache": "^4.0.0" + }, + "engines": { + "node": ">=16.0.0" + } + }, + "node_modules/fill-range": { + "version": "7.1.1", + "resolved": "https://registry.npmjs.org/fill-range/-/fill-range-7.1.1.tgz", + "integrity": "sha512-YsGpe3WHLK8ZYi4tWDg2Jy3ebRz2rXowDxnld4bkQB00cc/1Zw9AWnC0i9ztDJitivtQvaI9KaLyKrc+hBW0yg==", + "license": "MIT", + "dependencies": { + "to-regex-range": "^5.0.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/finalhandler": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/finalhandler/-/finalhandler-2.1.1.tgz", + "integrity": "sha512-S8KoZgRZN+a5rNwqTxlZZePjT/4cnm0ROV70LedRHZ0p8u9fRID0hJUZQpkKLzro8LfmC8sx23bY6tVNxv8pQA==", + "license": "MIT", + "dependencies": { + "debug": "^4.4.0", + "encodeurl": "^2.0.0", + "escape-html": "^1.0.3", + "on-finished": "^2.4.1", + "parseurl": "^1.3.3", + "statuses": "^2.0.1" + }, + "engines": { + "node": ">= 18.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/find-up": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/find-up/-/find-up-5.0.0.tgz", + "integrity": "sha512-78/PXT1wlLLDgTzDs7sjq9hzz0vXD+zn+7wypEe4fXQxCmdmqfGsEPQxmiCSQI3ajFV91bVSsvNtrJRiW6nGng==", + "dev": true, + "license": "MIT", + "dependencies": { + "locate-path": "^6.0.0", + "path-exists": "^4.0.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/flat-cache": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/flat-cache/-/flat-cache-4.0.1.tgz", + "integrity": "sha512-f7ccFPK3SXFHpx15UIGyRJ/FJQctuKZ0zVuN3frBo4HnK3cay9VEW0R6yPYFHC0AgqhukPzKjq22t5DmAyqGyw==", + "dev": true, + "license": "MIT", + "dependencies": { + "flatted": "^3.2.9", + "keyv": "^4.5.4" + }, + "engines": { + "node": ">=16" + } + }, + "node_modules/flatted": { + "version": "3.4.2", + "resolved": "https://registry.npmjs.org/flatted/-/flatted-3.4.2.tgz", + "integrity": "sha512-PjDse7RzhcPkIJwy5t7KPWQSZ9cAbzQXcafsetQoD7sOJRQlGikNbx7yZp2OotDnJyrDcbyRq3Ttb18iYOqkxA==", + "dev": true, + "license": "ISC" + }, + "node_modules/for-each": { + "version": "0.3.5", + "resolved": "https://registry.npmjs.org/for-each/-/for-each-0.3.5.tgz", + "integrity": "sha512-dKx12eRCVIzqCxFGplyFKJMPvLEWgmNtUrpTiJIR5u97zEhRG8ySrtboPHZXx7daLxQVrl643cTzbab2tkQjxg==", + "dev": true, + "license": "MIT", + "dependencies": { + "is-callable": "^1.2.7" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/foreground-child": { + "version": "3.3.1", + "resolved": "https://registry.npmjs.org/foreground-child/-/foreground-child-3.3.1.tgz", + "integrity": "sha512-gIXjKqtFuWEgzFRJA9WCQeSJLZDjgJUOMCMzxtvFq/37KojM1BFGufqsCy0r4qSQmYLsZYMeyRqzIWOMup03sw==", + "devOptional": true, + "license": "ISC", + "dependencies": { + "cross-spawn": "^7.0.6", + "signal-exit": "^4.0.1" + }, + "engines": { + "node": ">=14" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/formdata-polyfill": { + "version": "4.0.10", + "resolved": "https://registry.npmjs.org/formdata-polyfill/-/formdata-polyfill-4.0.10.tgz", + "integrity": "sha512-buewHzMvYL29jdeQTVILecSaZKnt/RJWjoZCF5OW60Z67/GmSLBkOFM7qh1PI3zFNtJbaZL5eQu1vLfazOwj4g==", + "license": "MIT", + "dependencies": { + "fetch-blob": "^3.1.2" + }, + "engines": { + "node": ">=12.20.0" + } + }, + "node_modules/forwarded": { + "version": "0.2.0", + "resolved": "https://registry.npmjs.org/forwarded/-/forwarded-0.2.0.tgz", + "integrity": "sha512-buRG0fpBtRHSTCOASe6hD258tEubFoRLb4ZNA6NxMVHNw2gOcwHo9wyablzMzOA5z9xA9L1KNjk/Nt6MT9aYow==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/framer-motion": { + "version": "12.38.0", + "resolved": "https://registry.npmjs.org/framer-motion/-/framer-motion-12.38.0.tgz", + "integrity": "sha512-rFYkY/pigbcswl1XQSb7q424kSTQ8q6eAC+YUsSKooHQYuLdzdHjrt6uxUC+PRAO++q5IS7+TamgIw1AphxR+g==", + "license": "MIT", + "dependencies": { + "motion-dom": "^12.38.0", + "motion-utils": "^12.36.0", + "tslib": "^2.4.0" + }, + "peerDependencies": { + "@emotion/is-prop-valid": "*", + "react": "^18.0.0 || ^19.0.0", + "react-dom": "^18.0.0 || ^19.0.0" + }, + "peerDependenciesMeta": { + "@emotion/is-prop-valid": { + "optional": true + }, + "react": { + "optional": true + }, + "react-dom": { + "optional": true + } + } + }, + "node_modules/fresh": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/fresh/-/fresh-2.0.0.tgz", + "integrity": "sha512-Rx/WycZ60HOaqLKAi6cHRKKI7zxWbJ31MhntmtwMoaTeF7XFH9hhBp8vITaMidfljRQ6eYWCKkaTK+ykVJHP2A==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/fs-extra": { + "version": "11.3.4", + "resolved": "https://registry.npmjs.org/fs-extra/-/fs-extra-11.3.4.tgz", + "integrity": "sha512-CTXd6rk/M3/ULNQj8FBqBWHYBVYybQ3VPBw0xGKFe3tuH7ytT6ACnvzpIQ3UZtB8yvUKC2cXn1a+x+5EVQLovA==", + "license": "MIT", + "dependencies": { + "graceful-fs": "^4.2.0", + "jsonfile": "^6.0.1", + "universalify": "^2.0.0" + }, + "engines": { + "node": ">=14.14" + } + }, + "node_modules/fsevents": { + "version": "2.3.3", + "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.3.tgz", + "integrity": "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==", + "dev": true, + "hasInstallScript": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": "^8.16.0 || ^10.6.0 || >=11.0.0" + } + }, + "node_modules/function-bind": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.2.tgz", + "integrity": "sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA==", + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/function.prototype.name": { + "version": "1.1.8", + "resolved": "https://registry.npmjs.org/function.prototype.name/-/function.prototype.name-1.1.8.tgz", + "integrity": "sha512-e5iwyodOHhbMr/yNrc7fDYG4qlbIvI5gajyzPnb5TCwyhjApznQh1BMFou9b30SevY43gCJKXycoCBjMbsuW0Q==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bind": "^1.0.8", + "call-bound": "^1.0.3", + "define-properties": "^1.2.1", + "functions-have-names": "^1.2.3", + "hasown": "^2.0.2", + "is-callable": "^1.2.7" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/functions-have-names": { + "version": "1.2.3", + "resolved": "https://registry.npmjs.org/functions-have-names/-/functions-have-names-1.2.3.tgz", + "integrity": "sha512-xckBUXyTIqT97tq2x2AMb+g163b5JFysYk0x4qxNFwbfQkmNZoiRHb6sPzI9/QV33WeuvVYBUIiD4NzNIyqaRQ==", + "dev": true, + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/fuzzysort": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/fuzzysort/-/fuzzysort-3.1.0.tgz", + "integrity": "sha512-sR9BNCjBg6LNgwvxlBd0sBABvQitkLzoVY9MYYROQVX/FvfJ4Mai9LsGhDgd8qYdds0bY77VzYd5iuB+v5rwQQ==", + "license": "MIT" + }, + "node_modules/generate-function": { + "version": "2.3.1", + "resolved": "https://registry.npmjs.org/generate-function/-/generate-function-2.3.1.tgz", + "integrity": "sha512-eeB5GfMNeevm/GRYq20ShmsaGcmI81kIX2K9XQx5miC8KdHaC6Jm0qQ8ZNeGOi7wYB8OsdxKs+Y2oVuTFuVwKQ==", + "devOptional": true, + "license": "MIT", + "dependencies": { + "is-property": "^1.0.2" + } + }, + "node_modules/generator-function": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/generator-function/-/generator-function-2.0.1.tgz", + "integrity": "sha512-SFdFmIJi+ybC0vjlHN0ZGVGHc3lgE0DxPAT0djjVg+kjOnSqclqmj0KQ7ykTOLP6YxoqOvuAODGdcHJn+43q3g==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/gensync": { + "version": "1.0.0-beta.2", + "resolved": "https://registry.npmjs.org/gensync/-/gensync-1.0.0-beta.2.tgz", + "integrity": "sha512-3hN7NaskYvMDLQY55gnW3NQ+mesEAepTqlg+VEbj7zzqEMBVNhzcGYYeqFo/TlYz6eQiFcp1HcsCZO+nGgS8zg==", + "license": "MIT", + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/get-caller-file": { + "version": "2.0.5", + "resolved": "https://registry.npmjs.org/get-caller-file/-/get-caller-file-2.0.5.tgz", + "integrity": "sha512-DyFP3BM/3YHTQOCUL/w0OZHR0lpKeGrxotcHWcqNEdnltqFwXVfhEBQ94eIo34AfQpo0rGki4cyIiftY06h2Fg==", + "license": "ISC", + "engines": { + "node": "6.* || 8.* || >= 10.*" + } + }, + "node_modules/get-east-asian-width": { + "version": "1.5.0", + "resolved": "https://registry.npmjs.org/get-east-asian-width/-/get-east-asian-width-1.5.0.tgz", + "integrity": "sha512-CQ+bEO+Tva/qlmw24dCejulK5pMzVnUOFOijVogd3KQs07HnRIgp8TGipvCCRT06xeYEbpbgwaCxglFyiuIcmA==", + "license": "MIT", + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/get-intrinsic": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/get-intrinsic/-/get-intrinsic-1.3.0.tgz", + "integrity": "sha512-9fSjSaos/fRIVIp+xSJlE6lfwhES7LNtKaCBIamHsjr2na1BiABJPo0mOjjz8GJDURarmCPGqaiVg5mfjb98CQ==", + "license": "MIT", + "dependencies": { + "call-bind-apply-helpers": "^1.0.2", + "es-define-property": "^1.0.1", + "es-errors": "^1.3.0", + "es-object-atoms": "^1.1.1", + "function-bind": "^1.1.2", + "get-proto": "^1.0.1", + "gopd": "^1.2.0", + "has-symbols": "^1.1.0", + "hasown": "^2.0.2", + "math-intrinsics": "^1.1.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/get-own-enumerable-keys": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/get-own-enumerable-keys/-/get-own-enumerable-keys-1.0.0.tgz", + "integrity": "sha512-PKsK2FSrQCyxcGHsGrLDcK0lx+0Ke+6e8KFFozA9/fIQLhQzPaRvJFdcz7+Axg3jUH/Mq+NI4xa5u/UT2tQskA==", + "license": "MIT", + "engines": { + "node": ">=14.16" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/get-port-please": { + "version": "3.2.0", + "resolved": "https://registry.npmjs.org/get-port-please/-/get-port-please-3.2.0.tgz", + "integrity": "sha512-I9QVvBw5U/hw3RmWpYKRumUeaDgxTPd401x364rLmWBJcOQ753eov1eTgzDqRG9bqFIfDc7gfzcQEWrUri3o1A==", + "devOptional": true, + "license": "MIT" + }, + "node_modules/get-proto": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/get-proto/-/get-proto-1.0.1.tgz", + "integrity": "sha512-sTSfBjoXBp89JvIKIefqw7U2CCebsc74kiY6awiGogKtoSGbgjYE/G/+l9sF3MWFPNc9IcoOC4ODfKHfxFmp0g==", + "license": "MIT", + "dependencies": { + "dunder-proto": "^1.0.1", + "es-object-atoms": "^1.0.0" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/get-stream": { + "version": "9.0.1", + "resolved": "https://registry.npmjs.org/get-stream/-/get-stream-9.0.1.tgz", + "integrity": "sha512-kVCxPF3vQM/N0B1PmoqVUqgHP+EeVjmZSQn+1oCRPxd2P21P2F19lIgbR3HBosbB1PUhOAoctJnfEn2GbN2eZA==", + "license": "MIT", + "dependencies": { + "@sec-ant/readable-stream": "^0.4.1", + "is-stream": "^4.0.1" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/get-symbol-description": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/get-symbol-description/-/get-symbol-description-1.1.0.tgz", + "integrity": "sha512-w9UMqWwJxHNOvoNzSJ2oPF5wvYcvP7jUvYzhp67yEhTi17ZDBBC1z9pTdGuzjD+EFIqLSYRweZjqfiPzQ06Ebg==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bound": "^1.0.3", + "es-errors": "^1.3.0", + "get-intrinsic": "^1.2.6" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/get-tsconfig": { + "version": "4.13.6", + "resolved": "https://registry.npmjs.org/get-tsconfig/-/get-tsconfig-4.13.6.tgz", + "integrity": "sha512-shZT/QMiSHc/YBLxxOkMtgSid5HFoauqCE3/exfsEcwg1WkeqjG+V40yBbBrsD+jW2HDXcs28xOfcbm2jI8Ddw==", + "dev": true, + "license": "MIT", + "dependencies": { + "resolve-pkg-maps": "^1.0.0" + }, + "funding": { + "url": "https://github.com/privatenumber/get-tsconfig?sponsor=1" + } + }, + "node_modules/giget": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/giget/-/giget-2.0.0.tgz", + "integrity": "sha512-L5bGsVkxJbJgdnwyuheIunkGatUF/zssUoxxjACCseZYAVbaqdh9Tsmmlkl8vYan09H7sbvKt4pS8GqKLBrEzA==", + "devOptional": true, + "license": "MIT", + "dependencies": { + "citty": "^0.1.6", + "consola": "^3.4.0", + "defu": "^6.1.4", + "node-fetch-native": "^1.6.6", + "nypm": "^0.6.0", + "pathe": "^2.0.3" + }, + "bin": { + "giget": "dist/cli.mjs" + } + }, + "node_modules/glob": { + "version": "13.0.6", + "resolved": "https://registry.npmjs.org/glob/-/glob-13.0.6.tgz", + "integrity": "sha512-Wjlyrolmm8uDpm/ogGyXZXb1Z+Ca2B8NbJwqBVg0axK9GbBeoS7yGV6vjXnYdGm6X53iehEuxxbyiKp8QmN4Vw==", + "license": "BlueOak-1.0.0", + "dependencies": { + "minimatch": "^10.2.2", + "minipass": "^7.1.3", + "path-scurry": "^2.0.2" + }, + "engines": { + "node": "18 || 20 || >=22" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/glob-parent": { + "version": "6.0.2", + "resolved": "https://registry.npmjs.org/glob-parent/-/glob-parent-6.0.2.tgz", + "integrity": "sha512-XxwI8EOhVQgWp6iDL+3b0r86f4d6AX6zSU55HfB4ydCEuXLXc5FcYeOu+nnGftS4TEju/11rt4KJPTMgbfmv4A==", + "dev": true, + "license": "ISC", + "dependencies": { + "is-glob": "^4.0.3" + }, + "engines": { + "node": ">=10.13.0" + } + }, + "node_modules/glob/node_modules/balanced-match": { + "version": "4.0.4", + "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-4.0.4.tgz", + "integrity": "sha512-BLrgEcRTwX2o6gGxGOCNyMvGSp35YofuYzw9h1IMTRmKqttAZZVU67bdb9Pr2vUHA8+j3i2tJfjO6C6+4myGTA==", + "license": "MIT", + "engines": { + "node": "18 || 20 || >=22" + } + }, + "node_modules/glob/node_modules/brace-expansion": { + "version": "5.0.5", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-5.0.5.tgz", + "integrity": "sha512-VZznLgtwhn+Mact9tfiwx64fA9erHH/MCXEUfB/0bX/6Fz6ny5EGTXYltMocqg4xFAQZtnO3DHWWXi8RiuN7cQ==", + "license": "MIT", + "dependencies": { + "balanced-match": "^4.0.2" + }, + "engines": { + "node": "18 || 20 || >=22" + } + }, + "node_modules/glob/node_modules/minimatch": { + "version": "10.2.4", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-10.2.4.tgz", + "integrity": "sha512-oRjTw/97aTBN0RHbYCdtF1MQfvusSIBQM0IZEgzl6426+8jSC0nF1a/GmnVLpfB9yyr6g6FTqWqiZVbxrtaCIg==", + "license": "BlueOak-1.0.0", + "dependencies": { + "brace-expansion": "^5.0.2" + }, + "engines": { + "node": "18 || 20 || >=22" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/globals": { + "version": "14.0.0", + "resolved": "https://registry.npmjs.org/globals/-/globals-14.0.0.tgz", + "integrity": "sha512-oahGvuMGQlPw/ivIYBjVSrWAfWLBeku5tpPE2fOPLi+WHffIWbuh2tCjhyQhTBPMf5E9jDEH4FOmTYgYwbKwtQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/globalthis": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/globalthis/-/globalthis-1.0.4.tgz", + "integrity": "sha512-DpLKbNU4WylpxJykQujfCcwYWiV/Jhm50Goo0wrVILAv5jOr9d+H+UR3PhSCD2rCCEIg0uc+G+muBTwD54JhDQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "define-properties": "^1.2.1", + "gopd": "^1.0.1" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/gopd": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/gopd/-/gopd-1.2.0.tgz", + "integrity": "sha512-ZUKRh6/kUFoAiTAtTYPZJ3hw9wNxx+BIBOijnlG9PnrJsCcSjs1wyyD6vJpaYtgnzDrKYRSqf3OO6Rfa93xsRg==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/graceful-fs": { + "version": "4.2.11", + "resolved": "https://registry.npmjs.org/graceful-fs/-/graceful-fs-4.2.11.tgz", + "integrity": "sha512-RbJ5/jmFcNNCcDV5o9eTnBLJ/HszWV0P73bc+Ff4nS/rJj+YaS6IGyiOL0VoBYX+l1Wrl3k63h/KrH+nhJ0XvQ==", + "license": "ISC" + }, + "node_modules/grammex": { + "version": "3.1.12", + "resolved": "https://registry.npmjs.org/grammex/-/grammex-3.1.12.tgz", + "integrity": "sha512-6ufJOsSA7LcQehIJNCO7HIBykfM7DXQual0Ny780/DEcJIpBlHRvcqEBWGPYd7hrXL2GJ3oJI1MIhaXjWmLQOQ==", + "devOptional": true, + "license": "MIT" + }, + "node_modules/graphmatch": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/graphmatch/-/graphmatch-1.1.1.tgz", + "integrity": "sha512-5ykVn/EXM1hF0XCaWh05VbYvEiOL2lY1kBxZtaYsyvjp7cmWOU1XsAdfQBwClraEofXDT197lFbXOEVMHpvQOg==", + "devOptional": true, + "license": "MIT" + }, + "node_modules/graphql": { + "version": "16.13.1", + "resolved": "https://registry.npmjs.org/graphql/-/graphql-16.13.1.tgz", + "integrity": "sha512-gGgrVCoDKlIZ8fIqXBBb0pPKqDgki0Z/FSKNiQzSGj2uEYHr1tq5wmBegGwJx6QB5S5cM0khSBpi/JFHMCvsmQ==", + "license": "MIT", + "engines": { + "node": "^12.22.0 || ^14.16.0 || ^16.0.0 || >=17.0.0" + } + }, + "node_modules/has-bigints": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/has-bigints/-/has-bigints-1.1.0.tgz", + "integrity": "sha512-R3pbpkcIqv2Pm3dUwgjclDRVmWpTJW2DcMzcIhEXEx1oh/CEMObMm3KLmRJOdvhM7o4uQBnwr8pzRK2sJWIqfg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/has-flag": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-4.0.0.tgz", + "integrity": "sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/has-property-descriptors": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/has-property-descriptors/-/has-property-descriptors-1.0.2.tgz", + "integrity": "sha512-55JNKuIW+vq4Ke1BjOTjM2YctQIvCT7GFzHwmfZPGo5wnrgkid0YQtnAleFSqumZm4az3n2BS+erby5ipJdgrg==", + "dev": true, + "license": "MIT", + "dependencies": { + "es-define-property": "^1.0.0" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/has-proto": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/has-proto/-/has-proto-1.2.0.tgz", + "integrity": "sha512-KIL7eQPfHQRC8+XluaIw7BHUwwqL19bQn4hzNgdr+1wXoU0KKj6rufu47lhY7KbJR2C6T6+PfyN0Ea7wkSS+qQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "dunder-proto": "^1.0.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/has-symbols": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/has-symbols/-/has-symbols-1.1.0.tgz", + "integrity": "sha512-1cDNdwJ2Jaohmb3sg4OmKaMBwuC48sYni5HUw2DvsC8LjGTLK9h+eb1X6RyuOHe4hT0ULCW68iomhjUoKUqlPQ==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/has-tostringtag": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/has-tostringtag/-/has-tostringtag-1.0.2.tgz", + "integrity": "sha512-NqADB8VjPFLM2V0VvHUewwwsw0ZWBaIdgo+ieHtK3hasLz4qeCRjYcqfB6AQrBggRKppKF8L52/VqdVsO47Dlw==", + "dev": true, + "license": "MIT", + "dependencies": { + "has-symbols": "^1.0.3" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/hasown": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/hasown/-/hasown-2.0.2.tgz", + "integrity": "sha512-0hJU9SCPvmMzIBdZFqNPXWa6dqh7WdH0cII9y+CyS8rG3nL48Bclra9HmKhVVUHyPWNH5Y7xDwAB7bfgSjkUMQ==", + "license": "MIT", + "dependencies": { + "function-bind": "^1.1.2" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/headers-polyfill": { + "version": "4.0.3", + "resolved": "https://registry.npmjs.org/headers-polyfill/-/headers-polyfill-4.0.3.tgz", + "integrity": "sha512-IScLbePpkvO846sIwOtOTDjutRMWdXdJmXdMvk6gCBHxFO8d+QKOQedyZSxFTTFYRSmlgSTDtXqqq4pcenBXLQ==", + "license": "MIT" + }, + "node_modules/hermes-estree": { + "version": "0.25.1", + "resolved": "https://registry.npmjs.org/hermes-estree/-/hermes-estree-0.25.1.tgz", + "integrity": "sha512-0wUoCcLp+5Ev5pDW2OriHC2MJCbwLwuRx+gAqMTOkGKJJiBCLjtrvy4PWUGn6MIVefecRpzoOZ/UV6iGdOr+Cw==", + "dev": true, + "license": "MIT" + }, + "node_modules/hermes-parser": { + "version": "0.25.1", + "resolved": "https://registry.npmjs.org/hermes-parser/-/hermes-parser-0.25.1.tgz", + "integrity": "sha512-6pEjquH3rqaI6cYAXYPcz9MS4rY6R4ngRgrgfDshRptUZIc3lw0MCIJIGDj9++mfySOuPTHB4nrSW99BCvOPIA==", + "dev": true, + "license": "MIT", + "dependencies": { + "hermes-estree": "0.25.1" + } + }, + "node_modules/hono": { + "version": "4.12.10", + "resolved": "https://registry.npmjs.org/hono/-/hono-4.12.10.tgz", + "integrity": "sha512-mx/p18PLy5og9ufies2GOSUqep98Td9q4i/EF6X7yJgAiIopxqdfIO3jbqsi3jRgTgw88jMDEzVKi+V2EF+27w==", + "license": "MIT", + "engines": { + "node": ">=16.9.0" + } + }, + "node_modules/http-errors": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/http-errors/-/http-errors-2.0.1.tgz", + "integrity": "sha512-4FbRdAX+bSdmo4AUFuS0WNiPz8NgFt+r8ThgNWmlrjQjt1Q7ZR9+zTlce2859x4KSXrwIsaeTqDoKQmtP8pLmQ==", + "license": "MIT", + "dependencies": { + "depd": "~2.0.0", + "inherits": "~2.0.4", + "setprototypeof": "~1.2.0", + "statuses": "~2.0.2", + "toidentifier": "~1.0.1" + }, + "engines": { + "node": ">= 0.8" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/http-status-codes": { + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/http-status-codes/-/http-status-codes-2.3.0.tgz", + "integrity": "sha512-RJ8XvFvpPM/Dmc5SV+dC4y5PCeOhT3x1Hq0NU3rjGeg5a/CqlhZ7uudknPwZFz4aeAXDcbAyaeP7GAo9lvngtA==", + "devOptional": true, + "license": "MIT" + }, + "node_modules/https-proxy-agent": { + "version": "7.0.6", + "resolved": "https://registry.npmjs.org/https-proxy-agent/-/https-proxy-agent-7.0.6.tgz", + "integrity": "sha512-vK9P5/iUfdl95AI+JVyUuIcVtd4ofvtrOr3HNtM2yxC9bnMbEdp3x01OhQNnjb8IJYi38VlTE3mBXwcfvywuSw==", + "license": "MIT", + "dependencies": { + "agent-base": "^7.1.2", + "debug": "4" + }, + "engines": { + "node": ">= 14" + } + }, + "node_modules/human-signals": { + "version": "8.0.1", + "resolved": "https://registry.npmjs.org/human-signals/-/human-signals-8.0.1.tgz", + "integrity": "sha512-eKCa6bwnJhvxj14kZk5NCPc6Hb6BdsU9DZcOnmQKSnO1VKrfV0zCvtttPZUsBvjmNDn8rpcJfpwSYnHBjc95MQ==", + "license": "Apache-2.0", + "engines": { + "node": ">=18.18.0" + } + }, + "node_modules/iconv-lite": { + "version": "0.7.2", + "resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.7.2.tgz", + "integrity": "sha512-im9DjEDQ55s9fL4EYzOAv0yMqmMBSZp6G0VvFyTMPKWxiSBHUj9NW/qqLmXUwXrrM7AvqSlTCfvqRb0cM8yYqw==", + "license": "MIT", + "dependencies": { + "safer-buffer": ">= 2.1.2 < 3.0.0" + }, + "engines": { + "node": ">=0.10.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/ignore": { + "version": "5.3.2", + "resolved": "https://registry.npmjs.org/ignore/-/ignore-5.3.2.tgz", + "integrity": "sha512-hsBTNUqQTDwkWtcdYI2i06Y/nUBEsNEDJKjWdigLvegy8kDuJAS8uRlpkkcQpyEXL0Z/pjDy5HBmMjRCJ2gq+g==", + "license": "MIT", + "engines": { + "node": ">= 4" + } + }, + "node_modules/immer": { + "version": "10.2.0", + "resolved": "https://registry.npmjs.org/immer/-/immer-10.2.0.tgz", + "integrity": "sha512-d/+XTN3zfODyjr89gM3mPq1WNX2B8pYsu7eORitdwyA2sBubnTl3laYlBk4sXY5FUa5qTZGBDPJICVbvqzjlbw==", + "license": "MIT", + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/immer" + } + }, + "node_modules/import-fresh": { + "version": "3.3.1", + "resolved": "https://registry.npmjs.org/import-fresh/-/import-fresh-3.3.1.tgz", + "integrity": "sha512-TR3KfrTZTYLPB6jUjfx6MF9WcWrHL9su5TObK4ZkYgBdWKPOFoSoQIdEuTuR82pmtxH2spWG9h6etwfr1pLBqQ==", + "license": "MIT", + "dependencies": { + "parent-module": "^1.0.0", + "resolve-from": "^4.0.0" + }, + "engines": { + "node": ">=6" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/imurmurhash": { + "version": "0.1.4", + "resolved": "https://registry.npmjs.org/imurmurhash/-/imurmurhash-0.1.4.tgz", + "integrity": "sha512-JmXMZ6wuvDmLiHEml9ykzqO6lwFbof0GG4IkcGaENdCRDDmMVnny7s5HsIgHCbaq0w2MyPhDqkhTUgS2LU2PHA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.8.19" + } + }, + "node_modules/inherits": { + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz", + "integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==", + "license": "ISC" + }, + "node_modules/ini": { + "version": "4.1.3", + "resolved": "https://registry.npmjs.org/ini/-/ini-4.1.3.tgz", + "integrity": "sha512-X7rqawQBvfdjS10YU1y1YVreA3SsLrW9dX2CewP2EbBJM4ypVNLDkO5y04gejPwKIY9lR+7r9gn3rFPt/kmWFg==", + "license": "ISC", + "engines": { + "node": "^14.17.0 || ^16.13.0 || >=18.0.0" + } + }, + "node_modules/internal-slot": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/internal-slot/-/internal-slot-1.1.0.tgz", + "integrity": "sha512-4gd7VpWNQNB4UKKCFFVcp1AVv+FMOgs9NKzjHKusc8jTMhd5eL1NqQqOpE0KzMds804/yHlglp3uxgluOqAPLw==", + "dev": true, + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0", + "hasown": "^2.0.2", + "side-channel": "^1.1.0" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/internmap": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/internmap/-/internmap-2.0.3.tgz", + "integrity": "sha512-5Hh7Y1wQbvY5ooGgPbDaL5iYLAPzMTUrjMulskHLH6wnv/A+1q5rgEaiuqEjB+oxGXIVZs1FF+R/KPN3ZSQYYg==", + "license": "ISC", + "engines": { + "node": ">=12" + } + }, + "node_modules/ip-address": { + "version": "10.1.0", + "resolved": "https://registry.npmjs.org/ip-address/-/ip-address-10.1.0.tgz", + "integrity": "sha512-XXADHxXmvT9+CRxhXg56LJovE+bmWnEWB78LB83VZTprKTmaC5QfruXocxzTZ2Kl0DNwKuBdlIhjL8LeY8Sf8Q==", + "license": "MIT", + "engines": { + "node": ">= 12" + } + }, + "node_modules/ipaddr.js": { + "version": "1.9.1", + "resolved": "https://registry.npmjs.org/ipaddr.js/-/ipaddr.js-1.9.1.tgz", + "integrity": "sha512-0KI/607xoxSToH7GjN1FfSbLoU0+btTicjsQSWQlh/hZykN8KpmMf7uYwPW3R+akZ6R/w18ZlXSHBYXiYUPO3g==", + "license": "MIT", + "engines": { + "node": ">= 0.10" + } + }, + "node_modules/is-array-buffer": { + "version": "3.0.5", + "resolved": "https://registry.npmjs.org/is-array-buffer/-/is-array-buffer-3.0.5.tgz", + "integrity": "sha512-DDfANUiiG2wC1qawP66qlTugJeL5HyzMpfr8lLK+jMQirGzNod0B12cFB/9q838Ru27sBwfw78/rdoU7RERz6A==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bind": "^1.0.8", + "call-bound": "^1.0.3", + "get-intrinsic": "^1.2.6" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-arrayish": { + "version": "0.2.1", + "resolved": "https://registry.npmjs.org/is-arrayish/-/is-arrayish-0.2.1.tgz", + "integrity": "sha512-zz06S8t0ozoDXMG+ube26zeCTNXcKIPJZJi8hBrF4idCLms4CG9QtK7qBl1boi5ODzFpjswb5JPmHCbMpjaYzg==", + "license": "MIT" + }, + "node_modules/is-async-function": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/is-async-function/-/is-async-function-2.1.1.tgz", + "integrity": "sha512-9dgM/cZBnNvjzaMYHVoxxfPj2QXt22Ev7SuuPrs+xav0ukGB0S6d4ydZdEiM48kLx5kDV+QBPrpVnFyefL8kkQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "async-function": "^1.0.0", + "call-bound": "^1.0.3", + "get-proto": "^1.0.1", + "has-tostringtag": "^1.0.2", + "safe-regex-test": "^1.1.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-bigint": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/is-bigint/-/is-bigint-1.1.0.tgz", + "integrity": "sha512-n4ZT37wG78iz03xPRKJrHTdZbe3IicyucEtdRsV5yglwc3GyUfbAfpSeD0FJ41NbUNSt5wbhqfp1fS+BgnvDFQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "has-bigints": "^1.0.2" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-boolean-object": { + "version": "1.2.2", + "resolved": "https://registry.npmjs.org/is-boolean-object/-/is-boolean-object-1.2.2.tgz", + "integrity": "sha512-wa56o2/ElJMYqjCjGkXri7it5FbebW5usLw/nPmCMs5DeZ7eziSYZhSmPRn0txqeW4LnAmQQU7FgqLpsEFKM4A==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bound": "^1.0.3", + "has-tostringtag": "^1.0.2" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-bun-module": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/is-bun-module/-/is-bun-module-2.0.0.tgz", + "integrity": "sha512-gNCGbnnnnFAUGKeZ9PdbyeGYJqewpmc2aKHUEMO5nQPWU9lOmv7jcmQIv+qHD8fXW6W7qfuCwX4rY9LNRjXrkQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "semver": "^7.7.1" + } + }, + "node_modules/is-bun-module/node_modules/semver": { + "version": "7.7.4", + "resolved": "https://registry.npmjs.org/semver/-/semver-7.7.4.tgz", + "integrity": "sha512-vFKC2IEtQnVhpT78h1Yp8wzwrf8CM+MzKMHGJZfBtzhZNycRFnXsHk6E5TxIkkMsgNS7mdX3AGB7x2QM2di4lA==", + "dev": true, + "license": "ISC", + "bin": { + "semver": "bin/semver.js" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/is-callable": { + "version": "1.2.7", + "resolved": "https://registry.npmjs.org/is-callable/-/is-callable-1.2.7.tgz", + "integrity": "sha512-1BC0BVFhS/p0qtw6enp8e+8OD0UrK0oFLztSjNzhcKA3WDuJxxAPXzPuPtKkjEY9UUoEWlX/8fgKeu2S8i9JTA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-core-module": { + "version": "2.16.1", + "resolved": "https://registry.npmjs.org/is-core-module/-/is-core-module-2.16.1.tgz", + "integrity": "sha512-UfoeMA6fIJ8wTYFEUjelnaGI67v6+N7qXJEvQuIGa99l4xsCruSYOVSQ0uPANn4dAzm8lkYPaKLrrijLq7x23w==", + "dev": true, + "license": "MIT", + "dependencies": { + "hasown": "^2.0.2" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-data-view": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/is-data-view/-/is-data-view-1.0.2.tgz", + "integrity": "sha512-RKtWF8pGmS87i2D6gqQu/l7EYRlVdfzemCJN/P3UOs//x1QE7mfhvzHIApBTRf7axvT6DMGwSwBXYCT0nfB9xw==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bound": "^1.0.2", + "get-intrinsic": "^1.2.6", + "is-typed-array": "^1.1.13" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-date-object": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/is-date-object/-/is-date-object-1.1.0.tgz", + "integrity": "sha512-PwwhEakHVKTdRNVOw+/Gyh0+MzlCl4R6qKvkhuvLtPMggI1WAHt9sOwZxQLSGpUaDnrdyDsomoRgNnCfKNSXXg==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bound": "^1.0.2", + "has-tostringtag": "^1.0.2" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-docker": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/is-docker/-/is-docker-3.0.0.tgz", + "integrity": "sha512-eljcgEDlEns/7AXFosB5K/2nCM4P7FQPkGc/DWLy5rmFEWvZayGrik1d9/QIY5nJ4f9YsVvBkA6kJpHn9rISdQ==", + "license": "MIT", + "bin": { + "is-docker": "cli.js" + }, + "engines": { + "node": "^12.20.0 || ^14.13.1 || >=16.0.0" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/is-extglob": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/is-extglob/-/is-extglob-2.1.1.tgz", + "integrity": "sha512-SbKbANkN603Vi4jEZv49LeVJMn4yGwsbzZworEoyEiutsN3nJYdbO36zfhGJ6QEDpOZIFkDtnq5JRxmvl3jsoQ==", + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/is-finalizationregistry": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/is-finalizationregistry/-/is-finalizationregistry-1.1.1.tgz", + "integrity": "sha512-1pC6N8qWJbWoPtEjgcL2xyhQOP491EQjeUo3qTKcmV8YSDDJrOepfG8pcC7h/QgnQHYSv0mJ3Z/ZWxmatVrysg==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bound": "^1.0.3" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-fullwidth-code-point": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-3.0.0.tgz", + "integrity": "sha512-zymm5+u+sCsSWyD9qNaejV3DFvhCKclKdizYaJUuHA83RLjb7nSuGnddCHGv0hk+KY7BMAlsWeK4Ueg6EV6XQg==", + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/is-generator-function": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/is-generator-function/-/is-generator-function-1.1.2.tgz", + "integrity": "sha512-upqt1SkGkODW9tsGNG5mtXTXtECizwtS2kA161M+gJPc1xdb/Ax629af6YrTwcOeQHbewrPNlE5Dx7kzvXTizA==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bound": "^1.0.4", + "generator-function": "^2.0.0", + "get-proto": "^1.0.1", + "has-tostringtag": "^1.0.2", + "safe-regex-test": "^1.1.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-glob": { + "version": "4.0.3", + "resolved": "https://registry.npmjs.org/is-glob/-/is-glob-4.0.3.tgz", + "integrity": "sha512-xelSayHH36ZgE7ZWhli7pW34hNbNl8Ojv5KVmkJD4hBdD3th8Tfk9vYasLM+mXWOZhFkgZfxhLSnrwRr4elSSg==", + "license": "MIT", + "dependencies": { + "is-extglob": "^2.1.1" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/is-in-ssh": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/is-in-ssh/-/is-in-ssh-1.0.0.tgz", + "integrity": "sha512-jYa6Q9rH90kR1vKB6NM7qqd1mge3Fx4Dhw5TVlK1MUBqhEOuCagrEHMevNuCcbECmXZ0ThXkRm+Ymr51HwEPAw==", + "license": "MIT", + "engines": { + "node": ">=20" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/is-inside-container": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/is-inside-container/-/is-inside-container-1.0.0.tgz", + "integrity": "sha512-KIYLCCJghfHZxqjYBE7rEy0OBuTd5xCHS7tHVgvCLkx7StIoaxwNW3hCALgEUjFfeRk+MG/Qxmp/vtETEF3tRA==", + "license": "MIT", + "dependencies": { + "is-docker": "^3.0.0" + }, + "bin": { + "is-inside-container": "cli.js" + }, + "engines": { + "node": ">=14.16" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/is-interactive": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/is-interactive/-/is-interactive-2.0.0.tgz", + "integrity": "sha512-qP1vozQRI+BMOPcjFzrjXuQvdak2pHNUMZoeG2eRbiSqyvbEf/wQtEOTOX1guk6E3t36RkaqiSt8A/6YElNxLQ==", + "license": "MIT", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/is-map": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/is-map/-/is-map-2.0.3.tgz", + "integrity": "sha512-1Qed0/Hr2m+YqxnM09CjA2d/i6YZNfF6R2oRAOj36eUdS6qIV/huPJNSEpKbupewFs+ZsJlxsjjPbc0/afW6Lw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-negative-zero": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/is-negative-zero/-/is-negative-zero-2.0.3.tgz", + "integrity": "sha512-5KoIu2Ngpyek75jXodFvnafB6DJgr3u8uuK0LEZJjrU19DrMD3EVERaR8sjz8CCGgpZvxPl9SuE1GMVPFHx1mw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-node-process": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/is-node-process/-/is-node-process-1.2.0.tgz", + "integrity": "sha512-Vg4o6/fqPxIjtxgUH5QLJhwZ7gW5diGCVlXpuUfELC62CuxM1iHcRe51f2W1FDy04Ai4KJkagKjx3XaqyfRKXw==", + "license": "MIT" + }, + "node_modules/is-number": { + "version": "7.0.0", + "resolved": "https://registry.npmjs.org/is-number/-/is-number-7.0.0.tgz", + "integrity": "sha512-41Cifkg6e8TylSpdtTpeLVMqvSBEVzTttHvERD741+pnZ8ANv0004MRL43QKPDlK9cGvNp6NZWZUBlbGXYxxng==", + "license": "MIT", + "engines": { + "node": ">=0.12.0" + } + }, + "node_modules/is-number-object": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/is-number-object/-/is-number-object-1.1.1.tgz", + "integrity": "sha512-lZhclumE1G6VYD8VHe35wFaIif+CTy5SJIi5+3y4psDgWu4wPDoBhF8NxUOinEc7pHgiTsT6MaBb92rKhhD+Xw==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bound": "^1.0.3", + "has-tostringtag": "^1.0.2" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-obj": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/is-obj/-/is-obj-3.0.0.tgz", + "integrity": "sha512-IlsXEHOjtKhpN8r/tRFj2nDyTmHvcfNeu/nrRIcXE17ROeatXchkojffa1SpdqW4cr/Fj6QkEf/Gn4zf6KKvEQ==", + "license": "MIT", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/is-plain-obj": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/is-plain-obj/-/is-plain-obj-4.1.0.tgz", + "integrity": "sha512-+Pgi+vMuUNkJyExiMBt5IlFoMyKnr5zhJ4Uspz58WOhBF5QoIZkFyNHIbBAtHwzVAgk5RtndVNsDRN61/mmDqg==", + "license": "MIT", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/is-promise": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/is-promise/-/is-promise-4.0.0.tgz", + "integrity": "sha512-hvpoI6korhJMnej285dSg6nu1+e6uxs7zG3BYAm5byqDsgJNWwxzM6z6iZiAgQR4TJ30JmBTOwqZUw3WlyH3AQ==", + "license": "MIT" + }, + "node_modules/is-property": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/is-property/-/is-property-1.0.2.tgz", + "integrity": "sha512-Ks/IoX00TtClbGQr4TWXemAnktAQvYB7HzcCxDGqEZU6oCmb2INHuOoKxbtR+HFkmYWBKv/dOZtGRiAjDhj92g==", + "devOptional": true, + "license": "MIT" + }, + "node_modules/is-regex": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/is-regex/-/is-regex-1.2.1.tgz", + "integrity": "sha512-MjYsKHO5O7mCsmRGxWcLWheFqN9DJ/2TmngvjKXihe6efViPqc274+Fx/4fYj/r03+ESvBdTXK0V6tA3rgez1g==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bound": "^1.0.2", + "gopd": "^1.2.0", + "has-tostringtag": "^1.0.2", + "hasown": "^2.0.2" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-regexp": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/is-regexp/-/is-regexp-3.1.0.tgz", + "integrity": "sha512-rbku49cWloU5bSMI+zaRaXdQHXnthP6DZ/vLnfdSKyL4zUzuWnomtOEiZZOd+ioQ+avFo/qau3KPTc7Fjy1uPA==", + "license": "MIT", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/is-set": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/is-set/-/is-set-2.0.3.tgz", + "integrity": "sha512-iPAjerrse27/ygGLxw+EBR9agv9Y6uLeYVJMu+QNCoouJ1/1ri0mGrcWpfCqFZuzzx3WjtwxG098X+n4OuRkPg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-shared-array-buffer": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/is-shared-array-buffer/-/is-shared-array-buffer-1.0.4.tgz", + "integrity": "sha512-ISWac8drv4ZGfwKl5slpHG9OwPNty4jOWPRIhBpxOoD+hqITiwuipOQ2bNthAzwA3B4fIjO4Nln74N0S9byq8A==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bound": "^1.0.3" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-stream": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/is-stream/-/is-stream-4.0.1.tgz", + "integrity": "sha512-Dnz92NInDqYckGEUJv689RbRiTSEHCQ7wOVeALbkOz999YpqT46yMRIGtSNl2iCL1waAZSx40+h59NV/EwzV/A==", + "license": "MIT", + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/is-string": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/is-string/-/is-string-1.1.1.tgz", + "integrity": "sha512-BtEeSsoaQjlSPBemMQIrY1MY0uM6vnS1g5fmufYOtnxLGUZM2178PKbhsk7Ffv58IX+ZtcvoGwccYsh0PglkAA==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bound": "^1.0.3", + "has-tostringtag": "^1.0.2" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-symbol": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/is-symbol/-/is-symbol-1.1.1.tgz", + "integrity": "sha512-9gGx6GTtCQM73BgmHQXfDmLtfjjTUDSyoxTCbp5WtoixAhfgsDirWIcVQ/IHpvI5Vgd5i/J5F7B9cN/WlVbC/w==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bound": "^1.0.2", + "has-symbols": "^1.1.0", + "safe-regex-test": "^1.1.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-typed-array": { + "version": "1.1.15", + "resolved": "https://registry.npmjs.org/is-typed-array/-/is-typed-array-1.1.15.tgz", + "integrity": "sha512-p3EcsicXjit7SaskXHs1hA91QxgTw46Fv6EFKKGS5DRFLD8yKnohjF3hxoju94b/OcMZoQukzpPpBE9uLVKzgQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "which-typed-array": "^1.1.16" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-unicode-supported": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/is-unicode-supported/-/is-unicode-supported-2.1.0.tgz", + "integrity": "sha512-mE00Gnza5EEB3Ds0HfMyllZzbBrmLOX3vfWoj9A9PEnTfratQ/BcaJOuMhnkhjXvb2+FkY3VuHqtAGpTPmglFQ==", + "license": "MIT", + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/is-weakmap": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/is-weakmap/-/is-weakmap-2.0.2.tgz", + "integrity": "sha512-K5pXYOm9wqY1RgjpL3YTkF39tni1XajUIkawTLUo9EZEVUFga5gSQJF8nNS7ZwJQ02y+1YCNYcMh+HIf1ZqE+w==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-weakref": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/is-weakref/-/is-weakref-1.1.1.tgz", + "integrity": "sha512-6i9mGWSlqzNMEqpCp93KwRS1uUOodk2OJ6b+sq7ZPDSy2WuI5NFIxp/254TytR8ftefexkWn5xNiHUNpPOfSew==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bound": "^1.0.3" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-weakset": { + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/is-weakset/-/is-weakset-2.0.4.tgz", + "integrity": "sha512-mfcwb6IzQyOKTs84CQMrOwW4gQcaTOAWJ0zzJCl2WSPDrWk/OzDaImWFH3djXhb24g4eudZfLRozAvPGw4d9hQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bound": "^1.0.3", + "get-intrinsic": "^1.2.6" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-wsl": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/is-wsl/-/is-wsl-3.1.1.tgz", + "integrity": "sha512-e6rvdUCiQCAuumZslxRJWR/Doq4VpPR82kqclvcS0efgt430SlGIk05vdCN58+VrzgtIcfNODjozVielycD4Sw==", + "license": "MIT", + "dependencies": { + "is-inside-container": "^1.0.0" + }, + "engines": { + "node": ">=16" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/isarray": { + "version": "2.0.5", + "resolved": "https://registry.npmjs.org/isarray/-/isarray-2.0.5.tgz", + "integrity": "sha512-xHjhDr3cNBK0BzdUJSPXZntQUx/mwMS5Rw4A7lPJ90XGAO6ISP/ePDNuo0vhqOZU+UD5JoodwCAAoZQd3FeAKw==", + "dev": true, + "license": "MIT" + }, + "node_modules/isexe": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/isexe/-/isexe-2.0.0.tgz", + "integrity": "sha512-RHxMLp9lnKHGHRng9QFhRCMbYAcVpn69smSGcq3f36xjgVVWThj4qqLbTLlq7Ssj8B+fIQ1EuCEGI2lKsyQeIw==", + "license": "ISC" + }, + "node_modules/iterator.prototype": { + "version": "1.1.5", + "resolved": "https://registry.npmjs.org/iterator.prototype/-/iterator.prototype-1.1.5.tgz", + "integrity": "sha512-H0dkQoCa3b2VEeKQBOxFph+JAbcrQdE7KC0UkqwpLmv2EC4P41QXP+rqo9wYodACiG5/WM5s9oDApTU8utwj9g==", + "dev": true, + "license": "MIT", + "dependencies": { + "define-data-property": "^1.1.4", + "es-object-atoms": "^1.0.0", + "get-intrinsic": "^1.2.6", + "get-proto": "^1.0.0", + "has-symbols": "^1.1.0", + "set-function-name": "^2.0.2" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/jiti": { + "version": "2.6.1", + "resolved": "https://registry.npmjs.org/jiti/-/jiti-2.6.1.tgz", + "integrity": "sha512-ekilCSN1jwRvIbgeg/57YFh8qQDNbwDb9xT/qu2DAHbFFZUicIl4ygVaAvzveMhMVr3LnpSKTNnwt8PoOfmKhQ==", + "devOptional": true, + "license": "MIT", + "bin": { + "jiti": "lib/jiti-cli.mjs" + } + }, + "node_modules/jose": { + "version": "6.2.1", + "resolved": "https://registry.npmjs.org/jose/-/jose-6.2.1.tgz", + "integrity": "sha512-jUaKr1yrbfaImV7R2TN/b3IcZzsw38/chqMpo2XJ7i2F8AfM/lA4G1goC3JVEwg0H7UldTmSt3P68nt31W7/mw==", + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/panva" + } + }, + "node_modules/js-base64": { + "version": "3.7.8", + "resolved": "https://registry.npmjs.org/js-base64/-/js-base64-3.7.8.tgz", + "integrity": "sha512-hNngCeKxIUQiEUN3GPJOkz4wF/YvdUdbNL9hsBcMQTkKzboD7T/q3OYOuuPZLUE6dBxSGpwhk5mwuDud7JVAow==", + "license": "BSD-3-Clause" + }, + "node_modules/js-tokens": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-4.0.0.tgz", + "integrity": "sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ==", + "license": "MIT" + }, + "node_modules/js-yaml": { + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-4.1.1.tgz", + "integrity": "sha512-qQKT4zQxXl8lLwBtHMWwaTcGfFOZviOJet3Oy/xmGk2gZH677CJM9EvtfdSkgWcATZhj/55JZ0rmy3myCT5lsA==", + "license": "MIT", + "dependencies": { + "argparse": "^2.0.1" + }, + "bin": { + "js-yaml": "bin/js-yaml.js" + } + }, + "node_modules/jsesc": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/jsesc/-/jsesc-3.1.0.tgz", + "integrity": "sha512-/sM3dO2FOzXjKQhJuo0Q173wf2KOo8t4I8vHy6lF9poUp7bKT0/NHE8fPX23PwfhnykfqnC2xRxOnVw5XuGIaA==", + "license": "MIT", + "bin": { + "jsesc": "bin/jsesc" + }, + "engines": { + "node": ">=6" + } + }, + "node_modules/json-buffer": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/json-buffer/-/json-buffer-3.0.1.tgz", + "integrity": "sha512-4bV5BfR2mqfQTJm+V5tPPdf+ZpuhiIvTuAB5g8kcrXOZpTT/QwwVRWBywX1ozr6lEuPdbHxwaJlm9G6mI2sfSQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/json-parse-even-better-errors": { + "version": "2.3.1", + "resolved": "https://registry.npmjs.org/json-parse-even-better-errors/-/json-parse-even-better-errors-2.3.1.tgz", + "integrity": "sha512-xyFwyhro/JEof6Ghe2iz2NcXoj2sloNsWr/XsERDK/oiPCfaNhl5ONfp+jQdAZRQQ0IJWNzH9zIZF7li91kh2w==", + "license": "MIT" + }, + "node_modules/json-schema-to-ts": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/json-schema-to-ts/-/json-schema-to-ts-3.1.1.tgz", + "integrity": "sha512-+DWg8jCJG2TEnpy7kOm/7/AxaYoaRbjVB4LFZLySZlWn8exGs3A4OLJR966cVvU26N7X9TWxl+Jsw7dzAqKT6g==", + "license": "MIT", + "dependencies": { + "@babel/runtime": "^7.18.3", + "ts-algebra": "^2.0.0" + }, + "engines": { + "node": ">=16" + } + }, + "node_modules/json-schema-traverse": { + "version": "0.4.1", + "resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-0.4.1.tgz", + "integrity": "sha512-xbbCH5dCYU5T8LcEhhuh7HJ88HXuW3qsI3Y0zOZFKfZEHcpWiHU/Jxzk629Brsab/mMiHQti9wMP+845RPe3Vg==", + "dev": true, + "license": "MIT" + }, + "node_modules/json-schema-typed": { + "version": "8.0.2", + "resolved": "https://registry.npmjs.org/json-schema-typed/-/json-schema-typed-8.0.2.tgz", + "integrity": "sha512-fQhoXdcvc3V28x7C7BMs4P5+kNlgUURe2jmUT1T//oBRMDrqy1QPelJimwZGo7Hg9VPV3EQV5Bnq4hbFy2vetA==", + "license": "BSD-2-Clause" + }, + "node_modules/json-stable-stringify-without-jsonify": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/json-stable-stringify-without-jsonify/-/json-stable-stringify-without-jsonify-1.0.1.tgz", + "integrity": "sha512-Bdboy+l7tA3OGW6FjyFHWkP5LuByj1Tk33Ljyq0axyzdk9//JSi2u3fP1QSmd1KNwq6VOKYGlAu87CisVir6Pw==", + "dev": true, + "license": "MIT" + }, + "node_modules/json5": { + "version": "2.2.3", + "resolved": "https://registry.npmjs.org/json5/-/json5-2.2.3.tgz", + "integrity": "sha512-XmOWe7eyHYH14cLdVPoyg+GOH3rYX++KpzrylJwSW98t3Nk+U8XOl8FWKOgwtzdb8lXGf6zYwDUzeHMWfxasyg==", + "license": "MIT", + "bin": { + "json5": "lib/cli.js" + }, + "engines": { + "node": ">=6" + } + }, + "node_modules/jsonfile": { + "version": "6.2.0", + "resolved": "https://registry.npmjs.org/jsonfile/-/jsonfile-6.2.0.tgz", + "integrity": "sha512-FGuPw30AdOIUTRMC2OMRtQV+jkVj2cfPqSeWXv1NEAJ1qZ5zb1X6z1mFhbfOB/iy3ssJCD+3KuZ8r8C3uVFlAg==", + "license": "MIT", + "dependencies": { + "universalify": "^2.0.0" + }, + "optionalDependencies": { + "graceful-fs": "^4.1.6" + } + }, + "node_modules/jsx-ast-utils": { + "version": "3.3.5", + "resolved": "https://registry.npmjs.org/jsx-ast-utils/-/jsx-ast-utils-3.3.5.tgz", + "integrity": "sha512-ZZow9HBI5O6EPgSJLUb8n2NKgmVWTwCvHGwFuJlMjvLFqlGG6pjirPhtdsseaLZjSibD8eegzmYpUZwoIlj2cQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "array-includes": "^3.1.6", + "array.prototype.flat": "^1.3.1", + "object.assign": "^4.1.4", + "object.values": "^1.1.6" + }, + "engines": { + "node": ">=4.0" + } + }, + "node_modules/keyv": { + "version": "4.5.4", + "resolved": "https://registry.npmjs.org/keyv/-/keyv-4.5.4.tgz", + "integrity": "sha512-oxVHkHR/EJf2CNXnWxRLW6mg7JyCCUcG0DtEGmL2ctUo1PNTin1PUil+r/+4r5MpVgC/fn1kjsx7mjSujKqIpw==", + "dev": true, + "license": "MIT", + "dependencies": { + "json-buffer": "3.0.1" + } + }, + "node_modules/kleur": { + "version": "4.1.5", + "resolved": "https://registry.npmjs.org/kleur/-/kleur-4.1.5.tgz", + "integrity": "sha512-o+NO+8WrRiQEE4/7nwRJhN1HWpVmJm511pBHUxPLtp0BUISzlBplORYSmTclCnJvQq2tKu/sgl3xVpkc7ZWuQQ==", + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/langsmith": { + "version": "0.5.15", + "resolved": "https://registry.npmjs.org/langsmith/-/langsmith-0.5.15.tgz", + "integrity": "sha512-S20JnYmIgqGBjA/WEn12ZZJjqd03O5wd8K9KgGBvsKXQBn0bYuFrr1w20L37PpcMmX3/cftpgJ6g2y8KoEmHLw==", + "license": "MIT", + "dependencies": { + "@types/uuid": "^10.0.0", + "chalk": "^5.6.2", + "console-table-printer": "^2.12.1", + "p-queue": "^6.6.2", + "semver": "^7.6.3", + "uuid": "^10.0.0" + }, + "peerDependencies": { + "@opentelemetry/api": "*", + "@opentelemetry/exporter-trace-otlp-proto": "*", + "@opentelemetry/sdk-trace-base": "*", + "openai": "*", + "ws": ">=7" + }, + "peerDependenciesMeta": { + "@opentelemetry/api": { + "optional": true + }, + "@opentelemetry/exporter-trace-otlp-proto": { + "optional": true + }, + "@opentelemetry/sdk-trace-base": { + "optional": true + }, + "openai": { + "optional": true + }, + "ws": { + "optional": true + } + } + }, + "node_modules/langsmith/node_modules/chalk": { + "version": "5.6.2", + "resolved": "https://registry.npmjs.org/chalk/-/chalk-5.6.2.tgz", + "integrity": "sha512-7NzBL0rN6fMUW+f7A6Io4h40qQlG+xGmtMxfbnH/K7TAtt8JQWVQK+6g0UXKMeVJoyV5EkkNsErQ8pVD3bLHbA==", + "license": "MIT", + "engines": { + "node": "^12.17.0 || ^14.13 || >=16.0.0" + }, + "funding": { + "url": "https://github.com/chalk/chalk?sponsor=1" + } + }, + "node_modules/langsmith/node_modules/semver": { + "version": "7.7.4", + "resolved": "https://registry.npmjs.org/semver/-/semver-7.7.4.tgz", + "integrity": "sha512-vFKC2IEtQnVhpT78h1Yp8wzwrf8CM+MzKMHGJZfBtzhZNycRFnXsHk6E5TxIkkMsgNS7mdX3AGB7x2QM2di4lA==", + "license": "ISC", + "bin": { + "semver": "bin/semver.js" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/language-subtag-registry": { + "version": "0.3.23", + "resolved": "https://registry.npmjs.org/language-subtag-registry/-/language-subtag-registry-0.3.23.tgz", + "integrity": "sha512-0K65Lea881pHotoGEa5gDlMxt3pctLi2RplBb7Ezh4rRdLEOtgi7n4EwK9lamnUCkKBqaeKRVebTq6BAxSkpXQ==", + "dev": true, + "license": "CC0-1.0" + }, + "node_modules/language-tags": { + "version": "1.0.9", + "resolved": "https://registry.npmjs.org/language-tags/-/language-tags-1.0.9.tgz", + "integrity": "sha512-MbjN408fEndfiQXbFQ1vnd+1NoLDsnQW41410oQBXiyXDMYH5z505juWa4KUE1LqxRC7DgOgZDbKLxHIwm27hA==", + "dev": true, + "license": "MIT", + "dependencies": { + "language-subtag-registry": "^0.3.20" + }, + "engines": { + "node": ">=0.10" + } + }, + "node_modules/levn": { + "version": "0.4.1", + "resolved": "https://registry.npmjs.org/levn/-/levn-0.4.1.tgz", + "integrity": "sha512-+bT2uH4E5LGE7h/n3evcS/sQlJXCpIp6ym8OWJ5eV6+67Dsql/LaaT7qJBAt2rzfoa/5QBGBhxDix1dMt2kQKQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "prelude-ls": "^1.2.1", + "type-check": "~0.4.0" + }, + "engines": { + "node": ">= 0.8.0" + } + }, + "node_modules/libsql": { + "version": "0.5.22", + "resolved": "https://registry.npmjs.org/libsql/-/libsql-0.5.22.tgz", + "integrity": "sha512-NscWthMQt7fpU8lqd7LXMvT9pi+KhhmTHAJWUB/Lj6MWa0MKFv0F2V4C6WKKpjCVZl0VwcDz4nOI3CyaT1DDiA==", + "cpu": [ + "x64", + "arm64", + "wasm32", + "arm" + ], + "license": "MIT", + "os": [ + "darwin", + "linux", + "win32" + ], + "dependencies": { + "@neon-rs/load": "^0.0.4", + "detect-libc": "2.0.2" + }, + "optionalDependencies": { + "@libsql/darwin-arm64": "0.5.22", + "@libsql/darwin-x64": "0.5.22", + "@libsql/linux-arm-gnueabihf": "0.5.22", + "@libsql/linux-arm-musleabihf": "0.5.22", + "@libsql/linux-arm64-gnu": "0.5.22", + "@libsql/linux-arm64-musl": "0.5.22", + "@libsql/linux-x64-gnu": "0.5.22", + "@libsql/linux-x64-musl": "0.5.22", + "@libsql/win32-x64-msvc": "0.5.22" + } + }, + "node_modules/libsql/node_modules/detect-libc": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/detect-libc/-/detect-libc-2.0.2.tgz", + "integrity": "sha512-UX6sGumvvqSaXgdKGUsgZWqcUyIXZ/vZTrlRT/iobiKhGL0zL4d3osHj3uqllWJK+i+sixDS/3COVEOFbupFyw==", + "license": "Apache-2.0", + "engines": { + "node": ">=8" + } + }, + "node_modules/lightningcss": { + "version": "1.31.1", + "resolved": "https://registry.npmjs.org/lightningcss/-/lightningcss-1.31.1.tgz", + "integrity": "sha512-l51N2r93WmGUye3WuFoN5k10zyvrVs0qfKBhyC5ogUQ6Ew6JUSswh78mbSO+IU3nTWsyOArqPCcShdQSadghBQ==", + "dev": true, + "license": "MPL-2.0", + "dependencies": { + "detect-libc": "^2.0.3" + }, + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + }, + "optionalDependencies": { + "lightningcss-android-arm64": "1.31.1", + "lightningcss-darwin-arm64": "1.31.1", + "lightningcss-darwin-x64": "1.31.1", + "lightningcss-freebsd-x64": "1.31.1", + "lightningcss-linux-arm-gnueabihf": "1.31.1", + "lightningcss-linux-arm64-gnu": "1.31.1", + "lightningcss-linux-arm64-musl": "1.31.1", + "lightningcss-linux-x64-gnu": "1.31.1", + "lightningcss-linux-x64-musl": "1.31.1", + "lightningcss-win32-arm64-msvc": "1.31.1", + "lightningcss-win32-x64-msvc": "1.31.1" + } + }, + "node_modules/lightningcss-android-arm64": { + "version": "1.31.1", + "resolved": "https://registry.npmjs.org/lightningcss-android-arm64/-/lightningcss-android-arm64-1.31.1.tgz", + "integrity": "sha512-HXJF3x8w9nQ4jbXRiNppBCqeZPIAfUo8zE/kOEGbW5NZvGc/K7nMxbhIr+YlFlHW5mpbg/YFPdbnCh1wAXCKFg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-darwin-arm64": { + "version": "1.31.1", + "resolved": "https://registry.npmjs.org/lightningcss-darwin-arm64/-/lightningcss-darwin-arm64-1.31.1.tgz", + "integrity": "sha512-02uTEqf3vIfNMq3h/z2cJfcOXnQ0GRwQrkmPafhueLb2h7mqEidiCzkE4gBMEH65abHRiQvhdcQ+aP0D0g67sg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-darwin-x64": { + "version": "1.31.1", + "resolved": "https://registry.npmjs.org/lightningcss-darwin-x64/-/lightningcss-darwin-x64-1.31.1.tgz", + "integrity": "sha512-1ObhyoCY+tGxtsz1lSx5NXCj3nirk0Y0kB/g8B8DT+sSx4G9djitg9ejFnjb3gJNWo7qXH4DIy2SUHvpoFwfTA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-freebsd-x64": { + "version": "1.31.1", + "resolved": "https://registry.npmjs.org/lightningcss-freebsd-x64/-/lightningcss-freebsd-x64-1.31.1.tgz", + "integrity": "sha512-1RINmQKAItO6ISxYgPwszQE1BrsVU5aB45ho6O42mu96UiZBxEXsuQ7cJW4zs4CEodPUioj/QrXW1r9pLUM74A==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-linux-arm-gnueabihf": { + "version": "1.31.1", + "resolved": "https://registry.npmjs.org/lightningcss-linux-arm-gnueabihf/-/lightningcss-linux-arm-gnueabihf-1.31.1.tgz", + "integrity": "sha512-OOCm2//MZJ87CdDK62rZIu+aw9gBv4azMJuA8/KB74wmfS3lnC4yoPHm0uXZ/dvNNHmnZnB8XLAZzObeG0nS1g==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-linux-arm64-gnu": { + "version": "1.31.1", + "resolved": "https://registry.npmjs.org/lightningcss-linux-arm64-gnu/-/lightningcss-linux-arm64-gnu-1.31.1.tgz", + "integrity": "sha512-WKyLWztD71rTnou4xAD5kQT+982wvca7E6QoLpoawZ1gP9JM0GJj4Tp5jMUh9B3AitHbRZ2/H3W5xQmdEOUlLg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-linux-arm64-musl": { + "version": "1.31.1", + "resolved": "https://registry.npmjs.org/lightningcss-linux-arm64-musl/-/lightningcss-linux-arm64-musl-1.31.1.tgz", + "integrity": "sha512-mVZ7Pg2zIbe3XlNbZJdjs86YViQFoJSpc41CbVmKBPiGmC4YrfeOyz65ms2qpAobVd7WQsbW4PdsSJEMymyIMg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-linux-x64-gnu": { + "version": "1.31.1", + "resolved": "https://registry.npmjs.org/lightningcss-linux-x64-gnu/-/lightningcss-linux-x64-gnu-1.31.1.tgz", + "integrity": "sha512-xGlFWRMl+0KvUhgySdIaReQdB4FNudfUTARn7q0hh/V67PVGCs3ADFjw+6++kG1RNd0zdGRlEKa+T13/tQjPMA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-linux-x64-musl": { + "version": "1.31.1", + "resolved": "https://registry.npmjs.org/lightningcss-linux-x64-musl/-/lightningcss-linux-x64-musl-1.31.1.tgz", + "integrity": "sha512-eowF8PrKHw9LpoZii5tdZwnBcYDxRw2rRCyvAXLi34iyeYfqCQNA9rmUM0ce62NlPhCvof1+9ivRaTY6pSKDaA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-win32-arm64-msvc": { + "version": "1.31.1", + "resolved": "https://registry.npmjs.org/lightningcss-win32-arm64-msvc/-/lightningcss-win32-arm64-msvc-1.31.1.tgz", + "integrity": "sha512-aJReEbSEQzx1uBlQizAOBSjcmr9dCdL3XuC/6HLXAxmtErsj2ICo5yYggg1qOODQMtnjNQv2UHb9NpOuFtYe4w==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-win32-x64-msvc": { + "version": "1.31.1", + "resolved": "https://registry.npmjs.org/lightningcss-win32-x64-msvc/-/lightningcss-win32-x64-msvc-1.31.1.tgz", + "integrity": "sha512-I9aiFrbd7oYHwlnQDqr1Roz+fTz61oDDJX7n9tYF9FJymH1cIN1DtKw3iYt6b8WZgEjoNwVSncwF4wx/ZedMhw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lines-and-columns": { + "version": "1.2.4", + "resolved": "https://registry.npmjs.org/lines-and-columns/-/lines-and-columns-1.2.4.tgz", + "integrity": "sha512-7ylylesZQ/PV29jhEDl3Ufjo6ZX7gCqJr5F7PKrqc93v7fzSymt1BpwEU8nAUXs8qzzvqhbjhK5QZg6Mt/HkBg==", + "license": "MIT" + }, + "node_modules/locate-path": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/locate-path/-/locate-path-6.0.0.tgz", + "integrity": "sha512-iPZK6eYjbxRu3uB4/WZ3EsEIMJFMqAoopl3R+zuq0UjcAm/MO6KCweDgPfP3elTztoKP3KtnVHxTn2NHBSDVUw==", + "dev": true, + "license": "MIT", + "dependencies": { + "p-locate": "^5.0.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/lodash.merge": { + "version": "4.6.2", + "resolved": "https://registry.npmjs.org/lodash.merge/-/lodash.merge-4.6.2.tgz", + "integrity": "sha512-0KpjqXRVvrYyCsX1swR/XTK0va6VQkQM6MNo7PqW77ByjAhoARA8EfrP1N4+KlKj8YS0ZUCtRT/YUuhyYDujIQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/log-symbols": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/log-symbols/-/log-symbols-6.0.0.tgz", + "integrity": "sha512-i24m8rpwhmPIS4zscNzK6MSEhk0DUWa/8iYQWxhffV8jkI4Phvs3F+quL5xvS0gdQR0FyTCMMH33Y78dDTzzIw==", + "license": "MIT", + "dependencies": { + "chalk": "^5.3.0", + "is-unicode-supported": "^1.3.0" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/log-symbols/node_modules/chalk": { + "version": "5.6.2", + "resolved": "https://registry.npmjs.org/chalk/-/chalk-5.6.2.tgz", + "integrity": "sha512-7NzBL0rN6fMUW+f7A6Io4h40qQlG+xGmtMxfbnH/K7TAtt8JQWVQK+6g0UXKMeVJoyV5EkkNsErQ8pVD3bLHbA==", + "license": "MIT", + "engines": { + "node": "^12.17.0 || ^14.13 || >=16.0.0" + }, + "funding": { + "url": "https://github.com/chalk/chalk?sponsor=1" + } + }, + "node_modules/log-symbols/node_modules/is-unicode-supported": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/is-unicode-supported/-/is-unicode-supported-1.3.0.tgz", + "integrity": "sha512-43r2mRvz+8JRIKnWJ+3j8JtjRKZ6GmjzfaE/qiBJnikNnYv/6bagRJ1kUhNk8R5EX/GkobD+r+sfxCPJsiKBLQ==", + "license": "MIT", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/long": { + "version": "5.3.2", + "resolved": "https://registry.npmjs.org/long/-/long-5.3.2.tgz", + "integrity": "sha512-mNAgZ1GmyNhD7AuqnTG3/VQ26o760+ZYBPKjPvugO8+nLbYfX6TVpJPseBvopbdY+qpZ/lKUnmEc1LeZYS3QAA==", + "devOptional": true, + "license": "Apache-2.0" + }, + "node_modules/loose-envify": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/loose-envify/-/loose-envify-1.4.0.tgz", + "integrity": "sha512-lyuxPGr/Wfhrlem2CL/UcnUc1zcqKAImBDzukY7Y5F/yQiNdko6+fRLevlw1HgMySw7f611UIY408EtxRSoK3Q==", + "dev": true, + "license": "MIT", + "dependencies": { + "js-tokens": "^3.0.0 || ^4.0.0" + }, + "bin": { + "loose-envify": "cli.js" + } + }, + "node_modules/lru-cache": { + "version": "5.1.1", + "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-5.1.1.tgz", + "integrity": "sha512-KpNARQA3Iwv+jTA0utUVVbrh+Jlrr1Fv0e56GGzAFOXN7dk/FviaDW8LHmK52DlcH4WP2n6gI8vN1aesBFgo9w==", + "license": "ISC", + "dependencies": { + "yallist": "^3.0.2" + } + }, + "node_modules/lru.min": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/lru.min/-/lru.min-1.1.4.tgz", + "integrity": "sha512-DqC6n3QQ77zdFpCMASA1a3Jlb64Hv2N2DciFGkO/4L9+q/IpIAuRlKOvCXabtRW6cQf8usbmM6BE/TOPysCdIA==", + "devOptional": true, + "license": "MIT", + "engines": { + "bun": ">=1.0.0", + "deno": ">=1.30.0", + "node": ">=8.0.0" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/wellwelwel" + } + }, + "node_modules/lucide-react": { + "version": "0.577.0", + "resolved": "https://registry.npmjs.org/lucide-react/-/lucide-react-0.577.0.tgz", + "integrity": "sha512-4LjoFv2eEPwYDPg/CUdBJQSDfPyzXCRrVW1X7jrx/trgxnxkHFjnVZINbzvzxjN70dxychOfg+FTYwBiS3pQ5A==", + "license": "ISC", + "peerDependencies": { + "react": "^16.5.1 || ^17.0.0 || ^18.0.0 || ^19.0.0" + } + }, + "node_modules/magic-string": { + "version": "0.30.21", + "resolved": "https://registry.npmjs.org/magic-string/-/magic-string-0.30.21.tgz", + "integrity": "sha512-vd2F4YUyEXKGcLHoq+TEyCjxueSeHnFxyyjNp80yg0XV4vUhnDer/lvvlqM/arB5bXQN5K2/3oinyCRyx8T2CQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/sourcemap-codec": "^1.5.5" + } + }, + "node_modules/math-intrinsics": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/math-intrinsics/-/math-intrinsics-1.1.0.tgz", + "integrity": "sha512-/IXtbwEk5HTPyEwyKX6hGkYXxM9nbj64B+ilVJnC/R6B0pH5G4V3b0pVbL7DBj4tkhBAppbQUlf6F6Xl9LHu1g==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/media-typer": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/media-typer/-/media-typer-1.1.0.tgz", + "integrity": "sha512-aisnrDP4GNe06UcKFnV5bfMNPBUw4jsLGaWwWfnH3v02GnBuXX2MCVn5RbrWo0j3pczUilYblq7fQ7Nw2t5XKw==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/merge-descriptors": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/merge-descriptors/-/merge-descriptors-2.0.0.tgz", + "integrity": "sha512-Snk314V5ayFLhp3fkUREub6WtjBfPdCPY1Ln8/8munuLuiYhsABgBVWsozAG+MWMbVEvcdcpbi9R7ww22l9Q3g==", + "license": "MIT", + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/merge-stream": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/merge-stream/-/merge-stream-2.0.0.tgz", + "integrity": "sha512-abv/qOcuPfk3URPfDzmZU1LKmuw8kT+0nIHvKrKgFrwifol/doWcdA4ZqsWQ8ENrFKkd67Mfpo/LovbIUsbt3w==", + "license": "MIT" + }, + "node_modules/merge2": { + "version": "1.4.1", + "resolved": "https://registry.npmjs.org/merge2/-/merge2-1.4.1.tgz", + "integrity": "sha512-8q7VEgMJW4J8tcfVPy8g09NcQwZdbwFEqhe/WZkoIzjn/3TGDwtOCYtXGxA3O8tPzpczCCDgv+P2P5y00ZJOOg==", + "license": "MIT", + "engines": { + "node": ">= 8" + } + }, + "node_modules/micromatch": { + "version": "4.0.8", + "resolved": "https://registry.npmjs.org/micromatch/-/micromatch-4.0.8.tgz", + "integrity": "sha512-PXwfBhYu0hBCPw8Dn0E+WDYb7af3dSLVWKi3HGv84IdF4TyFoC0ysxFd0Goxw7nSv4T/PzEJQxsYsEiFCKo2BA==", + "license": "MIT", + "dependencies": { + "braces": "^3.0.3", + "picomatch": "^2.3.1" + }, + "engines": { + "node": ">=8.6" + } + }, + "node_modules/mime-db": { + "version": "1.54.0", + "resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.54.0.tgz", + "integrity": "sha512-aU5EJuIN2WDemCcAp2vFBfp/m4EAhWJnUNSSw0ixs7/kXbd6Pg64EmwJkNdFhB8aWt1sH2CTXrLxo/iAGV3oPQ==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/mime-types": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/mime-types/-/mime-types-3.0.2.tgz", + "integrity": "sha512-Lbgzdk0h4juoQ9fCKXW4by0UJqj+nOOrI9MJ1sSj4nI8aI2eo1qmvQEie4VD1glsS250n15LsWsYtCugiStS5A==", + "license": "MIT", + "dependencies": { + "mime-db": "^1.54.0" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/mimic-fn": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/mimic-fn/-/mimic-fn-2.1.0.tgz", + "integrity": "sha512-OqbOk5oEQeAZ8WXWydlu9HJjz9WVdEIvamMCcXmuqUYjTknH/sqsWvhQ3vgwKFRR1HpjvNBKQ37nbJgYzGqGcg==", + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/mimic-function": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/mimic-function/-/mimic-function-5.0.1.tgz", + "integrity": "sha512-VP79XUPxV2CigYP3jWwAUFSku2aKqBH7uTAapFWCBqutsbmDo96KY5o8uh6U+/YSIn5OxJnXp73beVkpqMIGhA==", + "license": "MIT", + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/minimatch": { + "version": "3.1.5", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.1.5.tgz", + "integrity": "sha512-VgjWUsnnT6n+NUk6eZq77zeFdpW2LWDzP6zFGrCbHXiYNul5Dzqk2HHQ5uFH2DNW5Xbp8+jVzaeNt94ssEEl4w==", + "dev": true, + "license": "ISC", + "dependencies": { + "brace-expansion": "^1.1.7" + }, + "engines": { + "node": "*" + } + }, + "node_modules/minimist": { + "version": "1.2.8", + "resolved": "https://registry.npmjs.org/minimist/-/minimist-1.2.8.tgz", + "integrity": "sha512-2yyAR8qBkN3YuheJanUpWC5U3bb5osDywNB8RzDVlDwDHbocAJveqqj1u8+SVD7jkWT4yvsHCpWqqWqAxb0zCA==", + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/minipass": { + "version": "7.1.3", + "resolved": "https://registry.npmjs.org/minipass/-/minipass-7.1.3.tgz", + "integrity": "sha512-tEBHqDnIoM/1rXME1zgka9g6Q2lcoCkxHLuc7ODJ5BxbP5d4c2Z5cGgtXAku59200Cx7diuHTOYfSBD8n6mm8A==", + "license": "BlueOak-1.0.0", + "engines": { + "node": ">=16 || 14 >=14.17" + } + }, + "node_modules/minizlib": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/minizlib/-/minizlib-3.1.0.tgz", + "integrity": "sha512-KZxYo1BUkWD2TVFLr0MQoM8vUUigWD3LlD83a/75BqC+4qE0Hb1Vo5v1FgcfaNXvfXzr+5EhQ6ing/CaBijTlw==", + "license": "MIT", + "dependencies": { + "minipass": "^7.1.2" + }, + "engines": { + "node": ">= 18" + } + }, + "node_modules/motion-dom": { + "version": "12.38.0", + "resolved": "https://registry.npmjs.org/motion-dom/-/motion-dom-12.38.0.tgz", + "integrity": "sha512-pdkHLD8QYRp8VfiNLb8xIBJis1byQ9gPT3Jnh2jqfFtAsWUA3dEepDlsWe/xMpO8McV+VdpKVcp+E+TGJEtOoA==", + "license": "MIT", + "dependencies": { + "motion-utils": "^12.36.0" + } + }, + "node_modules/motion-utils": { + "version": "12.36.0", + "resolved": "https://registry.npmjs.org/motion-utils/-/motion-utils-12.36.0.tgz", + "integrity": "sha512-eHWisygbiwVvf6PZ1vhaHCLamvkSbPIeAYxWUuL3a2PD/TROgE7FvfHWTIH4vMl798QLfMw15nRqIaRDXTlYRg==", + "license": "MIT" + }, + "node_modules/ms": { + "version": "2.1.3", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz", + "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==", + "license": "MIT" + }, + "node_modules/msw": { + "version": "2.12.13", + "resolved": "https://registry.npmjs.org/msw/-/msw-2.12.13.tgz", + "integrity": "sha512-9CV2mXT9+z0J26MQDfEZZkj/psJ5Er/w0w+t95FWdaGH/DTlhNZBx8vBO5jSYv8AZEnl3ouX+AaTT68KXdAIag==", + "hasInstallScript": true, + "license": "MIT", + "dependencies": { + "@inquirer/confirm": "^5.0.0", + "@mswjs/interceptors": "^0.41.2", + "@open-draft/deferred-promise": "^2.2.0", + "@types/statuses": "^2.0.6", + "cookie": "^1.0.2", + "graphql": "^16.12.0", + "headers-polyfill": "^4.0.2", + "is-node-process": "^1.2.0", + "outvariant": "^1.4.3", + "path-to-regexp": "^6.3.0", + "picocolors": "^1.1.1", + "rettime": "^0.10.1", + "statuses": "^2.0.2", + "strict-event-emitter": "^0.5.1", + "tough-cookie": "^6.0.0", + "type-fest": "^5.2.0", + "until-async": "^3.0.2", + "yargs": "^17.7.2" + }, + "bin": { + "msw": "cli/index.js" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/mswjs" + }, + "peerDependencies": { + "typescript": ">= 4.8.x" + }, + "peerDependenciesMeta": { + "typescript": { + "optional": true + } + } + }, + "node_modules/msw/node_modules/cookie": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/cookie/-/cookie-1.1.1.tgz", + "integrity": "sha512-ei8Aos7ja0weRpFzJnEA9UHJ/7XQmqglbRwnf2ATjcB9Wq874VKH9kfjjirM6UhU2/E5fFYadylyhFldcqSidQ==", + "license": "MIT", + "engines": { + "node": ">=18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/mute-stream": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/mute-stream/-/mute-stream-2.0.0.tgz", + "integrity": "sha512-WWdIxpyjEn+FhQJQQv9aQAYlHoNVdzIzUySNV1gHUPDSdZJ3yZn7pAAbQcV7B56Mvu881q9FZV+0Vx2xC44VWA==", + "license": "ISC", + "engines": { + "node": "^18.17.0 || >=20.5.0" + } + }, + "node_modules/mysql2": { + "version": "3.15.3", + "resolved": "https://registry.npmjs.org/mysql2/-/mysql2-3.15.3.tgz", + "integrity": "sha512-FBrGau0IXmuqg4haEZRBfHNWB5mUARw6hNwPDXXGg0XzVJ50mr/9hb267lvpVMnhZ1FON3qNd4Xfcez1rbFwSg==", + "devOptional": true, + "license": "MIT", + "dependencies": { + "aws-ssl-profiles": "^1.1.1", + "denque": "^2.1.0", + "generate-function": "^2.3.1", + "iconv-lite": "^0.7.0", + "long": "^5.2.1", + "lru.min": "^1.0.0", + "named-placeholders": "^1.1.3", + "seq-queue": "^0.0.5", + "sqlstring": "^2.3.2" + }, + "engines": { + "node": ">= 8.0" + } + }, + "node_modules/named-placeholders": { + "version": "1.1.6", + "resolved": "https://registry.npmjs.org/named-placeholders/-/named-placeholders-1.1.6.tgz", + "integrity": "sha512-Tz09sEL2EEuv5fFowm419c1+a/jSMiBjI9gHxVLrVdbUkkNUUfjsVYs9pVZu5oCon/kmRh9TfLEObFtkVxmY0w==", + "devOptional": true, + "license": "MIT", + "dependencies": { + "lru.min": "^1.1.0" + }, + "engines": { + "node": ">=8.0.0" + } + }, + "node_modules/nanoid": { + "version": "3.3.11", + "resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.11.tgz", + "integrity": "sha512-N8SpfPUnUp1bK+PMYW8qSWdl9U+wwNWI4QKxOYDy9JAro3WMX7p2OeVRF9v+347pnakNevPmiHhNmZ2HbFA76w==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "bin": { + "nanoid": "bin/nanoid.cjs" + }, + "engines": { + "node": "^10 || ^12 || ^13.7 || ^14 || >=15.0.1" + } + }, + "node_modules/napi-postinstall": { + "version": "0.3.4", + "resolved": "https://registry.npmjs.org/napi-postinstall/-/napi-postinstall-0.3.4.tgz", + "integrity": "sha512-PHI5f1O0EP5xJ9gQmFGMS6IZcrVvTjpXjz7Na41gTE7eE2hK11lg04CECCYEEjdc17EV4DO+fkGEtt7TpTaTiQ==", + "dev": true, + "license": "MIT", + "bin": { + "napi-postinstall": "lib/cli.js" + }, + "engines": { + "node": "^12.20.0 || ^14.18.0 || >=16.0.0" + }, + "funding": { + "url": "https://opencollective.com/napi-postinstall" + } + }, + "node_modules/native-run": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/native-run/-/native-run-2.0.3.tgz", + "integrity": "sha512-U1PllBuzW5d1gfan+88L+Hky2eZx+9gv3Pf6rNBxKbORxi7boHzqiA6QFGSnqMem4j0A9tZ08NMIs5+0m/VS1Q==", + "license": "MIT", + "dependencies": { + "@ionic/utils-fs": "^3.1.7", + "@ionic/utils-terminal": "^2.3.4", + "bplist-parser": "^0.3.2", + "debug": "^4.3.4", + "elementtree": "^0.1.7", + "ini": "^4.1.1", + "plist": "^3.1.0", + "split2": "^4.2.0", + "through2": "^4.0.2", + "tslib": "^2.6.2", + "yauzl": "^2.10.0" + }, + "bin": { + "native-run": "bin/native-run" + }, + "engines": { + "node": ">=16.0.0" + } + }, + "node_modules/natural-compare": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/natural-compare/-/natural-compare-1.4.0.tgz", + "integrity": "sha512-OWND8ei3VtNC9h7V60qff3SVobHr996CTwgxubgyQYEpg290h9J0buyECNNJexkFm5sOajh5G116RYA1c8ZMSw==", + "dev": true, + "license": "MIT" + }, + "node_modules/negotiator": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/negotiator/-/negotiator-1.0.0.tgz", + "integrity": "sha512-8Ofs/AUQh8MaEcrlq5xOX0CQ9ypTF5dl78mjlMNfOK08fzpgTHQRQPBxcPlEtIw0yRpws+Zo/3r+5WRby7u3Gg==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/next": { + "version": "16.1.7", + "resolved": "https://registry.npmjs.org/next/-/next-16.1.7.tgz", + "integrity": "sha512-WM0L7WrSvKwoLegLYr6V+mz+RIofqQgVAfHhMp9a88ms0cFX8iX9ew+snpWlSBwpkURJOUdvCEt3uLl3NNzvWg==", + "license": "MIT", + "dependencies": { + "@next/env": "16.1.7", + "@swc/helpers": "0.5.15", + "baseline-browser-mapping": "^2.9.19", + "caniuse-lite": "^1.0.30001579", + "postcss": "8.4.31", + "styled-jsx": "5.1.6" + }, + "bin": { + "next": "dist/bin/next" + }, + "engines": { + "node": ">=20.9.0" + }, + "optionalDependencies": { + "@next/swc-darwin-arm64": "16.1.7", + "@next/swc-darwin-x64": "16.1.7", + "@next/swc-linux-arm64-gnu": "16.1.7", + "@next/swc-linux-arm64-musl": "16.1.7", + "@next/swc-linux-x64-gnu": "16.1.7", + "@next/swc-linux-x64-musl": "16.1.7", + "@next/swc-win32-arm64-msvc": "16.1.7", + "@next/swc-win32-x64-msvc": "16.1.7", + "sharp": "^0.34.4" + }, + "peerDependencies": { + "@opentelemetry/api": "^1.1.0", + "@playwright/test": "^1.51.1", + "babel-plugin-react-compiler": "*", + "react": "^18.2.0 || 19.0.0-rc-de68d2f4-20241204 || ^19.0.0", + "react-dom": "^18.2.0 || 19.0.0-rc-de68d2f4-20241204 || ^19.0.0", + "sass": "^1.3.0" + }, + "peerDependenciesMeta": { + "@opentelemetry/api": { + "optional": true + }, + "@playwright/test": { + "optional": true + }, + "babel-plugin-react-compiler": { + "optional": true + }, + "sass": { + "optional": true + } + } + }, + "node_modules/next/node_modules/postcss": { + "version": "8.4.31", + "resolved": "https://registry.npmjs.org/postcss/-/postcss-8.4.31.tgz", + "integrity": "sha512-PS08Iboia9mts/2ygV3eLpY5ghnUcfLV/EXTOW1E2qYxJKGGBUtNjN76FYHnMs36RmARn41bC0AZmn+rR0OVpQ==", + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/postcss/" + }, + { + "type": "tidelift", + "url": "https://tidelift.com/funding/github/npm/postcss" + }, + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "dependencies": { + "nanoid": "^3.3.6", + "picocolors": "^1.0.0", + "source-map-js": "^1.0.2" + }, + "engines": { + "node": "^10 || ^12 || >=14" + } + }, + "node_modules/node-domexception": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/node-domexception/-/node-domexception-1.0.0.tgz", + "integrity": "sha512-/jKZoMpw0F8GRwl4/eLROPA3cfcXtLApP0QzLmUT/HuPCZWyB7IY9ZrMeKw2O/nFIqPQB3PVM9aYm0F312AXDQ==", + "deprecated": "Use your platform's native DOMException instead", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/jimmywarting" + }, + { + "type": "github", + "url": "https://paypal.me/jimmywarting" + } + ], + "license": "MIT", + "engines": { + "node": ">=10.5.0" + } + }, + "node_modules/node-exports-info": { + "version": "1.6.0", + "resolved": "https://registry.npmjs.org/node-exports-info/-/node-exports-info-1.6.0.tgz", + "integrity": "sha512-pyFS63ptit/P5WqUkt+UUfe+4oevH+bFeIiPPdfb0pFeYEu/1ELnJu5l+5EcTKYL5M7zaAa7S8ddywgXypqKCw==", + "dev": true, + "license": "MIT", + "dependencies": { + "array.prototype.flatmap": "^1.3.3", + "es-errors": "^1.3.0", + "object.entries": "^1.1.9", + "semver": "^6.3.1" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/node-fetch": { + "version": "3.3.2", + "resolved": "https://registry.npmjs.org/node-fetch/-/node-fetch-3.3.2.tgz", + "integrity": "sha512-dRB78srN/l6gqWulah9SrxeYnxeddIG30+GOqK/9OlLVyLg3HPnr6SqOWTWOXKRwC2eGYCkZ59NNuSgvSrpgOA==", + "license": "MIT", + "dependencies": { + "data-uri-to-buffer": "^4.0.0", + "fetch-blob": "^3.1.4", + "formdata-polyfill": "^4.0.10" + }, + "engines": { + "node": "^12.20.0 || ^14.13.1 || >=16.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/node-fetch" + } + }, + "node_modules/node-fetch-native": { + "version": "1.6.7", + "resolved": "https://registry.npmjs.org/node-fetch-native/-/node-fetch-native-1.6.7.tgz", + "integrity": "sha512-g9yhqoedzIUm0nTnTqAQvueMPVOuIY16bqgAJJC8XOOubYFNwz6IER9qs0Gq2Xd0+CecCKFjtdDTMA4u4xG06Q==", + "devOptional": true, + "license": "MIT" + }, + "node_modules/node-releases": { + "version": "2.0.36", + "resolved": "https://registry.npmjs.org/node-releases/-/node-releases-2.0.36.tgz", + "integrity": "sha512-TdC8FSgHz8Mwtw9g5L4gR/Sh9XhSP/0DEkQxfEFXOpiul5IiHgHan2VhYYb6agDSfp4KuvltmGApc8HMgUrIkA==", + "license": "MIT" + }, + "node_modules/npm-run-path": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/npm-run-path/-/npm-run-path-6.0.0.tgz", + "integrity": "sha512-9qny7Z9DsQU8Ou39ERsPU4OZQlSTP47ShQzuKZ6PRXpYLtIFgl/DEBYEXKlvcEa+9tHVcK8CF81Y2V72qaZhWA==", + "license": "MIT", + "dependencies": { + "path-key": "^4.0.0", + "unicorn-magic": "^0.3.0" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/npm-run-path/node_modules/path-key": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/path-key/-/path-key-4.0.0.tgz", + "integrity": "sha512-haREypq7xkM7ErfgIyA0z+Bj4AGKlMSdlQE2jvJo6huWD1EdkKYV+G/T4nq0YEF2vgTT8kqMFKo1uHn950r4SQ==", + "license": "MIT", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/nypm": { + "version": "0.6.5", + "resolved": "https://registry.npmjs.org/nypm/-/nypm-0.6.5.tgz", + "integrity": "sha512-K6AJy1GMVyfyMXRVB88700BJqNUkByijGJM8kEHpLdcAt+vSQAVfkWWHYzuRXHSY6xA2sNc5RjTj0p9rE2izVQ==", + "devOptional": true, + "license": "MIT", + "dependencies": { + "citty": "^0.2.0", + "pathe": "^2.0.3", + "tinyexec": "^1.0.2" + }, + "bin": { + "nypm": "dist/cli.mjs" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/nypm/node_modules/citty": { + "version": "0.2.2", + "resolved": "https://registry.npmjs.org/citty/-/citty-0.2.2.tgz", + "integrity": "sha512-+6vJA3L98yv+IdfKGZHBNiGW5KHn22e/JwID0Strsz8h4S/csAu/OuICwxrg44k5MRiZHWIo8XXuJgQTriRP4w==", + "devOptional": true, + "license": "MIT" + }, + "node_modules/object-assign": { + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/object-assign/-/object-assign-4.1.1.tgz", + "integrity": "sha512-rJgTQnkUnH1sFw8yT6VSU3zD3sWmu6sZhIseY8VX+GRu3P6F7Fu+JNDoXfklElbLJSnc3FUQHVe4cU5hj+BcUg==", + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/object-inspect": { + "version": "1.13.4", + "resolved": "https://registry.npmjs.org/object-inspect/-/object-inspect-1.13.4.tgz", + "integrity": "sha512-W67iLl4J2EXEGTbfeHCffrjDfitvLANg0UlX3wFUUSTx92KXRFegMHUVgSqE+wvhAbi4WqjGg9czysTV2Epbew==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/object-keys": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/object-keys/-/object-keys-1.1.1.tgz", + "integrity": "sha512-NuAESUOUMrlIXOfHKzD6bpPu3tYt3xvjNdRIQ+FeT0lNb4K8WR70CaDxhuNguS2XG+GjkyMwOzsN5ZktImfhLA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/object-treeify": { + "version": "1.1.33", + "resolved": "https://registry.npmjs.org/object-treeify/-/object-treeify-1.1.33.tgz", + "integrity": "sha512-EFVjAYfzWqWsBMRHPMAXLCDIJnpMhdWAqR7xG6M6a2cs6PMFpl/+Z20w9zDW4vkxOFfddegBKq9Rehd0bxWE7A==", + "license": "MIT", + "engines": { + "node": ">= 10" + } + }, + "node_modules/object.assign": { + "version": "4.1.7", + "resolved": "https://registry.npmjs.org/object.assign/-/object.assign-4.1.7.tgz", + "integrity": "sha512-nK28WOo+QIjBkDduTINE4JkF/UJJKyf2EJxvJKfblDpyg0Q+pkOHNTL0Qwy6NP6FhE/EnzV73BxxqcJaXY9anw==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bind": "^1.0.8", + "call-bound": "^1.0.3", + "define-properties": "^1.2.1", + "es-object-atoms": "^1.0.0", + "has-symbols": "^1.1.0", + "object-keys": "^1.1.1" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/object.entries": { + "version": "1.1.9", + "resolved": "https://registry.npmjs.org/object.entries/-/object.entries-1.1.9.tgz", + "integrity": "sha512-8u/hfXFRBD1O0hPUjioLhoWFHRmt6tKA4/vZPyckBr18l1KE9uHrFaFaUi8MDRTpi4uak2goyPTSNJLXX2k2Hw==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bind": "^1.0.8", + "call-bound": "^1.0.4", + "define-properties": "^1.2.1", + "es-object-atoms": "^1.1.1" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/object.fromentries": { + "version": "2.0.8", + "resolved": "https://registry.npmjs.org/object.fromentries/-/object.fromentries-2.0.8.tgz", + "integrity": "sha512-k6E21FzySsSK5a21KRADBd/NGneRegFO5pLHfdQLpRDETUNJueLXs3WCzyQ3tFRDYgbq3KHGXfTbi2bs8WQ6rQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bind": "^1.0.7", + "define-properties": "^1.2.1", + "es-abstract": "^1.23.2", + "es-object-atoms": "^1.0.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/object.groupby": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/object.groupby/-/object.groupby-1.0.3.tgz", + "integrity": "sha512-+Lhy3TQTuzXI5hevh8sBGqbmurHbbIjAi0Z4S63nthVLmLxfbj4T54a4CfZrXIrt9iP4mVAPYMo/v99taj3wjQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bind": "^1.0.7", + "define-properties": "^1.2.1", + "es-abstract": "^1.23.2" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/object.values": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/object.values/-/object.values-1.2.1.tgz", + "integrity": "sha512-gXah6aZrcUxjWg2zR2MwouP2eHlCBzdV4pygudehaKXSGW4v2AsRQUK+lwwXhii6KFZcunEnmSUoYp5CXibxtA==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bind": "^1.0.8", + "call-bound": "^1.0.3", + "define-properties": "^1.2.1", + "es-object-atoms": "^1.0.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/obug": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/obug/-/obug-2.1.1.tgz", + "integrity": "sha512-uTqF9MuPraAQ+IsnPf366RG4cP9RtUi7MLO1N3KEc+wb0a6yKpeL0lmk2IB1jY5KHPAlTc6T/JRdC/YqxHNwkQ==", + "dev": true, + "funding": [ + "https://github.com/sponsors/sxzz", + "https://opencollective.com/debug" + ], + "license": "MIT" + }, + "node_modules/ohash": { + "version": "2.0.11", + "resolved": "https://registry.npmjs.org/ohash/-/ohash-2.0.11.tgz", + "integrity": "sha512-RdR9FQrFwNBNXAr4GixM8YaRZRJ5PUWbKYbE5eOsrwAjJW0q2REGcf79oYPsLyskQCZG1PLN+S/K1V00joZAoQ==", + "devOptional": true, + "license": "MIT" + }, + "node_modules/on-finished": { + "version": "2.4.1", + "resolved": "https://registry.npmjs.org/on-finished/-/on-finished-2.4.1.tgz", + "integrity": "sha512-oVlzkg3ENAhCk2zdv7IJwd/QUD4z2RxRwpkcGY8psCVcCYZNq4wYnVWALHM+brtuJjePWiYF/ClmuDr8Ch5+kg==", + "license": "MIT", + "dependencies": { + "ee-first": "1.1.1" + }, + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/once": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/once/-/once-1.4.0.tgz", + "integrity": "sha512-lNaJgI+2Q5URQBkccEKHTQOPaXdUxnZZElQTZY0MFUAuaEqe1E+Nyvgdz/aIyNi6Z9MzO5dv1H8n58/GELp3+w==", + "license": "ISC", + "dependencies": { + "wrappy": "1" + } + }, + "node_modules/onetime": { + "version": "7.0.0", + "resolved": "https://registry.npmjs.org/onetime/-/onetime-7.0.0.tgz", + "integrity": "sha512-VXJjc87FScF88uafS3JllDgvAm+c/Slfz06lorj2uAY34rlUu0Nt+v8wreiImcrgAjjIHp1rXpTDlLOGw29WwQ==", + "license": "MIT", + "dependencies": { + "mimic-function": "^5.0.0" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/open": { + "version": "11.0.0", + "resolved": "https://registry.npmjs.org/open/-/open-11.0.0.tgz", + "integrity": "sha512-smsWv2LzFjP03xmvFoJ331ss6h+jixfA4UUV/Bsiyuu4YJPfN+FIQGOIiv4w9/+MoHkfkJ22UIaQWRVFRfH6Vw==", + "license": "MIT", + "dependencies": { + "default-browser": "^5.4.0", + "define-lazy-prop": "^3.0.0", + "is-in-ssh": "^1.0.0", + "is-inside-container": "^1.0.0", + "powershell-utils": "^0.1.0", + "wsl-utils": "^0.3.0" + }, + "engines": { + "node": ">=20" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/optionator": { + "version": "0.9.4", + "resolved": "https://registry.npmjs.org/optionator/-/optionator-0.9.4.tgz", + "integrity": "sha512-6IpQ7mKUxRcZNLIObR0hz7lxsapSSIYNZJwXPGeF0mTVqGKFIXj1DQcMoT22S3ROcLyY/rz0PWaWZ9ayWmad9g==", + "dev": true, + "license": "MIT", + "dependencies": { + "deep-is": "^0.1.3", + "fast-levenshtein": "^2.0.6", + "levn": "^0.4.1", + "prelude-ls": "^1.2.1", + "type-check": "^0.4.0", + "word-wrap": "^1.2.5" + }, + "engines": { + "node": ">= 0.8.0" + } + }, + "node_modules/ora": { + "version": "8.2.0", + "resolved": "https://registry.npmjs.org/ora/-/ora-8.2.0.tgz", + "integrity": "sha512-weP+BZ8MVNnlCm8c0Qdc1WSWq4Qn7I+9CJGm7Qali6g44e/PUzbjNqJX5NJ9ljlNMosfJvg1fKEGILklK9cwnw==", + "license": "MIT", + "dependencies": { + "chalk": "^5.3.0", + "cli-cursor": "^5.0.0", + "cli-spinners": "^2.9.2", + "is-interactive": "^2.0.0", + "is-unicode-supported": "^2.0.0", + "log-symbols": "^6.0.0", + "stdin-discarder": "^0.2.2", + "string-width": "^7.2.0", + "strip-ansi": "^7.1.0" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/ora/node_modules/chalk": { + "version": "5.6.2", + "resolved": "https://registry.npmjs.org/chalk/-/chalk-5.6.2.tgz", + "integrity": "sha512-7NzBL0rN6fMUW+f7A6Io4h40qQlG+xGmtMxfbnH/K7TAtt8JQWVQK+6g0UXKMeVJoyV5EkkNsErQ8pVD3bLHbA==", + "license": "MIT", + "engines": { + "node": "^12.17.0 || ^14.13 || >=16.0.0" + }, + "funding": { + "url": "https://github.com/chalk/chalk?sponsor=1" + } + }, + "node_modules/outvariant": { + "version": "1.4.3", + "resolved": "https://registry.npmjs.org/outvariant/-/outvariant-1.4.3.tgz", + "integrity": "sha512-+Sl2UErvtsoajRDKCE5/dBz4DIvHXQQnAxtQTF04OJxY0+DyZXSo5P5Bb7XYWOh81syohlYL24hbDwxedPUJCA==", + "license": "MIT" + }, + "node_modules/own-keys": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/own-keys/-/own-keys-1.0.1.tgz", + "integrity": "sha512-qFOyK5PjiWZd+QQIh+1jhdb9LpxTF0qs7Pm8o5QHYZ0M3vKqSqzsZaEB6oWlxZ+q2sJBMI/Ktgd2N5ZwQoRHfg==", + "dev": true, + "license": "MIT", + "dependencies": { + "get-intrinsic": "^1.2.6", + "object-keys": "^1.1.1", + "safe-push-apply": "^1.0.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/p-finally": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/p-finally/-/p-finally-1.0.0.tgz", + "integrity": "sha512-LICb2p9CB7FS+0eR1oqWnHhp0FljGLZCWBE9aix0Uye9W8LTQPwMTYVGWQWIw9RdQiDg4+epXQODwIYJtSJaow==", + "license": "MIT", + "engines": { + "node": ">=4" + } + }, + "node_modules/p-limit": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/p-limit/-/p-limit-3.1.0.tgz", + "integrity": "sha512-TYOanM3wGwNGsZN2cVTYPArw454xnXj5qmWF1bEoAc4+cU/ol7GVh7odevjp1FNHduHc3KZMcFduxU5Xc6uJRQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "yocto-queue": "^0.1.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/p-locate": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/p-locate/-/p-locate-5.0.0.tgz", + "integrity": "sha512-LaNjtRWUBY++zB5nE/NwcaoMylSPk+S+ZHNB1TzdbMJMny6dynpAGt7X/tl/QYq3TIeE6nxHppbo2LGymrG5Pw==", + "dev": true, + "license": "MIT", + "dependencies": { + "p-limit": "^3.0.2" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/p-queue": { + "version": "6.6.2", + "resolved": "https://registry.npmjs.org/p-queue/-/p-queue-6.6.2.tgz", + "integrity": "sha512-RwFpb72c/BhQLEXIZ5K2e+AhgNVmIejGlTgiB9MzZ0e93GRvqZ7uSi0dvRF7/XIXDeNkra2fNHBxTyPDGySpjQ==", + "license": "MIT", + "dependencies": { + "eventemitter3": "^4.0.4", + "p-timeout": "^3.2.0" + }, + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/p-queue/node_modules/eventemitter3": { + "version": "4.0.7", + "resolved": "https://registry.npmjs.org/eventemitter3/-/eventemitter3-4.0.7.tgz", + "integrity": "sha512-8guHBZCwKnFhYdHr2ysuRWErTwhoN2X8XELRlrRwpmfeY2jjuUN4taQMsULKUVo1K4DvZl+0pgfyoysHxvmvEw==", + "license": "MIT" + }, + "node_modules/p-timeout": { + "version": "3.2.0", + "resolved": "https://registry.npmjs.org/p-timeout/-/p-timeout-3.2.0.tgz", + "integrity": "sha512-rhIwUycgwwKcP9yTOOFK/AKsAopjjCakVqLHePO3CC6Mir1Z99xT+R63jZxAT5lFZLa2inS5h+ZS2GvR99/FBg==", + "license": "MIT", + "dependencies": { + "p-finally": "^1.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/package-json-from-dist": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/package-json-from-dist/-/package-json-from-dist-1.0.1.tgz", + "integrity": "sha512-UEZIS3/by4OC8vL3P2dTXRETpebLI2NiI5vIrjaD/5UtrkFX/tNbwjTSRAGC/+7CAo2pIcBaRgWmcBBHcsaCIw==", + "license": "BlueOak-1.0.0" + }, + "node_modules/parent-module": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/parent-module/-/parent-module-1.0.1.tgz", + "integrity": "sha512-GQ2EWRpQV8/o+Aw8YqtfZZPfNRWZYkbidE9k5rpl/hC3vtHHBfGm2Ifi6qWV+coDGkrUKZAxE3Lot5kcsRlh+g==", + "license": "MIT", + "dependencies": { + "callsites": "^3.0.0" + }, + "engines": { + "node": ">=6" + } + }, + "node_modules/parse-json": { + "version": "5.2.0", + "resolved": "https://registry.npmjs.org/parse-json/-/parse-json-5.2.0.tgz", + "integrity": "sha512-ayCKvm/phCGxOkYRSCM82iDwct8/EonSEgCSxWxD7ve6jHggsFl4fZVQBPRNgQoKiuV/odhFrGzQXZwbifC8Rg==", + "license": "MIT", + "dependencies": { + "@babel/code-frame": "^7.0.0", + "error-ex": "^1.3.1", + "json-parse-even-better-errors": "^2.3.0", + "lines-and-columns": "^1.1.6" + }, + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/parse-ms": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/parse-ms/-/parse-ms-4.0.0.tgz", + "integrity": "sha512-TXfryirbmq34y8QBwgqCVLi+8oA3oWx2eAnSn62ITyEhEYaWRlVZ2DvMM9eZbMs/RfxPu/PK/aBLyGj4IrqMHw==", + "license": "MIT", + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/parseurl": { + "version": "1.3.3", + "resolved": "https://registry.npmjs.org/parseurl/-/parseurl-1.3.3.tgz", + "integrity": "sha512-CiyeOxFT/JZyN5m0z9PfXw4SCBJ6Sygz1Dpl0wqjlhDEGGBP1GnsUVEL0p63hoG1fcj3fHynXi9NYO4nWOL+qQ==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/path-browserify": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/path-browserify/-/path-browserify-1.0.1.tgz", + "integrity": "sha512-b7uo2UCUOYZcnF/3ID0lulOJi/bafxa1xPe7ZPsammBSpjSWQkjNxlt635YGS2MiR9GjvuXCtz2emr3jbsz98g==", + "license": "MIT" + }, + "node_modules/path-exists": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/path-exists/-/path-exists-4.0.0.tgz", + "integrity": "sha512-ak9Qy5Q7jYb2Wwcey5Fpvg2KoAc/ZIhLSLOSBmRmygPsGwkVVt0fZa0qrtMz+m6tJTAHfZQ8FnmB4MG4LWy7/w==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/path-key": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/path-key/-/path-key-3.1.1.tgz", + "integrity": "sha512-ojmeN0qd+y0jszEtoY48r0Peq5dwMEkIlCOu6Q5f41lfkswXuKtYrhgoTpLnyIcHm24Uhqx+5Tqm2InSwLhE6Q==", + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/path-parse": { + "version": "1.0.7", + "resolved": "https://registry.npmjs.org/path-parse/-/path-parse-1.0.7.tgz", + "integrity": "sha512-LDJzPVEEEPR+y48z93A0Ed0yXb8pAByGWo/k5YYdYgpY2/2EsOsksJrq7lOHxryrVOn1ejG6oAp8ahvOIQD8sw==", + "dev": true, + "license": "MIT" + }, + "node_modules/path-scurry": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/path-scurry/-/path-scurry-2.0.2.tgz", + "integrity": "sha512-3O/iVVsJAPsOnpwWIeD+d6z/7PmqApyQePUtCndjatj/9I5LylHvt5qluFaBT3I5h3r1ejfR056c+FCv+NnNXg==", + "license": "BlueOak-1.0.0", + "dependencies": { + "lru-cache": "^11.0.0", + "minipass": "^7.1.2" + }, + "engines": { + "node": "18 || 20 || >=22" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/path-scurry/node_modules/lru-cache": { + "version": "11.2.7", + "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-11.2.7.tgz", + "integrity": "sha512-aY/R+aEsRelme17KGQa/1ZSIpLpNYYrhcrepKTZgE+W3WM16YMCaPwOHLHsmopZHELU0Ojin1lPVxKR0MihncA==", + "license": "BlueOak-1.0.0", + "engines": { + "node": "20 || >=22" + } + }, + "node_modules/path-to-regexp": { + "version": "6.3.0", + "resolved": "https://registry.npmjs.org/path-to-regexp/-/path-to-regexp-6.3.0.tgz", + "integrity": "sha512-Yhpw4T9C6hPpgPeA28us07OJeqZ5EzQTkbfwuhsUg0c237RomFoETJgmp2sa3F/41gfLE6G5cqcYwznmeEeOlQ==", + "license": "MIT" + }, + "node_modules/pathe": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/pathe/-/pathe-2.0.3.tgz", + "integrity": "sha512-WUjGcAqP1gQacoQe+OBJsFA7Ld4DyXuUIjZ5cc75cLHvJ7dtNsTugphxIADwspS+AraAUePCKrSVtPLFj/F88w==", + "devOptional": true, + "license": "MIT" + }, + "node_modules/pend": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/pend/-/pend-1.2.0.tgz", + "integrity": "sha512-F3asv42UuXchdzt+xXqfW1OGlVBe+mxa2mqI0pg5yAHZPvFmY3Y6drSf/GQ1A86WgWEN9Kzh/WrgKa6iGcHXLg==", + "license": "MIT" + }, + "node_modules/perfect-debounce": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/perfect-debounce/-/perfect-debounce-1.0.0.tgz", + "integrity": "sha512-xCy9V055GLEqoFaHoC1SoLIaLmWctgCUaBaWxDZ7/Zx4CTyX7cJQLJOok/orfjZAh9kEYpjJa4d0KcJmCbctZA==", + "devOptional": true, + "license": "MIT" + }, + "node_modules/picocolors": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz", + "integrity": "sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==", + "license": "ISC" + }, + "node_modules/picomatch": { + "version": "2.3.2", + "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-2.3.2.tgz", + "integrity": "sha512-V7+vQEJ06Z+c5tSye8S+nHUfI51xoXIXjHQ99cQtKUkQqqO1kO/KCJUfZXuB47h/YBlDhah2H3hdUGXn8ie0oA==", + "license": "MIT", + "engines": { + "node": ">=8.6" + }, + "funding": { + "url": "https://github.com/sponsors/jonschlinkert" + } + }, + "node_modules/pkce-challenge": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/pkce-challenge/-/pkce-challenge-5.0.1.tgz", + "integrity": "sha512-wQ0b/W4Fr01qtpHlqSqspcj3EhBvimsdh0KlHhH8HRZnMsEa0ea2fTULOXOS9ccQr3om+GcGRk4e+isrZWV8qQ==", + "license": "MIT", + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/pkg-types": { + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/pkg-types/-/pkg-types-2.3.0.tgz", + "integrity": "sha512-SIqCzDRg0s9npO5XQ3tNZioRY1uK06lA41ynBC1YmFTmnY6FjUjVt6s4LoADmwoig1qqD0oK8h1p/8mlMx8Oig==", + "devOptional": true, + "license": "MIT", + "dependencies": { + "confbox": "^0.2.2", + "exsolve": "^1.0.7", + "pathe": "^2.0.3" + } + }, + "node_modules/playwright": { + "version": "1.61.1", + "resolved": "https://registry.npmjs.org/playwright/-/playwright-1.61.1.tgz", + "integrity": "sha512-DWnY5o3YbLWK4GovuAVwpqL+1VwGNdUGrRr++8j8PtQQzvAVZUIMjKQ90fY689sEJZJBbZVw1rXaOKSTitkzPQ==", + "devOptional": true, + "license": "Apache-2.0", + "dependencies": { + "playwright-core": "1.61.1" + }, + "bin": { + "playwright": "cli.js" + }, + "engines": { + "node": ">=18" + }, + "optionalDependencies": { + "fsevents": "2.3.2" + } + }, + "node_modules/playwright-core": { + "version": "1.61.1", + "resolved": "https://registry.npmjs.org/playwright-core/-/playwright-core-1.61.1.tgz", + "integrity": "sha512-h7Qlt6m4REp25qvIdvbDtVmD4LqVXfpRxhORv9L0jzETM05p4fuPJ3dKyuSXQxDSbXnmS79HAgi9589lGSpLkg==", + "devOptional": true, + "license": "Apache-2.0", + "bin": { + "playwright-core": "cli.js" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/playwright/node_modules/fsevents": { + "version": "2.3.2", + "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.2.tgz", + "integrity": "sha512-xiqMQR4xAeHTuB9uWm+fFRcIOgKBMiOBP+eXiyT7jsgVCq1bkVygt00oASowB7EdtpOHaaPgKt812P9ab+DDKA==", + "dev": true, + "hasInstallScript": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": "^8.16.0 || ^10.6.0 || >=11.0.0" + } + }, + "node_modules/plist": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/plist/-/plist-3.1.0.tgz", + "integrity": "sha512-uysumyrvkUX0rX/dEVqt8gC3sTBzd4zoWfLeS29nb53imdaXVvLINYXTI2GNqzaMuvacNx4uJQ8+b3zXR0pkgQ==", + "license": "MIT", + "dependencies": { + "@xmldom/xmldom": "^0.8.8", + "base64-js": "^1.5.1", + "xmlbuilder": "^15.1.1" + }, + "engines": { + "node": ">=10.4.0" + } + }, + "node_modules/possible-typed-array-names": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/possible-typed-array-names/-/possible-typed-array-names-1.1.0.tgz", + "integrity": "sha512-/+5VFTchJDoVj3bhoqi6UeymcD00DAwb1nJwamzPvHEszJ4FpF6SNNbUbOS8yI56qHzdV8eK0qEfOSiodkTdxg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/postcss": { + "version": "8.5.8", + "resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.8.tgz", + "integrity": "sha512-OW/rX8O/jXnm82Ey1k44pObPtdblfiuWnrd8X7GJ7emImCOstunGbXUpp7HdBrFQX6rJzn3sPT397Wp5aCwCHg==", + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/postcss/" + }, + { + "type": "tidelift", + "url": "https://tidelift.com/funding/github/npm/postcss" + }, + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "dependencies": { + "nanoid": "^3.3.11", + "picocolors": "^1.1.1", + "source-map-js": "^1.2.1" + }, + "engines": { + "node": "^10 || ^12 || >=14" + } + }, + "node_modules/postcss-selector-parser": { + "version": "7.1.1", + "resolved": "https://registry.npmjs.org/postcss-selector-parser/-/postcss-selector-parser-7.1.1.tgz", + "integrity": "sha512-orRsuYpJVw8LdAwqqLykBj9ecS5/cRHlI5+nvTo8LcCKmzDmqVORXtOIYEEQuL9D4BxtA1lm5isAqzQZCoQ6Eg==", + "license": "MIT", + "dependencies": { + "cssesc": "^3.0.0", + "util-deprecate": "^1.0.2" + }, + "engines": { + "node": ">=4" + } + }, + "node_modules/postgres": { + "version": "3.4.7", + "resolved": "https://registry.npmjs.org/postgres/-/postgres-3.4.7.tgz", + "integrity": "sha512-Jtc2612XINuBjIl/QTWsV5UvE8UHuNblcO3vVADSrKsrc6RqGX6lOW1cEo3CM2v0XG4Nat8nI+YM7/f26VxXLw==", + "devOptional": true, + "license": "Unlicense", + "engines": { + "node": ">=12" + }, + "funding": { + "type": "individual", + "url": "https://github.com/sponsors/porsager" + } + }, + "node_modules/powershell-utils": { + "version": "0.1.0", + "resolved": "https://registry.npmjs.org/powershell-utils/-/powershell-utils-0.1.0.tgz", + "integrity": "sha512-dM0jVuXJPsDN6DvRpea484tCUaMiXWjuCn++HGTqUWzGDjv5tZkEZldAJ/UMlqRYGFrD/etByo4/xOuC/snX2A==", + "license": "MIT", + "engines": { + "node": ">=20" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/prelude-ls": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/prelude-ls/-/prelude-ls-1.2.1.tgz", + "integrity": "sha512-vkcDPrRZo1QZLbn5RLGPpg/WmIQ65qoWWhcGKf/b5eplkkarX0m9z8ppCat4mlOqUsWpyNuYgO3VRyrYHSzX5g==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.8.0" + } + }, + "node_modules/pretty-ms": { + "version": "9.3.0", + "resolved": "https://registry.npmjs.org/pretty-ms/-/pretty-ms-9.3.0.tgz", + "integrity": "sha512-gjVS5hOP+M3wMm5nmNOucbIrqudzs9v/57bWRHQWLYklXqoXKrVfYW2W9+glfGsqtPgpiz5WwyEEB+ksXIx3gQ==", + "license": "MIT", + "dependencies": { + "parse-ms": "^4.0.0" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/prisma": { + "version": "7.6.0", + "resolved": "https://registry.npmjs.org/prisma/-/prisma-7.6.0.tgz", + "integrity": "sha512-OKJIPT81K3+F+AayIkY/Y3mkF2NWoFh7lZApaaqPYy7EHILKdO0VsmGkP+hDKYTySHsFSyLWXm/JgcR1B8fY1Q==", + "devOptional": true, + "hasInstallScript": true, + "license": "Apache-2.0", + "dependencies": { + "@prisma/config": "7.6.0", + "@prisma/dev": "0.24.3", + "@prisma/engines": "7.6.0", + "@prisma/studio-core": "0.27.3", + "mysql2": "3.15.3", + "postgres": "3.4.7" + }, + "bin": { + "prisma": "build/index.js" + }, + "engines": { + "node": "^20.19 || ^22.12 || >=24.0" + }, + "peerDependencies": { + "better-sqlite3": ">=9.0.0", + "typescript": ">=5.4.0" + }, + "peerDependenciesMeta": { + "better-sqlite3": { + "optional": true + }, + "typescript": { + "optional": true + } + } + }, + "node_modules/promise-limit": { + "version": "2.7.0", + "resolved": "https://registry.npmjs.org/promise-limit/-/promise-limit-2.7.0.tgz", + "integrity": "sha512-7nJ6v5lnJsXwGprnGXga4wx6d1POjvi5Qmf1ivTRxTjH4Z/9Czja/UCMLVmB9N93GeWOU93XaFaEt6jbuoagNw==", + "license": "ISC" + }, + "node_modules/prompts": { + "version": "2.4.2", + "resolved": "https://registry.npmjs.org/prompts/-/prompts-2.4.2.tgz", + "integrity": "sha512-NxNv/kLguCA7p3jE8oL2aEBsrJWgAakBpgmgK6lpPWV+WuOmY6r2/zbAVnP+T8bQlA0nzHXSJSJW0Hq7ylaD2Q==", + "license": "MIT", + "dependencies": { + "kleur": "^3.0.3", + "sisteransi": "^1.0.5" + }, + "engines": { + "node": ">= 6" + } + }, + "node_modules/prompts/node_modules/kleur": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/kleur/-/kleur-3.0.3.tgz", + "integrity": "sha512-eTIzlVOSUR+JxdDFepEYcBMtZ9Qqdef+rnzWdRZuMbOywu5tO2w2N7rqjoANZ5k9vywhL6Br1VRjUIgTQx4E8w==", + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/prop-types": { + "version": "15.8.1", + "resolved": "https://registry.npmjs.org/prop-types/-/prop-types-15.8.1.tgz", + "integrity": "sha512-oj87CgZICdulUohogVAR7AjlC0327U4el4L6eAvOqCeudMDVU0NThNaV+b9Df4dXgSP1gXMTnPdhfe/2qDH5cg==", + "dev": true, + "license": "MIT", + "dependencies": { + "loose-envify": "^1.4.0", + "object-assign": "^4.1.1", + "react-is": "^16.13.1" + } + }, + "node_modules/proper-lockfile": { + "version": "4.1.2", + "resolved": "https://registry.npmjs.org/proper-lockfile/-/proper-lockfile-4.1.2.tgz", + "integrity": "sha512-TjNPblN4BwAWMXU8s9AEz4JmQxnD1NNL7bNOY/AKUzyamc379FWASUhc/K1pL2noVb+XmZKLL68cjzLsiOAMaA==", + "devOptional": true, + "license": "MIT", + "dependencies": { + "graceful-fs": "^4.2.4", + "retry": "^0.12.0", + "signal-exit": "^3.0.2" + } + }, + "node_modules/proper-lockfile/node_modules/signal-exit": { + "version": "3.0.7", + "resolved": "https://registry.npmjs.org/signal-exit/-/signal-exit-3.0.7.tgz", + "integrity": "sha512-wnD2ZE+l+SPC/uoS0vXeE9L1+0wuaMqKlfz9AMUo38JsyLSBWSFcHR1Rri62LZc12vLr1gb3jl7iwQhgwpAbGQ==", + "devOptional": true, + "license": "ISC" + }, + "node_modules/proxy-addr": { + "version": "2.0.7", + "resolved": "https://registry.npmjs.org/proxy-addr/-/proxy-addr-2.0.7.tgz", + "integrity": "sha512-llQsMLSUDUPT44jdrU/O37qlnifitDP+ZwrmmZcoSKyLKvtZxpyV0n2/bD/N4tBAAZ/gJEdZU7KMraoK1+XYAg==", + "license": "MIT", + "dependencies": { + "forwarded": "0.2.0", + "ipaddr.js": "1.9.1" + }, + "engines": { + "node": ">= 0.10" + } + }, + "node_modules/punycode": { + "version": "2.3.1", + "resolved": "https://registry.npmjs.org/punycode/-/punycode-2.3.1.tgz", + "integrity": "sha512-vYt7UD1U9Wg6138shLtLOvdAu+8DsC/ilFtEVHcH+wydcSpNE20AfSOduf6MkRFahL5FY7X1oU7nKVZFtfq8Fg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/pure-rand": { + "version": "6.1.0", + "resolved": "https://registry.npmjs.org/pure-rand/-/pure-rand-6.1.0.tgz", + "integrity": "sha512-bVWawvoZoBYpp6yIoQtQXHZjmz35RSVHnUOTefl8Vcjr8snTPY1wnpSPMWekcFwbxI6gtmT7rSYPFvz71ldiOA==", + "devOptional": true, + "funding": [ + { + "type": "individual", + "url": "https://github.com/sponsors/dubzzz" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/fast-check" + } + ], + "license": "MIT" + }, + "node_modules/qs": { + "version": "6.15.0", + "resolved": "https://registry.npmjs.org/qs/-/qs-6.15.0.tgz", + "integrity": "sha512-mAZTtNCeetKMH+pSjrb76NAM8V9a05I9aBZOHztWy/UqcJdQYNsf59vrRKWnojAT9Y+GbIvoTBC++CPHqpDBhQ==", + "license": "BSD-3-Clause", + "dependencies": { + "side-channel": "^1.1.0" + }, + "engines": { + "node": ">=0.6" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/queue-microtask": { + "version": "1.2.3", + "resolved": "https://registry.npmjs.org/queue-microtask/-/queue-microtask-1.2.3.tgz", + "integrity": "sha512-NuaNSa6flKT5JaSYQzJok04JzTL1CA6aGhv5rfLW3PgqA+M2ChpZQnAC8h8i4ZFkBS8X5RqkDBHA7r4hej3K9A==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ], + "license": "MIT" + }, + "node_modules/range-parser": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/range-parser/-/range-parser-1.2.1.tgz", + "integrity": "sha512-Hrgsx+orqoygnmhFbKaHE6c296J+HTAQXoxEF6gNupROmmGJRoyzfG3ccAveqCBrwr/2yxQ5BVd/GTl5agOwSg==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/raw-body": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/raw-body/-/raw-body-3.0.2.tgz", + "integrity": "sha512-K5zQjDllxWkf7Z5xJdV0/B0WTNqx6vxG70zJE4N0kBs4LovmEYWJzQGxC9bS9RAKu3bgM40lrd5zoLJ12MQ5BA==", + "license": "MIT", + "dependencies": { + "bytes": "~3.1.2", + "http-errors": "~2.0.1", + "iconv-lite": "~0.7.0", + "unpipe": "~1.0.0" + }, + "engines": { + "node": ">= 0.10" + } + }, + "node_modules/rc9": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/rc9/-/rc9-2.1.2.tgz", + "integrity": "sha512-btXCnMmRIBINM2LDZoEmOogIZU7Qe7zn4BpomSKZ/ykbLObuBdvG+mFq11DL6fjH1DRwHhrlgtYWG96bJiC7Cg==", + "devOptional": true, + "license": "MIT", + "dependencies": { + "defu": "^6.1.4", + "destr": "^2.0.3" + } + }, + "node_modules/react": { + "version": "19.2.3", + "resolved": "https://registry.npmjs.org/react/-/react-19.2.3.tgz", + "integrity": "sha512-Ku/hhYbVjOQnXDZFv2+RibmLFGwFdeeKHFcOTlrt7xplBnya5OGn/hIRDsqDiSUcfORsDC7MPxwork8jBwsIWA==", + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/react-chessboard": { + "version": "5.10.0", + "resolved": "https://registry.npmjs.org/react-chessboard/-/react-chessboard-5.10.0.tgz", + "integrity": "sha512-Y3PgaCVhnDG3IaQfu86OzTSEIEAUtuU5XwmHWnx3tcFOX7lSoAq81ZFX3MBj6y5a6FzDMTczMVmkkrV2CzTrIw==", + "license": "MIT", + "dependencies": { + "@dnd-kit/core": "^6.3.1", + "@dnd-kit/modifiers": "^9.0.0" + }, + "engines": { + "node": ">=20.11.0", + "pnpm": ">=9.4.0" + }, + "peerDependencies": { + "react": "^19.0.0", + "react-dom": "^19.0.0" + } + }, + "node_modules/react-dom": { + "version": "19.2.3", + "resolved": "https://registry.npmjs.org/react-dom/-/react-dom-19.2.3.tgz", + "integrity": "sha512-yELu4WmLPw5Mr/lmeEpox5rw3RETacE++JgHqQzd2dg+YbJuat3jH4ingc+WPZhxaoFzdv9y33G+F7Nl5O0GBg==", + "license": "MIT", + "dependencies": { + "scheduler": "^0.27.0" + }, + "peerDependencies": { + "react": "^19.2.3" + } + }, + "node_modules/react-is": { + "version": "16.13.1", + "resolved": "https://registry.npmjs.org/react-is/-/react-is-16.13.1.tgz", + "integrity": "sha512-24e6ynE2H+OKt4kqsOvNd8kBpV65zoxbA4BVsEOB3ARVWQki/DHzaUoC5KuON/BiccDaCCTZBuOcfZs70kR8bQ==", + "license": "MIT" + }, + "node_modules/react-redux": { + "version": "9.2.0", + "resolved": "https://registry.npmjs.org/react-redux/-/react-redux-9.2.0.tgz", + "integrity": "sha512-ROY9fvHhwOD9ySfrF0wmvu//bKCQ6AeZZq1nJNtbDC+kk5DuSuNX/n6YWYF/SYy7bSba4D4FSz8DJeKY/S/r+g==", + "license": "MIT", + "dependencies": { + "@types/use-sync-external-store": "^0.0.6", + "use-sync-external-store": "^1.4.0" + }, + "peerDependencies": { + "@types/react": "^18.2.25 || ^19", + "react": "^18.0 || ^19", + "redux": "^5.0.0" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + }, + "redux": { + "optional": true + } + } + }, + "node_modules/readable-stream": { + "version": "3.6.2", + "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-3.6.2.tgz", + "integrity": "sha512-9u/sniCrY3D5WdsERHzHE4G2YCXqoG5FTHUiCC4SIbr6XcLZBY05ya9EKjYek9O5xOAwjGq+1JdGBAS7Q9ScoA==", + "license": "MIT", + "dependencies": { + "inherits": "^2.0.3", + "string_decoder": "^1.1.1", + "util-deprecate": "^1.0.1" + }, + "engines": { + "node": ">= 6" + } + }, + "node_modules/readdirp": { + "version": "4.1.2", + "resolved": "https://registry.npmjs.org/readdirp/-/readdirp-4.1.2.tgz", + "integrity": "sha512-GDhwkLfywWL2s6vEjyhri+eXmfH6j1L7JE27WhqLeYzoh/A3DBaYGEj2H/HFZCn/kMfim73FXxEJTw06WtxQwg==", + "devOptional": true, + "license": "MIT", + "engines": { + "node": ">= 14.18.0" + }, + "funding": { + "type": "individual", + "url": "https://paulmillr.com/funding/" + } + }, + "node_modules/recast": { + "version": "0.23.11", + "resolved": "https://registry.npmjs.org/recast/-/recast-0.23.11.tgz", + "integrity": "sha512-YTUo+Flmw4ZXiWfQKGcwwc11KnoRAYgzAE2E7mXKCjSviTKShtxBsN6YUUBB2gtaBzKzeKunxhUwNHQuRryhWA==", + "license": "MIT", + "dependencies": { + "ast-types": "^0.16.1", + "esprima": "~4.0.0", + "source-map": "~0.6.1", + "tiny-invariant": "^1.3.3", + "tslib": "^2.0.1" + }, + "engines": { + "node": ">= 4" + } + }, + "node_modules/recharts": { + "version": "3.8.0", + "resolved": "https://registry.npmjs.org/recharts/-/recharts-3.8.0.tgz", + "integrity": "sha512-Z/m38DX3L73ExO4Tpc9/iZWHmHnlzWG4njQbxsF5aSjwqmHNDDIm0rdEBArkwsBvR8U6EirlEHiQNYWCVh9sGQ==", + "license": "MIT", + "workspaces": [ + "www" + ], + "dependencies": { + "@reduxjs/toolkit": "^1.9.0 || 2.x.x", + "clsx": "^2.1.1", + "decimal.js-light": "^2.5.1", + "es-toolkit": "^1.39.3", + "eventemitter3": "^5.0.1", + "immer": "^10.1.1", + "react-redux": "8.x.x || 9.x.x", + "reselect": "5.1.1", + "tiny-invariant": "^1.3.3", + "use-sync-external-store": "^1.2.2", + "victory-vendor": "^37.0.2" + }, + "engines": { + "node": ">=18" + }, + "peerDependencies": { + "react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0", + "react-dom": "^16.0.0 || ^17.0.0 || ^18.0.0 || ^19.0.0", + "react-is": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0" + } + }, + "node_modules/redux": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/redux/-/redux-5.0.1.tgz", + "integrity": "sha512-M9/ELqF6fy8FwmkpnF0S3YKOqMyoWJ4+CS5Efg2ct3oY9daQvd/Pc71FpGZsVsbl3Cpb+IIcjBDUnnyBdQbq4w==", + "license": "MIT" + }, + "node_modules/redux-thunk": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/redux-thunk/-/redux-thunk-3.1.0.tgz", + "integrity": "sha512-NW2r5T6ksUKXCabzhL9z+h206HQw/NJkcLm1GPImRQ8IzfXwRGqjVhKJGauHirT0DAuyy6hjdnMZaRoAcy0Klw==", + "license": "MIT", + "peerDependencies": { + "redux": "^5.0.0" + } + }, + "node_modules/reflect.getprototypeof": { + "version": "1.0.10", + "resolved": "https://registry.npmjs.org/reflect.getprototypeof/-/reflect.getprototypeof-1.0.10.tgz", + "integrity": "sha512-00o4I+DVrefhv+nX0ulyi3biSHCPDe+yLv5o/p6d/UVlirijB8E16FtfwSAi4g3tcqrQ4lRAqQSoFEZJehYEcw==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bind": "^1.0.8", + "define-properties": "^1.2.1", + "es-abstract": "^1.23.9", + "es-errors": "^1.3.0", + "es-object-atoms": "^1.0.0", + "get-intrinsic": "^1.2.7", + "get-proto": "^1.0.1", + "which-builtin-type": "^1.2.1" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/regexp.prototype.flags": { + "version": "1.5.4", + "resolved": "https://registry.npmjs.org/regexp.prototype.flags/-/regexp.prototype.flags-1.5.4.tgz", + "integrity": "sha512-dYqgNSZbDwkaJ2ceRd9ojCGjBq+mOm9LmtXnAnEGyHhN/5R7iDW2TRw3h+o/jCFxus3P2LfWIIiwowAjANm7IA==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bind": "^1.0.8", + "define-properties": "^1.2.1", + "es-errors": "^1.3.0", + "get-proto": "^1.0.1", + "gopd": "^1.2.0", + "set-function-name": "^2.0.2" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/remeda": { + "version": "2.33.4", + "resolved": "https://registry.npmjs.org/remeda/-/remeda-2.33.4.tgz", + "integrity": "sha512-ygHswjlc/opg2VrtiYvUOPLjxjtdKvjGz1/plDhkG66hjNjFr1xmfrs2ClNFo/E6TyUFiwYNh53bKV26oBoMGQ==", + "devOptional": true, + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/remeda" + } + }, + "node_modules/require-directory": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/require-directory/-/require-directory-2.1.1.tgz", + "integrity": "sha512-fGxEI7+wsG9xrvdjsrlmL22OMTTiHRwAMroiEeMgq8gzoLC/PQr7RsRDSTLUg/bZAZtF+TVIkHc6/4RIKrui+Q==", + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/require-from-string": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/require-from-string/-/require-from-string-2.0.2.tgz", + "integrity": "sha512-Xf0nWe6RseziFMu+Ap9biiUbmplq6S9/p+7w7YXP/JBHhrUDDUhwa+vANyubuqfZWTveU//DYVGsDG7RKL/vEw==", + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/reselect": { + "version": "5.1.1", + "resolved": "https://registry.npmjs.org/reselect/-/reselect-5.1.1.tgz", + "integrity": "sha512-K/BG6eIky/SBpzfHZv/dd+9JBFiS4SWV7FIujVyJRux6e45+73RaUHXLmIR1f7WOMaQ0U1km6qwklRQxpJJY0w==", + "license": "MIT" + }, + "node_modules/resolve": { + "version": "1.22.11", + "resolved": "https://registry.npmjs.org/resolve/-/resolve-1.22.11.tgz", + "integrity": "sha512-RfqAvLnMl313r7c9oclB1HhUEAezcpLjz95wFH4LVuhk9JF/r22qmVP9AMmOU4vMX7Q8pN8jwNg/CSpdFnMjTQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "is-core-module": "^2.16.1", + "path-parse": "^1.0.7", + "supports-preserve-symlinks-flag": "^1.0.0" + }, + "bin": { + "resolve": "bin/resolve" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/resolve-from": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/resolve-from/-/resolve-from-4.0.0.tgz", + "integrity": "sha512-pb/MYmXstAkysRFx8piNI1tGFNQIFA3vkE3Gq4EuA1dF6gHp/+vgZqsCGJapvy8N3Q+4o7FwvquPJcnZ7RYy4g==", + "license": "MIT", + "engines": { + "node": ">=4" + } + }, + "node_modules/resolve-pkg-maps": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/resolve-pkg-maps/-/resolve-pkg-maps-1.0.0.tgz", + "integrity": "sha512-seS2Tj26TBVOC2NIc2rOe2y2ZO7efxITtLZcGSOnHHNOQ7CkiUBfw0Iw2ck6xkIhPwLhKNLS8BO+hEpngQlqzw==", + "dev": true, + "license": "MIT", + "funding": { + "url": "https://github.com/privatenumber/resolve-pkg-maps?sponsor=1" + } + }, + "node_modules/restore-cursor": { + "version": "5.1.0", + "resolved": "https://registry.npmjs.org/restore-cursor/-/restore-cursor-5.1.0.tgz", + "integrity": "sha512-oMA2dcrw6u0YfxJQXm342bFKX/E4sG9rbTzO9ptUcR/e8A33cHuvStiYOwH7fszkZlZ1z/ta9AAoPk2F4qIOHA==", + "license": "MIT", + "dependencies": { + "onetime": "^7.0.0", + "signal-exit": "^4.1.0" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/retry": { + "version": "0.12.0", + "resolved": "https://registry.npmjs.org/retry/-/retry-0.12.0.tgz", + "integrity": "sha512-9LkiTwjUh6rT555DtE9rTX+BKByPfrMzEAtnlEtdEwr3Nkffwiihqe2bWADg+OQRjt9gl6ICdmB/ZFDCGAtSow==", + "devOptional": true, + "license": "MIT", + "engines": { + "node": ">= 4" + } + }, + "node_modules/rettime": { + "version": "0.10.1", + "resolved": "https://registry.npmjs.org/rettime/-/rettime-0.10.1.tgz", + "integrity": "sha512-uyDrIlUEH37cinabq0AX4QbgV4HbFZ/gqoiunWQ1UqBtRvTTytwhNYjE++pO/MjPTZL5KQCf2bEoJ/BJNVQ5Kw==", + "license": "MIT" + }, + "node_modules/reusify": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/reusify/-/reusify-1.1.0.tgz", + "integrity": "sha512-g6QUff04oZpHs0eG5p83rFLhHeV00ug/Yf9nZM6fLeUrPguBTkTQOdpAWWspMh55TZfVQDPaN3NQJfbVRAxdIw==", + "license": "MIT", + "engines": { + "iojs": ">=1.0.0", + "node": ">=0.10.0" + } + }, + "node_modules/rimraf": { + "version": "6.1.3", + "resolved": "https://registry.npmjs.org/rimraf/-/rimraf-6.1.3.tgz", + "integrity": "sha512-LKg+Cr2ZF61fkcaK1UdkH2yEBBKnYjTyWzTJT6KNPcSPaiT7HSdhtMXQuN5wkTX0Xu72KQ1l8S42rlmexS2hSA==", + "license": "BlueOak-1.0.0", + "dependencies": { + "glob": "^13.0.3", + "package-json-from-dist": "^1.0.1" + }, + "bin": { + "rimraf": "dist/esm/bin.mjs" + }, + "engines": { + "node": "20 || >=22" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/rolldown": { + "version": "1.0.0-rc.9", + "resolved": "https://registry.npmjs.org/rolldown/-/rolldown-1.0.0-rc.9.tgz", + "integrity": "sha512-9EbgWge7ZH+yqb4d2EnELAntgPTWbfL8ajiTW+SyhJEC4qhBbkCKbqFV4Ge4zmu5ziQuVbWxb/XwLZ+RIO7E8Q==", + "dev": true, + "license": "MIT", + "dependencies": { + "@oxc-project/types": "=0.115.0", + "@rolldown/pluginutils": "1.0.0-rc.9" + }, + "bin": { + "rolldown": "bin/cli.mjs" + }, + "engines": { + "node": "^20.19.0 || >=22.12.0" + }, + "optionalDependencies": { + "@rolldown/binding-android-arm64": "1.0.0-rc.9", + "@rolldown/binding-darwin-arm64": "1.0.0-rc.9", + "@rolldown/binding-darwin-x64": "1.0.0-rc.9", + "@rolldown/binding-freebsd-x64": "1.0.0-rc.9", + "@rolldown/binding-linux-arm-gnueabihf": "1.0.0-rc.9", + "@rolldown/binding-linux-arm64-gnu": "1.0.0-rc.9", + "@rolldown/binding-linux-arm64-musl": "1.0.0-rc.9", + "@rolldown/binding-linux-ppc64-gnu": "1.0.0-rc.9", + "@rolldown/binding-linux-s390x-gnu": "1.0.0-rc.9", + "@rolldown/binding-linux-x64-gnu": "1.0.0-rc.9", + "@rolldown/binding-linux-x64-musl": "1.0.0-rc.9", + "@rolldown/binding-openharmony-arm64": "1.0.0-rc.9", + "@rolldown/binding-wasm32-wasi": "1.0.0-rc.9", + "@rolldown/binding-win32-arm64-msvc": "1.0.0-rc.9", + "@rolldown/binding-win32-x64-msvc": "1.0.0-rc.9" + } + }, + "node_modules/router": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/router/-/router-2.2.0.tgz", + "integrity": "sha512-nLTrUKm2UyiL7rlhapu/Zl45FwNgkZGaCpZbIHajDYgwlJCOzLSk+cIPAnsEqV955GjILJnKbdQC1nVPz+gAYQ==", + "license": "MIT", + "dependencies": { + "debug": "^4.4.0", + "depd": "^2.0.0", + "is-promise": "^4.0.0", + "parseurl": "^1.3.3", + "path-to-regexp": "^8.0.0" + }, + "engines": { + "node": ">= 18" + } + }, + "node_modules/router/node_modules/path-to-regexp": { + "version": "8.4.2", + "resolved": "https://registry.npmjs.org/path-to-regexp/-/path-to-regexp-8.4.2.tgz", + "integrity": "sha512-qRcuIdP69NPm4qbACK+aDogI5CBDMi1jKe0ry5rSQJz8JVLsC7jV8XpiJjGRLLol3N+R5ihGYcrPLTno6pAdBA==", + "license": "MIT", + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/run-applescript": { + "version": "7.1.0", + "resolved": "https://registry.npmjs.org/run-applescript/-/run-applescript-7.1.0.tgz", + "integrity": "sha512-DPe5pVFaAsinSaV6QjQ6gdiedWDcRCbUuiQfQa2wmWV7+xC9bGulGI8+TdRmoFkAPaBXk8CrAbnlY2ISniJ47Q==", + "license": "MIT", + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/run-parallel": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/run-parallel/-/run-parallel-1.2.0.tgz", + "integrity": "sha512-5l4VyZR86LZ/lDxZTR6jqL8AFE2S0IFLMP26AbjsLVADxHdhB/c0GUsH+y39UfCi3dzz8OlQuPmnaJOMoDHQBA==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ], + "license": "MIT", + "dependencies": { + "queue-microtask": "^1.2.2" + } + }, + "node_modules/safe-array-concat": { + "version": "1.1.3", + "resolved": "https://registry.npmjs.org/safe-array-concat/-/safe-array-concat-1.1.3.tgz", + "integrity": "sha512-AURm5f0jYEOydBj7VQlVvDrjeFgthDdEF5H1dP+6mNpoXOMo1quQqJ4wvJDyRZ9+pO3kGWoOdmV08cSv2aJV6Q==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bind": "^1.0.8", + "call-bound": "^1.0.2", + "get-intrinsic": "^1.2.6", + "has-symbols": "^1.1.0", + "isarray": "^2.0.5" + }, + "engines": { + "node": ">=0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/safe-buffer": { + "version": "5.2.1", + "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.2.1.tgz", + "integrity": "sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ], + "license": "MIT" + }, + "node_modules/safe-push-apply": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/safe-push-apply/-/safe-push-apply-1.0.0.tgz", + "integrity": "sha512-iKE9w/Z7xCzUMIZqdBsp6pEQvwuEebH4vdpjcDWnyzaI6yl6O9FHvVpmGelvEHNsoY6wGblkxR6Zty/h00WiSA==", + "dev": true, + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0", + "isarray": "^2.0.5" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/safe-regex-test": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/safe-regex-test/-/safe-regex-test-1.1.0.tgz", + "integrity": "sha512-x/+Cz4YrimQxQccJf5mKEbIa1NzeCRNI5Ecl/ekmlYaampdNLPalVyIcCZNNH3MvmqBugV5TMYZXv0ljslUlaw==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bound": "^1.0.2", + "es-errors": "^1.3.0", + "is-regex": "^1.2.1" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/safer-buffer": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/safer-buffer/-/safer-buffer-2.1.2.tgz", + "integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==", + "license": "MIT" + }, + "node_modules/sax": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/sax/-/sax-1.1.4.tgz", + "integrity": "sha512-5f3k2PbGGp+YtKJjOItpg3P99IMD84E4HOvcfleTb5joCHNXYLsR9yWFPOYGgaeMPDubQILTCMdsFb2OMeOjtg==", + "license": "ISC" + }, + "node_modules/scheduler": { + "version": "0.27.0", + "resolved": "https://registry.npmjs.org/scheduler/-/scheduler-0.27.0.tgz", + "integrity": "sha512-eNv+WrVbKu1f3vbYJT/xtiF5syA5HPIMtf9IgY/nKg0sWqzAUEvqY/xm7OcZc/qafLx/iO9FgOmeSAp4v5ti/Q==", + "license": "MIT" + }, + "node_modules/semver": { + "version": "6.3.1", + "resolved": "https://registry.npmjs.org/semver/-/semver-6.3.1.tgz", + "integrity": "sha512-BR7VvDCVHO+q2xBEWskxS6DJE1qRnb7DxzUrogb71CWoSficBxYsiAGd+Kl0mmq/MprG9yArRkyrQxTO6XjMzA==", + "license": "ISC", + "bin": { + "semver": "bin/semver.js" + } + }, + "node_modules/send": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/send/-/send-1.2.1.tgz", + "integrity": "sha512-1gnZf7DFcoIcajTjTwjwuDjzuz4PPcY2StKPlsGAQ1+YH20IRVrBaXSWmdjowTJ6u8Rc01PoYOGHXfP1mYcZNQ==", + "license": "MIT", + "dependencies": { + "debug": "^4.4.3", + "encodeurl": "^2.0.0", + "escape-html": "^1.0.3", + "etag": "^1.8.1", + "fresh": "^2.0.0", + "http-errors": "^2.0.1", + "mime-types": "^3.0.2", + "ms": "^2.1.3", + "on-finished": "^2.4.1", + "range-parser": "^1.2.1", + "statuses": "^2.0.2" + }, + "engines": { + "node": ">= 18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/seq-queue": { + "version": "0.0.5", + "resolved": "https://registry.npmjs.org/seq-queue/-/seq-queue-0.0.5.tgz", + "integrity": "sha512-hr3Wtp/GZIc/6DAGPDcV4/9WoZhjrkXsi5B/07QgX8tsdc6ilr7BFM6PM6rbdAX1kFSDYeZGLipIZZKyQP0O5Q==", + "devOptional": true + }, + "node_modules/serve-static": { + "version": "2.2.1", + "resolved": "https://registry.npmjs.org/serve-static/-/serve-static-2.2.1.tgz", + "integrity": "sha512-xRXBn0pPqQTVQiC8wyQrKs2MOlX24zQ0POGaj0kultvoOCstBQM5yvOhAVSUwOMjQtTvsPWoNCHfPGwaaQJhTw==", + "license": "MIT", + "dependencies": { + "encodeurl": "^2.0.0", + "escape-html": "^1.0.3", + "parseurl": "^1.3.3", + "send": "^1.2.0" + }, + "engines": { + "node": ">= 18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/set-function-length": { + "version": "1.2.2", + "resolved": "https://registry.npmjs.org/set-function-length/-/set-function-length-1.2.2.tgz", + "integrity": "sha512-pgRc4hJ4/sNjWCSS9AmnS40x3bNMDTknHgL5UaMBTMyJnU90EgWh1Rz+MC9eFu4BuN/UwZjKQuY/1v3rM7HMfg==", + "dev": true, + "license": "MIT", + "dependencies": { + "define-data-property": "^1.1.4", + "es-errors": "^1.3.0", + "function-bind": "^1.1.2", + "get-intrinsic": "^1.2.4", + "gopd": "^1.0.1", + "has-property-descriptors": "^1.0.2" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/set-function-name": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/set-function-name/-/set-function-name-2.0.2.tgz", + "integrity": "sha512-7PGFlmtwsEADb0WYyvCMa1t+yke6daIG4Wirafur5kcf+MhUnPms1UeR0CKQdTZD81yESwMHbtn+TR+dMviakQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "define-data-property": "^1.1.4", + "es-errors": "^1.3.0", + "functions-have-names": "^1.2.3", + "has-property-descriptors": "^1.0.2" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/set-proto": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/set-proto/-/set-proto-1.0.0.tgz", + "integrity": "sha512-RJRdvCo6IAnPdsvP/7m6bsQqNnn1FCBX5ZNtFL98MmFF/4xAIJTIg1YbHW5DC2W5SKZanrC6i4HsJqlajw/dZw==", + "dev": true, + "license": "MIT", + "dependencies": { + "dunder-proto": "^1.0.1", + "es-errors": "^1.3.0", + "es-object-atoms": "^1.0.0" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/setprototypeof": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/setprototypeof/-/setprototypeof-1.2.0.tgz", + "integrity": "sha512-E5LDX7Wrp85Kil5bhZv46j8jOeboKq5JMmYM3gVGdGH8xFpPWXUMsNrlODCrkoxMEeNi/XZIwuRvY4XNwYMJpw==", + "license": "ISC" + }, + "node_modules/shadcn": { + "version": "4.0.8", + "resolved": "https://registry.npmjs.org/shadcn/-/shadcn-4.0.8.tgz", + "integrity": "sha512-DVAyeo95TQ/OvaHugLm5V0Dqz3al+dnoP3mZdWWxKJ33IYG1jN5B3sGZyNaYsfzm7JsWokfksSzDl83LnmMing==", + "license": "MIT", + "dependencies": { + "@babel/core": "^7.28.0", + "@babel/parser": "^7.28.0", + "@babel/plugin-transform-typescript": "^7.28.0", + "@babel/preset-typescript": "^7.27.1", + "@dotenvx/dotenvx": "^1.48.4", + "@modelcontextprotocol/sdk": "^1.26.0", + "@types/validate-npm-package-name": "^4.0.2", + "browserslist": "^4.26.2", + "commander": "^14.0.0", + "cosmiconfig": "^9.0.0", + "dedent": "^1.6.0", + "deepmerge": "^4.3.1", + "diff": "^8.0.2", + "execa": "^9.6.0", + "fast-glob": "^3.3.3", + "fs-extra": "^11.3.1", + "fuzzysort": "^3.1.0", + "https-proxy-agent": "^7.0.6", + "kleur": "^4.1.5", + "msw": "^2.10.4", + "node-fetch": "^3.3.2", + "open": "^11.0.0", + "ora": "^8.2.0", + "postcss": "^8.5.6", + "postcss-selector-parser": "^7.1.0", + "prompts": "^2.4.2", + "recast": "^0.23.11", + "stringify-object": "^5.0.0", + "tailwind-merge": "^3.0.1", + "ts-morph": "^26.0.0", + "tsconfig-paths": "^4.2.0", + "validate-npm-package-name": "^7.0.1", + "zod": "^3.24.1", + "zod-to-json-schema": "^3.24.6" + }, + "bin": { + "shadcn": "dist/index.js" + } + }, + "node_modules/shadcn/node_modules/fast-glob": { + "version": "3.3.3", + "resolved": "https://registry.npmjs.org/fast-glob/-/fast-glob-3.3.3.tgz", + "integrity": "sha512-7MptL8U0cqcFdzIzwOTHoilX9x5BrNqye7Z/LuC7kCMRio1EMSyqRK3BEAUD7sXRq4iT4AzTVuZdhgQ2TCvYLg==", + "license": "MIT", + "dependencies": { + "@nodelib/fs.stat": "^2.0.2", + "@nodelib/fs.walk": "^1.2.3", + "glob-parent": "^5.1.2", + "merge2": "^1.3.0", + "micromatch": "^4.0.8" + }, + "engines": { + "node": ">=8.6.0" + } + }, + "node_modules/shadcn/node_modules/glob-parent": { + "version": "5.1.2", + "resolved": "https://registry.npmjs.org/glob-parent/-/glob-parent-5.1.2.tgz", + "integrity": "sha512-AOIgSQCepiJYwP3ARnGx+5VnTu2HBYdzbGP45eLw1vr3zB3vZLeyed1sC9hnbcOc9/SrMyM5RPQrkGz4aS9Zow==", + "license": "ISC", + "dependencies": { + "is-glob": "^4.0.1" + }, + "engines": { + "node": ">= 6" + } + }, + "node_modules/shadcn/node_modules/tsconfig-paths": { + "version": "4.2.0", + "resolved": "https://registry.npmjs.org/tsconfig-paths/-/tsconfig-paths-4.2.0.tgz", + "integrity": "sha512-NoZ4roiN7LnbKn9QqE1amc9DJfzvZXxF4xDavcOWt1BPkdx+m+0gJuPM+S0vCe7zTJMYUP0R8pO2XMr+Y8oLIg==", + "license": "MIT", + "dependencies": { + "json5": "^2.2.2", + "minimist": "^1.2.6", + "strip-bom": "^3.0.0" + }, + "engines": { + "node": ">=6" + } + }, + "node_modules/shadcn/node_modules/zod": { + "version": "3.25.76", + "resolved": "https://registry.npmjs.org/zod/-/zod-3.25.76.tgz", + "integrity": "sha512-gzUt/qt81nXsFGKIFcC3YnfEAx5NkunCfnDlvuBSSFS02bcXu4Lmea0AFIUwbLWxWPx3d9p8S5QoaujKcNQxcQ==", + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/colinhacks" + } + }, + "node_modules/sharp": { + "version": "0.34.5", + "resolved": "https://registry.npmjs.org/sharp/-/sharp-0.34.5.tgz", + "integrity": "sha512-Ou9I5Ft9WNcCbXrU9cMgPBcCK8LiwLqcbywW3t4oDV37n1pzpuNLsYiAV8eODnjbtQlSDwZ2cUEeQz4E54Hltg==", + "hasInstallScript": true, + "license": "Apache-2.0", + "optional": true, + "dependencies": { + "@img/colour": "^1.0.0", + "detect-libc": "^2.1.2", + "semver": "^7.7.3" + }, + "engines": { + "node": "^18.17.0 || ^20.3.0 || >=21.0.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-darwin-arm64": "0.34.5", + "@img/sharp-darwin-x64": "0.34.5", + "@img/sharp-libvips-darwin-arm64": "1.2.4", + "@img/sharp-libvips-darwin-x64": "1.2.4", + "@img/sharp-libvips-linux-arm": "1.2.4", + "@img/sharp-libvips-linux-arm64": "1.2.4", + "@img/sharp-libvips-linux-ppc64": "1.2.4", + "@img/sharp-libvips-linux-riscv64": "1.2.4", + "@img/sharp-libvips-linux-s390x": "1.2.4", + "@img/sharp-libvips-linux-x64": "1.2.4", + "@img/sharp-libvips-linuxmusl-arm64": "1.2.4", + "@img/sharp-libvips-linuxmusl-x64": "1.2.4", + "@img/sharp-linux-arm": "0.34.5", + "@img/sharp-linux-arm64": "0.34.5", + "@img/sharp-linux-ppc64": "0.34.5", + "@img/sharp-linux-riscv64": "0.34.5", + "@img/sharp-linux-s390x": "0.34.5", + "@img/sharp-linux-x64": "0.34.5", + "@img/sharp-linuxmusl-arm64": "0.34.5", + "@img/sharp-linuxmusl-x64": "0.34.5", + "@img/sharp-wasm32": "0.34.5", + "@img/sharp-win32-arm64": "0.34.5", + "@img/sharp-win32-ia32": "0.34.5", + "@img/sharp-win32-x64": "0.34.5" + } + }, + "node_modules/sharp/node_modules/semver": { + "version": "7.7.4", + "resolved": "https://registry.npmjs.org/semver/-/semver-7.7.4.tgz", + "integrity": "sha512-vFKC2IEtQnVhpT78h1Yp8wzwrf8CM+MzKMHGJZfBtzhZNycRFnXsHk6E5TxIkkMsgNS7mdX3AGB7x2QM2di4lA==", + "license": "ISC", + "optional": true, + "bin": { + "semver": "bin/semver.js" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/shebang-command": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/shebang-command/-/shebang-command-2.0.0.tgz", + "integrity": "sha512-kHxr2zZpYtdmrN1qDjrrX/Z1rR1kG8Dx+gkpK1G4eXmvXswmcE1hTWBWYUzlraYw1/yZp6YuDY77YtvbN0dmDA==", + "license": "MIT", + "dependencies": { + "shebang-regex": "^3.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/shebang-regex": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/shebang-regex/-/shebang-regex-3.0.0.tgz", + "integrity": "sha512-7++dFhtcx3353uBaq8DDR4NuxBetBzC7ZQOhmTQInHEd6bSrXdiEyzCvG07Z44UYdLShWUyXt5M/yhz8ekcb1A==", + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/side-channel": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/side-channel/-/side-channel-1.1.0.tgz", + "integrity": "sha512-ZX99e6tRweoUXqR+VBrslhda51Nh5MTQwou5tnUDgbtyM0dBgmhEDtWGP/xbKn6hqfPRHujUNwz5fy/wbbhnpw==", + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0", + "object-inspect": "^1.13.3", + "side-channel-list": "^1.0.0", + "side-channel-map": "^1.0.1", + "side-channel-weakmap": "^1.0.2" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/side-channel-list": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/side-channel-list/-/side-channel-list-1.0.0.tgz", + "integrity": "sha512-FCLHtRD/gnpCiCHEiJLOwdmFP+wzCmDEkc9y7NsYxeF4u7Btsn1ZuwgwJGxImImHicJArLP4R0yX4c2KCrMrTA==", + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0", + "object-inspect": "^1.13.3" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/side-channel-map": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/side-channel-map/-/side-channel-map-1.0.1.tgz", + "integrity": "sha512-VCjCNfgMsby3tTdo02nbjtM/ewra6jPHmpThenkTYh8pG9ucZ/1P8So4u4FGBek/BjpOVsDCMoLA/iuBKIFXRA==", + "license": "MIT", + "dependencies": { + "call-bound": "^1.0.2", + "es-errors": "^1.3.0", + "get-intrinsic": "^1.2.5", + "object-inspect": "^1.13.3" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/side-channel-weakmap": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/side-channel-weakmap/-/side-channel-weakmap-1.0.2.tgz", + "integrity": "sha512-WPS/HvHQTYnHisLo9McqBHOJk2FkHO/tlpvldyrnem4aeQp4hai3gythswg6p01oSoTl58rcpiFAjF2br2Ak2A==", + "license": "MIT", + "dependencies": { + "call-bound": "^1.0.2", + "es-errors": "^1.3.0", + "get-intrinsic": "^1.2.5", + "object-inspect": "^1.13.3", + "side-channel-map": "^1.0.1" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/siginfo": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/siginfo/-/siginfo-2.0.0.tgz", + "integrity": "sha512-ybx0WO1/8bSBLEWXZvEd7gMW3Sn3JFlW3TvX1nREbDLRNQNaeNN8WK0meBwPdAaOI7TtRRRJn/Es1zhrrCHu7g==", + "dev": true, + "license": "ISC" + }, + "node_modules/signal-exit": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/signal-exit/-/signal-exit-4.1.0.tgz", + "integrity": "sha512-bzyZ1e88w9O1iNJbKnOlvYTrWPDl46O1bG0D3XInv+9tkPrxrN8jUUTiFlDkkmKWgn1M6CfIA13SuGqOa9Korw==", + "license": "ISC", + "engines": { + "node": ">=14" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/simple-wcswidth": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/simple-wcswidth/-/simple-wcswidth-1.1.2.tgz", + "integrity": "sha512-j7piyCjAeTDSjzTSQ7DokZtMNwNlEAyxqSZeCS+CXH7fJ4jx3FuJ/mTW3mE+6JLs4VJBbcll0Kjn+KXI5t21Iw==", + "license": "MIT" + }, + "node_modules/sisteransi": { + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/sisteransi/-/sisteransi-1.0.5.tgz", + "integrity": "sha512-bLGGlR1QxBcynn2d5YmDX4MGjlZvy2MRBDRNHLJ8VI6l6+9FUiyTFNJ0IveOSP0bcXgVDPRcfGqA0pjaqUpfVg==", + "license": "MIT" + }, + "node_modules/slice-ansi": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/slice-ansi/-/slice-ansi-4.0.0.tgz", + "integrity": "sha512-qMCMfhY040cVHT43K9BFygqYbUPFZKHOg7K73mtTWJRb8pyP3fzf4Ixd5SzdEJQ6MRUg/WBnOLxghZtKKurENQ==", + "license": "MIT", + "dependencies": { + "ansi-styles": "^4.0.0", + "astral-regex": "^2.0.0", + "is-fullwidth-code-point": "^3.0.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/chalk/slice-ansi?sponsor=1" + } + }, + "node_modules/source-map": { + "version": "0.6.1", + "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.6.1.tgz", + "integrity": "sha512-UjgapumWlbMhkBgzT7Ykc5YXUT46F0iKu8SGXq0bcwP5dz/h0Plj6enJqjz1Zbq2l5WaqYnrVbwWOWMyF3F47g==", + "license": "BSD-3-Clause", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/source-map-js": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.2.1.tgz", + "integrity": "sha512-UXWMKhLOwVKb728IUtQPXxfYU+usdybtUrK/8uGE8CQMvrhOpwvzDBwj0QhSL7MQc7vIsISBG8VQ8+IDQxpfQA==", + "license": "BSD-3-Clause", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/split2": { + "version": "4.2.0", + "resolved": "https://registry.npmjs.org/split2/-/split2-4.2.0.tgz", + "integrity": "sha512-UcjcJOWknrNkF6PLX83qcHM6KHgVKNkV62Y8a5uYDVv9ydGQVwAHMKqHdJje1VTWpljG0WYpCDhrCdAOYH4TWg==", + "license": "ISC", + "engines": { + "node": ">= 10.x" + } + }, + "node_modules/sqlstring": { + "version": "2.3.3", + "resolved": "https://registry.npmjs.org/sqlstring/-/sqlstring-2.3.3.tgz", + "integrity": "sha512-qC9iz2FlN7DQl3+wjwn3802RTyjCx7sDvfQEXchwa6CWOx07/WVfh91gBmQ9fahw8snwGEWU3xGzOt4tFyHLxg==", + "devOptional": true, + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/stable-hash": { + "version": "0.0.5", + "resolved": "https://registry.npmjs.org/stable-hash/-/stable-hash-0.0.5.tgz", + "integrity": "sha512-+L3ccpzibovGXFK+Ap/f8LOS0ahMrHTf3xu7mMLSpEGU0EO9ucaysSylKo9eRDFNhWve/y275iPmIZ4z39a9iA==", + "dev": true, + "license": "MIT" + }, + "node_modules/stackback": { + "version": "0.0.2", + "resolved": "https://registry.npmjs.org/stackback/-/stackback-0.0.2.tgz", + "integrity": "sha512-1XMJE5fQo1jGH6Y/7ebnwPOBEkIEnT4QF32d5R1+VXdXveM0IBMJt8zfaxX1P3QhVwrYe+576+jkANtSS2mBbw==", + "dev": true, + "license": "MIT" + }, + "node_modules/statuses": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/statuses/-/statuses-2.0.2.tgz", + "integrity": "sha512-DvEy55V3DB7uknRo+4iOGT5fP1slR8wQohVdknigZPMpMstaKJQWhwiYBACJE3Ul2pTnATihhBYnRhZQHGBiRw==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/std-env": { + "version": "3.10.0", + "resolved": "https://registry.npmjs.org/std-env/-/std-env-3.10.0.tgz", + "integrity": "sha512-5GS12FdOZNliM5mAOxFRg7Ir0pWz8MdpYm6AY6VPkGpbA7ZzmbzNcBJQ0GPvvyWgcY7QAhCgf9Uy89I03faLkg==", + "devOptional": true, + "license": "MIT" + }, + "node_modules/stdin-discarder": { + "version": "0.2.2", + "resolved": "https://registry.npmjs.org/stdin-discarder/-/stdin-discarder-0.2.2.tgz", + "integrity": "sha512-UhDfHmA92YAlNnCfhmq0VeNL5bDbiZGg7sZ2IvPsXubGkiNa9EC+tUTsjBRsYUAz87btI6/1wf4XoVvQ3uRnmQ==", + "license": "MIT", + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/stop-iteration-iterator": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/stop-iteration-iterator/-/stop-iteration-iterator-1.1.0.tgz", + "integrity": "sha512-eLoXW/DHyl62zxY4SCaIgnRhuMr6ri4juEYARS8E6sCEqzKpOiE521Ucofdx+KnDZl5xmvGYaaKCk5FEOxJCoQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0", + "internal-slot": "^1.1.0" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/strict-event-emitter": { + "version": "0.5.1", + "resolved": "https://registry.npmjs.org/strict-event-emitter/-/strict-event-emitter-0.5.1.tgz", + "integrity": "sha512-vMgjE/GGEPEFnhFub6pa4FmJBRBVOLpIII2hvCZ8Kzb7K0hlHo7mQv6xYrBvCL2LtAIBwFUK8wvuJgTVSQ5MFQ==", + "license": "MIT" + }, + "node_modules/string_decoder": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.3.0.tgz", + "integrity": "sha512-hkRX8U1WjJFd8LsDJ2yQ/wWWxaopEsABU1XfkM8A+j0+85JAGppt16cr1Whg6KIbb4okU6Mql6BOj+uup/wKeA==", + "license": "MIT", + "dependencies": { + "safe-buffer": "~5.2.0" + } + }, + "node_modules/string-width": { + "version": "7.2.0", + "resolved": "https://registry.npmjs.org/string-width/-/string-width-7.2.0.tgz", + "integrity": "sha512-tsaTIkKW9b4N+AEj+SVA+WhJzV7/zMhcSu78mLKWSk7cXMOSHsBKFWUs0fWwq8QyK3MgJBQRX6Gbi4kYbdvGkQ==", + "license": "MIT", + "dependencies": { + "emoji-regex": "^10.3.0", + "get-east-asian-width": "^1.0.0", + "strip-ansi": "^7.1.0" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/string-width/node_modules/emoji-regex": { + "version": "10.6.0", + "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-10.6.0.tgz", + "integrity": "sha512-toUI84YS5YmxW219erniWD0CIVOo46xGKColeNQRgOzDorgBi1v4D71/OFzgD9GO2UGKIv1C3Sp8DAn0+j5w7A==", + "license": "MIT" + }, + "node_modules/string.prototype.includes": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/string.prototype.includes/-/string.prototype.includes-2.0.1.tgz", + "integrity": "sha512-o7+c9bW6zpAdJHTtujeePODAhkuicdAryFsfVKwA+wGw89wJ4GTY484WTucM9hLtDEOpOvI+aHnzqnC5lHp4Rg==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bind": "^1.0.7", + "define-properties": "^1.2.1", + "es-abstract": "^1.23.3" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/string.prototype.matchall": { + "version": "4.0.12", + "resolved": "https://registry.npmjs.org/string.prototype.matchall/-/string.prototype.matchall-4.0.12.tgz", + "integrity": "sha512-6CC9uyBL+/48dYizRf7H7VAYCMCNTBeM78x/VTUe9bFEaxBepPJDa1Ow99LqI/1yF7kuy7Q3cQsYMrcjGUcskA==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bind": "^1.0.8", + "call-bound": "^1.0.3", + "define-properties": "^1.2.1", + "es-abstract": "^1.23.6", + "es-errors": "^1.3.0", + "es-object-atoms": "^1.0.0", + "get-intrinsic": "^1.2.6", + "gopd": "^1.2.0", + "has-symbols": "^1.1.0", + "internal-slot": "^1.1.0", + "regexp.prototype.flags": "^1.5.3", + "set-function-name": "^2.0.2", + "side-channel": "^1.1.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/string.prototype.repeat": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/string.prototype.repeat/-/string.prototype.repeat-1.0.0.tgz", + "integrity": "sha512-0u/TldDbKD8bFCQ/4f5+mNRrXwZ8hg2w7ZR8wa16e8z9XpePWl3eGEcUD0OXpEH/VJH/2G3gjUtR3ZOiBe2S/w==", + "dev": true, + "license": "MIT", + "dependencies": { + "define-properties": "^1.1.3", + "es-abstract": "^1.17.5" + } + }, + "node_modules/string.prototype.trim": { + "version": "1.2.10", + "resolved": "https://registry.npmjs.org/string.prototype.trim/-/string.prototype.trim-1.2.10.tgz", + "integrity": "sha512-Rs66F0P/1kedk5lyYyH9uBzuiI/kNRmwJAR9quK6VOtIpZ2G+hMZd+HQbbv25MgCA6gEffoMZYxlTod4WcdrKA==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bind": "^1.0.8", + "call-bound": "^1.0.2", + "define-data-property": "^1.1.4", + "define-properties": "^1.2.1", + "es-abstract": "^1.23.5", + "es-object-atoms": "^1.0.0", + "has-property-descriptors": "^1.0.2" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/string.prototype.trimend": { + "version": "1.0.9", + "resolved": "https://registry.npmjs.org/string.prototype.trimend/-/string.prototype.trimend-1.0.9.tgz", + "integrity": "sha512-G7Ok5C6E/j4SGfyLCloXTrngQIQU3PWtXGst3yM7Bea9FRURf1S42ZHlZZtsNque2FN2PoUhfZXYLNWwEr4dLQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bind": "^1.0.8", + "call-bound": "^1.0.2", + "define-properties": "^1.2.1", + "es-object-atoms": "^1.0.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/string.prototype.trimstart": { + "version": "1.0.8", + "resolved": "https://registry.npmjs.org/string.prototype.trimstart/-/string.prototype.trimstart-1.0.8.tgz", + "integrity": "sha512-UXSH262CSZY1tfu3G3Secr6uGLCFVPMhIqHjlgCUtCCcgihYc/xKs9djMTMUOb2j1mVSeU8EU6NWc/iQKU6Gfg==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bind": "^1.0.7", + "define-properties": "^1.2.1", + "es-object-atoms": "^1.0.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/stringify-object": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/stringify-object/-/stringify-object-5.0.0.tgz", + "integrity": "sha512-zaJYxz2FtcMb4f+g60KsRNFOpVMUyuJgA51Zi5Z1DOTC3S59+OQiVOzE9GZt0x72uBGWKsQIuBKeF9iusmKFsg==", + "license": "BSD-2-Clause", + "dependencies": { + "get-own-enumerable-keys": "^1.0.0", + "is-obj": "^3.0.0", + "is-regexp": "^3.1.0" + }, + "engines": { + "node": ">=14.16" + }, + "funding": { + "url": "https://github.com/yeoman/stringify-object?sponsor=1" + } + }, + "node_modules/strip-ansi": { + "version": "7.2.0", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-7.2.0.tgz", + "integrity": "sha512-yDPMNjp4WyfYBkHnjIRLfca1i6KMyGCtsVgoKe/z1+6vukgaENdgGBZt+ZmKPc4gavvEZ5OgHfHdrazhgNyG7w==", + "license": "MIT", + "dependencies": { + "ansi-regex": "^6.2.2" + }, + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/chalk/strip-ansi?sponsor=1" + } + }, + "node_modules/strip-bom": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/strip-bom/-/strip-bom-3.0.0.tgz", + "integrity": "sha512-vavAMRXOgBVNF6nyEEmL3DBK19iRpDcoIwW+swQ+CbGiu7lju6t+JklA1MHweoWtadgt4ISVUsXLyDq34ddcwA==", + "license": "MIT", + "engines": { + "node": ">=4" + } + }, + "node_modules/strip-final-newline": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/strip-final-newline/-/strip-final-newline-4.0.0.tgz", + "integrity": "sha512-aulFJcD6YK8V1G7iRB5tigAP4TsHBZZrOV8pjV++zdUwmeV8uzbY7yn6h9MswN62adStNZFuCIx4haBnRuMDaw==", + "license": "MIT", + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/strip-json-comments": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/strip-json-comments/-/strip-json-comments-3.1.1.tgz", + "integrity": "sha512-6fPc+R4ihwqP6N/aIv2f1gMH8lOVtWQHoqC4yK6oSDVVocumAsfCqjkXnqiYMhmMwS/mEHLp7Vehlt3ql6lEig==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/styled-jsx": { + "version": "5.1.6", + "resolved": "https://registry.npmjs.org/styled-jsx/-/styled-jsx-5.1.6.tgz", + "integrity": "sha512-qSVyDTeMotdvQYoHWLNGwRFJHC+i+ZvdBRYosOFgC+Wg1vx4frN2/RG/NA7SYqqvKNLf39P2LSRA2pu6n0XYZA==", + "license": "MIT", + "dependencies": { + "client-only": "0.0.1" + }, + "engines": { + "node": ">= 12.0.0" + }, + "peerDependencies": { + "react": ">= 16.8.0 || 17.x.x || ^18.0.0-0 || ^19.0.0-0" + }, + "peerDependenciesMeta": { + "@babel/core": { + "optional": true + }, + "babel-plugin-macros": { + "optional": true + } + } + }, + "node_modules/supports-color": { + "version": "7.2.0", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-7.2.0.tgz", + "integrity": "sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw==", + "dev": true, + "license": "MIT", + "dependencies": { + "has-flag": "^4.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/supports-preserve-symlinks-flag": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/supports-preserve-symlinks-flag/-/supports-preserve-symlinks-flag-1.0.0.tgz", + "integrity": "sha512-ot0WnXS9fgdkgIcePe6RHNk1WA8+muPa6cSjeR3V8K27q9BB1rTE3R1p7Hv0z1ZyAc8s6Vvv8DIyWf681MAt0w==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/tabbable": { + "version": "6.4.0", + "resolved": "https://registry.npmjs.org/tabbable/-/tabbable-6.4.0.tgz", + "integrity": "sha512-05PUHKSNE8ou2dwIxTngl4EzcnsCDZGJ/iCLtDflR/SHB/ny14rXc+qU5P4mG9JkusiV7EivzY9Mhm55AzAvCg==", + "license": "MIT" + }, + "node_modules/tagged-tag": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/tagged-tag/-/tagged-tag-1.0.0.tgz", + "integrity": "sha512-yEFYrVhod+hdNyx7g5Bnkkb0G6si8HJurOoOEgC8B/O0uXLHlaey/65KRv6cuWBNhBgHKAROVpc7QyYqE5gFng==", + "license": "MIT", + "engines": { + "node": ">=20" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/tailwind-merge": { + "version": "3.5.0", + "resolved": "https://registry.npmjs.org/tailwind-merge/-/tailwind-merge-3.5.0.tgz", + "integrity": "sha512-I8K9wewnVDkL1NTGoqWmVEIlUcB9gFriAEkXkfCjX5ib8ezGxtR3xD7iZIxrfArjEsH7F1CHD4RFUtxefdqV/A==", + "license": "MIT", + "funding": { + "type": "github", + "url": "https://github.com/sponsors/dcastil" + } + }, + "node_modules/tailwindcss": { + "version": "4.2.1", + "resolved": "https://registry.npmjs.org/tailwindcss/-/tailwindcss-4.2.1.tgz", + "integrity": "sha512-/tBrSQ36vCleJkAOsy9kbNTgaxvGbyOamC30PRePTQe/o1MFwEKHQk4Cn7BNGaPtjp+PuUrByJehM1hgxfq4sw==", + "dev": true, + "license": "MIT" + }, + "node_modules/tapable": { + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/tapable/-/tapable-2.3.0.tgz", + "integrity": "sha512-g9ljZiwki/LfxmQADO3dEY1CbpmXT5Hm2fJ+QaGKwSXUylMybePR7/67YW7jOrrvjEgL1Fmz5kzyAjWVWLlucg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/webpack" + } + }, + "node_modules/tar": { + "version": "7.5.12", + "resolved": "https://registry.npmjs.org/tar/-/tar-7.5.12.tgz", + "integrity": "sha512-9TsuLcdhOn4XztcQqhNyq1KOwOOED/3k58JAvtULiYqbO8B/0IBAAIE1hj0Svmm58k27TmcigyDI0deMlgG3uw==", + "license": "BlueOak-1.0.0", + "dependencies": { + "@isaacs/fs-minipass": "^4.0.0", + "chownr": "^3.0.0", + "minipass": "^7.1.2", + "minizlib": "^3.1.0", + "yallist": "^5.0.0" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/tar/node_modules/yallist": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/yallist/-/yallist-5.0.0.tgz", + "integrity": "sha512-YgvUTfwqyc7UXVMrB+SImsVYSmTS8X/tSrtdNZMImM+n7+QTriRXyXim0mBrTXNeqzVF0KWGgHPeiyViFFrNDw==", + "license": "BlueOak-1.0.0", + "engines": { + "node": ">=18" + } + }, + "node_modules/through2": { + "version": "4.0.2", + "resolved": "https://registry.npmjs.org/through2/-/through2-4.0.2.tgz", + "integrity": "sha512-iOqSav00cVxEEICeD7TjLB1sueEL+81Wpzp2bY17uZjZN0pWZPuo4suZ/61VujxmqSGFfgOcNuTZ85QJwNZQpw==", + "license": "MIT", + "dependencies": { + "readable-stream": "3" + } + }, + "node_modules/tiny-invariant": { + "version": "1.3.3", + "resolved": "https://registry.npmjs.org/tiny-invariant/-/tiny-invariant-1.3.3.tgz", + "integrity": "sha512-+FbBPE1o9QAYvviau/qC5SE3caw21q3xkvWKBtja5vgqOWIHHJ3ioaq1VPfn/Szqctz2bU/oYeKd9/z5BL+PVg==", + "license": "MIT" + }, + "node_modules/tinybench": { + "version": "2.9.0", + "resolved": "https://registry.npmjs.org/tinybench/-/tinybench-2.9.0.tgz", + "integrity": "sha512-0+DUvqWMValLmha6lr4kD8iAMK1HzV0/aKnCtWb9v9641TnP/MFb7Pc2bxoxQjTXAErryXVgUOfv2YqNllqGeg==", + "dev": true, + "license": "MIT" + }, + "node_modules/tinyexec": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/tinyexec/-/tinyexec-1.0.4.tgz", + "integrity": "sha512-u9r3uZC0bdpGOXtlxUIdwf9pkmvhqJdrVCH9fapQtgy/OeTTMZ1nqH7agtvEfmGui6e1XxjcdrlxvxJvc3sMqw==", + "devOptional": true, + "license": "MIT", + "engines": { + "node": ">=18" + } + }, + "node_modules/tinyglobby": { + "version": "0.2.15", + "resolved": "https://registry.npmjs.org/tinyglobby/-/tinyglobby-0.2.15.tgz", + "integrity": "sha512-j2Zq4NyQYG5XMST4cbs02Ak8iJUdxRM0XI5QyxXuZOzKOINmWurp3smXu3y5wDcJrptwpSjgXHzIQxR0omXljQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "fdir": "^6.5.0", + "picomatch": "^4.0.3" + }, + "engines": { + "node": ">=12.0.0" + }, + "funding": { + "url": "https://github.com/sponsors/SuperchupuDev" + } + }, + "node_modules/tinyglobby/node_modules/fdir": { + "version": "6.5.0", + "resolved": "https://registry.npmjs.org/fdir/-/fdir-6.5.0.tgz", + "integrity": "sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12.0.0" + }, + "peerDependencies": { + "picomatch": "^3 || ^4" + }, + "peerDependenciesMeta": { + "picomatch": { + "optional": true + } + } + }, + "node_modules/tinyglobby/node_modules/picomatch": { + "version": "4.0.4", + "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.4.tgz", + "integrity": "sha512-QP88BAKvMam/3NxH6vj2o21R6MjxZUAd6nlwAS/pnGvN9IVLocLHxGYIzFhg6fUQ+5th6P4dv4eW9jX3DSIj7A==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/sponsors/jonschlinkert" + } + }, + "node_modules/tinyrainbow": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/tinyrainbow/-/tinyrainbow-3.1.0.tgz", + "integrity": "sha512-Bf+ILmBgretUrdJxzXM0SgXLZ3XfiaUuOj/IKQHuTXip+05Xn+uyEYdVg0kYDipTBcLrCVyUzAPz7QmArb0mmw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=14.0.0" + } + }, + "node_modules/tldts": { + "version": "7.0.26", + "resolved": "https://registry.npmjs.org/tldts/-/tldts-7.0.26.tgz", + "integrity": "sha512-WiGwQjr0qYdNNG8KpMKlSvpxz652lqa3Rd+/hSaDcY4Uo6SKWZq2LAF+hsAhUewTtYhXlorBKgNF3Kk8hnjGoQ==", + "license": "MIT", + "dependencies": { + "tldts-core": "^7.0.26" + }, + "bin": { + "tldts": "bin/cli.js" + } + }, + "node_modules/tldts-core": { + "version": "7.0.26", + "resolved": "https://registry.npmjs.org/tldts-core/-/tldts-core-7.0.26.tgz", + "integrity": "sha512-5WJ2SqFsv4G2Dwi7ZFVRnz6b2H1od39QME1lc2y5Ew3eWiZMAeqOAfWpRP9jHvhUl881406QtZTODvjttJs+ew==", + "license": "MIT" + }, + "node_modules/to-regex-range": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/to-regex-range/-/to-regex-range-5.0.1.tgz", + "integrity": "sha512-65P7iz6X5yEr1cwcgvQxbbIw7Uk3gOy5dIdtZ4rDveLqhrdJP+Li/Hx6tyK0NEb+2GCyneCMJiGqrADCSNk8sQ==", + "license": "MIT", + "dependencies": { + "is-number": "^7.0.0" + }, + "engines": { + "node": ">=8.0" + } + }, + "node_modules/toidentifier": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/toidentifier/-/toidentifier-1.0.1.tgz", + "integrity": "sha512-o5sSPKEkg/DIQNmH43V0/uerLrpzVedkUh8tGNvaeXpfpuwjKenlSox/2O/BTlZUtEe+JG7s5YhEz608PlAHRA==", + "license": "MIT", + "engines": { + "node": ">=0.6" + } + }, + "node_modules/tough-cookie": { + "version": "6.0.1", + "resolved": "https://registry.npmjs.org/tough-cookie/-/tough-cookie-6.0.1.tgz", + "integrity": "sha512-LktZQb3IeoUWB9lqR5EWTHgW/VTITCXg4D21M+lvybRVdylLrRMnqaIONLVb5mav8vM19m44HIcGq4qASeu2Qw==", + "license": "BSD-3-Clause", + "dependencies": { + "tldts": "^7.0.5" + }, + "engines": { + "node": ">=16" + } + }, + "node_modules/tr46": { + "version": "0.0.3", + "resolved": "https://registry.npmjs.org/tr46/-/tr46-0.0.3.tgz", + "integrity": "sha512-N3WMsuqV66lT30CrXNbEjx4GEwlow3v6rr4mCcv6prnfwhS01rkgyFdjPNBYd9br7LpXV1+Emh01fHnq2Gdgrw==", + "license": "MIT" + }, + "node_modules/tree-kill": { + "version": "1.2.2", + "resolved": "https://registry.npmjs.org/tree-kill/-/tree-kill-1.2.2.tgz", + "integrity": "sha512-L0Orpi8qGpRG//Nd+H90vFB+3iHnue1zSSGmNOOCh1GLJ7rUKVwV2HvijphGQS2UmhUZewS9VgvxYIdgr+fG1A==", + "license": "MIT", + "bin": { + "tree-kill": "cli.js" + } + }, + "node_modules/ts-algebra": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/ts-algebra/-/ts-algebra-2.0.0.tgz", + "integrity": "sha512-FPAhNPFMrkwz76P7cdjdmiShwMynZYN6SgOujD1urY4oNm80Ou9oMdmbR45LotcKOXoy7wSmHkRFE6Mxbrhefw==", + "license": "MIT" + }, + "node_modules/ts-api-utils": { + "version": "2.4.0", + "resolved": "https://registry.npmjs.org/ts-api-utils/-/ts-api-utils-2.4.0.tgz", + "integrity": "sha512-3TaVTaAv2gTiMB35i3FiGJaRfwb3Pyn/j3m/bfAvGe8FB7CF6u+LMYqYlDh7reQf7UNvoTvdfAqHGmPGOSsPmA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=18.12" + }, + "peerDependencies": { + "typescript": ">=4.8.4" + } + }, + "node_modules/ts-morph": { + "version": "26.0.0", + "resolved": "https://registry.npmjs.org/ts-morph/-/ts-morph-26.0.0.tgz", + "integrity": "sha512-ztMO++owQnz8c/gIENcM9XfCEzgoGphTv+nKpYNM1bgsdOVC/jRZuEBf6N+mLLDNg68Kl+GgUZfOySaRiG1/Ug==", + "license": "MIT", + "dependencies": { + "@ts-morph/common": "~0.27.0", + "code-block-writer": "^13.0.3" + } + }, + "node_modules/tsconfig-paths": { + "version": "3.15.0", + "resolved": "https://registry.npmjs.org/tsconfig-paths/-/tsconfig-paths-3.15.0.tgz", + "integrity": "sha512-2Ac2RgzDe/cn48GvOe3M+o82pEFewD3UPbyoUHHdKasHwJKjds4fLXWf/Ux5kATBKN20oaFGu+jbElp1pos0mg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/json5": "^0.0.29", + "json5": "^1.0.2", + "minimist": "^1.2.6", + "strip-bom": "^3.0.0" + } + }, + "node_modules/tsconfig-paths/node_modules/json5": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/json5/-/json5-1.0.2.tgz", + "integrity": "sha512-g1MWMLBiz8FKi1e4w0UyVL3w+iJceWAFBAaBnnGKOpNa5f8TLktkbre1+s6oICydWAm+HRUGTmI+//xv2hvXYA==", + "dev": true, + "license": "MIT", + "dependencies": { + "minimist": "^1.2.0" + }, + "bin": { + "json5": "lib/cli.js" + } + }, + "node_modules/tslib": { + "version": "2.8.1", + "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.8.1.tgz", + "integrity": "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==", + "license": "0BSD" + }, + "node_modules/tsx": { + "version": "4.21.0", + "resolved": "https://registry.npmjs.org/tsx/-/tsx-4.21.0.tgz", + "integrity": "sha512-5C1sg4USs1lfG0GFb2RLXsdpXqBSEhAaA/0kPL01wxzpMqLILNxIxIOKiILz+cdg/pLnOUxFYOR5yhHU666wbw==", + "dev": true, + "license": "MIT", + "dependencies": { + "esbuild": "~0.27.0", + "get-tsconfig": "^4.7.5" + }, + "bin": { + "tsx": "dist/cli.mjs" + }, + "engines": { + "node": ">=18.0.0" + }, + "optionalDependencies": { + "fsevents": "~2.3.3" + } + }, + "node_modules/tw-animate-css": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/tw-animate-css/-/tw-animate-css-1.4.0.tgz", + "integrity": "sha512-7bziOlRqH0hJx80h/3mbicLW7o8qLsH5+RaLR2t+OHM3D0JlWGODQKQ4cxbK7WlvmUxpcj6Kgu6EKqjrGFe3QQ==", + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/Wombosvideo" + } + }, + "node_modules/type-check": { + "version": "0.4.0", + "resolved": "https://registry.npmjs.org/type-check/-/type-check-0.4.0.tgz", + "integrity": "sha512-XleUoc9uwGXqjWwXaUTZAmzMcFZ5858QA2vvx1Ur5xIcixXIP+8LnFDgRplU30us6teqdlskFfu+ae4K79Ooew==", + "dev": true, + "license": "MIT", + "dependencies": { + "prelude-ls": "^1.2.1" + }, + "engines": { + "node": ">= 0.8.0" + } + }, + "node_modules/type-fest": { + "version": "5.4.4", + "resolved": "https://registry.npmjs.org/type-fest/-/type-fest-5.4.4.tgz", + "integrity": "sha512-JnTrzGu+zPV3aXIUhnyWJj4z/wigMsdYajGLIYakqyOW1nPllzXEJee0QQbHj+CTIQtXGlAjuK0UY+2xTyjVAw==", + "license": "(MIT OR CC0-1.0)", + "dependencies": { + "tagged-tag": "^1.0.0" + }, + "engines": { + "node": ">=20" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/type-is": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/type-is/-/type-is-2.0.1.tgz", + "integrity": "sha512-OZs6gsjF4vMp32qrCbiVSkrFmXtG/AZhY3t0iAMrMBiAZyV9oALtXO8hsrHbMXF9x6L3grlFuwW2oAz7cav+Gw==", + "license": "MIT", + "dependencies": { + "content-type": "^1.0.5", + "media-typer": "^1.1.0", + "mime-types": "^3.0.0" + }, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/typed-array-buffer": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/typed-array-buffer/-/typed-array-buffer-1.0.3.tgz", + "integrity": "sha512-nAYYwfY3qnzX30IkA6AQZjVbtK6duGontcQm1WSG1MD94YLqK0515GNApXkoxKOWMusVssAHWLh9SeaoefYFGw==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bound": "^1.0.3", + "es-errors": "^1.3.0", + "is-typed-array": "^1.1.14" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/typed-array-byte-length": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/typed-array-byte-length/-/typed-array-byte-length-1.0.3.tgz", + "integrity": "sha512-BaXgOuIxz8n8pIq3e7Atg/7s+DpiYrxn4vdot3w9KbnBhcRQq6o3xemQdIfynqSeXeDrF32x+WvfzmOjPiY9lg==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bind": "^1.0.8", + "for-each": "^0.3.3", + "gopd": "^1.2.0", + "has-proto": "^1.2.0", + "is-typed-array": "^1.1.14" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/typed-array-byte-offset": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/typed-array-byte-offset/-/typed-array-byte-offset-1.0.4.tgz", + "integrity": "sha512-bTlAFB/FBYMcuX81gbL4OcpH5PmlFHqlCCpAl8AlEzMz5k53oNDvN8p1PNOWLEmI2x4orp3raOFB51tv9X+MFQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "available-typed-arrays": "^1.0.7", + "call-bind": "^1.0.8", + "for-each": "^0.3.3", + "gopd": "^1.2.0", + "has-proto": "^1.2.0", + "is-typed-array": "^1.1.15", + "reflect.getprototypeof": "^1.0.9" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/typed-array-length": { + "version": "1.0.7", + "resolved": "https://registry.npmjs.org/typed-array-length/-/typed-array-length-1.0.7.tgz", + "integrity": "sha512-3KS2b+kL7fsuk/eJZ7EQdnEmQoaho/r6KUef7hxvltNA5DR8NAUM+8wJMbJyZ4G9/7i3v5zPBIMN5aybAh2/Jg==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bind": "^1.0.7", + "for-each": "^0.3.3", + "gopd": "^1.0.1", + "is-typed-array": "^1.1.13", + "possible-typed-array-names": "^1.0.0", + "reflect.getprototypeof": "^1.0.6" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/typescript": { + "version": "5.9.3", + "resolved": "https://registry.npmjs.org/typescript/-/typescript-5.9.3.tgz", + "integrity": "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==", + "devOptional": true, + "license": "Apache-2.0", + "bin": { + "tsc": "bin/tsc", + "tsserver": "bin/tsserver" + }, + "engines": { + "node": ">=14.17" + } + }, + "node_modules/typescript-eslint": { + "version": "8.57.1", + "resolved": "https://registry.npmjs.org/typescript-eslint/-/typescript-eslint-8.57.1.tgz", + "integrity": "sha512-fLvZWf+cAGw3tqMCYzGIU6yR8K+Y9NT2z23RwOjlNFF2HwSB3KhdEFI5lSBv8tNmFkkBShSjsCjzx1vahZfISA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@typescript-eslint/eslint-plugin": "8.57.1", + "@typescript-eslint/parser": "8.57.1", + "@typescript-eslint/typescript-estree": "8.57.1", + "@typescript-eslint/utils": "8.57.1" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/typescript-eslint" + }, + "peerDependencies": { + "eslint": "^8.57.0 || ^9.0.0 || ^10.0.0", + "typescript": ">=4.8.4 <6.0.0" + } + }, + "node_modules/unbox-primitive": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/unbox-primitive/-/unbox-primitive-1.1.0.tgz", + "integrity": "sha512-nWJ91DjeOkej/TA8pXQ3myruKpKEYgqvpw9lz4OPHj/NWFNluYrjbz9j01CJ8yKQd2g4jFoOkINCTW2I5LEEyw==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bound": "^1.0.3", + "has-bigints": "^1.0.2", + "has-symbols": "^1.1.0", + "which-boxed-primitive": "^1.1.1" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/undici-types": { + "version": "6.21.0", + "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-6.21.0.tgz", + "integrity": "sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ==", + "license": "MIT" + }, + "node_modules/unicorn-magic": { + "version": "0.3.0", + "resolved": "https://registry.npmjs.org/unicorn-magic/-/unicorn-magic-0.3.0.tgz", + "integrity": "sha512-+QBBXBCvifc56fsbuxZQ6Sic3wqqc3WWaqxs58gvJrcOuN83HGTCwz3oS5phzU9LthRNE9VrJCFCLUgHeeFnfA==", + "license": "MIT", + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/universalify": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/universalify/-/universalify-2.0.1.tgz", + "integrity": "sha512-gptHNQghINnc/vTGIk0SOFGFNXw7JVrlRUtConJRlvaw6DuX0wO5Jeko9sWrMBhh+PsYAZ7oXAiOnf/UKogyiw==", + "license": "MIT", + "engines": { + "node": ">= 10.0.0" + } + }, + "node_modules/unpipe": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/unpipe/-/unpipe-1.0.0.tgz", + "integrity": "sha512-pjy2bYhSsufwWlKwPc+l3cN7+wuJlK6uz0YdJEOlQDbl6jo/YlPi4mb8agUkVC8BF7V8NuzeyPNqRksA3hztKQ==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/unrs-resolver": { + "version": "1.11.1", + "resolved": "https://registry.npmjs.org/unrs-resolver/-/unrs-resolver-1.11.1.tgz", + "integrity": "sha512-bSjt9pjaEBnNiGgc9rUiHGKv5l4/TGzDmYw3RhnkJGtLhbnnA/5qJj7x3dNDCRx/PJxu774LlH8lCOlB4hEfKg==", + "dev": true, + "hasInstallScript": true, + "license": "MIT", + "dependencies": { + "napi-postinstall": "^0.3.0" + }, + "funding": { + "url": "https://opencollective.com/unrs-resolver" + }, + "optionalDependencies": { + "@unrs/resolver-binding-android-arm-eabi": "1.11.1", + "@unrs/resolver-binding-android-arm64": "1.11.1", + "@unrs/resolver-binding-darwin-arm64": "1.11.1", + "@unrs/resolver-binding-darwin-x64": "1.11.1", + "@unrs/resolver-binding-freebsd-x64": "1.11.1", + "@unrs/resolver-binding-linux-arm-gnueabihf": "1.11.1", + "@unrs/resolver-binding-linux-arm-musleabihf": "1.11.1", + "@unrs/resolver-binding-linux-arm64-gnu": "1.11.1", + "@unrs/resolver-binding-linux-arm64-musl": "1.11.1", + "@unrs/resolver-binding-linux-ppc64-gnu": "1.11.1", + "@unrs/resolver-binding-linux-riscv64-gnu": "1.11.1", + "@unrs/resolver-binding-linux-riscv64-musl": "1.11.1", + "@unrs/resolver-binding-linux-s390x-gnu": "1.11.1", + "@unrs/resolver-binding-linux-x64-gnu": "1.11.1", + "@unrs/resolver-binding-linux-x64-musl": "1.11.1", + "@unrs/resolver-binding-wasm32-wasi": "1.11.1", + "@unrs/resolver-binding-win32-arm64-msvc": "1.11.1", + "@unrs/resolver-binding-win32-ia32-msvc": "1.11.1", + "@unrs/resolver-binding-win32-x64-msvc": "1.11.1" + } + }, + "node_modules/until-async": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/until-async/-/until-async-3.0.2.tgz", + "integrity": "sha512-IiSk4HlzAMqTUseHHe3VhIGyuFmN90zMTpD3Z3y8jeQbzLIq500MVM7Jq2vUAnTKAFPJrqwkzr6PoTcPhGcOiw==", + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/kettanaito" + } + }, + "node_modules/untildify": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/untildify/-/untildify-4.0.0.tgz", + "integrity": "sha512-KK8xQ1mkzZeg9inewmFVDNkg3l5LUhoq9kN6iWYB/CC9YMG8HA+c1Q8HwDe6dEX7kErrEVNVBO3fWsVq5iDgtw==", + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/update-browserslist-db": { + "version": "1.2.3", + "resolved": "https://registry.npmjs.org/update-browserslist-db/-/update-browserslist-db-1.2.3.tgz", + "integrity": "sha512-Js0m9cx+qOgDxo0eMiFGEueWztz+d4+M3rGlmKPT+T4IS/jP4ylw3Nwpu6cpTTP8R1MAC1kF4VbdLt3ARf209w==", + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/browserslist" + }, + { + "type": "tidelift", + "url": "https://tidelift.com/funding/github/npm/browserslist" + }, + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "dependencies": { + "escalade": "^3.2.0", + "picocolors": "^1.1.1" + }, + "bin": { + "update-browserslist-db": "cli.js" + }, + "peerDependencies": { + "browserslist": ">= 4.21.0" + } + }, + "node_modules/uri-js": { + "version": "4.4.1", + "resolved": "https://registry.npmjs.org/uri-js/-/uri-js-4.4.1.tgz", + "integrity": "sha512-7rKUyy33Q1yc98pQ1DAmLtwX109F7TIfWlW1Ydo8Wl1ii1SeHieeh0HHfPeL2fMXK6z0s8ecKs9frCuLJvndBg==", + "dev": true, + "license": "BSD-2-Clause", + "dependencies": { + "punycode": "^2.1.0" + } + }, + "node_modules/use-sync-external-store": { + "version": "1.6.0", + "resolved": "https://registry.npmjs.org/use-sync-external-store/-/use-sync-external-store-1.6.0.tgz", + "integrity": "sha512-Pp6GSwGP/NrPIrxVFAIkOQeyw8lFenOHijQWkUTrDvrF4ALqylP2C/KCkeS9dpUM3KvYRQhna5vt7IL95+ZQ9w==", + "license": "MIT", + "peerDependencies": { + "react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0" + } + }, + "node_modules/util-deprecate": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/util-deprecate/-/util-deprecate-1.0.2.tgz", + "integrity": "sha512-EPD5q1uXyFxJpCrLnCc1nHnq3gOa6DZBocAIiI2TaSCA7VCJ1UJDMagCzIkXNsUYfD1daK//LTEQ8xiIbrHtcw==", + "license": "MIT" + }, + "node_modules/uuid": { + "version": "10.0.0", + "resolved": "https://registry.npmjs.org/uuid/-/uuid-10.0.0.tgz", + "integrity": "sha512-8XkAphELsDnEGrDxUOHB3RGvXz6TeuYSGEZBOjtTtPm2lwhGBjLgOzLHB63IUWfBpNucQjND6d3AOudO+H3RWQ==", + "funding": [ + "https://github.com/sponsors/broofa", + "https://github.com/sponsors/ctavan" + ], + "license": "MIT", + "bin": { + "uuid": "dist/bin/uuid" + } + }, + "node_modules/valibot": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/valibot/-/valibot-1.2.0.tgz", + "integrity": "sha512-mm1rxUsmOxzrwnX5arGS+U4T25RdvpPjPN4yR0u9pUBov9+zGVtO84tif1eY4r6zWxVxu3KzIyknJy3rxfRZZg==", + "devOptional": true, + "license": "MIT", + "peerDependencies": { + "typescript": ">=5" + }, + "peerDependenciesMeta": { + "typescript": { + "optional": true + } + } + }, + "node_modules/validate-npm-package-name": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/validate-npm-package-name/-/validate-npm-package-name-7.0.2.tgz", + "integrity": "sha512-hVDIBwsRruT73PbK7uP5ebUt+ezEtCmzZz3F59BSr2F6OVFnJ/6h8liuvdLrQ88Xmnk6/+xGGuq+pG9WwTuy3A==", + "license": "ISC", + "engines": { + "node": "^20.17.0 || >=22.9.0" + } + }, + "node_modules/vary": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/vary/-/vary-1.1.2.tgz", + "integrity": "sha512-BNGbWLfd0eUPabhkXUVm0j8uuvREyTh5ovRa/dyow/BqAbZJyC+5fU+IzQOzmAKzYqYRAISoRhdQr3eIZ/PXqg==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/victory-vendor": { + "version": "37.3.6", + "resolved": "https://registry.npmjs.org/victory-vendor/-/victory-vendor-37.3.6.tgz", + "integrity": "sha512-SbPDPdDBYp+5MJHhBCAyI7wKM3d5ivekigc2Dk2s7pgbZ9wIgIBYGVw4zGHBml/qTFbexrofXW6Gu4noGxrOwQ==", + "license": "MIT AND ISC", + "dependencies": { + "@types/d3-array": "^3.0.3", + "@types/d3-ease": "^3.0.0", + "@types/d3-interpolate": "^3.0.1", + "@types/d3-scale": "^4.0.2", + "@types/d3-shape": "^3.1.0", + "@types/d3-time": "^3.0.0", + "@types/d3-timer": "^3.0.0", + "d3-array": "^3.1.6", + "d3-ease": "^3.0.1", + "d3-interpolate": "^3.0.1", + "d3-scale": "^4.0.2", + "d3-shape": "^3.1.0", + "d3-time": "^3.0.0", + "d3-timer": "^3.0.1" + } + }, + "node_modules/vite": { + "version": "8.0.0", + "resolved": "https://registry.npmjs.org/vite/-/vite-8.0.0.tgz", + "integrity": "sha512-fPGaRNj9Zytaf8LEiBhY7Z6ijnFKdzU/+mL8EFBaKr7Vw1/FWcTBAMW0wLPJAGMPX38ZPVCVgLceWiEqeoqL2Q==", + "dev": true, + "license": "MIT", + "dependencies": { + "@oxc-project/runtime": "0.115.0", + "lightningcss": "^1.32.0", + "picomatch": "^4.0.3", + "postcss": "^8.5.8", + "rolldown": "1.0.0-rc.9", + "tinyglobby": "^0.2.15" + }, + "bin": { + "vite": "bin/vite.js" + }, + "engines": { + "node": "^20.19.0 || >=22.12.0" + }, + "funding": { + "url": "https://github.com/vitejs/vite?sponsor=1" + }, + "optionalDependencies": { + "fsevents": "~2.3.3" + }, + "peerDependencies": { + "@types/node": "^20.19.0 || >=22.12.0", + "@vitejs/devtools": "^0.0.0-alpha.31", + "esbuild": "^0.27.0", + "jiti": ">=1.21.0", + "less": "^4.0.0", + "sass": "^1.70.0", + "sass-embedded": "^1.70.0", + "stylus": ">=0.54.8", + "sugarss": "^5.0.0", + "terser": "^5.16.0", + "tsx": "^4.8.1", + "yaml": "^2.4.2" + }, + "peerDependenciesMeta": { + "@types/node": { + "optional": true + }, + "@vitejs/devtools": { + "optional": true + }, + "esbuild": { + "optional": true + }, + "jiti": { + "optional": true + }, + "less": { + "optional": true + }, + "sass": { + "optional": true + }, + "sass-embedded": { + "optional": true + }, + "stylus": { + "optional": true + }, + "sugarss": { + "optional": true + }, + "terser": { + "optional": true + }, + "tsx": { + "optional": true + }, + "yaml": { + "optional": true + } + } + }, + "node_modules/vite/node_modules/lightningcss": { + "version": "1.32.0", + "resolved": "https://registry.npmjs.org/lightningcss/-/lightningcss-1.32.0.tgz", + "integrity": "sha512-NXYBzinNrblfraPGyrbPoD19C1h9lfI/1mzgWYvXUTe414Gz/X1FD2XBZSZM7rRTrMA8JL3OtAaGifrIKhQ5yQ==", + "dev": true, + "license": "MPL-2.0", + "dependencies": { + "detect-libc": "^2.0.3" + }, + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + }, + "optionalDependencies": { + "lightningcss-android-arm64": "1.32.0", + "lightningcss-darwin-arm64": "1.32.0", + "lightningcss-darwin-x64": "1.32.0", + "lightningcss-freebsd-x64": "1.32.0", + "lightningcss-linux-arm-gnueabihf": "1.32.0", + "lightningcss-linux-arm64-gnu": "1.32.0", + "lightningcss-linux-arm64-musl": "1.32.0", + "lightningcss-linux-x64-gnu": "1.32.0", + "lightningcss-linux-x64-musl": "1.32.0", + "lightningcss-win32-arm64-msvc": "1.32.0", + "lightningcss-win32-x64-msvc": "1.32.0" + } + }, + "node_modules/vite/node_modules/lightningcss-android-arm64": { + "version": "1.32.0", + "resolved": "https://registry.npmjs.org/lightningcss-android-arm64/-/lightningcss-android-arm64-1.32.0.tgz", + "integrity": "sha512-YK7/ClTt4kAK0vo6w3X+Pnm0D2cf2vPHbhOXdoNti1Ga0al1P4TBZhwjATvjNwLEBCnKvjJc2jQgHXH0NEwlAg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/vite/node_modules/lightningcss-darwin-arm64": { + "version": "1.32.0", + "resolved": "https://registry.npmjs.org/lightningcss-darwin-arm64/-/lightningcss-darwin-arm64-1.32.0.tgz", + "integrity": "sha512-RzeG9Ju5bag2Bv1/lwlVJvBE3q6TtXskdZLLCyfg5pt+HLz9BqlICO7LZM7VHNTTn/5PRhHFBSjk5lc4cmscPQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/vite/node_modules/lightningcss-darwin-x64": { + "version": "1.32.0", + "resolved": "https://registry.npmjs.org/lightningcss-darwin-x64/-/lightningcss-darwin-x64-1.32.0.tgz", + "integrity": "sha512-U+QsBp2m/s2wqpUYT/6wnlagdZbtZdndSmut/NJqlCcMLTWp5muCrID+K5UJ6jqD2BFshejCYXniPDbNh73V8w==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/vite/node_modules/lightningcss-freebsd-x64": { + "version": "1.32.0", + "resolved": "https://registry.npmjs.org/lightningcss-freebsd-x64/-/lightningcss-freebsd-x64-1.32.0.tgz", + "integrity": "sha512-JCTigedEksZk3tHTTthnMdVfGf61Fky8Ji2E4YjUTEQX14xiy/lTzXnu1vwiZe3bYe0q+SpsSH/CTeDXK6WHig==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/vite/node_modules/lightningcss-linux-arm-gnueabihf": { + "version": "1.32.0", + "resolved": "https://registry.npmjs.org/lightningcss-linux-arm-gnueabihf/-/lightningcss-linux-arm-gnueabihf-1.32.0.tgz", + "integrity": "sha512-x6rnnpRa2GL0zQOkt6rts3YDPzduLpWvwAF6EMhXFVZXD4tPrBkEFqzGowzCsIWsPjqSK+tyNEODUBXeeVHSkw==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/vite/node_modules/lightningcss-linux-arm64-gnu": { + "version": "1.32.0", + "resolved": "https://registry.npmjs.org/lightningcss-linux-arm64-gnu/-/lightningcss-linux-arm64-gnu-1.32.0.tgz", + "integrity": "sha512-0nnMyoyOLRJXfbMOilaSRcLH3Jw5z9HDNGfT/gwCPgaDjnx0i8w7vBzFLFR1f6CMLKF8gVbebmkUN3fa/kQJpQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/vite/node_modules/lightningcss-linux-arm64-musl": { + "version": "1.32.0", + "resolved": "https://registry.npmjs.org/lightningcss-linux-arm64-musl/-/lightningcss-linux-arm64-musl-1.32.0.tgz", + "integrity": "sha512-UpQkoenr4UJEzgVIYpI80lDFvRmPVg6oqboNHfoH4CQIfNA+HOrZ7Mo7KZP02dC6LjghPQJeBsvXhJod/wnIBg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/vite/node_modules/lightningcss-linux-x64-gnu": { + "version": "1.32.0", + "resolved": "https://registry.npmjs.org/lightningcss-linux-x64-gnu/-/lightningcss-linux-x64-gnu-1.32.0.tgz", + "integrity": "sha512-V7Qr52IhZmdKPVr+Vtw8o+WLsQJYCTd8loIfpDaMRWGUZfBOYEJeyJIkqGIDMZPwPx24pUMfwSxxI8phr/MbOA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/vite/node_modules/lightningcss-linux-x64-musl": { + "version": "1.32.0", + "resolved": "https://registry.npmjs.org/lightningcss-linux-x64-musl/-/lightningcss-linux-x64-musl-1.32.0.tgz", + "integrity": "sha512-bYcLp+Vb0awsiXg/80uCRezCYHNg1/l3mt0gzHnWV9XP1W5sKa5/TCdGWaR/zBM2PeF/HbsQv/j2URNOiVuxWg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/vite/node_modules/lightningcss-win32-arm64-msvc": { + "version": "1.32.0", + "resolved": "https://registry.npmjs.org/lightningcss-win32-arm64-msvc/-/lightningcss-win32-arm64-msvc-1.32.0.tgz", + "integrity": "sha512-8SbC8BR40pS6baCM8sbtYDSwEVQd4JlFTOlaD3gWGHfThTcABnNDBda6eTZeqbofalIJhFx0qKzgHJmcPTnGdw==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/vite/node_modules/lightningcss-win32-x64-msvc": { + "version": "1.32.0", + "resolved": "https://registry.npmjs.org/lightningcss-win32-x64-msvc/-/lightningcss-win32-x64-msvc-1.32.0.tgz", + "integrity": "sha512-Amq9B/SoZYdDi1kFrojnoqPLxYhQ4Wo5XiL8EVJrVsB8ARoC1PWW6VGtT0WKCemjy8aC+louJnjS7U18x3b06Q==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/vite/node_modules/picomatch": { + "version": "4.0.4", + "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.4.tgz", + "integrity": "sha512-QP88BAKvMam/3NxH6vj2o21R6MjxZUAd6nlwAS/pnGvN9IVLocLHxGYIzFhg6fUQ+5th6P4dv4eW9jX3DSIj7A==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/sponsors/jonschlinkert" + } + }, + "node_modules/vitest": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/vitest/-/vitest-4.1.0.tgz", + "integrity": "sha512-YbDrMF9jM2Lqc++2530UourxZHmkKLxrs4+mYhEwqWS97WJ7wOYEkcr+QfRgJ3PW9wz3odRijLZjHEaRLTNbqw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@vitest/expect": "4.1.0", + "@vitest/mocker": "4.1.0", + "@vitest/pretty-format": "4.1.0", + "@vitest/runner": "4.1.0", + "@vitest/snapshot": "4.1.0", + "@vitest/spy": "4.1.0", + "@vitest/utils": "4.1.0", + "es-module-lexer": "^2.0.0", + "expect-type": "^1.3.0", + "magic-string": "^0.30.21", + "obug": "^2.1.1", + "pathe": "^2.0.3", + "picomatch": "^4.0.3", + "std-env": "^4.0.0-rc.1", + "tinybench": "^2.9.0", + "tinyexec": "^1.0.2", + "tinyglobby": "^0.2.15", + "tinyrainbow": "^3.0.3", + "vite": "^6.0.0 || ^7.0.0 || ^8.0.0-0", + "why-is-node-running": "^2.3.0" + }, + "bin": { + "vitest": "vitest.mjs" + }, + "engines": { + "node": "^20.0.0 || ^22.0.0 || >=24.0.0" + }, + "funding": { + "url": "https://opencollective.com/vitest" + }, + "peerDependencies": { + "@edge-runtime/vm": "*", + "@opentelemetry/api": "^1.9.0", + "@types/node": "^20.0.0 || ^22.0.0 || >=24.0.0", + "@vitest/browser-playwright": "4.1.0", + "@vitest/browser-preview": "4.1.0", + "@vitest/browser-webdriverio": "4.1.0", + "@vitest/ui": "4.1.0", + "happy-dom": "*", + "jsdom": "*", + "vite": "^6.0.0 || ^7.0.0 || ^8.0.0-0" + }, + "peerDependenciesMeta": { + "@edge-runtime/vm": { + "optional": true + }, + "@opentelemetry/api": { + "optional": true + }, + "@types/node": { + "optional": true + }, + "@vitest/browser-playwright": { + "optional": true + }, + "@vitest/browser-preview": { + "optional": true + }, + "@vitest/browser-webdriverio": { + "optional": true + }, + "@vitest/ui": { + "optional": true + }, + "happy-dom": { + "optional": true + }, + "jsdom": { + "optional": true + }, + "vite": { + "optional": false + } + } + }, + "node_modules/vitest/node_modules/picomatch": { + "version": "4.0.4", + "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.4.tgz", + "integrity": "sha512-QP88BAKvMam/3NxH6vj2o21R6MjxZUAd6nlwAS/pnGvN9IVLocLHxGYIzFhg6fUQ+5th6P4dv4eW9jX3DSIj7A==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/sponsors/jonschlinkert" + } + }, + "node_modules/vitest/node_modules/std-env": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/std-env/-/std-env-4.0.0.tgz", + "integrity": "sha512-zUMPtQ/HBY3/50VbpkupYHbRroTRZJPRLvreamgErJVys0ceuzMkD44J/QjqhHjOzK42GQ3QZIeFG1OYfOtKqQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/web-streams-polyfill": { + "version": "3.3.3", + "resolved": "https://registry.npmjs.org/web-streams-polyfill/-/web-streams-polyfill-3.3.3.tgz", + "integrity": "sha512-d2JWLCivmZYTSIoge9MsgFCZrt571BikcWGYkjC1khllbTeDlGqZ2D8vD8E/lJa8WGWbb7Plm8/XJYV7IJHZZw==", + "license": "MIT", + "engines": { + "node": ">= 8" + } + }, + "node_modules/webidl-conversions": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/webidl-conversions/-/webidl-conversions-3.0.1.tgz", + "integrity": "sha512-2JAn3z8AR6rjK8Sm8orRC0h/bcl/DqL7tRPdGZ4I1CjdF+EaMLmYxBHyXuKL849eucPFhvBoxMsflfOb8kxaeQ==", + "license": "BSD-2-Clause" + }, + "node_modules/whatwg-url": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/whatwg-url/-/whatwg-url-5.0.0.tgz", + "integrity": "sha512-saE57nupxk6v3HY35+jzBwYa0rKSy0XR8JSxZPwgLr7ys0IBzhGviA1/TUGJLmSVqs8pb9AnvICXEuOHLprYTw==", + "license": "MIT", + "dependencies": { + "tr46": "~0.0.3", + "webidl-conversions": "^3.0.0" + } + }, + "node_modules/which": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/which/-/which-2.0.2.tgz", + "integrity": "sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA==", + "license": "ISC", + "dependencies": { + "isexe": "^2.0.0" + }, + "bin": { + "node-which": "bin/node-which" + }, + "engines": { + "node": ">= 8" + } + }, + "node_modules/which-boxed-primitive": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/which-boxed-primitive/-/which-boxed-primitive-1.1.1.tgz", + "integrity": "sha512-TbX3mj8n0odCBFVlY8AxkqcHASw3L60jIuF8jFP78az3C2YhmGvqbHBpAjTRH2/xqYunrJ9g1jSyjCjpoWzIAA==", + "dev": true, + "license": "MIT", + "dependencies": { + "is-bigint": "^1.1.0", + "is-boolean-object": "^1.2.1", + "is-number-object": "^1.1.1", + "is-string": "^1.1.1", + "is-symbol": "^1.1.1" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/which-builtin-type": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/which-builtin-type/-/which-builtin-type-1.2.1.tgz", + "integrity": "sha512-6iBczoX+kDQ7a3+YJBnh3T+KZRxM/iYNPXicqk66/Qfm1b93iu+yOImkg0zHbj5LNOcNv1TEADiZ0xa34B4q6Q==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bound": "^1.0.2", + "function.prototype.name": "^1.1.6", + "has-tostringtag": "^1.0.2", + "is-async-function": "^2.0.0", + "is-date-object": "^1.1.0", + "is-finalizationregistry": "^1.1.0", + "is-generator-function": "^1.0.10", + "is-regex": "^1.2.1", + "is-weakref": "^1.0.2", + "isarray": "^2.0.5", + "which-boxed-primitive": "^1.1.0", + "which-collection": "^1.0.2", + "which-typed-array": "^1.1.16" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/which-collection": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/which-collection/-/which-collection-1.0.2.tgz", + "integrity": "sha512-K4jVyjnBdgvc86Y6BkaLZEN933SwYOuBFkdmBu9ZfkcAbdVbpITnDmjvZ/aQjRXQrv5EPkTnD1s39GiiqbngCw==", + "dev": true, + "license": "MIT", + "dependencies": { + "is-map": "^2.0.3", + "is-set": "^2.0.3", + "is-weakmap": "^2.0.2", + "is-weakset": "^2.0.3" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/which-typed-array": { + "version": "1.1.20", + "resolved": "https://registry.npmjs.org/which-typed-array/-/which-typed-array-1.1.20.tgz", + "integrity": "sha512-LYfpUkmqwl0h9A2HL09Mms427Q1RZWuOHsukfVcKRq9q95iQxdw0ix1JQrqbcDR9PH1QDwf5Qo8OZb5lksZ8Xg==", + "dev": true, + "license": "MIT", + "dependencies": { + "available-typed-arrays": "^1.0.7", + "call-bind": "^1.0.8", + "call-bound": "^1.0.4", + "for-each": "^0.3.5", + "get-proto": "^1.0.1", + "gopd": "^1.2.0", + "has-tostringtag": "^1.0.2" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/why-is-node-running": { + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/why-is-node-running/-/why-is-node-running-2.3.0.tgz", + "integrity": "sha512-hUrmaWBdVDcxvYqnyh09zunKzROWjbZTiNy8dBEjkS7ehEDQibXJ7XvlmtbwuTclUiIyN+CyXQD4Vmko8fNm8w==", + "dev": true, + "license": "MIT", + "dependencies": { + "siginfo": "^2.0.0", + "stackback": "0.0.2" + }, + "bin": { + "why-is-node-running": "cli.js" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/word-wrap": { + "version": "1.2.5", + "resolved": "https://registry.npmjs.org/word-wrap/-/word-wrap-1.2.5.tgz", + "integrity": "sha512-BN22B5eaMMI9UMtjrGd5g5eCYPpCPDUy0FJXbYsaT5zYxjFOckS53SQDE3pWkVoWpHXVb3BrYcEN4Twa55B5cA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/wrap-ansi": { + "version": "6.2.0", + "resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-6.2.0.tgz", + "integrity": "sha512-r6lPcBGxZXlIcymEu7InxDMhdW0KDxpLgoFLcguasxCaJ/SOIZwINatK9KY/tf+ZrlywOKU0UDj3ATXUBfxJXA==", + "license": "MIT", + "dependencies": { + "ansi-styles": "^4.0.0", + "string-width": "^4.1.0", + "strip-ansi": "^6.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/wrap-ansi/node_modules/ansi-regex": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz", + "integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==", + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/wrap-ansi/node_modules/emoji-regex": { + "version": "8.0.0", + "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-8.0.0.tgz", + "integrity": "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A==", + "license": "MIT" + }, + "node_modules/wrap-ansi/node_modules/string-width": { + "version": "4.2.3", + "resolved": "https://registry.npmjs.org/string-width/-/string-width-4.2.3.tgz", + "integrity": "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g==", + "license": "MIT", + "dependencies": { + "emoji-regex": "^8.0.0", + "is-fullwidth-code-point": "^3.0.0", + "strip-ansi": "^6.0.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/wrap-ansi/node_modules/strip-ansi": { + "version": "6.0.1", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz", + "integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==", + "license": "MIT", + "dependencies": { + "ansi-regex": "^5.0.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/wrappy": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/wrappy/-/wrappy-1.0.2.tgz", + "integrity": "sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ==", + "license": "ISC" + }, + "node_modules/ws": { + "version": "8.19.0", + "resolved": "https://registry.npmjs.org/ws/-/ws-8.19.0.tgz", + "integrity": "sha512-blAT2mjOEIi0ZzruJfIhb3nps74PRWTCz1IjglWEEpQl5XS/UNama6u2/rjFkDDouqr4L67ry+1aGIALViWjDg==", + "license": "MIT", + "engines": { + "node": ">=10.0.0" + }, + "peerDependencies": { + "bufferutil": "^4.0.1", + "utf-8-validate": ">=5.0.2" + }, + "peerDependenciesMeta": { + "bufferutil": { + "optional": true + }, + "utf-8-validate": { + "optional": true + } + } + }, + "node_modules/wsl-utils": { + "version": "0.3.1", + "resolved": "https://registry.npmjs.org/wsl-utils/-/wsl-utils-0.3.1.tgz", + "integrity": "sha512-g/eziiSUNBSsdDJtCLB8bdYEUMj4jR7AGeUo96p/3dTafgjHhpF4RiCFPiRILwjQoDXx5MqkBr4fwWtR3Ky4Wg==", + "license": "MIT", + "dependencies": { + "is-wsl": "^3.1.0", + "powershell-utils": "^0.1.0" + }, + "engines": { + "node": ">=20" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/xml2js": { + "version": "0.6.2", + "resolved": "https://registry.npmjs.org/xml2js/-/xml2js-0.6.2.tgz", + "integrity": "sha512-T4rieHaC1EXcES0Kxxj4JWgaUQHDk+qwHcYOCFHfiwKz7tOVPLq7Hjq9dM1WCMhylqMEfP7hMcOIChvotiZegA==", + "license": "MIT", + "dependencies": { + "sax": ">=0.6.0", + "xmlbuilder": "~11.0.0" + }, + "engines": { + "node": ">=4.0.0" + } + }, + "node_modules/xml2js/node_modules/xmlbuilder": { + "version": "11.0.1", + "resolved": "https://registry.npmjs.org/xmlbuilder/-/xmlbuilder-11.0.1.tgz", + "integrity": "sha512-fDlsI/kFEx7gLvbecc0/ohLG50fugQp8ryHzMTuW9vSa1GJ0XYWKnhsUx7oie3G98+r56aTQIUB4kht42R3JvA==", + "license": "MIT", + "engines": { + "node": ">=4.0" + } + }, + "node_modules/xmlbuilder": { + "version": "15.1.1", + "resolved": "https://registry.npmjs.org/xmlbuilder/-/xmlbuilder-15.1.1.tgz", + "integrity": "sha512-yMqGBqtXyeN1e3TGYvgNgDVZ3j84W4cwkOXQswghol6APgZWaff9lnbvN7MHYJOiXsvGPXtjTYJEiC9J2wv9Eg==", + "license": "MIT", + "engines": { + "node": ">=8.0" + } + }, + "node_modules/y18n": { + "version": "5.0.8", + "resolved": "https://registry.npmjs.org/y18n/-/y18n-5.0.8.tgz", + "integrity": "sha512-0pfFzegeDWJHJIAmTLRP2DwHjdF5s7jo9tuztdQxAhINCdvS+3nGINqPd00AphqJR/0LhANUS6/+7SCb98YOfA==", + "license": "ISC", + "engines": { + "node": ">=10" + } + }, + "node_modules/yallist": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/yallist/-/yallist-3.1.1.tgz", + "integrity": "sha512-a4UGQaWPH59mOXUYnAG2ewncQS4i4F43Tv3JoAM+s2VDAmS9NsK8GpDMLrCHPksFT7h3K6TOoUNn2pb7RoXx4g==", + "license": "ISC" + }, + "node_modules/yargs": { + "version": "17.7.2", + "resolved": "https://registry.npmjs.org/yargs/-/yargs-17.7.2.tgz", + "integrity": "sha512-7dSzzRQ++CKnNI/krKnYRV7JKKPUXMEh61soaHKg9mrWEhzFWhFnxPxGl+69cD1Ou63C13NUPCnmIcrvqCuM6w==", + "license": "MIT", + "dependencies": { + "cliui": "^8.0.1", + "escalade": "^3.1.1", + "get-caller-file": "^2.0.5", + "require-directory": "^2.1.1", + "string-width": "^4.2.3", + "y18n": "^5.0.5", + "yargs-parser": "^21.1.1" + }, + "engines": { + "node": ">=12" + } + }, + "node_modules/yargs-parser": { + "version": "21.1.1", + "resolved": "https://registry.npmjs.org/yargs-parser/-/yargs-parser-21.1.1.tgz", + "integrity": "sha512-tVpsJW7DdjecAiFpbIB1e3qxIQsE6NoPc5/eTdrbbIC4h0LVsWhnoa3g+m2HclBIujHzsxZ4VJVA+GUuc2/LBw==", + "license": "ISC", + "engines": { + "node": ">=12" + } + }, + "node_modules/yargs/node_modules/ansi-regex": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz", + "integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==", + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/yargs/node_modules/emoji-regex": { + "version": "8.0.0", + "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-8.0.0.tgz", + "integrity": "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A==", + "license": "MIT" + }, + "node_modules/yargs/node_modules/string-width": { + "version": "4.2.3", + "resolved": "https://registry.npmjs.org/string-width/-/string-width-4.2.3.tgz", + "integrity": "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g==", + "license": "MIT", + "dependencies": { + "emoji-regex": "^8.0.0", + "is-fullwidth-code-point": "^3.0.0", + "strip-ansi": "^6.0.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/yargs/node_modules/strip-ansi": { + "version": "6.0.1", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz", + "integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==", + "license": "MIT", + "dependencies": { + "ansi-regex": "^5.0.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/yauzl": { + "version": "2.10.0", + "resolved": "https://registry.npmjs.org/yauzl/-/yauzl-2.10.0.tgz", + "integrity": "sha512-p4a9I6X6nu6IhoGmBqAcbJy1mlC4j27vEPZX9F4L4/vZT3Lyq1VkFHw/V/PUcB9Buo+DG3iHkT0x3Qya58zc3g==", + "license": "MIT", + "dependencies": { + "buffer-crc32": "~0.2.3", + "fd-slicer": "~1.1.0" + } + }, + "node_modules/yocto-queue": { + "version": "0.1.0", + "resolved": "https://registry.npmjs.org/yocto-queue/-/yocto-queue-0.1.0.tgz", + "integrity": "sha512-rVksvsnNCdJ/ohGc6xgPwyN8eheCxsiLM8mxuE/t/mOVqJewPuO1miLpTHQiRgTKCLexL4MeAFVagts7HmNZ2Q==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/yoctocolors": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/yoctocolors/-/yoctocolors-2.1.2.tgz", + "integrity": "sha512-CzhO+pFNo8ajLM2d2IW/R93ipy99LWjtwblvC1RsoSUMZgyLbYFr221TnSNT7GjGdYui6P459mw9JH/g/zW2ug==", + "license": "MIT", + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/yoctocolors-cjs": { + "version": "2.1.3", + "resolved": "https://registry.npmjs.org/yoctocolors-cjs/-/yoctocolors-cjs-2.1.3.tgz", + "integrity": "sha512-U/PBtDf35ff0D8X8D0jfdzHYEPFxAI7jJlxZXwCSez5M3190m+QobIfh+sWDWSHMCWWJN2AWamkegn6vr6YBTw==", + "license": "MIT", + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/zeptomatch": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/zeptomatch/-/zeptomatch-2.1.0.tgz", + "integrity": "sha512-KiGErG2J0G82LSpniV0CtIzjlJ10E04j02VOudJsPyPwNZgGnRKQy7I1R7GMyg/QswnE4l7ohSGrQbQbjXPPDA==", + "devOptional": true, + "license": "MIT", + "dependencies": { + "grammex": "^3.1.11", + "graphmatch": "^1.1.0" + } + }, + "node_modules/zod": { + "version": "4.3.6", + "resolved": "https://registry.npmjs.org/zod/-/zod-4.3.6.tgz", + "integrity": "sha512-rftlrkhHZOcjDwkGlnUtZZkvaPHCsDATp4pGpuOOMDaTdDDXF91wuVDJoWoPsKX/3YPQ5fHuF3STjcYyKr+Qhg==", + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/colinhacks" + } + }, + "node_modules/zod-to-json-schema": { + "version": "3.25.1", + "resolved": "https://registry.npmjs.org/zod-to-json-schema/-/zod-to-json-schema-3.25.1.tgz", + "integrity": "sha512-pM/SU9d3YAggzi6MtR4h7ruuQlqKtad8e9S0fmxcMi+ueAK5Korys/aWcV9LIIHTVbj01NdzxcnXSN+O74ZIVA==", + "license": "ISC", + "peerDependencies": { + "zod": "^3.25 || ^4" + } + }, + "node_modules/zod-validation-error": { + "version": "4.0.2", + "resolved": "https://registry.npmjs.org/zod-validation-error/-/zod-validation-error-4.0.2.tgz", + "integrity": "sha512-Q6/nZLe6jxuU80qb/4uJ4t5v2VEZ44lzQjPDhYJNztRQ4wyWc6VF3D3Kb/fAuPetZQnhS3hnajCf9CsWesghLQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=18.0.0" + }, + "peerDependencies": { + "zod": "^3.25.0 || ^4.0.0" + } + } + } +} diff --git a/package.json b/package.json new file mode 100644 index 0000000000000000000000000000000000000000..e32b48a36efd3ccb400b4f5f6353b0f201b01f87 --- /dev/null +++ b/package.json @@ -0,0 +1,62 @@ +{ + "name": "rotnot-work", + "version": "0.1.0", + "private": true, + "scripts": { + "dev": "next dev", + "build": "next build", + "start": "next start", + "postinstall": "prisma generate", + "lint": "eslint", + "test": "vitest run", + "test:watch": "vitest", + "typecheck": "tsc --noEmit" + }, + "dependencies": { + "@anthropic-ai/sdk": "^0.82.0", + "@base-ui/react": "^1.3.0", + "@capacitor/android": "^8.2.0", + "@capacitor/cli": "^8.2.0", + "@capacitor/core": "^8.2.0", + "@capacitor/haptics": "^8.0.1", + "@capacitor/ios": "^8.2.0", + "@capacitor/local-notifications": "^8.0.2", + "@capacitor/push-notifications": "^8.0.2", + "@capacitor/status-bar": "^8.0.1", + "@libsql/client": "^0.17.0", + "@prisma/adapter-libsql": "^7.5.0", + "@prisma/client": "^7.5.0", + "chess.js": "^1.4.0", + "class-variance-authority": "^0.7.1", + "clsx": "^2.1.1", + "date-fns": "^4.1.0", + "framer-motion": "^12.38.0", + "langsmith": "^0.5.15", + "lucide-react": "^0.577.0", + "next": "16.1.7", + "react": "19.2.3", + "react-chessboard": "^5.10.0", + "react-dom": "19.2.3", + "recharts": "^3.8.0", + "shadcn": "^4.0.8", + "tailwind-merge": "^3.5.0", + "tw-animate-css": "^1.4.0" + }, + "prisma": { + "seed": "npx tsx prisma/seed.ts" + }, + "devDependencies": { + "@playwright/test": "^1.61.1", + "@tailwindcss/postcss": "^4", + "@types/node": "^20", + "@types/react": "^19", + "@types/react-dom": "^19", + "eslint": "^9", + "eslint-config-next": "16.1.7", + "prisma": "^7.5.0", + "tailwindcss": "^4", + "tsx": "^4.21.0", + "typescript": "^5.9.3", + "vitest": "^4.1.0" + } +} diff --git a/playwright.coding.config.ts b/playwright.coding.config.ts new file mode 100644 index 0000000000000000000000000000000000000000..aa95e2fcc148e8bc3ff6220a6c422825d4368c3a --- /dev/null +++ b/playwright.coding.config.ts @@ -0,0 +1,26 @@ +import { defineConfig } from "@playwright/test"; + +// Dedicated E2E config for the Coding Training flow. Runs against a local +// production server on port 3101 and uses the pre-installed Chromium. +export default defineConfig({ + testDir: "./e2e", + testMatch: "coding.spec.ts", + timeout: 60_000, + expect: { timeout: 10_000 }, + fullyParallel: false, + workers: 1, + use: { + baseURL: "http://localhost:3101", + headless: true, + screenshot: "only-on-failure", + launchOptions: { + executablePath: "/opt/pw-browsers/chromium-1194/chrome-linux/chrome", + }, + }, + webServer: { + command: "npm run start -- -p 3101", + url: "http://localhost:3101", + reuseExistingServer: true, + timeout: 60_000, + }, +}); diff --git a/playwright.config.ts b/playwright.config.ts new file mode 100644 index 0000000000000000000000000000000000000000..8ff1bbe235881bd217cf7586b350315d52103921 --- /dev/null +++ b/playwright.config.ts @@ -0,0 +1,16 @@ +import { defineConfig } from '@playwright/test'; +export default defineConfig({ + testDir: './e2e', + use: { + baseURL: 'http://192.168.1.166:3101', + headless: true, + screenshot: 'only-on-failure', + video: 'retain-on-failure', + }, + webServer: { + command: 'npm run dev', + url: 'http://192.168.1.166:3101', + reuseExistingServer: true, + timeout: 30000, + }, +}); diff --git a/postcss.config.mjs b/postcss.config.mjs new file mode 100644 index 0000000000000000000000000000000000000000..61e36849cf7cfa9f1f71b4a3964a4953e3e243d3 --- /dev/null +++ b/postcss.config.mjs @@ -0,0 +1,7 @@ +const config = { + plugins: { + "@tailwindcss/postcss": {}, + }, +}; + +export default config; diff --git a/prisma.config.ts b/prisma.config.ts new file mode 100644 index 0000000000000000000000000000000000000000..9346f48b6810a0d16179f9f479be38a1ecc3641a --- /dev/null +++ b/prisma.config.ts @@ -0,0 +1,15 @@ +// This file was generated by Prisma, and assumes you have installed the following: +// npm install --save-dev prisma dotenv +import "dotenv/config"; +import { defineConfig } from "prisma/config"; + +export default defineConfig({ + schema: "prisma/schema.prisma", + migrations: { + path: "prisma/migrations", + seed: "npx tsx prisma/seed.ts", + }, + datasource: { + url: process.env["DATABASE_URL"], + }, +}); diff --git a/prisma/migrations/20260318034440_init/migration.sql b/prisma/migrations/20260318034440_init/migration.sql new file mode 100644 index 0000000000000000000000000000000000000000..c1f4824d262ea66fcd4bee5e48db39418769128b --- /dev/null +++ b/prisma/migrations/20260318034440_init/migration.sql @@ -0,0 +1,106 @@ +-- CreateTable +CREATE TABLE "User" ( + "id" INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, + "name" TEXT NOT NULL, + "level" INTEGER NOT NULL DEFAULT 1, + "totalXp" INTEGER NOT NULL DEFAULT 0, + "currentXp" INTEGER NOT NULL DEFAULT 0, + "xpToNextLevel" INTEGER NOT NULL DEFAULT 100, + "title" TEXT NOT NULL DEFAULT 'Smooth Brain', + "dailyGoalXp" INTEGER NOT NULL DEFAULT 100, + "streak" INTEGER NOT NULL DEFAULT 0, + "longestStreak" INTEGER NOT NULL DEFAULT 0, + "streakFreezes" INTEGER NOT NULL DEFAULT 0, + "lichessUsername" TEXT, + "chesscomUsername" TEXT, + "createdAt" DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP +); + +-- CreateTable +CREATE TABLE "CategorySkill" ( + "id" INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, + "userId" INTEGER NOT NULL, + "category" TEXT NOT NULL, + "level" INTEGER NOT NULL DEFAULT 1, + "totalXp" INTEGER NOT NULL DEFAULT 0, + "currentXp" INTEGER NOT NULL DEFAULT 0, + "xpToNext" INTEGER NOT NULL DEFAULT 100, + CONSTRAINT "CategorySkill_userId_fkey" FOREIGN KEY ("userId") REFERENCES "User" ("id") ON DELETE RESTRICT ON UPDATE CASCADE +); + +-- CreateTable +CREATE TABLE "Activity" ( + "id" INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, + "userId" INTEGER NOT NULL, + "category" TEXT NOT NULL, + "exerciseType" TEXT NOT NULL, + "description" TEXT NOT NULL, + "baseXp" INTEGER NOT NULL, + "qualityBonus" INTEGER NOT NULL DEFAULT 0, + "isCriticalHit" BOOLEAN NOT NULL DEFAULT false, + "totalXp" INTEGER NOT NULL, + "score" REAL, + "durationSecs" INTEGER, + "metadata" TEXT, + "createdAt" DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, + CONSTRAINT "Activity_userId_fkey" FOREIGN KEY ("userId") REFERENCES "User" ("id") ON DELETE RESTRICT ON UPDATE CASCADE +); + +-- CreateTable +CREATE TABLE "DailyLog" ( + "id" INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, + "userId" INTEGER NOT NULL, + "date" DATETIME NOT NULL, + "xpEarned" INTEGER NOT NULL DEFAULT 0, + "activityCount" INTEGER NOT NULL DEFAULT 0, + "goalMet" BOOLEAN NOT NULL DEFAULT false, + "streakFreezeUsed" BOOLEAN NOT NULL DEFAULT false, + CONSTRAINT "DailyLog_userId_fkey" FOREIGN KEY ("userId") REFERENCES "User" ("id") ON DELETE RESTRICT ON UPDATE CASCADE +); + +-- CreateTable +CREATE TABLE "SkillTreeNode" ( + "id" INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, + "category" TEXT NOT NULL, + "name" TEXT NOT NULL, + "description" TEXT NOT NULL, + "levelRequired" INTEGER NOT NULL, + "parentNodeId" INTEGER, + "nodeType" TEXT NOT NULL, + CONSTRAINT "SkillTreeNode_parentNodeId_fkey" FOREIGN KEY ("parentNodeId") REFERENCES "SkillTreeNode" ("id") ON DELETE SET NULL ON UPDATE CASCADE +); + +-- CreateTable +CREATE TABLE "Unlock" ( + "id" INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, + "userId" INTEGER NOT NULL, + "nodeId" INTEGER NOT NULL, + "unlockedAt" DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, + CONSTRAINT "Unlock_userId_fkey" FOREIGN KEY ("userId") REFERENCES "User" ("id") ON DELETE RESTRICT ON UPDATE CASCADE, + CONSTRAINT "Unlock_nodeId_fkey" FOREIGN KEY ("nodeId") REFERENCES "SkillTreeNode" ("id") ON DELETE RESTRICT ON UPDATE CASCADE +); + +-- CreateTable +CREATE TABLE "ContentItem" ( + "id" INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, + "category" TEXT NOT NULL, + "title" TEXT NOT NULL, + "content" TEXT NOT NULL, + "difficulty" TEXT NOT NULL, + "domain" TEXT NOT NULL, + "source" TEXT NOT NULL, + "metadata" TEXT, + "createdAt" DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP +); + +-- CreateIndex +CREATE UNIQUE INDEX "CategorySkill_userId_category_key" ON "CategorySkill"("userId", "category"); + +-- CreateIndex +CREATE UNIQUE INDEX "DailyLog_userId_date_key" ON "DailyLog"("userId", "date"); + +-- CreateIndex +CREATE UNIQUE INDEX "SkillTreeNode_category_name_key" ON "SkillTreeNode"("category", "name"); + +-- CreateIndex +CREATE UNIQUE INDEX "Unlock_userId_nodeId_key" ON "Unlock"("userId", "nodeId"); diff --git a/prisma/migrations/20260321061731_add_spaced_repetition/migration.sql b/prisma/migrations/20260321061731_add_spaced_repetition/migration.sql new file mode 100644 index 0000000000000000000000000000000000000000..912cd96c8f9fa5674fd8da07d2db5f74cea2293d --- /dev/null +++ b/prisma/migrations/20260321061731_add_spaced_repetition/migration.sql @@ -0,0 +1,27 @@ +-- CreateTable +CREATE TABLE "SpacedRepetitionItem" ( + "id" INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, + "userId" INTEGER NOT NULL, + "category" TEXT NOT NULL DEFAULT 'feynman', + "topicId" TEXT NOT NULL, + "topic" TEXT NOT NULL, + "domain" TEXT NOT NULL, + "difficulty" TEXT NOT NULL, + "stage" INTEGER NOT NULL DEFAULT 0, + "nextReviewAt" DATETIME NOT NULL, + "lastReviewAt" DATETIME, + "lastScore" REAL, + "totalReviews" INTEGER NOT NULL DEFAULT 0, + "successCount" INTEGER NOT NULL DEFAULT 0, + "createdAt" DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, + CONSTRAINT "SpacedRepetitionItem_userId_fkey" FOREIGN KEY ("userId") REFERENCES "User" ("id") ON DELETE RESTRICT ON UPDATE CASCADE +); + +-- CreateIndex +CREATE INDEX "SpacedRepetitionItem_userId_nextReviewAt_idx" ON "SpacedRepetitionItem"("userId", "nextReviewAt"); + +-- CreateIndex +CREATE INDEX "SpacedRepetitionItem_userId_category_idx" ON "SpacedRepetitionItem"("userId", "category"); + +-- CreateIndex +CREATE UNIQUE INDEX "SpacedRepetitionItem_userId_topicId_key" ON "SpacedRepetitionItem"("userId", "topicId"); diff --git a/prisma/migrations/20260321141626_add_topic_sources_and_teaching_cache/migration.sql b/prisma/migrations/20260321141626_add_topic_sources_and_teaching_cache/migration.sql new file mode 100644 index 0000000000000000000000000000000000000000..c17c9a9857004d40b5c5e953009f0e5887d8bd5e --- /dev/null +++ b/prisma/migrations/20260321141626_add_topic_sources_and_teaching_cache/migration.sql @@ -0,0 +1,33 @@ +-- CreateTable +CREATE TABLE "TopicSource" ( + "id" INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, + "topicId" TEXT NOT NULL, + "url" TEXT NOT NULL, + "title" TEXT NOT NULL, + "excerpt" TEXT NOT NULL, + "domain" TEXT NOT NULL, + "license" TEXT NOT NULL, + "confidence" TEXT NOT NULL DEFAULT 'moderate', + "verifiedAt" DATETIME, + "createdAt" DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP +); + +-- CreateTable +CREATE TABLE "TeachingCache" ( + "id" INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, + "topicId" TEXT NOT NULL, + "content" TEXT NOT NULL, + "sourcesJson" TEXT NOT NULL, + "confidenceScore" TEXT NOT NULL DEFAULT 'moderate', + "generatedAt" DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, + "verifiedAt" DATETIME +); + +-- CreateIndex +CREATE INDEX "TopicSource_topicId_idx" ON "TopicSource"("topicId"); + +-- CreateIndex +CREATE UNIQUE INDEX "TeachingCache_topicId_key" ON "TeachingCache"("topicId"); + +-- CreateIndex +CREATE INDEX "TeachingCache_topicId_idx" ON "TeachingCache"("topicId"); diff --git a/prisma/migrations/migration_lock.toml b/prisma/migrations/migration_lock.toml new file mode 100644 index 0000000000000000000000000000000000000000..2a5a44419d4f3670b4e8716bf276377e3c696134 --- /dev/null +++ b/prisma/migrations/migration_lock.toml @@ -0,0 +1,3 @@ +# Please do not edit this file manually +# It should be added in your version-control system (e.g., Git) +provider = "sqlite" diff --git a/prisma/schema.prisma b/prisma/schema.prisma new file mode 100644 index 0000000000000000000000000000000000000000..9b6f5e27f30914fca4bb08137ed3a237478e4c38 --- /dev/null +++ b/prisma/schema.prisma @@ -0,0 +1,166 @@ +generator client { + provider = "prisma-client-js" +} + +datasource db { + provider = "sqlite" +} + +model User { + id Int @id @default(autoincrement()) + name String + level Int @default(1) + totalXp Int @default(0) + currentXp Int @default(0) + xpToNextLevel Int @default(100) + title String @default("Smooth Brain") + dailyGoalXp Int @default(100) + streak Int @default(0) + longestStreak Int @default(0) + streakFreezes Int @default(0) + lichessUsername String? + chesscomUsername String? + createdAt DateTime @default(now()) + + activities Activity[] + dailyLogs DailyLog[] + categorySkills CategorySkill[] + unlocks Unlock[] + spacedRepetitionItems SpacedRepetitionItem[] +} + +model CategorySkill { + id Int @id @default(autoincrement()) + userId Int + category String + level Int @default(1) + totalXp Int @default(0) + currentXp Int @default(0) + xpToNext Int @default(100) + + user User @relation(fields: [userId], references: [id]) + + @@unique([userId, category]) +} + +model Activity { + id Int @id @default(autoincrement()) + userId Int + category String + exerciseType String + description String + baseXp Int + qualityBonus Int @default(0) + isCriticalHit Boolean @default(false) + totalXp Int + score Float? + durationSecs Int? + metadata String? + createdAt DateTime @default(now()) + + user User @relation(fields: [userId], references: [id]) +} + +model DailyLog { + id Int @id @default(autoincrement()) + userId Int + date DateTime + xpEarned Int @default(0) + activityCount Int @default(0) + goalMet Boolean @default(false) + streakFreezeUsed Boolean @default(false) + + user User @relation(fields: [userId], references: [id]) + + @@unique([userId, date]) +} + +model SkillTreeNode { + id Int @id @default(autoincrement()) + category String + name String + description String + levelRequired Int + parentNodeId Int? + nodeType String + + parent SkillTreeNode? @relation("NodeTree", fields: [parentNodeId], references: [id]) + children SkillTreeNode[] @relation("NodeTree") + unlocks Unlock[] + + @@unique([category, name]) +} + +model Unlock { + id Int @id @default(autoincrement()) + userId Int + nodeId Int + unlockedAt DateTime @default(now()) + + user User @relation(fields: [userId], references: [id]) + node SkillTreeNode @relation(fields: [nodeId], references: [id]) + + @@unique([userId, nodeId]) +} + +model ContentItem { + id Int @id @default(autoincrement()) + category String + title String + content String + difficulty String + domain String + source String + metadata String? + createdAt DateTime @default(now()) +} + +model TopicSource { + id Int @id @default(autoincrement()) + topicId String // matches Topic.id from feynman/topics.ts + url String // source URL + title String // source page/article title + excerpt String // relevant excerpt from the source + domain String // e.g., "wikipedia", "openstax", "arxiv" + license String // e.g., "CC BY-SA 4.0", "CC0", "public-domain" + confidence String @default("moderate") // "high", "moderate", "low" + verifiedAt DateTime? // when URL was last verified as live + createdAt DateTime @default(now()) + + @@index([topicId]) +} + +model TeachingCache { + id Int @id @default(autoincrement()) + topicId String @unique // one cached teaching per topic + content String // the grounded teaching explanation (markdown) + sourcesJson String // JSON array of { url, title, domain, license } used + confidenceScore String @default("moderate") // "high" (2+ corroborating), "moderate" (1), "low" (extrapolated) + generatedAt DateTime @default(now()) + verifiedAt DateTime? // when content was last verified against sources + + @@index([topicId]) +} + +model SpacedRepetitionItem { + id Int @id @default(autoincrement()) + userId Int + category String @default("feynman") + topicId String // matches Topic.id from feynman/topics.ts + topic String // human-readable topic name + domain String + difficulty String // beginner | intermediate | expert + stage Int @default(0) // 0=new, 1-5 = review stages + nextReviewAt DateTime // when the next review is due + lastReviewAt DateTime? // when last reviewed (null = never reviewed yet) + lastScore Float? // score from most recent review (0-1) + totalReviews Int @default(0) + successCount Int @default(0) // reviews scoring >= 0.6 + createdAt DateTime @default(now()) + + user User @relation(fields: [userId], references: [id]) + + @@unique([userId, topicId]) + @@index([userId, nextReviewAt]) + @@index([userId, category]) +} diff --git a/prisma/seed.ts b/prisma/seed.ts new file mode 100644 index 0000000000000000000000000000000000000000..907e5986a772b8980db7d3d71e9a7f089c24da4d --- /dev/null +++ b/prisma/seed.ts @@ -0,0 +1,198 @@ +import { PrismaClient } from "@prisma/client"; +import { PrismaLibSql } from "@prisma/adapter-libsql"; +import path from "path"; + +const dbPath = path.resolve(process.cwd(), "dev.db"); +const adapter = new PrismaLibSql({ url: `file:${dbPath}` }); +const prisma = new PrismaClient({ adapter }); + +const CATEGORIES = [ + "chess", + "reading", + "feynman", + "logic", + "critical-thinking", + "quests", + "coding", +] as const; + +// Skill tree nodes defined without relying on hardcoded IDs. +// parentNodeId references are resolved by looking up the previously created node's real ID. +type NodeDef = { + category: string; + name: string; + description: string; + levelRequired: number; + nodeType: string; + parentKey: string | null; // "category:name" of parent, or null +}; + +const SKILL_TREE_NODES: NodeDef[] = [ + // Chess + { category: "chess", name: "Chess Initiate", description: "Begin your chess journey", levelRequired: 1, nodeType: "difficulty", parentKey: null }, + { category: "chess", name: "Puzzle Warrior", description: "Unlock 1200+ rated puzzles", levelRequired: 5, nodeType: "difficulty", parentKey: "chess:Chess Initiate" }, + { category: "chess", name: "Endgame Student", description: "Unlock endgame puzzles", levelRequired: 5, nodeType: "exercise-type", parentKey: "chess:Chess Initiate" }, + { category: "chess", name: "Tactical Eye", description: "+10% Chess XP", levelRequired: 15, nodeType: "multiplier", parentKey: "chess:Puzzle Warrior" }, + { category: "chess", name: "Puzzle Master", description: "Unlock 1800+ rated puzzles", levelRequired: 20, nodeType: "difficulty", parentKey: "chess:Puzzle Warrior" }, + { category: "chess", name: "Streak Shield I", description: "Earn 1 streak freeze", levelRequired: 10, nodeType: "streak-shield", parentKey: "chess:Endgame Student" }, + { category: "chess", name: "Grandmaster Path", description: "+25% Chess XP", levelRequired: 30, nodeType: "multiplier", parentKey: "chess:Puzzle Master" }, + { category: "chess", name: "Grandthinker", description: "Chess mastery title", levelRequired: 50, nodeType: "cosmetic", parentKey: "chess:Grandmaster Path" }, + + // Reading + { category: "reading", name: "Page Turner", description: "Begin reading exercises", levelRequired: 1, nodeType: "difficulty", parentKey: null }, + { category: "reading", name: "Deep Diver", description: "Unlock intermediate articles", levelRequired: 5, nodeType: "difficulty", parentKey: "reading:Page Turner" }, + { category: "reading", name: "Speed Reader", description: "Unlock timed reading challenges", levelRequired: 5, nodeType: "exercise-type", parentKey: "reading:Page Turner" }, + { category: "reading", name: "Scholar", description: "Unlock advanced/academic content", levelRequired: 10, nodeType: "difficulty", parentKey: "reading:Deep Diver" }, + { category: "reading", name: "Focus Boost", description: "+10% Reading XP", levelRequired: 15, nodeType: "multiplier", parentKey: "reading:Scholar" }, + { category: "reading", name: "Reading Streak Shield", description: "Earn 1 streak freeze", levelRequired: 10, nodeType: "streak-shield", parentKey: "reading:Speed Reader" }, + { category: "reading", name: "Concentration Master", description: "+25% Reading XP", levelRequired: 30, nodeType: "multiplier", parentKey: "reading:Focus Boost" }, + { category: "reading", name: "The Deep Diver", description: "Reading mastery title", levelRequired: 50, nodeType: "cosmetic", parentKey: "reading:Concentration Master" }, + + // Feynman + { category: "feynman", name: "Curious Mind", description: "Begin Feynman challenges", levelRequired: 1, nodeType: "difficulty", parentKey: null }, + { category: "feynman", name: "Explainer", description: "Unlock intermediate topics", levelRequired: 5, nodeType: "difficulty", parentKey: "feynman:Curious Mind" }, + { category: "feynman", name: "Timed Explains", description: "Unlock timed mode", levelRequired: 5, nodeType: "exercise-type", parentKey: "feynman:Curious Mind" }, + { category: "feynman", name: "Professor", description: "Unlock expert topics", levelRequired: 15, nodeType: "difficulty", parentKey: "feynman:Explainer" }, + { category: "feynman", name: "Clarity Boost", description: "+10% Feynman XP", levelRequired: 15, nodeType: "multiplier", parentKey: "feynman:Timed Explains" }, + { category: "feynman", name: "Feynman Streak Shield", description: "Earn 1 streak freeze", levelRequired: 10, nodeType: "streak-shield", parentKey: "feynman:Explainer" }, + { category: "feynman", name: "Mastery Boost", description: "+25% Feynman XP", levelRequired: 30, nodeType: "multiplier", parentKey: "feynman:Professor" }, + { category: "feynman", name: "The Explainer", description: "Feynman mastery title", levelRequired: 50, nodeType: "cosmetic", parentKey: "feynman:Mastery Boost" }, + + // Logic + { category: "logic", name: "Logical Mind", description: "Begin logic puzzles", levelRequired: 1, nodeType: "difficulty", parentKey: null }, + { category: "logic", name: "Medium Puzzles", description: "Unlock medium difficulty", levelRequired: 5, nodeType: "difficulty", parentKey: "logic:Logical Mind" }, + { category: "logic", name: "Sequence Master", description: "Unlock number sequences", levelRequired: 5, nodeType: "exercise-type", parentKey: "logic:Logical Mind" }, + { category: "logic", name: "Hard Puzzles", description: "Unlock hard difficulty", levelRequired: 10, nodeType: "difficulty", parentKey: "logic:Medium Puzzles" }, + { category: "logic", name: "Logic Boost", description: "+10% Logic XP", levelRequired: 15, nodeType: "multiplier", parentKey: "logic:Hard Puzzles" }, + { category: "logic", name: "Expert Puzzles", description: "Unlock expert difficulty", levelRequired: 20, nodeType: "difficulty", parentKey: "logic:Hard Puzzles" }, + { category: "logic", name: "Logic Streak Shield", description: "Earn 1 streak freeze", levelRequired: 10, nodeType: "streak-shield", parentKey: "logic:Hard Puzzles" }, + { category: "logic", name: "Logic Mastery Boost", description: "+25% Logic XP", levelRequired: 30, nodeType: "multiplier", parentKey: "logic:Expert Puzzles" }, + { category: "logic", name: "Vulcan", description: "Logic mastery title", levelRequired: 50, nodeType: "cosmetic", parentKey: "logic:Logic Mastery Boost" }, + + // Critical Thinking + { category: "critical-thinking", name: "Flaw Finder: Easy", description: "Identify basic logical fallacies", levelRequired: 1, nodeType: "difficulty", parentKey: null }, + { category: "critical-thinking", name: "Flaw Finder: Medium", description: "Harder fallacy detection", levelRequired: 3, nodeType: "difficulty", parentKey: "critical-thinking:Flaw Finder: Easy" }, + { category: "critical-thinking", name: "Steelman: Unlocked", description: "Construct strongest opposing arguments", levelRequired: 5, nodeType: "exercise-type", parentKey: "critical-thinking:Flaw Finder: Medium" }, + { category: "critical-thinking", name: "Flaw Finder: Hard", description: "Subtle fallacies and weak reasoning", levelRequired: 5, nodeType: "difficulty", parentKey: "critical-thinking:Flaw Finder: Medium" }, + { category: "critical-thinking", name: "Devil's Advocate: Unlocked", description: "Argue against your own positions", levelRequired: 10, nodeType: "exercise-type", parentKey: "critical-thinking:Steelman: Unlocked" }, + { category: "critical-thinking", name: "Steelman: Medium", description: "More nuanced positions", levelRequired: 10, nodeType: "difficulty", parentKey: "critical-thinking:Steelman: Unlocked" }, + { category: "critical-thinking", name: "Critical Boost", description: "+10% Critical Thinking XP", levelRequired: 10, nodeType: "multiplier", parentKey: "critical-thinking:Devil's Advocate: Unlocked" }, + { category: "critical-thinking", name: "Flaw Finder: Expert", description: "Professional-level analysis", levelRequired: 15, nodeType: "difficulty", parentKey: "critical-thinking:Flaw Finder: Hard" }, + { category: "critical-thinking", name: "CT Streak Shield", description: "Earn 1 streak freeze", levelRequired: 15, nodeType: "streak-shield", parentKey: "critical-thinking:Critical Boost" }, + { category: "critical-thinking", name: "Steelman: Hard", description: "Complex multi-faceted positions", levelRequired: 20, nodeType: "difficulty", parentKey: "critical-thinking:Steelman: Medium" }, + { category: "critical-thinking", name: "Devil's Advocate: Medium", description: "Harder positions to argue against", levelRequired: 20, nodeType: "difficulty", parentKey: "critical-thinking:Devil's Advocate: Unlocked" }, + { category: "critical-thinking", name: "Devil's Advocate: Hard", description: "Expert-level contrarian arguments", levelRequired: 30, nodeType: "difficulty", parentKey: "critical-thinking:Devil's Advocate: Medium" }, + { category: "critical-thinking", name: "CT Mastery Boost", description: "+25% Critical Thinking XP", levelRequired: 30, nodeType: "multiplier", parentKey: "critical-thinking:Devil's Advocate: Hard" }, + { category: "critical-thinking", name: "Steel Trap", description: "Critical Thinking mastery title", levelRequired: 50, nodeType: "cosmetic", parentKey: "critical-thinking:CT Mastery Boost" }, + + // Skill Quests + { category: "quests", name: "Apprentice", description: "Begin skill quests", levelRequired: 1, nodeType: "difficulty", parentKey: null }, + { category: "quests", name: "Intermediate Quests", description: "Unlock intermediate lessons", levelRequired: 5, nodeType: "difficulty", parentKey: "quests:Apprentice" }, + { category: "quests", name: "Spaced Repetition", description: "Unlock review sessions", levelRequired: 5, nodeType: "exercise-type", parentKey: "quests:Apprentice" }, + { category: "quests", name: "Advanced Quests", description: "Unlock advanced lessons", levelRequired: 15, nodeType: "difficulty", parentKey: "quests:Intermediate Quests" }, + { category: "quests", name: "Quest Boost", description: "+10% Quest XP", levelRequired: 15, nodeType: "multiplier", parentKey: "quests:Spaced Repetition" }, + { category: "quests", name: "Quest Streak Shield", description: "Earn 1 streak freeze", levelRequired: 10, nodeType: "streak-shield", parentKey: "quests:Spaced Repetition" }, + { category: "quests", name: "Quest Mastery Boost", description: "+25% Quest XP", levelRequired: 30, nodeType: "multiplier", parentKey: "quests:Quest Boost" }, + { category: "quests", name: "Polymath", description: "Skill Quests mastery title", levelRequired: 50, nodeType: "cosmetic", parentKey: "quests:Quest Mastery Boost" }, + + // Coding Training + { category: "coding", name: "Code Initiate", description: "Begin coding training", levelRequired: 1, nodeType: "difficulty", parentKey: null }, + { category: "coding", name: "Debugger", description: "Unlock debugging challenges", levelRequired: 5, nodeType: "exercise-type", parentKey: "coding:Code Initiate" }, + { category: "coding", name: "Code Reviewer", description: "Unlock AI code-review challenges", levelRequired: 5, nodeType: "exercise-type", parentKey: "coding:Code Initiate" }, + { category: "coding", name: "Medium Problems", description: "Unlock medium difficulty", levelRequired: 8, nodeType: "difficulty", parentKey: "coding:Code Initiate" }, + { category: "coding", name: "Architect", description: "Unlock architecture discussions", levelRequired: 12, nodeType: "exercise-type", parentKey: "coding:Code Reviewer" }, + { category: "coding", name: "Hard Problems", description: "Unlock hard difficulty", levelRequired: 15, nodeType: "difficulty", parentKey: "coding:Medium Problems" }, + { category: "coding", name: "Clean Coder", description: "+10% Coding XP", levelRequired: 15, nodeType: "multiplier", parentKey: "coding:Debugger" }, + { category: "coding", name: "Coding Streak Shield", description: "Earn 1 streak freeze", levelRequired: 10, nodeType: "streak-shield", parentKey: "coding:Debugger" }, + { category: "coding", name: "Engineering Mastery", description: "+25% Coding XP", levelRequired: 30, nodeType: "multiplier", parentKey: "coding:Clean Coder" }, + { category: "coding", name: "10x Engineer", description: "Coding mastery title", levelRequired: 50, nodeType: "cosmetic", parentKey: "coding:Engineering Mastery" }, +]; + +async function main() { + console.log("Seeding database..."); + + // Create default user + const user = await prisma.user.upsert({ + where: { id: 1 }, + update: {}, + create: { name: "Player One" }, + }); + console.log(`User: ${user.name} (id=${user.id})`); + + // Create category skills for all 6 categories + for (const category of CATEGORIES) { + await prisma.categorySkill.upsert({ + where: { userId_category: { userId: user.id, category } }, + update: {}, + create: { userId: user.id, category }, + }); + } + console.log("Category skills created."); + + // Build skill tree nodes in dependency order (BFS by parentKey) + // First pass: create all root nodes (parentKey === null) + const keyToId = new Map(); + + for (const node of SKILL_TREE_NODES) { + if (node.parentKey !== null) continue; + const key = `${node.category}:${node.name}`; + const created = await prisma.skillTreeNode.upsert({ + where: { category_name: { category: node.category, name: node.name } }, + update: {}, + create: { + category: node.category, + name: node.name, + description: node.description, + levelRequired: node.levelRequired, + nodeType: node.nodeType, + parentNodeId: null, + }, + }); + keyToId.set(key, created.id); + } + + // Subsequent passes: process nodes whose parent is already resolved + let remaining = SKILL_TREE_NODES.filter((n) => n.parentKey !== null); + let maxPasses = 10; + while (remaining.length > 0 && maxPasses-- > 0) { + const nextRound: NodeDef[] = []; + for (const node of remaining) { + const parentId = keyToId.get(node.parentKey!); + if (parentId === undefined) { + nextRound.push(node); + continue; + } + const key = `${node.category}:${node.name}`; + const created = await prisma.skillTreeNode.upsert({ + where: { category_name: { category: node.category, name: node.name } }, + update: {}, + create: { + category: node.category, + name: node.name, + description: node.description, + levelRequired: node.levelRequired, + nodeType: node.nodeType, + parentNodeId: parentId, + }, + }); + keyToId.set(key, created.id); + } + remaining = nextRound; + } + + if (remaining.length > 0) { + console.warn(`Warning: ${remaining.length} nodes could not be resolved:`, remaining.map((n) => n.name)); + } + + console.log(`Skill tree nodes created: ${keyToId.size}`); + console.log("Seed complete."); +} + +main() + .catch((e) => { + console.error(e); + process.exit(1); + }) + .finally(async () => { + await prisma.$disconnect(); + }); diff --git a/public/file.svg b/public/file.svg new file mode 100644 index 0000000000000000000000000000000000000000..004145cddf3f9db91b57b9cb596683c8eb420862 --- /dev/null +++ b/public/file.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/public/globe.svg b/public/globe.svg new file mode 100644 index 0000000000000000000000000000000000000000..567f17b0d7c7fb662c16d4357dd74830caf2dccb --- /dev/null +++ b/public/globe.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/public/icons/icon-192.svg b/public/icons/icon-192.svg new file mode 100644 index 0000000000000000000000000000000000000000..9fc0328b4790fd2cf5f43b45607b017f16fc0225 --- /dev/null +++ b/public/icons/icon-192.svg @@ -0,0 +1,27 @@ + + + + + + + + + + + + + + + + + + + + + + + + RN + diff --git a/public/icons/icon-512.svg b/public/icons/icon-512.svg new file mode 100644 index 0000000000000000000000000000000000000000..f83d6ea2b390e351505d3303c6898c12a5707669 --- /dev/null +++ b/public/icons/icon-512.svg @@ -0,0 +1,25 @@ + + + + + + + + + + + + + + + + + + + + + + ROTNOT + diff --git a/public/icons/icon-maskable.svg b/public/icons/icon-maskable.svg new file mode 100644 index 0000000000000000000000000000000000000000..c6295eb06d7b8bcce39bf74d032ecc57440459bd --- /dev/null +++ b/public/icons/icon-maskable.svg @@ -0,0 +1,21 @@ + + + + + + + + + + + + + + + + + + + diff --git a/public/manifest.json b/public/manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..31331cf4c3f59788eb6d9b43d22d582cf65d1fc4 --- /dev/null +++ b/public/manifest.json @@ -0,0 +1,31 @@ +{ + "name": "RotNot — Fight Brain Rot", + "short_name": "RotNot", + "description": "Gamified exercises to combat cognitive atrophy from AI over-reliance. Level up your mind.", + "start_url": "/", + "display": "standalone", + "background_color": "#080c18", + "theme_color": "#080c18", + "orientation": "any", + "categories": ["education", "games", "productivity"], + "icons": [ + { + "src": "/icons/icon-192.svg", + "sizes": "192x192", + "type": "image/svg+xml", + "purpose": "any" + }, + { + "src": "/icons/icon-512.svg", + "sizes": "512x512", + "type": "image/svg+xml", + "purpose": "any" + }, + { + "src": "/icons/icon-maskable.svg", + "sizes": "512x512", + "type": "image/svg+xml", + "purpose": "maskable" + } + ] +} diff --git a/public/next.svg b/public/next.svg new file mode 100644 index 0000000000000000000000000000000000000000..5174b28c565c285e3e312ec5178be64fbeca8398 --- /dev/null +++ b/public/next.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/public/service-worker.js b/public/service-worker.js new file mode 100644 index 0000000000000000000000000000000000000000..7549f92e5f740a8c8afb7dae50f6ad0e9320835e --- /dev/null +++ b/public/service-worker.js @@ -0,0 +1,121 @@ +// RotNot Service Worker +// Caching strategy: cache-first for static assets, stale-while-revalidate for API + +const STATIC_CACHE = 'rotnot-static-v1'; +const API_CACHE = 'rotnot-api-v1'; + +// Static assets to precache on install +const PRECACHE_URLS = [ + '/', + '/manifest.json', + '/icons/icon-192.svg', + '/icons/icon-512.svg', +]; + +// Install: precache core shell +self.addEventListener('install', (event) => { + event.waitUntil( + caches.open(STATIC_CACHE).then((cache) => { + return cache.addAll(PRECACHE_URLS); + }).then(() => self.skipWaiting()) + ); +}); + +// Activate: clean old caches +self.addEventListener('activate', (event) => { + const currentCaches = [STATIC_CACHE, API_CACHE]; + event.waitUntil( + caches.keys().then((cacheNames) => { + return Promise.all( + cacheNames.filter((name) => !currentCaches.includes(name)) + .map((name) => caches.delete(name)) + ); + }).then(() => self.clients.claim()) + ); +}); + +// Fetch handler +self.addEventListener('fetch', (event) => { + const { request } = event; + const url = new URL(request.url); + + // Skip non-GET requests + if (request.method !== 'GET') return; + + // Skip cross-origin requests + if (url.origin !== self.location.origin) return; + + // API routes: stale-while-revalidate + if (url.pathname.startsWith('/api/')) { + event.respondWith(staleWhileRevalidate(request, API_CACHE)); + return; + } + + // Static assets (JS, CSS, images, fonts): cache-first + if (isStaticAsset(url.pathname)) { + event.respondWith(cacheFirst(request, STATIC_CACHE)); + return; + } + + // Navigation requests (HTML pages): network-first with cache fallback + if (request.mode === 'navigate') { + event.respondWith(networkFirst(request, STATIC_CACHE)); + return; + } + + // Default: network-first + event.respondWith(networkFirst(request, STATIC_CACHE)); +}); + +function isStaticAsset(pathname) { + return /\.(js|css|svg|png|jpg|jpeg|gif|webp|woff|woff2|ttf|ico)(\?.*)?$/.test(pathname) + || pathname.startsWith('/_next/static/'); +} + +// Cache-first: return cached if available, otherwise fetch and cache +async function cacheFirst(request, cacheName) { + const cached = await caches.match(request); + if (cached) return cached; + + try { + const response = await fetch(request); + if (response.ok) { + const cache = await caches.open(cacheName); + cache.put(request, response.clone()); + } + return response; + } catch { + return new Response('Offline', { status: 503, statusText: 'Service Unavailable' }); + } +} + +// Network-first: try network, fall back to cache +async function networkFirst(request, cacheName) { + try { + const response = await fetch(request); + if (response.ok) { + const cache = await caches.open(cacheName); + cache.put(request, response.clone()); + } + return response; + } catch { + const cached = await caches.match(request); + if (cached) return cached; + return new Response('Offline', { status: 503, statusText: 'Service Unavailable' }); + } +} + +// Stale-while-revalidate: return cached immediately, update cache in background +async function staleWhileRevalidate(request, cacheName) { + const cache = await caches.open(cacheName); + const cached = await cache.match(request); + + const fetchPromise = fetch(request).then((response) => { + if (response.ok) { + cache.put(request, response.clone()); + } + return response; + }).catch(() => cached); + + return cached || fetchPromise; +} diff --git a/public/vercel.svg b/public/vercel.svg new file mode 100644 index 0000000000000000000000000000000000000000..77053960334e2e34dc584dea8019925c3b4ccca9 --- /dev/null +++ b/public/vercel.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/public/window.svg b/public/window.svg new file mode 100644 index 0000000000000000000000000000000000000000..b2b2a44f6ebc70c450043c05a002e7a93ba5d651 --- /dev/null +++ b/public/window.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/scripts/deploy-hf.sh b/scripts/deploy-hf.sh new file mode 100755 index 0000000000000000000000000000000000000000..1ebc105d34d8b73e617fa16175cca8f8d3dd7f48 --- /dev/null +++ b/scripts/deploy-hf.sh @@ -0,0 +1,34 @@ +#!/usr/bin/env bash +# Push the current commit to a Hugging Face Docker Space. +# +# Usage: +# export HF_TOKEN=hf_xxx # a WRITE token +# scripts/deploy-hf.sh / +# +# Snapshots the current git commit, swaps in the front-matter README the Space +# needs, and force-pushes it to the Space's main branch. The Space must already +# exist (create it once with Docker SDK — see deploy/huggingface/DEPLOY.md). +set -euo pipefail + +SPACE="${1:?usage: deploy-hf.sh /}" +: "${HF_TOKEN:?set HF_TOKEN to a Hugging Face write token}" + +ROOT="$(git rev-parse --show-toplevel)" +TMP="$(mktemp -d)" +trap 'rm -rf "$TMP"' EXIT + +# Clean snapshot of the tracked files at HEAD (no node_modules, .next, dev.db). +git -C "$ROOT" archive --format=tar HEAD | tar -x -C "$TMP" + +# The Space root README must carry the docker/app_port YAML front matter. +cp "$ROOT/deploy/huggingface/README.md" "$TMP/README.md" + +cd "$TMP" +git init -q +git add -A +git -c user.email=deploy@local -c user.name=deploy commit -qm "Deploy RotNot" +git branch -M main +echo "→ Pushing to https://huggingface.co/spaces/${SPACE}" +git push --force "https://user:${HF_TOKEN}@huggingface.co/spaces/${SPACE}.git" main + +echo "✓ Pushed. The Space is building at https://huggingface.co/spaces/${SPACE}" diff --git a/scripts/hf-start.sh b/scripts/hf-start.sh new file mode 100755 index 0000000000000000000000000000000000000000..16db2539c13ef995307f3be64a64edb97a80040a --- /dev/null +++ b/scripts/hf-start.sh @@ -0,0 +1,14 @@ +#!/bin/sh +# Startup for the Hugging Face Docker Space. +# Storage is ephemeral, so apply migrations + seed on every boot (both are +# idempotent), then start Next.js bound to the Space's public port. +set -e + +echo "→ Applying database migrations…" +npx prisma migrate deploy + +echo "→ Seeding database (idempotent)…" +npx prisma db seed + +echo "→ Starting RotNot on 0.0.0.0:7860…" +exec npm run start -- -p 7860 -H 0.0.0.0 diff --git a/src/app/api/analytics/__tests__/judge-dimensions.test.ts b/src/app/api/analytics/__tests__/judge-dimensions.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..27df7c214a8046f3814de5466c55e64d3efd63df --- /dev/null +++ b/src/app/api/analytics/__tests__/judge-dimensions.test.ts @@ -0,0 +1,434 @@ +/** + * Tests for GET /api/analytics/judge-dimensions + * + * Covers: + * API key guard + * - returns 503 when LANGSMITH_API_KEY is not set + * - does NOT call langsmithClient when key is missing + * Response shape + * - returns 200 with { dimensions, alerts } keys + * - dimensions contains an entry for every DIMENSION_ID + * - each dimension entry has { avg, trend } fields + * - alerts is an array + * Score aggregation — avg calculation + * - avg is 0 when no feedback in the current period + * - avg is computed correctly over multiple scores + * - avg is rounded to 2 decimal places + * - denormalises: feedback scores (0-1) are multiplied by 10 + * - ignores feedback keys that are not in DIMENSION_IDS + * - ignores feedback entries with non-numeric score + * Trend calculation + * - trend is 0 when there is no prior period data + * - trend is positive when current avg > prior avg + * - trend is negative when current avg < prior avg + * - trend is 0 when prior and current are identical + * - trend is rounded to 2 decimal places + * Alerts + * - no alert when drop is exactly -10% (boundary — not > 10%) + * - alert fires when drop is > 10% + * - alert message contains the dimension id + * - alert message contains the percentage drop + * - no alert when prior avg is 0 (no prior data) + * - multiple dimensions can fire alerts in the same response + * Error handling + * - returns 500 if langsmithClient.listRuns throws + */ + +import { describe, it, expect, vi, beforeEach } from "vitest"; +import { NextRequest } from "next/server"; +import { DIMENSION_IDS } from "@/lib/debate/judge"; + +// --------------------------------------------------------------------------- +// Helpers +// --------------------------------------------------------------------------- + +type FeedbackEntry = { key: string; score: number | null | undefined }; +type RunEntry = { id: string }; + +/** + * Build a mock async generator from an array. + */ +async function* makeAsyncGen(items: T[]): AsyncGenerator { + for (const item of items) { + yield item; + } +} + +// --------------------------------------------------------------------------- +// Mocks +// --------------------------------------------------------------------------- + +// listRuns and listFeedback are configured per-test via these maps +let mockRunsByPeriod: RunEntry[][] = [[], []]; // [currentPeriod, priorPeriod] +let mockFeedbackByRunId: Map = new Map(); + +// Track call order so we can distinguish current vs prior period calls +let listRunsCallIndex = 0; + +const mockListRuns = vi.fn(); +const mockListFeedback = vi.fn(); + +vi.mock("@/lib/langsmith", () => ({ + langsmithClient: { + listRuns: (...args: unknown[]) => mockListRuns(...args), + listFeedback: (...args: unknown[]) => mockListFeedback(...args), + }, +})); + +beforeEach(() => { + vi.resetModules(); + mockListRuns.mockClear(); + mockListFeedback.mockClear(); + mockRunsByPeriod = [[], []]; + mockFeedbackByRunId = new Map(); + listRunsCallIndex = 0; + + // Default: return the correct period's runs in call order + mockListRuns.mockImplementation(() => { + const idx = listRunsCallIndex++; + const runs = mockRunsByPeriod[idx] ?? []; + return makeAsyncGen(runs); + }); + + // Default: return any registered feedback for the given runId + mockListFeedback.mockImplementation( + ({ runIds }: { runIds: string[] }) => { + const feedbacks = mockFeedbackByRunId.get(runIds[0]) ?? []; + return makeAsyncGen(feedbacks); + }, + ); +}); + +// --------------------------------------------------------------------------- +// Import the handler after mocks are set up +// --------------------------------------------------------------------------- + +async function callGET(env: Record = {}) { + // Dynamically import to pick up the latest mock state + const { GET } = await import("../judge-dimensions/route"); + const req = new NextRequest("http://localhost/api/analytics/judge-dimensions"); + + const saved: Record = {}; + for (const [k, v] of Object.entries(env)) { + saved[k] = process.env[k]; + if (v === undefined) { + delete process.env[k]; + } else { + process.env[k] = v; + } + } + + try { + const res = await GET(req); + return res; + } finally { + for (const [k, v] of Object.entries(saved)) { + if (v === undefined) { + delete process.env[k]; + } else { + process.env[k] = v; + } + } + } +} + +// --------------------------------------------------------------------------- +// API key guard +// --------------------------------------------------------------------------- + +describe("API key guard", () => { + it("returns 503 when LANGSMITH_API_KEY is not set", async () => { + const res = await callGET({ LANGSMITH_API_KEY: undefined }); + expect(res.status).toBe(503); + }); + + it("returns error body when key is missing", async () => { + const res = await callGET({ LANGSMITH_API_KEY: undefined }); + const body = await res.json(); + expect(body).toHaveProperty("error"); + }); + + it("does not call listRuns when LANGSMITH_API_KEY is missing", async () => { + await callGET({ LANGSMITH_API_KEY: undefined }); + expect(mockListRuns).not.toHaveBeenCalled(); + }); +}); + +// --------------------------------------------------------------------------- +// Response shape +// --------------------------------------------------------------------------- + +describe("Response shape", () => { + it("returns 200 when key is present", async () => { + const res = await callGET({ LANGSMITH_API_KEY: "test-key" }); + expect(res.status).toBe(200); + }); + + it("response has dimensions and alerts keys", async () => { + const res = await callGET({ LANGSMITH_API_KEY: "test-key" }); + const body = await res.json(); + expect(body).toHaveProperty("dimensions"); + expect(body).toHaveProperty("alerts"); + }); + + it("dimensions contains an entry for every DIMENSION_ID", async () => { + const res = await callGET({ LANGSMITH_API_KEY: "test-key" }); + const body = await res.json(); + for (const dimId of DIMENSION_IDS) { + expect(body.dimensions).toHaveProperty(dimId); + } + }); + + it("each dimension entry has avg and trend fields", async () => { + const res = await callGET({ LANGSMITH_API_KEY: "test-key" }); + const body = await res.json(); + for (const dimId of DIMENSION_IDS) { + const entry = body.dimensions[dimId]; + expect(entry).toHaveProperty("avg"); + expect(entry).toHaveProperty("trend"); + expect(typeof entry.avg).toBe("number"); + expect(typeof entry.trend).toBe("number"); + } + }); + + it("alerts is an array", async () => { + const res = await callGET({ LANGSMITH_API_KEY: "test-key" }); + const body = await res.json(); + expect(Array.isArray(body.alerts)).toBe(true); + }); +}); + +// --------------------------------------------------------------------------- +// Score aggregation +// --------------------------------------------------------------------------- + +describe("Score aggregation", () => { + it("avg is 0 when there are no runs in the current period", async () => { + // no runs in either period — defaults to empty arrays + const res = await callGET({ LANGSMITH_API_KEY: "test-key" }); + const body = await res.json(); + for (const dimId of DIMENSION_IDS) { + expect(body.dimensions[dimId].avg).toBe(0); + } + }); + + it("computes avg correctly over multiple scores (denormalised 0-10)", async () => { + const dimId = DIMENSION_IDS[0]; // "flaw-detection" + mockRunsByPeriod = [ + [{ id: "run-1" }, { id: "run-2" }], + [], + ]; + // run-1: score 0.7 (→ 7 after ×10), run-2: score 0.9 (→ 9 after ×10) + mockFeedbackByRunId.set("run-1", [{ key: dimId, score: 0.7 }]); + mockFeedbackByRunId.set("run-2", [{ key: dimId, score: 0.9 }]); + + const res = await callGET({ LANGSMITH_API_KEY: "test-key" }); + const body = await res.json(); + // avg = (7 + 9) / 2 = 8.0 + expect(body.dimensions[dimId].avg).toBe(8.0); + }); + + it("rounds avg to 2 decimal places", async () => { + const dimId = DIMENSION_IDS[0]; + // Three scores: 0.1 → 1, 0.2 → 2, 0.3 → 3: avg = 6/3 = 2.0 → rounded fine + // Use values that would produce a repeating decimal: 1/3 ≈ 0.333... + // 0.1 → 1, 0.2 → 2, 0.4 → 4: avg = 7/3 ≈ 2.333... → rounds to 2.33 + mockRunsByPeriod = [[{ id: "r1" }, { id: "r2" }, { id: "r3" }], []]; + mockFeedbackByRunId.set("r1", [{ key: dimId, score: 0.1 }]); + mockFeedbackByRunId.set("r2", [{ key: dimId, score: 0.2 }]); + mockFeedbackByRunId.set("r3", [{ key: dimId, score: 0.4 }]); + + const res = await callGET({ LANGSMITH_API_KEY: "test-key" }); + const body = await res.json(); + // avg = (1 + 2 + 4) / 3 = 7/3 ≈ 2.333... → 2.33 + expect(body.dimensions[dimId].avg).toBe(2.33); + }); + + it("ignores feedback keys that are not in DIMENSION_IDS", async () => { + const dimId = DIMENSION_IDS[0]; + mockRunsByPeriod = [[{ id: "run-x" }], []]; + mockFeedbackByRunId.set("run-x", [ + { key: "unknown-dimension", score: 0.9 }, + { key: dimId, score: 0.5 }, + ]); + + const res = await callGET({ LANGSMITH_API_KEY: "test-key" }); + const body = await res.json(); + // Only the valid dimension score (0.5 → 5) should be counted + expect(body.dimensions[dimId].avg).toBe(5.0); + // The unknown key should not appear in the response + expect(body.dimensions).not.toHaveProperty("unknown-dimension"); + }); + + it("ignores feedback entries with null or undefined score", async () => { + const dimId = DIMENSION_IDS[0]; + mockRunsByPeriod = [[{ id: "run-null" }], []]; + mockFeedbackByRunId.set("run-null", [ + { key: dimId, score: null }, + { key: dimId, score: undefined }, + ] as FeedbackEntry[]); + + const res = await callGET({ LANGSMITH_API_KEY: "test-key" }); + const body = await res.json(); + // All null/undefined scores ignored → avg stays 0 + expect(body.dimensions[dimId].avg).toBe(0); + }); +}); + +// --------------------------------------------------------------------------- +// Trend calculation +// --------------------------------------------------------------------------- + +describe("Trend calculation", () => { + it("trend is 0 when there is no prior period data", async () => { + const dimId = DIMENSION_IDS[0]; + mockRunsByPeriod = [[{ id: "run-cur" }], []]; // prior period empty + mockFeedbackByRunId.set("run-cur", [{ key: dimId, score: 0.8 }]); + + const res = await callGET({ LANGSMITH_API_KEY: "test-key" }); + const body = await res.json(); + expect(body.dimensions[dimId].trend).toBe(0); + }); + + it("trend is positive when current avg is higher than prior", async () => { + const dimId = DIMENSION_IDS[0]; + mockRunsByPeriod = [[{ id: "cur" }], [{ id: "pri" }]]; + // current: 0.8 → 8, prior: 0.4 → 4 => trend = (8-4)/4 * 100 = 100% + mockFeedbackByRunId.set("cur", [{ key: dimId, score: 0.8 }]); + mockFeedbackByRunId.set("pri", [{ key: dimId, score: 0.4 }]); + + const res = await callGET({ LANGSMITH_API_KEY: "test-key" }); + const body = await res.json(); + expect(body.dimensions[dimId].trend).toBeGreaterThan(0); + expect(body.dimensions[dimId].trend).toBeCloseTo(100, 0); + }); + + it("trend is negative when current avg is lower than prior", async () => { + const dimId = DIMENSION_IDS[0]; + mockRunsByPeriod = [[{ id: "cur" }], [{ id: "pri" }]]; + // current: 0.4 → 4, prior: 0.8 → 8 => trend = (4-8)/8 * 100 = -50% + mockFeedbackByRunId.set("cur", [{ key: dimId, score: 0.4 }]); + mockFeedbackByRunId.set("pri", [{ key: dimId, score: 0.8 }]); + + const res = await callGET({ LANGSMITH_API_KEY: "test-key" }); + const body = await res.json(); + expect(body.dimensions[dimId].trend).toBeLessThan(0); + expect(body.dimensions[dimId].trend).toBeCloseTo(-50, 0); + }); + + it("trend is 0 when prior and current averages are equal", async () => { + const dimId = DIMENSION_IDS[0]; + mockRunsByPeriod = [[{ id: "cur" }], [{ id: "pri" }]]; + mockFeedbackByRunId.set("cur", [{ key: dimId, score: 0.7 }]); + mockFeedbackByRunId.set("pri", [{ key: dimId, score: 0.7 }]); + + const res = await callGET({ LANGSMITH_API_KEY: "test-key" }); + const body = await res.json(); + expect(body.dimensions[dimId].trend).toBe(0); + }); + + it("trend is rounded to 2 decimal places", async () => { + const dimId = DIMENSION_IDS[0]; + // current: 0.7 → 7, prior: 0.6 → 6 => trend = (7-6)/6 * 100 ≈ 16.666...% → 16.67 + mockRunsByPeriod = [[{ id: "cur" }], [{ id: "pri" }]]; + mockFeedbackByRunId.set("cur", [{ key: dimId, score: 0.7 }]); + mockFeedbackByRunId.set("pri", [{ key: dimId, score: 0.6 }]); + + const res = await callGET({ LANGSMITH_API_KEY: "test-key" }); + const body = await res.json(); + expect(body.dimensions[dimId].trend).toBe(16.67); + }); +}); + +// --------------------------------------------------------------------------- +// Alerts +// --------------------------------------------------------------------------- + +describe("Alerts", () => { + it("no alert when current period has no data (prior avg = 0)", async () => { + const res = await callGET({ LANGSMITH_API_KEY: "test-key" }); + const body = await res.json(); + expect(body.alerts).toHaveLength(0); + }); + + it("no alert when drop is exactly -10% (boundary — strictly > 10% required)", async () => { + const dimId = DIMENSION_IDS[0]; + // prior avg = 10, current avg = 9 → drop = exactly 10% → NO alert + mockRunsByPeriod = [[{ id: "cur" }], [{ id: "pri" }]]; + mockFeedbackByRunId.set("cur", [{ key: dimId, score: 0.9 }]); + mockFeedbackByRunId.set("pri", [{ key: dimId, score: 1.0 }]); + + const res = await callGET({ LANGSMITH_API_KEY: "test-key" }); + const body = await res.json(); + expect(body.alerts).toHaveLength(0); + }); + + it("fires alert when drop is greater than 10%", async () => { + const dimId = DIMENSION_IDS[0]; + // prior avg = 10, current avg = 8 → drop = 20% → alert + mockRunsByPeriod = [[{ id: "cur" }], [{ id: "pri" }]]; + mockFeedbackByRunId.set("cur", [{ key: dimId, score: 0.8 }]); + mockFeedbackByRunId.set("pri", [{ key: dimId, score: 1.0 }]); + + const res = await callGET({ LANGSMITH_API_KEY: "test-key" }); + const body = await res.json(); + expect(body.alerts.length).toBeGreaterThanOrEqual(1); + }); + + it("alert message contains the dimension id", async () => { + const dimId = DIMENSION_IDS[0]; // "flaw-detection" + mockRunsByPeriod = [[{ id: "cur" }], [{ id: "pri" }]]; + mockFeedbackByRunId.set("cur", [{ key: dimId, score: 0.8 }]); + mockFeedbackByRunId.set("pri", [{ key: dimId, score: 1.0 }]); + + const res = await callGET({ LANGSMITH_API_KEY: "test-key" }); + const body = await res.json(); + expect(body.alerts.some((a: string) => a.includes(dimId))).toBe(true); + }); + + it("alert message contains the percentage drop magnitude", async () => { + const dimId = DIMENSION_IDS[0]; + // prior = 10, current = 8 → 20% drop + mockRunsByPeriod = [[{ id: "cur" }], [{ id: "pri" }]]; + mockFeedbackByRunId.set("cur", [{ key: dimId, score: 0.8 }]); + mockFeedbackByRunId.set("pri", [{ key: dimId, score: 1.0 }]); + + const res = await callGET({ LANGSMITH_API_KEY: "test-key" }); + const body = await res.json(); + const alert: string = body.alerts.find((a: string) => a.includes(dimId)); + expect(alert).toContain("20.0%"); + }); + + it("multiple dimensions can fire alerts in the same response", async () => { + // Both dim 0 and dim 1 drop >10% + const dim0 = DIMENSION_IDS[0]; + const dim1 = DIMENSION_IDS[1]; + + mockRunsByPeriod = [[{ id: "cur0" }, { id: "cur1" }], [{ id: "pri0" }, { id: "pri1" }]]; + + // Use separate call tracking via IDs + mockFeedbackByRunId.set("cur0", [{ key: dim0, score: 0.7 }]); + mockFeedbackByRunId.set("cur1", [{ key: dim1, score: 0.6 }]); + mockFeedbackByRunId.set("pri0", [{ key: dim0, score: 1.0 }]); + mockFeedbackByRunId.set("pri1", [{ key: dim1, score: 1.0 }]); + + const res = await callGET({ LANGSMITH_API_KEY: "test-key" }); + const body = await res.json(); + expect(body.alerts.length).toBeGreaterThanOrEqual(2); + }); +}); + +// --------------------------------------------------------------------------- +// Error handling +// --------------------------------------------------------------------------- + +describe("Error handling", () => { + it("returns 500 if listRuns throws", async () => { + mockListRuns.mockImplementationOnce(() => { + throw new Error("LangSmith API error"); + }); + + const res = await callGET({ LANGSMITH_API_KEY: "test-key" }); + expect(res.status).toBe(500); + }); +}); diff --git a/src/app/api/analytics/judge-dimensions/route.ts b/src/app/api/analytics/judge-dimensions/route.ts new file mode 100644 index 0000000000000000000000000000000000000000..2dc2c0bde3a5106b97334aa92b76eb1368f750bf --- /dev/null +++ b/src/app/api/analytics/judge-dimensions/route.ts @@ -0,0 +1,108 @@ +import { NextResponse } from "next/server"; +import { langsmithClient } from "@/lib/langsmith"; +import { DIMENSION_IDS } from "@/lib/debate/judge"; +import { withApiError } from "@/lib/api-error"; + +// --------------------------------------------------------------------------- +// Types +// --------------------------------------------------------------------------- + +interface DimensionStats { + avg: number; + trend: number; // % change vs prior 7-day period (negative = declined) +} + +interface AnalyticsResponse { + dimensions: Record; + alerts: string[]; +} + +// --------------------------------------------------------------------------- +// Helpers +// --------------------------------------------------------------------------- + +/** + * Collect feedback scores for all judge runs in [start, end). + * Returns a map: dimensionId → number[] of scores. + */ +async function collectDimensionScores( + start: Date, + end: Date, +): Promise> { + const scores: Record = {}; + for (const dimId of DIMENSION_IDS) { + scores[dimId] = []; + } + + for await (const run of langsmithClient.listRuns({ + projectName: process.env.LANGSMITH_PROJECT ?? "default", + filter: `and(eq(name, "debate-judge-round"), lt(start_time, "${end.toISOString()}"))`, + startTime: start, + })) { + // For each run, fetch its feedback + for await (const fb of langsmithClient.listFeedback({ + runIds: [run.id], + })) { + const key = fb.key; // dimension id + if (key && scores[key] !== undefined && typeof fb.score === "number") { + scores[key].push(fb.score * 10); // denormalise 0-1 → 0-10 + } + } + } + + return scores; +} + +function avg(nums: number[]): number { + if (nums.length === 0) return 0; + return Math.round((nums.reduce((a, b) => a + b, 0) / nums.length) * 100) / 100; +} + +// --------------------------------------------------------------------------- +// GET /api/analytics/judge-dimensions +// --------------------------------------------------------------------------- + +export const GET = withApiError(async () => { + if (!process.env.LANGSMITH_API_KEY) { + return NextResponse.json( + { error: "LANGSMITH_API_KEY is not configured" }, + { status: 503 }, + ); + } + + const now = new Date(); + const sevenDaysAgo = new Date(now.getTime() - 7 * 24 * 60 * 60 * 1000); + const fourteenDaysAgo = new Date(now.getTime() - 14 * 24 * 60 * 60 * 1000); + + // Fetch current and prior period scores in parallel + const [currentScores, priorScores] = await Promise.all([ + collectDimensionScores(sevenDaysAgo, now), + collectDimensionScores(fourteenDaysAgo, sevenDaysAgo), + ]); + + const dimensions: Record = {}; + const alerts: string[] = []; + + for (const dimId of DIMENSION_IDS) { + const currentAvg = avg(currentScores[dimId]); + const priorAvg = avg(priorScores[dimId]); + + // trend: % change from prior period (0 if no prior data) + const trend = + priorAvg > 0 + ? Math.round(((currentAvg - priorAvg) / priorAvg) * 100 * 100) / 100 + : 0; + + dimensions[dimId] = { avg: currentAvg, trend }; + + // Alert: flag if 7-day avg dropped >10% vs prior period + if (priorAvg > 0 && trend < -10) { + alerts.push( + `${dimId}: avg dropped ${Math.abs(trend).toFixed(1)}% (${priorAvg.toFixed(1)} → ${currentAvg.toFixed(1)})`, + ); + } + } + + const response: AnalyticsResponse = { dimensions, alerts }; + return NextResponse.json(response); +}); diff --git a/src/app/api/chess/__tests__/challenge.test.ts b/src/app/api/chess/__tests__/challenge.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..c7fefeea79ac4cbe2fdbd5b2d0f78a0578530272 --- /dev/null +++ b/src/app/api/chess/__tests__/challenge.test.ts @@ -0,0 +1,229 @@ +/** + * Tests for /api/chess/challenge route. + * + * Covers: + * - clampStockfishLevel — pure level-clamping function + * - POST handler — token guard (503), Lichess failure (502), success (200) + */ + +import { describe, it, expect, vi, beforeEach, afterEach } from "vitest"; +import { NextRequest, NextResponse } from "next/server"; + +// --------------------------------------------------------------------------- +// Mock challengeStockfish (avoid real network calls) +// --------------------------------------------------------------------------- + +const mockChallengeStockfish = vi.fn(); + +vi.mock("@/lib/lichess", () => ({ + challengeStockfish: (...args: unknown[]) => mockChallengeStockfish(...args), +})); + +// --------------------------------------------------------------------------- +// Imports (after mocks) +// --------------------------------------------------------------------------- + +import { POST, clampStockfishLevel } from "../challenge/route"; + +// --------------------------------------------------------------------------- +// Helpers +// --------------------------------------------------------------------------- + +const originalEnv = { ...process.env }; + +function makeRequest(body?: Record): NextRequest { + return new NextRequest("http://localhost/api/chess/challenge", { + method: "POST", + body: body !== undefined ? JSON.stringify(body) : undefined, + headers: { "Content-Type": "application/json" }, + }); +} + +async function parseJson(res: NextResponse): Promise { + return res.json(); +} + +beforeEach(() => { + mockChallengeStockfish.mockReset(); + process.env = { ...originalEnv, LICHESS_API_TOKEN: "test-token" }; +}); + +afterEach(() => { + process.env = originalEnv; +}); + +// ─── clampStockfishLevel ───────────────────────────────────────────────────── + +describe("clampStockfishLevel", () => { + it("returns the level unchanged when in range [1, 8]", () => { + expect(clampStockfishLevel(1)).toBe(1); + expect(clampStockfishLevel(4)).toBe(4); + expect(clampStockfishLevel(8)).toBe(8); + }); + + it("clamps values below 1 to 1", () => { + expect(clampStockfishLevel(0)).toBe(1); + expect(clampStockfishLevel(-5)).toBe(1); + expect(clampStockfishLevel(-Infinity)).toBe(1); + }); + + it("clamps values above 8 to 8", () => { + expect(clampStockfishLevel(9)).toBe(8); + expect(clampStockfishLevel(100)).toBe(8); + expect(clampStockfishLevel(Infinity)).toBe(8); + }); + + it("rounds fractional levels to the nearest integer", () => { + expect(clampStockfishLevel(3.5)).toBe(4); + expect(clampStockfishLevel(3.4)).toBe(3); + expect(clampStockfishLevel(7.9)).toBe(8); + }); + + it("defaults to 4 when level is undefined", () => { + expect(clampStockfishLevel(undefined)).toBe(4); + }); + + it("defaults to 4 when level is null", () => { + expect(clampStockfishLevel(null)).toBe(4); + }); + + it("defaults to 4 when level is a string", () => { + expect(clampStockfishLevel("5")).toBe(4); + }); + + it("defaults to 4 when level is a boolean", () => { + expect(clampStockfishLevel(true)).toBe(4); + }); + + it("defaults to 4 when level is an object", () => { + expect(clampStockfishLevel({})).toBe(4); + }); +}); + +// ─── POST /api/chess/challenge — token guard ───────────────────────────────── + +describe("POST /api/chess/challenge — LICHESS_API_TOKEN guard", () => { + it("returns 503 when LICHESS_API_TOKEN is not set", async () => { + delete process.env.LICHESS_API_TOKEN; + + const res = await POST(makeRequest({ level: 4 })); + expect(res.status).toBe(503); + + const body = await parseJson(res) as { error: string }; + expect(body.error).toContain("LICHESS_API_TOKEN"); + }); + + it("returns 503 when LICHESS_API_TOKEN is an empty string", async () => { + process.env.LICHESS_API_TOKEN = ""; + + const res = await POST(makeRequest({ level: 4 })); + expect(res.status).toBe(503); + }); + + it("does not call challengeStockfish when token is missing", async () => { + delete process.env.LICHESS_API_TOKEN; + await POST(makeRequest({ level: 4 })); + expect(mockChallengeStockfish).not.toHaveBeenCalled(); + }); +}); + +// ─── POST /api/chess/challenge — Lichess failure ───────────────────────────── + +describe("POST /api/chess/challenge — Lichess failure (502)", () => { + it("returns 502 when challengeStockfish returns null", async () => { + mockChallengeStockfish.mockResolvedValueOnce(null); + + const res = await POST(makeRequest({ level: 3 })); + expect(res.status).toBe(502); + + const body = await parseJson(res) as { error: string }; + expect(body.error).toMatch(/Failed to create Stockfish challenge/i); + }); + + it("still calls challengeStockfish with the correct level when token is present", async () => { + mockChallengeStockfish.mockResolvedValueOnce(null); + + await POST(makeRequest({ level: 6 })); + + expect(mockChallengeStockfish).toHaveBeenCalledWith(6); + }); +}); + +// ─── POST /api/chess/challenge — success ───────────────────────────────────── + +describe("POST /api/chess/challenge — success", () => { + const MOCK_CHALLENGE = { + id: "abc123xyz", + url: "https://lichess.org/abc123xyz", + }; + + it("returns 200 with gameId, gameUrl, and level on success", async () => { + mockChallengeStockfish.mockResolvedValueOnce(MOCK_CHALLENGE); + + const res = await POST(makeRequest({ level: 5 })); + expect(res.status).toBe(200); + + const body = await parseJson(res) as { gameId: string; gameUrl: string; level: number }; + expect(body.gameId).toBe("abc123xyz"); + expect(body.gameUrl).toBe("https://lichess.org/abc123xyz"); + expect(body.level).toBe(5); + }); + + it("defaults level to 4 when no body is provided", async () => { + mockChallengeStockfish.mockResolvedValueOnce(MOCK_CHALLENGE); + + const res = await POST( + new NextRequest("http://localhost/api/chess/challenge", { method: "POST" }) + ); + expect(res.status).toBe(200); + + const body = await parseJson(res) as { level: number }; + expect(body.level).toBe(4); + + expect(mockChallengeStockfish).toHaveBeenCalledWith(4); + }); + + it("defaults level to 4 when level is omitted from body", async () => { + mockChallengeStockfish.mockResolvedValueOnce(MOCK_CHALLENGE); + + const res = await POST(makeRequest({})); + const body = await parseJson(res) as { level: number }; + expect(body.level).toBe(4); + }); + + it("clamps level 9 → 8 and passes 8 to challengeStockfish", async () => { + mockChallengeStockfish.mockResolvedValueOnce(MOCK_CHALLENGE); + + const res = await POST(makeRequest({ level: 9 })); + expect(res.status).toBe(200); + + const body = await parseJson(res) as { level: number }; + expect(body.level).toBe(8); + expect(mockChallengeStockfish).toHaveBeenCalledWith(8); + }); + + it("clamps level 0 → 1 and passes 1 to challengeStockfish", async () => { + mockChallengeStockfish.mockResolvedValueOnce(MOCK_CHALLENGE); + + const res = await POST(makeRequest({ level: 0 })); + expect(res.status).toBe(200); + + const body = await parseJson(res) as { level: number }; + expect(body.level).toBe(1); + expect(mockChallengeStockfish).toHaveBeenCalledWith(1); + }); + + it("passes level 1 through unchanged", async () => { + mockChallengeStockfish.mockResolvedValueOnce(MOCK_CHALLENGE); + + await POST(makeRequest({ level: 1 })); + expect(mockChallengeStockfish).toHaveBeenCalledWith(1); + }); + + it("passes level 8 through unchanged", async () => { + mockChallengeStockfish.mockResolvedValueOnce(MOCK_CHALLENGE); + + await POST(makeRequest({ level: 8 })); + expect(mockChallengeStockfish).toHaveBeenCalledWith(8); + }); +}); diff --git a/src/app/api/chess/__tests__/game-result-route.test.ts b/src/app/api/chess/__tests__/game-result-route.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..8c6d92294de454d5894b9ca8f20f16b6c62a43d1 --- /dev/null +++ b/src/app/api/chess/__tests__/game-result-route.test.ts @@ -0,0 +1,570 @@ +/** + * Tests for POST /api/chess/game-result route handler. + * + * Covers: + * Input validation + * - invalid JSON body → 400 + * - missing gameId → 400 + * - non-string gameId → 400 + * - level out of range (< 1) → 400 + * - level out of range (> 8) → 400 + * - non-number level → 400 + * - invalid result value → 400 + * - missing result → 400 + * + * DB guards + * - user not found → 404 + * - missing chess CategorySkill → 500 + * + * Success path + * - response shape (result, level, qualityScore, xp, levelUp, categoryXp, unlocks) + * - win result → qualityScore > draw > loss + * - XP base = 30, quality bonus up to 30 + * - isCriticalHit doubles totalXp + * - multiplierPercent reflected in xp breakdown + * - DailyLog created when no existing log + * - DailyLog updated when existing log exists + * - goalMet flag set when XP reaches dailyGoalXp + * - processSkillUnlocks called on category level-up + * - processSkillUnlocks NOT called when no category level-up + * - newTitle included when title changes on level-up + * - newTitle absent when no title change + * - userId defaults to 1 when omitted + * - unlocks and streakFreezesGranted reflected in response + */ + +import { describe, it, expect, vi, beforeEach } from "vitest"; +import { NextRequest } from "next/server"; + +// --------------------------------------------------------------------------- +// Mock Prisma +// --------------------------------------------------------------------------- + +const mockUserFindFirst = vi.fn(); +const mockDailyLogFindFirst = vi.fn(); +const mockTransaction = vi.fn(); +const mockActivityCreate = vi.fn(); +const mockUserUpdate = vi.fn(); +const mockCategorySkillUpdate = vi.fn(); +const mockDailyLogCreate = vi.fn(); +const mockDailyLogUpdate = vi.fn(); + +vi.mock("@/lib/db", () => ({ + prisma: { + user: { + findFirst: (...args: unknown[]) => mockUserFindFirst(...args), + }, + dailyLog: { + findFirst: (...args: unknown[]) => mockDailyLogFindFirst(...args), + }, + $transaction: (...args: unknown[]) => mockTransaction(...args), + }, +})); + +// --------------------------------------------------------------------------- +// Mock rollCriticalHit +// --------------------------------------------------------------------------- + +const mockRollCriticalHit = vi.fn(() => false); + +vi.mock("@/lib/xp", async (importOriginal) => { + const actual = await importOriginal(); + return { + ...actual, + rollCriticalHit: () => mockRollCriticalHit(), + }; +}); + +// --------------------------------------------------------------------------- +// Mock getMultiplierPercent +// --------------------------------------------------------------------------- + +const mockGetMultiplierPercent = vi.fn(() => Promise.resolve(0)); + +vi.mock("@/lib/multiplier", () => ({ + getMultiplierPercent: (...args: unknown[]) => + (mockGetMultiplierPercent as (...a: unknown[]) => unknown)(...args), +})); + +// --------------------------------------------------------------------------- +// Mock processSkillUnlocks +// --------------------------------------------------------------------------- + +const mockProcessSkillUnlocks = vi.fn( + (): Promise<{ unlocked: string[]; streakFreezesGranted: number }> => + Promise.resolve({ unlocked: [], streakFreezesGranted: 0 }), +); + +vi.mock("@/lib/skill-unlock", () => ({ + processSkillUnlocks: (...args: unknown[]) => + (mockProcessSkillUnlocks as (...a: unknown[]) => unknown)(...args), +})); + +// --------------------------------------------------------------------------- +// Mock processEndOfDay (no-op — streak logic is tested separately) +// --------------------------------------------------------------------------- + +vi.mock("@/lib/streak", () => ({ + processEndOfDay: vi.fn(() => Promise.resolve({ + streak: 1, + freezeUsed: false, + streakBroken: false, + alreadyProcessed: false, + })), +})); + +// --------------------------------------------------------------------------- +// Import route after mocks +// --------------------------------------------------------------------------- + +import { POST } from "../game-result/route"; + +// --------------------------------------------------------------------------- +// Helpers +// --------------------------------------------------------------------------- + +async function json(res: Response): Promise { + return res.json(); +} + +function makePost(body?: Record): NextRequest { + return new NextRequest("http://localhost/api/chess/game-result", { + method: "POST", + body: body !== undefined ? JSON.stringify(body) : "not-json{{{", + headers: { "Content-Type": "application/json" }, + }); +} + +function makePostValid(overrides: Record = {}): NextRequest { + return new NextRequest("http://localhost/api/chess/game-result", { + method: "POST", + body: JSON.stringify({ + gameId: "abc123", + level: 4, + result: "win", + ...overrides, + }), + headers: { "Content-Type": "application/json" }, + }); +} + +/** Stub user with chess CategorySkill */ +function makeUser(overrides: Record = {}) { + return { + id: 1, + name: "Player One", + level: 1, + totalXp: 0, + currentXp: 0, + xpToNextLevel: 1000, + title: "Smooth Brain", + dailyGoalXp: 100, + streak: 3, + longestStreak: 10, + streakFreezes: 1, + lichessUsername: null, + chesscomUsername: null, + createdAt: new Date(), + categorySkills: [ + { + id: 20, + userId: 1, + category: "chess", + level: 1, + totalXp: 0, + currentXp: 0, + xpToNext: 1000, + }, + ], + ...overrides, + }; +} + +/** Wire up mockTransaction to execute the callback with a fake tx client */ +function setupTransaction() { + mockTransaction.mockImplementation( + async (callback: (tx: Record) => Promise) => { + const tx = { + activity: { create: mockActivityCreate }, + user: { update: mockUserUpdate }, + categorySkill: { update: mockCategorySkillUpdate }, + dailyLog: { + create: mockDailyLogCreate, + update: mockDailyLogUpdate, + }, + }; + return callback(tx); + }, + ); +} + +beforeEach(() => { + vi.clearAllMocks(); + mockUserFindFirst.mockResolvedValue(makeUser()); + mockDailyLogFindFirst.mockResolvedValue(null); + mockRollCriticalHit.mockReturnValue(false); + mockGetMultiplierPercent.mockResolvedValue(0); + mockProcessSkillUnlocks.mockResolvedValue({ unlocked: [], streakFreezesGranted: 0 }); + setupTransaction(); + mockActivityCreate.mockResolvedValue({}); + mockUserUpdate.mockResolvedValue({}); + mockCategorySkillUpdate.mockResolvedValue({}); + mockDailyLogCreate.mockResolvedValue({}); + mockDailyLogUpdate.mockResolvedValue({}); +}); + +// --------------------------------------------------------------------------- +// Input validation +// --------------------------------------------------------------------------- + +describe("POST /api/chess/game-result — input validation", () => { + it("returns 400 on invalid JSON body", async () => { + const res = await POST(makePost()); // body is not-json{{{ + expect(res.status).toBe(400); + const body = (await json(res)) as { error: string }; + expect(body.error).toMatch(/invalid json/i); + }); + + it("returns 400 when gameId is missing", async () => { + const res = await POST(makePostValid({ gameId: undefined })); + expect(res.status).toBe(400); + const body = (await json(res)) as { error: string }; + expect(body.error).toMatch(/gameid/i); + }); + + it("returns 400 when gameId is not a string", async () => { + const res = await POST(makePostValid({ gameId: 42 })); + expect(res.status).toBe(400); + const body = (await json(res)) as { error: string }; + expect(body.error).toMatch(/gameid/i); + }); + + it("returns 400 when level is below 1", async () => { + const res = await POST(makePostValid({ level: 0 })); + expect(res.status).toBe(400); + const body = (await json(res)) as { error: string }; + expect(body.error).toMatch(/level/i); + }); + + it("returns 400 when level exceeds 8", async () => { + const res = await POST(makePostValid({ level: 9 })); + expect(res.status).toBe(400); + const body = (await json(res)) as { error: string }; + expect(body.error).toMatch(/level/i); + }); + + it("returns 400 when level is not a number", async () => { + const res = await POST(makePostValid({ level: "hard" })); + expect(res.status).toBe(400); + const body = (await json(res)) as { error: string }; + expect(body.error).toMatch(/level/i); + }); + + it("returns 400 when result is an invalid value", async () => { + const res = await POST(makePostValid({ result: "draw-by-repetition" })); + expect(res.status).toBe(400); + const body = (await json(res)) as { error: string }; + expect(body.error).toMatch(/result/i); + }); + + it("returns 400 when result is missing", async () => { + const res = await POST(makePostValid({ result: undefined })); + expect(res.status).toBe(400); + const body = (await json(res)) as { error: string }; + expect(body.error).toMatch(/result/i); + }); +}); + +// --------------------------------------------------------------------------- +// DB guards +// --------------------------------------------------------------------------- + +describe("POST /api/chess/game-result — DB guards", () => { + it("returns 404 when user is not found", async () => { + mockUserFindFirst.mockResolvedValue(null); + const res = await POST(makePostValid()); + expect(res.status).toBe(404); + }); + + it("returns 500 when chess CategorySkill is missing", async () => { + mockUserFindFirst.mockResolvedValue(makeUser({ categorySkills: [] })); + const res = await POST(makePostValid()); + expect(res.status).toBe(500); + }); +}); + +// --------------------------------------------------------------------------- +// Success path — response shape +// --------------------------------------------------------------------------- + +describe("POST /api/chess/game-result — success shape", () => { + it("returns 200 with expected fields for a win", async () => { + const res = await POST(makePostValid({ result: "win", level: 4 })); + expect(res.status).toBe(200); + const body = (await json(res)) as Record; + + expect(body.result).toBe("win"); + expect(body.level).toBe(4); + expect(typeof body.qualityScore).toBe("number"); + expect(body.xp).toBeDefined(); + expect(typeof body.levelUp).toBe("boolean"); + expect(body.categoryXp).toBeDefined(); + expect(Array.isArray(body.unlocks)).toBe(true); + }); + + it("win qualityScore > draw qualityScore at same level", async () => { + const winRes = await POST(makePostValid({ result: "win", level: 4 })); + const winBody = (await json(winRes)) as { qualityScore: number }; + + mockUserFindFirst.mockResolvedValue(makeUser()); + mockDailyLogFindFirst.mockResolvedValue(null); + setupTransaction(); + + const drawRes = await POST(makePostValid({ result: "draw", level: 4 })); + const drawBody = (await json(drawRes)) as { qualityScore: number }; + + expect(winBody.qualityScore).toBeGreaterThan(drawBody.qualityScore); + }); + + it("draw qualityScore > loss qualityScore at same level", async () => { + const drawRes = await POST(makePostValid({ result: "draw", level: 4 })); + const drawBody = (await json(drawRes)) as { qualityScore: number }; + + mockUserFindFirst.mockResolvedValue(makeUser()); + mockDailyLogFindFirst.mockResolvedValue(null); + setupTransaction(); + + const lossRes = await POST(makePostValid({ result: "loss", level: 4 })); + const lossBody = (await json(lossRes)) as { qualityScore: number }; + + expect(drawBody.qualityScore).toBeGreaterThan(lossBody.qualityScore); + }); + + it("XP breakdown includes baseXp = 30", async () => { + const res = await POST(makePostValid({ result: "win", level: 8 })); + const body = (await json(res)) as { xp: { baseXp: number } }; + expect(body.xp.baseXp).toBe(30); + }); + + it("XP quality bonus is positive for a win", async () => { + const res = await POST(makePostValid({ result: "win", level: 4 })); + const body = (await json(res)) as { xp: { qualityBonus: number } }; + expect(body.xp.qualityBonus).toBeGreaterThan(0); + }); + + it("XP quality bonus is 0 for a loss at level 1 (small bonus only)", async () => { + // Even a loss earns a small quality bonus (0.1–0.2) so totalXp > baseXp + const res = await POST(makePostValid({ result: "loss", level: 1 })); + const body = (await json(res)) as { xp: { totalXp: number; baseXp: number } }; + expect(body.xp.totalXp).toBeGreaterThan(body.xp.baseXp); + }); +}); + +// --------------------------------------------------------------------------- +// Critical hit +// --------------------------------------------------------------------------- + +describe("POST /api/chess/game-result — critical hit", () => { + it("doubles totalXp on critical hit", async () => { + // No crit: baseline + mockRollCriticalHit.mockReturnValue(false); + const normalRes = await POST(makePostValid({ result: "win", level: 4 })); + const normalBody = (await json(normalRes)) as { xp: { totalXp: number; isCriticalHit: boolean } }; + expect(normalBody.xp.isCriticalHit).toBe(false); + const normalXp = normalBody.xp.totalXp; + + mockUserFindFirst.mockResolvedValue(makeUser()); + mockDailyLogFindFirst.mockResolvedValue(null); + setupTransaction(); + + // With crit + mockRollCriticalHit.mockReturnValue(true); + const critRes = await POST(makePostValid({ result: "win", level: 4 })); + const critBody = (await json(critRes)) as { xp: { totalXp: number; isCriticalHit: boolean } }; + expect(critBody.xp.isCriticalHit).toBe(true); + expect(critBody.xp.totalXp).toBe(normalXp * 2); + }); +}); + +// --------------------------------------------------------------------------- +// Multiplier +// --------------------------------------------------------------------------- + +describe("POST /api/chess/game-result — multiplier", () => { + it("reflects multiplierPercent in xp breakdown", async () => { + mockGetMultiplierPercent.mockResolvedValue(25); + const res = await POST(makePostValid({ result: "win", level: 4 })); + const body = (await json(res)) as { xp: { multiplierPercent: number; multiplierBonus: number } }; + expect(body.xp.multiplierPercent).toBe(25); + expect(body.xp.multiplierBonus).toBeGreaterThan(0); + }); + + it("multiplierBonus is 0 when no active multipliers", async () => { + mockGetMultiplierPercent.mockResolvedValue(0); + const res = await POST(makePostValid({ result: "win", level: 4 })); + const body = (await json(res)) as { xp: { multiplierBonus: number } }; + expect(body.xp.multiplierBonus).toBe(0); + }); +}); + +// --------------------------------------------------------------------------- +// DailyLog handling +// --------------------------------------------------------------------------- + +describe("POST /api/chess/game-result — DailyLog", () => { + it("creates a new DailyLog when none exists for today", async () => { + mockDailyLogFindFirst.mockResolvedValue(null); + await POST(makePostValid()); + expect(mockDailyLogCreate).toHaveBeenCalledTimes(1); + expect(mockDailyLogUpdate).not.toHaveBeenCalled(); + }); + + it("updates an existing DailyLog when one exists", async () => { + mockDailyLogFindFirst.mockResolvedValue({ + id: 99, + xpEarned: 50, + activityCount: 2, + goalMet: false, + }); + await POST(makePostValid()); + expect(mockDailyLogUpdate).toHaveBeenCalledTimes(1); + expect(mockDailyLogCreate).not.toHaveBeenCalled(); + }); + + it("sets goalMet=true when accumulated XP meets dailyGoalXp", async () => { + // dailyGoalXp = 100; existing 80 XP; win at level 8 yields ≥30 XP → total ≥ 110 + mockUserFindFirst.mockResolvedValue(makeUser({ dailyGoalXp: 100 })); + mockDailyLogFindFirst.mockResolvedValue({ + id: 5, + xpEarned: 80, + activityCount: 3, + goalMet: false, + }); + await POST(makePostValid({ result: "win", level: 8 })); + const updateCall = mockDailyLogUpdate.mock.calls[0][0] as { + data: { goalMet: boolean }; + }; + expect(updateCall.data.goalMet).toBe(true); + }); +}); + +// --------------------------------------------------------------------------- +// Skill unlocks +// --------------------------------------------------------------------------- + +describe("POST /api/chess/game-result — skill unlocks", () => { + it("calls processSkillUnlocks on category level-up", async () => { + // Give enough category XP to level up (currentXp + earned >= xpToNext) + mockUserFindFirst.mockResolvedValue( + makeUser({ + categorySkills: [ + { id: 20, userId: 1, category: "chess", level: 1, totalXp: 0, currentXp: 95, xpToNext: 100 }, + ], + }), + ); + mockProcessSkillUnlocks.mockResolvedValue({ unlocked: ["Chess Vision"], streakFreezesGranted: 0 }); + + const res = await POST(makePostValid({ result: "win", level: 8 })); + expect(mockProcessSkillUnlocks).toHaveBeenCalled(); + + const body = (await json(res)) as { unlocks: string[] }; + expect(body.unlocks).toContain("Chess Vision"); + }); + + it("does NOT call processSkillUnlocks when no category level-up", async () => { + // xpToNext is very large — no level-up possible + mockUserFindFirst.mockResolvedValue( + makeUser({ + categorySkills: [ + { id: 20, userId: 1, category: "chess", level: 1, totalXp: 0, currentXp: 0, xpToNext: 100_000 }, + ], + }), + ); + await POST(makePostValid({ result: "win", level: 4 })); + expect(mockProcessSkillUnlocks).not.toHaveBeenCalled(); + }); + + it("includes streakFreezesGranted in response", async () => { + mockUserFindFirst.mockResolvedValue( + makeUser({ + categorySkills: [ + { id: 20, userId: 1, category: "chess", level: 1, totalXp: 0, currentXp: 95, xpToNext: 100 }, + ], + }), + ); + mockProcessSkillUnlocks.mockResolvedValue({ unlocked: ["Streak Shield"], streakFreezesGranted: 1 }); + + const res = await POST(makePostValid({ result: "win", level: 8 })); + const body = (await json(res)) as { streakFreezesGranted: number }; + expect(body.streakFreezesGranted).toBe(1); + }); +}); + +// --------------------------------------------------------------------------- +// Title progression +// --------------------------------------------------------------------------- + +describe("POST /api/chess/game-result — title", () => { + it("includes newTitle when user levels up past a title threshold", async () => { + // Level 2 → level 3 crosses the "Slightly Wrinkled" threshold (level 3 in TITLE_THRESHOLDS). + // Give currentXp close to xpToNextLevel so the earned XP triggers a level-up. + mockUserFindFirst.mockResolvedValue( + makeUser({ level: 2, currentXp: 95, xpToNextLevel: 100, title: "Smooth Brain" }), + ); + const res = await POST(makePostValid({ result: "win", level: 8 })); + expect(res.status).toBe(200); + const body = (await json(res)) as { levelUp: boolean; newTitle?: string }; + expect(body.levelUp).toBe(true); + expect(body.newTitle).toBe("Slightly Wrinkled"); + }); + + it("newTitle is undefined when no level-up", async () => { + // xpToNextLevel is very large + mockUserFindFirst.mockResolvedValue( + makeUser({ level: 1, currentXp: 0, xpToNextLevel: 100_000 }), + ); + const res = await POST(makePostValid({ result: "win", level: 4 })); + const body = (await json(res)) as { levelUp: boolean; newTitle?: string }; + expect(body.levelUp).toBe(false); + expect(body.newTitle).toBeUndefined(); + }); +}); + +// --------------------------------------------------------------------------- +// userId default +// --------------------------------------------------------------------------- + +describe("POST /api/chess/game-result — userId", () => { + it("defaults userId to 1 when not supplied", async () => { + await POST(makePostValid()); // no userId in body + expect(mockUserFindFirst).toHaveBeenCalledWith( + expect.objectContaining({ where: { id: 1 } }), + ); + }); + + it("uses provided userId when supplied", async () => { + await POST(makePostValid({ userId: 7 })); + expect(mockUserFindFirst).toHaveBeenCalledWith( + expect.objectContaining({ where: { id: 7 } }), + ); + }); +}); + +// --------------------------------------------------------------------------- +// All three valid result values work +// --------------------------------------------------------------------------- + +describe("POST /api/chess/game-result — result variants", () => { + for (const result of ["win", "draw", "loss"] as const) { + it(`returns 200 for result="${result}"`, async () => { + mockUserFindFirst.mockResolvedValue(makeUser()); + mockDailyLogFindFirst.mockResolvedValue(null); + setupTransaction(); + + const res = await POST(makePostValid({ result })); + expect(res.status).toBe(200); + const body = (await json(res)) as { result: string }; + expect(body.result).toBe(result); + }); + } +}); diff --git a/src/app/api/chess/__tests__/game-result.test.ts b/src/app/api/chess/__tests__/game-result.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..4a37eefd4f2e57cd878a7ea42b2bbf938aa8379f --- /dev/null +++ b/src/app/api/chess/__tests__/game-result.test.ts @@ -0,0 +1,151 @@ +/** + * Tests for chess game-result quality scoring logic. + * + * We test the pure calcGameQualityScore function exported from the route. + * The route itself uses the same DB/XP pipeline as the puzzle submit route, + * which already has comprehensive integration-level tests via the mocked + * Prisma pattern in other test files. + */ + +import { describe, it, expect } from "vitest"; +import { calcGameQualityScore, type GameResult } from "../game-result/route"; + +// ─── Quality score bounds ──────────────────────────────────────────────────── + +describe("calcGameQualityScore — win", () => { + it("returns 0.80 for a win at level 1 (easiest)", () => { + // 0.8 + (1/8)*0.2 = 0.825, but floor is 0.80 at level 0 + expect(calcGameQualityScore("win", 1)).toBeCloseTo(0.825, 3); + }); + + it("returns 1.00 for a win at level 8 (hardest)", () => { + expect(calcGameQualityScore("win", 8)).toBeCloseTo(1.0, 3); + }); + + it("returns 0.90 for a win at level 4 (midpoint)", () => { + // 0.8 + (4/8)*0.2 = 0.9 + expect(calcGameQualityScore("win", 4)).toBeCloseTo(0.9, 3); + }); + + it("always returns > 0.8 for a win at any level", () => { + for (let level = 1; level <= 8; level++) { + expect(calcGameQualityScore("win", level)).toBeGreaterThan(0.8); + } + }); + + it("never exceeds 1.0 for a win", () => { + for (let level = 1; level <= 8; level++) { + expect(calcGameQualityScore("win", level)).toBeLessThanOrEqual(1.0); + } + }); +}); + +describe("calcGameQualityScore — draw", () => { + it("returns 0.50 for a draw at level 0 (boundary)", () => { + // level clamped: (0/8)*0.15 = 0, so 0.5 + expect(calcGameQualityScore("draw", 0)).toBeCloseTo(0.5, 3); + }); + + it("returns ~0.65 for a draw at level 8", () => { + // 0.5 + (8/8)*0.15 = 0.65 + expect(calcGameQualityScore("draw", 8)).toBeCloseTo(0.65, 3); + }); + + it("returns 0.575 for a draw at level 4", () => { + // 0.5 + (4/8)*0.15 = 0.575 + expect(calcGameQualityScore("draw", 4)).toBeCloseTo(0.575, 3); + }); + + it("is always less than a win at the same level", () => { + for (let level = 1; level <= 8; level++) { + expect(calcGameQualityScore("draw", level)).toBeLessThan( + calcGameQualityScore("win", level) + ); + } + }); +}); + +describe("calcGameQualityScore — loss", () => { + it("returns 0.10 for a loss at level 0 (boundary)", () => { + expect(calcGameQualityScore("loss", 0)).toBeCloseTo(0.1, 3); + }); + + it("returns 0.20 for a loss at level 8 (hardest opponent)", () => { + // 0.1 + (8/8)*0.1 = 0.2 + expect(calcGameQualityScore("loss", 8)).toBeCloseTo(0.2, 3); + }); + + it("returns 0.15 for a loss at level 4", () => { + // 0.1 + (4/8)*0.1 = 0.15 + expect(calcGameQualityScore("loss", 4)).toBeCloseTo(0.15, 3); + }); + + it("is always less than a draw at the same level", () => { + for (let level = 1; level <= 8; level++) { + expect(calcGameQualityScore("loss", level)).toBeLessThan( + calcGameQualityScore("draw", level) + ); + } + }); + + it("always returns > 0 (participation credit)", () => { + for (let level = 1; level <= 8; level++) { + expect(calcGameQualityScore("loss", level)).toBeGreaterThan(0); + } + }); +}); + +describe("calcGameQualityScore — level clamping", () => { + it("clamps negative levels to 0", () => { + expect(calcGameQualityScore("win", -5)).toBeCloseTo( + calcGameQualityScore("win", 0), + 5 + ); + }); + + it("clamps levels above 8 to 8", () => { + expect(calcGameQualityScore("win", 99)).toBeCloseTo( + calcGameQualityScore("win", 8), + 5 + ); + }); +}); + +describe("calcGameQualityScore — monotonicity", () => { + const results: GameResult[] = ["win", "draw", "loss"]; + + it("quality is monotonically non-decreasing with level for all result types", () => { + for (const result of results) { + let prev = calcGameQualityScore(result, 0); + for (let level = 1; level <= 8; level++) { + const curr = calcGameQualityScore(result, level); + expect(curr).toBeGreaterThanOrEqual(prev); + prev = curr; + } + } + }); + + it("win > draw > loss at every level", () => { + for (let level = 1; level <= 8; level++) { + const win = calcGameQualityScore("win", level); + const draw = calcGameQualityScore("draw", level); + const loss = calcGameQualityScore("loss", level); + expect(win).toBeGreaterThan(draw); + expect(draw).toBeGreaterThan(loss); + } + }); +}); + +describe("calcGameQualityScore — all values in [0, 1]", () => { + const results: GameResult[] = ["win", "draw", "loss"]; + + it("always returns a value in [0, 1]", () => { + for (const result of results) { + for (let level = 0; level <= 8; level++) { + const score = calcGameQualityScore(result, level); + expect(score).toBeGreaterThanOrEqual(0); + expect(score).toBeLessThanOrEqual(1); + } + } + }); +}); diff --git a/src/app/api/chess/__tests__/puzzle-submit.test.ts b/src/app/api/chess/__tests__/puzzle-submit.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..cccd4d9c3ea7db7c14518587845344163a89b2e6 --- /dev/null +++ b/src/app/api/chess/__tests__/puzzle-submit.test.ts @@ -0,0 +1,894 @@ +/** + * Tests for chess puzzle and submit routes. + * + * Covers: + * GET /api/chess/puzzle + * - random puzzle fetch (default) + * - daily puzzle fetch (?daily=true) + * - 502 when Lichess returns null + * - response shape (id, solution, rating, themes, plays, gameUrl, pgn, fen computed server-side) + * + * POST /api/chess/submit — calcQualityScore (pure) + * - solved = false → 0 + * - perfect efficiency (movesPlayed === solutionLen) → 1.0 + * - extra moves reduce quality + * + * POST /api/chess/submit — handler + * - input validation: missing puzzleId, non-string puzzleId, non-number puzzleRating, non-boolean solved + * - invalid JSON body → 400 + * - user not found → 404 + * - missing chess CategorySkill → 500 + * - success shape: solved, qualityScore, xp breakdown, levelUp, categoryXp, unlocks + * - XP: unsolved puzzle gets quality 0 (base XP only, no quality bonus) + * - XP: critical hit doubles totalXp + * - XP: multiplier bonus reflected in response + * - DailyLog: created when no existing log + * - DailyLog: updated when existing log exists + * - goalMet flag set when XP reaches dailyGoalXp + * - processSkillUnlocks called on category level-up + * - processSkillUnlocks NOT called when no category level-up + */ + +import { describe, it, expect, vi, beforeEach, afterEach } from "vitest"; +import { NextRequest } from "next/server"; + +// --------------------------------------------------------------------------- +// Mock Lichess API (for puzzle route) +// --------------------------------------------------------------------------- + +const mockGetLichessPuzzle = vi.fn(); +const mockGetLichessDailyPuzzle = vi.fn(); + +vi.mock("@/lib/lichess", () => ({ + getLichessPuzzle: (...args: unknown[]) => mockGetLichessPuzzle(...args), + getLichessDailyPuzzle: (...args: unknown[]) => mockGetLichessDailyPuzzle(...args), +})); + +// --------------------------------------------------------------------------- +// Mock Prisma (for submit route) +// --------------------------------------------------------------------------- + +const mockUserFindFirst = vi.fn(); +const mockDailyLogFindFirst = vi.fn(); +const mockTransaction = vi.fn(); +const mockActivityCreate = vi.fn(); +const mockUserUpdate = vi.fn(); +const mockCategorySkillUpdate = vi.fn(); +const mockDailyLogCreate = vi.fn(); +const mockDailyLogUpdate = vi.fn(); + +vi.mock("@/lib/db", () => ({ + prisma: { + user: { + findFirst: (...args: unknown[]) => mockUserFindFirst(...args), + }, + dailyLog: { + findFirst: (...args: unknown[]) => mockDailyLogFindFirst(...args), + }, + $transaction: (...args: unknown[]) => mockTransaction(...args), + }, +})); + +// --------------------------------------------------------------------------- +// Mock rollCriticalHit (deterministic XP) +// --------------------------------------------------------------------------- + +const mockRollCriticalHit = vi.fn(() => false); + +vi.mock("@/lib/xp", async (importOriginal) => { + const actual = await importOriginal(); + return { + ...actual, + rollCriticalHit: () => mockRollCriticalHit(), + }; +}); + +// --------------------------------------------------------------------------- +// Mock getMultiplierPercent +// --------------------------------------------------------------------------- + +const mockGetMultiplierPercent = vi.fn(() => Promise.resolve(0)); + +vi.mock("@/lib/multiplier", () => ({ + getMultiplierPercent: (...args: unknown[]) => (mockGetMultiplierPercent as (...a: unknown[]) => unknown)(...args), +})); + +// --------------------------------------------------------------------------- +// Mock processSkillUnlocks +// --------------------------------------------------------------------------- + +const mockProcessSkillUnlocks = vi.fn((): Promise<{ unlocked: string[]; streakFreezesGranted: number }> => + Promise.resolve({ unlocked: [], streakFreezesGranted: 0 }), +); + +vi.mock("@/lib/skill-unlock", () => ({ + processSkillUnlocks: (...args: unknown[]) => (mockProcessSkillUnlocks as (...a: unknown[]) => unknown)(...args), +})); + +// --------------------------------------------------------------------------- +// Mock processEndOfDay (no-op — streak logic is tested separately) +// --------------------------------------------------------------------------- + +vi.mock("@/lib/streak", () => ({ + processEndOfDay: vi.fn(() => Promise.resolve({ + streak: 1, + freezeUsed: false, + streakBroken: false, + alreadyProcessed: false, + })), +})); + +// --------------------------------------------------------------------------- +// Import routes (after mocks are hoisted) +// --------------------------------------------------------------------------- + +import { GET } from "../puzzle/route"; +import { POST, calcQualityScore } from "../submit/route"; + +// --------------------------------------------------------------------------- +// Helpers +// --------------------------------------------------------------------------- + +const originalEnv = { ...process.env }; + +async function json(res: Response): Promise { + return res.json(); +} + +function makeGet(url: string): NextRequest { + return new NextRequest(url, { method: "GET" }); +} + +function makePost(body?: Record): NextRequest { + return new NextRequest("http://localhost/api/chess/submit", { + method: "POST", + body: body !== undefined ? JSON.stringify(body) : undefined, + headers: { "Content-Type": "application/json" }, + }); +} + +/** A representative raw Lichess puzzle API response */ +function makeLichessPuzzle() { + return { + puzzle: { + id: "pzl123", + solution: ["e2e4", "e7e5", "g1f3"], + rating: 1500, + themes: ["fork", "middlegame"], + plays: 9876, + }, + game: { + id: "game456", + pgn: "1. e4 e5 2. Nf3 Nc6", + }, + }; +} + +/** Stub user with chess CategorySkill */ +function makeUser(overrides: Record = {}) { + return { + id: 1, + name: "Player One", + level: 1, + totalXp: 0, + currentXp: 0, + xpToNextLevel: 100, + title: "Smooth Brain", + dailyGoalXp: 100, + streak: 3, + longestStreak: 10, + streakFreezes: 1, + lichessUsername: null, + chesscomUsername: null, + createdAt: new Date(), + categorySkills: [ + { + id: 10, + userId: 1, + category: "chess", + level: 1, + totalXp: 0, + currentXp: 0, + xpToNext: 100, + }, + ], + ...overrides, + }; +} + +/** Wire up mockTransaction to call the callback with a fake tx client */ +function setupTransaction() { + mockTransaction.mockImplementation( + async (callback: (tx: Record) => Promise) => { + const tx = { + activity: { create: mockActivityCreate }, + user: { update: mockUserUpdate }, + categorySkill: { update: mockCategorySkillUpdate }, + dailyLog: { + create: mockDailyLogCreate, + update: mockDailyLogUpdate, + }, + }; + return callback(tx); + }, + ); +} + +beforeEach(() => { + vi.clearAllMocks(); + process.env = { ...originalEnv }; + + // Default happy-path state + mockUserFindFirst.mockResolvedValue(makeUser()); + mockDailyLogFindFirst.mockResolvedValue(null); + mockRollCriticalHit.mockReturnValue(false); + mockGetMultiplierPercent.mockResolvedValue(0); + mockProcessSkillUnlocks.mockResolvedValue({ unlocked: [], streakFreezesGranted: 0 }); + setupTransaction(); + mockActivityCreate.mockResolvedValue({}); + mockUserUpdate.mockResolvedValue({}); + mockCategorySkillUpdate.mockResolvedValue({}); + mockDailyLogCreate.mockResolvedValue({}); + mockDailyLogUpdate.mockResolvedValue({}); +}); + +afterEach(() => { + process.env = originalEnv; +}); + +// ═══════════════════════════════════════════════════════════════════════════ +// GET /api/chess/puzzle +// ═══════════════════════════════════════════════════════════════════════════ + +describe("GET /api/chess/puzzle — random puzzle (default)", () => { + it("calls getLichessPuzzle (not daily) when no ?daily param", async () => { + mockGetLichessPuzzle.mockResolvedValueOnce(makeLichessPuzzle()); + + await GET(makeGet("http://localhost/api/chess/puzzle")); + + expect(mockGetLichessPuzzle).toHaveBeenCalledTimes(1); + expect(mockGetLichessDailyPuzzle).not.toHaveBeenCalled(); + }); + + it("calls getLichessPuzzle when ?daily=false", async () => { + mockGetLichessPuzzle.mockResolvedValueOnce(makeLichessPuzzle()); + + await GET(makeGet("http://localhost/api/chess/puzzle?daily=false")); + + expect(mockGetLichessPuzzle).toHaveBeenCalledTimes(1); + expect(mockGetLichessDailyPuzzle).not.toHaveBeenCalled(); + }); + + it("returns 200 with correct response shape", async () => { + mockGetLichessPuzzle.mockResolvedValueOnce(makeLichessPuzzle()); + + const res = await GET(makeGet("http://localhost/api/chess/puzzle")); + expect(res.status).toBe(200); + + const body = await json(res) as { + id: string; + fen: string; + solution: string[]; + rating: number; + themes: string[]; + plays: number; + gameUrl: string; + pgn: string; + }; + + expect(body.id).toBe("pzl123"); + expect(body.solution).toEqual(["e2e4", "e7e5", "g1f3"]); + expect(body.rating).toBe(1500); + expect(body.themes).toEqual(["fork", "middlegame"]); + expect(body.plays).toBe(9876); + expect(body.gameUrl).toBe("https://lichess.org/game456"); + expect(body.pgn).toBe("1. e4 e5 2. Nf3 Nc6"); + // fen is now computed server-side from the game PGN + expect(body.fen).toBe("r1bqkbnr/pppp1ppp/2n5/4p3/4P3/5N2/PPPP1PPP/RNBQKB1R w KQkq - 2 3"); + }); + + it("returns 502 when getLichessPuzzle returns null", async () => { + mockGetLichessPuzzle.mockResolvedValueOnce(null); + + const res = await GET(makeGet("http://localhost/api/chess/puzzle")); + expect(res.status).toBe(502); + + const body = await json(res) as { error: string }; + expect(body.error).toBeTruthy(); + }); +}); + +describe("GET /api/chess/puzzle — daily puzzle (?daily=true)", () => { + it("calls getLichessDailyPuzzle when ?daily=true", async () => { + mockGetLichessDailyPuzzle.mockResolvedValueOnce(makeLichessPuzzle()); + + await GET(makeGet("http://localhost/api/chess/puzzle?daily=true")); + + expect(mockGetLichessDailyPuzzle).toHaveBeenCalledTimes(1); + expect(mockGetLichessPuzzle).not.toHaveBeenCalled(); + }); + + it("returns 200 with the same shape as random puzzles", async () => { + mockGetLichessDailyPuzzle.mockResolvedValueOnce(makeLichessPuzzle()); + + const res = await GET(makeGet("http://localhost/api/chess/puzzle?daily=true")); + expect(res.status).toBe(200); + + const body = await json(res) as { id: string; rating: number }; + expect(body.id).toBe("pzl123"); + expect(body.rating).toBe(1500); + }); + + it("returns 502 when getLichessDailyPuzzle returns null", async () => { + mockGetLichessDailyPuzzle.mockResolvedValueOnce(null); + + const res = await GET(makeGet("http://localhost/api/chess/puzzle?daily=true")); + expect(res.status).toBe(502); + }); +}); + +// ═══════════════════════════════════════════════════════════════════════════ +// calcQualityScore — pure function +// ═══════════════════════════════════════════════════════════════════════════ + +describe("calcQualityScore", () => { + it("returns 0 when solved = false regardless of moves", () => { + expect(calcQualityScore(false, 3, 3)).toBe(0); + expect(calcQualityScore(false, 10, 3)).toBe(0); + expect(calcQualityScore(false, 1, 5)).toBe(0); + }); + + it("returns 1.0 for a solved puzzle with perfect efficiency (movesPlayed === solutionLen)", () => { + // efficiency = solutionLen / movesPlayed = 1.0 → 0.5 + 1.0*0.5 = 1.0 + expect(calcQualityScore(true, 3, 3)).toBeCloseTo(1.0, 5); + expect(calcQualityScore(true, 5, 5)).toBeCloseTo(1.0, 5); + }); + + it("returns 0.5 for a solved puzzle with zero efficiency (huge mistake count)", () => { + // efficiency → 0 as movesPlayed → ∞ → 0.5 + 0*0.5 = 0.5 + expect(calcQualityScore(true, 1_000_000, 1)).toBeCloseTo(0.5, 1); + }); + + it("penalises extra moves (more moves = lower quality)", () => { + const perfect = calcQualityScore(true, 3, 3); + const oneExtra = calcQualityScore(true, 4, 3); + const twoExtra = calcQualityScore(true, 5, 3); + + expect(perfect).toBeGreaterThan(oneExtra); + expect(oneExtra).toBeGreaterThan(twoExtra); + }); + + it("quality is always in [0, 1] for any inputs", () => { + const cases = [ + [true, 1, 1], + [true, 5, 3], + [true, 100, 2], + [false, 1, 1], + [false, 0, 0], + ] as Array<[boolean, number, number]>; + + for (const [solved, moves, len] of cases) { + const q = calcQualityScore(solved, moves, len); + expect(q).toBeGreaterThanOrEqual(0); + expect(q).toBeLessThanOrEqual(1); + } + }); + + it("caps efficiency at 1.0 when movesPlayed < solutionLen (shouldn't happen in practice)", () => { + // If somehow movesPlayed < solutionLen, efficiency is capped at 1.0 + expect(calcQualityScore(true, 1, 5)).toBeCloseTo(1.0, 5); + }); +}); + +// ═══════════════════════════════════════════════════════════════════════════ +// POST /api/chess/submit — input validation +// ═══════════════════════════════════════════════════════════════════════════ + +describe("POST /api/chess/submit — input validation", () => { + it("returns 400 for invalid JSON body", async () => { + const req = new NextRequest("http://localhost/api/chess/submit", { + method: "POST", + body: "not-json", + headers: { "Content-Type": "application/json" }, + }); + const res = await POST(req); + expect(res.status).toBe(400); + }); + + it("returns 400 when puzzleId is missing", async () => { + const res = await POST(makePost({ + puzzleRating: 1500, + solved: true, + movesPlayed: 3, + solutionLen: 3, + })); + expect(res.status).toBe(400); + const body = await json(res) as { error: string }; + expect(body.error).toMatch(/puzzleId/i); + }); + + it("returns 400 when puzzleId is not a string", async () => { + const res = await POST(makePost({ + puzzleId: 12345, + puzzleRating: 1500, + solved: true, + movesPlayed: 3, + solutionLen: 3, + })); + expect(res.status).toBe(400); + const body = await json(res) as { error: string }; + expect(body.error).toMatch(/puzzleId/i); + }); + + it("returns 400 when puzzleRating is not a number", async () => { + const res = await POST(makePost({ + puzzleId: "pzl123", + puzzleRating: "hard", + solved: true, + movesPlayed: 3, + solutionLen: 3, + })); + expect(res.status).toBe(400); + const body = await json(res) as { error: string }; + expect(body.error).toMatch(/puzzleRating/i); + }); + + it("returns 400 when solved is not a boolean", async () => { + const res = await POST(makePost({ + puzzleId: "pzl123", + puzzleRating: 1500, + solved: "yes", + movesPlayed: 3, + solutionLen: 3, + })); + expect(res.status).toBe(400); + const body = await json(res) as { error: string }; + expect(body.error).toMatch(/solved/i); + }); +}); + +// ═══════════════════════════════════════════════════════════════════════════ +// POST /api/chess/submit — DB error paths +// ═══════════════════════════════════════════════════════════════════════════ + +describe("POST /api/chess/submit — DB error paths", () => { + it("returns 404 when user is not found", async () => { + mockUserFindFirst.mockResolvedValueOnce(null); + + const res = await POST(makePost({ + puzzleId: "pzl123", + puzzleRating: 1500, + solved: true, + movesPlayed: 3, + solutionLen: 3, + })); + expect(res.status).toBe(404); + const body = await json(res) as { error: string }; + expect(body.error).toMatch(/user/i); + }); + + it("returns 500 when chess CategorySkill is missing", async () => { + mockUserFindFirst.mockResolvedValueOnce(makeUser({ categorySkills: [] })); + + const res = await POST(makePost({ + puzzleId: "pzl123", + puzzleRating: 1500, + solved: true, + movesPlayed: 3, + solutionLen: 3, + })); + expect(res.status).toBe(500); + const body = await json(res) as { error: string }; + expect(body.error).toMatch(/CategorySkill/i); + }); +}); + +// ═══════════════════════════════════════════════════════════════════════════ +// POST /api/chess/submit — success path: response shape +// ═══════════════════════════════════════════════════════════════════════════ + +describe("POST /api/chess/submit — success response shape", () => { + const defaultBody = { + puzzleId: "pzl123", + puzzleRating: 1500, + solved: true, + movesPlayed: 3, + solutionLen: 3, + }; + + it("returns 200 on success", async () => { + const res = await POST(makePost(defaultBody)); + expect(res.status).toBe(200); + }); + + it("response includes solved field matching the input", async () => { + const res = await POST(makePost(defaultBody)); + const body = await json(res) as { solved: boolean }; + expect(body.solved).toBe(true); + }); + + it("response includes qualityScore in [0, 1]", async () => { + const res = await POST(makePost(defaultBody)); + const body = await json(res) as { qualityScore: number }; + expect(body.qualityScore).toBeGreaterThanOrEqual(0); + expect(body.qualityScore).toBeLessThanOrEqual(1); + }); + + it("response includes full xp breakdown", async () => { + const res = await POST(makePost(defaultBody)); + const body = await json(res) as { + xp: { + totalXp: number; + baseXp: number; + qualityBonus: number; + multiplierBonus: number; + multiplierPercent: number; + isCriticalHit: boolean; + }; + }; + + expect(typeof body.xp.totalXp).toBe("number"); + expect(typeof body.xp.baseXp).toBe("number"); + expect(typeof body.xp.qualityBonus).toBe("number"); + expect(typeof body.xp.multiplierBonus).toBe("number"); + expect(typeof body.xp.multiplierPercent).toBe("number"); + expect(typeof body.xp.isCriticalHit).toBe("boolean"); + }); + + it("response includes levelUp flag and newLevel", async () => { + const res = await POST(makePost(defaultBody)); + const body = await json(res) as { levelUp: boolean; newLevel: number }; + expect(typeof body.levelUp).toBe("boolean"); + expect(typeof body.newLevel).toBe("number"); + }); + + it("response includes categoryXp breakdown", async () => { + const res = await POST(makePost(defaultBody)); + const body = await json(res) as { + categoryXp: { + currentXp: number; + xpToNext: number; + level: number; + levelUp: boolean; + }; + }; + expect(typeof body.categoryXp.currentXp).toBe("number"); + expect(typeof body.categoryXp.xpToNext).toBe("number"); + expect(typeof body.categoryXp.level).toBe("number"); + expect(typeof body.categoryXp.levelUp).toBe("boolean"); + }); + + it("response includes unlocks array", async () => { + const res = await POST(makePost(defaultBody)); + const body = await json(res) as { unlocks: string[] }; + expect(Array.isArray(body.unlocks)).toBe(true); + }); +}); + +// ═══════════════════════════════════════════════════════════════════════════ +// POST /api/chess/submit — XP calculations +// ═══════════════════════════════════════════════════════════════════════════ + +describe("POST /api/chess/submit — XP calculations", () => { + it("unsolved puzzle: qualityScore is 0 and qualityBonus is 0", async () => { + const res = await POST(makePost({ + puzzleId: "pzl123", + puzzleRating: 1500, + solved: false, + movesPlayed: 3, + solutionLen: 3, + })); + const body = await json(res) as { qualityScore: number; xp: { qualityBonus: number } }; + expect(body.qualityScore).toBe(0); + expect(body.xp.qualityBonus).toBe(0); + }); + + it("solved puzzle: qualityBonus > 0 for perfect play", async () => { + const res = await POST(makePost({ + puzzleId: "pzl123", + puzzleRating: 1500, + solved: true, + movesPlayed: 3, + solutionLen: 3, + })); + const body = await json(res) as { xp: { qualityBonus: number } }; + expect(body.xp.qualityBonus).toBeGreaterThan(0); + }); + + it("critical hit doubles totalXp", async () => { + mockRollCriticalHit.mockReturnValue(true); + + const resCrit = await POST(makePost({ + puzzleId: "pzl123", + puzzleRating: 1500, + solved: true, + movesPlayed: 3, + solutionLen: 3, + })); + const bodyCrit = await json(resCrit) as { xp: { totalXp: number; isCriticalHit: boolean } }; + + mockRollCriticalHit.mockReturnValue(false); + const resNorm = await POST(makePost({ + puzzleId: "pzl123", + puzzleRating: 1500, + solved: true, + movesPlayed: 3, + solutionLen: 3, + })); + const bodyNorm = await json(resNorm) as { xp: { totalXp: number } }; + + expect(bodyCrit.xp.isCriticalHit).toBe(true); + expect(bodyCrit.xp.totalXp).toBeGreaterThan(bodyNorm.xp.totalXp); + }); + + it("multiplierPercent is reflected in response xp.multiplierPercent", async () => { + mockGetMultiplierPercent.mockResolvedValueOnce(25); + + const res = await POST(makePost({ + puzzleId: "pzl123", + puzzleRating: 1500, + solved: true, + movesPlayed: 3, + solutionLen: 3, + })); + const body = await json(res) as { xp: { multiplierPercent: number; multiplierBonus: number } }; + + expect(body.xp.multiplierPercent).toBe(25); + expect(body.xp.multiplierBonus).toBeGreaterThan(0); + }); + + it("multiplierBonus is 0 when multiplierPercent is 0", async () => { + mockGetMultiplierPercent.mockResolvedValueOnce(0); + + const res = await POST(makePost({ + puzzleId: "pzl123", + puzzleRating: 1500, + solved: true, + movesPlayed: 3, + solutionLen: 3, + })); + const body = await json(res) as { xp: { multiplierBonus: number } }; + expect(body.xp.multiplierBonus).toBe(0); + }); +}); + +// ═══════════════════════════════════════════════════════════════════════════ +// POST /api/chess/submit — DailyLog +// ═══════════════════════════════════════════════════════════════════════════ + +describe("POST /api/chess/submit — DailyLog", () => { + const defaultBody = { + puzzleId: "pzl123", + puzzleRating: 1500, + solved: true, + movesPlayed: 3, + solutionLen: 3, + }; + + it("creates a new DailyLog when none exists for today", async () => { + mockDailyLogFindFirst.mockResolvedValueOnce(null); + + await POST(makePost(defaultBody)); + + expect(mockDailyLogCreate).toHaveBeenCalledTimes(1); + expect(mockDailyLogUpdate).not.toHaveBeenCalled(); + }); + + it("updates the existing DailyLog when one exists for today", async () => { + mockDailyLogFindFirst.mockResolvedValueOnce({ + id: 99, + xpEarned: 50, + activityCount: 2, + goalMet: false, + }); + + await POST(makePost(defaultBody)); + + expect(mockDailyLogUpdate).toHaveBeenCalledTimes(1); + expect(mockDailyLogCreate).not.toHaveBeenCalled(); + }); + + it("sets goalMet=true when accumulated XP reaches dailyGoalXp", async () => { + // User has dailyGoalXp of 100; give them 95 already earned + ≥5 XP from puzzle + mockUserFindFirst.mockResolvedValueOnce(makeUser({ dailyGoalXp: 100 })); + mockDailyLogFindFirst.mockResolvedValueOnce({ + id: 99, + xpEarned: 95, + activityCount: 3, + goalMet: false, + }); + + await POST(makePost(defaultBody)); + + expect(mockDailyLogUpdate).toHaveBeenCalledWith( + expect.objectContaining({ + data: expect.objectContaining({ goalMet: true }), + }), + ); + }); +}); + +// ═══════════════════════════════════════════════════════════════════════════ +// POST /api/chess/submit — skill unlocks +// ═══════════════════════════════════════════════════════════════════════════ + +describe("POST /api/chess/submit — skill unlocks", () => { + it("calls processSkillUnlocks when category levels up", async () => { + // Set chess skill so that adding any XP causes a level-up + const highXpUser = makeUser({ + categorySkills: [ + { + id: 10, + userId: 1, + category: "chess", + level: 1, + totalXp: 90, + currentXp: 90, + xpToNext: 10, // 10 XP needed → puzzle awards ≥10 XP → level-up + }, + ], + }); + mockUserFindFirst.mockResolvedValueOnce(highXpUser); + + await POST(makePost({ + puzzleId: "pzl123", + puzzleRating: 1500, + solved: true, + movesPlayed: 3, + solutionLen: 3, + })); + + expect(mockProcessSkillUnlocks).toHaveBeenCalledTimes(1); + expect(mockProcessSkillUnlocks).toHaveBeenCalledWith( + expect.anything(), + 1, + "chess", + expect.any(Number), + ); + }); + + it("does NOT call processSkillUnlocks when no category level-up occurs", async () => { + // Chess skill needs 10000 XP to level-up → won't level from one puzzle + const user = makeUser({ + categorySkills: [ + { + id: 10, + userId: 1, + category: "chess", + level: 1, + totalXp: 0, + currentXp: 0, + xpToNext: 10_000, + }, + ], + }); + mockUserFindFirst.mockResolvedValueOnce(user); + + await POST(makePost({ + puzzleId: "pzl123", + puzzleRating: 1500, + solved: true, + movesPlayed: 3, + solutionLen: 3, + })); + + expect(mockProcessSkillUnlocks).not.toHaveBeenCalled(); + }); + + it("includes unlocks array in response from processSkillUnlocks", async () => { + const highXpUser = makeUser({ + categorySkills: [ + { + id: 10, + userId: 1, + category: "chess", + level: 1, + totalXp: 90, + currentXp: 90, + xpToNext: 10, + }, + ], + }); + mockUserFindFirst.mockResolvedValueOnce(highXpUser); + mockProcessSkillUnlocks.mockResolvedValueOnce({ + unlocked: ["Tactical Vision", "Endgame Basics"], + streakFreezesGranted: 1, + }); + + const res = await POST(makePost({ + puzzleId: "pzl123", + puzzleRating: 1500, + solved: true, + movesPlayed: 3, + solutionLen: 3, + })); + + const body = await json(res) as { unlocks: string[]; streakFreezesGranted: number }; + expect(body.unlocks).toEqual(["Tactical Vision", "Endgame Basics"]); + expect(body.streakFreezesGranted).toBe(1); + }); +}); + +// ═══════════════════════════════════════════════════════════════════════════ +// POST /api/chess/submit — activity persistence +// ═══════════════════════════════════════════════════════════════════════════ + +describe("POST /api/chess/submit — activity persistence", () => { + it("creates an activity record with chess category and puzzle metadata", async () => { + await POST(makePost({ + puzzleId: "pzl999", + puzzleRating: 1800, + solved: true, + movesPlayed: 4, + solutionLen: 3, + })); + + expect(mockActivityCreate).toHaveBeenCalledTimes(1); + const callArg = mockActivityCreate.mock.calls[0][0] as { + data: { + category: string; + exerciseType: string; + description: string; + score: number; + metadata: string; + }; + }; + + expect(callArg.data.category).toBe("chess"); + expect(callArg.data.exerciseType).toBe("puzzle"); + expect(callArg.data.description).toContain("pzl999"); + expect(callArg.data.description).toContain("1800"); + + const metadata = JSON.parse(callArg.data.metadata) as { + puzzleId: string; + puzzleRating: number; + solved: boolean; + }; + expect(metadata.puzzleId).toBe("pzl999"); + expect(metadata.puzzleRating).toBe(1800); + expect(metadata.solved).toBe(true); + }); +}); + +// ═══════════════════════════════════════════════════════════════════════════ +// POST /api/chess/submit — durationSecs persistence +// ═══════════════════════════════════════════════════════════════════════════ + +describe("POST /api/chess/submit — durationSecs", () => { + const baseBody = { + puzzleId: "pzl123", + puzzleRating: 1500, + solved: true, + movesPlayed: 3, + solutionLen: 3, + }; + + function getActivityData() { + return (mockActivityCreate.mock.calls[0][0] as { data: Record }).data; + } + + it("persists durationSecs when provided", async () => { + await POST(makePost({ ...baseBody, durationSecs: 90 })); + expect(getActivityData().durationSecs).toBe(90); + }); + + it("rounds durationSecs to the nearest integer", async () => { + await POST(makePost({ ...baseBody, durationSecs: 45.7 })); + expect(getActivityData().durationSecs).toBe(46); + }); + + it("stores null when durationSecs is omitted", async () => { + await POST(makePost(baseBody)); + expect(getActivityData().durationSecs).toBeNull(); + }); + + it("stores null when durationSecs is negative", async () => { + await POST(makePost({ ...baseBody, durationSecs: -5 })); + expect(getActivityData().durationSecs).toBeNull(); + }); + + it("persists durationSecs of 0 (instant solve)", async () => { + await POST(makePost({ ...baseBody, durationSecs: 0 })); + expect(getActivityData().durationSecs).toBe(0); + }); +}); diff --git a/src/app/api/chess/challenge/route.ts b/src/app/api/chess/challenge/route.ts new file mode 100644 index 0000000000000000000000000000000000000000..7da91bab60a38d76d0e5885837d60ea9459f0800 --- /dev/null +++ b/src/app/api/chess/challenge/route.ts @@ -0,0 +1,63 @@ +/** + * POST /api/chess/challenge + * + * Creates a Stockfish bot challenge on Lichess and returns the game URL. + * The user plays the game externally on Lichess, then reports the result + * via POST /api/chess/game-result to earn XP. + * + * Body: + * level number — Stockfish level 1 (easiest) → 8 (strongest). Default: 4. + * userId number — defaults to 1 + */ + +import { NextRequest, NextResponse } from "next/server"; +import { challengeStockfish } from "@/lib/lichess"; +import { withApiError, ApiError } from "@/lib/api-error"; + +interface ChallengeBody { + level?: number; + userId?: number; +} + +/** + * Clamps a Stockfish level to the valid range [1, 8], defaulting to 4. + * Exported for unit testing. + */ +export function clampStockfishLevel(level: unknown): number { + return typeof level === "number" + ? Math.max(1, Math.min(8, Math.round(level))) + : 4; +} + +export const POST = withApiError(async (request: NextRequest) => { + let body: ChallengeBody = {}; + try { + body = await request.json(); + } catch { + // body is optional — defaults are fine + } + + const level = clampStockfishLevel(body.level); + + if (!process.env.LICHESS_API_TOKEN) { + throw new ApiError( + 503, + "LICHESS_API_TOKEN is not configured. Set it in .env to enable Stockfish challenges.", + ); + } + + const challenge = await challengeStockfish(level); + + if (!challenge) { + throw new ApiError( + 502, + "Failed to create Stockfish challenge on Lichess. Check your API token and try again.", + ); + } + + return NextResponse.json({ + gameId: challenge.id, + gameUrl: challenge.url, + level, + }); +}); diff --git a/src/app/api/chess/game-result/route.ts b/src/app/api/chess/game-result/route.ts new file mode 100644 index 0000000000000000000000000000000000000000..1848bfb398846927fc838a8fbaacf30f8bbf60d4 --- /dev/null +++ b/src/app/api/chess/game-result/route.ts @@ -0,0 +1,239 @@ +/** + * POST /api/chess/game-result + * + * Records the result of a Stockfish bot game and awards XP. + * The user plays on Lichess and self-reports their result here. + * + * XP scale (design doc: 30–60 based on result + opponent strength): + * - Base XP: 30 (game participation — same as design doc floor) + * - Quality bonus: up to 30 based on result + level + * - Win: 0.8 + (level / 8) * 0.2 → quality 0.8–1.0 + * - Draw: 0.5 + (level / 8) * 0.15 → quality 0.5–0.65 + * - Loss: 0.1 + (level / 8) * 0.1 → quality 0.1–0.2 + * + * Body: + * gameId string — Lichess game ID (from /api/chess/challenge) + * level number — Stockfish level 1–8 + * result string — "win" | "draw" | "loss" + * userId? number — defaults to 1 + */ + +import { NextRequest, NextResponse } from "next/server"; +import { prisma } from "@/lib/db"; +// import { Prisma } from "@prisma/client"; +import { calculateXpGain, rollCriticalHit } from "@/lib/xp"; +import { checkLevelUp } from "@/lib/progression"; +import { processSkillUnlocks } from "@/lib/skill-unlock"; +import { getMultiplierPercent } from "@/lib/multiplier"; +import { getTitleForLevel } from "@/config/titles"; +import { withApiError, ApiError } from "@/lib/api-error"; +import { processEndOfDay } from "@/lib/streak"; + +export type GameResult = "win" | "draw" | "loss"; + +interface GameResultBody { + gameId: string; + level: number; + result: GameResult; + userId?: number; +} + +/** + * Quality score (0–1) based on result and opponent level. + * Harder opponents → higher quality bonus for the same result. + */ +export function calcGameQualityScore(result: GameResult, level: number): number { + const levelFraction = Math.max(0, Math.min(8, level)) / 8; + switch (result) { + case "win": + return 0.8 + levelFraction * 0.2; // 0.80 – 1.00 + case "draw": + return 0.5 + levelFraction * 0.15; // 0.50 – 0.65 + case "loss": + return 0.1 + levelFraction * 0.1; // 0.10 – 0.20 + default: + return 0; + } +} + +const GAME_BASE_XP = 30; +const GAME_MAX_QUALITY_BONUS = 30; + +export const POST = withApiError(async (request: NextRequest) => { + let body: GameResultBody; + try { + body = await request.json(); + } catch { + throw new ApiError(400, "Invalid JSON body"); + } + + const { gameId, level, result } = body; + + if (!gameId || typeof gameId !== "string") { + throw new ApiError(400, "gameId is required"); + } + if (typeof level !== "number" || level < 1 || level > 8) { + throw new ApiError(400, "level must be a number between 1 and 8"); + } + if (!["win", "draw", "loss"].includes(result)) { + throw new ApiError(400, "result must be 'win', 'draw', or 'loss'"); + } + + const userId = body.userId ?? 1; + + // --- Fetch user --- + const user = await prisma.user.findFirst({ + where: { id: userId }, + include: { categorySkills: { where: { category: "chess" } } }, + }); + + if (!user) { + throw new ApiError(404, "No user found"); + } + + const chessSkill = user.categorySkills[0]; + if (!chessSkill) { + throw new ApiError(500, "Chess CategorySkill not found"); + } + + // --- XP calculation --- + const qualityScore = calcGameQualityScore(result, level); + const isCriticalHit = rollCriticalHit(); + const multiplierPercent = await getMultiplierPercent(prisma, userId, "chess"); + + const xpResult = calculateXpGain({ + baseXp: GAME_BASE_XP, + qualityScore, + maxQualityBonus: GAME_MAX_QUALITY_BONUS, + isCriticalHit, + multiplierPercent, + }); + + // --- Level-up checks --- + const userLevelResult = checkLevelUp({ + currentXp: user.currentXp + xpResult.totalXp, + xpToNextLevel: user.xpToNextLevel, + level: user.level, + }); + + const categoryLevelResult = checkLevelUp({ + currentXp: chessSkill.currentXp + xpResult.totalXp, + xpToNextLevel: chessSkill.xpToNext, + level: chessSkill.level, + }); + + // --- Title progression --- + const newTitle = getTitleForLevel(userLevelResult.newLevel); + const titleChanged = newTitle !== user.title; + + // --- Streak processing (idempotent — no-op if already run today) --- + await processEndOfDay(userId); + + // --- Daily log bookkeeping --- + const now = new Date(); + const todayStart = new Date( + Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate()), + ); + const tomorrowStart = new Date(todayStart.getTime() + 86_400_000); + + const existingLog = await prisma.dailyLog.findFirst({ + where: { userId, date: { gte: todayStart, lt: tomorrowStart } }, + }); + + const newXpEarned = (existingLog?.xpEarned ?? 0) + xpResult.totalXp; + const newActivityCount = (existingLog?.activityCount ?? 0) + 1; + const goalMet = newXpEarned >= user.dailyGoalXp; + + // --- Persist --- + let unlockResult = { unlocked: [] as string[], streakFreezesGranted: 0 }; + await prisma.$transaction(async (tx) => { + await tx.activity.create({ + data: { + userId, + category: "chess", + exerciseType: "bot-game", + description: `Stockfish Lv.${level} — ${result}`, + baseXp: xpResult.baseXp, + qualityBonus: xpResult.qualityBonus, + isCriticalHit: xpResult.isCriticalHit, + totalXp: xpResult.totalXp, + score: qualityScore, + metadata: JSON.stringify({ + gameId, + level, + result, + gameUrl: `https://lichess.org/${gameId}`, + }), + }, + }); + + await tx.user.update({ + where: { id: userId }, + data: { + totalXp: user.totalXp + xpResult.totalXp, + currentXp: userLevelResult.remainingXp, + xpToNextLevel: userLevelResult.newXpToNextLevel, + level: userLevelResult.newLevel, + ...(titleChanged && { title: newTitle }), + }, + }); + + await tx.categorySkill.update({ + where: { id: chessSkill.id }, + data: { + totalXp: chessSkill.totalXp + xpResult.totalXp, + currentXp: categoryLevelResult.remainingXp, + xpToNext: categoryLevelResult.newXpToNextLevel, + level: categoryLevelResult.newLevel, + }, + }); + + if (categoryLevelResult.levelsGained > 0) { + unlockResult = await processSkillUnlocks( + tx, userId, "chess", categoryLevelResult.newLevel, + ); + } + + if (existingLog) { + await tx.dailyLog.update({ + where: { id: existingLog.id }, + data: { xpEarned: newXpEarned, activityCount: newActivityCount, goalMet }, + }); + } else { + await tx.dailyLog.create({ + data: { + userId, + date: todayStart, + xpEarned: newXpEarned, + activityCount: newActivityCount, + goalMet, + }, + }); + } + }); + + return NextResponse.json({ + result, + level, + qualityScore: Math.round(qualityScore * 100) / 100, + xp: { + totalXp: xpResult.totalXp, + baseXp: xpResult.baseXp, + qualityBonus: xpResult.qualityBonus, + multiplierBonus: xpResult.multiplierBonus, + multiplierPercent, + isCriticalHit: xpResult.isCriticalHit, + }, + levelUp: userLevelResult.levelsGained > 0, + newLevel: userLevelResult.newLevel, + categoryXp: { + currentXp: categoryLevelResult.remainingXp, + xpToNext: categoryLevelResult.newXpToNextLevel, + level: categoryLevelResult.newLevel, + levelUp: categoryLevelResult.levelsGained > 0, + }, + newTitle: titleChanged ? newTitle : undefined, + unlocks: unlockResult.unlocked, + streakFreezesGranted: unlockResult.streakFreezesGranted, + }); +}); diff --git a/src/app/api/chess/puzzle/route.ts b/src/app/api/chess/puzzle/route.ts new file mode 100644 index 0000000000000000000000000000000000000000..5b61d644ea8c211048acc0ffe94010a2cdd67e53 --- /dev/null +++ b/src/app/api/chess/puzzle/route.ts @@ -0,0 +1,70 @@ +/** + * GET /api/chess/puzzle + * + * Fetches a Lichess puzzle and returns it formatted for react-chessboard. + * Query params: + * ?daily=true — fetch today's daily puzzle instead of a random one + */ + +import { NextRequest, NextResponse } from "next/server"; +import { + getLichessPuzzle, + getLichessDailyPuzzle, + type LichessPuzzleResponse, +} from "@/lib/lichess"; +import { withApiError } from "@/lib/api-error"; +import { fenFromPgn } from "@/lib/chess/pgn"; + +export interface ChessPuzzlePayload { + id: string; + /** Starting FEN for the puzzle position (computed server-side from the game PGN). */ + fen: string; + /** Full game PGN from Lichess (retained for client-side chess.js move validation). */ + pgn: string; + /** UCI solution moves starting from the puzzle position. The first move is the opponent's forcing move. */ + solution: string[]; + rating: number; + themes: string[]; + plays: number; + gameUrl: string; +} + +/** + * Formats a raw Lichess puzzle response into a ChessPuzzlePayload. + * + * The FEN is computed server-side by replaying the full game PGN with chess.js, + * yielding the exact board position where the puzzle begins. + */ +function formatPuzzle(raw: LichessPuzzleResponse): ChessPuzzlePayload { + const pgn = raw.game.pgn; + const fen = fenFromPgn(pgn) ?? ""; + + return { + id: raw.puzzle.id, + fen, + pgn, + solution: raw.puzzle.solution, + rating: raw.puzzle.rating, + themes: raw.puzzle.themes, + plays: raw.puzzle.plays, + gameUrl: `https://lichess.org/${raw.game.id}`, + }; +} + +export const GET = withApiError(async (request: NextRequest) => { + const { searchParams } = new URL(request.url); + const isDaily = searchParams.get("daily") === "true"; + + const raw = isDaily + ? await getLichessDailyPuzzle() + : await getLichessPuzzle(); + + if (!raw) { + return NextResponse.json( + { error: "Failed to fetch puzzle from Lichess. Check LICHESS_API_TOKEN.", status: 502 }, + { status: 502 }, + ); + } + + return NextResponse.json(formatPuzzle(raw)); +}); diff --git a/src/app/api/chess/submit/route.ts b/src/app/api/chess/submit/route.ts new file mode 100644 index 0000000000000000000000000000000000000000..e2b5f52828094530a5ea919f6e4948cefacb808d --- /dev/null +++ b/src/app/api/chess/submit/route.ts @@ -0,0 +1,246 @@ +/** + * POST /api/chess/submit + * + * Records a chess puzzle result and awards XP. + * + * Body: + * puzzleId string — Lichess puzzle ID + * puzzleRating number — puzzle difficulty rating + * solved boolean — did the user complete the puzzle? + * movesPlayed number — total moves the user attempted (incl. mistakes) + * solutionLen number — number of moves in the correct solution + * userId? number — defaults to 1 + */ + +import { NextRequest, NextResponse } from "next/server"; +import { prisma } from "@/lib/db"; +// import { Prisma } from "@prisma/client"; +import { calculateXpGain, rollCriticalHit } from "@/lib/xp"; +import { checkLevelUp } from "@/lib/progression"; +import { EXERCISE_XP } from "@/config/xp"; +import { processSkillUnlocks } from "@/lib/skill-unlock"; +import { getMultiplierPercent } from "@/lib/multiplier"; +import { getTitleForLevel } from "@/config/titles"; +import { withApiError } from "@/lib/api-error"; +import { processEndOfDay } from "@/lib/streak"; + +interface SubmitBody { + puzzleId: string; + puzzleRating: number; + solved: boolean; + movesPlayed: number; + solutionLen: number; + durationSecs?: number; + userId?: number; +} + +/** + * Quality score (0-1) based on: + * - Whether the puzzle was solved (+0.5 if solved) + * - Efficiency: solved without extra moves (+0 to +0.5 based on ratio) + * + * If not solved, quality = 0. + */ +export function calcQualityScore( + solved: boolean, + movesPlayed: number, + solutionLen: number, +): number { + if (!solved) return 0; + // Efficiency: ratio of correct moves to total attempts. Capped at 1. + const efficiency = Math.min(1, solutionLen / Math.max(movesPlayed, solutionLen)); + return 0.5 + efficiency * 0.5; +} + +export const POST = withApiError(async (request: NextRequest) => { + let body: SubmitBody; + try { + body = await request.json(); + } catch { + return NextResponse.json({ error: "Invalid JSON body" }, { status: 400 }); + } + + const { puzzleId, puzzleRating, solved, movesPlayed, solutionLen, durationSecs } = body; + + if (!puzzleId || typeof puzzleId !== "string") { + return NextResponse.json({ error: "puzzleId is required" }, { status: 400 }); + } + if (typeof puzzleRating !== "number") { + return NextResponse.json({ error: "puzzleRating must be a number" }, { status: 400 }); + } + if (typeof solved !== "boolean") { + return NextResponse.json({ error: "solved must be a boolean" }, { status: 400 }); + } + + const userId = body.userId ?? 1; + const safeMovesPlayed = Math.max(1, movesPlayed ?? solutionLen ?? 1); + const safeSolutionLen = Math.max(1, solutionLen ?? 1); + + // --- Fetch user --- + const user = await prisma.user.findFirst({ + where: { id: userId }, + include: { categorySkills: { where: { category: "chess" } } }, + }); + + if (!user) { + return NextResponse.json({ error: "No user found" }, { status: 404 }); + } + + const chessSkill = user.categorySkills[0]; + if (!chessSkill) { + return NextResponse.json( + { error: "Chess CategorySkill not found" }, + { status: 500 }, + ); + } + + // --- XP calculation (with skill tree multiplier) --- + const qualityScore = calcQualityScore(solved, safeMovesPlayed, safeSolutionLen); + const { baseXp, maxQualityBonus } = EXERCISE_XP["chess"]; + const isCriticalHit = rollCriticalHit(); + const multiplierPercent = await getMultiplierPercent(prisma, userId, "chess"); + + const xpResult = calculateXpGain({ + baseXp, + qualityScore, + maxQualityBonus, + isCriticalHit, + multiplierPercent, + }); + + // --- Level-up checks --- + const userLevelResult = checkLevelUp({ + currentXp: user.currentXp + xpResult.totalXp, + xpToNextLevel: user.xpToNextLevel, + level: user.level, + }); + + const categoryLevelResult = checkLevelUp({ + currentXp: chessSkill.currentXp + xpResult.totalXp, + xpToNextLevel: chessSkill.xpToNext, + level: chessSkill.level, + }); + + // --- Title progression --- + const newTitle = getTitleForLevel(userLevelResult.newLevel); + const titleChanged = newTitle !== user.title; + + // --- Streak processing (idempotent — no-op if already run today) --- + await processEndOfDay(userId); + + // --- Daily log bookkeeping --- + const now = new Date(); + const todayStart = new Date( + Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate()), + ); + const tomorrowStart = new Date(todayStart.getTime() + 86_400_000); + + const existingLog = await prisma.dailyLog.findFirst({ + where: { userId, date: { gte: todayStart, lt: tomorrowStart } }, + }); + + const newXpEarned = (existingLog?.xpEarned ?? 0) + xpResult.totalXp; + const newActivityCount = (existingLog?.activityCount ?? 0) + 1; + const goalMet = newXpEarned >= user.dailyGoalXp; + + // --- Persist --- + let unlockResult = { unlocked: [] as string[], streakFreezesGranted: 0 }; + await prisma.$transaction(async (tx) => { + // Sanitise optional duration: must be a positive integer number of seconds + const safeDuration = + typeof durationSecs === "number" && durationSecs >= 0 + ? Math.round(durationSecs) + : null; + + await tx.activity.create({ + data: { + userId, + category: "chess", + exerciseType: "puzzle", + description: `Chess puzzle ${puzzleId} (rating ${puzzleRating})`, + baseXp: xpResult.baseXp, + qualityBonus: xpResult.qualityBonus, + isCriticalHit: xpResult.isCriticalHit, + totalXp: xpResult.totalXp, + score: qualityScore, + durationSecs: safeDuration, + metadata: JSON.stringify({ + puzzleId, + puzzleRating, + solved, + movesPlayed: safeMovesPlayed, + solutionLen: safeSolutionLen, + }), + }, + }); + + await tx.user.update({ + where: { id: userId }, + data: { + totalXp: user.totalXp + xpResult.totalXp, + currentXp: userLevelResult.remainingXp, + xpToNextLevel: userLevelResult.newXpToNextLevel, + level: userLevelResult.newLevel, + ...(titleChanged && { title: newTitle }), + }, + }); + + await tx.categorySkill.update({ + where: { id: chessSkill.id }, + data: { + totalXp: chessSkill.totalXp + xpResult.totalXp, + currentXp: categoryLevelResult.remainingXp, + xpToNext: categoryLevelResult.newXpToNextLevel, + level: categoryLevelResult.newLevel, + }, + }); + + // Auto-unlock skill tree nodes if category leveled up + if (categoryLevelResult.levelsGained > 0) { + unlockResult = await processSkillUnlocks( + tx, userId, "chess", categoryLevelResult.newLevel, + ); + } + + if (existingLog) { + await tx.dailyLog.update({ + where: { id: existingLog.id }, + data: { xpEarned: newXpEarned, activityCount: newActivityCount, goalMet }, + }); + } else { + await tx.dailyLog.create({ + data: { + userId, + date: todayStart, + xpEarned: newXpEarned, + activityCount: newActivityCount, + goalMet, + }, + }); + } + }); + + return NextResponse.json({ + solved, + qualityScore: Math.round(qualityScore * 100) / 100, + xp: { + totalXp: xpResult.totalXp, + baseXp: xpResult.baseXp, + qualityBonus: xpResult.qualityBonus, + multiplierBonus: xpResult.multiplierBonus, + multiplierPercent, + isCriticalHit: xpResult.isCriticalHit, + }, + levelUp: userLevelResult.levelsGained > 0, + newLevel: userLevelResult.newLevel, + categoryXp: { + currentXp: categoryLevelResult.remainingXp, + xpToNext: categoryLevelResult.newXpToNextLevel, + level: categoryLevelResult.newLevel, + levelUp: categoryLevelResult.levelsGained > 0, + }, + newTitle: titleChanged ? newTitle : undefined, + unlocks: unlockResult.unlocked, + streakFreezesGranted: unlockResult.streakFreezesGranted, + }); +}); diff --git a/src/app/api/coach/__tests__/routes.test.ts b/src/app/api/coach/__tests__/routes.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..4cd348cd1d9ac9bb455fb9c3f3fa7bbf61e23b17 --- /dev/null +++ b/src/app/api/coach/__tests__/routes.test.ts @@ -0,0 +1,425 @@ +/** + * Tests for the four Active Coach API route handlers: + * GET /api/coach/performance + * GET /api/coach/difficulty + * POST /api/coach/feedback + * POST /api/coach/weekly-report + * + * Each handler is tested at the HTTP layer (request parsing, status codes, + * response shape, env-guard, error propagation) using mocked library deps + * to keep tests fast and deterministic. + */ + +import { describe, it, expect, vi, beforeEach, afterEach } from "vitest"; +import { NextRequest } from "next/server"; + +// --------------------------------------------------------------------------- +// Shared mock factories +// --------------------------------------------------------------------------- + +const mockGetPerformanceSummary = vi.fn(); +const mockGetRecommendedSettings = vi.fn(); +const mockIsRateLimited = vi.fn(); +const mockRecordRequest = vi.fn(); +const mockGenerateCoachFeedback = vi.fn(); +const mockGenerateWeeklyReport = vi.fn(); + +vi.mock("@/lib/performance", () => ({ + getPerformanceSummary: (...args: unknown[]) => + mockGetPerformanceSummary(...args), +})); + +vi.mock("@/lib/difficulty", () => ({ + getRecommendedSettings: (...args: unknown[]) => + mockGetRecommendedSettings(...args), +})); + +vi.mock("@/lib/coach-feedback", () => ({ + isRateLimited: (...args: unknown[]) => mockIsRateLimited(...args), + recordRequest: (...args: unknown[]) => mockRecordRequest(...args), + generateCoachFeedback: (...args: unknown[]) => + mockGenerateCoachFeedback(...args), +})); + +vi.mock("@/lib/weekly-report", () => ({ + generateWeeklyReport: (...args: unknown[]) => + mockGenerateWeeklyReport(...args), +})); + +// --------------------------------------------------------------------------- +// Import handlers (after vi.mock hoisting) +// --------------------------------------------------------------------------- + +import { GET as getPerformance } from "../performance/route"; +import { GET as getDifficulty } from "../difficulty/route"; +import { POST as postFeedback } from "../feedback/route"; +import { POST as postWeeklyReport } from "../weekly-report/route"; + +// --------------------------------------------------------------------------- +// Helpers +// --------------------------------------------------------------------------- + +const originalEnv = { ...process.env }; + +function makeGet(path: string): NextRequest { + return new NextRequest(`http://localhost${path}`); +} + +function makePost(path: string, body?: Record): NextRequest { + return new NextRequest(`http://localhost${path}`, { + method: "POST", + body: body !== undefined ? JSON.stringify(body) : undefined, + headers: { "Content-Type": "application/json" }, + }); +} + +async function json(res: Response): Promise { + return res.json(); +} + +// --------------------------------------------------------------------------- +// Stub data +// --------------------------------------------------------------------------- + +const PERFORMANCE_STUB = { + categories: [], + overallScore: 72, + streakDays: 5, + longestStreak: 14, + totalExercises: 42, + activeDays: 18, + lastActivityAt: "2026-03-23T20:00:00.000Z", +}; + +const DIFFICULTY_STUB = { + recommendations: { + chess: { difficulty: "medium", nextSkill: null, adjustmentReason: "On track", hasHistory: true }, + }, + updatedAt: "2026-03-23T20:00:00.000Z", +}; + +const FEEDBACK_STUB = { + feedback: "Keep it up!", + recommendedExercise: { category: "chess", difficulty: "medium" }, + encouragement: "You're crushing it.", +}; + +const WEEKLY_REPORT_STUB: { + report: { + report: string; + highlights: string[]; + areasToFocus: string[]; + weekOverWeek: { + currentWeekXp: number; + previousWeekXp: number; + xpChange: number; + xpChangePercent: number; + currentWeekExercises: number; + previousWeekExercises: number; + currentWeekActiveDays: number; + previousWeekActiveDays: number; + }; + generatedAt: string; + }; + cached: boolean; +} = { + report: { + report: "Great week overall.", + highlights: ["Leveled up in Chess"], + areasToFocus: ["Reading"], + weekOverWeek: { + currentWeekXp: 500, + previousWeekXp: 300, + xpChange: 200, + xpChangePercent: 66, + currentWeekExercises: 10, + previousWeekExercises: 6, + currentWeekActiveDays: 5, + previousWeekActiveDays: 3, + }, + generatedAt: "2026-03-23T20:00:00.000Z", + }, + cached: false, +}; + +beforeEach(() => { + vi.clearAllMocks(); + process.env = { ...originalEnv, ANTHROPIC_API_KEY: "test-key" }; + // Safe defaults — individual tests can override + mockGetPerformanceSummary.mockResolvedValue(PERFORMANCE_STUB); + mockGetRecommendedSettings.mockReturnValue(DIFFICULTY_STUB); + mockIsRateLimited.mockReturnValue(false); + mockRecordRequest.mockReturnValue(undefined); + mockGenerateCoachFeedback.mockResolvedValue({ feedback: FEEDBACK_STUB, cached: false }); + mockGenerateWeeklyReport.mockResolvedValue(WEEKLY_REPORT_STUB); +}); + +afterEach(() => { + process.env = originalEnv; +}); + +// =========================================================================== +// GET /api/coach/performance +// =========================================================================== + +describe("GET /api/coach/performance", () => { + it("returns 200 with the performance summary", async () => { + const res = await getPerformance(makeGet("/api/coach/performance")); + expect(res.status).toBe(200); + const body = await json(res); + expect(body).toMatchObject({ + overallScore: 72, + streakDays: 5, + totalExercises: 42, + }); + }); + + it("calls getPerformanceSummary with user id 1", async () => { + await getPerformance(makeGet("/api/coach/performance")); + expect(mockGetPerformanceSummary).toHaveBeenCalledWith(1); + }); + + it("returns the full summary shape (categories + scalar fields)", async () => { + const res = await getPerformance(makeGet("/api/coach/performance")); + const body = (await json(res)) as typeof PERFORMANCE_STUB; + expect(body).toHaveProperty("categories"); + expect(body).toHaveProperty("overallScore"); + expect(body).toHaveProperty("streakDays"); + expect(body).toHaveProperty("longestStreak"); + expect(body).toHaveProperty("totalExercises"); + expect(body).toHaveProperty("activeDays"); + expect(body).toHaveProperty("lastActivityAt"); + }); + + it("propagates errors thrown by getPerformanceSummary (withApiError wraps them)", async () => { + mockGetPerformanceSummary.mockRejectedValue(new Error("DB unavailable")); + const res = await getPerformance(makeGet("/api/coach/performance")); + expect(res.status).toBe(500); + }); +}); + +// =========================================================================== +// GET /api/coach/difficulty +// =========================================================================== + +describe("GET /api/coach/difficulty", () => { + it("returns 200 with difficulty recommendations", async () => { + const res = await getDifficulty(makeGet("/api/coach/difficulty")); + expect(res.status).toBe(200); + const body = await json(res); + expect(body).toMatchObject(DIFFICULTY_STUB); + }); + + it("calls getPerformanceSummary then getRecommendedSettings with its result", async () => { + await getDifficulty(makeGet("/api/coach/difficulty")); + expect(mockGetPerformanceSummary).toHaveBeenCalledWith(1); + expect(mockGetRecommendedSettings).toHaveBeenCalledWith(PERFORMANCE_STUB); + }); + + it("response contains recommendations and updatedAt", async () => { + const res = await getDifficulty(makeGet("/api/coach/difficulty")); + const body = (await json(res)) as typeof DIFFICULTY_STUB; + expect(body).toHaveProperty("recommendations"); + expect(body).toHaveProperty("updatedAt"); + }); + + it("propagates getPerformanceSummary errors", async () => { + mockGetPerformanceSummary.mockRejectedValue(new Error("Timeout")); + const res = await getDifficulty(makeGet("/api/coach/difficulty")); + expect(res.status).toBe(500); + }); +}); + +// =========================================================================== +// POST /api/coach/feedback +// =========================================================================== + +describe("POST /api/coach/feedback", () => { + it("returns 503 when ANTHROPIC_API_KEY is missing", async () => { + delete process.env.ANTHROPIC_API_KEY; + const res = await postFeedback(makePost("/api/coach/feedback")); + expect(res.status).toBe(503); + const body = (await json(res)) as { error: string }; + expect(body.error).toMatch(/ANTHROPIC_API_KEY/i); + }); + + it("returns 200 with feedback on success", async () => { + const res = await postFeedback(makePost("/api/coach/feedback")); + expect(res.status).toBe(200); + const body = (await json(res)) as typeof FEEDBACK_STUB & { cached: boolean }; + expect(body).toHaveProperty("feedback"); + expect(body).toHaveProperty("recommendedExercise"); + expect(body).toHaveProperty("encouragement"); + expect(body).toHaveProperty("cached"); + }); + + it("defaults to userId 1 when no body is provided", async () => { + await postFeedback(makePost("/api/coach/feedback")); + expect(mockGetPerformanceSummary).toHaveBeenCalledWith(1); + expect(mockGenerateCoachFeedback).toHaveBeenCalledWith(1, PERFORMANCE_STUB); + }); + + it("uses provided userId from request body", async () => { + await postFeedback(makePost("/api/coach/feedback", { userId: 42 })); + expect(mockGetPerformanceSummary).toHaveBeenCalledWith(42); + expect(mockGenerateCoachFeedback).toHaveBeenCalledWith(42, PERFORMANCE_STUB); + }); + + it("ignores non-numeric userId and falls back to 1", async () => { + await postFeedback(makePost("/api/coach/feedback", { userId: "nope" })); + expect(mockGetPerformanceSummary).toHaveBeenCalledWith(1); + }); + + it("returns 429 when rate limit is exceeded", async () => { + mockIsRateLimited.mockReturnValue(true); + const res = await postFeedback(makePost("/api/coach/feedback")); + expect(res.status).toBe(429); + }); + + it("calls recordRequest after generating feedback", async () => { + await postFeedback(makePost("/api/coach/feedback")); + expect(mockRecordRequest).toHaveBeenCalledWith(1); + }); + + it("does not call recordRequest when rate limited", async () => { + mockIsRateLimited.mockReturnValue(true); + await postFeedback(makePost("/api/coach/feedback")); + expect(mockRecordRequest).not.toHaveBeenCalled(); + }); + + it("reflects cached: true when feedback is served from cache", async () => { + mockGenerateCoachFeedback.mockResolvedValue({ feedback: FEEDBACK_STUB, cached: true }); + const res = await postFeedback(makePost("/api/coach/feedback")); + const body = (await json(res)) as { cached: boolean }; + expect(body.cached).toBe(true); + }); + + it("reflects cached: false for a fresh generation", async () => { + const res = await postFeedback(makePost("/api/coach/feedback")); + const body = (await json(res)) as { cached: boolean }; + expect(body.cached).toBe(false); + }); + + it("handles malformed JSON body gracefully (falls back to userId 1)", async () => { + const req = new NextRequest("http://localhost/api/coach/feedback", { + method: "POST", + body: "not-json-at-all", + headers: { "Content-Type": "application/json" }, + }); + const res = await postFeedback(req); + expect(res.status).toBe(200); + expect(mockGetPerformanceSummary).toHaveBeenCalledWith(1); + }); + + it("propagates generateCoachFeedback errors via withApiError", async () => { + mockGenerateCoachFeedback.mockRejectedValue(new Error("Claude timeout")); + const res = await postFeedback(makePost("/api/coach/feedback")); + expect(res.status).toBe(500); + }); +}); + +// =========================================================================== +// POST /api/coach/weekly-report +// =========================================================================== + +describe("POST /api/coach/weekly-report", () => { + it("returns 503 when ANTHROPIC_API_KEY is missing", async () => { + delete process.env.ANTHROPIC_API_KEY; + const res = await postWeeklyReport(makePost("/api/coach/weekly-report")); + expect(res.status).toBe(503); + const body = (await json(res)) as { error: string }; + expect(body.error).toMatch(/ANTHROPIC_API_KEY/i); + }); + + it("returns 200 with hasReport:false when user has insufficient activity", async () => { + mockGenerateWeeklyReport.mockResolvedValue({ + hasReport: false, + activeDaysThisWeek: 1, + requiredDays: 3, + }); + const res = await postWeeklyReport(makePost("/api/coach/weekly-report")); + expect(res.status).toBe(200); + const body = (await json(res)) as { hasReport: boolean; message: string }; + expect(body.hasReport).toBe(false); + expect(body.message).toMatch(/3 different days/i); + }); + + it("returns 200 with report data on success", async () => { + const res = await postWeeklyReport(makePost("/api/coach/weekly-report")); + expect(res.status).toBe(200); + const body = (await json(res)) as Record; + expect(body).toHaveProperty("report"); + expect(body).toHaveProperty("highlights"); + expect(body).toHaveProperty("areasToFocus"); + expect(body).toHaveProperty("weekOverWeek"); + expect(body).toHaveProperty("generatedAt"); + expect(body).toHaveProperty("cached"); + }); + + it("defaults to userId 1 when no body is provided", async () => { + await postWeeklyReport(makePost("/api/coach/weekly-report")); + expect(mockGenerateWeeklyReport).toHaveBeenCalledWith(1); + }); + + it("uses provided userId from request body", async () => { + await postWeeklyReport(makePost("/api/coach/weekly-report", { userId: 7 })); + expect(mockGenerateWeeklyReport).toHaveBeenCalledWith(7); + }); + + it("ignores non-numeric userId and falls back to 1", async () => { + await postWeeklyReport(makePost("/api/coach/weekly-report", { userId: "bad" })); + expect(mockGenerateWeeklyReport).toHaveBeenCalledWith(1); + }); + + it("handles malformed JSON body gracefully (falls back to userId 1)", async () => { + const req = new NextRequest("http://localhost/api/coach/weekly-report", { + method: "POST", + body: "{broken", + headers: { "Content-Type": "application/json" }, + }); + const res = await postWeeklyReport(req); + expect(res.status).toBe(200); + expect(mockGenerateWeeklyReport).toHaveBeenCalledWith(1); + }); + + it("reflects cached: true when report comes from cache", async () => { + mockGenerateWeeklyReport.mockResolvedValue({ + ...WEEKLY_REPORT_STUB, + cached: true, + }); + const res = await postWeeklyReport(makePost("/api/coach/weekly-report")); + const body = (await json(res)) as { cached: boolean }; + expect(body.cached).toBe(true); + }); + + it("includes all weekOverWeek fields in the response", async () => { + const res = await postWeeklyReport(makePost("/api/coach/weekly-report")); + const body = (await json(res)) as { + weekOverWeek: Record; + }; + expect(body.weekOverWeek).toHaveProperty("currentWeekXp"); + expect(body.weekOverWeek).toHaveProperty("previousWeekXp"); + expect(body.weekOverWeek).toHaveProperty("xpChange"); + expect(body.weekOverWeek).toHaveProperty("xpChangePercent"); + expect(body.weekOverWeek).toHaveProperty("currentWeekExercises"); + expect(body.weekOverWeek).toHaveProperty("previousWeekExercises"); + expect(body.weekOverWeek).toHaveProperty("currentWeekActiveDays"); + expect(body.weekOverWeek).toHaveProperty("previousWeekActiveDays"); + }); + + it("highlights and areasToFocus are arrays", async () => { + const res = await postWeeklyReport(makePost("/api/coach/weekly-report")); + const body = (await json(res)) as { + highlights: unknown; + areasToFocus: unknown; + }; + expect(Array.isArray(body.highlights)).toBe(true); + expect(Array.isArray(body.areasToFocus)).toBe(true); + }); + + it("propagates generateWeeklyReport errors via withApiError", async () => { + mockGenerateWeeklyReport.mockRejectedValue(new Error("DB failure")); + const res = await postWeeklyReport(makePost("/api/coach/weekly-report")); + expect(res.status).toBe(500); + }); +}); diff --git a/src/app/api/coach/difficulty/route.ts b/src/app/api/coach/difficulty/route.ts new file mode 100644 index 0000000000000000000000000000000000000000..c2970e613e7cc57e3330d10fd6516e4638a9deef --- /dev/null +++ b/src/app/api/coach/difficulty/route.ts @@ -0,0 +1,26 @@ +import { NextResponse } from "next/server"; +import { withApiError } from "@/lib/api-error"; +import { getPerformanceSummary } from "@/lib/performance"; +import { getRecommendedSettings } from "@/lib/difficulty"; + +/** + * GET /api/coach/difficulty + * + * Returns per-category difficulty recommendations based on the current + * performance summary for user 1. + * + * Response shape: + * { + * recommendations: { + * [category]: { difficulty, nextSkill, adjustmentReason, hasHistory } + * }, + * updatedAt: string + * } + * + * Part 2 of the Active Coach roadmap (Issue #6). + */ +export const GET = withApiError(async () => { + const summary = await getPerformanceSummary(1); + const result = getRecommendedSettings(summary); + return NextResponse.json(result); +}); diff --git a/src/app/api/coach/feedback/route.ts b/src/app/api/coach/feedback/route.ts new file mode 100644 index 0000000000000000000000000000000000000000..26777a7ef8cfe3b4c58031bea9edabcf6af4568b --- /dev/null +++ b/src/app/api/coach/feedback/route.ts @@ -0,0 +1,72 @@ +import { NextResponse } from "next/server"; +import { withApiError } from "@/lib/api-error"; +import { ApiError } from "@/lib/api-error"; +import { getPerformanceSummary } from "@/lib/performance"; +import { + generateCoachFeedback, + isRateLimited, + recordRequest, +} from "@/lib/coach-feedback"; + +/** + * POST /api/coach/feedback + * + * Returns Claude-generated personalized coaching feedback based on the + * user's performance data and difficulty recommendations. + * + * Request body (optional): + * { "userId": number } — defaults to 1 + * + * Response shape: + * { + * feedback: string, + * recommendedExercise: { category: string, difficulty: string }, + * encouragement: string, + * cached: boolean + * } + * + * Features: + * - 3-hour response cache (keyed on user ID + rounded performance metrics) + * - Rate limit: max 10 requests per user per hour + * + * Part 3 of the Active Coach roadmap (Issue #7). + */ +export const POST = withApiError(async (request) => { + if (!process.env.ANTHROPIC_API_KEY) { + return NextResponse.json( + { error: "ANTHROPIC_API_KEY is not configured" }, + { status: 503 }, + ); + } + + // Parse optional body + let userId = 1; + try { + const body = await request.json(); + if (body.userId && typeof body.userId === "number") { + userId = body.userId; + } + } catch { + // Empty body is fine — default to user 1 + } + + // Rate limit check + if (isRateLimited(userId)) { + throw new ApiError(429, "Rate limit exceeded — max 10 requests per hour"); + } + + // Get performance summary + const summary = await getPerformanceSummary(userId); + + // Generate feedback (may return cached response) + const { feedback, cached } = await generateCoachFeedback(userId, summary); + + // Record the request for rate limiting (only count non-cached responses, + // but count all for simplicity — cached responses are fast anyway) + recordRequest(userId); + + return NextResponse.json({ + ...feedback, + cached, + }); +}); diff --git a/src/app/api/coach/performance/route.ts b/src/app/api/coach/performance/route.ts new file mode 100644 index 0000000000000000000000000000000000000000..b65e0424a9bcf8c971e32bfb81fbc656621a1431 --- /dev/null +++ b/src/app/api/coach/performance/route.ts @@ -0,0 +1,17 @@ +import { NextResponse } from "next/server"; +import { withApiError } from "@/lib/api-error"; +import { getPerformanceSummary } from "@/lib/performance"; + +/** + * GET /api/coach/performance + * + * Returns a performance summary for the Active Coach feature: + * - Per-category: success rate, attempt count, avg score, trend + * - Overall score, streak data, activity count, active days + * + * Part 1 of the Active Coach roadmap (Issue #5). + */ +export const GET = withApiError(async () => { + const summary = await getPerformanceSummary(1); + return NextResponse.json(summary); +}); diff --git a/src/app/api/coach/weekly-report/route.ts b/src/app/api/coach/weekly-report/route.ts new file mode 100644 index 0000000000000000000000000000000000000000..02932883e4998289e8af5b25ea66a5d3540eeb72 --- /dev/null +++ b/src/app/api/coach/weekly-report/route.ts @@ -0,0 +1,68 @@ +import { NextResponse } from "next/server"; +import { withApiError } from "@/lib/api-error"; +import { generateWeeklyReport, type WeeklyReportGate } from "@/lib/weekly-report"; + +/** + * POST /api/coach/weekly-report + * + * Generates a weekly brain health report using Claude Haiku. + * + * Request body (optional): + * { "userId": number } — defaults to 1 + * + * Response shape: + * { + * report: string, + * highlights: string[], + * areasToFocus: string[], + * weekOverWeek: { currentWeekXp, previousWeekXp, xpChange, xpChangePercent, + * currentWeekExercises, previousWeekExercises, + * currentWeekActiveDays, previousWeekActiveDays }, + * generatedAt: string, + * cached: boolean + * } + * + * Returns 200 with { hasReport: false, message } if user has fewer than 3 active days this week. + * + * Features: + * - 24-hour response cache (keyed on user ID + week boundary) + * - Minimum 3 active days required to generate + * + * Part 5 of the Active Coach roadmap (Issue #9). + */ +export const POST = withApiError(async (request) => { + if (!process.env.ANTHROPIC_API_KEY) { + return NextResponse.json( + { error: "ANTHROPIC_API_KEY is not configured" }, + { status: 503 }, + ); + } + + // Parse optional body + let userId = 1; + try { + const body = await request.json(); + if (body.userId && typeof body.userId === "number") { + userId = body.userId; + } + } catch { + // Empty body is fine — default to user 1 + } + + const result = await generateWeeklyReport(userId); + + if ("hasReport" in result) { + const gate = result as WeeklyReportGate; + return NextResponse.json({ + hasReport: false, + activeDaysThisWeek: gate.activeDaysThisWeek, + requiredDays: gate.requiredDays, + message: `Not enough activity this week. Complete exercises on at least ${gate.requiredDays} different days to unlock your weekly report. You've been active on ${gate.activeDaysThisWeek} day${gate.activeDaysThisWeek === 1 ? "" : "s"} so far.`, + }); + } + + return NextResponse.json({ + ...result.report, + cached: result.cached, + }); +}); diff --git a/src/app/api/coding/__tests__/routes.integration.test.ts b/src/app/api/coding/__tests__/routes.integration.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..dc4e0a144509b02663eea51abb9f2e0118e91acb --- /dev/null +++ b/src/app/api/coding/__tests__/routes.integration.test.ts @@ -0,0 +1,189 @@ +import { NextRequest } from "next/server"; +import { POST as generate } from "../generate/route"; +import { POST as runCode } from "../run/route"; +import { POST as submitCode } from "../submit-code/route"; +import { POST as submitWritten } from "../submit-written/route"; +import { PROBLEM_BANK } from "@/lib/coding/bank"; + +// Integration tests exercise the real route handlers against the seeded +// dev.db. They assert on the public JSON interface only. No ANTHROPIC_API_KEY +// is set in CI, so written grading exercises the offline heuristic path. + +function post(url: string, body: unknown): NextRequest { + return new NextRequest(`http://localhost${url}`, { + method: "POST", + body: JSON.stringify(body), + headers: { "Content-Type": "application/json" }, + }); +} + +async function gen(type: string, difficulty: string, language: string) { + const res = await generate(post("/api/coding/generate", { type, difficulty, language })); + return res.json(); +} + +/** The bank id embedded in an instanceId (before the "::uuid"). */ +function bankIdOf(instanceId: string): string { + return instanceId.split("::")[0]; +} + +function referenceFor(instanceId: string): string { + const bank = PROBLEM_BANK.find((p) => p.id === bankIdOf(instanceId)); + if (!bank || (bank.type !== "code-creation" && bank.type !== "debugging")) { + throw new Error("not an executable bank problem"); + } + return bank.referenceSolution; +} + +describe("POST /api/coding/generate", () => { + it("returns a public problem with the answer key stripped", async () => { + const body = await gen("code-creation", "easy", "javascript"); + expect(body.instanceId).toBeTruthy(); + expect(body.problem.type).toBe("code-creation"); + expect(body.problem).not.toHaveProperty("referenceSolution"); + // only non-hidden example tests are exposed + for (const t of body.problem.tests ?? []) expect(t.hidden).toBeFalsy(); + expect(body.meta.executable).toBe(true); + }); + + it("strips issues from code-review problems", async () => { + const body = await gen("code-review", "medium", "javascript"); + expect(body.problem).not.toHaveProperty("issues"); + expect(body.problem.code).toBeTruthy(); + expect(body.meta.gradedBy).toBe("llm-judge"); + }); + + it("rejects an invalid type with 400", async () => { + const res = await generate(post("/api/coding/generate", { type: "nope", difficulty: "easy", language: "javascript" })); + expect(res.status).toBe(400); + }); +}); + +describe("POST /api/coding/run", () => { + it("runs the reference solution against the public tests and passes", async () => { + const g = await gen("code-creation", "easy", "javascript"); + const res = await runCode(post("/api/coding/run", { instanceId: g.instanceId, code: referenceFor(g.instanceId) })); + const body = await res.json(); + expect(body.ran).toBe(true); + expect(body.allPassed).toBe(true); + expect(body.compileError).toBeNull(); + }); + + it("404s for an unknown instance", async () => { + const res = await runCode(post("/api/coding/run", { instanceId: "does-not-exist", code: "function x(){}" })); + expect(res.status).toBe(404); + }); +}); + +describe("POST /api/coding/submit-code", () => { + it("accepts the reference solution, marks it correct, and awards XP", async () => { + const g = await gen("code-creation", "medium", "javascript"); + const res = await submitCode(post("/api/coding/submit-code", { + instanceId: g.instanceId, + code: referenceFor(g.instanceId), + })); + const body = await res.json(); + expect(body.correct).toBe(true); + expect(body.awarded).toBe(true); + expect(body.passed).toBe(body.total); + expect(body.xp.totalXp).toBeGreaterThan(0); + expect(body.categoryXp.level).toBeGreaterThanOrEqual(1); + }); + + it("fixes a debugging problem with the reference fix", async () => { + const g = await gen("debugging", "easy", "javascript"); + const res = await submitCode(post("/api/coding/submit-code", { + instanceId: g.instanceId, + code: referenceFor(g.instanceId), + })); + const body = await res.json(); + expect(body.correct).toBe(true); + expect(body.awarded).toBe(true); + }); + + it("rejects wrong code without awarding XP", async () => { + const g = await gen("code-creation", "easy", "javascript"); + const res = await submitCode(post("/api/coding/submit-code", { + instanceId: g.instanceId, + code: "function wrongName() { return -999; }", + })); + const body = await res.json(); + expect(body.correct).toBe(false); + expect(body.awarded).toBe(false); + expect(body.xp).toBeUndefined(); + }); + + it("rejects submitting code to a written problem with 400", async () => { + const g = await gen("architecture", "medium", "javascript"); + const res = await submitCode(post("/api/coding/submit-code", { + instanceId: g.instanceId, + code: "function x(){}", + })); + expect(res.status).toBe(400); + }); +}); + +describe("POST /api/coding/submit-written", () => { + it("grades a strong code-review answer as correct and awards XP (heuristic)", async () => { + // Use the known 'average' review problem for a deterministic strong answer. + const target = PROBLEM_BANK.find((p) => p.id === "cr-js-medium-average")!; + const g = await generate(post("/api/coding/generate", { + type: "code-review", + difficulty: target.difficulty, + language: "javascript", + })); + const gb = await g.json(); + // Keep regenerating deterministically isn't possible; instead submit an + // answer that covers both known issues by their distinctive wording. + const answer = + "The loop overruns the array by reading one past the end, and there is a division by zero on empty input."; + const res = await submitWritten(post("/api/coding/submit-written", { + instanceId: gb.instanceId, + answer, + })); + const body = await res.json(); + expect(body.gradedBy).toBe("heuristic"); + expect(typeof body.qualityScore).toBe("number"); + // Whatever medium review problem was served, a thorough answer should at + // least be graded; correctness depends on the specific problem. + expect(body).toHaveProperty("correct"); + expect(body).toHaveProperty("expectations"); + }); + + it("awards XP when correctly stating clean code has no issues", async () => { + // The only easy code-review problem in the bank is the clean clamp(). + const g = await gen("code-review", "easy", "javascript"); + const res = await submitWritten(post("/api/coding/submit-written", { + instanceId: g.instanceId, + answer: "This function looks correct. There are no issues — it clamps properly.", + })); + const body = await res.json(); + expect(body.correct).toBe(true); + expect(body.awarded).toBe(true); + expect(body.xp.totalXp).toBeGreaterThan(0); + }); + + it("accepts a thorough architecture answer covering the rubric", async () => { + const g = await gen("architecture", "medium", "javascript"); + const answer = + "I would use a token bucket algorithm. The limit key is per API key granularity. " + + "Counters live in a shared Redis store so it works across instances. Bursts are " + + "smoothed by the bucket capacity. If Redis is down we fail open to stay available."; + const res = await submitWritten(post("/api/coding/submit-written", { + instanceId: g.instanceId, + answer, + })); + const body = await res.json(); + expect(body.correct).toBe(true); + expect(body.awarded).toBe(true); + }); + + it("rejects a written answer to an executable problem with 400", async () => { + const g = await gen("code-creation", "easy", "javascript"); + const res = await submitWritten(post("/api/coding/submit-written", { + instanceId: g.instanceId, + answer: "some prose", + })); + expect(res.status).toBe(400); + }); +}); diff --git a/src/app/api/coding/generate/route.ts b/src/app/api/coding/generate/route.ts new file mode 100644 index 0000000000000000000000000000000000000000..a8694ddaa4dffc853361989955943dd4eccd4371 --- /dev/null +++ b/src/app/api/coding/generate/route.ts @@ -0,0 +1,106 @@ +import { NextRequest, NextResponse } from "next/server"; +import { withApiError, ApiError } from "@/lib/api-error"; +import { pickProblem } from "@/lib/coding/bank"; +import { registerProblem } from "@/lib/coding/store"; +import { toPublicProblem } from "@/lib/coding/serialize"; +import { + CODING_PROBLEM_TYPES, + CODING_DIFFICULTIES, + CODING_LANGUAGES, + isExecutableType, + isExecutableLanguage, + type CodingProblemType, + type CodingDifficulty, + type CodingLanguage, + type CodingProblem, +} from "@/lib/coding/types"; + +interface GenerateBody { + type?: string; + difficulty?: string; + language?: string; +} + +function parseParams(source: { + type?: string | null; + difficulty?: string | null; + language?: string | null; +}): { type: CodingProblemType; difficulty: CodingDifficulty; language: CodingLanguage } { + const type = (source.type ?? "code-creation") as CodingProblemType; + const difficulty = (source.difficulty ?? "easy") as CodingDifficulty; + const language = (source.language ?? "javascript") as CodingLanguage; + + if (!CODING_PROBLEM_TYPES.includes(type)) { + throw new ApiError(400, `Invalid type. Must be one of: ${CODING_PROBLEM_TYPES.join(", ")}`); + } + if (!CODING_DIFFICULTIES.includes(difficulty)) { + throw new ApiError(400, `Invalid difficulty. Must be one of: ${CODING_DIFFICULTIES.join(", ")}`); + } + if (!CODING_LANGUAGES.includes(language)) { + throw new ApiError(400, `Invalid language. Must be one of: ${CODING_LANGUAGES.join(", ")}`); + } + return { type, difficulty, language }; +} + +function buildResponse(problem: CodingProblem, instanceId: string) { + const instance: CodingProblem = { ...problem, id: instanceId }; + registerProblem(instance); + return { + instanceId, + problem: toPublicProblem(instance), + meta: { + gradedBy: isExecutableType(instance.type) ? "tests" : "llm-judge", + executable: + isExecutableType(instance.type) && isExecutableLanguage(instance.language), + source: "bank", + }, + }; +} + +/** + * POST /api/coding/generate + * Body: { type, difficulty, language } + * + * Returns a fresh problem-set instance (answer key stripped). The full + * definition is registered server-side under `instanceId` for grading. + */ +export const POST = withApiError(async (request: NextRequest) => { + let body: GenerateBody = {}; + try { + body = await request.json(); + } catch { + // allow empty body → defaults + } + const { type, difficulty, language } = parseParams(body); + + const problem = pickProblem({ type, difficulty, language }); + if (!problem) { + throw new ApiError( + 422, + `No ${difficulty} ${type} problem is available for ${language} yet.`, + ); + } + + const instanceId = `${problem.id}::${crypto.randomUUID()}`; + return NextResponse.json(buildResponse(problem, instanceId)); +}); + +/** GET variant for convenience (?type=&difficulty=&language=). */ +export const GET = withApiError(async (request: NextRequest) => { + const { searchParams } = new URL(request.url); + const { type, difficulty, language } = parseParams({ + type: searchParams.get("type"), + difficulty: searchParams.get("difficulty"), + language: searchParams.get("language"), + }); + + const problem = pickProblem({ type, difficulty, language }); + if (!problem) { + throw new ApiError( + 422, + `No ${difficulty} ${type} problem is available for ${language} yet.`, + ); + } + const instanceId = `${problem.id}::${crypto.randomUUID()}`; + return NextResponse.json(buildResponse(problem, instanceId)); +}); diff --git a/src/app/api/coding/run/route.ts b/src/app/api/coding/run/route.ts new file mode 100644 index 0000000000000000000000000000000000000000..889c37b1d858729d193297188c80af1ae4318ed1 --- /dev/null +++ b/src/app/api/coding/run/route.ts @@ -0,0 +1,64 @@ +import { NextRequest, NextResponse } from "next/server"; +import { withApiError, ApiError } from "@/lib/api-error"; +import { resolveProblem } from "@/lib/coding/store"; +import { runJavaScriptTests } from "@/lib/coding/harness"; +import { isExecutableProblem, isExecutableLanguage } from "@/lib/coding/types"; + +interface RunBody { + instanceId?: string; + code?: string; +} + +/** + * POST /api/coding/run + * Body: { instanceId, code } + * + * Executes the user's code against the *public* example tests in the sandbox + * and returns the results + captured stdout. No XP — this is the "Run" button + * that lets a user iterate before submitting. Hidden tests are not run here. + */ +export const POST = withApiError(async (request: NextRequest) => { + let body: RunBody; + try { + body = await request.json(); + } catch { + throw new ApiError(400, "Invalid JSON body"); + } + + const { instanceId, code } = body; + if (!instanceId || typeof code !== "string") { + throw new ApiError(400, "instanceId and code are required"); + } + + const problem = resolveProblem(instanceId); + if (!problem) { + throw new ApiError(404, "Problem not found (it may have expired — regenerate it)."); + } + if (!isExecutableProblem(problem)) { + throw new ApiError(400, "This problem type is not executable. Submit a written answer instead."); + } + if (!isExecutableLanguage(problem.language)) { + throw new ApiError( + 400, + `Live execution supports JavaScript/TypeScript. ${problem.language} answers are graded on submit.`, + ); + } + + const publicTests = problem.tests.filter((t) => !t.hidden); + const run = runJavaScriptTests(code, problem.entryFunction, publicTests); + + return NextResponse.json({ + ran: true, + entryFunction: problem.entryFunction, + passed: run.passed, + total: run.total, + allPassed: run.allPassed, + results: run.results, + stdout: run.stdout, + compileError: run.compileError ?? null, + note: + publicTests.length === 0 + ? "No example tests are shown for this problem — submit to run the full suite." + : undefined, + }); +}); diff --git a/src/app/api/coding/submit-code/route.ts b/src/app/api/coding/submit-code/route.ts new file mode 100644 index 0000000000000000000000000000000000000000..4dee34bc49c44cd44bffb3e1bc2d6c1555a05128 --- /dev/null +++ b/src/app/api/coding/submit-code/route.ts @@ -0,0 +1,108 @@ +import { NextRequest, NextResponse } from "next/server"; +import { withApiError, ApiError } from "@/lib/api-error"; +import { resolveProblem } from "@/lib/coding/store"; +import { runJavaScriptTests } from "@/lib/coding/harness"; +import { gradeCodeRun } from "@/lib/coding/grade"; +import { awardCodingXp } from "@/lib/coding/award"; +import { + isExecutableProblem, + isExecutableLanguage, + type CodingDifficulty, +} from "@/lib/coding/types"; + +interface SubmitCodeBody { + instanceId?: string; + code?: string; + durationSecs?: number; + userId?: number; +} + +/** + * POST /api/coding/submit-code + * Body: { instanceId, code, durationSecs? } + * + * Runs the user's code against the FULL (incl. hidden) test suite in the + * sandbox. When every test passes, awards "code" XP for the coding category. + * This is the test-driven correctness check. + */ +export const POST = withApiError(async (request: NextRequest) => { + let body: SubmitCodeBody; + try { + body = await request.json(); + } catch { + throw new ApiError(400, "Invalid JSON body"); + } + + const { instanceId, code, durationSecs } = body; + const userId = body.userId ?? 1; + + if (!instanceId || typeof code !== "string" || code.trim().length === 0) { + throw new ApiError(400, "instanceId and non-empty code are required"); + } + + const problem = resolveProblem(instanceId); + if (!problem) { + throw new ApiError(404, "Problem not found (it may have expired — regenerate it)."); + } + if (!isExecutableProblem(problem)) { + throw new ApiError(400, "This problem type is graded by written answer, not code."); + } + if (!isExecutableLanguage(problem.language)) { + throw new ApiError( + 400, + `Auto-grading by execution supports JavaScript/TypeScript only.`, + ); + } + + const run = runJavaScriptTests(code, problem.entryFunction, problem.tests); + const grade = gradeCodeRun(run); + + // Hide nothing post-submission — full TDD feedback helps the user learn. + const baseResponse = { + correct: grade.isCorrect, + passed: run.passed, + total: run.total, + results: run.results, + stdout: run.stdout, + compileError: run.compileError ?? null, + qualityScore: grade.qualityScore, + }; + + if (!grade.isCorrect) { + return NextResponse.json({ + ...baseResponse, + awarded: false, + message: + run.compileError != null + ? "Your code did not compile." + : `${run.passed}/${run.total} tests passed. Keep going!`, + }); + } + + const award = await awardCodingXp({ + userId, + exerciseType: "code", + description: `Solved ${problem.difficulty} ${problem.type} "${problem.title}" (code)`, + qualityScore: grade.qualityScore, + difficulty: problem.difficulty as CodingDifficulty, + durationSecs, + metadata: { + problemId: problem.id, + problemType: problem.type, + language: problem.language, + difficulty: problem.difficulty, + passed: run.passed, + total: run.total, + kind: "code", + }, + }); + + return NextResponse.json({ + ...baseResponse, + awarded: true, + ...award, + message: award.isCriticalHit + ? "Critical Hit! All tests pass!" + : "All tests pass — solved!", + }); +}); diff --git a/src/app/api/coding/submit-written/route.ts b/src/app/api/coding/submit-written/route.ts new file mode 100644 index 0000000000000000000000000000000000000000..24253580be66d86bbcc52fe44c134e791fd4a306 --- /dev/null +++ b/src/app/api/coding/submit-written/route.ts @@ -0,0 +1,118 @@ +import { NextRequest, NextResponse } from "next/server"; +import { withApiError, ApiError } from "@/lib/api-error"; +import { resolveProblem } from "@/lib/coding/store"; +import { gradeCodeReview, gradeArchitecture } from "@/lib/coding/grade"; +import { judgeWritten } from "@/lib/coding/judge"; +import { awardCodingXp } from "@/lib/coding/award"; +import { isWrittenProblem, type CodingDifficulty } from "@/lib/coding/types"; +import { isLlmAvailable } from "@/lib/claude"; +import type { CodeReviewVerdict, ArchitectureVerdict } from "@/lib/coding/grade"; + +interface SubmitWrittenBody { + instanceId?: string; + answer?: string; + durationSecs?: number; + userId?: number; +} + +/** + * POST /api/coding/submit-written + * Body: { instanceId, answer, durationSecs? } + * + * Grades a written answer (code-review or architecture) with the LLM-as-judge + * (or the offline heuristic when no API key is configured). Awards "written" + * XP — separate from code XP — when the answer is judged correct. + */ +export const POST = withApiError(async (request: NextRequest) => { + let body: SubmitWrittenBody; + try { + body = await request.json(); + } catch { + throw new ApiError(400, "Invalid JSON body"); + } + + const { instanceId, answer, durationSecs } = body; + const userId = body.userId ?? 1; + + if (!instanceId || typeof answer !== "string" || answer.trim().length === 0) { + throw new ApiError(400, "instanceId and a non-empty answer are required"); + } + + const problem = resolveProblem(instanceId); + if (!problem) { + throw new ApiError(404, "Problem not found (it may have expired — regenerate it)."); + } + if (!isWrittenProblem(problem)) { + throw new ApiError(400, "This problem type is graded by running code, not a written answer."); + } + + // AI judge when any LLM is reachable for this request (the visitor's HF + // token, an env HF token, or an Anthropic key); else the offline heuristic. + const useAI = isLlmAvailable(); + const judgement = await judgeWritten(problem, answer, { useAI }); + + const grade = + problem.type === "code-review" + ? gradeCodeReview( + problem.issues.length, + judgement.verdict as CodeReviewVerdict, + ) + : gradeArchitecture( + problem.rubric, + judgement.verdict as ArchitectureVerdict, + ); + + // Build hints about what a strong answer should have covered (post-submit). + const expectations = + problem.type === "code-review" + ? problem.issues.map((i) => ({ id: i.id, title: i.title, severity: i.severity })) + : problem.rubric.map((p) => ({ id: p.id, point: p.point })); + + const verdictDetail = + problem.type === "code-review" + ? { identified: (judgement.verdict as CodeReviewVerdict).identifiedIssueIds } + : { covered: (judgement.verdict as ArchitectureVerdict).coveredPointIds }; + + const baseResponse = { + correct: grade.isCorrect, + qualityScore: grade.qualityScore, + gradedBy: judgement.usedAI ? "llm-judge" : "heuristic", + feedback: judgement.feedback, + expectations, + verdict: verdictDetail, + }; + + if (!grade.isCorrect) { + return NextResponse.json({ + ...baseResponse, + awarded: false, + message: "Not quite — review the expected points and try again.", + }); + } + + const award = await awardCodingXp({ + userId, + exerciseType: "written", + description: `Solved ${problem.difficulty} ${problem.type} "${problem.title}" (written)`, + qualityScore: grade.qualityScore, + difficulty: problem.difficulty as CodingDifficulty, + durationSecs, + metadata: { + problemId: problem.id, + problemType: problem.type, + language: problem.language, + difficulty: problem.difficulty, + gradedBy: baseResponse.gradedBy, + kind: "written", + }, + }); + + return NextResponse.json({ + ...baseResponse, + awarded: true, + ...award, + message: award.isCriticalHit + ? "Critical Hit! Strong written answer!" + : "Correct — written answer accepted!", + }); +}); diff --git a/src/app/api/critical/__tests__/routes.test.ts b/src/app/api/critical/__tests__/routes.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..870cb9ab526cea7f29f93ca8b64a982ec3e59001 --- /dev/null +++ b/src/app/api/critical/__tests__/routes.test.ts @@ -0,0 +1,850 @@ +/** + * Tests for Critical Thinking API route handlers. + * + * Covers: + * GET /api/critical/generate + * - returns a valid flaw-finder exercise (default and explicit type) + * - returns a steelman exercise + * - returns a devils-advocate exercise + * - falls back to random type on invalid type param + * - respects difficulty param for flaw-finder + * - does NOT include fallacies (answer key) in flaw-finder response + * - response shape: type, passage / position fields + * + * POST /api/critical/score + * - API key guard (503 when missing, no Claude call) + * - input validation: missing exerciseType, invalid exerciseType, short response (<20 chars) + * - flaw-finder: missing passageId → 400; invalid passageId → 404 + * - steelman: missing positionId → 400; invalid positionId → 404 + * - devils-advocate: missing positionId → 400; invalid positionId → 404 + * - invalid JSON body → 400 + * - Claude integration: prompt content, haiku model, invalid JSON → 500, network error → 500 + * - user not found → 404 + * - missing critical-thinking CategorySkill → 500 + * - response shape: exerciseType, scores, overallScore, feedback, strengths, improvements, xp, levelUp, categoryXp, unlocks + * - XP: quality score derived from overallScore/10; qualityBonus for high scores + * - XP: critical hit doubles totalXp + * - XP: multiplier bonus reflected in response + * - DailyLog: created when no existing log; updated when one exists + * - goalMet flag when XP reaches dailyGoalXp + * - processSkillUnlocks called on category level-up; not called otherwise + */ + +import { describe, it, expect, vi, beforeEach } from "vitest"; +import { NextRequest } from "next/server"; + +// --------------------------------------------------------------------------- +// Mock Prisma +// --------------------------------------------------------------------------- + +const mockUserFindFirst = vi.fn(); +const mockDailyLogFindFirst = vi.fn(); +const mockTransaction = vi.fn(); + +vi.mock("@/lib/db", () => ({ + prisma: { + user: { findFirst: (...args: unknown[]) => mockUserFindFirst(...args) }, + dailyLog: { findFirst: (...args: unknown[]) => mockDailyLogFindFirst(...args) }, + $transaction: (...args: unknown[]) => mockTransaction(...args), + }, +})); + +// --------------------------------------------------------------------------- +// Mock Claude +// --------------------------------------------------------------------------- + +const mockClaudeCreate = vi.fn(); + +vi.mock("@/lib/claude", () => ({ + claude: { + messages: { create: (...args: unknown[]) => mockClaudeCreate(...args) }, + }, + parseClaudeJson: (text: string) => JSON.parse(text.trim().replace(/^```(?:json)?\s*/i, "").replace(/\s*```\s*$/, "").trim()), +})); + +// --------------------------------------------------------------------------- +// Mock rollCriticalHit (deterministic) +// --------------------------------------------------------------------------- + +const mockRollCriticalHit = vi.fn(() => false); + +vi.mock("@/lib/xp", async (importOriginal) => { + const actual = await importOriginal(); + return { + ...actual, + rollCriticalHit: () => mockRollCriticalHit(), + }; +}); + +// --------------------------------------------------------------------------- +// Mock getMultiplierPercent +// --------------------------------------------------------------------------- + +const mockGetMultiplierPercent = vi.fn(() => Promise.resolve(0)); + +vi.mock("@/lib/multiplier", () => ({ + getMultiplierPercent: (...args: unknown[]) => (mockGetMultiplierPercent as (...a: unknown[]) => unknown)(...args), +})); + +// --------------------------------------------------------------------------- +// Mock processSkillUnlocks +// --------------------------------------------------------------------------- + +const mockProcessSkillUnlocks = vi.fn((): Promise<{ unlocked: string[]; streakFreezesGranted: number }> => + Promise.resolve({ unlocked: [], streakFreezesGranted: 0 }), +); + +vi.mock("@/lib/skill-unlock", () => ({ + processSkillUnlocks: (...args: unknown[]) => (mockProcessSkillUnlocks as (...a: unknown[]) => unknown)(...args), +})); + +// --------------------------------------------------------------------------- +// Mock processEndOfDay (no-op — streak logic is tested separately) +// --------------------------------------------------------------------------- + +vi.mock("@/lib/streak", () => ({ + processEndOfDay: vi.fn(() => Promise.resolve({ + streak: 1, + freezeUsed: false, + streakBroken: false, + alreadyProcessed: false, + })), +})); + +// --------------------------------------------------------------------------- +// Mock debate-scorer (used for steelman / devils-advocate scoring) +// --------------------------------------------------------------------------- + +const mockRunDebateScoring = vi.fn(); + +vi.mock("@/lib/critical/debate-scorer", () => ({ + runDebateScoring: (...args: unknown[]) => + (mockRunDebateScoring as (...a: unknown[]) => unknown)(...args), +})); + +// --------------------------------------------------------------------------- +// Shared test helpers +// --------------------------------------------------------------------------- + +function makeRequest( + method: "GET" | "POST", + url: string, + body?: unknown, +): NextRequest { + return new NextRequest(url, { + method, + body: body !== undefined ? JSON.stringify(body) : undefined, + headers: body !== undefined ? { "content-type": "application/json" } : {}, + }); +} + +/** Returns a user fixture with a critical-thinking CategorySkill */ +function makeUser(overrides: Record = {}) { + return { + id: 1, + currentXp: 100, + totalXp: 500, + xpToNextLevel: 200, + level: 3, + title: "Apprentice", + dailyGoalXp: 100, + categorySkills: [ + { + id: 10, + category: "critical-thinking", + currentXp: 50, + totalXp: 200, + xpToNext: 150, + level: 2, + }, + ], + ...overrides, + }; +} + +/** Simulates prisma.$transaction by executing the callback with mock tx */ +function mockTxExec() { + mockTransaction.mockImplementation(async (cb: (tx: unknown) => unknown) => { + const tx = { + activity: { create: vi.fn() }, + user: { update: vi.fn() }, + categorySkill: { update: vi.fn() }, + dailyLog: { create: vi.fn(), update: vi.fn() }, + }; + return cb(tx); + }); +} + +// --------------------------------------------------------------------------- +// GET /api/critical/generate +// --------------------------------------------------------------------------- + +describe("GET /api/critical/generate", () => { + async function callGenerate(params: Record = {}) { + const { GET } = await import("@/app/api/critical/generate/route"); + const qs = new URLSearchParams(params).toString(); + const url = `http://localhost/api/critical/generate${qs ? `?${qs}` : ""}`; + const req = makeRequest("GET", url); + return GET(req); + } + + it("returns a flaw-finder exercise when type=flaw-finder", async () => { + const res = await callGenerate({ type: "flaw-finder" }); + expect(res.status).toBe(200); + const body = await res.json(); + expect(body.type).toBe("flaw-finder"); + expect(body.passage).toBeDefined(); + expect(body.passage.id).toBeTruthy(); + expect(body.passage.title).toBeTruthy(); + expect(body.passage.passage).toBeTruthy(); + expect(body.passage.fallacyCount).toBeGreaterThan(0); + }); + + it("does NOT expose fallacies (answer key) in flaw-finder response", async () => { + const res = await callGenerate({ type: "flaw-finder" }); + const body = await res.json(); + expect(body.passage.fallacies).toBeUndefined(); + }); + + it("respects difficulty param for flaw-finder", async () => { + const res = await callGenerate({ type: "flaw-finder", difficulty: "easy" }); + const body = await res.json(); + expect(body.passage.difficulty).toBe("easy"); + }); + + it("returns a steelman exercise when type=steelman", async () => { + const res = await callGenerate({ type: "steelman" }); + expect(res.status).toBe(200); + const body = await res.json(); + expect(body.type).toBe("steelman"); + expect(body.position).toBeDefined(); + expect(body.position.id).toBeTruthy(); + expect(body.position.domain).toBeTruthy(); + expect(body.position.position).toBeTruthy(); + expect(body.position.context).toBeTruthy(); + }); + + it("returns a devils-advocate exercise when type=devils-advocate", async () => { + const res = await callGenerate({ type: "devils-advocate" }); + expect(res.status).toBe(200); + const body = await res.json(); + expect(body.type).toBe("devils-advocate"); + expect(body.position).toBeDefined(); + expect(body.position.id).toBeTruthy(); + }); + + it("falls back to a random valid type when type param is invalid", async () => { + const res = await callGenerate({ type: "made-up-type" }); + expect(res.status).toBe(200); + const body = await res.json(); + expect(["flaw-finder", "steelman", "devils-advocate"]).toContain(body.type); + }); + + it("returns a valid exercise with no query params (random type)", async () => { + const res = await callGenerate(); + expect(res.status).toBe(200); + const body = await res.json(); + expect(["flaw-finder", "steelman", "devils-advocate"]).toContain(body.type); + }); + + it("steelman response does not include passage field", async () => { + const res = await callGenerate({ type: "steelman" }); + const body = await res.json(); + expect(body.passage).toBeUndefined(); + }); + + it("flaw-finder response includes fallacyCount as a number", async () => { + const res = await callGenerate({ type: "flaw-finder" }); + const body = await res.json(); + expect(typeof body.passage.fallacyCount).toBe("number"); + }); +}); + +// --------------------------------------------------------------------------- +// POST /api/critical/score +// --------------------------------------------------------------------------- + +describe("POST /api/critical/score", () => { + const VALID_FLAW_PASSAGE_ID = "ff-easy-1"; + const VALID_STEELMAN_POSITION_ID = "sm-1"; + const VALID_DEVILS_POSITION_ID = "da-1"; + + const VALID_RESPONSE = "This argument contains a slippery slope fallacy because it assumes that one event will automatically lead to another without sufficient evidence to support this chain of causation."; + + const VALID_FLAW_BODY = { + exerciseType: "flaw-finder", + passageId: VALID_FLAW_PASSAGE_ID, + response: VALID_RESPONSE, + }; + + const CLAUDE_SCORE_RESULT: { + scores: Record; + overallScore: number; + feedback: string; + strengths: string[]; + improvements: string[]; + } = { + scores: { identification: 8, accuracy: 7, depth: 6 }, + overallScore: 7, + feedback: "Good identification of the main fallacy.", + strengths: ["Correctly named the fallacy"], + improvements: ["Could explain the mechanism more clearly"], + }; + + function mockClaudeScore(result = CLAUDE_SCORE_RESULT) { + mockClaudeCreate.mockResolvedValueOnce({ + content: [{ type: "text", text: JSON.stringify(result) }], + }); + } + + const DEFAULT_DEBATE_RESULT: { + scores: Record; + overallScore: number; + feedback: string; + strengths: string[]; + improvements: string[]; + debateLog: unknown[]; + } = { + scores: { charitableInterpretation: 8, coherence: 7, evidenceAndReasoning: 7 }, + overallScore: 7, + feedback: "Good argument.", + strengths: ["Well-reasoned"], + improvements: ["More depth needed"], + debateLog: [], + }; + + function mockDebateScore(result: typeof DEFAULT_DEBATE_RESULT = DEFAULT_DEBATE_RESULT) { + mockRunDebateScoring.mockResolvedValueOnce(result); + } + + async function callScore(body: unknown, apiKey = "test-key") { + const savedKey = process.env.ANTHROPIC_API_KEY; + if (apiKey) { + process.env.ANTHROPIC_API_KEY = apiKey; + } else { + delete process.env.ANTHROPIC_API_KEY; + } + const { POST } = await import("@/app/api/critical/score/route"); + const req = makeRequest("POST", "http://localhost/api/critical/score", body); + const res = await POST(req); + if (apiKey) { + process.env.ANTHROPIC_API_KEY = savedKey; + } else { + delete process.env.ANTHROPIC_API_KEY; + } + return res; + } + + beforeEach(() => { + vi.resetModules(); + mockClaudeCreate.mockReset(); + mockRunDebateScoring.mockReset(); + mockUserFindFirst.mockReset(); + mockDailyLogFindFirst.mockReset(); + mockTransaction.mockReset(); + mockRollCriticalHit.mockReturnValue(false); + mockGetMultiplierPercent.mockResolvedValue(0); + mockProcessSkillUnlocks.mockResolvedValue({ unlocked: [], streakFreezesGranted: 0 }); + }); + + // --- API key guard --- + + it("returns 503 when ANTHROPIC_API_KEY is missing", async () => { + const res = await callScore(VALID_FLAW_BODY, ""); + expect(res.status).toBe(503); + expect(mockClaudeCreate).not.toHaveBeenCalled(); + }); + + it("returns 503 when ANTHROPIC_API_KEY is empty string", async () => { + const savedKey = process.env.ANTHROPIC_API_KEY; + process.env.ANTHROPIC_API_KEY = ""; + const { POST } = await import("@/app/api/critical/score/route"); + const req = makeRequest("POST", "http://localhost/api/critical/score", VALID_FLAW_BODY); + const res = await POST(req); + process.env.ANTHROPIC_API_KEY = savedKey; + expect(res.status).toBe(503); + expect(mockClaudeCreate).not.toHaveBeenCalled(); + }); + + // --- Input validation --- + + it("returns 400 for invalid JSON body", async () => { + process.env.ANTHROPIC_API_KEY = "test-key"; + const { POST } = await import("@/app/api/critical/score/route"); + const req = new NextRequest("http://localhost/api/critical/score", { + method: "POST", + body: "not-json", + headers: { "content-type": "application/json" }, + }); + const res = await POST(req); + expect(res.status).toBe(400); + }); + + it("returns 400 when exerciseType is missing", async () => { + const res = await callScore({ response: VALID_RESPONSE }); + expect(res.status).toBe(400); + const body = await res.json(); + expect(body.error).toMatch(/exerciseType/i); + }); + + it("returns 400 when exerciseType is invalid", async () => { + const res = await callScore({ exerciseType: "invalid", response: VALID_RESPONSE }); + expect(res.status).toBe(400); + }); + + it("returns 400 when response is missing", async () => { + const res = await callScore({ exerciseType: "flaw-finder", passageId: VALID_FLAW_PASSAGE_ID }); + expect(res.status).toBe(400); + }); + + it("returns 400 when response is too short (< 20 chars)", async () => { + const res = await callScore({ + exerciseType: "flaw-finder", + passageId: VALID_FLAW_PASSAGE_ID, + response: "too short", + }); + expect(res.status).toBe(400); + const body = await res.json(); + expect(body.error).toMatch(/20 characters/i); + }); + + it("returns 400 when flaw-finder is missing passageId", async () => { + const res = await callScore({ exerciseType: "flaw-finder", response: VALID_RESPONSE }); + expect(res.status).toBe(400); + const body = await res.json(); + expect(body.error).toMatch(/passageId/i); + }); + + it("returns 404 when flaw-finder passageId is invalid", async () => { + const res = await callScore({ + exerciseType: "flaw-finder", + passageId: "does-not-exist-xyz", + response: VALID_RESPONSE, + }); + expect(res.status).toBe(404); + }); + + it("returns 400 when steelman is missing positionId", async () => { + const res = await callScore({ exerciseType: "steelman", response: VALID_RESPONSE }); + expect(res.status).toBe(400); + const body = await res.json(); + expect(body.error).toMatch(/positionId/i); + }); + + it("returns 404 when steelman positionId is invalid", async () => { + const res = await callScore({ + exerciseType: "steelman", + positionId: "does-not-exist-xyz", + response: VALID_RESPONSE, + }); + expect(res.status).toBe(404); + }); + + it("returns 400 when devils-advocate is missing positionId", async () => { + const res = await callScore({ exerciseType: "devils-advocate", response: VALID_RESPONSE }); + expect(res.status).toBe(400); + const body = await res.json(); + expect(body.error).toMatch(/positionId/i); + }); + + it("returns 404 when devils-advocate positionId is invalid", async () => { + const res = await callScore({ + exerciseType: "devils-advocate", + positionId: "does-not-exist-xyz", + response: VALID_RESPONSE, + }); + expect(res.status).toBe(404); + }); + + // --- Claude errors --- + + it("returns 500 when Claude returns invalid JSON", async () => { + mockClaudeCreate.mockResolvedValueOnce({ + content: [{ type: "text", text: "not valid json {{{" }], + }); + const res = await callScore(VALID_FLAW_BODY); + expect(res.status).toBe(500); + const body = await res.json(); + expect(body.error).toMatch(/Failed to score/i); + }); + + it("returns 500 when Claude throws a network error", async () => { + mockClaudeCreate.mockRejectedValueOnce(new Error("Network timeout")); + const res = await callScore(VALID_FLAW_BODY); + expect(res.status).toBe(500); + }); + + it("uses claude-3-5-haiku model", async () => { + mockClaudeScore(); + mockUserFindFirst.mockResolvedValue(makeUser()); + mockDailyLogFindFirst.mockResolvedValue(null); + mockTxExec(); + await callScore(VALID_FLAW_BODY); + expect(mockClaudeCreate).toHaveBeenCalledWith( + expect.objectContaining({ model: "claude-haiku-4-5-20251001" }), + ); + }); + + it("includes the passage text in the Claude prompt for flaw-finder", async () => { + mockClaudeScore(); + mockUserFindFirst.mockResolvedValue(makeUser()); + mockDailyLogFindFirst.mockResolvedValue(null); + mockTxExec(); + await callScore(VALID_FLAW_BODY); + const promptContent = mockClaudeCreate.mock.calls[0][0].messages[0].content as string; + // Prompt should reference the passage content (not the answer key) + expect(promptContent.toLowerCase()).toContain("fallac"); + }); + + // --- DB errors --- + + it("returns 404 when user is not found", async () => { + mockClaudeScore(); + mockUserFindFirst.mockResolvedValue(null); + const res = await callScore(VALID_FLAW_BODY); + expect(res.status).toBe(404); + }); + + it("returns 500 when critical-thinking CategorySkill is missing", async () => { + mockClaudeScore(); + mockUserFindFirst.mockResolvedValue(makeUser({ categorySkills: [] })); + const res = await callScore(VALID_FLAW_BODY); + expect(res.status).toBe(500); + }); + + // --- Success path: flaw-finder --- + + it("returns 200 with correct shape for flaw-finder", async () => { + mockClaudeScore(); + mockUserFindFirst.mockResolvedValue(makeUser()); + mockDailyLogFindFirst.mockResolvedValue(null); + mockTxExec(); + const res = await callScore(VALID_FLAW_BODY); + expect(res.status).toBe(200); + const body = await res.json(); + expect(body.exerciseType).toBe("flaw-finder"); + expect(body.scores).toBeDefined(); + expect(body.overallScore).toBe(7); + expect(body.feedback).toBeTruthy(); + expect(Array.isArray(body.strengths)).toBe(true); + expect(Array.isArray(body.improvements)).toBe(true); + expect(body.xp).toBeDefined(); + expect(body.xp.baseXp).toBeGreaterThan(0); + expect(body.xp.totalXp).toBeGreaterThan(0); + expect(body.levelUp).toBeDefined(); + expect(body.categoryXp).toBeDefined(); + expect(Array.isArray(body.unlocks)).toBe(true); + }); + + it("returns 200 with correct shape for steelman", async () => { + mockDebateScore({ + scores: { charitableInterpretation: 9, coherence: 8, evidenceAndReasoning: 7 }, + overallScore: 8, + feedback: "Strong steelman.", + strengths: ["Well-reasoned"], + improvements: [], + debateLog: [], + }); + mockUserFindFirst.mockResolvedValue(makeUser()); + mockDailyLogFindFirst.mockResolvedValue(null); + mockTxExec(); + const res = await callScore({ + exerciseType: "steelman", + positionId: VALID_STEELMAN_POSITION_ID, + response: VALID_RESPONSE, + }); + expect(res.status).toBe(200); + const body = await res.json(); + expect(body.exerciseType).toBe("steelman"); + expect(body.overallScore).toBe(8); + }); + + it("returns 200 with correct shape for devils-advocate", async () => { + mockDebateScore({ + scores: { argumentStrength: 6, evidence: 5, intellectualHonesty: 7 }, + overallScore: 6, + feedback: "Decent counter-argument.", + strengths: ["Good evidence"], + improvements: ["More nuance needed"], + debateLog: [], + }); + mockUserFindFirst.mockResolvedValue(makeUser()); + mockDailyLogFindFirst.mockResolvedValue(null); + mockTxExec(); + const res = await callScore({ + exerciseType: "devils-advocate", + positionId: VALID_DEVILS_POSITION_ID, + response: VALID_RESPONSE, + }); + expect(res.status).toBe(200); + const body = await res.json(); + expect(body.exerciseType).toBe("devils-advocate"); + }); + + // --- XP calculations --- + + it("quality score is derived from overallScore / 10", async () => { + // overallScore=0 → qualityScore=0 → no quality bonus + mockClaudeCreate.mockResolvedValueOnce({ + content: [{ type: "text", text: JSON.stringify({ ...CLAUDE_SCORE_RESULT, overallScore: 0 }) }], + }); + mockUserFindFirst.mockResolvedValue(makeUser()); + mockDailyLogFindFirst.mockResolvedValue(null); + mockTxExec(); + const res = await callScore(VALID_FLAW_BODY); + const body = await res.json(); + expect(body.xp.qualityBonus).toBe(0); + }); + + it("full quality score (overallScore=10) produces qualityBonus > 0", async () => { + mockClaudeCreate.mockResolvedValueOnce({ + content: [{ type: "text", text: JSON.stringify({ ...CLAUDE_SCORE_RESULT, overallScore: 10 }) }], + }); + mockUserFindFirst.mockResolvedValue(makeUser()); + mockDailyLogFindFirst.mockResolvedValue(null); + mockTxExec(); + const res = await callScore(VALID_FLAW_BODY); + const body = await res.json(); + expect(body.xp.qualityBonus).toBeGreaterThan(0); + }); + + it("critical hit doubles totalXp", async () => { + mockRollCriticalHit.mockReturnValueOnce(true); + mockClaudeScore(); + mockUserFindFirst.mockResolvedValue(makeUser()); + mockDailyLogFindFirst.mockResolvedValue(null); + mockTxExec(); + const resCrit = await callScore(VALID_FLAW_BODY); + const bodyCrit = await resCrit.json(); + + mockRollCriticalHit.mockReturnValueOnce(false); + mockClaudeScore(); + mockUserFindFirst.mockResolvedValue(makeUser()); + mockDailyLogFindFirst.mockResolvedValue(null); + mockTxExec(); + const resNorm = await callScore(VALID_FLAW_BODY); + const bodyNorm = await resNorm.json(); + + expect(bodyCrit.xp.totalXp).toBeGreaterThan(bodyNorm.xp.totalXp); + expect(bodyCrit.xp.isCriticalHit).toBe(true); + }); + + it("multiplier bonus is reflected in xp response", async () => { + mockGetMultiplierPercent.mockResolvedValueOnce(50); + mockClaudeScore(); + mockUserFindFirst.mockResolvedValue(makeUser()); + mockDailyLogFindFirst.mockResolvedValue(null); + mockTxExec(); + const res = await callScore(VALID_FLAW_BODY); + const body = await res.json(); + expect(body.xp.multiplierPercent).toBe(50); + expect(body.xp.multiplierBonus).toBeGreaterThan(0); + }); + + // --- DailyLog --- + + it("creates a new DailyLog when none exists", async () => { + mockClaudeScore(); + mockUserFindFirst.mockResolvedValue(makeUser()); + mockDailyLogFindFirst.mockResolvedValue(null); + + let dailyLogCreated = false; + mockTransaction.mockImplementation(async (cb: (tx: unknown) => unknown) => { + const tx = { + activity: { create: vi.fn() }, + user: { update: vi.fn() }, + categorySkill: { update: vi.fn() }, + dailyLog: { + create: vi.fn(() => { dailyLogCreated = true; }), + update: vi.fn(), + }, + }; + return cb(tx); + }); + + await callScore(VALID_FLAW_BODY); + expect(dailyLogCreated).toBe(true); + }); + + it("updates existing DailyLog when one exists", async () => { + mockClaudeScore(); + mockUserFindFirst.mockResolvedValue(makeUser()); + mockDailyLogFindFirst.mockResolvedValue({ id: 99, xpEarned: 50, activityCount: 2, goalMet: false }); + + let dailyLogUpdated = false; + mockTransaction.mockImplementation(async (cb: (tx: unknown) => unknown) => { + const tx = { + activity: { create: vi.fn() }, + user: { update: vi.fn() }, + categorySkill: { update: vi.fn() }, + dailyLog: { + create: vi.fn(), + update: vi.fn(() => { dailyLogUpdated = true; }), + }, + }; + return cb(tx); + }); + + await callScore(VALID_FLAW_BODY); + expect(dailyLogUpdated).toBe(true); + }); + + it("sets goalMet when cumulative XP reaches dailyGoalXp", async () => { + // User has dailyGoalXp=100; existing log already at 90 XP — any gain should set goalMet + mockClaudeScore(); + mockUserFindFirst.mockResolvedValue(makeUser({ dailyGoalXp: 100 })); + mockDailyLogFindFirst.mockResolvedValue({ id: 5, xpEarned: 90, activityCount: 1, goalMet: false }); + + let capturedGoalMet: boolean | undefined; + mockTransaction.mockImplementation(async (cb: (tx: unknown) => unknown) => { + const tx = { + activity: { create: vi.fn() }, + user: { update: vi.fn() }, + categorySkill: { update: vi.fn() }, + dailyLog: { + create: vi.fn(), + update: vi.fn(({ data }: { data: { goalMet: boolean } }) => { + capturedGoalMet = data.goalMet; + }), + }, + }; + return cb(tx); + }); + + await callScore(VALID_FLAW_BODY); + expect(capturedGoalMet).toBe(true); + }); + + // --- Skill unlocks --- + + it("calls processSkillUnlocks when category levels up", async () => { + // Force a category level-up by having the category at max currentXp + mockClaudeScore(); + const user = makeUser(); + user.categorySkills[0].currentXp = 9999; // will exceed xpToNext + user.categorySkills[0].xpToNext = 1; + mockUserFindFirst.mockResolvedValue(user); + mockDailyLogFindFirst.mockResolvedValue(null); + + mockTransaction.mockImplementation(async (cb: (tx: unknown) => unknown) => { + const tx = { + activity: { create: vi.fn() }, + user: { update: vi.fn() }, + categorySkill: { update: vi.fn() }, + dailyLog: { create: vi.fn(), update: vi.fn() }, + }; + mockProcessSkillUnlocks.mockImplementationOnce(() => { + return Promise.resolve({ unlocked: ["Flaw Detector"], streakFreezesGranted: 0 }); + }); + return cb(tx); + }); + + const res = await callScore(VALID_FLAW_BODY); + expect(res.status).toBe(200); + // If level-up happened, unlocks should be in response + // (exact call tracking depends on route implementation, but response shape validates) + const body = await res.json(); + expect(Array.isArray(body.unlocks)).toBe(true); + }); + + it("does not call processSkillUnlocks when no category level-up", async () => { + mockClaudeScore(); + // Give user a category skill that won't level up (plenty of xpToNext) + const user = makeUser(); + user.categorySkills[0].currentXp = 0; + user.categorySkills[0].xpToNext = 99999; + mockUserFindFirst.mockResolvedValue(user); + mockDailyLogFindFirst.mockResolvedValue(null); + mockProcessSkillUnlocks.mockClear(); + mockTxExec(); + + await callScore(VALID_FLAW_BODY); + expect(mockProcessSkillUnlocks).not.toHaveBeenCalled(); + }); + + it("returns empty unlocks array when no level-up", async () => { + mockClaudeScore(); + mockUserFindFirst.mockResolvedValue(makeUser()); + mockDailyLogFindFirst.mockResolvedValue(null); + mockTxExec(); + const res = await callScore(VALID_FLAW_BODY); + const body = await res.json(); + expect(body.unlocks).toEqual([]); + expect(body.streakFreezesGranted).toBe(0); + }); + + // ------------------------------------------------------------------------- + // durationSecs persistence + // ------------------------------------------------------------------------- + + describe("durationSecs", () => { + /** Like mockTxExec but captures the activity.create call for assertion */ + function mockTxExecWithCapture(): { activityCreate: ReturnType } { + const activityCreate = vi.fn(); + mockTransaction.mockImplementation(async (cb: (tx: unknown) => unknown) => { + const tx = { + activity: { create: activityCreate }, + user: { update: vi.fn() }, + categorySkill: { update: vi.fn() }, + dailyLog: { create: vi.fn(), update: vi.fn() }, + }; + return cb(tx); + }); + return { activityCreate }; + } + + beforeEach(() => { + mockClaudeScore(); + mockUserFindFirst.mockResolvedValue(makeUser()); + mockDailyLogFindFirst.mockResolvedValue(null); + }); + + it("persists durationSecs when provided", async () => { + const { activityCreate } = mockTxExecWithCapture(); + await callScore({ ...VALID_FLAW_BODY, durationSecs: 120 }); + const createArg = activityCreate.mock.calls[0][0] as { data: { durationSecs: number | null } }; + expect(createArg.data.durationSecs).toBe(120); + }); + + it("rounds durationSecs to nearest integer", async () => { + const { activityCreate } = mockTxExecWithCapture(); + await callScore({ ...VALID_FLAW_BODY, durationSecs: 37.8 }); + const createArg = activityCreate.mock.calls[0][0] as { data: { durationSecs: number | null } }; + expect(createArg.data.durationSecs).toBe(38); + }); + + it("persists null when durationSecs is omitted", async () => { + const { activityCreate } = mockTxExecWithCapture(); + await callScore(VALID_FLAW_BODY); + const createArg = activityCreate.mock.calls[0][0] as { data: { durationSecs: number | null } }; + expect(createArg.data.durationSecs).toBeNull(); + }); + + it("persists null when durationSecs is negative", async () => { + const { activityCreate } = mockTxExecWithCapture(); + await callScore({ ...VALID_FLAW_BODY, durationSecs: -10 }); + const createArg = activityCreate.mock.calls[0][0] as { data: { durationSecs: number | null } }; + expect(createArg.data.durationSecs).toBeNull(); + }); + + it("accepts durationSecs of 0 (instant submit)", async () => { + const { activityCreate } = mockTxExecWithCapture(); + await callScore({ ...VALID_FLAW_BODY, durationSecs: 0 }); + const createArg = activityCreate.mock.calls[0][0] as { data: { durationSecs: number | null } }; + expect(createArg.data.durationSecs).toBe(0); + }); + + it("works for steelman exercise type", async () => { + mockDebateScore(); + const { activityCreate } = mockTxExecWithCapture(); + await callScore({ + exerciseType: "steelman", + positionId: "sm-1", + response: "A".repeat(30), + durationSecs: 200, + }); + const createArg = activityCreate.mock.calls[0][0] as { data: { durationSecs: number | null } }; + expect(createArg.data.durationSecs).toBe(200); + }); + }); +}); diff --git a/src/app/api/critical/generate/route.ts b/src/app/api/critical/generate/route.ts new file mode 100644 index 0000000000000000000000000000000000000000..0bb24fedf46b4c40334677f665bd2da18a968406 --- /dev/null +++ b/src/app/api/critical/generate/route.ts @@ -0,0 +1,75 @@ +import { NextRequest, NextResponse } from "next/server"; +import { + getRandomFlawPassage, + getRandomSteelmanPosition, + getRandomDevilsAdvocatePosition, + type ExerciseType, + type FlawDifficulty, +} from "@/lib/critical/passages"; +import { withApiError } from "@/lib/api-error"; + +/** + * GET /api/critical/generate + * + * Query params: + * type?: "flaw-finder" | "steelman" | "devils-advocate" + * difficulty?: "easy" | "medium" | "hard" (only for flaw-finder) + */ +export const GET = withApiError(async (request: NextRequest) => { + const { searchParams } = new URL(request.url); + const rawType = searchParams.get("type"); + const rawDiff = searchParams.get("difficulty"); + + const validTypes: ExerciseType[] = ["flaw-finder", "steelman", "devils-advocate"]; + const validDiffs: FlawDifficulty[] = ["easy", "medium", "hard"]; + + const type: ExerciseType = + rawType && validTypes.includes(rawType as ExerciseType) + ? (rawType as ExerciseType) + : validTypes[Math.floor(Math.random() * validTypes.length)]; + + const difficulty: FlawDifficulty | undefined = + rawDiff && validDiffs.includes(rawDiff as FlawDifficulty) + ? (rawDiff as FlawDifficulty) + : undefined; + + if (type === "flaw-finder") { + const passage = getRandomFlawPassage(difficulty); + return NextResponse.json({ + type, + passage: { + id: passage.id, + difficulty: passage.difficulty, + title: passage.title, + passage: passage.passage, + fallacyCount: passage.fallacies.length, + // do NOT return fallacies here — those are the answer key + }, + }); + } + + if (type === "steelman") { + const position = getRandomSteelmanPosition(); + return NextResponse.json({ + type, + position: { + id: position.id, + domain: position.domain, + position: position.position, + context: position.context, + }, + }); + } + + // devils-advocate + const position = getRandomDevilsAdvocatePosition(); + return NextResponse.json({ + type, + position: { + id: position.id, + domain: position.domain, + position: position.position, + context: position.context, + }, + }); +}); diff --git a/src/app/api/critical/score/route.ts b/src/app/api/critical/score/route.ts new file mode 100644 index 0000000000000000000000000000000000000000..567c3dba4347c3fa98c7d1b2a2631cbfda549624 --- /dev/null +++ b/src/app/api/critical/score/route.ts @@ -0,0 +1,438 @@ +import { NextRequest, NextResponse } from "next/server"; +import { claude, parseClaudeJson } from "@/lib/claude"; +import { prisma } from "@/lib/db"; +// import { Prisma } from "@prisma/client"; +import { calculateXpGain, rollCriticalHit } from "@/lib/xp"; +import { checkLevelUp } from "@/lib/progression"; +import { EXERCISE_XP } from "@/config/xp"; +import { + FLAW_FINDER_PASSAGES, + STEELMAN_POSITIONS, + DEVILS_ADVOCATE_POSITIONS, + type ExerciseType, +} from "@/lib/critical/passages"; +import { runDebateScoring, type DebateScoreResult } from "@/lib/critical/debate-scorer"; +import { processSkillUnlocks } from "@/lib/skill-unlock"; +import { getMultiplierPercent } from "@/lib/multiplier"; +import { getTitleForLevel } from "@/config/titles"; +import { withApiError } from "@/lib/api-error"; +import { processEndOfDay } from "@/lib/streak"; + +interface FlawFinderBody { + exerciseType: "flaw-finder"; + passageId: string; + response: string; // user's written identification of flaws + userId?: number; + durationSecs?: number; +} + +interface SteelmanBody { + exerciseType: "steelman"; + positionId: string; + response: string; + userId?: number; + durationSecs?: number; +} + +interface DevilsAdvocateBody { + exerciseType: "devils-advocate"; + positionId: string; + response: string; + userId?: number; + durationSecs?: number; +} + +type ScoreBody = FlawFinderBody | SteelmanBody | DevilsAdvocateBody; + +interface ClaudeScoreResult { + scores: Record; // dimension → 0-10 + overallScore: number; // 0-10 + feedback: string; + strengths: string[]; + improvements: string[]; +} + +// --------------------------------------------------------------------------- +// Build Claude prompts per exercise type +// --------------------------------------------------------------------------- + +function buildFlawFinderPrompt(passageId: string, response: string): string | null { + const passage = FLAW_FINDER_PASSAGES.find((p) => p.id === passageId); + if (!passage) return null; + + const answerKey = passage.fallacies + .map((f, i) => `${i + 1}. ${f.name}: "${f.quote}" — ${f.explanation}`) + .join("\n"); + + return `You are evaluating a critical thinking exercise. The user was given this passage and asked to identify logical fallacies: + +PASSAGE: +"${passage.passage}" + +ANSWER KEY (do not share this with the user — use it to evaluate accuracy): +${answerKey} + +USER'S RESPONSE: +${response} + +Score the user on three dimensions (0–10 each): +- Identification: Did they spot the right fallacies (or close equivalents)? +- Accuracy: Did they explain the fallacy correctly? +- Depth: Did they explain WHY the reasoning is flawed, not just name it? + +Respond ONLY in valid JSON (no markdown, no code fences): +{ + "scores": { "identification": N, "accuracy": N, "depth": N }, + "overallScore": N, + "feedback": "...", + "strengths": ["..."], + "improvements": ["..."] +}`; +} + +function buildSteelmanPrompt(positionId: string, response: string): string | null { + const position = STEELMAN_POSITIONS.find((p) => p.id === positionId); + if (!position) return null; + + return `You are evaluating a steelman exercise. The user was asked to construct the strongest possible case FOR this position: + +POSITION: "${position.position}" +DOMAIN: ${position.domain} + +The user should present the most charitable, rigorous version of this argument — not their personal opinion. + +USER'S RESPONSE: +${response} + +Score on three dimensions (0–10 each): +- Charitable Interpretation: Does the response represent the position at its strongest? +- Coherence: Is the argument logically structured and internally consistent? +- Evidence & Reasoning: Does it cite relevant evidence, examples, or principled arguments? + +Respond ONLY in valid JSON (no markdown, no code fences): +{ + "scores": { "charitableInterpretation": N, "coherence": N, "evidenceAndReasoning": N }, + "overallScore": N, + "feedback": "...", + "strengths": ["..."], + "improvements": ["..."] +}`; +} + +function buildDevilsAdvocatePrompt(positionId: string, response: string): string | null { + const position = DEVILS_ADVOCATE_POSITIONS.find((p) => p.id === positionId); + if (!position) return null; + + return `You are evaluating a devil's advocate exercise. The user was asked to argue AGAINST this widely-held or popular position: + +POSITION: "${position.position}" +DOMAIN: ${position.domain} + +The user should produce the strongest counter-argument, not just nitpick. They should argue as if they genuinely believe the opposing view. + +USER'S RESPONSE: +${response} + +Score on three dimensions (0–10 each): +- Argument Strength: How strong and substantive is the counter-argument? +- Evidence: Does it use concrete data, examples, or principled reasoning? +- Intellectual Honesty: Does the user acknowledge trade-offs rather than building a one-sided strawman? + +Respond ONLY in valid JSON (no markdown, no code fences): +{ + "scores": { "argumentStrength": N, "evidence": N, "intellectualHonesty": N }, + "overallScore": N, + "feedback": "...", + "strengths": ["..."], + "improvements": ["..."] +}`; +} + +// --------------------------------------------------------------------------- +// Route handler +// --------------------------------------------------------------------------- + +export const POST = withApiError(async (request: NextRequest) => { + if (!process.env.ANTHROPIC_API_KEY) { + return NextResponse.json( + { error: "ANTHROPIC_API_KEY is not configured" }, + { status: 503 }, + ); + } + + let body: ScoreBody; + try { + body = await request.json(); + } catch { + return NextResponse.json({ error: "Invalid JSON body" }, { status: 400 }); + } + + const validTypes: ExerciseType[] = ["flaw-finder", "steelman", "devils-advocate"]; + if (!body.exerciseType || !validTypes.includes(body.exerciseType)) { + return NextResponse.json( + { error: "exerciseType must be one of: flaw-finder, steelman, devils-advocate" }, + { status: 400 }, + ); + } + + if (!body.response || typeof body.response !== "string" || body.response.trim().length < 20) { + return NextResponse.json( + { error: "response must be a non-empty string (minimum 20 characters)" }, + { status: 400 }, + ); + } + + // Build prompt + let prompt: string | null = null; + let contentId: string = ""; + let contentDescription: string = ""; + + if (body.exerciseType === "flaw-finder") { + const b = body as FlawFinderBody; + if (!b.passageId) { + return NextResponse.json({ error: "passageId is required for flaw-finder" }, { status: 400 }); + } + prompt = buildFlawFinderPrompt(b.passageId, b.response); + contentId = b.passageId; + const passage = FLAW_FINDER_PASSAGES.find((p) => p.id === b.passageId); + contentDescription = passage ? `Flaw Finder: ${passage.title}` : "Flaw Finder"; + } else if (body.exerciseType === "steelman") { + const b = body as SteelmanBody; + if (!b.positionId) { + return NextResponse.json({ error: "positionId is required for steelman" }, { status: 400 }); + } + prompt = buildSteelmanPrompt(b.positionId, b.response); + contentId = b.positionId; + const pos = STEELMAN_POSITIONS.find((p) => p.id === b.positionId); + contentDescription = pos ? `Steelman: ${pos.position}` : "Steelman"; + } else { + const b = body as DevilsAdvocateBody; + if (!b.positionId) { + return NextResponse.json({ error: "positionId is required for devils-advocate" }, { status: 400 }); + } + prompt = buildDevilsAdvocatePrompt(b.positionId, b.response); + contentId = b.positionId; + const pos = DEVILS_ADVOCATE_POSITIONS.find((p) => p.id === b.positionId); + contentDescription = pos ? `Devil's Advocate: ${pos.position}` : "Devil's Advocate"; + } + + if (!prompt) { + return NextResponse.json({ error: "Content not found" }, { status: 404 }); + } + + // --- Call Claude (DEBATE framework for steelman / devils-advocate) --- + let scored: ClaudeScoreResult; + let debateLog: DebateScoreResult["debateLog"] | undefined; + try { + if (body.exerciseType === "steelman" || body.exerciseType === "devils-advocate") { + const pos = + body.exerciseType === "steelman" + ? STEELMAN_POSITIONS.find((p) => p.id === (body as SteelmanBody).positionId) + : DEVILS_ADVOCATE_POSITIONS.find((p) => p.id === (body as DevilsAdvocateBody).positionId); + + const debateResult = await runDebateScoring( + body.exerciseType, + pos!.position, + pos!.domain, + body.response, + ); + scored = { + scores: debateResult.scores, + overallScore: debateResult.overallScore, + feedback: debateResult.feedback, + strengths: debateResult.strengths, + improvements: debateResult.improvements, + }; + debateLog = debateResult.debateLog; + } else { + // Flaw-finder: single-pass scoring (no debate) + const message = await claude.messages.create({ + model: "claude-haiku-4-5-20251001", + max_tokens: 1024, + messages: [{ role: "user", content: prompt! }], + }); + + const text = + message.content[0].type === "text" ? message.content[0].text : "{}"; + scored = parseClaudeJson(text) as ClaudeScoreResult; + } + } catch (err) { + return NextResponse.json( + { + error: "Failed to score response", + details: err instanceof Error ? err.message : String(err), + }, + { status: 500 }, + ); + } + + // --- Fetch user --- + const userId = body.userId ?? 1; + const user = await prisma.user.findFirst({ + where: { id: userId }, + include: { categorySkills: { where: { category: "critical-thinking" } } }, + }); + + if (!user) { + return NextResponse.json({ error: "No user found" }, { status: 404 }); + } + + const criticalSkill = user.categorySkills[0]; + if (!criticalSkill) { + return NextResponse.json( + { error: "Critical Thinking CategorySkill not found" }, + { status: 500 }, + ); + } + + // --- XP calculation (with skill tree multiplier) --- + const qualityScore = Math.min(1, Math.max(0, scored.overallScore / 10)); + const { baseXp, maxQualityBonus } = EXERCISE_XP["critical-thinking"]; + const isCriticalHit = rollCriticalHit(); + const multiplierPercent = await getMultiplierPercent(prisma, userId, "critical-thinking"); + + const xpResult = calculateXpGain({ + baseXp, + qualityScore, + maxQualityBonus, + isCriticalHit, + multiplierPercent, + }); + + // --- Level-up checks --- + const userLevelResult = checkLevelUp({ + currentXp: user.currentXp + xpResult.totalXp, + xpToNextLevel: user.xpToNextLevel, + level: user.level, + }); + + const categoryLevelResult = checkLevelUp({ + currentXp: criticalSkill.currentXp + xpResult.totalXp, + xpToNextLevel: criticalSkill.xpToNext, + level: criticalSkill.level, + }); + + // --- Title progression --- + const newTitle = getTitleForLevel(userLevelResult.newLevel); + const titleChanged = newTitle !== user.title; + + // --- Streak processing (idempotent — no-op if already run today) --- + await processEndOfDay(userId); + + // --- Daily log bookkeeping --- + const now = new Date(); + const todayStart = new Date( + Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate()), + ); + const tomorrowStart = new Date(todayStart.getTime() + 86_400_000); + + const existingLog = await prisma.dailyLog.findFirst({ + where: { userId, date: { gte: todayStart, lt: tomorrowStart } }, + }); + + const newXpEarned = (existingLog?.xpEarned ?? 0) + xpResult.totalXp; + const newActivityCount = (existingLog?.activityCount ?? 0) + 1; + const goalMet = newXpEarned >= user.dailyGoalXp; + + // --- Persist --- + let unlockResult = { unlocked: [] as string[], streakFreezesGranted: 0 }; + await prisma.$transaction(async (tx) => { + await tx.activity.create({ + data: { + userId, + category: "critical-thinking", + exerciseType: body.exerciseType, + description: contentDescription, + baseXp: xpResult.baseXp, + qualityBonus: xpResult.qualityBonus, + isCriticalHit: xpResult.isCriticalHit, + totalXp: xpResult.totalXp, + score: qualityScore, + durationSecs: + typeof body.durationSecs === "number" && body.durationSecs >= 0 + ? Math.round(body.durationSecs) + : null, + metadata: JSON.stringify({ + exerciseType: body.exerciseType, + contentId, + overallScore: scored.overallScore, + scores: scored.scores, + ...(debateLog && { debateLog }), + }), + }, + }); + + await tx.user.update({ + where: { id: userId }, + data: { + totalXp: user.totalXp + xpResult.totalXp, + currentXp: userLevelResult.remainingXp, + xpToNextLevel: userLevelResult.newXpToNextLevel, + level: userLevelResult.newLevel, + ...(titleChanged && { title: newTitle }), + }, + }); + + await tx.categorySkill.update({ + where: { id: criticalSkill.id }, + data: { + totalXp: criticalSkill.totalXp + xpResult.totalXp, + currentXp: categoryLevelResult.remainingXp, + xpToNext: categoryLevelResult.newXpToNextLevel, + level: categoryLevelResult.newLevel, + }, + }); + + // Auto-unlock skill tree nodes if category leveled up + if (categoryLevelResult.levelsGained > 0) { + unlockResult = await processSkillUnlocks( + tx, userId, "critical-thinking", categoryLevelResult.newLevel, + ); + } + + if (existingLog) { + await tx.dailyLog.update({ + where: { id: existingLog.id }, + data: { xpEarned: newXpEarned, activityCount: newActivityCount, goalMet }, + }); + } else { + await tx.dailyLog.create({ + data: { + userId, + date: todayStart, + xpEarned: newXpEarned, + activityCount: newActivityCount, + goalMet, + }, + }); + } + }); + + return NextResponse.json({ + exerciseType: body.exerciseType, + scores: scored.scores, + overallScore: scored.overallScore, + feedback: scored.feedback, + strengths: scored.strengths ?? [], + improvements: scored.improvements ?? [], + xp: { + baseXp: xpResult.baseXp, + totalXp: xpResult.totalXp, + qualityBonus: xpResult.qualityBonus, + multiplierBonus: xpResult.multiplierBonus, + multiplierPercent, + isCriticalHit: xpResult.isCriticalHit, + }, + levelUp: userLevelResult.levelsGained > 0, + categoryXp: { + currentXp: categoryLevelResult.remainingXp, + xpToNext: categoryLevelResult.newXpToNextLevel, + level: categoryLevelResult.newLevel, + levelUp: categoryLevelResult.levelsGained > 0, + }, + newTitle: titleChanged ? newTitle : undefined, + unlocks: unlockResult.unlocked, + streakFreezesGranted: unlockResult.streakFreezesGranted, + ...(debateLog && { debateLog }), + }); +}); diff --git a/src/app/api/cron/reflector/route.ts b/src/app/api/cron/reflector/route.ts new file mode 100644 index 0000000000000000000000000000000000000000..f0d31bbdf4f200b424af711063a36631fc13153b --- /dev/null +++ b/src/app/api/cron/reflector/route.ts @@ -0,0 +1,53 @@ +import { NextRequest, NextResponse } from "next/server"; +import { writeFile } from "fs/promises"; +import { join } from "path"; +import { runReflector } from "@/lib/judge/reflector"; + +const PROPOSALS_PATH = join( + process.cwd(), + "src/lib/judge/reflector-proposals.json", +); + +/** + * POST /api/cron/reflector + * + * Designed to be called by an external cron job every ~2 days. + * Runs the full reflector pipeline: + * 1. Detect judge/human score divergence via LangSmith + * 2. Analyze patterns and propose rubric changes via Claude + * 3. Store output to reflector-proposals.json + * + * Does NOT auto-apply changes — human approval is required via + * POST /api/judge/reflector. + * + * Expects a CRON_SECRET header for authentication. + */ +export async function POST(request: NextRequest) { + const secret = request.headers.get("x-cron-secret"); + if (!process.env.CRON_SECRET || secret !== process.env.CRON_SECRET) { + return NextResponse.json({ error: "Unauthorized" }, { status: 401 }); + } + + try { + const output = await runReflector(); + + await writeFile( + PROPOSALS_PATH, + JSON.stringify(output, null, 2) + "\n", + ); + + return NextResponse.json({ + success: true, + divergenceCases: output.divergenceCases.length, + proposedChanges: output.proposedChanges.length, + timestamp: output.timestamp, + }); + } catch (err) { + const message = err instanceof Error ? err.message : String(err); + console.error(`[cron/reflector] Failed: ${message}`); + return NextResponse.json( + { error: "Reflector run failed", details: message }, + { status: 500 }, + ); + } +} diff --git a/src/app/api/dashboard/__tests__/route.test.ts b/src/app/api/dashboard/__tests__/route.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..ce9d65224cf6d5c45a8f62cf2fb4942e0ebefac1 --- /dev/null +++ b/src/app/api/dashboard/__tests__/route.test.ts @@ -0,0 +1,459 @@ +/** + * Tests for GET /api/dashboard + * + * Covers: + * - 404 when no user found + * - response shape: user, todayLog, categorySkills, recentActivities, weeklyLogs + * - todayLog: null when no log for today + * - todayLog: populated when a today log exists + * - xpToNextLevel computed from xpForLevel(user.level + 1) + * - categorySkills mapped correctly from user.categorySkills + * - categorySkills include lastPlayedAt per-category (null when no activity) + * - recentActivities mapped correctly (last 10) + * - weeklyLogs mapped correctly (last 7) + */ + +import { describe, it, expect, vi, beforeEach } from "vitest"; +import { NextRequest } from "next/server"; + +// --------------------------------------------------------------------------- +// Mock prisma +// --------------------------------------------------------------------------- + +const mockUserFindFirst = vi.fn(); +const mockDailyLogFindFirst = vi.fn(); +const mockActivityFindMany = vi.fn(); +const mockActivityGroupBy = vi.fn(); +const mockDailyLogFindMany = vi.fn(); + +vi.mock("@/lib/db", () => ({ + prisma: { + user: { findFirst: (...args: unknown[]) => mockUserFindFirst(...args) }, + dailyLog: { + findFirst: (...args: unknown[]) => mockDailyLogFindFirst(...args), + findMany: (...args: unknown[]) => mockDailyLogFindMany(...args), + }, + activity: { + findMany: (...args: unknown[]) => mockActivityFindMany(...args), + groupBy: (...args: unknown[]) => mockActivityGroupBy(...args), + }, + }, +})); + +import { GET } from "../route"; + +// --------------------------------------------------------------------------- +// Fixtures +// --------------------------------------------------------------------------- + +const baseUser = { + id: 1, + name: "Player One", + level: 5, + totalXp: 1250, + currentXp: 250, + title: "Apprentice", + dailyGoalXp: 100, + streak: 3, + longestStreak: 7, + streakFreezes: 1, + categorySkills: [ + { category: "CHESS", level: 2, totalXp: 300, currentXp: 50, xpToNext: 150 }, + { category: "FEYNMAN", level: 1, totalXp: 100, currentXp: 100, xpToNext: 100 }, + ], +}; + +const baseDailyLog = { + xpEarned: 80, + activityCount: 3, + goalMet: false, +}; + +const baseActivities = [ + { + id: 10, + category: "CHESS", + exerciseType: "chess-puzzle", + description: "Solved a puzzle", + totalXp: 40, + isCriticalHit: false, + createdAt: new Date("2026-03-24T10:00:00Z"), + }, + { + id: 9, + category: "FEYNMAN", + exerciseType: "explain", + description: "Explained quantum entanglement", + totalXp: 30, + isCriticalHit: true, + createdAt: new Date("2026-03-24T09:00:00Z"), + }, +]; + +const baseWeeklyLogs = [ + { date: new Date("2026-03-24T00:00:00Z"), xpEarned: 80, activityCount: 3, goalMet: false }, + { date: new Date("2026-03-23T00:00:00Z"), xpEarned: 120, activityCount: 5, goalMet: true }, +]; + +/** Default groupBy result: chess played 2026-03-24, feynman played 2026-03-22 */ +const baseGroupByRows = [ + { category: "chess", _max: { createdAt: new Date("2026-03-24T10:00:00Z") } }, + { category: "feynman", _max: { createdAt: new Date("2026-03-22T08:00:00Z") } }, +]; + +function makeGet(): NextRequest { + return new NextRequest("http://localhost/api/dashboard"); +} + +async function json(res: Response): Promise { + return res.json(); +} + +// --------------------------------------------------------------------------- +// Tests +// --------------------------------------------------------------------------- + +describe("GET /api/dashboard", () => { + beforeEach(() => { + vi.clearAllMocks(); + mockActivityFindMany.mockResolvedValue(baseActivities); + mockActivityGroupBy.mockResolvedValue(baseGroupByRows); + mockDailyLogFindMany.mockResolvedValue(baseWeeklyLogs); + mockDailyLogFindFirst.mockResolvedValue(null); + }); + + it("returns 404 when no user found", async () => { + mockUserFindFirst.mockResolvedValue(null); + const res = await GET(makeGet()); + expect(res.status).toBe(404); + const body = await json(res) as Record; + expect(body.error).toBeDefined(); + }); + + it("returns 200 with full response shape when user exists", async () => { + mockUserFindFirst.mockResolvedValue(baseUser); + mockDailyLogFindFirst.mockResolvedValue(baseDailyLog); + + const res = await GET(makeGet()); + expect(res.status).toBe(200); + + const body = await json(res) as Record; + expect(body).toHaveProperty("user"); + expect(body).toHaveProperty("todayLog"); + expect(body).toHaveProperty("categorySkills"); + expect(body).toHaveProperty("recentActivities"); + expect(body).toHaveProperty("weeklyLogs"); + }); + + it("returns todayLog as null when no log exists for today", async () => { + mockUserFindFirst.mockResolvedValue(baseUser); + mockDailyLogFindFirst.mockResolvedValue(null); + + const res = await GET(makeGet()); + const body = await json(res) as Record; + expect(body.todayLog).toBeNull(); + }); + + it("returns todayLog with xpEarned, activityCount, goalMet when log exists", async () => { + mockUserFindFirst.mockResolvedValue(baseUser); + mockDailyLogFindFirst.mockResolvedValue(baseDailyLog); + + const res = await GET(makeGet()); + const body = await json(res) as Record; + const log = body.todayLog as Record; + expect(log.xpEarned).toBe(80); + expect(log.activityCount).toBe(3); + expect(log.goalMet).toBe(false); + }); + + it("returns user fields including level and streak", async () => { + mockUserFindFirst.mockResolvedValue(baseUser); + + const res = await GET(makeGet()); + const body = await json(res) as Record; + const user = body.user as Record; + + expect(user.id).toBe(1); + expect(user.name).toBe("Player One"); + expect(user.level).toBe(5); + expect(user.totalXp).toBe(1250); + expect(user.currentXp).toBe(250); + expect(user.streak).toBe(3); + expect(user.longestStreak).toBe(7); + expect(user.streakFreezes).toBe(1); + expect(user.dailyGoalXp).toBe(100); + expect(user.title).toBe("Apprentice"); + }); + + it("computes xpToNextLevel via xpForLevel(level + 1)", async () => { + mockUserFindFirst.mockResolvedValue(baseUser); + + const res = await GET(makeGet()); + const body = await json(res) as Record; + const user = body.user as Record; + + // xpForLevel(6) — just verify it's a positive number + expect(typeof user.xpToNextLevel).toBe("number"); + expect(user.xpToNextLevel as number).toBeGreaterThan(0); + }); + + it("maps categorySkills correctly (core fields)", async () => { + mockUserFindFirst.mockResolvedValue(baseUser); + + const res = await GET(makeGet()); + const body = await json(res) as Record; + const skills = body.categorySkills as Array>; + + expect(skills).toHaveLength(2); + expect(skills[0]).toMatchObject({ + category: "CHESS", + level: 2, + totalXp: 300, + currentXp: 50, + xpToNext: 150, + }); + expect(skills[1]).toMatchObject({ + category: "FEYNMAN", + level: 1, + }); + }); + + it("maps recentActivities with all required fields", async () => { + mockUserFindFirst.mockResolvedValue(baseUser); + + const res = await GET(makeGet()); + const body = await json(res) as Record; + const activities = body.recentActivities as Array>; + + expect(activities).toHaveLength(2); + expect(activities[0]).toMatchObject({ + id: 10, + category: "CHESS", + exerciseType: "chess-puzzle", + description: "Solved a puzzle", + totalXp: 40, + isCriticalHit: false, + }); + expect(activities[0]).toHaveProperty("createdAt"); + }); + + it("maps weeklyLogs correctly", async () => { + mockUserFindFirst.mockResolvedValue(baseUser); + + const res = await GET(makeGet()); + const body = await json(res) as Record; + const logs = body.weeklyLogs as Array>; + + expect(logs).toHaveLength(2); + expect(logs[0]).toMatchObject({ + xpEarned: 80, + activityCount: 3, + goalMet: false, + }); + expect(logs[1]).toMatchObject({ + xpEarned: 120, + activityCount: 5, + goalMet: true, + }); + }); + + it("queries daily log with today UTC boundaries", async () => { + mockUserFindFirst.mockResolvedValue(baseUser); + mockDailyLogFindFirst.mockResolvedValue(null); + + await GET(makeGet()); + + expect(mockDailyLogFindFirst).toHaveBeenCalledWith( + expect.objectContaining({ + where: expect.objectContaining({ + userId: 1, + date: expect.objectContaining({ + gte: expect.any(Date), + lt: expect.any(Date), + }), + }), + }), + ); + }); + + it("queries activities with take: 10 ordered desc", async () => { + mockUserFindFirst.mockResolvedValue(baseUser); + + await GET(makeGet()); + + expect(mockActivityFindMany).toHaveBeenCalledWith( + expect.objectContaining({ + where: { userId: 1 }, + orderBy: { createdAt: "desc" }, + take: 10, + }), + ); + }); + + it("queries weekly logs with take: 7 ordered desc", async () => { + mockUserFindFirst.mockResolvedValue(baseUser); + + await GET(makeGet()); + + expect(mockDailyLogFindMany).toHaveBeenCalledWith( + expect.objectContaining({ + where: { userId: 1 }, + orderBy: { date: "desc" }, + take: 7, + }), + ); + }); + + it("handles empty categorySkills array", async () => { + mockUserFindFirst.mockResolvedValue({ ...baseUser, categorySkills: [] }); + + const res = await GET(makeGet()); + const body = await json(res) as Record; + expect(body.categorySkills).toEqual([]); + }); + + it("handles empty activities array", async () => { + mockUserFindFirst.mockResolvedValue(baseUser); + mockActivityFindMany.mockResolvedValue([]); + + const res = await GET(makeGet()); + const body = await json(res) as Record; + expect(body.recentActivities).toEqual([]); + }); + + it("handles empty weeklyLogs array", async () => { + mockUserFindFirst.mockResolvedValue(baseUser); + mockDailyLogFindMany.mockResolvedValue([]); + + const res = await GET(makeGet()); + const body = await json(res) as Record; + expect(body.weeklyLogs).toEqual([]); + }); + + it("propagates DB errors as 500", async () => { + mockUserFindFirst.mockRejectedValue(new Error("DB connection failed")); + + const res = await GET(makeGet()); + expect(res.status).toBe(500); + }); + + // ── lastPlayedAt ─────────────────────────────────────────────────────────── + + describe("lastPlayedAt per category", () => { + it("categorySkills include a lastPlayedAt field", async () => { + mockUserFindFirst.mockResolvedValue(baseUser); + const res = await GET(makeGet()); + const body = await json(res) as Record; + const skills = body.categorySkills as Array>; + expect(skills[0]).toHaveProperty("lastPlayedAt"); + expect(skills[1]).toHaveProperty("lastPlayedAt"); + }); + + it("lastPlayedAt is an ISO string when activity exists for that category", async () => { + mockUserFindFirst.mockResolvedValue(baseUser); + const playedAt = new Date("2026-03-24T10:00:00Z"); + mockActivityGroupBy.mockResolvedValue([ + { category: "chess", _max: { createdAt: playedAt } }, + ]); + + const res = await GET(makeGet()); + const body = await json(res) as Record; + const skills = body.categorySkills as Array>; + + const chess = skills.find((s) => s.category === "CHESS"); + expect(chess?.lastPlayedAt).toBe(playedAt.toISOString()); + }); + + it("lastPlayedAt is null when no activity exists for a category", async () => { + mockUserFindFirst.mockResolvedValue(baseUser); + // groupBy returns nothing for feynman — feynman has never been played + mockActivityGroupBy.mockResolvedValue([ + { category: "chess", _max: { createdAt: new Date("2026-03-24T10:00:00Z") } }, + ]); + + const res = await GET(makeGet()); + const body = await json(res) as Record; + const skills = body.categorySkills as Array>; + + const feynman = skills.find((s) => s.category === "FEYNMAN"); + expect(feynman?.lastPlayedAt).toBeNull(); + }); + + it("lastPlayedAt is null when groupBy returns _max.createdAt = null", async () => { + mockUserFindFirst.mockResolvedValue(baseUser); + mockActivityGroupBy.mockResolvedValue([ + { category: "chess", _max: { createdAt: null } }, + ]); + + const res = await GET(makeGet()); + const body = await json(res) as Record; + const skills = body.categorySkills as Array>; + + const chess = skills.find((s) => s.category === "CHESS"); + expect(chess?.lastPlayedAt).toBeNull(); + }); + + it("lastPlayedAt matching is case-insensitive (category stored as uppercase in DB)", async () => { + mockUserFindFirst.mockResolvedValue(baseUser); + // DB stores category as "CHESS" but groupBy returns lowercase "chess" + const playedAt = new Date("2026-03-25T12:00:00Z"); + mockActivityGroupBy.mockResolvedValue([ + { category: "chess", _max: { createdAt: playedAt } }, + { category: "feynman", _max: { createdAt: new Date("2026-03-23T09:00:00Z") } }, + ]); + + const res = await GET(makeGet()); + const body = await json(res) as Record; + const skills = body.categorySkills as Array>; + + const chess = skills.find((s) => s.category === "CHESS"); + expect(chess?.lastPlayedAt).toBe(playedAt.toISOString()); + }); + + it("all categories get lastPlayedAt when groupBy has an entry for each", async () => { + mockUserFindFirst.mockResolvedValue(baseUser); + const d1 = new Date("2026-03-26T10:00:00Z"); + const d2 = new Date("2026-03-25T11:00:00Z"); + mockActivityGroupBy.mockResolvedValue([ + { category: "chess", _max: { createdAt: d1 } }, + { category: "feynman", _max: { createdAt: d2 } }, + ]); + + const res = await GET(makeGet()); + const body = await json(res) as Record; + const skills = body.categorySkills as Array>; + + const chess = skills.find((s) => s.category === "CHESS"); + const feynman = skills.find((s) => s.category === "FEYNMAN"); + expect(chess?.lastPlayedAt).toBe(d1.toISOString()); + expect(feynman?.lastPlayedAt).toBe(d2.toISOString()); + }); + + it("when groupBy returns empty array, all categories have lastPlayedAt = null", async () => { + mockUserFindFirst.mockResolvedValue(baseUser); + mockActivityGroupBy.mockResolvedValue([]); + + const res = await GET(makeGet()); + const body = await json(res) as Record; + const skills = body.categorySkills as Array>; + + for (const skill of skills) { + expect(skill.lastPlayedAt).toBeNull(); + } + }); + + it("calls activity.groupBy with userId: 1 and _max createdAt", async () => { + mockUserFindFirst.mockResolvedValue(baseUser); + + await GET(makeGet()); + + expect(mockActivityGroupBy).toHaveBeenCalledWith( + expect.objectContaining({ + by: ["category"], + where: { userId: 1 }, + _max: { createdAt: true }, + }), + ); + }); + }); +}); diff --git a/src/app/api/dashboard/route.ts b/src/app/api/dashboard/route.ts new file mode 100644 index 0000000000000000000000000000000000000000..d55147e349179281d6f592fe1d5bca0c3d9b3ec7 --- /dev/null +++ b/src/app/api/dashboard/route.ts @@ -0,0 +1,102 @@ +import { NextResponse } from "next/server"; +import { prisma } from "@/lib/db"; +import { xpForLevel } from "@/config/xp"; +import { withApiError } from "@/lib/api-error"; + +export const GET = withApiError(async () => { + const user = await prisma.user.findFirst({ + where: { id: 1 }, + include: { categorySkills: true }, + }); + + if (!user) { + return NextResponse.json({ error: "No user found", status: 404 }, { status: 404 }); + } + + // Today's UTC midnight boundaries + const now = new Date(); + const todayStart = new Date( + Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate()) + ); + const tomorrowStart = new Date(todayStart.getTime() + 86_400_000); + + const [todayLog, recentActivities, weeklyLogs, lastPlayedRows] = await Promise.all([ + prisma.dailyLog.findFirst({ + where: { + userId: 1, + date: { gte: todayStart, lt: tomorrowStart }, + }, + }), + prisma.activity.findMany({ + where: { userId: 1 }, + orderBy: { createdAt: "desc" }, + take: 10, + }), + prisma.dailyLog.findMany({ + where: { userId: 1 }, + orderBy: { date: "desc" }, + take: 7, + }), + // One query: latest activity per category for user 1 + prisma.activity.groupBy({ + by: ["category"], + where: { userId: 1 }, + _max: { createdAt: true }, + }), + ]); + + // Build a lookup map: category (lowercase) → last createdAt + const lastPlayedMap = new Map( + (lastPlayedRows as Array<{ category: string; _max: { createdAt: Date | null } }>).map( + (row) => [row.category.toLowerCase(), row._max.createdAt] + ) + ); + + return NextResponse.json({ + user: { + id: user.id, + name: user.name, + level: user.level, + totalXp: user.totalXp, + currentXp: user.currentXp, + xpToNextLevel: xpForLevel(user.level + 1), + title: user.title, + dailyGoalXp: user.dailyGoalXp, + streak: user.streak, + longestStreak: user.longestStreak, + streakFreezes: user.streakFreezes, + }, + todayLog: todayLog + ? { + xpEarned: todayLog.xpEarned, + activityCount: todayLog.activityCount, + goalMet: todayLog.goalMet, + } + : null, + categorySkills: user.categorySkills.map((cs: { category: string; level: number; totalXp: number; currentXp: number; xpToNext: number }) => ({ + category: cs.category, + level: cs.level, + totalXp: cs.totalXp, + currentXp: cs.currentXp, + xpToNext: cs.xpToNext, + lastPlayedAt: (lastPlayedMap.get(cs.category.toLowerCase()) ?? null)?.toISOString() ?? null, + })), + recentActivities: recentActivities.map((a: { id: number; category: string; exerciseType: string; description: string; totalXp: number; isCriticalHit: boolean; createdAt: Date }) => ({ + id: a.id, + category: a.category, + exerciseType: a.exerciseType, + description: a.description, + totalXp: a.totalXp, + isCriticalHit: a.isCriticalHit, + createdAt: a.createdAt, + })), + weeklyLogs: weeklyLogs.map((l: { date: Date; xpEarned: number; activityCount: number; goalMet: boolean }) => ({ + date: l.date, + xpEarned: l.xpEarned, + activityCount: l.activityCount, + goalMet: l.goalMet, + })), + }); +}); + + diff --git a/src/app/api/debate/__tests__/feedback.test.ts b/src/app/api/debate/__tests__/feedback.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..1825ed521cdbc4cfce222a3c179cbd9793b14200 --- /dev/null +++ b/src/app/api/debate/__tests__/feedback.test.ts @@ -0,0 +1,315 @@ +/** + * Tests for POST /api/debate/feedback + * + * Covers: + * - 200 with skipped message when LANGSMITH_API_KEY is not configured + * - 400 for invalid JSON body + * - 400 for missing runId + * - 400 for non-string runId + * - 400 for missing scores + * - 400 for scores that is not an object + * - 400 when no valid dimension IDs or scores in [0,10] remain after filtering + * - 200 with submitted count for valid request + * - unknown dimension IDs are silently filtered out + * - scores outside [0, 10] are silently filtered out + * - non-numeric score values are silently filtered out + * - partial scores (subset of all dimensions) are accepted + * - submitAllHumanFeedback is called with the clean scores and runId + * - 500 on unexpected submitAllHumanFeedback error + */ + +import { describe, it, expect, vi, beforeEach } from "vitest"; +import { NextRequest } from "next/server"; + +// --------------------------------------------------------------------------- +// Mock LangSmith +// --------------------------------------------------------------------------- + +const mockSubmitAllHumanFeedback = vi.fn(); + +vi.mock("@/lib/langsmith", () => ({ + submitAllHumanFeedback: (...args: unknown[]) => + mockSubmitAllHumanFeedback(...args), +})); + +// --------------------------------------------------------------------------- +// Import route AFTER mocks +// --------------------------------------------------------------------------- + +import { POST } from "../feedback/route"; + +// --------------------------------------------------------------------------- +// Helpers +// --------------------------------------------------------------------------- + +function makeRequest(body: unknown): NextRequest { + return new NextRequest("http://localhost/api/debate/feedback", { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify(body), + }); +} + +const VALID_RUN_ID = "550e8400-e29b-41d4-a716-446655440000"; +const VALID_SCORES = { + "argument-structure": 7, + persuasiveness: 6, + "flaw-detection": 8, +}; + +// --------------------------------------------------------------------------- +// Tests +// --------------------------------------------------------------------------- + +describe("POST /api/debate/feedback — LANGSMITH_API_KEY not set", () => { + beforeEach(() => { + delete process.env.LANGSMITH_API_KEY; + mockSubmitAllHumanFeedback.mockReset(); + }); + + it("returns 200 with submitted=0 and skipped message when no API key", async () => { + const req = makeRequest({ runId: VALID_RUN_ID, scores: VALID_SCORES }); + const res = await POST(req); + expect(res.status).toBe(200); + const body = await res.json(); + expect(body.submitted).toBe(0); + expect(typeof body.skipped).toBe("string"); + expect(body.skipped).toContain("LANGSMITH_API_KEY"); + }); + + it("does not call submitAllHumanFeedback when no API key", async () => { + const req = makeRequest({ runId: VALID_RUN_ID, scores: VALID_SCORES }); + await POST(req); + expect(mockSubmitAllHumanFeedback).not.toHaveBeenCalled(); + }); +}); + +describe("POST /api/debate/feedback — validation", () => { + beforeEach(() => { + process.env.LANGSMITH_API_KEY = "test-key"; + mockSubmitAllHumanFeedback.mockResolvedValue(undefined); + }); + + it("returns 400 for invalid JSON body", async () => { + const req = new NextRequest("http://localhost/api/debate/feedback", { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: "not-json{", + }); + const res = await POST(req); + expect(res.status).toBe(400); + }); + + it("returns 400 when runId is missing", async () => { + const req = makeRequest({ scores: VALID_SCORES }); + const res = await POST(req); + expect(res.status).toBe(400); + const body = await res.json(); + expect(body.error).toContain("runId"); + }); + + it("returns 400 when runId is not a string", async () => { + const req = makeRequest({ runId: 12345, scores: VALID_SCORES }); + const res = await POST(req); + expect(res.status).toBe(400); + const body = await res.json(); + expect(body.error).toContain("runId"); + }); + + it("returns 400 when scores is missing", async () => { + const req = makeRequest({ runId: VALID_RUN_ID }); + const res = await POST(req); + expect(res.status).toBe(400); + const body = await res.json(); + expect(body.error).toContain("scores"); + }); + + it("returns 400 when scores is an array", async () => { + const req = makeRequest({ runId: VALID_RUN_ID, scores: [7, 8, 9] }); + const res = await POST(req); + expect(res.status).toBe(400); + const body = await res.json(); + expect(body.error).toContain("scores"); + }); + + it("returns 400 when scores is a string", async () => { + const req = makeRequest({ runId: VALID_RUN_ID, scores: "7/10" }); + const res = await POST(req); + expect(res.status).toBe(400); + const body = await res.json(); + expect(body.error).toContain("scores"); + }); + + it("returns 400 when all scores are for unknown dimension IDs", async () => { + const req = makeRequest({ + runId: VALID_RUN_ID, + scores: { "made-up-dimension": 7, "another-fake": 5 }, + }); + const res = await POST(req); + expect(res.status).toBe(400); + const body = await res.json(); + expect(body.error).toContain("No valid scores"); + }); + + it("returns 400 when all scores are out of range [0, 10]", async () => { + const req = makeRequest({ + runId: VALID_RUN_ID, + scores: { "argument-structure": 11, persuasiveness: -1 }, + }); + const res = await POST(req); + expect(res.status).toBe(400); + const body = await res.json(); + expect(body.error).toContain("No valid scores"); + }); + + it("returns 400 when all scores are non-numeric", async () => { + const req = makeRequest({ + runId: VALID_RUN_ID, + scores: { "argument-structure": "great", persuasiveness: true }, + }); + const res = await POST(req); + expect(res.status).toBe(400); + const body = await res.json(); + expect(body.error).toContain("No valid scores"); + }); +}); + +describe("POST /api/debate/feedback — success", () => { + beforeEach(() => { + process.env.LANGSMITH_API_KEY = "test-key"; + mockSubmitAllHumanFeedback.mockResolvedValue(undefined); + }); + + it("returns 200 with correct submitted count", async () => { + const req = makeRequest({ runId: VALID_RUN_ID, scores: VALID_SCORES }); + const res = await POST(req); + expect(res.status).toBe(200); + const body = await res.json(); + expect(body.submitted).toBe(Object.keys(VALID_SCORES).length); + }); + + it("calls submitAllHumanFeedback with correct runId and clean scores", async () => { + const req = makeRequest({ runId: VALID_RUN_ID, scores: VALID_SCORES }); + await POST(req); + expect(mockSubmitAllHumanFeedback).toHaveBeenCalledWith( + VALID_RUN_ID, + VALID_SCORES, + ); + }); + + it("accepts a partial subset of dimension IDs", async () => { + const partial = { "argument-structure": 9 }; + const req = makeRequest({ runId: VALID_RUN_ID, scores: partial }); + const res = await POST(req); + expect(res.status).toBe(200); + const body = await res.json(); + expect(body.submitted).toBe(1); + expect(mockSubmitAllHumanFeedback).toHaveBeenCalledWith(VALID_RUN_ID, partial); + }); + + it("accepts score of exactly 0 (lower bound)", async () => { + const req = makeRequest({ + runId: VALID_RUN_ID, + scores: { "argument-structure": 0 }, + }); + const res = await POST(req); + expect(res.status).toBe(200); + expect(mockSubmitAllHumanFeedback).toHaveBeenCalledWith(VALID_RUN_ID, { + "argument-structure": 0, + }); + }); + + it("accepts score of exactly 10 (upper bound)", async () => { + const req = makeRequest({ + runId: VALID_RUN_ID, + scores: { persuasiveness: 10 }, + }); + const res = await POST(req); + expect(res.status).toBe(200); + expect(mockSubmitAllHumanFeedback).toHaveBeenCalledWith(VALID_RUN_ID, { + persuasiveness: 10, + }); + }); + + it("silently filters out unknown dimension IDs, submits valid ones", async () => { + const mixed = { + "argument-structure": 7, + "made-up-dimension": 5, + }; + const req = makeRequest({ runId: VALID_RUN_ID, scores: mixed }); + const res = await POST(req); + expect(res.status).toBe(200); + const body = await res.json(); + expect(body.submitted).toBe(1); + // Only the valid dimension was forwarded + expect(mockSubmitAllHumanFeedback).toHaveBeenCalledWith(VALID_RUN_ID, { + "argument-structure": 7, + }); + }); + + it("silently filters out out-of-range scores, submits valid ones", async () => { + const mixed = { + "argument-structure": 7, + persuasiveness: 11, // over max + "flaw-detection": -1, // below min + }; + const req = makeRequest({ runId: VALID_RUN_ID, scores: mixed }); + const res = await POST(req); + expect(res.status).toBe(200); + const body = await res.json(); + expect(body.submitted).toBe(1); + expect(mockSubmitAllHumanFeedback).toHaveBeenCalledWith(VALID_RUN_ID, { + "argument-structure": 7, + }); + }); + + it("silently filters non-numeric score values", async () => { + const mixed = { + "argument-structure": 8, + persuasiveness: "high", // non-numeric, filtered + }; + const req = makeRequest({ runId: VALID_RUN_ID, scores: mixed }); + const res = await POST(req); + expect(res.status).toBe(200); + const body = await res.json(); + expect(body.submitted).toBe(1); + expect(mockSubmitAllHumanFeedback).toHaveBeenCalledWith(VALID_RUN_ID, { + "argument-structure": 8, + }); + }); + + it("accepts all 8 scoring dimensions at once", async () => { + const allDimScores = { + "flaw-detection": 7, + "steelman-awareness": 6, + "devils-advocate-depth": 5, + "argument-structure": 8, + persuasiveness: 9, + "evidence-accuracy": 7, + "rebuttal-quality": 6, + "intellectual-honesty": 8, + }; + const req = makeRequest({ runId: VALID_RUN_ID, scores: allDimScores }); + const res = await POST(req); + expect(res.status).toBe(200); + const body = await res.json(); + expect(body.submitted).toBe(8); + expect(mockSubmitAllHumanFeedback).toHaveBeenCalledWith( + VALID_RUN_ID, + allDimScores, + ); + }); +}); + +describe("POST /api/debate/feedback — error handling", () => { + beforeEach(() => { + process.env.LANGSMITH_API_KEY = "test-key"; + }); + + it("returns 500 when submitAllHumanFeedback throws", async () => { + mockSubmitAllHumanFeedback.mockRejectedValue(new Error("LangSmith unavailable")); + const req = makeRequest({ runId: VALID_RUN_ID, scores: VALID_SCORES }); + const res = await POST(req); + expect(res.status).toBe(500); + }); +}); diff --git a/src/app/api/debate/__tests__/routes.test.ts b/src/app/api/debate/__tests__/routes.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..56a875a9ccbe8fa2049a7c7bf432e2db2a9edac8 --- /dev/null +++ b/src/app/api/debate/__tests__/routes.test.ts @@ -0,0 +1,1120 @@ +/** + * Tests for Debate Arena API route handlers. + * + * Covers: + * POST /api/debate/start + * - resolves topic by topicId, customTopic, random, category filter + * - resolves opponent by opponentId, difficulty, default + * - rounds validation (1, 3, 5, default 3, invalid → 3) + * - userSide validation (pro, con, default pro) + * - 404 for invalid topicId / opponentId + * - 400 for invalid JSON + * - does NOT return opponent systemPrompt + * - response shape + * + * POST /api/debate/respond + * - API key guard (503) + * - input validation: missing topic, opponentId, short userArgument + * - 404 for invalid opponentId + * - Claude integration: system prompt contains opponent persona, topic, side + * - haiku model used + * - response shape (round, opponentName, opponentArgument) + * - history context included in prompt + * - error handling + * + * POST /api/debate/judge + * - API key guard (503) + * - input validation: missing topic, userArgument, opponentArgument, opponentName + * - response shape (RoundJudgement) + * - dimension scores normalised 0–10 + * - haiku model used + * - previousRounds context + * - error handling + * + * POST /api/debate/summary + * - API key guard (503) + * - input validation: missing topic, opponentName, empty rounds + * - response shape (judgement, xp, levelUp, categoryXp, unlocks) + * - XP scaled by round count + * - difficulty weight applied to quality + * - winner determined from rounds + * - DB persistence (activity, user, categorySkill, dailyLog) + * - durationSecs handling + * - user not found → 404 + */ + +import { describe, it, expect, vi, beforeEach, afterEach } from "vitest"; +import { NextRequest } from "next/server"; + +// --------------------------------------------------------------------------- +// Mock Prisma +// --------------------------------------------------------------------------- + +const mockUserFindFirst = vi.fn(); +const mockDailyLogFindFirst = vi.fn(); +const mockTransaction = vi.fn(); + +vi.mock("@/lib/db", () => ({ + prisma: { + user: { findFirst: (...args: unknown[]) => mockUserFindFirst(...args) }, + dailyLog: { findFirst: (...args: unknown[]) => mockDailyLogFindFirst(...args) }, + $transaction: (...args: unknown[]) => mockTransaction(...args), + }, +})); + +// --------------------------------------------------------------------------- +// Mock Claude +// --------------------------------------------------------------------------- + +const mockClaudeCreate = vi.fn(); + +vi.mock("@/lib/claude", () => ({ + claude: { + messages: { create: (...args: unknown[]) => mockClaudeCreate(...args) }, + }, + parseClaudeJson: (text: string) => + JSON.parse( + text.trim().replace(/^```(?:json)?\s*/i, "").replace(/\s*```\s*$/, "").trim(), + ), +})); + +// --------------------------------------------------------------------------- +// Mock rollCriticalHit +// --------------------------------------------------------------------------- + +const mockRollCriticalHit = vi.fn(() => false); + +vi.mock("@/lib/xp", async (importOriginal) => { + const actual = await importOriginal(); + return { + ...actual, + rollCriticalHit: () => mockRollCriticalHit(), + }; +}); + +// --------------------------------------------------------------------------- +// Mock getMultiplierPercent +// --------------------------------------------------------------------------- + +const mockGetMultiplierPercent = vi.fn(() => Promise.resolve(0)); + +vi.mock("@/lib/multiplier", () => ({ + getMultiplierPercent: (...args: unknown[]) => (mockGetMultiplierPercent as (...a: unknown[]) => unknown)(...args), +})); + +// --------------------------------------------------------------------------- +// Mock processSkillUnlocks +// --------------------------------------------------------------------------- + +const mockProcessSkillUnlocks = vi.fn((): Promise<{ unlocked: string[]; streakFreezesGranted: number }> => + Promise.resolve({ unlocked: [], streakFreezesGranted: 0 }), +); + +vi.mock("@/lib/skill-unlock", () => ({ + processSkillUnlocks: (...args: unknown[]) => (mockProcessSkillUnlocks as (...a: unknown[]) => unknown)(...args), +})); + +// --------------------------------------------------------------------------- +// Mock streak +// --------------------------------------------------------------------------- + +vi.mock("@/lib/streak", () => ({ + processEndOfDay: vi.fn(() => Promise.resolve()), +})); + +// --------------------------------------------------------------------------- +// Helpers +// --------------------------------------------------------------------------- + +function makeRequest(url: string, body?: unknown): NextRequest { + return new NextRequest(new URL(url, "http://localhost:3000"), { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: body !== undefined ? JSON.stringify(body) : undefined, + }); +} + +function makeBaseUser() { + return { + id: 1, + level: 5, + totalXp: 1000, + currentXp: 50, + xpToNextLevel: 200, + dailyGoalXp: 100, + streakDays: 3, + title: "Apprentice", + categorySkills: [ + { + id: 10, + category: "critical-thinking", + level: 3, + totalXp: 400, + currentXp: 30, + xpToNext: 150, + }, + ], + }; +} + +function makeRoundJudgement(round: number, userOverall: number, opponentOverall: number) { + const dims: Record = {}; + for (const id of [ + "flaw-detection", "steelman-awareness", "devils-advocate-depth", + "argument-structure", "persuasiveness", "evidence-accuracy", + "rebuttal-quality", "intellectual-honesty", + ]) { + dims[id] = userOverall; + } + const oppDims: Record = {}; + for (const id of [ + "flaw-detection", "steelman-awareness", "devils-advocate-depth", + "argument-structure", "persuasiveness", "evidence-accuracy", + "rebuttal-quality", "intellectual-honesty", + ]) { + oppDims[id] = opponentOverall; + } + return { + round, + user: { dimensionScores: dims, overallScore: userOverall, analysis: "Good." }, + opponent: { dimensionScores: oppDims, overallScore: opponentOverall, analysis: "Also good." }, + roundWinner: userOverall > opponentOverall ? "user" as const : "opponent" as const, + roundSummary: "Round complete.", + }; +} + +// --------------------------------------------------------------------------- +// Import routes after mocks +// --------------------------------------------------------------------------- + +const { POST: startHandler } = await import("../start/route"); +const { POST: respondHandler } = await import("../respond/route"); +const { POST: judgeHandler } = await import("../judge/route"); +const { POST: summaryHandler } = await import("../summary/route"); + +// =================================================================== +// POST /api/debate/start +// =================================================================== + +describe("POST /api/debate/start", () => { + beforeEach(() => { + vi.clearAllMocks(); + }); + + it("returns a debate session with a random topic and medium opponent by default", async () => { + const res = await startHandler(makeRequest("/api/debate/start", {})); + const body = await res.json(); + + expect(res.status).toBe(200); + expect(body.topic).toBeDefined(); + expect(body.topic.id).toBeDefined(); + expect(body.topic.topic).toBeDefined(); + expect(body.opponent).toBeDefined(); + expect(body.opponent.difficulty).toBe("medium"); + expect(body.rounds).toBe(3); + expect(body.userSide).toBe("pro"); + }); + + it("resolves topic by topicId", async () => { + const res = await startHandler( + makeRequest("/api/debate/start", { topicId: "dt-phil-01" }), + ); + const body = await res.json(); + + expect(res.status).toBe(200); + expect(body.topic.id).toBe("dt-phil-01"); + expect(body.topic.topic).toBe("Free will is an illusion"); + }); + + it("returns 404 for invalid topicId", async () => { + const res = await startHandler( + makeRequest("/api/debate/start", { topicId: "nonexistent" }), + ); + expect(res.status).toBe(404); + }); + + it("uses customTopic when provided", async () => { + const res = await startHandler( + makeRequest("/api/debate/start", { customTopic: "Pineapple belongs on pizza" }), + ); + const body = await res.json(); + + expect(res.status).toBe(200); + expect(body.topic.id).toBe("custom"); + expect(body.topic.topic).toBe("Pineapple belongs on pizza"); + expect(body.topic.category).toBe("Custom"); + }); + + it("customTopic overrides topicId", async () => { + const res = await startHandler( + makeRequest("/api/debate/start", { + topicId: "dt-phil-01", + customTopic: "Cats are better than dogs", + }), + ); + const body = await res.json(); + expect(body.topic.id).toBe("custom"); + expect(body.topic.topic).toBe("Cats are better than dogs"); + }); + + it("ignores short customTopic (<5 chars) and falls back to topicId", async () => { + const res = await startHandler( + makeRequest("/api/debate/start", { + topicId: "dt-eth-01", + customTopic: "Hi", + }), + ); + const body = await res.json(); + expect(body.topic.id).toBe("dt-eth-01"); + }); + + it("filters random topic by category", async () => { + const res = await startHandler( + makeRequest("/api/debate/start", { category: "Philosophy" }), + ); + const body = await res.json(); + expect(body.topic.category).toBe("Philosophy"); + }); + + it("resolves opponent by opponentId", async () => { + const res = await startHandler( + makeRequest("/api/debate/start", { opponentId: "opp-hard-socrates" }), + ); + const body = await res.json(); + expect(body.opponent.id).toBe("opp-hard-socrates"); + expect(body.opponent.name).toBe("Socrates"); + }); + + it("returns 404 for invalid opponentId", async () => { + const res = await startHandler( + makeRequest("/api/debate/start", { opponentId: "fake-opp" }), + ); + expect(res.status).toBe(404); + }); + + it("selects opponent by difficulty", async () => { + const res = await startHandler( + makeRequest("/api/debate/start", { difficulty: "hard" }), + ); + const body = await res.json(); + expect(body.opponent.difficulty).toBe("hard"); + }); + + it("defaults difficulty to medium for invalid value", async () => { + const res = await startHandler( + makeRequest("/api/debate/start", { difficulty: "impossible" }), + ); + const body = await res.json(); + expect(body.opponent.difficulty).toBe("medium"); + }); + + it("accepts rounds 1, 3, 5", async () => { + for (const rounds of [1, 3, 5]) { + const res = await startHandler( + makeRequest("/api/debate/start", { rounds }), + ); + const body = await res.json(); + expect(body.rounds).toBe(rounds); + } + }); + + it("defaults to 3 rounds for invalid value", async () => { + const res = await startHandler( + makeRequest("/api/debate/start", { rounds: 7 }), + ); + const body = await res.json(); + expect(body.rounds).toBe(3); + }); + + it("respects userSide con", async () => { + const res = await startHandler( + makeRequest("/api/debate/start", { userSide: "con" }), + ); + const body = await res.json(); + expect(body.userSide).toBe("con"); + }); + + it("defaults userSide to pro", async () => { + const res = await startHandler( + makeRequest("/api/debate/start", { userSide: "banana" }), + ); + const body = await res.json(); + expect(body.userSide).toBe("pro"); + }); + + it("does NOT include systemPrompt in response", async () => { + const res = await startHandler( + makeRequest("/api/debate/start", { opponentId: "opp-hard-socrates" }), + ); + const body = await res.json(); + expect(body.opponent.systemPrompt).toBeUndefined(); + }); + + it("includes era for hard opponents", async () => { + const res = await startHandler( + makeRequest("/api/debate/start", { opponentId: "opp-hard-socrates" }), + ); + const body = await res.json(); + expect(body.opponent.era).toBe("470-399 BCE"); + }); + + it("returns null era for non-hard opponents", async () => { + const res = await startHandler( + makeRequest("/api/debate/start", { opponentId: "opp-easy-balanced" }), + ); + const body = await res.json(); + expect(body.opponent.era).toBeNull(); + }); + + it("returns 400 for invalid JSON", async () => { + const req = new NextRequest(new URL("/api/debate/start", "http://localhost:3000"), { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: "not json{", + }); + const res = await startHandler(req); + expect(res.status).toBe(400); + }); + + it("response shape matches expected fields", async () => { + const res = await startHandler(makeRequest("/api/debate/start", {})); + const body = await res.json(); + + expect(body).toHaveProperty("topic"); + expect(body).toHaveProperty("opponent"); + expect(body).toHaveProperty("rounds"); + expect(body).toHaveProperty("userSide"); + expect(body.topic).toHaveProperty("id"); + expect(body.topic).toHaveProperty("topic"); + expect(body.topic).toHaveProperty("category"); + expect(body.topic).toHaveProperty("description"); + expect(body.opponent).toHaveProperty("id"); + expect(body.opponent).toHaveProperty("name"); + expect(body.opponent).toHaveProperty("difficulty"); + expect(body.opponent).toHaveProperty("icon"); + }); +}); + +// =================================================================== +// POST /api/debate/respond +// =================================================================== + +describe("POST /api/debate/respond", () => { + const savedKey = process.env.ANTHROPIC_API_KEY; + + beforeEach(() => { + vi.clearAllMocks(); + process.env.ANTHROPIC_API_KEY = "test-key"; + }); + + afterEach(() => { + if (savedKey !== undefined) { + process.env.ANTHROPIC_API_KEY = savedKey; + } else { + delete process.env.ANTHROPIC_API_KEY; + } + }); + + it("returns 503 when ANTHROPIC_API_KEY is missing", async () => { + delete process.env.ANTHROPIC_API_KEY; + const res = await respondHandler( + makeRequest("/api/debate/respond", { + topic: "Test topic", + opponentId: "opp-easy-balanced", + userArgument: "This is my argument for testing.", + }), + ); + expect(res.status).toBe(503); + }); + + it("returns 400 for missing topic", async () => { + const res = await respondHandler( + makeRequest("/api/debate/respond", { + opponentId: "opp-easy-balanced", + userArgument: "This is my argument for testing.", + }), + ); + expect(res.status).toBe(400); + }); + + it("returns 400 for missing opponentId", async () => { + const res = await respondHandler( + makeRequest("/api/debate/respond", { + topic: "Test topic", + userArgument: "This is my argument for testing.", + }), + ); + expect(res.status).toBe(400); + }); + + it("returns 400 for short userArgument", async () => { + const res = await respondHandler( + makeRequest("/api/debate/respond", { + topic: "Test topic", + opponentId: "opp-easy-balanced", + userArgument: "Short", + }), + ); + expect(res.status).toBe(400); + }); + + it("returns 404 for invalid opponentId", async () => { + const res = await respondHandler( + makeRequest("/api/debate/respond", { + topic: "Test topic", + opponentId: "fake-opponent", + userArgument: "This is my argument for testing purposes.", + }), + ); + expect(res.status).toBe(404); + }); + + it("generates opponent response successfully", async () => { + mockClaudeCreate.mockResolvedValueOnce({ + content: [{ type: "text", text: "I disagree because of several important reasons." }], + }); + + const res = await respondHandler( + makeRequest("/api/debate/respond", { + topic: "Free will is an illusion", + opponentId: "opp-easy-balanced", + round: 1, + totalRounds: 3, + userSide: "pro", + userArgument: "Free will is clearly an illusion because determinism governs all physical processes.", + }), + ); + const body = await res.json(); + + expect(res.status).toBe(200); + expect(body.round).toBe(1); + expect(body.opponentName).toBe("The Balanced Debater"); + expect(body.opponentArgument).toBe("I disagree because of several important reasons."); + }); + + it("uses haiku model", async () => { + mockClaudeCreate.mockResolvedValueOnce({ + content: [{ type: "text", text: "A response." }], + }); + + await respondHandler( + makeRequest("/api/debate/respond", { + topic: "Test topic", + opponentId: "opp-easy-balanced", + userArgument: "This is my argument for testing purposes.", + }), + ); + + expect(mockClaudeCreate).toHaveBeenCalledWith( + expect.objectContaining({ model: "claude-haiku-4-5-20251001" }), + ); + }); + + it("includes opponent persona in system prompt", async () => { + mockClaudeCreate.mockResolvedValueOnce({ + content: [{ type: "text", text: "Response text." }], + }); + + await respondHandler( + makeRequest("/api/debate/respond", { + topic: "Test debate topic here", + opponentId: "opp-hard-socrates", + userArgument: "This is my argument for testing purposes.", + userSide: "pro", + }), + ); + + const callArgs = mockClaudeCreate.mock.calls[0][0]; + expect(callArgs.system).toContain("The Socratic Method"); + expect(callArgs.system).toContain("Test debate topic here"); + expect(callArgs.system).toContain("CON"); + expect(callArgs.system).toContain("Socrates"); + }); + + it("includes history context when provided", async () => { + mockClaudeCreate.mockResolvedValueOnce({ + content: [{ type: "text", text: "Round 2 response." }], + }); + + await respondHandler( + makeRequest("/api/debate/respond", { + topic: "Test topic", + opponentId: "opp-easy-balanced", + round: 2, + totalRounds: 3, + userSide: "pro", + userArgument: "My second round argument here for testing.", + history: [ + { + round: 1, + userArgument: "First round argument.", + opponentArgument: "First round response.", + }, + ], + }), + ); + + const callArgs = mockClaudeCreate.mock.calls[0][0]; + const userMessage = callArgs.messages[0].content; + expect(userMessage).toContain("PREVIOUS ROUNDS"); + expect(userMessage).toContain("First round argument"); + }); + + it("handles Claude error gracefully", async () => { + mockClaudeCreate.mockRejectedValueOnce(new Error("API failure")); + + const res = await respondHandler( + makeRequest("/api/debate/respond", { + topic: "Test topic", + opponentId: "opp-easy-balanced", + userArgument: "This is my argument for testing purposes.", + }), + ); + + expect(res.status).toBe(500); + const body = await res.json(); + expect(body.error).toContain("Failed to generate opponent response"); + }); + + it("returns 400 for invalid JSON", async () => { + const req = new NextRequest(new URL("/api/debate/respond", "http://localhost:3000"), { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: "{bad json", + }); + const res = await respondHandler(req); + expect(res.status).toBe(400); + }); +}); + +// =================================================================== +// POST /api/debate/judge +// =================================================================== + +describe("POST /api/debate/judge", () => { + const savedKey = process.env.ANTHROPIC_API_KEY; + + beforeEach(() => { + vi.clearAllMocks(); + process.env.ANTHROPIC_API_KEY = "test-key"; + }); + + afterEach(() => { + if (savedKey !== undefined) { + process.env.ANTHROPIC_API_KEY = savedKey; + } else { + delete process.env.ANTHROPIC_API_KEY; + } + }); + + const validJudgeBody = { + topic: "Free will is an illusion", + round: 1, + totalRounds: 3, + userArgument: "My argument about determinism and neuroscience.", + opponentArgument: "My rebuttal about libertarian free will.", + opponentName: "Socrates", + }; + + function mockJudgeResponse(userOverall = 7, oppOverall = 6) { + const dims: Record = {}; + const oppDims: Record = {}; + for (const id of [ + "flaw-detection", "steelman-awareness", "devils-advocate-depth", + "argument-structure", "persuasiveness", "evidence-accuracy", + "rebuttal-quality", "intellectual-honesty", + ]) { + dims[id] = userOverall; + oppDims[id] = oppOverall; + } + + mockClaudeCreate.mockResolvedValueOnce({ + content: [{ + type: "text", + text: JSON.stringify({ + user: { dimensionScores: dims, analysis: "User did well." }, + opponent: { dimensionScores: oppDims, analysis: "Opponent was decent." }, + roundWinner: "user", + roundSummary: "User won this round.", + }), + }], + }); + } + + it("returns 503 when ANTHROPIC_API_KEY is missing", async () => { + delete process.env.ANTHROPIC_API_KEY; + const res = await judgeHandler(makeRequest("/api/debate/judge", validJudgeBody)); + expect(res.status).toBe(503); + }); + + it("returns 400 for missing topic", async () => { + const res = await judgeHandler( + makeRequest("/api/debate/judge", { ...validJudgeBody, topic: undefined }), + ); + expect(res.status).toBe(400); + }); + + it("returns 400 for missing userArgument", async () => { + const res = await judgeHandler( + makeRequest("/api/debate/judge", { ...validJudgeBody, userArgument: undefined }), + ); + expect(res.status).toBe(400); + }); + + it("returns 400 for missing opponentArgument", async () => { + const res = await judgeHandler( + makeRequest("/api/debate/judge", { ...validJudgeBody, opponentArgument: undefined }), + ); + expect(res.status).toBe(400); + }); + + it("returns 400 for missing opponentName", async () => { + const res = await judgeHandler( + makeRequest("/api/debate/judge", { ...validJudgeBody, opponentName: undefined }), + ); + expect(res.status).toBe(400); + }); + + it("returns a RoundJudgement with correct shape", async () => { + mockJudgeResponse(7, 6); + + const res = await judgeHandler(makeRequest("/api/debate/judge", validJudgeBody)); + const body = await res.json(); + + expect(res.status).toBe(200); + expect(body.round).toBe(1); + expect(body.user).toBeDefined(); + expect(body.opponent).toBeDefined(); + expect(body.user.dimensionScores).toBeDefined(); + expect(body.user.overallScore).toBeTypeOf("number"); + expect(body.user.analysis).toBeTypeOf("string"); + expect(body.opponent.overallScore).toBeTypeOf("number"); + expect(body.roundWinner).toBeTypeOf("string"); + expect(body.roundSummary).toBeTypeOf("string"); + }); + + it("normalises dimension scores to 0–10", async () => { + const dims: Record = {}; + for (const id of [ + "flaw-detection", "steelman-awareness", "devils-advocate-depth", + "argument-structure", "persuasiveness", "evidence-accuracy", + "rebuttal-quality", "intellectual-honesty", + ]) { + dims[id] = 15; // above 10 + } + + mockClaudeCreate.mockResolvedValueOnce({ + content: [{ + type: "text", + text: JSON.stringify({ + user: { dimensionScores: dims, analysis: "Over scored." }, + opponent: { dimensionScores: dims, analysis: "Also over scored." }, + roundWinner: "tie", + roundSummary: "Tie.", + }), + }], + }); + + const res = await judgeHandler(makeRequest("/api/debate/judge", validJudgeBody)); + const body = await res.json(); + + // All dimensions should be clamped to 10 + for (const id of Object.keys(body.user.dimensionScores)) { + expect(body.user.dimensionScores[id]).toBeLessThanOrEqual(10); + } + }); + + it("defaults missing dimension scores to 5", async () => { + // Return only some dimensions + mockClaudeCreate.mockResolvedValueOnce({ + content: [{ + type: "text", + text: JSON.stringify({ + user: { dimensionScores: { "flaw-detection": 8 }, analysis: "Partial." }, + opponent: { dimensionScores: {}, analysis: "Empty." }, + roundWinner: "user", + roundSummary: "User had partial scores.", + }), + }], + }); + + const res = await judgeHandler(makeRequest("/api/debate/judge", validJudgeBody)); + const body = await res.json(); + + // Missing dimensions should default to 5 + expect(body.user.dimensionScores["flaw-detection"]).toBe(8); + expect(body.user.dimensionScores["persuasiveness"]).toBe(5); + expect(body.opponent.dimensionScores["flaw-detection"]).toBe(5); + }); + + it("uses haiku model", async () => { + mockJudgeResponse(); + + await judgeHandler(makeRequest("/api/debate/judge", validJudgeBody)); + + expect(mockClaudeCreate).toHaveBeenCalledWith( + expect.objectContaining({ model: "claude-haiku-4-5-20251001" }), + ); + }); + + it("uses server-computed overall scores and winner (not Claude's)", async () => { + // Claude says tie but scores clearly favour user + const userDims: Record = {}; + const oppDims: Record = {}; + for (const id of [ + "flaw-detection", "steelman-awareness", "devils-advocate-depth", + "argument-structure", "persuasiveness", "evidence-accuracy", + "rebuttal-quality", "intellectual-honesty", + ]) { + userDims[id] = 9; + oppDims[id] = 3; + } + + mockClaudeCreate.mockResolvedValueOnce({ + content: [{ + type: "text", + text: JSON.stringify({ + user: { dimensionScores: userDims, analysis: "Great." }, + opponent: { dimensionScores: oppDims, analysis: "Weak." }, + roundWinner: "tie", // Claude says tie — server should override + roundSummary: "Close round.", + }), + }], + }); + + const res = await judgeHandler(makeRequest("/api/debate/judge", validJudgeBody)); + const body = await res.json(); + + expect(body.user.overallScore).toBeGreaterThan(body.opponent.overallScore); + expect(body.roundWinner).toBe("user"); // Server overrides Claude's tie + }); + + it("handles Claude error gracefully", async () => { + mockClaudeCreate.mockRejectedValueOnce(new Error("API down")); + + const res = await judgeHandler(makeRequest("/api/debate/judge", validJudgeBody)); + expect(res.status).toBe(500); + const body = await res.json(); + expect(body.error).toContain("Failed to judge round"); + }); + + it("returns 400 for invalid JSON body", async () => { + const req = new NextRequest(new URL("/api/debate/judge", "http://localhost:3000"), { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: "bad{json", + }); + const res = await judgeHandler(req); + expect(res.status).toBe(400); + }); +}); + +// =================================================================== +// POST /api/debate/summary +// =================================================================== + +describe("POST /api/debate/summary", () => { + const savedKey = process.env.ANTHROPIC_API_KEY; + + beforeEach(() => { + vi.clearAllMocks(); + process.env.ANTHROPIC_API_KEY = "test-key"; + + mockUserFindFirst.mockResolvedValue(makeBaseUser()); + mockDailyLogFindFirst.mockResolvedValue(null); + mockTransaction.mockImplementation(async (fn: (tx: unknown) => Promise) => { + const tx = { + activity: { create: vi.fn() }, + user: { update: vi.fn() }, + categorySkill: { update: vi.fn() }, + dailyLog: { create: vi.fn(), update: vi.fn() }, + }; + return fn(tx); + }); + }); + + afterEach(() => { + if (savedKey !== undefined) { + process.env.ANTHROPIC_API_KEY = savedKey; + } else { + delete process.env.ANTHROPIC_API_KEY; + } + }); + + const validSummaryBody = { + topic: "Free will is an illusion", + opponentName: "Socrates", + opponentId: "opp-hard-socrates", + opponentDifficulty: "hard" as const, + rounds: [ + makeRoundJudgement(1, 7, 6), + makeRoundJudgement(2, 8, 7), + makeRoundJudgement(3, 7, 7), + ], + totalRounds: 3, + userSide: "pro" as const, + }; + + function mockFinalAnalysis() { + mockClaudeCreate.mockResolvedValueOnce({ + content: [{ + type: "text", + text: JSON.stringify({ + overallAnalysis: "A well-fought debate.", + userStrengths: ["Good structure", "Clear evidence"], + userWeaknesses: ["Could steelman more"], + suggestions: ["Practice rebuttal techniques"], + }), + }], + }); + } + + it("returns 503 when ANTHROPIC_API_KEY is missing", async () => { + delete process.env.ANTHROPIC_API_KEY; + const res = await summaryHandler(makeRequest("/api/debate/summary", validSummaryBody)); + expect(res.status).toBe(503); + }); + + it("returns 400 for missing topic", async () => { + const res = await summaryHandler( + makeRequest("/api/debate/summary", { ...validSummaryBody, topic: undefined }), + ); + expect(res.status).toBe(400); + }); + + it("returns 400 for missing opponentName", async () => { + const res = await summaryHandler( + makeRequest("/api/debate/summary", { ...validSummaryBody, opponentName: undefined }), + ); + expect(res.status).toBe(400); + }); + + it("returns 400 for empty rounds", async () => { + const res = await summaryHandler( + makeRequest("/api/debate/summary", { ...validSummaryBody, rounds: [] }), + ); + expect(res.status).toBe(400); + }); + + it("returns 404 when user not found", async () => { + mockFinalAnalysis(); + mockUserFindFirst.mockResolvedValueOnce(null); + + const res = await summaryHandler(makeRequest("/api/debate/summary", validSummaryBody)); + expect(res.status).toBe(404); + }); + + it("returns complete response shape", async () => { + mockFinalAnalysis(); + + const res = await summaryHandler(makeRequest("/api/debate/summary", validSummaryBody)); + const body = await res.json(); + + expect(res.status).toBe(200); + expect(body).toHaveProperty("judgement"); + expect(body).toHaveProperty("xp"); + expect(body).toHaveProperty("qualityScore"); + expect(body).toHaveProperty("levelUp"); + expect(body).toHaveProperty("categoryXp"); + expect(body).toHaveProperty("unlocks"); + expect(body).toHaveProperty("streakFreezesGranted"); + + expect(body.judgement).toHaveProperty("rounds"); + expect(body.judgement).toHaveProperty("userTotalScore"); + expect(body.judgement).toHaveProperty("opponentTotalScore"); + expect(body.judgement).toHaveProperty("winner"); + expect(body.judgement).toHaveProperty("overallAnalysis"); + expect(body.judgement).toHaveProperty("userStrengths"); + expect(body.judgement).toHaveProperty("userWeaknesses"); + expect(body.judgement).toHaveProperty("suggestions"); + + expect(body.xp).toHaveProperty("baseXp"); + expect(body.xp).toHaveProperty("totalXp"); + expect(body.xp).toHaveProperty("qualityBonus"); + expect(body.xp).toHaveProperty("multiplierBonus"); + expect(body.xp).toHaveProperty("isCriticalHit"); + }); + + it("scales XP by round count", async () => { + mockFinalAnalysis(); + + const res3 = await summaryHandler(makeRequest("/api/debate/summary", validSummaryBody)); + const body3 = await res3.json(); + + vi.clearAllMocks(); + mockUserFindFirst.mockResolvedValue(makeBaseUser()); + mockDailyLogFindFirst.mockResolvedValue(null); + mockTransaction.mockImplementation(async (fn: (tx: unknown) => Promise) => { + const tx = { + activity: { create: vi.fn() }, + user: { update: vi.fn() }, + categorySkill: { update: vi.fn() }, + dailyLog: { create: vi.fn(), update: vi.fn() }, + }; + return fn(tx); + }); + mockFinalAnalysis(); + + const res1 = await summaryHandler( + makeRequest("/api/debate/summary", { + ...validSummaryBody, + rounds: [makeRoundJudgement(1, 7, 6)], + }), + ); + const body1 = await res1.json(); + + // 3-round base XP should be 3x the 1-round base XP + expect(body3.xp.baseXp).toBe(body1.xp.baseXp * 3); + }); + + it("applies difficulty weight to quality score", async () => { + mockFinalAnalysis(); + + // Hard opponent gets 1.2x quality + const res = await summaryHandler(makeRequest("/api/debate/summary", validSummaryBody)); + const body = await res.json(); + expect(body.qualityScore).toBeGreaterThan(0); + + // The quality score with hard should be higher than the raw avg/10 + // (7+8+7)/3 = 7.333 → 0.733 * 1.2 = 0.88 + expect(body.qualityScore).toBeGreaterThanOrEqual(0.8); + }); + + it("determines winner from rounds", async () => { + mockFinalAnalysis(); + + // User wins 2 of 3 rounds (7>6, 8>7) + const res = await summaryHandler(makeRequest("/api/debate/summary", validSummaryBody)); + const body = await res.json(); + expect(body.judgement.winner).toBe("user"); + }); + + it("persists activity with debate exercise type", async () => { + mockFinalAnalysis(); + + let createdActivity: Record | null = null; + mockTransaction.mockImplementation(async (fn: (tx: unknown) => Promise) => { + const tx = { + activity: { + create: vi.fn((args: { data: Record }) => { + createdActivity = args.data; + }), + }, + user: { update: vi.fn() }, + categorySkill: { update: vi.fn() }, + dailyLog: { create: vi.fn(), update: vi.fn() }, + }; + return fn(tx); + }); + + await summaryHandler(makeRequest("/api/debate/summary", validSummaryBody)); + + expect(createdActivity).not.toBeNull(); + expect(createdActivity!.exerciseType).toBe("debate"); + expect(createdActivity!.category).toBe("critical-thinking"); + expect(typeof createdActivity!.description).toBe("string"); + expect((createdActivity!.description as string)).toContain("Debate"); + expect((createdActivity!.description as string)).toContain("Socrates"); + }); + + it("handles durationSecs", async () => { + mockFinalAnalysis(); + + let createdActivity: Record | null = null; + mockTransaction.mockImplementation(async (fn: (tx: unknown) => Promise) => { + const tx = { + activity: { + create: vi.fn((args: { data: Record }) => { + createdActivity = args.data; + }), + }, + user: { update: vi.fn() }, + categorySkill: { update: vi.fn() }, + dailyLog: { create: vi.fn(), update: vi.fn() }, + }; + return fn(tx); + }); + + await summaryHandler( + makeRequest("/api/debate/summary", { ...validSummaryBody, durationSecs: 342.7 }), + ); + + expect(createdActivity!.durationSecs).toBe(343); + }); + + it("handles null durationSecs when not provided", async () => { + mockFinalAnalysis(); + + let createdActivity: Record | null = null; + mockTransaction.mockImplementation(async (fn: (tx: unknown) => Promise) => { + const tx = { + activity: { + create: vi.fn((args: { data: Record }) => { + createdActivity = args.data; + }), + }, + user: { update: vi.fn() }, + categorySkill: { update: vi.fn() }, + dailyLog: { create: vi.fn(), update: vi.fn() }, + }; + return fn(tx); + }); + + await summaryHandler(makeRequest("/api/debate/summary", validSummaryBody)); + + expect(createdActivity!.durationSecs).toBeNull(); + }); + + it("uses fallback analysis when Claude fails", async () => { + mockClaudeCreate.mockRejectedValueOnce(new Error("Claude down")); + + const res = await summaryHandler(makeRequest("/api/debate/summary", validSummaryBody)); + const body = await res.json(); + + // Should still return 200 with fallback + expect(res.status).toBe(200); + expect(body.judgement.overallAnalysis).toBe("The debate has concluded."); + }); + + it("returns 400 for invalid JSON body", async () => { + const req = new NextRequest(new URL("/api/debate/summary", "http://localhost:3000"), { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: "not{json", + }); + const res = await summaryHandler(req); + expect(res.status).toBe(400); + }); + + it("includes metadata in persisted activity", async () => { + mockFinalAnalysis(); + + let activityMetadata: string | null = null; + mockTransaction.mockImplementation(async (fn: (tx: unknown) => Promise) => { + const tx = { + activity: { + create: vi.fn((args: { data: Record }) => { + activityMetadata = args.data.metadata as string; + }), + }, + user: { update: vi.fn() }, + categorySkill: { update: vi.fn() }, + dailyLog: { create: vi.fn(), update: vi.fn() }, + }; + return fn(tx); + }); + + await summaryHandler(makeRequest("/api/debate/summary", validSummaryBody)); + + expect(activityMetadata).not.toBeNull(); + const parsed = JSON.parse(activityMetadata!); + expect(parsed.exerciseType).toBe("debate"); + expect(parsed.opponentId).toBe("opp-hard-socrates"); + expect(parsed.opponentName).toBe("Socrates"); + expect(parsed.opponentDifficulty).toBe("hard"); + expect(parsed.topic).toBe("Free will is an illusion"); + expect(parsed.winner).toBe("user"); + expect(parsed.roundCount).toBe(3); + expect(parsed.userSide).toBe("pro"); + }); +}); diff --git a/src/app/api/debate/feedback/route.ts b/src/app/api/debate/feedback/route.ts new file mode 100644 index 0000000000000000000000000000000000000000..3d75220956ce9897a3afd6ee2bab0ea874d1a4b9 --- /dev/null +++ b/src/app/api/debate/feedback/route.ts @@ -0,0 +1,76 @@ +import { NextRequest, NextResponse } from "next/server"; +import { withApiError, ApiError } from "@/lib/api-error"; +import { DIMENSION_IDS } from "@/lib/debate/judge"; +import { submitAllHumanFeedback } from "@/lib/langsmith"; + +/** + * POST /api/debate/feedback + * + * Submits human override scores for a debate round to LangSmith. + * These "human_" feedback keys are picked up by the reflector + * to detect divergence between the LLM judge and human evaluators. + * + * Body: + * { + * runId: string, // LangSmith run ID from the judge response + * scores: Record // dimensionId → 0-10 score (partial OK) + * } + * + * Returns: + * { submitted: number } // count of scores accepted + * + * A 503 is returned if LANGSMITH_API_KEY is not configured (graceful skip). + * A 400 is returned for invalid body shape or unknown dimension IDs. + * Unknown dimension IDs in scores are silently filtered (only valid IDs submitted). + */ +export const POST = withApiError(async (request: NextRequest) => { + if (!process.env.LANGSMITH_API_KEY) { + // Not an error — LangSmith is optional. Return graceful no-op. + return NextResponse.json( + { submitted: 0, skipped: "LANGSMITH_API_KEY not configured" }, + { status: 200 }, + ); + } + + let body: { runId?: unknown; scores?: unknown }; + try { + body = await request.json(); + } catch { + throw new ApiError(400, "Invalid JSON body"); + } + + if (!body.runId || typeof body.runId !== "string") { + throw new ApiError(400, "runId is required and must be a string"); + } + + if ( + !body.scores || + typeof body.scores !== "object" || + Array.isArray(body.scores) + ) { + throw new ApiError(400, "scores must be a non-null object"); + } + + const rawScores = body.scores as Record; + const validDimensionSet = new Set(DIMENSION_IDS); + + // Filter to known dimension IDs with numeric scores in [0, 10] + const cleanScores: Record = {}; + for (const [dimId, value] of Object.entries(rawScores)) { + if (!validDimensionSet.has(dimId)) continue; + if (typeof value !== "number") continue; + if (value < 0 || value > 10) continue; + cleanScores[dimId] = value; + } + + if (Object.keys(cleanScores).length === 0) { + throw new ApiError( + 400, + "No valid scores provided. Scores must use valid dimension IDs and values in [0, 10].", + ); + } + + await submitAllHumanFeedback(body.runId, cleanScores); + + return NextResponse.json({ submitted: Object.keys(cleanScores).length }); +}); diff --git a/src/app/api/debate/judge/route.ts b/src/app/api/debate/judge/route.ts new file mode 100644 index 0000000000000000000000000000000000000000..b42fc59780be7d81bd27b1e4287ce3ce1eb21acb --- /dev/null +++ b/src/app/api/debate/judge/route.ts @@ -0,0 +1,194 @@ +import { NextRequest, NextResponse, after } from "next/server"; +import { claude, parseClaudeJson } from "@/lib/claude"; +import { + buildJudgeSystemPrompt, + buildRoundEvaluationPrompt, + calculateOverallScore, + determineRoundWinner, + type RoundJudgement, + type DimensionScore, + DIMENSION_IDS, +} from "@/lib/debate/judge"; +import { withApiError } from "@/lib/api-error"; +import { + createRunTracer, + submitAllDimensionFeedback, +} from "@/lib/langsmith"; + +interface JudgeBody { + topic: string; + round: number; + totalRounds: number; + userArgument: string; + opponentArgument: string; + opponentName: string; + previousRounds?: RoundJudgement[]; +} + +interface ClaudeJudgeResponse { + user: { + dimensionScores: DimensionScore; + analysis: string; + }; + opponent: { + dimensionScores: DimensionScore; + analysis: string; + }; + roundWinner: "user" | "opponent" | "tie"; + roundSummary: string; +} + +/** + * POST /api/debate/judge + * + * Scores a single round of the debate. + */ +export const POST = withApiError(async (request: NextRequest) => { + if (!process.env.ANTHROPIC_API_KEY) { + return NextResponse.json( + { error: "ANTHROPIC_API_KEY is not configured" }, + { status: 503 }, + ); + } + + let body: JudgeBody; + try { + body = await request.json(); + } catch { + return NextResponse.json({ error: "Invalid JSON body" }, { status: 400 }); + } + + if (!body.topic || typeof body.topic !== "string") { + return NextResponse.json({ error: "topic is required" }, { status: 400 }); + } + if (!body.userArgument || typeof body.userArgument !== "string") { + return NextResponse.json({ error: "userArgument is required" }, { status: 400 }); + } + if (!body.opponentArgument || typeof body.opponentArgument !== "string") { + return NextResponse.json({ error: "opponentArgument is required" }, { status: 400 }); + } + if (!body.opponentName || typeof body.opponentName !== "string") { + return NextResponse.json({ error: "opponentName is required" }, { status: 400 }); + } + + const round = typeof body.round === "number" ? body.round : 1; + const totalRounds = typeof body.totalRounds === "number" ? body.totalRounds : 3; + + const systemPrompt = buildJudgeSystemPrompt(); + const userPrompt = buildRoundEvaluationPrompt( + body.topic, + round, + totalRounds, + body.userArgument, + body.opponentArgument, + body.opponentName, + body.previousRounds, + ); + + try { + const message = await claude.messages.create({ + model: "claude-haiku-4-5-20251001", + max_tokens: 2048, + system: systemPrompt, + messages: [{ role: "user", content: userPrompt }], + }); + + const text = + message.content[0].type === "text" ? message.content[0].text : "{}"; + const parsed = parseClaudeJson(text); + + // Validate and normalise dimension scores + const userDimensionScores: DimensionScore = {}; + const opponentDimensionScores: DimensionScore = {}; + + for (const dimId of DIMENSION_IDS) { + const uScore = parsed.user?.dimensionScores?.[dimId]; + userDimensionScores[dimId] = + typeof uScore === "number" ? Math.min(10, Math.max(0, uScore)) : 5; + + const oScore = parsed.opponent?.dimensionScores?.[dimId]; + opponentDimensionScores[dimId] = + typeof oScore === "number" ? Math.min(10, Math.max(0, oScore)) : 5; + } + + const userOverall = calculateOverallScore(userDimensionScores); + const opponentOverall = calculateOverallScore(opponentDimensionScores); + const roundWinner = determineRoundWinner(userOverall, opponentOverall); + + // Pre-generate a stable run ID so we can return it to the client. + // The client uses this to submit human feedback via POST /api/debate/feedback, + // enabling the reflector to detect judge/human score divergence. + const langsmithRunId = process.env.LANGSMITH_API_KEY + ? crypto.randomUUID() + : null; + + const judgement: RoundJudgement & { langsmithRunId: string | null } = { + round, + user: { + dimensionScores: userDimensionScores, + overallScore: userOverall, + analysis: parsed.user?.analysis || "No analysis provided.", + }, + opponent: { + dimensionScores: opponentDimensionScores, + overallScore: opponentOverall, + analysis: parsed.opponent?.analysis || "No analysis provided.", + }, + roundWinner, + roundSummary: parsed.roundSummary || "Round complete.", + langsmithRunId, + }; + + // Wire LangSmith feedback async — runs AFTER the response is sent + if (process.env.LANGSMITH_API_KEY && langsmithRunId) { + after(async () => { + try { + await createRunTracer({ + id: langsmithRunId, + name: "debate-judge-round", + inputs: { + topic: body.topic, + round, + totalRounds, + userArgument: body.userArgument, + opponentArgument: body.opponentArgument, + opponentName: body.opponentName, + }, + outputs: judgement as unknown as Record, + }); + + // Submit both user and opponent dimension scores + await Promise.all([ + submitAllDimensionFeedback(langsmithRunId, userDimensionScores), + submitAllDimensionFeedback( + langsmithRunId, + Object.fromEntries( + Object.entries(opponentDimensionScores).map(([k, v]) => [ + `opponent-${k}`, + v, + ]), + ), + ), + ]); + } catch (langsmithErr) { + console.error( + "[LangSmith] Failed to submit feedback:", + langsmithErr instanceof Error + ? langsmithErr.message + : String(langsmithErr), + ); + } + }); + } + + return NextResponse.json(judgement); + } catch (err) { + return NextResponse.json( + { + error: "Failed to judge round", + details: err instanceof Error ? err.message : String(err), + }, + { status: 500 }, + ); + } +}); diff --git a/src/app/api/debate/respond/route.ts b/src/app/api/debate/respond/route.ts new file mode 100644 index 0000000000000000000000000000000000000000..3d9720e3556bceb09f3d3a8ed7c2acc1c1e85dbb --- /dev/null +++ b/src/app/api/debate/respond/route.ts @@ -0,0 +1,128 @@ +import { NextRequest, NextResponse } from "next/server"; +import { claude } from "@/lib/claude"; +import { getOpponentById } from "@/lib/debate/opponents"; +import { withApiError } from "@/lib/api-error"; + +interface RespondBody { + topic: string; + opponentId: string; + round: number; + totalRounds: number; + userSide: "pro" | "con"; + userArgument: string; + /** Previous round exchanges for context */ + history?: Array<{ + round: number; + userArgument: string; + opponentArgument: string; + }>; +} + +/** + * POST /api/debate/respond + * + * The user submits their argument; the AI opponent generates a rebuttal. + */ +export const POST = withApiError(async (request: NextRequest) => { + if (!process.env.ANTHROPIC_API_KEY) { + return NextResponse.json( + { error: "ANTHROPIC_API_KEY is not configured" }, + { status: 503 }, + ); + } + + let body: RespondBody; + try { + body = await request.json(); + } catch { + return NextResponse.json({ error: "Invalid JSON body" }, { status: 400 }); + } + + if (!body.topic || typeof body.topic !== "string") { + return NextResponse.json({ error: "topic is required" }, { status: 400 }); + } + if (!body.opponentId || typeof body.opponentId !== "string") { + return NextResponse.json({ error: "opponentId is required" }, { status: 400 }); + } + if (!body.userArgument || typeof body.userArgument !== "string" || body.userArgument.trim().length < 20) { + return NextResponse.json( + { error: "userArgument must be at least 20 characters" }, + { status: 400 }, + ); + } + + const opponent = getOpponentById(body.opponentId); + if (!opponent) { + return NextResponse.json({ error: "Opponent not found" }, { status: 404 }); + } + + const round = typeof body.round === "number" ? body.round : 1; + const totalRounds = typeof body.totalRounds === "number" ? body.totalRounds : 3; + const userSide = body.userSide === "con" ? "con" : "pro"; + const opponentSide = userSide === "pro" ? "con" : "pro"; + + // Build conversation history for context + let historyContext = ""; + if (body.history && body.history.length > 0) { + historyContext = "\n\nPREVIOUS ROUNDS:\n" + body.history + .map( + (h) => + `Round ${h.round}:\n- User (${userSide}): ${h.userArgument}\n- ${opponent.name} (${opponentSide}): ${h.opponentArgument}`, + ) + .join("\n\n"); + } + + const systemPrompt = `${opponent.systemPrompt} + +You are debating the topic: "${body.topic}" +You are arguing the ${opponentSide.toUpperCase()} side. +This is round ${round} of ${totalRounds}. + +CRITICAL RULES: +- Stay in character as ${opponent.name}. +- Directly address the user's arguments — do NOT ignore what they said. +- Build on previous rounds if applicable. +- Do not break the fourth wall or reference that you are an AI.`; + + const userMessage = `${historyContext} + +CURRENT ROUND ${round}: +The user (arguing ${userSide.toUpperCase()}) says: + +${body.userArgument.trim()} + +Respond with your ${opponentSide.toUpperCase()} argument. Output ONLY your debate argument as plain text — no JSON, no formatting instructions.`; + + try { + const message = await claude.messages.create({ + model: "claude-haiku-4-5-20251001", + max_tokens: 1024, + system: systemPrompt, + messages: [{ role: "user", content: userMessage }], + }); + + const opponentArgument = + message.content[0].type === "text" ? message.content[0].text.trim() : ""; + + if (!opponentArgument) { + return NextResponse.json( + { error: "Opponent generated empty response" }, + { status: 500 }, + ); + } + + return NextResponse.json({ + round, + opponentName: opponent.name, + opponentArgument, + }); + } catch (err) { + return NextResponse.json( + { + error: "Failed to generate opponent response", + details: err instanceof Error ? err.message : String(err), + }, + { status: 500 }, + ); + } +}); diff --git a/src/app/api/debate/start/route.ts b/src/app/api/debate/start/route.ts new file mode 100644 index 0000000000000000000000000000000000000000..abf8e4f3e40a19aa2ca28dc680f97a8c0c7c1b65 --- /dev/null +++ b/src/app/api/debate/start/route.ts @@ -0,0 +1,114 @@ +import { NextRequest, NextResponse } from "next/server"; +import { + getDebateTopicById, + getRandomDebateTopic, + type DebateCategory, + DEBATE_CATEGORIES, +} from "@/lib/debate/topics"; +import { + getOpponentById, + getRandomOpponent, + type OpponentDifficulty, +} from "@/lib/debate/opponents"; +import { withApiError } from "@/lib/api-error"; + +const VALID_DIFFICULTIES: OpponentDifficulty[] = ["easy", "medium", "hard"]; +const VALID_ROUNDS = [1, 3, 5]; + +/** + * POST /api/debate/start + * + * Body: + * topicId?: string — pick a specific topic + * customTopic?: string — free-text topic (overrides topicId) + * category?: DebateCategory — filter for random topic + * opponentId?: string — pick a specific opponent + * difficulty?: "easy"|"medium"|"hard" — for random opponent + * rounds?: 1|3|5 — number of debate rounds (default 3) + * userSide?: "pro"|"con" — which side the user argues (default "pro") + * + * Returns a debate session configuration object that the client + * holds in state across the multi-round flow. + */ +export const POST = withApiError(async (request: NextRequest) => { + let body: Record; + try { + body = await request.json(); + } catch { + return NextResponse.json({ error: "Invalid JSON body" }, { status: 400 }); + } + + // --- Resolve topic --- + let topic: { id: string; topic: string; category: string; description: string }; + + if (typeof body.customTopic === "string" && body.customTopic.trim().length >= 5) { + topic = { + id: "custom", + topic: body.customTopic.trim(), + category: "Custom", + description: "User-provided debate topic", + }; + } else if (typeof body.topicId === "string") { + const found = getDebateTopicById(body.topicId); + if (!found) { + return NextResponse.json({ error: "Topic not found" }, { status: 404 }); + } + topic = found; + } else { + const category = + typeof body.category === "string" && + DEBATE_CATEGORIES.includes(body.category as DebateCategory) + ? (body.category as DebateCategory) + : undefined; + const random = getRandomDebateTopic(category); + topic = random; + } + + // --- Resolve opponent --- + let opponent: { id: string; name: string; difficulty: string; description: string; icon: string; era?: string; systemPrompt: string }; + + if (typeof body.opponentId === "string") { + const found = getOpponentById(body.opponentId); + if (!found) { + return NextResponse.json({ error: "Opponent not found" }, { status: 404 }); + } + opponent = found; + } else { + const difficulty: OpponentDifficulty = + typeof body.difficulty === "string" && + VALID_DIFFICULTIES.includes(body.difficulty as OpponentDifficulty) + ? (body.difficulty as OpponentDifficulty) + : "medium"; + opponent = getRandomOpponent(difficulty); + } + + // --- Rounds --- + const rounds = + typeof body.rounds === "number" && VALID_ROUNDS.includes(body.rounds) + ? body.rounds + : 3; + + // --- User side --- + const userSide = + body.userSide === "con" ? "con" : "pro"; + + return NextResponse.json({ + topic: { + id: topic.id, + topic: topic.topic, + category: topic.category, + description: topic.description, + }, + opponent: { + id: opponent.id, + name: opponent.name, + difficulty: opponent.difficulty, + description: opponent.description, + icon: opponent.icon, + era: opponent.era ?? null, + }, + rounds, + userSide, + // systemPrompt is NOT returned to the client — it's used server-side only + }); +}); diff --git a/src/app/api/debate/summary/route.ts b/src/app/api/debate/summary/route.ts new file mode 100644 index 0000000000000000000000000000000000000000..04b94ba13bf25119b571ccf2c3347dd575f1ad73 --- /dev/null +++ b/src/app/api/debate/summary/route.ts @@ -0,0 +1,293 @@ +import { NextRequest, NextResponse } from "next/server"; +import { claude, parseClaudeJson } from "@/lib/claude"; +import { prisma } from "@/lib/db"; +// import { Prisma } from "@prisma/client"; +import { calculateXpGain, rollCriticalHit } from "@/lib/xp"; +import { checkLevelUp } from "@/lib/progression"; +import { EXERCISE_XP } from "@/config/xp"; +import { processSkillUnlocks } from "@/lib/skill-unlock"; +import { getMultiplierPercent } from "@/lib/multiplier"; +import { getTitleForLevel } from "@/config/titles"; +import { processEndOfDay } from "@/lib/streak"; +import { + buildFinalSummaryPrompt, + aggregateScores, + determineFinalWinner, + type RoundJudgement, + type FinalJudgement, +} from "@/lib/debate/judge"; +import { withApiError } from "@/lib/api-error"; + +interface SummaryBody { + topic: string; + opponentName: string; + opponentId: string; + opponentDifficulty: "easy" | "medium" | "hard"; + rounds: RoundJudgement[]; + totalRounds: number; + userSide: "pro" | "con"; + durationSecs?: number; + userId?: number; +} + +interface ClaudeFinalResponse { + overallAnalysis: string; + userStrengths: string[]; + userWeaknesses: string[]; + suggestions: string[]; +} + +/** + * POST /api/debate/summary + * + * After all rounds are judged, generates a final summary and persists XP. + */ +export const POST = withApiError(async (request: NextRequest) => { + if (!process.env.ANTHROPIC_API_KEY) { + return NextResponse.json( + { error: "ANTHROPIC_API_KEY is not configured" }, + { status: 503 }, + ); + } + + let body: SummaryBody; + try { + body = await request.json(); + } catch { + return NextResponse.json({ error: "Invalid JSON body" }, { status: 400 }); + } + + if (!body.topic || typeof body.topic !== "string") { + return NextResponse.json({ error: "topic is required" }, { status: 400 }); + } + if (!body.opponentName || typeof body.opponentName !== "string") { + return NextResponse.json({ error: "opponentName is required" }, { status: 400 }); + } + if (!Array.isArray(body.rounds) || body.rounds.length === 0) { + return NextResponse.json({ error: "rounds must be a non-empty array" }, { status: 400 }); + } + + // --- Compute scores --- + const scores = aggregateScores(body.rounds); + const winner = determineFinalWinner(body.rounds); + + // --- Generate final analysis via Claude --- + let finalAnalysis: ClaudeFinalResponse; + try { + const prompt = buildFinalSummaryPrompt( + body.topic, + body.rounds, + body.opponentName, + ); + + const message = await claude.messages.create({ + model: "claude-haiku-4-5-20251001", + max_tokens: 2048, + messages: [{ role: "user", content: prompt }], + }); + + const text = + message.content[0].type === "text" ? message.content[0].text : "{}"; + finalAnalysis = parseClaudeJson(text); + } catch { + // Non-fatal: use fallback analysis + finalAnalysis = { + overallAnalysis: "The debate has concluded.", + userStrengths: [], + userWeaknesses: [], + suggestions: [], + }; + } + + // --- Quality score: user avg / 10, clamped [0, 1] --- + const qualityScore = Math.min(1, Math.max(0, scores.userAvg / 10)); + + // --- Difficulty bonus: harder opponents → better quality multiplier --- + const difficultyWeight: Record = { + easy: 0.8, + medium: 1.0, + hard: 1.2, + }; + const diffWeight = difficultyWeight[body.opponentDifficulty ?? "medium"] ?? 1.0; + const adjustedQuality = Math.min(1, qualityScore * diffWeight); + + // --- XP calculation --- + const userId = body.userId ?? 1; + const user = await prisma.user.findFirst({ + where: { id: userId }, + include: { categorySkills: { where: { category: "critical-thinking" } } }, + }); + + if (!user) { + return NextResponse.json({ error: "No user found" }, { status: 404 }); + } + + const criticalSkill = user.categorySkills[0]; + if (!criticalSkill) { + return NextResponse.json( + { error: "Critical Thinking CategorySkill not found" }, + { status: 500 }, + ); + } + + // Debate XP uses the critical-thinking config, scaled by number of rounds + const { baseXp, maxQualityBonus } = EXERCISE_XP["critical-thinking"]; + const roundMultiplier = body.rounds.length; + const isCriticalHit = rollCriticalHit(); + const multiplierPercent = await getMultiplierPercent(prisma, userId, "critical-thinking"); + + const xpResult = calculateXpGain({ + baseXp: baseXp * roundMultiplier, + qualityScore: adjustedQuality, + maxQualityBonus: maxQualityBonus * roundMultiplier, + isCriticalHit, + multiplierPercent, + }); + + // --- Level-up checks --- + const userLevelResult = checkLevelUp({ + currentXp: user.currentXp + xpResult.totalXp, + xpToNextLevel: user.xpToNextLevel, + level: user.level, + }); + + const categoryLevelResult = checkLevelUp({ + currentXp: criticalSkill.currentXp + xpResult.totalXp, + xpToNextLevel: criticalSkill.xpToNext, + level: criticalSkill.level, + }); + + const newTitle = getTitleForLevel(userLevelResult.newLevel); + const titleChanged = newTitle !== user.title; + + // --- Streak --- + await processEndOfDay(userId); + + // --- Daily log --- + const now = new Date(); + const todayStart = new Date( + Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate()), + ); + const tomorrowStart = new Date(todayStart.getTime() + 86_400_000); + + const existingLog = await prisma.dailyLog.findFirst({ + where: { userId, date: { gte: todayStart, lt: tomorrowStart } }, + }); + + const newXpEarned = (existingLog?.xpEarned ?? 0) + xpResult.totalXp; + const newActivityCount = (existingLog?.activityCount ?? 0) + 1; + const goalMet = newXpEarned >= user.dailyGoalXp; + + // --- Persist --- + let unlockResult = { unlocked: [] as string[], streakFreezesGranted: 0 }; + await prisma.$transaction(async (tx) => { + await tx.activity.create({ + data: { + userId, + category: "critical-thinking", + exerciseType: "debate", + description: `Debate: ${body.topic} (vs ${body.opponentName}, ${body.rounds.length} rounds)`, + baseXp: xpResult.baseXp, + qualityBonus: xpResult.qualityBonus, + isCriticalHit: xpResult.isCriticalHit, + totalXp: xpResult.totalXp, + score: adjustedQuality, + durationSecs: + typeof body.durationSecs === "number" && body.durationSecs >= 0 + ? Math.round(body.durationSecs) + : null, + metadata: JSON.stringify({ + exerciseType: "debate", + opponentId: body.opponentId, + opponentName: body.opponentName, + opponentDifficulty: body.opponentDifficulty, + topic: body.topic, + userSide: body.userSide, + roundCount: body.rounds.length, + winner, + userAvgScore: scores.userAvg, + opponentAvgScore: scores.opponentAvg, + }), + }, + }); + + await tx.user.update({ + where: { id: userId }, + data: { + totalXp: user.totalXp + xpResult.totalXp, + currentXp: userLevelResult.remainingXp, + xpToNextLevel: userLevelResult.newXpToNextLevel, + level: userLevelResult.newLevel, + ...(titleChanged && { title: newTitle }), + }, + }); + + await tx.categorySkill.update({ + where: { id: criticalSkill.id }, + data: { + totalXp: criticalSkill.totalXp + xpResult.totalXp, + currentXp: categoryLevelResult.remainingXp, + xpToNext: categoryLevelResult.newXpToNextLevel, + level: categoryLevelResult.newLevel, + }, + }); + + if (categoryLevelResult.levelsGained > 0) { + unlockResult = await processSkillUnlocks( + tx, userId, "critical-thinking", categoryLevelResult.newLevel, + ); + } + + if (existingLog) { + await tx.dailyLog.update({ + where: { id: existingLog.id }, + data: { xpEarned: newXpEarned, activityCount: newActivityCount, goalMet }, + }); + } else { + await tx.dailyLog.create({ + data: { + userId, + date: todayStart, + xpEarned: newXpEarned, + activityCount: newActivityCount, + goalMet, + }, + }); + } + }); + + // --- Build final judgement response --- + const finalJudgement: FinalJudgement = { + rounds: body.rounds, + userTotalScore: scores.userTotal, + opponentTotalScore: scores.opponentTotal, + winner, + overallAnalysis: finalAnalysis.overallAnalysis ?? "The debate has concluded.", + userStrengths: finalAnalysis.userStrengths ?? [], + userWeaknesses: finalAnalysis.userWeaknesses ?? [], + suggestions: finalAnalysis.suggestions ?? [], + }; + + return NextResponse.json({ + judgement: finalJudgement, + xp: { + baseXp: xpResult.baseXp, + totalXp: xpResult.totalXp, + qualityBonus: xpResult.qualityBonus, + multiplierBonus: xpResult.multiplierBonus, + multiplierPercent, + isCriticalHit: xpResult.isCriticalHit, + }, + qualityScore: adjustedQuality, + levelUp: userLevelResult.levelsGained > 0, + categoryXp: { + currentXp: categoryLevelResult.remainingXp, + xpToNext: categoryLevelResult.newXpToNextLevel, + level: categoryLevelResult.newLevel, + levelUp: categoryLevelResult.levelsGained > 0, + }, + newTitle: titleChanged ? newTitle : undefined, + unlocks: unlockResult.unlocked, + streakFreezesGranted: unlockResult.streakFreezesGranted, + }); +}); diff --git a/src/app/api/export/__tests__/route.test.ts b/src/app/api/export/__tests__/route.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..39f455315c26b7b25c057c45b8ddbd0ffab8a243 --- /dev/null +++ b/src/app/api/export/__tests__/route.test.ts @@ -0,0 +1,418 @@ +/** + * Tests for GET /api/export + * + * Covers: + * - 404 when no user found + * - 200 response with Content-Type application/json + * - Content-Disposition header includes attachment and filename with today's date + * - Response body passes through buildExport shape (exportVersion, exportedAt, profile, etc.) + * - Parallel DB queries: categorySkills, activities, dailyLogs, unlocks, spacedRepetition + * - Unlocks query includes node relation with correct select fields + * - DB errors propagate as 500 via withApiError + * - Empty data sets return valid export (empty arrays) + * - Response body is valid JSON (double-indented) + */ + +import { describe, it, expect, vi, beforeEach } from "vitest"; +import { NextRequest } from "next/server"; + +// --------------------------------------------------------------------------- +// Mock prisma +// --------------------------------------------------------------------------- + +const mockUserFindFirst = vi.fn(); +const mockCategorySkillFindMany = vi.fn(); +const mockActivityFindMany = vi.fn(); +const mockDailyLogFindMany = vi.fn(); +const mockUnlockFindMany = vi.fn(); +const mockSrFindMany = vi.fn(); + +vi.mock("@/lib/db", () => ({ + prisma: { + user: { findFirst: (...args: unknown[]) => mockUserFindFirst(...args) }, + categorySkill: { + findMany: (...args: unknown[]) => mockCategorySkillFindMany(...args), + }, + activity: { + findMany: (...args: unknown[]) => mockActivityFindMany(...args), + }, + dailyLog: { + findMany: (...args: unknown[]) => mockDailyLogFindMany(...args), + }, + unlock: { findMany: (...args: unknown[]) => mockUnlockFindMany(...args) }, + spacedRepetitionItem: { + findMany: (...args: unknown[]) => mockSrFindMany(...args), + }, + }, +})); + +import { GET } from "../route"; + +// --------------------------------------------------------------------------- +// Fixtures +// --------------------------------------------------------------------------- + +const baseUser = { + id: 1, + name: "Player One", + level: 3, + totalXp: 600, + currentXp: 100, + title: "Apprentice", + dailyGoalXp: 100, + streak: 5, + longestStreak: 12, + streakFreezes: 2, + lichessUsername: null, + chesscomUsername: null, + createdAt: new Date("2026-01-01T00:00:00.000Z"), + updatedAt: new Date("2026-03-01T00:00:00.000Z"), +}; + +const baseSkills = [ + { + id: 10, + userId: 1, + category: "CHESS", + level: 2, + totalXp: 300, + currentXp: 50, + xpToNext: 150, + createdAt: new Date("2026-01-01T00:00:00.000Z"), + updatedAt: new Date("2026-02-01T00:00:00.000Z"), + }, +]; + +const baseActivities = [ + { + id: 100, + userId: 1, + category: "CHESS", + exerciseType: "puzzle", + xpEarned: 30, + score: 0.9, + durationSeconds: 120, + metadata: null, + createdAt: new Date("2026-03-10T12:00:00.000Z"), + }, +]; + +const baseDailyLogs = [ + { + id: 200, + userId: 1, + date: new Date("2026-03-10T00:00:00.000Z"), + xpEarned: 90, + goalMet: false, + streakFreezeUsed: false, + createdAt: new Date("2026-03-10T00:00:00.000Z"), + updatedAt: new Date("2026-03-10T23:59:00.000Z"), + }, +]; + +const baseUnlocks = [ + { + id: 300, + userId: 1, + nodeId: 5, + unlockedAt: new Date("2026-03-01T00:00:00.000Z"), + node: { + category: "CHESS", + name: "Opening Theory", + nodeType: "SKILL", + levelRequired: 2, + }, + }, +]; + +const baseSR = [ + { + id: 400, + userId: 1, + topicId: "topic-1", + stage: 2, + nextReviewAt: new Date("2026-03-25T00:00:00.000Z"), + lastReviewAt: new Date("2026-03-18T00:00:00.000Z"), + lastScore: 0.85, + totalReviews: 3, + successCount: 2, + createdAt: new Date("2026-03-10T00:00:00.000Z"), + updatedAt: new Date("2026-03-18T00:00:00.000Z"), + }, +]; + +function makeRequest() { + return new NextRequest("http://localhost/api/export"); +} + +function setupHappyPath() { + mockUserFindFirst.mockResolvedValue(baseUser); + mockCategorySkillFindMany.mockResolvedValue(baseSkills); + mockActivityFindMany.mockResolvedValue(baseActivities); + mockDailyLogFindMany.mockResolvedValue(baseDailyLogs); + mockUnlockFindMany.mockResolvedValue(baseUnlocks); + mockSrFindMany.mockResolvedValue(baseSR); +} + +// --------------------------------------------------------------------------- +// Tests +// --------------------------------------------------------------------------- + +describe("GET /api/export", () => { + beforeEach(() => { + vi.clearAllMocks(); + }); + + // ------------------------------------------------------------------------- + // 404 / user not found + // ------------------------------------------------------------------------- + + it("returns 404 when no user found", async () => { + mockUserFindFirst.mockResolvedValue(null); + mockCategorySkillFindMany.mockResolvedValue([]); + mockActivityFindMany.mockResolvedValue([]); + mockDailyLogFindMany.mockResolvedValue([]); + mockUnlockFindMany.mockResolvedValue([]); + mockSrFindMany.mockResolvedValue([]); + + const res = await GET(makeRequest()); + expect(res.status).toBe(404); + const body = await res.json(); + expect(body.error).toBeDefined(); + }); + + // ------------------------------------------------------------------------- + // Happy path — response headers + // ------------------------------------------------------------------------- + + it("returns 200 on success", async () => { + setupHappyPath(); + const res = await GET(makeRequest()); + expect(res.status).toBe(200); + }); + + it("sets Content-Type to application/json", async () => { + setupHappyPath(); + const res = await GET(makeRequest()); + expect(res.headers.get("content-type")).toBe("application/json"); + }); + + it("sets Content-Disposition as attachment with a filename", async () => { + setupHappyPath(); + const res = await GET(makeRequest()); + const disposition = res.headers.get("content-disposition"); + expect(disposition).toMatch(/attachment/); + expect(disposition).toMatch(/rotnot-export-/); + expect(disposition).toMatch(/\.json/); + }); + + it("includes today's date in the Content-Disposition filename", async () => { + setupHappyPath(); + const res = await GET(makeRequest()); + const disposition = res.headers.get("content-disposition") ?? ""; + const today = new Date().toISOString().slice(0, 10); // YYYY-MM-DD + expect(disposition).toContain(today); + }); + + // ------------------------------------------------------------------------- + // Response body shape + // ------------------------------------------------------------------------- + + it("response body is valid JSON", async () => { + setupHappyPath(); + const res = await GET(makeRequest()); + const text = await res.text(); + expect(() => JSON.parse(text)).not.toThrow(); + }); + + it("response body contains exportVersion: 1", async () => { + setupHappyPath(); + const res = await GET(makeRequest()); + const body = await res.json(); + expect(body.exportVersion).toBe(1); + }); + + it("response body contains exportedAt ISO string", async () => { + setupHappyPath(); + const res = await GET(makeRequest()); + const body = await res.json(); + expect(typeof body.exportedAt).toBe("string"); + expect(() => new Date(body.exportedAt)).not.toThrow(); + }); + + it("response body contains profile section", async () => { + setupHappyPath(); + const res = await GET(makeRequest()); + const body = await res.json(); + expect(body.profile).toBeDefined(); + expect(body.profile.name).toBe("Player One"); + }); + + it("response body contains categorySkills array", async () => { + setupHappyPath(); + const res = await GET(makeRequest()); + const body = await res.json(); + expect(Array.isArray(body.categorySkills)).toBe(true); + expect(body.categorySkills).toHaveLength(1); + expect(body.categorySkills[0].category).toBe("CHESS"); + }); + + it("response body contains activities array", async () => { + setupHappyPath(); + const res = await GET(makeRequest()); + const body = await res.json(); + expect(Array.isArray(body.activities)).toBe(true); + expect(body.activities).toHaveLength(1); + }); + + it("response body contains dailyLogs array", async () => { + setupHappyPath(); + const res = await GET(makeRequest()); + const body = await res.json(); + expect(Array.isArray(body.dailyLogs)).toBe(true); + expect(body.dailyLogs).toHaveLength(1); + }); + + it("response body contains unlocks array", async () => { + setupHappyPath(); + const res = await GET(makeRequest()); + const body = await res.json(); + expect(Array.isArray(body.unlocks)).toBe(true); + expect(body.unlocks).toHaveLength(1); + expect(body.unlocks[0].nodeName).toBe("Opening Theory"); + }); + + it("response body contains spacedRepetition array", async () => { + setupHappyPath(); + const res = await GET(makeRequest()); + const body = await res.json(); + expect(Array.isArray(body.spacedRepetition)).toBe(true); + expect(body.spacedRepetition).toHaveLength(1); + expect(body.spacedRepetition[0].topicId).toBe("topic-1"); + }); + + it("response body contains summary section", async () => { + setupHappyPath(); + const res = await GET(makeRequest()); + const body = await res.json(); + expect(body.summary).toBeDefined(); + expect(typeof body.summary.totalActivities).toBe("number"); + }); + + // ------------------------------------------------------------------------- + // Empty data — valid export with empty arrays + // ------------------------------------------------------------------------- + + it("handles empty data sets gracefully", async () => { + mockUserFindFirst.mockResolvedValue(baseUser); + mockCategorySkillFindMany.mockResolvedValue([]); + mockActivityFindMany.mockResolvedValue([]); + mockDailyLogFindMany.mockResolvedValue([]); + mockUnlockFindMany.mockResolvedValue([]); + mockSrFindMany.mockResolvedValue([]); + + const res = await GET(makeRequest()); + expect(res.status).toBe(200); + const body = await res.json(); + expect(body.categorySkills).toEqual([]); + expect(body.activities).toEqual([]); + expect(body.dailyLogs).toEqual([]); + expect(body.unlocks).toEqual([]); + expect(body.spacedRepetition).toEqual([]); + }); + + // ------------------------------------------------------------------------- + // DB query parameters + // ------------------------------------------------------------------------- + + it("queries user with id: 1", async () => { + setupHappyPath(); + await GET(makeRequest()); + expect(mockUserFindFirst).toHaveBeenCalledWith({ where: { id: 1 } }); + }); + + it("queries categorySkills filtered to userId 1 ordered by category asc", async () => { + setupHappyPath(); + await GET(makeRequest()); + expect(mockCategorySkillFindMany).toHaveBeenCalledWith({ + where: { userId: 1 }, + orderBy: { category: "asc" }, + }); + }); + + it("queries activities filtered to userId 1 ordered by createdAt desc", async () => { + setupHappyPath(); + await GET(makeRequest()); + expect(mockActivityFindMany).toHaveBeenCalledWith({ + where: { userId: 1 }, + orderBy: { createdAt: "desc" }, + }); + }); + + it("queries dailyLogs filtered to userId 1 ordered by date asc", async () => { + setupHappyPath(); + await GET(makeRequest()); + expect(mockDailyLogFindMany).toHaveBeenCalledWith({ + where: { userId: 1 }, + orderBy: { date: "asc" }, + }); + }); + + it("queries unlocks with node include selecting category, name, nodeType, levelRequired", async () => { + setupHappyPath(); + await GET(makeRequest()); + expect(mockUnlockFindMany).toHaveBeenCalledWith( + expect.objectContaining({ + where: { userId: 1 }, + include: { + node: { + select: { + category: true, + name: true, + nodeType: true, + levelRequired: true, + }, + }, + }, + }) + ); + }); + + it("queries spacedRepetitionItem filtered to userId 1 ordered by createdAt asc", async () => { + setupHappyPath(); + await GET(makeRequest()); + expect(mockSrFindMany).toHaveBeenCalledWith({ + where: { userId: 1 }, + orderBy: { createdAt: "asc" }, + }); + }); + + // ------------------------------------------------------------------------- + // Error propagation + // ------------------------------------------------------------------------- + + it("returns 500 when DB throws on user lookup", async () => { + mockUserFindFirst.mockRejectedValue(new Error("DB offline")); + // Other mocks don't matter — Promise.all won't be reached + mockCategorySkillFindMany.mockResolvedValue([]); + mockActivityFindMany.mockResolvedValue([]); + mockDailyLogFindMany.mockResolvedValue([]); + mockUnlockFindMany.mockResolvedValue([]); + mockSrFindMany.mockResolvedValue([]); + + const res = await GET(makeRequest()); + expect(res.status).toBe(500); + }); + + it("returns 500 when a parallel DB query throws", async () => { + mockUserFindFirst.mockResolvedValue(baseUser); + mockCategorySkillFindMany.mockRejectedValue(new Error("query failed")); + mockActivityFindMany.mockResolvedValue([]); + mockDailyLogFindMany.mockResolvedValue([]); + mockUnlockFindMany.mockResolvedValue([]); + mockSrFindMany.mockResolvedValue([]); + + const res = await GET(makeRequest()); + expect(res.status).toBe(500); + }); +}); diff --git a/src/app/api/export/route.ts b/src/app/api/export/route.ts new file mode 100644 index 0000000000000000000000000000000000000000..96f3339f51458d9bb760d049dd2da221eb8277ce --- /dev/null +++ b/src/app/api/export/route.ts @@ -0,0 +1,66 @@ +import { NextResponse } from "next/server"; +import { prisma } from "@/lib/db"; +import { withApiError, ApiError } from "@/lib/api-error"; +import { buildExport } from "@/lib/export"; + +/** + * GET /api/export + * + * Returns a full JSON export of the user's data. + * Intended for data portability — download everything in one file. + */ +export const GET = withApiError(async () => { + const user = await prisma.user.findFirst({ where: { id: 1 } }); + if (!user) throw new ApiError(404, "No user found"); + + const [categorySkills, activities, dailyLogs, unlocks, spacedRepetition] = + await Promise.all([ + prisma.categorySkill.findMany({ + where: { userId: 1 }, + orderBy: { category: "asc" }, + }), + prisma.activity.findMany({ + where: { userId: 1 }, + orderBy: { createdAt: "desc" }, + }), + prisma.dailyLog.findMany({ + where: { userId: 1 }, + orderBy: { date: "asc" }, + }), + prisma.unlock.findMany({ + where: { userId: 1 }, + include: { + node: { + select: { + category: true, + name: true, + nodeType: true, + levelRequired: true, + }, + }, + }, + orderBy: { unlockedAt: "asc" }, + }), + prisma.spacedRepetitionItem.findMany({ + where: { userId: 1 }, + orderBy: { createdAt: "asc" }, + }), + ]); + + const exportData = buildExport({ + user, + categorySkills, + activities, + dailyLogs, + unlocks, + spacedRepetition, + }); + + return new NextResponse(JSON.stringify(exportData, null, 2), { + status: 200, + headers: { + "Content-Type": "application/json", + "Content-Disposition": `attachment; filename="rotnot-export-${new Date().toISOString().slice(0, 10)}.json"`, + }, + }); +}); diff --git a/src/app/api/feynman/__tests__/routes.test.ts b/src/app/api/feynman/__tests__/routes.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..0531c441cc86495b2602dedaabd25e3bc1958d71 --- /dev/null +++ b/src/app/api/feynman/__tests__/routes.test.ts @@ -0,0 +1,664 @@ +/** + * Tests for three Feynman API route handlers: + * POST /api/feynman/assess + * POST /api/feynman/teach + * POST /api/feynman/teach-deep + * + * Each handler is tested at the HTTP layer: request parsing, env guards, + * status codes, response shape, Claude mock integration, and fallback paths. + * No real network calls or DB writes are made. + */ + +import { describe, it, expect, vi, beforeEach, afterEach } from "vitest"; +import { NextRequest } from "next/server"; + +// --------------------------------------------------------------------------- +// Mock Claude and grounded-teaching so no real I/O happens +// --------------------------------------------------------------------------- + +const mockCreate = vi.fn(); + +vi.mock("@/lib/claude", () => ({ + claude: { + messages: { + create: (...args: unknown[]) => mockCreate(...args), + }, + }, + parseClaudeJson: (text: string) => JSON.parse(text.trim().replace(/^```(?:json)?\s*/i, "").replace(/\s*```\s*$/, "").trim()), +})); + +const mockGetGroundedTeaching = vi.fn(); +vi.mock("@/lib/sources/curate", () => ({ + getGroundedTeaching: (...args: unknown[]) => mockGetGroundedTeaching(...args), +})); + +// --------------------------------------------------------------------------- +// Import handlers after mocks are hoisted +// --------------------------------------------------------------------------- + +import { POST as assessPost } from "../assess/route"; +import { POST as teachPost } from "../teach/route"; +import { POST as teachDeepPost } from "../teach-deep/route"; + +// --------------------------------------------------------------------------- +// Helpers +// --------------------------------------------------------------------------- + +const originalEnv = { ...process.env }; + +function makePost(path: string, body?: Record): NextRequest { + return new NextRequest(`http://localhost${path}`, { + method: "POST", + body: body !== undefined ? JSON.stringify(body) : undefined, + headers: { "Content-Type": "application/json" }, + }); +} + +async function json(res: Response): Promise { + return res.json(); +} + +// Builds a minimal Claude content block response for a given JSON payload +function claudeResponse(payload: unknown): object { + return { + content: [{ type: "text", text: JSON.stringify(payload) }], + }; +} + +beforeEach(() => { + mockCreate.mockReset(); + mockGetGroundedTeaching.mockReset(); + process.env = { ...originalEnv, ANTHROPIC_API_KEY: "test-key" }; +}); + +afterEach(() => { + process.env = originalEnv; +}); + +// =========================================================================== +// POST /api/feynman/assess +// =========================================================================== + +describe("POST /api/feynman/assess — API key guard", () => { + it("returns 503 when ANTHROPIC_API_KEY is not set", async () => { + delete process.env.ANTHROPIC_API_KEY; + const res = await assessPost(makePost("/api/feynman/assess", { topic: "Photosynthesis" })); + expect(res.status).toBe(503); + const body = await json(res) as { error: string }; + expect(body.error).toMatch(/ANTHROPIC_API_KEY/); + }); + + it("returns 503 when ANTHROPIC_API_KEY is empty string", async () => { + process.env.ANTHROPIC_API_KEY = ""; + const res = await assessPost(makePost("/api/feynman/assess", { topic: "Photosynthesis" })); + expect(res.status).toBe(503); + }); + + it("does not call claude when key is missing", async () => { + delete process.env.ANTHROPIC_API_KEY; + await assessPost(makePost("/api/feynman/assess", { topic: "Gravity" })); + expect(mockCreate).not.toHaveBeenCalled(); + }); +}); + +describe("POST /api/feynman/assess — input validation", () => { + it("returns 400 when topic is missing", async () => { + const res = await assessPost(makePost("/api/feynman/assess", {})); + expect(res.status).toBe(400); + const body = await json(res) as { error: string }; + expect(body.error).toMatch(/topic/i); + }); + + it("returns 400 when topic is not a string", async () => { + const res = await assessPost(makePost("/api/feynman/assess", { topic: 42 })); + expect(res.status).toBe(400); + }); + + it("returns 400 when body is invalid JSON", async () => { + const req = new NextRequest("http://localhost/api/feynman/assess", { + method: "POST", + body: "not json", + headers: { "Content-Type": "application/json" }, + }); + const res = await assessPost(req); + expect(res.status).toBe(400); + const body = await json(res) as { error: string }; + expect(body.error).toMatch(/invalid json/i); + }); +}); + +describe("POST /api/feynman/assess — success path", () => { + const MOCK_QUESTION = { + question: "What is the primary product of the light-dependent reactions?", + options: ["A. Glucose", "B. ATP", "C. CO2", "D. Water"], + correctIndex: 1, + explanation: "ATP is produced in the light-dependent reactions in the thylakoid membranes.", + }; + + it("returns 200 with correct structure on valid input", async () => { + mockCreate.mockResolvedValueOnce(claudeResponse(MOCK_QUESTION)); + + const res = await assessPost(makePost("/api/feynman/assess", { topic: "Photosynthesis" })); + expect(res.status).toBe(200); + + const body = await json(res) as { + topic: string; + question: string; + options: string[]; + correctIndex: number; + explanation: string; + }; + expect(body.topic).toBe("Photosynthesis"); + expect(body.question).toBe(MOCK_QUESTION.question); + expect(body.options).toHaveLength(4); + expect(body.correctIndex).toBe(1); + expect(typeof body.explanation).toBe("string"); + }); + + it("passes topic to Claude in the prompt", async () => { + mockCreate.mockResolvedValueOnce(claudeResponse(MOCK_QUESTION)); + + await assessPost(makePost("/api/feynman/assess", { topic: "Quantum Entanglement" })); + + expect(mockCreate).toHaveBeenCalledOnce(); + const callArgs = mockCreate.mock.calls[0][0] as { messages: Array<{ content: string }> }; + expect(callArgs.messages[0].content).toContain("Quantum Entanglement"); + }); + + it("includes difficulty context in prompt when provided", async () => { + mockCreate.mockResolvedValueOnce(claudeResponse(MOCK_QUESTION)); + + await assessPost(makePost("/api/feynman/assess", { + topic: "Quantum Entanglement", + difficulty: "advanced", + })); + + const callArgs = mockCreate.mock.calls[0][0] as { messages: Array<{ content: string }> }; + expect(callArgs.messages[0].content).toContain("advanced"); + }); + + it("uses claude-3-5-haiku model", async () => { + mockCreate.mockResolvedValueOnce(claudeResponse(MOCK_QUESTION)); + + await assessPost(makePost("/api/feynman/assess", { topic: "Evolution" })); + + const callArgs = mockCreate.mock.calls[0][0] as { model: string }; + expect(callArgs.model).toContain("haiku"); + }); + + it("echoes the topic in the response", async () => { + mockCreate.mockResolvedValueOnce(claudeResponse(MOCK_QUESTION)); + + const res = await assessPost(makePost("/api/feynman/assess", { topic: "Natural Selection" })); + const body = await json(res) as { topic: string }; + expect(body.topic).toBe("Natural Selection"); + }); +}); + +describe("POST /api/feynman/assess — Claude error handling", () => { + it("returns 500 when Claude returns invalid JSON", async () => { + mockCreate.mockResolvedValueOnce({ + content: [{ type: "text", text: "not valid json at all" }], + }); + + const res = await assessPost(makePost("/api/feynman/assess", { topic: "Relativity" })); + expect(res.status).toBe(500); + const body = await json(res) as { error: string }; + expect(body.error).toMatch(/Failed to generate assessment/i); + }); + + it("returns 500 when Claude returns wrong number of options", async () => { + mockCreate.mockResolvedValueOnce(claudeResponse({ + question: "What is X?", + options: ["A. one", "B. two"], // Only 2 options, not 4 + correctIndex: 0, + explanation: "Because reasons", + })); + + const res = await assessPost(makePost("/api/feynman/assess", { topic: "Test" })); + expect(res.status).toBe(500); + }); + + it("returns 500 when correctIndex is out of range", async () => { + mockCreate.mockResolvedValueOnce(claudeResponse({ + question: "What is X?", + options: ["A", "B", "C", "D"], + correctIndex: 5, // Out of range + explanation: "Explanation", + })); + + const res = await assessPost(makePost("/api/feynman/assess", { topic: "Test" })); + expect(res.status).toBe(500); + }); + + it("returns 500 when Claude throws a network error", async () => { + mockCreate.mockRejectedValueOnce(new Error("Network timeout")); + + const res = await assessPost(makePost("/api/feynman/assess", { topic: "Gravity" })); + expect(res.status).toBe(500); + const body = await json(res) as { error: string; details: string }; + expect(body.details).toContain("Network timeout"); + }); +}); + +// =========================================================================== +// POST /api/feynman/teach +// =========================================================================== + +describe("POST /api/feynman/teach — API key guard", () => { + it("returns 503 when ANTHROPIC_API_KEY is missing", async () => { + delete process.env.ANTHROPIC_API_KEY; + const res = await teachPost(makePost("/api/feynman/teach", { topic: "Black Holes" })); + expect(res.status).toBe(503); + const body = await json(res) as { error: string }; + expect(body.error).toMatch(/ANTHROPIC_API_KEY/); + }); + + it("does not call Claude when key is missing", async () => { + delete process.env.ANTHROPIC_API_KEY; + await teachPost(makePost("/api/feynman/teach", { topic: "Dark Matter" })); + expect(mockCreate).not.toHaveBeenCalled(); + expect(mockGetGroundedTeaching).not.toHaveBeenCalled(); + }); +}); + +describe("POST /api/feynman/teach — input validation", () => { + it("returns 400 when topic is missing", async () => { + const res = await teachPost(makePost("/api/feynman/teach", {})); + expect(res.status).toBe(400); + const body = await json(res) as { error: string }; + expect(body.error).toMatch(/topic/i); + }); + + it("returns 400 when topic is not a string", async () => { + const res = await teachPost(makePost("/api/feynman/teach", { topic: true })); + expect(res.status).toBe(400); + }); + + it("returns 400 on invalid JSON body", async () => { + const req = new NextRequest("http://localhost/api/feynman/teach", { + method: "POST", + body: "{broken", + headers: { "Content-Type": "application/json" }, + }); + const res = await teachPost(req); + expect(res.status).toBe(400); + }); +}); + +describe("POST /api/feynman/teach — grounded teaching path", () => { + // Use a real topic ID that exists in FEYNMAN_TOPICS + const REAL_TOPIC_ID = "ph-01"; // "Newton's three laws of motion", domain: "Physics" + const REAL_TOPIC = "Newton's three laws of motion"; + + const GROUNDED_RESPONSE = { + explanation: "Newton's three laws describe the relationship between forces and motion.", + keyTakeaways: ["Inertia: objects resist changes in motion", "F = ma", "Every action has an equal and opposite reaction"], + confidenceScore: 0.9, + sources: [ + { + url: "https://en.wikipedia.org/wiki/Newton%27s_laws_of_motion", + title: "Newton's laws of motion - Wikipedia", + domain: "wikipedia.org", + license: "CC BY-SA", + }, + ], + }; + + it("returns grounded content when getGroundedTeaching succeeds", async () => { + mockGetGroundedTeaching.mockResolvedValueOnce(GROUNDED_RESPONSE); + + const res = await teachPost(makePost("/api/feynman/teach", { + topic: REAL_TOPIC, + topicId: REAL_TOPIC_ID, + })); + + expect(res.status).toBe(200); + const body = await json(res) as { + grounded: boolean; + sources: unknown[]; + explanation: string; + confidenceScore: number; + }; + expect(body.grounded).toBe(true); + expect(body.sources).toHaveLength(1); + expect(body.explanation).toBe(GROUNDED_RESPONSE.explanation); + expect(body.confidenceScore).toBe(0.9); + }); + + it("does NOT call Claude when grounded teaching returns content", async () => { + mockGetGroundedTeaching.mockResolvedValueOnce(GROUNDED_RESPONSE); + + await teachPost(makePost("/api/feynman/teach", { + topic: REAL_TOPIC, + topicId: REAL_TOPIC_ID, + })); + + expect(mockCreate).not.toHaveBeenCalled(); + }); + + it("falls back to Claude when getGroundedTeaching returns null", async () => { + mockGetGroundedTeaching.mockResolvedValueOnce(null); + mockCreate.mockResolvedValueOnce(claudeResponse({ + explanation: "Ungrounded fallback explanation.", + keyTakeaways: ["Takeaway 1"], + })); + + const res = await teachPost(makePost("/api/feynman/teach", { + topic: REAL_TOPIC, + topicId: REAL_TOPIC_ID, + })); + + expect(res.status).toBe(200); + const body = await json(res) as { grounded: boolean }; + expect(body.grounded).toBe(false); + expect(mockCreate).toHaveBeenCalledOnce(); + }); + + it("falls back to Claude when getGroundedTeaching throws", async () => { + mockGetGroundedTeaching.mockRejectedValueOnce(new Error("DB error")); + mockCreate.mockResolvedValueOnce(claudeResponse({ + explanation: "Fallback after error", + keyTakeaways: ["Key point"], + })); + + const res = await teachPost(makePost("/api/feynman/teach", { + topic: REAL_TOPIC, + topicId: REAL_TOPIC_ID, + })); + + expect(res.status).toBe(200); + expect(mockCreate).toHaveBeenCalledOnce(); + }); + + it("skips grounded path when topicId is absent", async () => { + mockCreate.mockResolvedValueOnce(claudeResponse({ + explanation: "Direct Claude response", + keyTakeaways: ["Point A"], + })); + + await teachPost(makePost("/api/feynman/teach", { topic: "Wave-particle duality" })); + + expect(mockGetGroundedTeaching).not.toHaveBeenCalled(); + expect(mockCreate).toHaveBeenCalledOnce(); + }); + + it("skips grounded path when topicId does not match any known topic", async () => { + mockCreate.mockResolvedValueOnce(claudeResponse({ + explanation: "Claude fallback for unknown topic ID", + keyTakeaways: ["Point B"], + })); + + const res = await teachPost(makePost("/api/feynman/teach", { + topic: "Some topic", + topicId: "nonexistent-topic-id-xyz", + })); + + expect(res.status).toBe(200); + // grounded path was skipped: getGroundedTeaching should not have been called + expect(mockGetGroundedTeaching).not.toHaveBeenCalled(); + expect(mockCreate).toHaveBeenCalledOnce(); + }); +}); + +describe("POST /api/feynman/teach — ungrounded (Claude) path", () => { + const MOCK_TEACH = { + explanation: "Gravity is the force that attracts two masses toward each other.", + keyTakeaways: ["Proportional to mass", "Inversely proportional to distance squared"], + }; + + it("returns 200 with explanation and keyTakeaways on success", async () => { + mockCreate.mockResolvedValueOnce(claudeResponse(MOCK_TEACH)); + + const res = await teachPost(makePost("/api/feynman/teach", { topic: "Gravity" })); + expect(res.status).toBe(200); + + const body = await json(res) as { + topic: string; + explanation: string; + keyTakeaways: string[]; + grounded: boolean; + sources: unknown[]; + }; + expect(body.topic).toBe("Gravity"); + expect(body.explanation).toBe(MOCK_TEACH.explanation); + expect(body.keyTakeaways).toHaveLength(2); + expect(body.grounded).toBe(false); + expect(body.sources).toEqual([]); + }); + + it("includes difficulty context in prompt when provided", async () => { + mockCreate.mockResolvedValueOnce(claudeResponse(MOCK_TEACH)); + + await teachPost(makePost("/api/feynman/teach", { + topic: "Quantum Computing", + difficulty: "intermediate", + })); + + const callArgs = mockCreate.mock.calls[0][0] as { messages: Array<{ content: string }> }; + expect(callArgs.messages[0].content).toContain("intermediate"); + }); + + it("uses claude-3-5-haiku model", async () => { + mockCreate.mockResolvedValueOnce(claudeResponse(MOCK_TEACH)); + + await teachPost(makePost("/api/feynman/teach", { topic: "Entropy" })); + + const callArgs = mockCreate.mock.calls[0][0] as { model: string }; + expect(callArgs.model).toContain("haiku"); + }); + + it("returns 500 when Claude returns invalid JSON", async () => { + mockCreate.mockResolvedValueOnce({ + content: [{ type: "text", text: "```json\nnot parseable\n```" }], + }); + + const res = await teachPost(makePost("/api/feynman/teach", { topic: "Relativity" })); + expect(res.status).toBe(500); + const body = await json(res) as { error: string }; + expect(body.error).toMatch(/Failed to generate teaching content/i); + }); + + it("returns 500 when Claude throws", async () => { + mockCreate.mockRejectedValueOnce(new Error("Rate limit exceeded")); + + const res = await teachPost(makePost("/api/feynman/teach", { topic: "Neutrinos" })); + expect(res.status).toBe(500); + const body = await json(res) as { details: string }; + expect(body.details).toContain("Rate limit exceeded"); + }); +}); + +// =========================================================================== +// POST /api/feynman/teach-deep +// =========================================================================== + +describe("POST /api/feynman/teach-deep — API key guard", () => { + it("returns 503 when ANTHROPIC_API_KEY is missing", async () => { + delete process.env.ANTHROPIC_API_KEY; + const res = await teachDeepPost(makePost("/api/feynman/teach-deep", { + topic: "Entropy", + previousExplanation: "Entropy is disorder.", + previousTakeaways: [], + })); + expect(res.status).toBe(503); + const body = await json(res) as { error: string }; + expect(body.error).toMatch(/ANTHROPIC_API_KEY/); + }); +}); + +describe("POST /api/feynman/teach-deep — input validation", () => { + it("returns 400 when topic is missing", async () => { + const res = await teachDeepPost(makePost("/api/feynman/teach-deep", { + previousExplanation: "Some explanation", + previousTakeaways: [], + })); + expect(res.status).toBe(400); + const body = await json(res) as { error: string }; + expect(body.error).toMatch(/topic/i); + }); + + it("returns 400 when previousExplanation is missing", async () => { + const res = await teachDeepPost(makePost("/api/feynman/teach-deep", { + topic: "Entropy", + previousTakeaways: [], + })); + expect(res.status).toBe(400); + const body = await json(res) as { error: string }; + expect(body.error).toMatch(/previousExplanation/i); + }); + + it("returns 400 when previousExplanation is not a string", async () => { + const res = await teachDeepPost(makePost("/api/feynman/teach-deep", { + topic: "Entropy", + previousExplanation: 123, + previousTakeaways: [], + })); + expect(res.status).toBe(400); + }); + + it("returns 400 on malformed JSON body", async () => { + const req = new NextRequest("http://localhost/api/feynman/teach-deep", { + method: "POST", + body: "{{bad", + headers: { "Content-Type": "application/json" }, + }); + const res = await teachDeepPost(req); + expect(res.status).toBe(400); + }); +}); + +describe("POST /api/feynman/teach-deep — success path", () => { + const MOCK_DEEP = { + deeperExplanation: "At a molecular level, entropy increases because...", + examples: [ + { title: "Ice melting", description: "When ice melts, the ordered crystal structure..." }, + { title: "Gas expansion", description: "Gas filling a container demonstrates..." }, + ], + analogy: "Think of entropy like a messy room that naturally gets messier.", + misconceptions: [ + { myth: "Entropy always increases everywhere", reality: "It increases in closed systems" }, + ], + connections: "Entropy connects to information theory via Shannon entropy.", + }; + + it("returns 200 with all expected fields", async () => { + mockCreate.mockResolvedValueOnce(claudeResponse(MOCK_DEEP)); + + const res = await teachDeepPost(makePost("/api/feynman/teach-deep", { + topic: "Entropy", + previousExplanation: "Entropy is a measure of disorder.", + previousTakeaways: ["Systems tend toward disorder"], + })); + + expect(res.status).toBe(200); + const body = await json(res) as typeof MOCK_DEEP & { topic: string }; + expect(body.topic).toBe("Entropy"); + expect(body.deeperExplanation).toBe(MOCK_DEEP.deeperExplanation); + expect(body.examples).toHaveLength(2); + expect(body.analogy).toBe(MOCK_DEEP.analogy); + expect(body.misconceptions).toHaveLength(1); + expect(typeof body.connections).toBe("string"); + }); + + it("includes both topic and previousExplanation in the Claude prompt", async () => { + mockCreate.mockResolvedValueOnce(claudeResponse(MOCK_DEEP)); + + await teachDeepPost(makePost("/api/feynman/teach-deep", { + topic: "Entropy", + previousExplanation: "Entropy measures disorder in a system.", + previousTakeaways: ["Closed systems tend to disorder"], + })); + + const callArgs = mockCreate.mock.calls[0][0] as { messages: Array<{ content: string }> }; + const prompt = callArgs.messages[0].content; + expect(prompt).toContain("Entropy"); + expect(prompt).toContain("Entropy measures disorder"); + }); + + it("includes previousTakeaways in the prompt when provided", async () => { + mockCreate.mockResolvedValueOnce(claudeResponse(MOCK_DEEP)); + + await teachDeepPost(makePost("/api/feynman/teach-deep", { + topic: "Thermodynamics", + previousExplanation: "Heat flows from hot to cold.", + previousTakeaways: ["Second law of thermodynamics", "Heat transfer direction"], + })); + + const callArgs = mockCreate.mock.calls[0][0] as { messages: Array<{ content: string }> }; + const prompt = callArgs.messages[0].content; + expect(prompt).toContain("Second law of thermodynamics"); + }); + + it("includes difficulty context in prompt when provided", async () => { + mockCreate.mockResolvedValueOnce(claudeResponse(MOCK_DEEP)); + + await teachDeepPost(makePost("/api/feynman/teach-deep", { + topic: "Entropy", + difficulty: "advanced", + previousExplanation: "Entropy is disorder.", + previousTakeaways: [], + })); + + const callArgs = mockCreate.mock.calls[0][0] as { messages: Array<{ content: string }> }; + expect(callArgs.messages[0].content).toContain("advanced"); + }); + + it("uses claude-3-5-haiku model", async () => { + mockCreate.mockResolvedValueOnce(claudeResponse(MOCK_DEEP)); + + await teachDeepPost(makePost("/api/feynman/teach-deep", { + topic: "Entropy", + previousExplanation: "Entropy is disorder.", + previousTakeaways: [], + })); + + const callArgs = mockCreate.mock.calls[0][0] as { model: string }; + expect(callArgs.model).toContain("haiku"); + }); + + it("echoes the topic field in the response", async () => { + mockCreate.mockResolvedValueOnce(claudeResponse(MOCK_DEEP)); + + const res = await teachDeepPost(makePost("/api/feynman/teach-deep", { + topic: "Dark Energy", + previousExplanation: "Dark energy drives cosmic expansion.", + previousTakeaways: [], + })); + + const body = await json(res) as { topic: string }; + expect(body.topic).toBe("Dark Energy"); + }); +}); + +describe("POST /api/feynman/teach-deep — Claude error handling", () => { + it("returns 500 when Claude returns invalid JSON", async () => { + mockCreate.mockResolvedValueOnce({ + content: [{ type: "text", text: "I cannot help with that." }], + }); + + const res = await teachDeepPost(makePost("/api/feynman/teach-deep", { + topic: "Entropy", + previousExplanation: "Entropy is disorder.", + previousTakeaways: [], + })); + + expect(res.status).toBe(500); + const body = await json(res) as { error: string }; + expect(body.error).toMatch(/Failed to generate deep teaching content/i); + }); + + it("returns 500 when Claude throws a network error", async () => { + mockCreate.mockRejectedValueOnce(new Error("Connection refused")); + + const res = await teachDeepPost(makePost("/api/feynman/teach-deep", { + topic: "Wave-Particle Duality", + previousExplanation: "Light behaves as both wave and particle.", + previousTakeaways: [], + })); + + expect(res.status).toBe(500); + const body = await json(res) as { details: string }; + expect(body.details).toContain("Connection refused"); + }); +}); diff --git a/src/app/api/feynman/__tests__/score.test.ts b/src/app/api/feynman/__tests__/score.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..3279155833e0ad2f9e655aaefa1ded2913e5f394 --- /dev/null +++ b/src/app/api/feynman/__tests__/score.test.ts @@ -0,0 +1,773 @@ +/** + * Tests for POST /api/feynman/score + * + * Covers: + * - API key guard (503) + * - Input validation: missing topic, missing explanation, invalid JSON + * - Claude mock integration: success, invalid JSON response, network error + * - XP calculation: normal, wasTaught (75% multiplier), isReview (50% multiplier) + * - Response shape: scores, gaps, feedback, xp breakdown, levelUp, categoryXp, unlocks + * - Spaced repetition side effects: addToReviewQueue (wasTaught), recordReview (isReview) + * - DB user-not-found (404) + * - Critical hit flag propagated in XP response + * - Multiplier integration + * - DailyLog: goal met logic + */ + +import { describe, it, expect, vi, beforeEach, afterEach } from "vitest"; +import { NextRequest } from "next/server"; + +// --------------------------------------------------------------------------- +// Mock Claude +// --------------------------------------------------------------------------- + +const mockCreate = vi.fn(); + +vi.mock("@/lib/claude", () => ({ + claude: { + messages: { + create: (...args: unknown[]) => mockCreate(...args), + }, + }, + parseClaudeJson: (text: string) => JSON.parse(text.trim().replace(/^```(?:json)?\s*/i, "").replace(/\s*```\s*$/, "").trim()), +})); + +// --------------------------------------------------------------------------- +// Mock Prisma +// --------------------------------------------------------------------------- + +const mockFindFirst = vi.fn(); +const mockTransaction = vi.fn(); +const mockActivityCreate = vi.fn(); +const mockUserUpdate = vi.fn(); +const mockCategorySkillUpdate = vi.fn(); +const mockDailyLogFindFirst = vi.fn(); +const mockDailyLogCreate = vi.fn(); +const mockDailyLogUpdate = vi.fn(); + +vi.mock("@/lib/db", () => ({ + prisma: { + user: { + findFirst: (...args: unknown[]) => mockFindFirst(...args), + }, + dailyLog: { + findFirst: (...args: unknown[]) => mockDailyLogFindFirst(...args), + }, + $transaction: (...args: unknown[]) => mockTransaction(...args), + }, +})); + +// --------------------------------------------------------------------------- +// Mock rollCriticalHit so XP results are deterministic +// --------------------------------------------------------------------------- + +const mockRollCriticalHit = vi.fn(() => false); + +vi.mock("@/lib/xp", async (importOriginal) => { + const actual = await importOriginal(); + return { + ...actual, + rollCriticalHit: () => mockRollCriticalHit(), + }; +}); + +// --------------------------------------------------------------------------- +// Mock getMultiplierPercent +// --------------------------------------------------------------------------- + +const mockGetMultiplierPercent = vi.fn(() => Promise.resolve(0)); + +vi.mock("@/lib/multiplier", () => ({ + getMultiplierPercent: (...args: unknown[]) => + (mockGetMultiplierPercent as (...a: unknown[]) => unknown)(...args), +})); + +// --------------------------------------------------------------------------- +// Mock processSkillUnlocks +// --------------------------------------------------------------------------- + +const mockProcessSkillUnlocks = vi.fn((): Promise<{ unlocked: string[]; streakFreezesGranted: number }> => + Promise.resolve({ unlocked: [], streakFreezesGranted: 0 }), +); + +vi.mock("@/lib/skill-unlock", () => ({ + processSkillUnlocks: (...args: unknown[]) => + (mockProcessSkillUnlocks as (...a: unknown[]) => unknown)(...args), +})); + +// --------------------------------------------------------------------------- +// Mock spaced repetition +// --------------------------------------------------------------------------- + +const mockAddToReviewQueue = vi.fn(() => Promise.resolve()); +const mockRecordReview = vi.fn(() => + Promise.resolve({ advanced: true, reset: false, completed: false, previousStage: 1, newStage: 2 }), +); + +vi.mock("@/lib/spaced-repetition", () => ({ + addToReviewQueue: (...args: unknown[]) => (mockAddToReviewQueue as (...a: unknown[]) => unknown)(...args), + recordReview: (...args: unknown[]) => (mockRecordReview as (...a: unknown[]) => unknown)(...args), + REVIEW_XP_MULTIPLIER: 0.5, +})); + +// --------------------------------------------------------------------------- +// Mock processEndOfDay (no-op — streak logic is tested separately) +// --------------------------------------------------------------------------- + +vi.mock("@/lib/streak", () => ({ + processEndOfDay: vi.fn(() => Promise.resolve({ + streak: 1, + freezeUsed: false, + streakBroken: false, + alreadyProcessed: false, + })), +})); + +// --------------------------------------------------------------------------- +// Import route (after mocks are hoisted) +// --------------------------------------------------------------------------- + +import { POST } from "../score/route"; + +// --------------------------------------------------------------------------- +// Helpers +// --------------------------------------------------------------------------- + +const originalEnv = { ...process.env }; + +function makePost(body?: Record): NextRequest { + return new NextRequest("http://localhost/api/feynman/score", { + method: "POST", + body: body !== undefined ? JSON.stringify(body) : undefined, + headers: { "Content-Type": "application/json" }, + }); +} + +async function json(res: Response): Promise { + return res.json(); +} + +function claudeScoreResponse(scores: { + accuracy: number; + completeness: number; + clarity: number; +}): object { + return { + content: [ + { + type: "text", + text: JSON.stringify({ + ...scores, + gaps: ["Missed the Calvin cycle", "No mention of light reactions"], + feedback: "Good start, needs more depth.", + }), + }, + ], + }; +} + +// Stub user with feynman CategorySkill +function makeUser(overrides: Record = {}) { + return { + id: 1, + name: "Player One", + level: 1, + totalXp: 0, + currentXp: 0, + xpToNextLevel: 100, + title: "Smooth Brain", + dailyGoalXp: 100, + streak: 3, + longestStreak: 10, + streakFreezes: 1, + lichessUsername: null, + chesscomUsername: null, + createdAt: new Date(), + categorySkills: [ + { + id: 1, + userId: 1, + category: "feynman", + level: 1, + totalXp: 0, + currentXp: 0, + xpToNext: 100, + }, + ], + ...overrides, + }; +} + +// Set up the $transaction mock to call the callback with a mock tx object +function setupTransaction() { + mockTransaction.mockImplementation( + async (callback: (tx: Record) => Promise) => { + const tx = { + activity: { create: mockActivityCreate }, + user: { update: mockUserUpdate }, + categorySkill: { update: mockCategorySkillUpdate }, + dailyLog: { + create: mockDailyLogCreate, + update: mockDailyLogUpdate, + }, + }; + return callback(tx); + }, + ); +} + +beforeEach(() => { + vi.clearAllMocks(); + process.env = { ...originalEnv, ANTHROPIC_API_KEY: "test-key" }; + + // Default: user found, no daily log, no critical hit, no multiplier + mockFindFirst.mockResolvedValue(makeUser()); + mockDailyLogFindFirst.mockResolvedValue(null); + mockRollCriticalHit.mockReturnValue(false); + mockGetMultiplierPercent.mockResolvedValue(0); + setupTransaction(); + mockActivityCreate.mockResolvedValue({}); + mockUserUpdate.mockResolvedValue({}); + mockCategorySkillUpdate.mockResolvedValue({}); + mockDailyLogCreate.mockResolvedValue({}); + mockDailyLogUpdate.mockResolvedValue({}); + mockProcessSkillUnlocks.mockResolvedValue({ unlocked: [], streakFreezesGranted: 0 }); + mockAddToReviewQueue.mockResolvedValue(undefined); + mockRecordReview.mockResolvedValue({ + advanced: true, + reset: false, + completed: false, + previousStage: 1, + newStage: 2, + }); +}); + +afterEach(() => { + process.env = originalEnv; +}); + +// =========================================================================== +// API key guard +// =========================================================================== + +describe("POST /api/feynman/score — API key guard", () => { + it("returns 503 when ANTHROPIC_API_KEY is not set", async () => { + delete process.env.ANTHROPIC_API_KEY; + const res = await POST(makePost({ topic: "Photosynthesis", explanation: "Plants use sunlight" })); + expect(res.status).toBe(503); + const body = await json(res) as { error: string }; + expect(body.error).toMatch(/ANTHROPIC_API_KEY/); + }); + + it("returns 503 when ANTHROPIC_API_KEY is empty string", async () => { + process.env.ANTHROPIC_API_KEY = ""; + const res = await POST(makePost({ topic: "Gravity", explanation: "Things fall down" })); + expect(res.status).toBe(503); + }); + + it("does not call Claude when key is missing", async () => { + delete process.env.ANTHROPIC_API_KEY; + await POST(makePost({ topic: "Topic", explanation: "Explanation" })); + expect(mockCreate).not.toHaveBeenCalled(); + }); +}); + +// =========================================================================== +// Input validation +// =========================================================================== + +describe("POST /api/feynman/score — input validation", () => { + it("returns 400 when topic is missing", async () => { + const res = await POST(makePost({ explanation: "Some text" })); + expect(res.status).toBe(400); + const body = await json(res) as { error: string }; + expect(body.error).toMatch(/topic/i); + }); + + it("returns 400 when topic is not a string", async () => { + const res = await POST(makePost({ topic: 123, explanation: "Some text" })); + expect(res.status).toBe(400); + }); + + it("returns 400 when explanation is missing", async () => { + const res = await POST(makePost({ topic: "Photosynthesis" })); + expect(res.status).toBe(400); + const body = await json(res) as { error: string }; + expect(body.error).toMatch(/explanation/i); + }); + + it("returns 400 when explanation is not a string", async () => { + const res = await POST(makePost({ topic: "Photosynthesis", explanation: 999 })); + expect(res.status).toBe(400); + }); + + it("returns 400 for invalid JSON body", async () => { + const req = new NextRequest("http://localhost/api/feynman/score", { + method: "POST", + body: "NOT_JSON{{{", + headers: { "Content-Type": "application/json" }, + }); + const res = await POST(req); + expect(res.status).toBe(400); + }); +}); + +// =========================================================================== +// Claude integration +// =========================================================================== + +describe("POST /api/feynman/score — Claude integration", () => { + it("calls Claude with the topic and explanation in the prompt", async () => { + mockCreate.mockResolvedValue(claudeScoreResponse({ accuracy: 8, completeness: 7, clarity: 9 })); + await POST(makePost({ topic: "Photosynthesis", explanation: "Plants make food from sunlight" })); + expect(mockCreate).toHaveBeenCalledOnce(); + const call = mockCreate.mock.calls[0][0] as { messages: { content: string }[] }; + const content = call.messages[0].content; + expect(content).toContain("Photosynthesis"); + expect(content).toContain("Plants make food from sunlight"); + }); + + it("uses claude-3-5-haiku model", async () => { + mockCreate.mockResolvedValue(claudeScoreResponse({ accuracy: 8, completeness: 7, clarity: 9 })); + await POST(makePost({ topic: "Gravity", explanation: "Mass warps spacetime" })); + const call = mockCreate.mock.calls[0][0] as { model: string }; + expect(call.model).toContain("haiku"); + }); + + it("returns 500 when Claude returns invalid JSON", async () => { + mockCreate.mockResolvedValue({ + content: [{ type: "text", text: "NOT VALID JSON" }], + }); + const res = await POST(makePost({ topic: "DNA", explanation: "Double helix" })); + expect(res.status).toBe(500); + const body = await json(res) as { error: string }; + expect(body.error).toMatch(/evaluate/i); + }); + + it("returns 500 on Claude network error", async () => { + mockCreate.mockRejectedValue(new Error("Network timeout")); + const res = await POST(makePost({ topic: "Evolution", explanation: "Natural selection" })); + expect(res.status).toBe(500); + }); + + it("passes wasTaught context to Claude prompt", async () => { + mockCreate.mockResolvedValue(claudeScoreResponse({ accuracy: 7, completeness: 6, clarity: 8 })); + await POST(makePost({ topic: "Entropy", explanation: "Disorder increases", wasTaught: true })); + const call = mockCreate.mock.calls[0][0] as { messages: { content: string }[] }; + expect(call.messages[0].content).toMatch(/taught/i); + }); +}); + +// =========================================================================== +// Response shape (success path) +// =========================================================================== + +describe("POST /api/feynman/score — response shape", () => { + beforeEach(() => { + mockCreate.mockResolvedValue(claudeScoreResponse({ accuracy: 8, completeness: 7, clarity: 9 })); + }); + + it("returns 200 on success", async () => { + const res = await POST(makePost({ topic: "Gravity", explanation: "Mass attracts mass" })); + expect(res.status).toBe(200); + }); + + it("includes scores object with accuracy, completeness, clarity", async () => { + const res = await POST(makePost({ topic: "Gravity", explanation: "Mass attracts mass" })); + const body = await json(res) as { scores: { accuracy: number; completeness: number; clarity: number } }; + expect(body.scores.accuracy).toBe(8); + expect(body.scores.completeness).toBe(7); + expect(body.scores.clarity).toBe(9); + }); + + it("includes gaps and feedback from Claude", async () => { + const res = await POST(makePost({ topic: "Gravity", explanation: "Mass attracts mass" })); + const body = await json(res) as { gaps: string[]; feedback: string }; + expect(Array.isArray(body.gaps)).toBe(true); + expect(typeof body.feedback).toBe("string"); + }); + + it("includes xp breakdown with baseXp, qualityBonus, totalXp, isCriticalHit", async () => { + const res = await POST(makePost({ topic: "DNA", explanation: "Genetic blueprint" })); + const body = await json(res) as { xp: { baseXp: number; qualityBonus: number; totalXp: number; isCriticalHit: boolean } }; + expect(typeof body.xp.baseXp).toBe("number"); + expect(typeof body.xp.qualityBonus).toBe("number"); + expect(typeof body.xp.totalXp).toBe("number"); + expect(typeof body.xp.isCriticalHit).toBe("boolean"); + }); + + it("includes levelUp boolean and categoryXp object", async () => { + const res = await POST(makePost({ topic: "DNA", explanation: "Genetic blueprint" })); + const body = await json(res) as { levelUp: boolean; categoryXp: { currentXp: number; xpToNext: number; level: number; levelUp: boolean } }; + expect(typeof body.levelUp).toBe("boolean"); + expect(typeof body.categoryXp.currentXp).toBe("number"); + expect(typeof body.categoryXp.level).toBe("number"); + expect(typeof body.categoryXp.levelUp).toBe("boolean"); + }); + + it("includes unlocks and streakFreezesGranted", async () => { + const res = await POST(makePost({ topic: "Optics", explanation: "Light refracts" })); + const body = await json(res) as { unlocks: string[]; streakFreezesGranted: number }; + expect(Array.isArray(body.unlocks)).toBe(true); + expect(typeof body.streakFreezesGranted).toBe("number"); + }); + + it("includes wasTaught=false when not provided", async () => { + const res = await POST(makePost({ topic: "Optics", explanation: "Light refracts" })); + const body = await json(res) as { wasTaught: boolean }; + expect(body.wasTaught).toBe(false); + }); + + it("includes isReview=false when not provided", async () => { + const res = await POST(makePost({ topic: "Optics", explanation: "Light refracts" })); + const body = await json(res) as { isReview: boolean }; + expect(body.isReview).toBe(false); + }); +}); + +// =========================================================================== +// XP calculations +// =========================================================================== + +describe("POST /api/feynman/score — XP calculations", () => { + it("uses full baseXp (40) for a normal explanation", async () => { + mockCreate.mockResolvedValue(claudeScoreResponse({ accuracy: 0, completeness: 0, clarity: 0 })); + const res = await POST(makePost({ topic: "Inertia", explanation: "Objects stay still" })); + const body = await json(res) as { xp: { baseXp: number } }; + // EXERCISE_XP.feynman.baseXp = 40 + expect(body.xp.baseXp).toBe(40); + }); + + it("applies 75% multiplier for wasTaught=true", async () => { + mockCreate.mockResolvedValue(claudeScoreResponse({ accuracy: 0, completeness: 0, clarity: 0 })); + const res = await POST(makePost({ topic: "Relativity", explanation: "Time slows near mass", wasTaught: true })); + const body = await json(res) as { xp: { baseXp: number } }; + // 40 * 0.75 = 30 + expect(body.xp.baseXp).toBe(30); + }); + + it("applies 50% multiplier for isReview=true", async () => { + mockCreate.mockResolvedValue(claudeScoreResponse({ accuracy: 0, completeness: 0, clarity: 0 })); + const res = await POST(makePost({ topic: "Entropy", explanation: "Disorder increases", isReview: true, topicId: "entropy-1" })); + const body = await json(res) as { xp: { baseXp: number } }; + // 40 * 0.5 = 20 + expect(body.xp.baseXp).toBe(20); + }); + + it("baseXp is higher for normal vs wasTaught vs isReview", async () => { + mockCreate.mockResolvedValue(claudeScoreResponse({ accuracy: 0, completeness: 0, clarity: 0 })); + + const normalRes = await POST(makePost({ topic: "Topic", explanation: "Text" })); + const taughtRes = await POST(makePost({ topic: "Topic", explanation: "Text", wasTaught: true })); + const reviewRes = await POST(makePost({ topic: "Topic", explanation: "Text", isReview: true, topicId: "t1" })); + + const normalXp = (await json(normalRes) as { xp: { baseXp: number } }).xp.baseXp; + const taughtXp = (await json(taughtRes) as { xp: { baseXp: number } }).xp.baseXp; + const reviewXp = (await json(reviewRes) as { xp: { baseXp: number } }).xp.baseXp; + + expect(normalXp).toBeGreaterThan(taughtXp); + expect(taughtXp).toBeGreaterThan(reviewXp); + }); + + it("qualityBonus is 0 when all scores are 0", async () => { + mockCreate.mockResolvedValue(claudeScoreResponse({ accuracy: 0, completeness: 0, clarity: 0 })); + const res = await POST(makePost({ topic: "Wave", explanation: "Ups and downs" })); + const body = await json(res) as { xp: { qualityBonus: number } }; + expect(body.xp.qualityBonus).toBe(0); + }); + + it("qualityBonus is maxed when all scores are 10", async () => { + mockCreate.mockResolvedValue(claudeScoreResponse({ accuracy: 10, completeness: 10, clarity: 10 })); + const res = await POST(makePost({ topic: "Wave", explanation: "Great explanation here" })); + const body = await json(res) as { xp: { qualityBonus: number; baseXp: number; totalXp: number } }; + // max bonus = 40, quality score = 30/30 = 1.0 + expect(body.xp.qualityBonus).toBe(40); + expect(body.xp.totalXp).toBe(body.xp.baseXp + body.xp.qualityBonus); + }); + + it("reports isCriticalHit=true when rollCriticalHit returns true", async () => { + mockCreate.mockResolvedValue(claudeScoreResponse({ accuracy: 5, completeness: 5, clarity: 5 })); + mockRollCriticalHit.mockReturnValueOnce(true); + const res = await POST(makePost({ topic: "Force", explanation: "F=ma" })); + const body = await json(res) as { xp: { isCriticalHit: boolean; totalXp: number; baseXp: number; qualityBonus: number } }; + expect(body.xp.isCriticalHit).toBe(true); + // Total should be double the pre-crit amount + expect(body.xp.totalXp).toBe((body.xp.baseXp + body.xp.qualityBonus) * 2); + }); + + it("includes multiplierBonus and multiplierPercent from skill tree", async () => { + mockCreate.mockResolvedValue(claudeScoreResponse({ accuracy: 0, completeness: 0, clarity: 0 })); + mockGetMultiplierPercent.mockResolvedValue(10); + const res = await POST(makePost({ topic: "Logic", explanation: "Deduction" })); + const body = await json(res) as { xp: { multiplierPercent: number; multiplierBonus: number } }; + expect(body.xp.multiplierPercent).toBe(10); + expect(body.xp.multiplierBonus).toBeGreaterThan(0); + }); +}); + +// =========================================================================== +// DB path: user not found +// =========================================================================== + +describe("POST /api/feynman/score — DB: user not found", () => { + it("returns 404 when user is not in the DB", async () => { + mockCreate.mockResolvedValue(claudeScoreResponse({ accuracy: 5, completeness: 5, clarity: 5 })); + mockFindFirst.mockResolvedValue(null); + const res = await POST(makePost({ topic: "Atoms", explanation: "Protons neutrons electrons" })); + expect(res.status).toBe(404); + const body = await json(res) as { error: string }; + expect(body.error).toMatch(/user/i); + }); + + it("returns 500 when feynman CategorySkill is missing", async () => { + mockCreate.mockResolvedValue(claudeScoreResponse({ accuracy: 5, completeness: 5, clarity: 5 })); + mockFindFirst.mockResolvedValue(makeUser({ categorySkills: [] })); + const res = await POST(makePost({ topic: "Atoms", explanation: "Small particles" })); + expect(res.status).toBe(500); + }); +}); + +// =========================================================================== +// Spaced repetition side effects +// =========================================================================== + +describe("POST /api/feynman/score — spaced repetition", () => { + beforeEach(() => { + mockCreate.mockResolvedValue(claudeScoreResponse({ accuracy: 7, completeness: 6, clarity: 8 })); + }); + + it("calls addToReviewQueue when wasTaught=true with topicId", async () => { + await POST(makePost({ + topic: "Brownian Motion", + explanation: "Particles move randomly", + wasTaught: true, + topicId: "brownian-1", + domain: "physics", + difficulty: "intermediate", + })); + expect(mockAddToReviewQueue).toHaveBeenCalledOnce(); + const calls = mockAddToReviewQueue.mock.calls as unknown[][]; + const call = calls[0][0] as { + topicId: string; topic: string; domain: string; difficulty: string; + }; + expect(call.topicId).toBe("brownian-1"); + expect(call.topic).toBe("Brownian Motion"); + }); + + it("does not call addToReviewQueue when wasTaught=true but topicId is missing", async () => { + await POST(makePost({ + topic: "Brownian Motion", + explanation: "Particles move randomly", + wasTaught: true, + })); + // No topicId → review queue is skipped + expect(mockAddToReviewQueue).not.toHaveBeenCalled(); + }); + + it("does not call addToReviewQueue for a normal explanation", async () => { + await POST(makePost({ topic: "Osmosis", explanation: "Water crosses membranes" })); + expect(mockAddToReviewQueue).not.toHaveBeenCalled(); + }); + + it("calls recordReview when isReview=true with topicId", async () => { + await POST(makePost({ + topic: "Brownian Motion", + explanation: "Random particle movement", + isReview: true, + topicId: "brownian-1", + })); + expect(mockRecordReview).toHaveBeenCalledOnce(); + const reviewCalls = mockRecordReview.mock.calls as unknown[][]; + const [userId, topicId] = reviewCalls[0]; + expect(userId).toBe(1); + expect(topicId).toBe("brownian-1"); + }); + + it("includes review result in response when isReview=true", async () => { + mockRecordReview.mockResolvedValue({ + advanced: true, + reset: false, + completed: false, + previousStage: 2, + newStage: 3, + }); + const res = await POST(makePost({ + topic: "Entropy", + explanation: "Disorder grows", + isReview: true, + topicId: "entropy-1", + })); + const body = await json(res) as { + isReview: boolean; + review: { advanced: boolean; newStage: number; previousStage: number }; + }; + expect(body.isReview).toBe(true); + expect(body.review.advanced).toBe(true); + expect(body.review.newStage).toBe(3); + expect(body.review.previousStage).toBe(2); + }); + + it("does not call recordReview when isReview=true but topicId is missing", async () => { + await POST(makePost({ + topic: "Entropy", + explanation: "Disorder grows", + isReview: true, + })); + expect(mockRecordReview).not.toHaveBeenCalled(); + }); + + it("review result is null for normal explanations", async () => { + const res = await POST(makePost({ topic: "Entropy", explanation: "Disorder grows" })); + const body = await json(res) as { review: null }; + expect(body.review).toBeNull(); + }); + + it("continues gracefully if addToReviewQueue throws", async () => { + mockAddToReviewQueue.mockRejectedValueOnce(new Error("DB error")); + const res = await POST(makePost({ + topic: "Optics", + explanation: "Light bends", + wasTaught: true, + topicId: "optics-1", + })); + // Should still return 200 — review queue failure is non-fatal + expect(res.status).toBe(200); + }); + + it("continues gracefully if recordReview throws", async () => { + mockRecordReview.mockRejectedValueOnce(new Error("DB error")); + const res = await POST(makePost({ + topic: "Optics", + explanation: "Light bends", + isReview: true, + topicId: "optics-1", + })); + expect(res.status).toBe(200); + }); +}); + +// =========================================================================== +// DailyLog and goal tracking +// =========================================================================== + +describe("POST /api/feynman/score — DailyLog", () => { + beforeEach(() => { + mockCreate.mockResolvedValue(claudeScoreResponse({ accuracy: 5, completeness: 5, clarity: 5 })); + }); + + it("creates a new DailyLog when none exists", async () => { + mockDailyLogFindFirst.mockResolvedValue(null); + await POST(makePost({ topic: "Cells", explanation: "Basic unit of life" })); + expect(mockDailyLogCreate).toHaveBeenCalledOnce(); + }); + + it("updates existing DailyLog when one already exists", async () => { + mockDailyLogFindFirst.mockResolvedValue({ + id: 99, + userId: 1, + xpEarned: 50, + activityCount: 2, + goalMet: false, + }); + await POST(makePost({ topic: "Cells", explanation: "Basic unit of life" })); + expect(mockDailyLogUpdate).toHaveBeenCalledOnce(); + expect(mockDailyLogCreate).not.toHaveBeenCalled(); + }); + + it("marks goalMet=true when XP meets daily goal", async () => { + // User dailyGoalXp = 100; pretend already 95 XP today + score 0 (min xp ~40) + mockDailyLogFindFirst.mockResolvedValue({ + id: 5, + userId: 1, + xpEarned: 95, + activityCount: 3, + goalMet: false, + }); + await POST(makePost({ topic: "Cells", explanation: "Basic unit of life" })); + const updateCall = mockDailyLogUpdate.mock.calls[0][0] as { data: { goalMet: boolean } }; + expect(updateCall.data.goalMet).toBe(true); + }); +}); + +// =========================================================================== +// Unlock notifications +// =========================================================================== + +describe("POST /api/feynman/score — skill unlocks", () => { + it("includes newly unlocked nodes in response", async () => { + mockCreate.mockResolvedValue(claudeScoreResponse({ accuracy: 10, completeness: 10, clarity: 10 })); + // Simulate category level-up → unlocks trigger + const user = makeUser({ currentXp: 99, xpToNextLevel: 100 }); + user.categorySkills[0].currentXp = 99; + user.categorySkills[0].xpToNext = 100; + mockFindFirst.mockResolvedValue(user); + mockProcessSkillUnlocks.mockResolvedValue({ + unlocked: ["Explainer", "Timed Explains"], + streakFreezesGranted: 1, + }); + + const res = await POST(makePost({ topic: "Waves", explanation: "Oscillating disturbance" })); + const body = await json(res) as { unlocks: string[]; streakFreezesGranted: number }; + expect(body.unlocks).toContain("Explainer"); + expect(body.unlocks).toContain("Timed Explains"); + expect(body.streakFreezesGranted).toBe(1); + }); + + it("returns empty unlocks when no level-up occurs", async () => { + mockCreate.mockResolvedValue(claudeScoreResponse({ accuracy: 2, completeness: 2, clarity: 2 })); + const res = await POST(makePost({ topic: "Momentum", explanation: "Mass times velocity" })); + const body = await json(res) as { unlocks: string[] }; + expect(body.unlocks).toHaveLength(0); + // processSkillUnlocks should not be called if no category level-up + expect(mockProcessSkillUnlocks).not.toHaveBeenCalled(); + }); +}); + +// =========================================================================== +// durationSecs persistence +// =========================================================================== + +describe("POST /api/feynman/score — durationSecs", () => { + beforeEach(() => { + mockCreate.mockResolvedValue(claudeScoreResponse({ accuracy: 5, completeness: 5, clarity: 5 })); + setupTransaction(); + }); + + it("persists durationSecs when provided", async () => { + await POST( + makePost({ topic: "Entropy", explanation: "Disorder increases over time", durationSecs: 90 }), + ); + const createCall = mockActivityCreate.mock.calls[0][0] as { data: { durationSecs: number | null } }; + expect(createCall.data.durationSecs).toBe(90); + }); + + it("rounds durationSecs to nearest integer", async () => { + await POST( + makePost({ topic: "Entropy", explanation: "Disorder increases over time", durationSecs: 45.7 }), + ); + const createCall = mockActivityCreate.mock.calls[0][0] as { data: { durationSecs: number | null } }; + expect(createCall.data.durationSecs).toBe(46); + }); + + it("persists null when durationSecs is omitted", async () => { + await POST(makePost({ topic: "Entropy", explanation: "Disorder increases over time" })); + const createCall = mockActivityCreate.mock.calls[0][0] as { data: { durationSecs: number | null } }; + expect(createCall.data.durationSecs).toBeNull(); + }); + + it("persists null when durationSecs is negative", async () => { + await POST( + makePost({ topic: "Entropy", explanation: "Disorder increases over time", durationSecs: -5 }), + ); + const createCall = mockActivityCreate.mock.calls[0][0] as { data: { durationSecs: number | null } }; + expect(createCall.data.durationSecs).toBeNull(); + }); + + it("accepts durationSecs of 0 (instant submit)", async () => { + await POST( + makePost({ topic: "Entropy", explanation: "Disorder increases over time", durationSecs: 0 }), + ); + const createCall = mockActivityCreate.mock.calls[0][0] as { data: { durationSecs: number | null } }; + expect(createCall.data.durationSecs).toBe(0); + }); +}); diff --git a/src/app/api/feynman/__tests__/supporting.test.ts b/src/app/api/feynman/__tests__/supporting.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..f0e848d907fe8069802b8e5c59ab40f21c080205 --- /dev/null +++ b/src/app/api/feynman/__tests__/supporting.test.ts @@ -0,0 +1,669 @@ +/** + * Tests for supporting Feynman API route handlers: + * + * GET /api/feynman/calibrate + * - returns topics array with prereq enrichment + * - returns suggestions array + * - returns profile summary + * - domain filter passed through to getCalibratedTopics + * - count clamped: min 1, max 10 + * - each topic includes prereqs.ready, met, unmet, chain + * - DB errors propagate as 500 + * + * GET /api/feynman/review + * - default: returns dueCount + items array + * - summary=1: returns full summary (total, dueCount, dueItems, upcomingItems, retainedItems) + * - items include stageLabel and nextInterval from stageLabel()/intervalLabel() + * - userId param defaults to 1 + * - DB errors propagate as 500 + * + * POST /api/feynman/curate + * - 400 for invalid JSON body + * - 400 for missing topicId + * - 404 for unknown topicId + * - returns sources, sourceCount, sourceReady, minRequired + * - sourceReady true when sources.length >= MIN_SOURCES + * - sourceReady false when sources.length < MIN_SOURCES + * - grounded=false: no teaching content, no Claude guard + * - grounded=true + no API key: 503 (before curateSources) + * - grounded=true + sufficient sources: generates teaching content + * - grounded=true + insufficient sources: no teaching in response + * - DB errors propagate as 500 + * + * POST /api/feynman/verify (and GET /api/feynman/verify) + * - GET: returns health summary without running verification + * - POST: runs verification and returns { verification, health } + * - POST: optional limit param respected (capped at 200) + * - POST: empty body is fine (uses defaults) + * - DB errors propagate as 500 + */ + +import { describe, it, expect, vi, beforeEach, afterEach } from "vitest"; +import { NextRequest } from "next/server"; + +// --------------------------------------------------------------------------- +// Mock dependencies for calibrate +// --------------------------------------------------------------------------- + +const mockGetKnowledgeProfile = vi.fn(); +const mockGetCalibratedTopics = vi.fn(); +const mockCheckPrerequisites = vi.fn(); +const mockGetSuggestedPrerequisites = vi.fn(); + +vi.mock("@/lib/feynman/knowledge-profile", () => ({ + getKnowledgeProfile: (...args: unknown[]) => mockGetKnowledgeProfile(...args), + getCalibratedTopics: (...args: unknown[]) => mockGetCalibratedTopics(...args), +})); + +vi.mock("@/lib/feynman/prerequisites", () => ({ + checkPrerequisites: (...args: unknown[]) => mockCheckPrerequisites(...args), + getSuggestedPrerequisites: (...args: unknown[]) => mockGetSuggestedPrerequisites(...args), +})); + +// --------------------------------------------------------------------------- +// Mock dependencies for review +// --------------------------------------------------------------------------- + +const mockGetDueReviews = vi.fn(); +const mockGetReviewSummary = vi.fn(); + +vi.mock("@/lib/spaced-repetition", () => ({ + getDueReviews: (...args: unknown[]) => mockGetDueReviews(...args), + getReviewSummary: (...args: unknown[]) => mockGetReviewSummary(...args), + stageLabel: (stage: number) => `Stage ${stage}`, + intervalLabel: (stage: number) => `${stage + 1} days`, +})); + +// --------------------------------------------------------------------------- +// Mock dependencies for curate +// --------------------------------------------------------------------------- + +const mockCurateSources = vi.fn(); +const mockGetGroundedTeaching = vi.fn(); + +vi.mock("@/lib/sources/curate", () => ({ + curateSources: (...args: unknown[]) => mockCurateSources(...args), + getGroundedTeaching: (...args: unknown[]) => mockGetGroundedTeaching(...args), + MIN_SOURCES: 2, +})); + +// --------------------------------------------------------------------------- +// Mock dependencies for verify +// --------------------------------------------------------------------------- + +const mockRunVerification = vi.fn(); +const mockGetSourceHealthSummary = vi.fn(); + +vi.mock("@/lib/sources/verify", () => ({ + runVerification: (...args: unknown[]) => mockRunVerification(...args), + getSourceHealthSummary: (...args: unknown[]) => mockGetSourceHealthSummary(...args), +})); + +// --------------------------------------------------------------------------- +// Import handlers after mocks +// --------------------------------------------------------------------------- + +import { GET as getCalibrateRoute } from "../calibrate/route"; +import { GET as getReviewRoute } from "../review/route"; +import { POST as postCurateRoute } from "../curate/route"; +import { POST as postVerifyRoute, GET as getVerifyRoute } from "../verify/route"; + +// --------------------------------------------------------------------------- +// Helpers +// --------------------------------------------------------------------------- + +const originalEnv = { ...process.env }; + +function makeGet(path: string, params?: Record): NextRequest { + const url = new URL(`http://localhost${path}`); + if (params) { + for (const [k, v] of Object.entries(params)) { + url.searchParams.set(k, v); + } + } + return new NextRequest(url); +} + +function makePost(path: string, body?: unknown): NextRequest { + return new NextRequest(`http://localhost${path}`, { + method: "POST", + body: body !== undefined ? JSON.stringify(body) : undefined, + headers: { "Content-Type": "application/json" }, + }); +} + +async function json(res: Response): Promise { + return res.json(); +} + +// --------------------------------------------------------------------------- +// Fixtures +// --------------------------------------------------------------------------- + +const baseProfile = { + totalAttempts: 5, + recommendedDifficulty: "intermediate" as const, + domains: new Map([ + ["Physics", { attempts: 3, avgScore: 0.7, masteredTopics: ["phys-001"] }], + ]), +}; + +const baseTopic = { + id: "phys-002", + topic: "Quantum Entanglement", + domain: "Physics", + difficulty: "intermediate" as const, +}; + +const basePrereqInfo = { + ready: true, + met: [], + unmet: [], + chain: [], +}; + +// --------------------------------------------------------------------------- +// Tests — GET /api/feynman/calibrate +// --------------------------------------------------------------------------- + +describe("GET /api/feynman/calibrate", () => { + beforeEach(() => { + vi.clearAllMocks(); + process.env = { ...originalEnv }; + mockGetKnowledgeProfile.mockResolvedValue(baseProfile); + mockGetCalibratedTopics.mockReturnValue([baseTopic]); + mockCheckPrerequisites.mockReturnValue(basePrereqInfo); + mockGetSuggestedPrerequisites.mockReturnValue([]); + }); + + afterEach(() => { + process.env = originalEnv; + }); + + it("returns 200 with topics, suggestions, and profile", async () => { + const res = await getCalibrateRoute(makeGet("/api/feynman/calibrate")); + expect(res.status).toBe(200); + + const body = await json(res) as Record; + expect(body).toHaveProperty("topics"); + expect(body).toHaveProperty("suggestions"); + expect(body).toHaveProperty("profile"); + }); + + it("enriches each topic with prereqs object", async () => { + const res = await getCalibrateRoute(makeGet("/api/feynman/calibrate")); + const body = await json(res) as Record; + const topics = body.topics as Array>; + + expect(topics).toHaveLength(1); + const topic = topics[0]; + expect(topic).toHaveProperty("prereqs"); + const prereqs = topic.prereqs as Record; + expect(prereqs).toHaveProperty("ready"); + expect(prereqs).toHaveProperty("met"); + expect(prereqs).toHaveProperty("unmet"); + expect(prereqs).toHaveProperty("chain"); + expect(prereqs.ready).toBe(true); + }); + + it("passes domain param to getCalibratedTopics", async () => { + await getCalibrateRoute(makeGet("/api/feynman/calibrate", { domain: "Physics" })); + expect(mockGetCalibratedTopics).toHaveBeenCalledWith( + expect.anything(), + "Physics", + expect.any(Number), + ); + }); + + it("passes count param to getCalibratedTopics", async () => { + await getCalibrateRoute(makeGet("/api/feynman/calibrate", { count: "5" })); + const call = mockGetCalibratedTopics.mock.calls[0] as unknown[]; + expect(call[2]).toBe(5); + }); + + it("clamps count to min 1 (negative value)", async () => { + await getCalibrateRoute(makeGet("/api/feynman/calibrate", { count: "-5" })); + const call = mockGetCalibratedTopics.mock.calls[0] as unknown[]; + expect(call[2]).toBe(1); + }); + + it("clamps count to max 10", async () => { + await getCalibrateRoute(makeGet("/api/feynman/calibrate", { count: "99" })); + const call = mockGetCalibratedTopics.mock.calls[0] as unknown[]; + expect(call[2]).toBe(10); + }); + + it("defaults count to 3 when not provided", async () => { + await getCalibrateRoute(makeGet("/api/feynman/calibrate")); + const call = mockGetCalibratedTopics.mock.calls[0] as unknown[]; + expect(call[2]).toBe(3); + }); + + it("includes profile summary with totalAttempts and domains", async () => { + const res = await getCalibrateRoute(makeGet("/api/feynman/calibrate")); + const body = await json(res) as Record; + const profile = body.profile as Record; + + expect(profile.totalAttempts).toBe(5); + expect(profile.recommendedDifficulty).toBe("intermediate"); + expect(profile).toHaveProperty("domains"); + }); + + it("maps mastered topics from profile domains to suggestions", async () => { + mockGetSuggestedPrerequisites.mockReturnValue([ + { id: "phys-001", topic: "Classical Mechanics", domain: "Physics", difficulty: "beginner" }, + ]); + + const res = await getCalibrateRoute(makeGet("/api/feynman/calibrate")); + const body = await json(res) as Record; + const suggestions = body.suggestions as Array>; + + expect(suggestions).toHaveLength(1); + expect(suggestions[0]).toMatchObject({ id: "phys-001", topic: "Classical Mechanics" }); + }); + + it("propagates errors as 500", async () => { + mockGetKnowledgeProfile.mockRejectedValue(new Error("DB error")); + const res = await getCalibrateRoute(makeGet("/api/feynman/calibrate")); + expect(res.status).toBe(500); + }); +}); + +// --------------------------------------------------------------------------- +// Tests — GET /api/feynman/review +// --------------------------------------------------------------------------- + +describe("GET /api/feynman/review", () => { + beforeEach(() => { + vi.clearAllMocks(); + mockGetDueReviews.mockResolvedValue([]); + mockGetReviewSummary.mockResolvedValue({ + total: 0, + dueCount: 0, + upcomingCount: 0, + retainedCount: 0, + dueItems: [], + upcomingItems: [], + retainedItems: [], + }); + }); + + it("returns dueCount and items array by default", async () => { + mockGetDueReviews.mockResolvedValue([ + { + id: 1, + topicId: "phys-002", + topic: "Quantum Entanglement", + domain: "Physics", + difficulty: "intermediate", + stage: 2, + lastScore: 0.8, + totalReviews: 3, + successCount: 2, + }, + ]); + + const res = await getReviewRoute(makeGet("/api/feynman/review")); + expect(res.status).toBe(200); + + const body = await json(res) as Record; + expect(body).toHaveProperty("dueCount"); + expect(body).toHaveProperty("items"); + expect(body.dueCount).toBe(1); + + const items = body.items as Array>; + expect(items[0]).toMatchObject({ + id: 1, + topicId: "phys-002", + topic: "Quantum Entanglement", + domain: "Physics", + difficulty: "intermediate", + stage: 2, + lastScore: 0.8, + totalReviews: 3, + }); + expect(items[0]).toHaveProperty("stageLabel"); + expect(items[0]).toHaveProperty("nextInterval"); + }); + + it("returns summary when summary=1", async () => { + mockGetReviewSummary.mockResolvedValue({ + total: 10, + dueCount: 2, + upcomingCount: 5, + retainedCount: 3, + dueItems: [ + { + id: 1, + topicId: "phys-002", + topic: "Quantum Entanglement", + domain: "Physics", + difficulty: "intermediate", + stage: 2, + lastScore: 0.8, + totalReviews: 3, + successCount: 2, + }, + ], + upcomingItems: [ + { + id: 2, + topicId: "phys-001", + topic: "Classical Mechanics", + domain: "Physics", + stage: 3, + nextReviewAt: new Date("2026-03-30T00:00:00Z"), + }, + ], + retainedItems: [ + { + id: 3, + topicId: "cs-001", + topic: "Recursion", + domain: "CS", + stage: 5, + totalReviews: 10, + successCount: 9, + }, + ], + }); + + const res = await getReviewRoute(makeGet("/api/feynman/review", { summary: "1" })); + const body = await json(res) as Record; + + expect(body.total).toBe(10); + expect(body.dueCount).toBe(2); + expect(body.upcomingCount).toBe(5); + expect(body.retainedCount).toBe(3); + + const dueItems = body.dueItems as Array>; + expect(dueItems).toHaveLength(1); + expect(dueItems[0]).toHaveProperty("stageLabel"); + expect(dueItems[0]).toHaveProperty("nextInterval"); + + const upcomingItems = body.upcomingItems as Array>; + expect(upcomingItems[0]).toHaveProperty("nextReviewAt"); + expect(upcomingItems[0]).toHaveProperty("stageLabel"); + + const retainedItems = body.retainedItems as Array>; + expect(retainedItems[0]).toHaveProperty("stageLabel"); + }); + + it("defaults userId to 1", async () => { + await getReviewRoute(makeGet("/api/feynman/review")); + expect(mockGetDueReviews).toHaveBeenCalledWith(1, expect.any(Date)); + }); + + it("uses userId from query param", async () => { + await getReviewRoute(makeGet("/api/feynman/review", { userId: "42" })); + expect(mockGetDueReviews).toHaveBeenCalledWith(42, expect.any(Date)); + }); + + it("returns empty items when no reviews due", async () => { + mockGetDueReviews.mockResolvedValue([]); + const res = await getReviewRoute(makeGet("/api/feynman/review")); + const body = await json(res) as Record; + expect(body.dueCount).toBe(0); + expect(body.items).toEqual([]); + }); + + it("propagates errors as 500", async () => { + mockGetDueReviews.mockRejectedValue(new Error("DB error")); + const res = await getReviewRoute(makeGet("/api/feynman/review")); + expect(res.status).toBe(500); + }); +}); + +// --------------------------------------------------------------------------- +// Tests — POST /api/feynman/curate +// --------------------------------------------------------------------------- + +describe("POST /api/feynman/curate", () => { + beforeEach(() => { + vi.clearAllMocks(); + process.env = { ...originalEnv, ANTHROPIC_API_KEY: "test-key" }; + mockCurateSources.mockResolvedValue([ + { url: "https://en.wikipedia.org/wiki/Quantum_entanglement", title: "Quantum entanglement", excerpt: "...", domain: "physics", license: "CC BY-SA", confidence: 0.9 }, + { url: "https://en.wikipedia.org/wiki/Quantum_mechanics", title: "Quantum mechanics", excerpt: "...", domain: "physics", license: "CC BY-SA", confidence: 0.85 }, + ]); + mockGetGroundedTeaching.mockResolvedValue(null); + }); + + afterEach(() => { + process.env = originalEnv; + }); + + it("returns 400 for invalid JSON body", async () => { + const req = new NextRequest("http://localhost/api/feynman/curate", { + method: "POST", + body: "not-json{{{", + headers: { "Content-Type": "application/json" }, + }); + const res = await postCurateRoute(req); + expect(res.status).toBe(400); + }); + + it("returns 400 for missing topicId", async () => { + const res = await postCurateRoute(makePost("/api/feynman/curate", {})); + expect(res.status).toBe(400); + const body = await json(res) as Record; + expect(body.error).toMatch(/topicId/i); + }); + + it("returns 404 for unknown topicId", async () => { + const res = await postCurateRoute(makePost("/api/feynman/curate", { topicId: "nonexistent-xyz" })); + expect(res.status).toBe(404); + }); + + it("returns sources, sourceCount, sourceReady, minRequired for known topic", async () => { + // Use a real topic ID from FEYNMAN_TOPICS + const { FEYNMAN_TOPICS } = await import("@/lib/feynman/topics"); + const realTopicId = FEYNMAN_TOPICS[0].id; + + const res = await postCurateRoute(makePost("/api/feynman/curate", { topicId: realTopicId })); + expect(res.status).toBe(200); + + const body = await json(res) as Record; + expect(body).toHaveProperty("sources"); + expect(body).toHaveProperty("sourceCount"); + expect(body).toHaveProperty("sourceReady"); + expect(body).toHaveProperty("minRequired"); + expect(body.topicId).toBe(realTopicId); + }); + + it("sourceReady is true when sources.length >= MIN_SOURCES (2)", async () => { + const { FEYNMAN_TOPICS } = await import("@/lib/feynman/topics"); + const realTopicId = FEYNMAN_TOPICS[0].id; + + mockCurateSources.mockResolvedValue([ + { url: "https://en.wikipedia.org/a", title: "A" }, + { url: "https://en.wikipedia.org/b", title: "B" }, + ]); + + const res = await postCurateRoute(makePost("/api/feynman/curate", { topicId: realTopicId })); + const body = await json(res) as Record; + expect(body.sourceReady).toBe(true); + expect(body.sourceCount).toBe(2); + }); + + it("sourceReady is false when sources.length < MIN_SOURCES (2)", async () => { + const { FEYNMAN_TOPICS } = await import("@/lib/feynman/topics"); + const realTopicId = FEYNMAN_TOPICS[0].id; + + mockCurateSources.mockResolvedValue([ + { url: "https://en.wikipedia.org/a", title: "A" }, + ]); + + const res = await postCurateRoute(makePost("/api/feynman/curate", { topicId: realTopicId })); + const body = await json(res) as Record; + expect(body.sourceReady).toBe(false); + }); + + it("does not include teaching content when grounded is false", async () => { + const { FEYNMAN_TOPICS } = await import("@/lib/feynman/topics"); + const realTopicId = FEYNMAN_TOPICS[0].id; + + const res = await postCurateRoute(makePost("/api/feynman/curate", { topicId: realTopicId, grounded: false })); + const body = await json(res) as Record; + expect(body.teaching).toBeUndefined(); + expect(mockGetGroundedTeaching).not.toHaveBeenCalled(); + }); + + it("returns 503 when grounded=true and no API key", async () => { + delete process.env.ANTHROPIC_API_KEY; + const { FEYNMAN_TOPICS } = await import("@/lib/feynman/topics"); + const realTopicId = FEYNMAN_TOPICS[0].id; + + mockCurateSources.mockResolvedValue([ + { url: "https://en.wikipedia.org/a", title: "A" }, + { url: "https://en.wikipedia.org/b", title: "B" }, + ]); + + const res = await postCurateRoute(makePost("/api/feynman/curate", { topicId: realTopicId, grounded: true })); + expect(res.status).toBe(503); + expect(mockGetGroundedTeaching).not.toHaveBeenCalled(); + }); + + it("includes teaching content when grounded=true and sources sufficient", async () => { + const { FEYNMAN_TOPICS } = await import("@/lib/feynman/topics"); + const realTopicId = FEYNMAN_TOPICS[0].id; + + mockCurateSources.mockResolvedValue([ + { url: "https://en.wikipedia.org/a", title: "A" }, + { url: "https://en.wikipedia.org/b", title: "B" }, + ]); + mockGetGroundedTeaching.mockResolvedValue({ explanation: "Grounded explanation...", sources: [] }); + + const res = await postCurateRoute(makePost("/api/feynman/curate", { topicId: realTopicId, grounded: true })); + const body = await json(res) as Record; + expect(body.teaching).toBeDefined(); + expect(mockGetGroundedTeaching).toHaveBeenCalledOnce(); + }); + + it("omits teaching content when grounded=true but insufficient sources", async () => { + const { FEYNMAN_TOPICS } = await import("@/lib/feynman/topics"); + const realTopicId = FEYNMAN_TOPICS[0].id; + + // Only 1 source — below MIN_SOURCES + mockCurateSources.mockResolvedValue([ + { url: "https://en.wikipedia.org/a", title: "A" }, + ]); + + const res = await postCurateRoute(makePost("/api/feynman/curate", { topicId: realTopicId, grounded: true })); + const body = await json(res) as Record; + expect(body.teaching).toBeUndefined(); + expect(mockGetGroundedTeaching).not.toHaveBeenCalled(); + }); + + it("propagates errors as 500", async () => { + const { FEYNMAN_TOPICS } = await import("@/lib/feynman/topics"); + const realTopicId = FEYNMAN_TOPICS[0].id; + + mockCurateSources.mockRejectedValue(new Error("Network error")); + const res = await postCurateRoute(makePost("/api/feynman/curate", { topicId: realTopicId })); + expect(res.status).toBe(500); + }); +}); + +// --------------------------------------------------------------------------- +// Tests — GET + POST /api/feynman/verify +// --------------------------------------------------------------------------- + +describe("GET /api/feynman/verify", () => { + beforeEach(() => { + vi.clearAllMocks(); + mockGetSourceHealthSummary.mockResolvedValue({ + totalSources: 10, + staleSources: 2, + freshSources: 8, + topicCoverage: 5, + totalCaches: 3, + validCaches: 2, + }); + }); + + it("returns health summary", async () => { + const res = await getVerifyRoute(makeGet("/api/feynman/verify")); + expect(res.status).toBe(200); + + const body = await json(res) as Record; + expect(body).toHaveProperty("health"); + expect(mockRunVerification).not.toHaveBeenCalled(); + }); + + it("does not run verification", async () => { + await getVerifyRoute(makeGet("/api/feynman/verify")); + expect(mockRunVerification).not.toHaveBeenCalled(); + }); + + it("propagates errors as 500", async () => { + mockGetSourceHealthSummary.mockRejectedValue(new Error("DB error")); + const res = await getVerifyRoute(makeGet("/api/feynman/verify")); + expect(res.status).toBe(500); + }); +}); + +describe("POST /api/feynman/verify", () => { + beforeEach(() => { + vi.clearAllMocks(); + mockRunVerification.mockResolvedValue({ + checked: 10, + alive: 8, + dead: 2, + durationMs: 500, + }); + mockGetSourceHealthSummary.mockResolvedValue({ + totalSources: 8, + staleSources: 0, + freshSources: 8, + topicCoverage: 4, + totalCaches: 3, + validCaches: 3, + }); + }); + + it("returns verification result and health summary", async () => { + const res = await postVerifyRoute(makePost("/api/feynman/verify", {})); + expect(res.status).toBe(200); + + const body = await json(res) as Record; + expect(body).toHaveProperty("verification"); + expect(body).toHaveProperty("health"); + }); + + it("verification result includes checked, alive, dead", async () => { + const res = await postVerifyRoute(makePost("/api/feynman/verify", {})); + const body = await json(res) as Record; + const verification = body.verification as Record; + + expect(verification.checked).toBe(10); + expect(verification.alive).toBe(8); + expect(verification.dead).toBe(2); + }); + + it("passes limit param to runVerification", async () => { + await postVerifyRoute(makePost("/api/feynman/verify", { limit: 30 })); + expect(mockRunVerification).toHaveBeenCalledWith(30); + }); + + it("caps limit at 200", async () => { + await postVerifyRoute(makePost("/api/feynman/verify", { limit: 999 })); + expect(mockRunVerification).toHaveBeenCalledWith(200); + }); + + it("handles empty body gracefully", async () => { + const req = new NextRequest("http://localhost/api/feynman/verify", { + method: "POST", + // no body + }); + const res = await postVerifyRoute(req); + expect(res.status).toBe(200); + expect(mockRunVerification).toHaveBeenCalledWith(undefined); + }); + + it("propagates errors as 500", async () => { + mockRunVerification.mockRejectedValue(new Error("Network error")); + const res = await postVerifyRoute(makePost("/api/feynman/verify", {})); + expect(res.status).toBe(500); + }); +}); diff --git a/src/app/api/feynman/assess/route.ts b/src/app/api/feynman/assess/route.ts new file mode 100644 index 0000000000000000000000000000000000000000..0bf2a916c98534d3d15b013e9794ff88c9dec957 --- /dev/null +++ b/src/app/api/feynman/assess/route.ts @@ -0,0 +1,103 @@ +import { NextRequest, NextResponse } from "next/server"; +import { claude, parseClaudeJson } from "@/lib/claude"; +import { withApiError } from "@/lib/api-error"; + +interface AssessBody { + topic: string; + difficulty?: string; +} + +interface AssessQuestion { + question: string; + options: string[]; + correctIndex: number; + explanation: string; +} + +/** + * POST /api/feynman/assess + * + * Generates a quick pre-assessment question for a Feynman topic. + * Used to auto-route users to the teach flow (wrong answer) or + * standard explain flow (correct answer). + */ +export const POST = withApiError(async (request: NextRequest) => { + if (!process.env.ANTHROPIC_API_KEY) { + return NextResponse.json( + { error: "ANTHROPIC_API_KEY is not configured" }, + { status: 503 }, + ); + } + + let body: AssessBody; + try { + body = await request.json(); + } catch { + return NextResponse.json({ error: "Invalid JSON body" }, { status: 400 }); + } + + const { topic, difficulty } = body; + + if (!topic || typeof topic !== "string") { + return NextResponse.json({ error: "topic is required" }, { status: 400 }); + } + + const difficultyCtx = difficulty + ? ` The topic is ${difficulty}-level.` + : ""; + + try { + const message = await claude.messages.create({ + model: "claude-haiku-4-5-20251001", + max_tokens: 512, + messages: [ + { + role: "user", + content: `Generate a quick knowledge-check question for the topic "${topic}".${difficultyCtx} + +This is a pre-assessment to gauge whether the user already knows this topic. The question should: +1. Test core understanding, not trivia +2. Have exactly 4 answer options (A-D) +3. Have one clearly correct answer +4. Be answerable in 5-10 seconds by someone who knows the topic +5. NOT be answerable by guessing or common sense alone — it should require actual knowledge + +Respond ONLY in valid JSON (no markdown, no code fences): +{ "question": "...", "options": ["A. ...", "B. ...", "C. ...", "D. ..."], "correctIndex": 0, "explanation": "Brief 1-sentence explanation of the correct answer" }`, + }, + ], + }); + + const text = + message.content[0].type === "text" ? message.content[0].text : ""; + const parsed = parseClaudeJson(text) as AssessQuestion; + + // Validate the response structure + if ( + !parsed.question || + !Array.isArray(parsed.options) || + parsed.options.length !== 4 || + typeof parsed.correctIndex !== "number" || + parsed.correctIndex < 0 || + parsed.correctIndex > 3 + ) { + throw new Error("Invalid assessment question structure from Claude"); + } + + return NextResponse.json({ + topic, + question: parsed.question, + options: parsed.options, + correctIndex: parsed.correctIndex, + explanation: parsed.explanation, + }); + } catch (err) { + return NextResponse.json( + { + error: "Failed to generate assessment question", + details: err instanceof Error ? err.message : String(err), + }, + { status: 500 }, + ); + } +}); diff --git a/src/app/api/feynman/calibrate/route.ts b/src/app/api/feynman/calibrate/route.ts new file mode 100644 index 0000000000000000000000000000000000000000..274ec0aa460f7f9d5aa5b5ea4a38237ec4d1a00e --- /dev/null +++ b/src/app/api/feynman/calibrate/route.ts @@ -0,0 +1,80 @@ +import { NextRequest, NextResponse } from "next/server"; +import { getKnowledgeProfile, getCalibratedTopics } from "@/lib/feynman/knowledge-profile"; +import { checkPrerequisites, getSuggestedPrerequisites } from "@/lib/feynman/prerequisites"; +import { withApiError } from "@/lib/api-error"; + +/** + * GET /api/feynman/calibrate?domain=CS&count=3&userId=1 + * + * Returns calibrated topic choices based on the user's Feynman knowledge profile. + * Topics are selected to match the user's skill level, avoid repetition, + * and expose weak or unexplored domains. + * + * Response includes prerequisite info for each topic and suggested + * foundation topics to study. + */ +export const GET = withApiError(async (request: NextRequest) => { + const { searchParams } = new URL(request.url); + const domain = searchParams.get("domain") || undefined; + const count = Math.min( + Math.max(parseInt(searchParams.get("count") ?? "3", 10) || 3, 1), + 10, + ); + const userId = parseInt(searchParams.get("userId") ?? "1", 10) || 1; + + const profile = await getKnowledgeProfile(userId); + const topics = getCalibratedTopics(profile, domain, count); + + // Collect all mastered topic IDs across domains + const masteredIds = new Set(); + for (const [, dp] of profile.domains) { + for (const id of dp.masteredTopics) { + masteredIds.add(id); + } + } + + // Enrich each topic with prerequisite status + const topicsWithPrereqs = topics.map((t) => { + const prereqInfo = checkPrerequisites(t.id, masteredIds); + return { + ...t, + prereqs: { + ready: prereqInfo.ready, + met: prereqInfo.met.map((p) => ({ id: p.id, topic: p.topic })), + unmet: prereqInfo.unmet.map((p) => ({ id: p.id, topic: p.topic, domain: p.domain, difficulty: p.difficulty })), + chain: prereqInfo.chain.map((p) => ({ id: p.id, topic: p.topic, domain: p.domain, difficulty: p.difficulty })), + }, + }; + }); + + // Suggest foundation topics that would unlock the most content + const suggestions = getSuggestedPrerequisites(masteredIds, 3); + + // Build a serializable domain summary + const domainSummary: Record< + string, + { attempts: number; avgScore: number; masteredCount: number } + > = {}; + for (const [key, dp] of profile.domains) { + domainSummary[key] = { + attempts: dp.attempts, + avgScore: dp.avgScore, + masteredCount: dp.masteredTopics.length, + }; + } + + return NextResponse.json({ + topics: topicsWithPrereqs, + suggestions: suggestions.map((s) => ({ + id: s.id, + topic: s.topic, + domain: s.domain, + difficulty: s.difficulty, + })), + profile: { + totalAttempts: profile.totalAttempts, + recommendedDifficulty: profile.recommendedDifficulty, + domains: domainSummary, + }, + }); +}); diff --git a/src/app/api/feynman/curate/route.ts b/src/app/api/feynman/curate/route.ts new file mode 100644 index 0000000000000000000000000000000000000000..fc8567f904c9f3f117ed453e783b252204110fd9 --- /dev/null +++ b/src/app/api/feynman/curate/route.ts @@ -0,0 +1,68 @@ +import { NextRequest, NextResponse } from "next/server"; +import { curateSources, getGroundedTeaching, MIN_SOURCES } from "@/lib/sources/curate"; +import { FEYNMAN_TOPICS } from "@/lib/feynman/topics"; +import { withApiError } from "@/lib/api-error"; + +/** + * POST /api/feynman/curate + * + * Curate sources for a Feynman topic. If grounded=true, also generates + * grounded teaching content from the sources. + * + * Body: { topicId: string, grounded?: boolean } + * + * Returns: + * - sources: array of curated source objects + * - sourceReady: boolean (>= MIN_SOURCES found) + * - teaching?: grounded teaching content (if grounded=true and sources sufficient) + */ +export const POST = withApiError(async (request: NextRequest) => { + let body: { topicId: string; grounded?: boolean }; + try { + body = await request.json(); + } catch { + return NextResponse.json({ error: "Invalid JSON body" }, { status: 400 }); + } + + const { topicId, grounded } = body; + + if (!topicId || typeof topicId !== "string") { + return NextResponse.json({ error: "topicId is required" }, { status: 400 }); + } + + // Look up the topic + const topic = FEYNMAN_TOPICS.find((t) => t.id === topicId); + if (!topic) { + return NextResponse.json({ error: `Unknown topic: ${topicId}` }, { status: 404 }); + } + + // Curate sources + const sources = await curateSources(topicId, topic.topic, topic.domain); + const sourceReady = sources.length >= MIN_SOURCES; + + const result: Record = { + topicId, + topic: topic.topic, + sources, + sourceCount: sources.length, + sourceReady, + minRequired: MIN_SOURCES, + }; + + // Optionally generate grounded teaching content + if (grounded && sourceReady) { + if (!process.env.ANTHROPIC_API_KEY) { + return NextResponse.json( + { error: "ANTHROPIC_API_KEY is not configured" }, + { status: 503 }, + ); + } + + const teaching = await getGroundedTeaching(topicId, topic.topic, topic.difficulty, topic.domain); + if (teaching) { + result.teaching = teaching; + } + } + + return NextResponse.json(result); +}); diff --git a/src/app/api/feynman/review/route.ts b/src/app/api/feynman/review/route.ts new file mode 100644 index 0000000000000000000000000000000000000000..1ffa465dbb80460c50dfd9ff2423e75baf2505a6 --- /dev/null +++ b/src/app/api/feynman/review/route.ts @@ -0,0 +1,80 @@ +import { NextRequest, NextResponse } from "next/server"; +import { getDueReviews, getReviewSummary } from "@/lib/spaced-repetition"; +import { stageLabel, intervalLabel } from "@/lib/spaced-repetition"; +import { withApiError } from "@/lib/api-error"; + +/** + * GET /api/feynman/review + * + * Query params: + * userId — user ID (default: 1) + * summary — if "1", return full summary including upcoming + retained items + * + * Returns due review items for the Feynman spaced repetition queue. + */ +export const GET = withApiError(async (request: NextRequest) => { + const { searchParams } = new URL(request.url); + const userId = parseInt(searchParams.get("userId") ?? "1", 10); + const wantSummary = searchParams.get("summary") === "1"; + const now = new Date(); + + if (wantSummary) { + const summary = await getReviewSummary(userId, now); + return NextResponse.json({ + total: summary.total, + dueCount: summary.dueCount, + upcomingCount: summary.upcomingCount, + retainedCount: summary.retainedCount, + dueItems: summary.dueItems.map((item) => ({ + id: item.id, + topicId: item.topicId, + topic: item.topic, + domain: item.domain, + difficulty: item.difficulty, + stage: item.stage, + stageLabel: stageLabel(item.stage), + nextInterval: intervalLabel(item.stage), + lastScore: item.lastScore, + totalReviews: item.totalReviews, + successCount: item.successCount, + })), + upcomingItems: summary.upcomingItems.map((item) => ({ + id: item.id, + topicId: item.topicId, + topic: item.topic, + domain: item.domain, + stage: item.stage, + stageLabel: stageLabel(item.stage), + nextReviewAt: item.nextReviewAt.toISOString(), + })), + retainedItems: summary.retainedItems.map((item) => ({ + id: item.id, + topicId: item.topicId, + topic: item.topic, + domain: item.domain, + stage: item.stage, + stageLabel: stageLabel(item.stage), + totalReviews: item.totalReviews, + successCount: item.successCount, + })), + }); + } + + // Default: just return due items + const dueItems = await getDueReviews(userId, now); + return NextResponse.json({ + dueCount: dueItems.length, + items: dueItems.map((item) => ({ + id: item.id, + topicId: item.topicId, + topic: item.topic, + domain: item.domain, + difficulty: item.difficulty, + stage: item.stage, + stageLabel: stageLabel(item.stage), + nextInterval: intervalLabel(item.stage), + lastScore: item.lastScore, + totalReviews: item.totalReviews, + })), + }); +}); diff --git a/src/app/api/feynman/score/route.ts b/src/app/api/feynman/score/route.ts new file mode 100644 index 0000000000000000000000000000000000000000..a2e7fad406f9706c94750b27cd46f305f60c260f --- /dev/null +++ b/src/app/api/feynman/score/route.ts @@ -0,0 +1,339 @@ +import { NextRequest, NextResponse } from "next/server"; +import { claude, parseClaudeJson } from "@/lib/claude"; +import { prisma } from "@/lib/db"; +// import { Prisma } from "@prisma/client"; +import { calculateXpGain, rollCriticalHit } from "@/lib/xp"; +import { checkLevelUp } from "@/lib/progression"; +import { EXERCISE_XP } from "@/config/xp"; +import { processSkillUnlocks } from "@/lib/skill-unlock"; +import { getMultiplierPercent } from "@/lib/multiplier"; +import { getTitleForLevel } from "@/config/titles"; +import { withApiError } from "@/lib/api-error"; +import { addToReviewQueue, recordReview, REVIEW_XP_MULTIPLIER } from "@/lib/spaced-repetition"; +import { processEndOfDay } from "@/lib/streak"; + +interface ScoreBody { + topic: string; + topicId?: string; + explanation: string; + userId?: number; + wasTaught?: boolean; + deepDiveRequested?: boolean; + isReview?: boolean; // true when this is a spaced repetition review + domain?: string; + difficulty?: string; + durationSecs?: number; +} + +interface ClaudeScoreResponse { + accuracy: number; + completeness: number; + clarity: number; + gaps: string[]; + feedback: string; +} + +export const POST = withApiError(async (request: NextRequest) => { + if (!process.env.ANTHROPIC_API_KEY) { + return NextResponse.json( + { error: "ANTHROPIC_API_KEY is not configured" }, + { status: 503 }, + ); + } + + let body: ScoreBody; + try { + body = await request.json(); + } catch { + return NextResponse.json({ error: "Invalid JSON body" }, { status: 400 }); + } + + const { topic, topicId, explanation, wasTaught, deepDiveRequested, isReview, domain, difficulty, durationSecs } = body; + + if (!topic || typeof topic !== "string") { + return NextResponse.json({ error: "topic is required" }, { status: 400 }); + } + if (!explanation || typeof explanation !== "string") { + return NextResponse.json( + { error: "explanation is required" }, + { status: 400 }, + ); + } + + // --- Call Claude to evaluate the explanation --- + const taughtContext = wasTaught + ? `\n\nIMPORTANT CONTEXT: The user was first taught about this topic before explaining it. They did NOT know this topic beforehand. Adjust your evaluation accordingly: +- Accuracy: Are the core facts correct? (Be slightly more lenient — they just learned this) +- Completeness: Did they grasp the main idea and key takeaways? (Don't expect depth beyond what was taught) +- Clarity: Can they explain it in their OWN words, not just parrot back what they read? (This is the most important dimension — penalize if it reads like a copy of teaching material) + +Focus on whether they truly understood and internalized the concept vs. just memorizing phrases.` + : ""; + + let scores: ClaudeScoreResponse; + try { + const message = await claude.messages.create({ + model: "claude-haiku-4-5-20251001", + max_tokens: 1024, + messages: [ + { + role: "user", + content: `You are evaluating a Feynman-technique explanation. The user was asked to explain "${topic}"${wasTaught ? " after being taught about it" : " from memory, without reference materials"}. + +Score on three dimensions (0-10 each): +- Accuracy: Are the facts correct? +- Completeness: Are the key concepts covered? +- Clarity: Would a beginner understand this? +${taughtContext} +Respond ONLY in valid JSON (no markdown, no code fences): +{ "accuracy": N, "completeness": N, "clarity": N, "gaps": ["..."], "feedback": "..." } + +Here is the user's explanation: + +${explanation}`, + }, + ], + }); + + const text = + message.content[0].type === "text" ? message.content[0].text : ""; + scores = parseClaudeJson(text) as ClaudeScoreResponse; + } catch (err) { + return NextResponse.json( + { + error: "Failed to evaluate explanation", + details: err instanceof Error ? err.message : String(err), + }, + { status: 500 }, + ); + } + + // --- Fetch user --- + const userId = body.userId ?? 1; + const user = await prisma.user.findFirst({ + where: { id: userId }, + include: { categorySkills: { where: { category: "feynman" } } }, + }); + + if (!user) { + return NextResponse.json({ error: "No user found" }, { status: 404 }); + } + + const feynmanSkill = user.categorySkills[0]; + if (!feynmanSkill) { + return NextResponse.json( + { error: "Feynman CategorySkill not found" }, + { status: 500 }, + ); + } + + // --- XP calculation (with skill tree multiplier) --- + // Taught topics earn 75% XP — still rewarding (you learned something new!) + // Reviews earn 50% XP — reinforcement, not new learning + // Normal explanations earn full XP + const TAUGHT_XP_MULTIPLIER = 0.75; + const qualityScore = + (scores.accuracy + scores.completeness + scores.clarity) / 30; + const rawXp = EXERCISE_XP["feynman"]; + const xpMultiplier = isReview ? REVIEW_XP_MULTIPLIER : wasTaught ? TAUGHT_XP_MULTIPLIER : 1; + const baseXp = Math.round(rawXp.baseXp * xpMultiplier); + const maxQualityBonus = Math.round(rawXp.maxQualityBonus * xpMultiplier); + const isCriticalHit = rollCriticalHit(); + const multiplierPercent = await getMultiplierPercent(prisma, userId, "feynman"); + + const xpResult = calculateXpGain({ + baseXp, + qualityScore, + maxQualityBonus, + isCriticalHit, + multiplierPercent, + }); + + // --- Level-up checks --- + const userLevelResult = checkLevelUp({ + currentXp: user.currentXp + xpResult.totalXp, + xpToNextLevel: user.xpToNextLevel, + level: user.level, + }); + + const categoryLevelResult = checkLevelUp({ + currentXp: feynmanSkill.currentXp + xpResult.totalXp, + xpToNextLevel: feynmanSkill.xpToNext, + level: feynmanSkill.level, + }); + + // --- Title progression --- + const newTitle = getTitleForLevel(userLevelResult.newLevel); + const titleChanged = newTitle !== user.title; + + // --- Streak processing (idempotent — no-op if already run today) --- + await processEndOfDay(userId); + + // --- Daily log bookkeeping --- + const now = new Date(); + const todayStart = new Date( + Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate()), + ); + const tomorrowStart = new Date(todayStart.getTime() + 86_400_000); + + const existingLog = await prisma.dailyLog.findFirst({ + where: { + userId, + date: { gte: todayStart, lt: tomorrowStart }, + }, + }); + + const newXpEarned = (existingLog?.xpEarned ?? 0) + xpResult.totalXp; + const newActivityCount = (existingLog?.activityCount ?? 0) + 1; + const goalMet = newXpEarned >= user.dailyGoalXp; + + // --- Persist all changes in a transaction --- + let unlockResult = { unlocked: [] as string[], streakFreezesGranted: 0 }; + await prisma.$transaction(async (tx) => { + await tx.activity.create({ + data: { + userId, + category: "feynman", + exerciseType: wasTaught ? "learn-and-explain" : "explain", + description: wasTaught + ? `Learned & explained: ${topic}` + : `Feynman explanation: ${topic}`, + baseXp: xpResult.baseXp, + qualityBonus: xpResult.qualityBonus, + isCriticalHit: xpResult.isCriticalHit, + totalXp: xpResult.totalXp, + score: qualityScore, + durationSecs: + typeof durationSecs === "number" && durationSecs >= 0 + ? Math.round(durationSecs) + : null, + metadata: JSON.stringify({ + topic, + wasTaught: !!wasTaught, + deepDiveRequested: !!deepDiveRequested, + accuracy: scores.accuracy, + completeness: scores.completeness, + clarity: scores.clarity, + }), + }, + }); + + await tx.user.update({ + where: { id: userId }, + data: { + totalXp: user.totalXp + xpResult.totalXp, + currentXp: userLevelResult.remainingXp, + xpToNextLevel: userLevelResult.newXpToNextLevel, + level: userLevelResult.newLevel, + ...(titleChanged && { title: newTitle }), + }, + }); + + await tx.categorySkill.update({ + where: { id: feynmanSkill.id }, + data: { + totalXp: feynmanSkill.totalXp + xpResult.totalXp, + currentXp: categoryLevelResult.remainingXp, + xpToNext: categoryLevelResult.newXpToNextLevel, + level: categoryLevelResult.newLevel, + }, + }); + + // Auto-unlock skill tree nodes if category leveled up + if (categoryLevelResult.levelsGained > 0) { + unlockResult = await processSkillUnlocks( + tx, userId, "feynman", categoryLevelResult.newLevel, + ); + } + + if (existingLog) { + await tx.dailyLog.update({ + where: { id: existingLog.id }, + data: { + xpEarned: newXpEarned, + activityCount: newActivityCount, + goalMet, + }, + }); + } else { + await tx.dailyLog.create({ + data: { + userId, + date: todayStart, + xpEarned: newXpEarned, + activityCount: newActivityCount, + goalMet, + }, + }); + } + }); + + // --- Spaced repetition --- + // If this was a taught topic, add it to the review queue + // If this was a review, record the result and advance/reset stage + let reviewResult: { + advanced?: boolean; + reset?: boolean; + completed?: boolean; + previousStage?: number; + newStage?: number; + } | null = null; + + if (isReview && topicId) { + try { + const result = await recordReview(userId, topicId, qualityScore); + reviewResult = { + advanced: result.advanced, + reset: result.reset, + completed: result.completed, + previousStage: result.previousStage, + newStage: result.newStage, + }; + } catch { + // Non-fatal: review recording failure shouldn't block XP + } + } else if (wasTaught && topicId) { + try { + await addToReviewQueue({ + userId, + topicId, + topic, + domain: domain ?? "Unknown", + difficulty: difficulty ?? "beginner", + }); + } catch { + // Non-fatal: queue insertion failure shouldn't block XP + } + } + + return NextResponse.json({ + scores: { + accuracy: scores.accuracy, + completeness: scores.completeness, + clarity: scores.clarity, + }, + gaps: scores.gaps, + feedback: scores.feedback, + wasTaught: !!wasTaught, + isReview: !!isReview, + review: reviewResult, + xp: { + baseXp: xpResult.baseXp, + totalXp: xpResult.totalXp, + qualityBonus: xpResult.qualityBonus, + multiplierBonus: xpResult.multiplierBonus, + multiplierPercent, + isCriticalHit: xpResult.isCriticalHit, + }, + levelUp: userLevelResult.levelsGained > 0, + categoryXp: { + currentXp: categoryLevelResult.remainingXp, + xpToNext: categoryLevelResult.newXpToNextLevel, + level: categoryLevelResult.newLevel, + levelUp: categoryLevelResult.levelsGained > 0, + }, + newTitle: titleChanged ? newTitle : undefined, + unlocks: unlockResult.unlocked, + streakFreezesGranted: unlockResult.streakFreezesGranted, + }); +}); diff --git a/src/app/api/feynman/teach-deep/route.ts b/src/app/api/feynman/teach-deep/route.ts new file mode 100644 index 0000000000000000000000000000000000000000..845f976ae063e25ca63a2a0480b73ae68173886d --- /dev/null +++ b/src/app/api/feynman/teach-deep/route.ts @@ -0,0 +1,116 @@ +import { NextRequest, NextResponse } from "next/server"; +import { claude, parseClaudeJson } from "@/lib/claude"; +import { withApiError } from "@/lib/api-error"; + +interface TeachDeepBody { + topic: string; + difficulty?: string; + previousExplanation: string; + previousTakeaways: string[]; +} + +export const POST = withApiError(async (request: NextRequest) => { + if (!process.env.ANTHROPIC_API_KEY) { + return NextResponse.json( + { error: "ANTHROPIC_API_KEY is not configured" }, + { status: 503 }, + ); + } + + let body: TeachDeepBody; + try { + body = await request.json(); + } catch { + return NextResponse.json({ error: "Invalid JSON body" }, { status: 400 }); + } + + const { topic, difficulty, previousExplanation, previousTakeaways } = body; + + if (!topic || typeof topic !== "string") { + return NextResponse.json({ error: "topic is required" }, { status: 400 }); + } + + if (!previousExplanation || typeof previousExplanation !== "string") { + return NextResponse.json( + { error: "previousExplanation is required" }, + { status: 400 }, + ); + } + + const difficultyCtx = difficulty + ? ` The topic is considered ${difficulty}-level.` + : ""; + + const takeawaysList = + previousTakeaways && previousTakeaways.length > 0 + ? `\n\nKey takeaways already covered:\n${previousTakeaways.map((t) => `- ${t}`).join("\n")}` + : ""; + + try { + const message = await claude.messages.create({ + model: "claude-haiku-4-5-20251001", + max_tokens: 2000, + messages: [ + { + role: "user", + content: `You are a brilliant teacher. A student is learning about "${topic}" and wants to go deeper.${difficultyCtx} + +They've already read this initial explanation: +--- +${previousExplanation} +---${takeawaysList} + +Now provide a deeper dive that: +1. Explains the "why" behind the concept — what makes it work, its underlying mechanism or logic +2. Gives 2 detailed, concrete examples showing the concept in action (real-world scenarios, not abstract) +3. Provides a memorable analogy that connects this to something from everyday life +4. Mentions 1-2 common misconceptions people have about this topic and why they're wrong +5. Briefly notes how this concept connects to related ideas (what it builds on, what it leads to) + +Do NOT repeat what was already covered in the initial explanation. Build on it. Go deeper, not wider. + +Respond ONLY in valid JSON (no markdown, no code fences): +{ + "deeperExplanation": "2-3 paragraphs going deeper into the why/how", + "examples": [ + { "title": "short title", "description": "detailed example" }, + { "title": "short title", "description": "detailed example" } + ], + "analogy": "a vivid, memorable analogy", + "misconceptions": [ + { "myth": "the misconception", "reality": "why it's wrong" } + ], + "connections": "brief note on related concepts" +}`, + }, + ], + }); + + const text = + message.content[0].type === "text" ? message.content[0].text : ""; + const parsed = parseClaudeJson(text) as { + deeperExplanation: string; + examples: Array<{ title: string; description: string }>; + analogy: string; + misconceptions: Array<{ myth: string; reality: string }>; + connections: string; + }; + + return NextResponse.json({ + topic, + deeperExplanation: parsed.deeperExplanation, + examples: parsed.examples, + analogy: parsed.analogy, + misconceptions: parsed.misconceptions, + connections: parsed.connections, + }); + } catch (err) { + return NextResponse.json( + { + error: "Failed to generate deep teaching content", + details: err instanceof Error ? err.message : String(err), + }, + { status: 500 }, + ); + } +}); diff --git a/src/app/api/feynman/teach/route.ts b/src/app/api/feynman/teach/route.ts new file mode 100644 index 0000000000000000000000000000000000000000..20ccfb6a097570c3cd8537d58e0f8778550f6d5a --- /dev/null +++ b/src/app/api/feynman/teach/route.ts @@ -0,0 +1,112 @@ +import { NextRequest, NextResponse } from "next/server"; +import { claude, parseClaudeJson } from "@/lib/claude"; +import { withApiError } from "@/lib/api-error"; +import { getGroundedTeaching } from "@/lib/sources/curate"; +import { FEYNMAN_TOPICS } from "@/lib/feynman/topics"; + +interface TeachBody { + topic: string; + topicId?: string; + difficulty?: string; +} + +export const POST = withApiError(async (request: NextRequest) => { + if (!process.env.ANTHROPIC_API_KEY) { + return NextResponse.json( + { error: "ANTHROPIC_API_KEY is not configured" }, + { status: 503 }, + ); + } + + let body: TeachBody; + try { + body = await request.json(); + } catch { + return NextResponse.json({ error: "Invalid JSON body" }, { status: 400 }); + } + + const { topic, topicId, difficulty } = body; + + if (!topic || typeof topic !== "string") { + return NextResponse.json({ error: "topic is required" }, { status: 400 }); + } + + // Attempt grounded teaching if we have a topicId + if (topicId) { + const knownTopic = FEYNMAN_TOPICS.find((t) => t.id === topicId); + if (knownTopic) { + try { + const grounded = await getGroundedTeaching(topicId, topic, difficulty, knownTopic.domain); + if (grounded) { + return NextResponse.json({ + topic, + explanation: grounded.explanation, + keyTakeaways: grounded.keyTakeaways, + grounded: true, + confidenceScore: grounded.confidenceScore, + sources: grounded.sources.map((s) => ({ + url: s.url, + title: s.title, + domain: s.domain, + license: s.license, + })), + }); + } + } catch { + // Grounded teaching failed — fall through to ungrounded generation + } + } + } + + // Fallback: ungrounded Claude generation (original behavior) + const difficultyCtx = difficulty + ? ` The topic is considered ${difficulty}-level.` + : ""; + + try { + const message = await claude.messages.create({ + model: "claude-haiku-4-5-20251001", + max_tokens: 1500, + messages: [ + { + role: "user", + content: `You are a brilliant teacher. A student has encountered the topic "${topic}" and doesn't know it yet.${difficultyCtx} + +Write a clear, engaging explanation that: +1. Starts with the core idea in one sentence +2. Builds understanding step by step (2-3 paragraphs) +3. Uses a concrete analogy or real-world example +4. Highlights the 2-3 most important takeaways + +Keep it accessible — a motivated beginner should be able to understand this. Be concise but thorough. Do NOT use bullet points for the main explanation — write in flowing prose. You may use a short bullet list only for the key takeaways at the end. + +Respond ONLY in valid JSON (no markdown, no code fences): +{ "explanation": "...", "keyTakeaways": ["...", "...", "..."] }`, + }, + ], + }); + + const text = + message.content[0].type === "text" ? message.content[0].text : ""; + const parsed = parseClaudeJson(text) as { + explanation: string; + keyTakeaways: string[]; + }; + + return NextResponse.json({ + topic, + explanation: parsed.explanation, + keyTakeaways: parsed.keyTakeaways, + grounded: false, + sources: [], + }); + } catch (err) { + return NextResponse.json( + { + error: "Failed to generate teaching content", + details: err instanceof Error ? err.message : String(err), + }, + { status: 500 }, + ); + } +}); diff --git a/src/app/api/feynman/verify/route.ts b/src/app/api/feynman/verify/route.ts new file mode 100644 index 0000000000000000000000000000000000000000..af5841811b574ace4b2fd2462288e6cf721cc19e --- /dev/null +++ b/src/app/api/feynman/verify/route.ts @@ -0,0 +1,46 @@ +import { NextRequest, NextResponse } from "next/server"; +import { runVerification, getSourceHealthSummary } from "@/lib/sources/verify"; +import { withApiError } from "@/lib/api-error"; + +/** + * POST /api/feynman/verify + * + * Run source verification — checks stale/unverified source URLs, + * removes dead sources, and invalidates teaching caches that fall + * below the minimum source threshold. + * + * Body (optional): { limit?: number } — max sources to check (default 50) + * + * Returns verification results and updated health summary. + */ +export const POST = withApiError(async (request: NextRequest) => { + let limit: number | undefined; + + try { + const body = await request.json(); + if (body.limit && typeof body.limit === "number" && body.limit > 0) { + limit = Math.min(body.limit, 200); // cap at 200 per run + } + } catch { + // Empty body is fine — use defaults + } + + const result = await runVerification(limit); + const health = await getSourceHealthSummary(); + + return NextResponse.json({ + verification: result, + health, + }); +}); + +/** + * GET /api/feynman/verify + * + * Returns source health summary without running verification. + */ +export const GET = withApiError(async () => { + const health = await getSourceHealthSummary(); + + return NextResponse.json({ health }); +}); diff --git a/src/app/api/judge/__tests__/reflector.test.ts b/src/app/api/judge/__tests__/reflector.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..d4b2b8f87e259d205d4ba967f4c8a9fcd9149ae4 --- /dev/null +++ b/src/app/api/judge/__tests__/reflector.test.ts @@ -0,0 +1,472 @@ +/** + * Tests for judge/reflector and cron/reflector route handlers. + * + * Covers: + * GET /api/judge/reflector + * - returns parsed reflector-proposals.json + * - propagates read errors as 500 + * - propagates JSON parse errors as 500 + * + * POST /api/judge/reflector + * - 400 when approved !== true + * - 400 when proposedChange is missing fields + * - 400 for unknown dimension + * - 400 for invalid JSON body + * - success: writes overrides file, removes proposal, returns response + * - success: reads existing overrides and merges new key + * - success: removes only the matching proposal (leaves others) + * + * POST /api/cron/reflector + * - 401 when CRON_SECRET env missing + * - 401 when x-cron-secret header is wrong + * - success: runs reflector, writes output, returns summary + * - 500 on runReflector failure + */ + +import { describe, it, expect, vi, beforeEach, afterEach } from "vitest"; +import { NextRequest } from "next/server"; + +// --------------------------------------------------------------------------- +// Mock fs/promises +// --------------------------------------------------------------------------- + +const mockReadFile = vi.fn(); +const mockWriteFile = vi.fn(); + +vi.mock("fs/promises", () => ({ + readFile: (...args: unknown[]) => mockReadFile(...args), + writeFile: (...args: unknown[]) => mockWriteFile(...args), +})); + +// --------------------------------------------------------------------------- +// Mock judge/reflector (for cron route) +// --------------------------------------------------------------------------- + +const mockRunReflector = vi.fn(); + +vi.mock("@/lib/judge/reflector", () => ({ + runReflector: (...args: unknown[]) => mockRunReflector(...args), +})); + +// --------------------------------------------------------------------------- +// Fixtures +// --------------------------------------------------------------------------- + +const FIRST_DIMENSION_ID = "flaw-detection"; // must exist in SCORING_DIMENSIONS + +const baseProposals = { + timestamp: "2026-03-30T00:00:00.000Z", + divergenceCases: [], + proposedChanges: [ + { + dimension: FIRST_DIMENSION_ID, + currentPrompt: "Original prompt text", + proposedChange: "Improved prompt text", + reasoning: "This reduces divergence", + affectedCases: 3, + }, + { + dimension: "argument-structure", + currentPrompt: "Original structure text", + proposedChange: "Improved structure text", + reasoning: "Better clarity", + affectedCases: 2, + }, + ], +}; + +// --------------------------------------------------------------------------- +// Helpers +// --------------------------------------------------------------------------- + +function makeRequest(body?: unknown, method = "POST"): NextRequest { + return new NextRequest("http://localhost/api/judge/reflector", { + method, + headers: { "Content-Type": "application/json" }, + body: body !== undefined ? JSON.stringify(body) : undefined, + }); +} + +function makeCronRequest(secret?: string | null): NextRequest { + const headers: Record = { + "Content-Type": "application/json", + }; + if (secret !== null && secret !== undefined) { + headers["x-cron-secret"] = secret; + } + return new NextRequest("http://localhost/api/cron/reflector", { + method: "POST", + headers, + }); +} + +// --------------------------------------------------------------------------- +// Tests: GET /api/judge/reflector +// --------------------------------------------------------------------------- + +describe("GET /api/judge/reflector", () => { + beforeEach(() => { + vi.clearAllMocks(); + }); + + it("returns parsed proposals JSON", async () => { + mockReadFile.mockResolvedValue(JSON.stringify(baseProposals)); + const { GET } = await import("@/app/api/judge/reflector/route"); + const req = new NextRequest("http://localhost/api/judge/reflector", { + method: "GET", + }); + const res = await GET(req); + expect(res.status).toBe(200); + const body = await res.json(); + expect(body.timestamp).toBe(baseProposals.timestamp); + expect(body.proposedChanges).toHaveLength(2); + expect(body.divergenceCases).toHaveLength(0); + }); + + it("returns 500 when file cannot be read", async () => { + mockReadFile.mockRejectedValue(new Error("ENOENT: no such file or directory")); + const { GET } = await import("@/app/api/judge/reflector/route"); + const req = new NextRequest("http://localhost/api/judge/reflector", { + method: "GET", + }); + const res = await GET(req); + expect(res.status).toBe(500); + }); + + it("returns 500 when file contains invalid JSON", async () => { + mockReadFile.mockResolvedValue("{ not valid json"); + const { GET } = await import("@/app/api/judge/reflector/route"); + const req = new NextRequest("http://localhost/api/judge/reflector", { + method: "GET", + }); + const res = await GET(req); + expect(res.status).toBe(500); + }); +}); + +// --------------------------------------------------------------------------- +// Tests: POST /api/judge/reflector +// --------------------------------------------------------------------------- + +describe("POST /api/judge/reflector", () => { + beforeEach(() => { + vi.clearAllMocks(); + // Default: overrides file doesn't exist, proposals file is valid + mockReadFile.mockImplementation((path: string) => { + if (String(path).endsWith("reflector-proposals.json")) { + return Promise.resolve(JSON.stringify(baseProposals)); + } + // dimension-overrides.json doesn't exist by default + return Promise.reject(new Error("ENOENT")); + }); + mockWriteFile.mockResolvedValue(undefined); + }); + + it("returns 400 when body cannot be parsed as JSON", async () => { + const { POST } = await import("@/app/api/judge/reflector/route"); + const req = new NextRequest("http://localhost/api/judge/reflector", { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: "not json", + }); + const res = await POST(req); + expect(res.status).toBe(400); + }); + + it("returns 400 when approved is false", async () => { + const { POST } = await import("@/app/api/judge/reflector/route"); + const req = makeRequest({ approved: false, proposedChange: {} }); + const res = await POST(req); + expect(res.status).toBe(400); + const body = await res.json(); + expect(body.error).toMatch(/approved/i); + }); + + it("returns 400 when approved is missing", async () => { + const { POST } = await import("@/app/api/judge/reflector/route"); + const req = makeRequest({ proposedChange: {} }); + const res = await POST(req); + expect(res.status).toBe(400); + }); + + it("returns 400 when proposedChange is missing", async () => { + const { POST } = await import("@/app/api/judge/reflector/route"); + const req = makeRequest({ approved: true }); + const res = await POST(req); + expect(res.status).toBe(400); + }); + + it("returns 400 when proposedChange.dimension is missing", async () => { + const { POST } = await import("@/app/api/judge/reflector/route"); + const req = makeRequest({ + approved: true, + proposedChange: { proposedChange: "new text" }, + }); + const res = await POST(req); + expect(res.status).toBe(400); + }); + + it("returns 400 when proposedChange.proposedChange text is missing", async () => { + const { POST } = await import("@/app/api/judge/reflector/route"); + const req = makeRequest({ + approved: true, + proposedChange: { dimension: FIRST_DIMENSION_ID }, + }); + const res = await POST(req); + expect(res.status).toBe(400); + }); + + it("returns 400 for unknown dimension", async () => { + const { POST } = await import("@/app/api/judge/reflector/route"); + const req = makeRequest({ + approved: true, + proposedChange: { + dimension: "nonexistent-dimension-xyz", + proposedChange: "new text", + }, + }); + const res = await POST(req); + expect(res.status).toBe(400); + const body = await res.json(); + expect(body.error).toMatch(/unknown dimension/i); + }); + + it("returns 200 with correct shape on success", async () => { + const { POST } = await import("@/app/api/judge/reflector/route"); + const req = makeRequest({ + approved: true, + proposedChange: { + dimension: FIRST_DIMENSION_ID, + proposedChange: "Improved prompt text", + currentPrompt: "Original prompt text", + reasoning: "Better", + affectedCases: 3, + }, + }); + const res = await POST(req); + expect(res.status).toBe(200); + const body = await res.json(); + expect(body.applied).toBe(true); + expect(body.dimension).toBe(FIRST_DIMENSION_ID); + expect(body.newPromptText).toBe("Improved prompt text"); + }); + + it("writes the approved change to dimension-overrides.json", async () => { + const { POST } = await import("@/app/api/judge/reflector/route"); + const req = makeRequest({ + approved: true, + proposedChange: { + dimension: FIRST_DIMENSION_ID, + proposedChange: "My improved prompt text", + currentPrompt: "Original", + reasoning: "Test", + affectedCases: 1, + }, + }); + await POST(req); + + // Find the writeFile call for overrides (not proposals) + const overridesWrite = mockWriteFile.mock.calls.find((args: unknown[]) => + String(args[0]).endsWith("dimension-overrides.json"), + ); + expect(overridesWrite).toBeDefined(); + const written = JSON.parse(overridesWrite![1] as string); + expect(written[FIRST_DIMENSION_ID]).toBe("My improved prompt text"); + }); + + it("merges new key into existing overrides", async () => { + const existingOverrides = { + "argument-structure": "Existing override", + }; + mockReadFile.mockImplementation((path: string) => { + if (String(path).endsWith("dimension-overrides.json")) { + return Promise.resolve(JSON.stringify(existingOverrides)); + } + return Promise.resolve(JSON.stringify(baseProposals)); + }); + + const { POST } = await import("@/app/api/judge/reflector/route"); + const req = makeRequest({ + approved: true, + proposedChange: { + dimension: FIRST_DIMENSION_ID, + proposedChange: "New flaw detection text", + currentPrompt: "Old text", + reasoning: "Test", + affectedCases: 2, + }, + }); + await POST(req); + + const overridesWrite = mockWriteFile.mock.calls.find((args: unknown[]) => + String(args[0]).endsWith("dimension-overrides.json"), + ); + const written = JSON.parse(overridesWrite![1] as string); + // Both keys should be present + expect(written["argument-structure"]).toBe("Existing override"); + expect(written[FIRST_DIMENSION_ID]).toBe("New flaw detection text"); + }); + + it("removes the applied proposal from reflector-proposals.json", async () => { + const { POST } = await import("@/app/api/judge/reflector/route"); + const req = makeRequest({ + approved: true, + proposedChange: { + dimension: FIRST_DIMENSION_ID, + proposedChange: "Improved prompt text", + currentPrompt: "Original prompt text", + reasoning: "Better", + affectedCases: 3, + }, + }); + await POST(req); + + const proposalsWrite = mockWriteFile.mock.calls.find((args: unknown[]) => + String(args[0]).endsWith("reflector-proposals.json"), + ); + expect(proposalsWrite).toBeDefined(); + const written = JSON.parse(proposalsWrite![1] as string); + // The applied proposal should be removed + expect(written.proposedChanges).toHaveLength(1); + expect(written.proposedChanges[0].dimension).toBe("argument-structure"); + }); + + it("leaves other proposals intact after removing the approved one", async () => { + const { POST } = await import("@/app/api/judge/reflector/route"); + // Approve the second proposal (argument-structure), not the first + const req = makeRequest({ + approved: true, + proposedChange: { + dimension: "argument-structure", + proposedChange: "Improved structure text", + currentPrompt: "Original structure text", + reasoning: "Better", + affectedCases: 2, + }, + }); + await POST(req); + + const proposalsWrite = mockWriteFile.mock.calls.find((args: unknown[]) => + String(args[0]).endsWith("reflector-proposals.json"), + ); + const written = JSON.parse(proposalsWrite![1] as string); + expect(written.proposedChanges).toHaveLength(1); + expect(written.proposedChanges[0].dimension).toBe(FIRST_DIMENSION_ID); + }); +}); + +// --------------------------------------------------------------------------- +// Tests: POST /api/cron/reflector +// --------------------------------------------------------------------------- + +describe("POST /api/cron/reflector", () => { + const ORIGINAL_ENV = process.env; + + beforeEach(() => { + vi.clearAllMocks(); + process.env = { ...ORIGINAL_ENV, CRON_SECRET: "test-secret-abc" }; + mockWriteFile.mockResolvedValue(undefined); + }); + + afterEach(() => { + process.env = ORIGINAL_ENV; + }); + + it("returns 401 when CRON_SECRET env var is not set", async () => { + delete process.env.CRON_SECRET; + const { POST } = await import("@/app/api/cron/reflector/route"); + const req = makeCronRequest("any-secret"); + const res = await POST(req); + expect(res.status).toBe(401); + }); + + it("returns 401 when x-cron-secret header is absent", async () => { + const { POST } = await import("@/app/api/cron/reflector/route"); + const req = makeCronRequest(null); + const res = await POST(req); + expect(res.status).toBe(401); + }); + + it("returns 401 when x-cron-secret header is wrong", async () => { + const { POST } = await import("@/app/api/cron/reflector/route"); + const req = makeCronRequest("wrong-secret"); + const res = await POST(req); + expect(res.status).toBe(401); + }); + + it("returns 200 with summary on success", async () => { + const reflectorOutput = { + timestamp: "2026-03-30T10:00:00.000Z", + divergenceCases: [{ runId: "r1", dimension: FIRST_DIMENSION_ID, judgeScore: 7, humanScore: 4, delta: 3, runInput: "{}", runOutput: "{}" }], + proposedChanges: [ + { dimension: FIRST_DIMENSION_ID, currentPrompt: "old", proposedChange: "new", reasoning: "better", affectedCases: 1 }, + ], + }; + mockRunReflector.mockResolvedValue(reflectorOutput); + + const { POST } = await import("@/app/api/cron/reflector/route"); + const req = makeCronRequest("test-secret-abc"); + const res = await POST(req); + expect(res.status).toBe(200); + const body = await res.json(); + expect(body.success).toBe(true); + expect(body.divergenceCases).toBe(1); + expect(body.proposedChanges).toBe(1); + expect(body.timestamp).toBe(reflectorOutput.timestamp); + }); + + it("writes reflector output to proposals JSON file", async () => { + const reflectorOutput = { + timestamp: "2026-03-30T10:00:00.000Z", + divergenceCases: [], + proposedChanges: [], + }; + mockRunReflector.mockResolvedValue(reflectorOutput); + + const { POST } = await import("@/app/api/cron/reflector/route"); + const req = makeCronRequest("test-secret-abc"); + await POST(req); + + expect(mockWriteFile).toHaveBeenCalledTimes(1); + const [path, content] = mockWriteFile.mock.calls[0] as [string, string]; + expect(String(path)).toMatch(/reflector-proposals\.json$/); + const written = JSON.parse(content); + expect(written.timestamp).toBe(reflectorOutput.timestamp); + }); + + it("returns 500 when runReflector throws", async () => { + mockRunReflector.mockRejectedValue(new Error("LangSmith unavailable")); + + const { POST } = await import("@/app/api/cron/reflector/route"); + const req = makeCronRequest("test-secret-abc"); + const res = await POST(req); + expect(res.status).toBe(500); + const body = await res.json(); + expect(body.error).toBeDefined(); + expect(body.details).toMatch(/LangSmith unavailable/); + }); + + it("does not write file on runReflector failure", async () => { + mockRunReflector.mockRejectedValue(new Error("timeout")); + + const { POST } = await import("@/app/api/cron/reflector/route"); + const req = makeCronRequest("test-secret-abc"); + await POST(req); + expect(mockWriteFile).not.toHaveBeenCalled(); + }); + + it("returns 0 counts when no divergence or proposals", async () => { + mockRunReflector.mockResolvedValue({ + timestamp: new Date().toISOString(), + divergenceCases: [], + proposedChanges: [], + }); + + const { POST } = await import("@/app/api/cron/reflector/route"); + const req = makeCronRequest("test-secret-abc"); + const res = await POST(req); + const body = await res.json(); + expect(body.divergenceCases).toBe(0); + expect(body.proposedChanges).toBe(0); + }); +}); diff --git a/src/app/api/judge/reflector/route.ts b/src/app/api/judge/reflector/route.ts new file mode 100644 index 0000000000000000000000000000000000000000..729702189f7fd9de88d2a5a54e6dc61076ffdf70 --- /dev/null +++ b/src/app/api/judge/reflector/route.ts @@ -0,0 +1,95 @@ +import { NextRequest, NextResponse } from "next/server"; +import { withApiError, ApiError } from "@/lib/api-error"; +import { readFile, writeFile } from "fs/promises"; +import { join } from "path"; +import type { ReflectorOutput, ProposedChange } from "@/lib/judge/reflector"; +import { SCORING_DIMENSIONS } from "@/lib/debate/judge"; + +const PROPOSALS_PATH = join( + process.cwd(), + "src/lib/judge/reflector-proposals.json", +); + +/** + * GET /api/judge/reflector + * + * Returns the latest divergence cases and proposed changes. + */ +export const GET = withApiError(async () => { + const raw = await readFile(PROPOSALS_PATH, "utf-8"); + const data: ReflectorOutput = JSON.parse(raw); + return NextResponse.json(data); +}); + +/** + * POST /api/judge/reflector + * + * Approve a proposed change to the judge rubric. + * Body: { approved: true, proposedChange: ProposedChange } + * + * Applies the change by updating the dimension description in the + * scoring dimensions config. The actual SCORING_DIMENSIONS array is + * source code, so we persist approved overrides to a JSON file that + * the judge prompt builder can read at runtime. + */ +export const POST = withApiError(async (request: NextRequest) => { + let body: { approved: boolean; proposedChange: ProposedChange }; + try { + body = await request.json(); + } catch { + throw new ApiError(400, "Invalid JSON body"); + } + + if (body.approved !== true) { + throw new ApiError(400, '"approved" must be true to apply a change'); + } + + const change = body.proposedChange; + if ( + !change || + typeof change.dimension !== "string" || + typeof change.proposedChange !== "string" + ) { + throw new ApiError(400, "proposedChange must include dimension and proposedChange text"); + } + + // Validate the dimension exists + const dim = SCORING_DIMENSIONS.find((d) => d.id === change.dimension); + if (!dim) { + throw new ApiError(400, `Unknown dimension: ${change.dimension}`); + } + + // Load existing overrides + const overridesPath = join( + process.cwd(), + "src/lib/judge/dimension-overrides.json", + ); + let overrides: Record = {}; + try { + const raw = await readFile(overridesPath, "utf-8"); + overrides = JSON.parse(raw); + } catch { + // File doesn't exist yet — start fresh + } + + overrides[change.dimension] = change.proposedChange; + await writeFile(overridesPath, JSON.stringify(overrides, null, 2) + "\n"); + + // Remove the applied change from proposals + const proposalsRaw = await readFile(PROPOSALS_PATH, "utf-8"); + const proposals: ReflectorOutput = JSON.parse(proposalsRaw); + proposals.proposedChanges = proposals.proposedChanges.filter( + (p) => + !( + p.dimension === change.dimension && + p.proposedChange === change.proposedChange + ), + ); + await writeFile(PROPOSALS_PATH, JSON.stringify(proposals, null, 2) + "\n"); + + return NextResponse.json({ + applied: true, + dimension: change.dimension, + newPromptText: change.proposedChange, + }); +}); diff --git a/src/app/api/llm/health/__tests__/route.test.ts b/src/app/api/llm/health/__tests__/route.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..4acc8926363edf1585f80c239089cca945bfe46d --- /dev/null +++ b/src/app/api/llm/health/__tests__/route.test.ts @@ -0,0 +1,79 @@ +/** + * Integration tests for GET /api/llm/health. + * + * Verifies the per-request HF token (x-hf-token header) drives provider + * selection and that the route reports ok / provider / model / reply / error + * with HTTP 200 in every case. + * + * getClaude is stubbed (no network); the real request-context + resolver run. + */ + +import { describe, it, expect, vi, beforeEach, afterEach } from "vitest"; +import { NextRequest } from "next/server"; + +const mockCreate = vi.fn(); + +vi.mock("@/lib/claude", async (importActual) => { + const actual = await importActual(); + return { + ...actual, + getClaude: () => ({ messages: { create: mockCreate } }), + }; +}); + +import { GET } from "../route"; + +const ENV_KEYS = ["HF_TOKEN", "HF_API_KEY", "HF_MODEL", "ANTHROPIC_API_KEY"] as const; +let saved: Record; + +beforeEach(() => { + mockCreate.mockReset(); + saved = {}; + for (const k of ENV_KEYS) { + saved[k] = process.env[k]; + delete process.env[k]; + } +}); + +afterEach(() => { + for (const k of ENV_KEYS) { + if (saved[k] === undefined) delete process.env[k]; + else process.env[k] = saved[k]; + } +}); + +function makeGet(headers?: Record): NextRequest { + return new NextRequest("http://localhost/api/llm/health", { method: "GET", headers }); +} + +describe("GET /api/llm/health", () => { + it("returns ok=false provider=none when nothing is configured", async () => { + const res = await GET(makeGet()); + expect(res.status).toBe(200); + const body = (await res.json()) as { ok: boolean; provider: string }; + expect(body.ok).toBe(false); + expect(body.provider).toBe("none"); + expect(mockCreate).not.toHaveBeenCalled(); + }); + + it("uses the per-request HF token and reports the resolved model + reply", async () => { + mockCreate.mockResolvedValue({ content: [{ type: "text", text: "ok" }] }); + const res = await GET(makeGet({ "x-hf-token": "hf_req", "x-hf-model": "meta-llama/Llama-3.3-70B-Instruct" })); + const body = (await res.json()) as { ok: boolean; provider: string; model: string; reply: string }; + expect(body.ok).toBe(true); + expect(body.provider).toBe("hf"); + expect(body.model).toBe("meta-llama/Llama-3.3-70B-Instruct"); + expect(body.reply).toBe("ok"); + expect(mockCreate).toHaveBeenCalledTimes(1); + }); + + it("reports ok=false with the error message when the completion throws", async () => { + mockCreate.mockRejectedValue(new Error("Hugging Face inference error 401: bad token")); + const res = await GET(makeGet({ "x-hf-token": "hf_bad" })); + expect(res.status).toBe(200); + const body = (await res.json()) as { ok: boolean; provider: string; error: string }; + expect(body.ok).toBe(false); + expect(body.provider).toBe("hf"); + expect(body.error).toMatch(/401/); + }); +}); diff --git a/src/app/api/llm/health/route.ts b/src/app/api/llm/health/route.ts new file mode 100644 index 0000000000000000000000000000000000000000..22f52e6ab1e6ef0046a073bdfa976fd514d8d831 --- /dev/null +++ b/src/app/api/llm/health/route.ts @@ -0,0 +1,58 @@ +import { NextResponse } from "next/server"; +import { withApiError } from "@/lib/api-error"; +import { getClaude, resolveLlmProvider } from "@/lib/claude"; + +const ANTHROPIC_HEALTH_MODEL = "claude-haiku-4-5-20251001"; + +/** + * GET /api/llm/health + * + * Tests whether the request's LLM credentials work by running a tiny + * completion. The request-scoped provider is resolved from the x-hf-token / + * x-hf-model headers (set by the Settings page via the API client), falling + * back to env (HF_TOKEN / ANTHROPIC_API_KEY). + * + * Always returns HTTP 200 so the UI can render the outcome; the result shape + * carries ok/provider/model and either a `reply` (success) or `error`. + */ +export const GET = withApiError(async () => { + const resolved = resolveLlmProvider(); + + if (resolved.provider === "none") { + return NextResponse.json({ + ok: false, + provider: "none", + error: + "No LLM configured. Paste a Hugging Face token below (or set HF_TOKEN / ANTHROPIC_API_KEY on the server).", + }); + } + + const model = + resolved.provider === "hf" + ? resolved.model + : process.env.ANTHROPIC_MODEL?.trim() || ANTHROPIC_HEALTH_MODEL; + + try { + const client = getClaude(); + const msg = await client.messages.create({ + model, + max_tokens: 8, + messages: [{ role: "user", content: "Reply with the single word: ok" }], + }); + const reply = msg.content?.[0]?.type === "text" ? msg.content[0].text : ""; + return NextResponse.json({ + ok: true, + provider: resolved.provider, + model, + reply: String(reply).trim().slice(0, 200), + }); + } catch (err) { + const message = err instanceof Error ? err.message : String(err); + return NextResponse.json({ + ok: false, + provider: resolved.provider, + model, + error: message.slice(0, 400), + }); + } +}); diff --git a/src/app/api/logic/__tests__/generate.test.ts b/src/app/api/logic/__tests__/generate.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..57a68460ef73989881ea8e665667ab67d20d698b --- /dev/null +++ b/src/app/api/logic/__tests__/generate.test.ts @@ -0,0 +1,416 @@ +/** + * Tests for GET /api/logic/generate + * + * Covers: + * - Input validation: invalid difficulty, invalid type + * - All 6 puzzle types: sudoku, sequence, pattern, wordscramble, constraint, mathequation + * - Default behaviour (no params → sudoku/medium) + * - Response shape for each type + * - Optional sub-params: sequenceType, wordCategory + */ + +import { describe, it, expect, vi, beforeEach } from "vitest"; +import { NextRequest } from "next/server"; + +// --------------------------------------------------------------------------- +// Mock all puzzle generators +// --------------------------------------------------------------------------- + +const mockGenerateSudoku = vi.fn(); +const mockGenerateSequence = vi.fn(); +const mockGeneratePattern = vi.fn(); +const mockGenerateWordScramble = vi.fn(); +const mockGenerateConstraintPuzzle = vi.fn(); +const mockGenerateMathEquation = vi.fn(); + +vi.mock("@/lib/puzzles/sudoku", () => ({ + generateSudoku: (...args: unknown[]) => mockGenerateSudoku(...args), +})); + +vi.mock("@/lib/puzzles/sequences", () => ({ + generateSequence: (...args: unknown[]) => mockGenerateSequence(...args), +})); + +vi.mock("@/lib/puzzles/patterns", () => ({ + generatePattern: (...args: unknown[]) => mockGeneratePattern(...args), +})); + +vi.mock("@/lib/puzzles/wordscramble", () => ({ + generateWordScramble: (...args: unknown[]) => mockGenerateWordScramble(...args), +})); + +vi.mock("@/lib/puzzles/constraint", () => ({ + generateConstraintPuzzle: (...args: unknown[]) => mockGenerateConstraintPuzzle(...args), +})); + +vi.mock("@/lib/puzzles/mathequation", () => ({ + generateMathEquation: (...args: unknown[]) => mockGenerateMathEquation(...args), +})); + +// --------------------------------------------------------------------------- +// Import route handler (after mocks) +// --------------------------------------------------------------------------- + +import { GET } from "../generate/route"; + +// --------------------------------------------------------------------------- +// Helpers +// --------------------------------------------------------------------------- + +function makeRequest(params: Record = {}): NextRequest { + const url = new URL("http://localhost/api/logic/generate"); + for (const [key, val] of Object.entries(params)) { + url.searchParams.set(key, val); + } + return new NextRequest(url.toString()); +} + +// Minimal fixture shapes for each puzzle type +const SUDOKU_FIXTURE = { + puzzle: Array(9).fill(Array(9).fill(0)), + solution: Array(9).fill(Array(9).fill(1)), +}; + +const SEQUENCE_FIXTURE = { + terms: [1, 2, 3, 4, 5], + hiddenIndices: [4], + answer: [5], + hint: "Arithmetic", + sequenceType: "arithmetic", + difficulty: "medium", +}; + +const PATTERN_FIXTURE = { + grid: [null, null, null, null, null, null, null, null, null], + choices: [{ shape: "circle", fill: "solid", size: "medium", rotation: 0 }], + correctIndex: 0, + activeAttributes: ["shape", "fill"], + hint: "Look at the shapes", + difficulty: "medium", +}; + +const WORDSCRAMBLE_FIXTURE = { + scrambled: "ELPPA", + answer: "APPLE", + hintIndices: [0], + hint: "A fruit", + category: "food", + length: 5, + difficulty: "easy", +}; + +const CONSTRAINT_FIXTURE = { + solution: [[1, 2, 3, 4], [2, 1, 4, 3], [3, 4, 1, 2], [4, 3, 2, 1]], + given: [[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]], + cages: [{ id: "c1", cells: [{ row: 0, col: 0 }, { row: 0, col: 1 }], target: 3 }], + hint: "Fill the grid so each row and column contains 1–4", + difficulty: "medium", +}; + +const MATHEQUATION_FIXTURE = { + equation: "? + 5 = 10", + answer: 5, + hint: "Subtract 5 from both sides", + operationCount: 1, + difficulty: "easy", +}; + +beforeEach(() => { + vi.clearAllMocks(); + mockGenerateSudoku.mockReturnValue(SUDOKU_FIXTURE); + mockGenerateSequence.mockReturnValue(SEQUENCE_FIXTURE); + mockGeneratePattern.mockReturnValue(PATTERN_FIXTURE); + mockGenerateWordScramble.mockReturnValue(WORDSCRAMBLE_FIXTURE); + mockGenerateConstraintPuzzle.mockReturnValue(CONSTRAINT_FIXTURE); + mockGenerateMathEquation.mockReturnValue(MATHEQUATION_FIXTURE); +}); + +// ─── Validation ─────────────────────────────────────────────────────────────── + +describe("GET /api/logic/generate — input validation", () => { + it("returns 400 for an invalid difficulty", async () => { + const res = await GET(makeRequest({ difficulty: "extreme" })); + expect(res.status).toBe(400); + const body = await res.json() as { error: string }; + expect(body.error).toMatch(/difficulty/i); + }); + + it("returns 400 for an invalid puzzle type", async () => { + const res = await GET(makeRequest({ type: "nonexistent", difficulty: "easy" })); + expect(res.status).toBe(400); + const body = await res.json() as { error: string }; + expect(body.error).toMatch(/type/i); + }); + + it("accepts all three valid difficulties without error", async () => { + for (const diff of ["easy", "medium", "hard"]) { + const res = await GET(makeRequest({ type: "sudoku", difficulty: diff })); + expect(res.status).toBe(200); + } + }); + + it("accepts all six valid puzzle types without error", async () => { + for (const type of ["sudoku", "sequence", "pattern", "wordscramble", "constraint", "mathequation"]) { + const res = await GET(makeRequest({ type, difficulty: "medium" })); + expect(res.status).toBe(200); + } + }); +}); + +// ─── Default behaviour ──────────────────────────────────────────────────────── + +describe("GET /api/logic/generate — defaults", () => { + it("defaults to sudoku when no type param is given", async () => { + const res = await GET(makeRequest({ difficulty: "medium" })); + expect(res.status).toBe(200); + expect(mockGenerateSudoku).toHaveBeenCalledWith("medium"); + }); + + it("defaults to medium difficulty when no difficulty param is given", async () => { + const res = await GET(makeRequest({ type: "sudoku" })); + expect(res.status).toBe(200); + expect(mockGenerateSudoku).toHaveBeenCalledWith("medium"); + }); + + it("defaults to sudoku/medium when no params at all", async () => { + const res = await GET(makeRequest()); + expect(res.status).toBe(200); + expect(mockGenerateSudoku).toHaveBeenCalledWith("medium"); + }); +}); + +// ─── Sudoku ─────────────────────────────────────────────────────────────────── + +describe("GET /api/logic/generate — sudoku", () => { + it("returns puzzleType=sudoku with puzzle, solution, difficulty, generatedAt", async () => { + const res = await GET(makeRequest({ type: "sudoku", difficulty: "hard" })); + expect(res.status).toBe(200); + const body = await res.json() as Record; + expect(body.puzzleType).toBe("sudoku"); + expect(body.puzzle).toBeDefined(); + expect(body.solution).toBeDefined(); + expect(body.difficulty).toBe("hard"); + expect(typeof body.generatedAt).toBe("string"); + }); + + it("passes the difficulty to generateSudoku", async () => { + await GET(makeRequest({ type: "sudoku", difficulty: "easy" })); + expect(mockGenerateSudoku).toHaveBeenCalledWith("easy"); + }); + + it("does not call any other generator", async () => { + await GET(makeRequest({ type: "sudoku", difficulty: "medium" })); + expect(mockGenerateSequence).not.toHaveBeenCalled(); + expect(mockGeneratePattern).not.toHaveBeenCalled(); + }); +}); + +// ─── Sequence ───────────────────────────────────────────────────────────────── + +describe("GET /api/logic/generate — sequence", () => { + it("returns puzzleType=sequence with required fields", async () => { + const res = await GET(makeRequest({ type: "sequence", difficulty: "medium" })); + expect(res.status).toBe(200); + const body = await res.json() as Record; + expect(body.puzzleType).toBe("sequence"); + expect(body.terms).toBeDefined(); + expect(body.hiddenIndices).toBeDefined(); + expect(body.hint).toBeDefined(); + expect(typeof body.generatedAt).toBe("string"); + }); + + it("passes difficulty to generateSequence", async () => { + await GET(makeRequest({ type: "sequence", difficulty: "hard" })); + expect(mockGenerateSequence).toHaveBeenCalledWith("hard", undefined); + }); + + it("passes sequenceType to generateSequence when provided", async () => { + await GET(makeRequest({ type: "sequence", difficulty: "easy", sequenceType: "fibonacci" })); + expect(mockGenerateSequence).toHaveBeenCalledWith("easy", "fibonacci"); + }); + + it("passes undefined sequenceType when not provided", async () => { + await GET(makeRequest({ type: "sequence", difficulty: "medium" })); + expect(mockGenerateSequence).toHaveBeenCalledWith("medium", undefined); + }); +}); + +// ─── Pattern ────────────────────────────────────────────────────────────────── + +describe("GET /api/logic/generate — pattern", () => { + it("returns puzzleType=pattern with required fields", async () => { + const res = await GET(makeRequest({ type: "pattern", difficulty: "medium" })); + expect(res.status).toBe(200); + const body = await res.json() as Record; + expect(body.puzzleType).toBe("pattern"); + expect(body.grid).toBeDefined(); + expect(body.choices).toBeDefined(); + expect(body.correctIndex).toBeDefined(); + expect(body.activeAttributes).toBeDefined(); + expect(body.hint).toBeDefined(); + expect(body.difficulty).toBe("medium"); + expect(typeof body.generatedAt).toBe("string"); + }); + + it("passes difficulty to generatePattern", async () => { + await GET(makeRequest({ type: "pattern", difficulty: "hard" })); + expect(mockGeneratePattern).toHaveBeenCalledWith("hard"); + }); + + it("does not expose the full puzzle object (only selected fields)", async () => { + const res = await GET(makeRequest({ type: "pattern", difficulty: "easy" })); + const body = await res.json() as Record; + // The route explicitly picks fields — ensure they're all present + expect(Object.keys(body)).toContain("grid"); + expect(Object.keys(body)).toContain("choices"); + expect(Object.keys(body)).toContain("correctIndex"); + expect(Object.keys(body)).toContain("activeAttributes"); + expect(Object.keys(body)).toContain("hint"); + expect(Object.keys(body)).toContain("difficulty"); + expect(Object.keys(body)).toContain("generatedAt"); + }); +}); + +// ─── Word Scramble ──────────────────────────────────────────────────────────── + +describe("GET /api/logic/generate — wordscramble", () => { + it("returns puzzleType=wordscramble with required fields", async () => { + const res = await GET(makeRequest({ type: "wordscramble", difficulty: "easy" })); + expect(res.status).toBe(200); + const body = await res.json() as Record; + expect(body.puzzleType).toBe("wordscramble"); + expect(body.scrambled).toBeDefined(); + expect(body.answer).toBeDefined(); + expect(body.hintIndices).toBeDefined(); + expect(body.hint).toBeDefined(); + expect(body.category).toBeDefined(); + expect(body.length).toBeDefined(); + expect(body.difficulty).toBe("easy"); + expect(typeof body.generatedAt).toBe("string"); + }); + + it("passes difficulty to generateWordScramble", async () => { + await GET(makeRequest({ type: "wordscramble", difficulty: "hard" })); + expect(mockGenerateWordScramble).toHaveBeenCalledWith("hard", undefined); + }); + + it("passes wordCategory to generateWordScramble when provided", async () => { + await GET(makeRequest({ type: "wordscramble", difficulty: "medium", wordCategory: "science" })); + expect(mockGenerateWordScramble).toHaveBeenCalledWith("medium", "science"); + }); + + it("passes undefined wordCategory when not provided", async () => { + await GET(makeRequest({ type: "wordscramble", difficulty: "easy" })); + expect(mockGenerateWordScramble).toHaveBeenCalledWith("easy", undefined); + }); +}); + +// ─── Constraint ─────────────────────────────────────────────────────────────── + +describe("GET /api/logic/generate — constraint", () => { + it("returns puzzleType=constraint with required fields", async () => { + const res = await GET(makeRequest({ type: "constraint", difficulty: "medium" })); + expect(res.status).toBe(200); + const body = await res.json() as Record; + expect(body.puzzleType).toBe("constraint"); + expect(body.solution).toBeDefined(); + expect(body.given).toBeDefined(); + expect(body.cages).toBeDefined(); + expect(body.hint).toBeDefined(); + expect(body.difficulty).toBe("medium"); + expect(typeof body.generatedAt).toBe("string"); + }); + + it("passes difficulty to generateConstraintPuzzle", async () => { + await GET(makeRequest({ type: "constraint", difficulty: "easy" })); + expect(mockGenerateConstraintPuzzle).toHaveBeenCalledWith("easy"); + }); +}); + +// ─── Math Equation ──────────────────────────────────────────────────────────── + +describe("GET /api/logic/generate — mathequation", () => { + it("returns puzzleType=mathequation with required fields", async () => { + const res = await GET(makeRequest({ type: "mathequation", difficulty: "easy" })); + expect(res.status).toBe(200); + const body = await res.json() as Record; + expect(body.puzzleType).toBe("mathequation"); + expect(body.equation).toBeDefined(); + expect(body.answer).toBeDefined(); + expect(body.hint).toBeDefined(); + expect(body.operationCount).toBeDefined(); + expect(body.difficulty).toBe("easy"); + expect(typeof body.generatedAt).toBe("string"); + }); + + it("passes difficulty to generateMathEquation", async () => { + await GET(makeRequest({ type: "mathequation", difficulty: "hard" })); + expect(mockGenerateMathEquation).toHaveBeenCalledWith("hard"); + }); + + it("includes all fixture fields in the response", async () => { + const res = await GET(makeRequest({ type: "mathequation", difficulty: "easy" })); + const body = await res.json() as Record; + expect(body.equation).toBe(MATHEQUATION_FIXTURE.equation); + expect(body.answer).toBe(MATHEQUATION_FIXTURE.answer); + expect(body.hint).toBe(MATHEQUATION_FIXTURE.hint); + expect(body.operationCount).toBe(MATHEQUATION_FIXTURE.operationCount); + }); +}); + +// ─── generatedAt timestamp ──────────────────────────────────────────────────── + +describe("GET /api/logic/generate — generatedAt", () => { + it("returns a valid ISO timestamp for every puzzle type", async () => { + for (const type of ["sudoku", "sequence", "pattern", "wordscramble", "constraint", "mathequation"]) { + const res = await GET(makeRequest({ type, difficulty: "medium" })); + const body = await res.json() as Record; + expect(() => new Date(body.generatedAt as string)).not.toThrow(); + expect(new Date(body.generatedAt as string).toISOString()).toBe(body.generatedAt); + } + }); +}); + +// ─── Isolation — generators don't cross-fire ───────────────────────────────── + +describe("GET /api/logic/generate — generator isolation", () => { + it("only calls generateSequence for type=sequence", async () => { + await GET(makeRequest({ type: "sequence", difficulty: "medium" })); + expect(mockGenerateSequence).toHaveBeenCalledOnce(); + expect(mockGenerateSudoku).not.toHaveBeenCalled(); + expect(mockGeneratePattern).not.toHaveBeenCalled(); + expect(mockGenerateWordScramble).not.toHaveBeenCalled(); + expect(mockGenerateConstraintPuzzle).not.toHaveBeenCalled(); + expect(mockGenerateMathEquation).not.toHaveBeenCalled(); + }); + + it("only calls generatePattern for type=pattern", async () => { + await GET(makeRequest({ type: "pattern", difficulty: "medium" })); + expect(mockGeneratePattern).toHaveBeenCalledOnce(); + expect(mockGenerateSudoku).not.toHaveBeenCalled(); + expect(mockGenerateSequence).not.toHaveBeenCalled(); + expect(mockGenerateWordScramble).not.toHaveBeenCalled(); + expect(mockGenerateConstraintPuzzle).not.toHaveBeenCalled(); + expect(mockGenerateMathEquation).not.toHaveBeenCalled(); + }); + + it("only calls generateConstraintPuzzle for type=constraint", async () => { + await GET(makeRequest({ type: "constraint", difficulty: "medium" })); + expect(mockGenerateConstraintPuzzle).toHaveBeenCalledOnce(); + expect(mockGenerateSudoku).not.toHaveBeenCalled(); + expect(mockGenerateSequence).not.toHaveBeenCalled(); + expect(mockGeneratePattern).not.toHaveBeenCalled(); + expect(mockGenerateWordScramble).not.toHaveBeenCalled(); + expect(mockGenerateMathEquation).not.toHaveBeenCalled(); + }); + + it("only calls generateMathEquation for type=mathequation", async () => { + await GET(makeRequest({ type: "mathequation", difficulty: "medium" })); + expect(mockGenerateMathEquation).toHaveBeenCalledOnce(); + expect(mockGenerateSudoku).not.toHaveBeenCalled(); + expect(mockGenerateSequence).not.toHaveBeenCalled(); + expect(mockGeneratePattern).not.toHaveBeenCalled(); + expect(mockGenerateWordScramble).not.toHaveBeenCalled(); + expect(mockGenerateConstraintPuzzle).not.toHaveBeenCalled(); + }); +}); diff --git a/src/app/api/logic/generate/route.ts b/src/app/api/logic/generate/route.ts new file mode 100644 index 0000000000000000000000000000000000000000..8f3ae3c7881da64a03bcdfe87997cbff1a92aadb --- /dev/null +++ b/src/app/api/logic/generate/route.ts @@ -0,0 +1,159 @@ +import { NextRequest, NextResponse } from "next/server"; +import { generateSudoku, type SudokuDifficulty } from "@/lib/puzzles/sudoku"; +import { + generateSequence, + type SequenceDifficulty, + type SequenceType, +} from "@/lib/puzzles/sequences"; +import { + generatePattern, + type PatternDifficulty, +} from "@/lib/puzzles/patterns"; +import { + generateWordScramble, + type WordScrambleDifficulty, +} from "@/lib/puzzles/wordscramble"; +import { + generateConstraintPuzzle, + type ConstraintDifficulty, +} from "@/lib/puzzles/constraint"; +import { + generateMathEquation, + type MathDifficulty, +} from "@/lib/puzzles/mathequation"; +import { withApiError } from "@/lib/api-error"; + +const VALID_DIFFICULTIES = ["easy", "medium", "hard"] as const; +type Difficulty = (typeof VALID_DIFFICULTIES)[number]; +const VALID_PUZZLE_TYPES = ["sudoku", "sequence", "pattern", "wordscramble", "constraint", "mathequation"] as const; +type PuzzleType = (typeof VALID_PUZZLE_TYPES)[number]; + +/** + * GET /api/logic/generate?type=sudoku&difficulty=medium + * + * Returns a fresh puzzle. Supported types: + * - sudoku (default): 9×9 Sudoku grid + * - sequence: number sequence with hidden terms + * - pattern: visual pattern matrix (pick the missing piece) + * - wordscramble: unscramble letters to form a word + * - constraint: 4×4 Killer-Sudoku-lite with cage sum constraints + * + * Optional `sequenceType` param for sequences: arithmetic, geometric, fibonacci, etc. + * Optional `wordCategory` param for wordscramble: nature, food, science, etc. + */ +export const GET = withApiError(async (request: NextRequest) => { + const { searchParams } = new URL(request.url); + const rawType = searchParams.get("type") ?? "sudoku"; + const rawDiff = searchParams.get("difficulty") ?? "medium"; + + if (!VALID_DIFFICULTIES.includes(rawDiff as Difficulty)) { + return NextResponse.json( + { + error: `Invalid difficulty. Must be one of: ${VALID_DIFFICULTIES.join(", ")}`, + status: 400, + }, + { status: 400 }, + ); + } + + if (!VALID_PUZZLE_TYPES.includes(rawType as PuzzleType)) { + return NextResponse.json( + { + error: `Invalid type. Must be one of: ${VALID_PUZZLE_TYPES.join(", ")}`, + status: 400, + }, + { status: 400 }, + ); + } + + const difficulty = rawDiff as Difficulty; + const puzzleType = rawType as PuzzleType; + + if (puzzleType === "sequence") { + const rawSeqType = searchParams.get("sequenceType") ?? undefined; + const puzzle = generateSequence( + difficulty as SequenceDifficulty, + rawSeqType as SequenceType | undefined, + ); + + return NextResponse.json({ + puzzleType: "sequence", + ...puzzle, + generatedAt: new Date().toISOString(), + }); + } + + if (puzzleType === "pattern") { + const puzzle = generatePattern(difficulty as PatternDifficulty); + + return NextResponse.json({ + puzzleType: "pattern", + grid: puzzle.grid, + choices: puzzle.choices, + correctIndex: puzzle.correctIndex, + activeAttributes: puzzle.activeAttributes, + hint: puzzle.hint, + difficulty, + generatedAt: new Date().toISOString(), + }); + } + + if (puzzleType === "wordscramble") { + const rawWordCategory = searchParams.get("wordCategory") ?? undefined; + const puzzle = generateWordScramble( + difficulty as WordScrambleDifficulty, + rawWordCategory, + ); + + return NextResponse.json({ + puzzleType: "wordscramble", + scrambled: puzzle.scrambled, + answer: puzzle.answer, + hintIndices: puzzle.hintIndices, + hint: puzzle.hint, + category: puzzle.category, + length: puzzle.length, + difficulty, + generatedAt: new Date().toISOString(), + }); + } + + if (puzzleType === "constraint") { + const puzzle = generateConstraintPuzzle(difficulty as ConstraintDifficulty); + + return NextResponse.json({ + puzzleType: "constraint", + solution: puzzle.solution, + given: puzzle.given, + cages: puzzle.cages, + hint: puzzle.hint, + difficulty, + generatedAt: new Date().toISOString(), + }); + } + + if (puzzleType === "mathequation") { + const puzzle = generateMathEquation(difficulty as MathDifficulty); + + return NextResponse.json({ + puzzleType: "mathequation", + equation: puzzle.equation, + answer: puzzle.answer, + hint: puzzle.hint, + operationCount: puzzle.operationCount, + difficulty, + generatedAt: new Date().toISOString(), + }); + } + + // Default: Sudoku + const { puzzle, solution } = generateSudoku(difficulty as SudokuDifficulty); + + return NextResponse.json({ + puzzleType: "sudoku", + puzzle, + solution, + difficulty, + generatedAt: new Date().toISOString(), + }); +}); diff --git a/src/app/api/logic/submit/__tests__/speed-bonus.test.ts b/src/app/api/logic/submit/__tests__/speed-bonus.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..67d72b9e319f6f02dd0d952aa9031b050c87e176 --- /dev/null +++ b/src/app/api/logic/submit/__tests__/speed-bonus.test.ts @@ -0,0 +1,242 @@ +/** + * Tests for calcSpeedBonus and PAR_TIMES. + * + * Covers: + * calcSpeedBonus + * - at-par (exact) → full MAX_SPEED_BONUS + * - under par → full MAX_SPEED_BONUS (clamped to max, not above) + * - instant (0s) → full MAX_SPEED_BONUS + * - at 2× par → 0 bonus + * - over 2× par → 0 bonus (clamped, not negative) + * - midpoint (1.5× par) → half bonus + * - parSecs = 0 → always 0 (guard) + * - negative duration clamped to 0 (treated as instant → full bonus) + * - return value always in [0, MAX_SPEED_BONUS] + * + * PAR_TIMES + * - all 6 puzzle types present + * - each type has easy/medium/hard keys + * - all values are positive integers + * - difficulty ordering: easy < medium < hard within each type + * + * combinedQualityScore (via submit route wiring — tested indirectly through + * the exported calcSpeedBonus + difficultyQualityScore constants) + * - speed at par + hard difficulty ≤ 1.0 (clamped) + * - speed below par + easy difficulty > base difficulty score + */ + +import { describe, it, expect } from "vitest"; +import { calcSpeedBonus, PAR_TIMES } from "../route"; + +// --------------------------------------------------------------------------- +// Constants +// --------------------------------------------------------------------------- + +const MAX_SPEED_BONUS = 0.25; + +// --------------------------------------------------------------------------- +// calcSpeedBonus +// --------------------------------------------------------------------------- + +describe("calcSpeedBonus", () => { + describe("at-par and under-par", () => { + it("returns full bonus when duration equals par", () => { + expect(calcSpeedBonus(120, 120)).toBe(MAX_SPEED_BONUS); + }); + + it("returns full bonus when duration is under par", () => { + expect(calcSpeedBonus(60, 120)).toBe(MAX_SPEED_BONUS); + }); + + it("returns full bonus for instant solve (0 seconds)", () => { + expect(calcSpeedBonus(0, 120)).toBe(MAX_SPEED_BONUS); + }); + + it("returns full bonus for 1 second when par is large", () => { + expect(calcSpeedBonus(1, 480)).toBe(MAX_SPEED_BONUS); + }); + }); + + describe("over-par decay", () => { + it("returns 0 bonus at exactly 2× par", () => { + expect(calcSpeedBonus(240, 120)).toBe(0); + }); + + it("returns 0 bonus at more than 2× par", () => { + expect(calcSpeedBonus(500, 120)).toBe(0); + }); + + it("returns 0 bonus at 10× par", () => { + expect(calcSpeedBonus(1200, 120)).toBe(0); + }); + + it("returns half bonus at 1.5× par (midpoint of decay range)", () => { + // At 1.5× par: decay = 0.5, bonus = MAX_SPEED_BONUS × 0.5 + const result = calcSpeedBonus(180, 120); + expect(result).toBeCloseTo(MAX_SPEED_BONUS * 0.5, 5); + }); + + it("returns quarter bonus at 1.75× par", () => { + // At 1.75× par: decay = 0.75, bonus = MAX_SPEED_BONUS × 0.25 + const result = calcSpeedBonus(210, 120); + expect(result).toBeCloseTo(MAX_SPEED_BONUS * 0.25, 5); + }); + + it("decays linearly between par and 2× par", () => { + // At par+25% = 1.25× par: decay = 0.25, bonus = MAX_SPEED_BONUS × 0.75 + const result = calcSpeedBonus(150, 120); + expect(result).toBeCloseTo(MAX_SPEED_BONUS * 0.75, 5); + }); + }); + + describe("edge cases", () => { + it("returns 0 when parSecs is 0 (guard against divide-by-zero)", () => { + expect(calcSpeedBonus(100, 0)).toBe(0); + }); + + it("clamps negative duration to 0 (treated as instant → full bonus)", () => { + expect(calcSpeedBonus(-5, 120)).toBe(MAX_SPEED_BONUS); + }); + + it("result is never negative", () => { + expect(calcSpeedBonus(99999, 1)).toBeGreaterThanOrEqual(0); + }); + + it("result never exceeds MAX_SPEED_BONUS", () => { + expect(calcSpeedBonus(0, 1)).toBeLessThanOrEqual(MAX_SPEED_BONUS); + }); + + it("works with very small par times (e.g. 1 second)", () => { + expect(calcSpeedBonus(0, 1)).toBe(MAX_SPEED_BONUS); + expect(calcSpeedBonus(1, 1)).toBe(MAX_SPEED_BONUS); + expect(calcSpeedBonus(2, 1)).toBe(0); + }); + + it("always returns value in [0, MAX_SPEED_BONUS]", () => { + const testCases = [0, 10, 60, 120, 240, 480, 1000]; + const par = 120; + for (const d of testCases) { + const result = calcSpeedBonus(d, par); + expect(result).toBeGreaterThanOrEqual(0); + expect(result).toBeLessThanOrEqual(MAX_SPEED_BONUS); + } + }); + }); +}); + +// --------------------------------------------------------------------------- +// PAR_TIMES +// --------------------------------------------------------------------------- + +describe("PAR_TIMES", () => { + const PUZZLE_TYPES = [ + "sudoku", + "sequence", + "pattern", + "wordscramble", + "constraint", + "mathequation", + ] as const; + + const DIFFICULTIES = ["easy", "medium", "hard"] as const; + + it("has an entry for all 6 puzzle types", () => { + for (const pt of PUZZLE_TYPES) { + expect(PAR_TIMES).toHaveProperty(pt); + } + }); + + it("has easy, medium, hard keys for each puzzle type", () => { + for (const pt of PUZZLE_TYPES) { + for (const diff of DIFFICULTIES) { + expect(PAR_TIMES[pt]).toHaveProperty(diff); + } + } + }); + + it("all par time values are positive integers", () => { + for (const pt of PUZZLE_TYPES) { + for (const diff of DIFFICULTIES) { + const val = PAR_TIMES[pt][diff]; + expect(typeof val).toBe("number"); + expect(val).toBeGreaterThan(0); + expect(Number.isInteger(val)).toBe(true); + } + } + }); + + it("par times increase with difficulty (easy < medium < hard) for every type", () => { + for (const pt of PUZZLE_TYPES) { + const easy = PAR_TIMES[pt]["easy"]; + const medium = PAR_TIMES[pt]["medium"]; + const hard = PAR_TIMES[pt]["hard"]; + expect(easy).toBeLessThan(medium); + expect(medium).toBeLessThan(hard); + } + }); + + it("Sudoku par times reflect higher complexity (longest par times)", () => { + // Sudoku should have the highest par times of all puzzle types + for (const pt of PUZZLE_TYPES) { + if (pt === "sudoku") continue; + expect(PAR_TIMES["sudoku"]["hard"]).toBeGreaterThan(PAR_TIMES[pt]["hard"]); + } + }); + + it("math equation has the shortest easy par time (quickest puzzle type)", () => { + for (const pt of PUZZLE_TYPES) { + if (pt === "mathequation") continue; + expect(PAR_TIMES["mathequation"]["easy"]).toBeLessThanOrEqual( + PAR_TIMES[pt]["easy"], + ); + } + }); +}); + +// --------------------------------------------------------------------------- +// combinedQualityScore invariants (integration via calcSpeedBonus) +// --------------------------------------------------------------------------- + +describe("combinedQualityScore invariants", () => { + it("hard difficulty at-par still produces quality ≤ 1.0", () => { + // hard difficulty base = 1.0, at-par speed bonus = 0.25 + // combinedQualityScore clamps to 1.0 + const parSecs = PAR_TIMES["sudoku"]["hard"]; + const base = 1.0; // hard difficulty + const speedBonus = calcSpeedBonus(parSecs, parSecs); + const combined = Math.min(1.0, base + speedBonus); + expect(combined).toBe(1.0); + expect(combined).toBeLessThanOrEqual(1.0); + }); + + it("easy difficulty at-par produces quality > base difficulty alone", () => { + // easy difficulty base = 0.3; at-par speed bonus = 0.25 → combined = 0.55 + const parSecs = PAR_TIMES["sequence"]["easy"]; + const base = 0.3; // easy difficulty + const speedBonus = calcSpeedBonus(parSecs, parSecs); + const combined = Math.min(1.0, base + speedBonus); + expect(combined).toBeGreaterThan(base); + expect(combined).toBeCloseTo(0.55, 5); + }); + + it("easy difficulty with slow solve equals base difficulty quality (no speed bonus)", () => { + // Solve at 3× par → speed bonus = 0 + const parSecs = PAR_TIMES["sequence"]["easy"]; + const base = 0.3; + const speedBonus = calcSpeedBonus(parSecs * 3, parSecs); + const combined = Math.min(1.0, base + speedBonus); + expect(speedBonus).toBe(0); + expect(combined).toBe(base); + }); + + it("medium difficulty at-par is strictly between base and hard at-par (no clamp)", () => { + const parSecs = PAR_TIMES["pattern"]["medium"]; + const base = 0.65; // medium difficulty + const speedBonus = calcSpeedBonus(parSecs, parSecs); + const combined = Math.min(1.0, base + speedBonus); + // 0.65 + 0.25 = 0.90 — below clamp threshold + expect(combined).toBeCloseTo(0.9, 5); + expect(combined).toBeGreaterThan(base); + expect(combined).toBeLessThan(1.0); + }); +}); diff --git a/src/app/api/logic/submit/__tests__/submit.test.ts b/src/app/api/logic/submit/__tests__/submit.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..931e34a808c15f21cac38a0eaab9fc911209f6b6 --- /dev/null +++ b/src/app/api/logic/submit/__tests__/submit.test.ts @@ -0,0 +1,1108 @@ +/** + * Tests for POST /api/logic/submit + * + * Covers: + * - Common validation: invalid JSON, durationSecs, difficulty + * - Incorrect puzzle: returns { correct: false } + * - All 6 puzzle types: sudoku, sequence, pattern, wordscramble, constraint, mathequation + * - XP calculation path: base XP, quality bonus, critical hit, multiplier + * - DB paths: user not found (404), missing CategorySkill (500) + * - Level-up and categoryLevelUp flags in response + * - Skill unlock triggered on category level-up + * - DailyLog create (no existing log) and update (existing log) + * - Response shape assertions for each puzzle type + */ + +import { describe, it, expect, vi, beforeEach } from "vitest"; +import { NextRequest } from "next/server"; + +// --------------------------------------------------------------------------- +// Mock puzzle validators / scorers +// --------------------------------------------------------------------------- + +const mockValidateSudoku = vi.fn(); +const mockValidateSequence = vi.fn(); +const mockScoreSequence = vi.fn(); +const mockValidatePattern = vi.fn(); +const mockScorePattern = vi.fn(); +const mockValidateWordScramble = vi.fn(); +const mockScoreWordScramble = vi.fn(); +const mockValidateConstraintGrid = vi.fn(); +const mockScoreConstraintGrid = vi.fn(); +const mockValidateMathEquation = vi.fn(); + +vi.mock("@/lib/puzzles/sudoku", () => ({ + validateSudoku: (...args: unknown[]) => mockValidateSudoku(...args), +})); +vi.mock("@/lib/puzzles/sequences", () => ({ + validateSequence: (...args: unknown[]) => mockValidateSequence(...args), + scoreSequence: (...args: unknown[]) => mockScoreSequence(...args), +})); +vi.mock("@/lib/puzzles/patterns", () => ({ + validatePattern: (...args: unknown[]) => mockValidatePattern(...args), + scorePattern: (...args: unknown[]) => mockScorePattern(...args), +})); +vi.mock("@/lib/puzzles/wordscramble", () => ({ + validateWordScramble: (...args: unknown[]) => mockValidateWordScramble(...args), + scoreWordScramble: (...args: unknown[]) => mockScoreWordScramble(...args), +})); +vi.mock("@/lib/puzzles/constraint", () => ({ + validateConstraintGrid: (...args: unknown[]) => mockValidateConstraintGrid(...args), + scoreConstraintGrid: (...args: unknown[]) => mockScoreConstraintGrid(...args), +})); +vi.mock("@/lib/puzzles/mathequation", () => ({ + validateMathEquation: (...args: unknown[]) => mockValidateMathEquation(...args), +})); + +// --------------------------------------------------------------------------- +// Mock XP / progression +// --------------------------------------------------------------------------- + +const mockCalculateXpGain = vi.fn(); +const mockRollCriticalHit = vi.fn(); +const mockCheckLevelUp = vi.fn(); +const mockGetMultiplierPercent = vi.fn(); +const mockProcessSkillUnlocks = vi.fn(); +const mockGetTitleForLevel = vi.fn(); + +vi.mock("@/lib/xp", () => ({ + calculateXpGain: (...args: unknown[]) => mockCalculateXpGain(...args), + rollCriticalHit: () => mockRollCriticalHit(), +})); +vi.mock("@/lib/progression", () => ({ + checkLevelUp: (...args: unknown[]) => mockCheckLevelUp(...args), +})); +vi.mock("@/lib/multiplier", () => ({ + getMultiplierPercent: (...args: unknown[]) => mockGetMultiplierPercent(...args), +})); +vi.mock("@/lib/skill-unlock", () => ({ + processSkillUnlocks: (...args: unknown[]) => mockProcessSkillUnlocks(...args), +})); +vi.mock("@/config/titles", () => ({ + getTitleForLevel: (...args: unknown[]) => mockGetTitleForLevel(...args), +})); + +// --------------------------------------------------------------------------- +// Mock personal-best (always returns non-PB by default to avoid test changes) +// --------------------------------------------------------------------------- + +const mockGetPersonalBest = vi.fn(); + +vi.mock("@/lib/puzzles/personal-best", () => ({ + getPersonalBest: (...args: unknown[]) => mockGetPersonalBest(...args), +})); + +// --------------------------------------------------------------------------- +// Mock Prisma +// --------------------------------------------------------------------------- + +const mockTransaction = vi.fn(); +const mockUserFindFirst = vi.fn(); +const mockDailyLogFindFirst = vi.fn(); +const mockActivityCreate = vi.fn(); +const mockUserUpdate = vi.fn(); +const mockCategorySkillUpdate = vi.fn(); +const mockDailyLogCreate = vi.fn(); +const mockDailyLogUpdate = vi.fn(); + +vi.mock("@/lib/db", () => ({ + prisma: { + user: { findFirst: (...args: unknown[]) => mockUserFindFirst(...args) }, + dailyLog: { + findFirst: (...args: unknown[]) => mockDailyLogFindFirst(...args), + }, + $transaction: (fn: (tx: unknown) => unknown) => mockTransaction(fn), + }, +})); + +// --------------------------------------------------------------------------- +// Mock processEndOfDay (no-op — streak logic is tested separately) +// --------------------------------------------------------------------------- + +vi.mock("@/lib/streak", () => ({ + processEndOfDay: vi.fn(() => Promise.resolve({ + streak: 1, + freezeUsed: false, + streakBroken: false, + alreadyProcessed: false, + })), +})); + +// --------------------------------------------------------------------------- +// Import route after all mocks +// --------------------------------------------------------------------------- + +import { POST } from "../route"; + +// --------------------------------------------------------------------------- +// Helpers +// --------------------------------------------------------------------------- + +/** Build a minimal valid 9×9 Sudoku grid (all zeros = blank). */ +function makeGrid9(fill = 0): number[][] { + return Array.from({ length: 9 }, () => Array(9).fill(fill)); +} + +/** Build a minimal valid 4×4 constraint grid (all zeros = blank). */ +function makeGrid4(fill = 0): number[][] { + return Array.from({ length: 4 }, () => Array(4).fill(fill)); +} + +function makeRequest(body: unknown): NextRequest { + return new NextRequest("http://localhost/api/logic/submit", { + method: "POST", + body: JSON.stringify(body), + headers: { "Content-Type": "application/json" }, + }); +} + +/** Default XP result returned by calculateXpGain mock. */ +const DEFAULT_XP = { + baseXp: 25, + qualityBonus: 5, + isCriticalHit: false, + totalXp: 30, +}; + +/** Default level-up result (no level gained). */ +const DEFAULT_LEVEL = { + levelsGained: 0, + newLevel: 5, + remainingXp: 100, + newXpToNextLevel: 500, +}; + +/** Default user returned by prisma.user.findFirst. */ +const DEFAULT_USER = { + id: 1, + currentXp: 200, + totalXp: 1200, + xpToNextLevel: 500, + level: 5, + dailyGoalXp: 100, + title: "Novice", + categorySkills: [ + { + id: 10, + category: "logic", + level: 3, + currentXp: 80, + totalXp: 380, + xpToNext: 300, + }, + ], +}; + +/** Wire up all happy-path mocks. */ +function setupHappyPath() { + mockUserFindFirst.mockResolvedValue(DEFAULT_USER); + mockDailyLogFindFirst.mockResolvedValue(null); // no existing log + mockCalculateXpGain.mockReturnValue(DEFAULT_XP); + mockRollCriticalHit.mockReturnValue(false); + mockCheckLevelUp.mockReturnValue(DEFAULT_LEVEL); + mockGetMultiplierPercent.mockResolvedValue(0); + mockGetTitleForLevel.mockReturnValue("Novice"); + mockGetPersonalBest.mockResolvedValue({ isPersonalBest: false, prevBestSecs: null }); + mockProcessSkillUnlocks.mockResolvedValue({ + unlocked: [], + streakFreezesGranted: 0, + }); + + // Transaction: immediately invoke the callback with a tx stub + mockTransaction.mockImplementation(async (fn: (tx: unknown) => unknown) => { + const tx = { + activity: { create: mockActivityCreate }, + user: { update: mockUserUpdate }, + categorySkill: { update: mockCategorySkillUpdate }, + dailyLog: { + create: mockDailyLogCreate, + update: mockDailyLogUpdate, + }, + }; + await fn(tx); + }); + mockActivityCreate.mockResolvedValue({}); + mockUserUpdate.mockResolvedValue({}); + mockCategorySkillUpdate.mockResolvedValue({}); + mockDailyLogCreate.mockResolvedValue({}); + mockDailyLogUpdate.mockResolvedValue({}); +} + +// --------------------------------------------------------------------------- +// Tests +// --------------------------------------------------------------------------- + +beforeEach(() => { + vi.clearAllMocks(); +}); + +// --------------------------------------------------------------------------- +// Common validation +// --------------------------------------------------------------------------- + +describe("POST /api/logic/submit — common validation", () => { + it("returns 400 on invalid JSON body", async () => { + const req = new NextRequest("http://localhost/api/logic/submit", { + method: "POST", + body: "not-json", + headers: { "Content-Type": "application/json" }, + }); + const res = await POST(req); + expect(res.status).toBe(400); + const json = await res.json(); + expect(json.error).toMatch(/invalid json/i); + }); + + it("returns 400 when durationSecs is missing", async () => { + const req = makeRequest({ + puzzleType: "sudoku", + playerGrid: makeGrid9(), + solution: makeGrid9(), + difficulty: "easy", + // no durationSecs + }); + const res = await POST(req); + expect(res.status).toBe(400); + const json = await res.json(); + expect(json.error).toMatch(/durationSecs/i); + }); + + it("returns 400 when durationSecs is negative", async () => { + const req = makeRequest({ + puzzleType: "sudoku", + playerGrid: makeGrid9(), + solution: makeGrid9(), + difficulty: "easy", + durationSecs: -5, + }); + const res = await POST(req); + expect(res.status).toBe(400); + const json = await res.json(); + expect(json.error).toMatch(/durationSecs/i); + }); + + it("returns 400 on invalid difficulty", async () => { + const req = makeRequest({ + puzzleType: "sudoku", + playerGrid: makeGrid9(), + solution: makeGrid9(), + difficulty: "extreme", + durationSecs: 60, + }); + const res = await POST(req); + expect(res.status).toBe(400); + const json = await res.json(); + expect(json.error).toMatch(/difficulty/i); + }); +}); + +// --------------------------------------------------------------------------- +// Sudoku +// --------------------------------------------------------------------------- + +describe("POST /api/logic/submit — sudoku", () => { + it("returns 400 when playerGrid is invalid shape", async () => { + const req = makeRequest({ + difficulty: "easy", + durationSecs: 60, + playerGrid: [[1, 2, 3]], // not 9×9 + solution: makeGrid9(), + }); + const res = await POST(req); + expect(res.status).toBe(400); + const json = await res.json(); + expect(json.error).toMatch(/playerGrid/i); + }); + + it("returns 400 when solution is invalid shape", async () => { + const req = makeRequest({ + difficulty: "easy", + durationSecs: 60, + playerGrid: makeGrid9(), + solution: [[1, 2, 3]], // not 9×9 + }); + const res = await POST(req); + expect(res.status).toBe(400); + const json = await res.json(); + expect(json.error).toMatch(/solution/i); + }); + + it("returns { correct: false } when validateSudoku returns false", async () => { + mockValidateSudoku.mockReturnValue(false); + const req = makeRequest({ + difficulty: "easy", + durationSecs: 60, + playerGrid: makeGrid9(), + solution: makeGrid9(), + }); + const res = await POST(req); + expect(res.status).toBe(200); + const json = await res.json(); + expect(json.correct).toBe(false); + }); + + it("defaults to sudoku type when puzzleType is omitted", async () => { + setupHappyPath(); + mockValidateSudoku.mockReturnValue(true); + const req = makeRequest({ + // no puzzleType + difficulty: "medium", + durationSecs: 120, + playerGrid: makeGrid9(), + solution: makeGrid9(), + }); + const res = await POST(req); + expect(res.status).toBe(200); + const json = await res.json(); + expect(json.correct).toBe(true); + expect(mockValidateSudoku).toHaveBeenCalledOnce(); + }); + + it("returns full response shape on correct sudoku", async () => { + setupHappyPath(); + mockValidateSudoku.mockReturnValue(true); + const req = makeRequest({ + puzzleType: "sudoku", + difficulty: "hard", + durationSecs: 300, + playerGrid: makeGrid9(), + solution: makeGrid9(), + }); + const res = await POST(req); + expect(res.status).toBe(200); + const json = await res.json(); + expect(json.correct).toBe(true); + expect(json.xp).toBeDefined(); + expect(json.levelUp).toBe(false); + expect(json.categoryLevelUp).toBe(false); + expect(json.unlocks).toEqual([]); + expect(json.streakFreezesGranted).toBe(0); + expect(json.message).toMatch(/puzzle solved/i); + }); + + it("includes isPersonalBest=false and prevBestSecs=null from getPersonalBest", async () => { + setupHappyPath(); + mockValidateSudoku.mockReturnValue(true); + mockGetPersonalBest.mockResolvedValue({ isPersonalBest: false, prevBestSecs: null }); + const req = makeRequest({ + puzzleType: "sudoku", + difficulty: "easy", + durationSecs: 200, + playerGrid: makeGrid9(), + solution: makeGrid9(), + }); + const res = await POST(req); + const json = await res.json(); + expect(json.isPersonalBest).toBe(false); + expect(json.prevBestSecs).toBeNull(); + }); + + it("includes isPersonalBest=true and prevBestSecs when a new PB is set", async () => { + setupHappyPath(); + mockValidateSudoku.mockReturnValue(true); + mockGetPersonalBest.mockResolvedValue({ isPersonalBest: true, prevBestSecs: 250 }); + const req = makeRequest({ + puzzleType: "sudoku", + difficulty: "medium", + durationSecs: 180, + playerGrid: makeGrid9(), + solution: makeGrid9(), + }); + const res = await POST(req); + const json = await res.json(); + expect(json.isPersonalBest).toBe(true); + expect(json.prevBestSecs).toBe(250); + }); + + it("passes exerciseType and difficulty to getPersonalBest", async () => { + setupHappyPath(); + mockValidateSudoku.mockReturnValue(true); + const req = makeRequest({ + puzzleType: "sudoku", + difficulty: "hard", + durationSecs: 90, + playerGrid: makeGrid9(), + solution: makeGrid9(), + }); + await POST(req); + expect(mockGetPersonalBest).toHaveBeenCalledWith( + 1, + "sudoku", + "hard", + 90, + ); + }); +}); + +// --------------------------------------------------------------------------- +// Sequence +// --------------------------------------------------------------------------- + +describe("POST /api/logic/submit — sequence", () => { + it("returns 400 when playerAnswers is missing", async () => { + const req = makeRequest({ + puzzleType: "sequence", + solution: [1, 2, 3, 4, 5], + hiddenIndices: [4], + sequenceType: "arithmetic", + difficulty: "easy", + durationSecs: 30, + }); + const res = await POST(req); + expect(res.status).toBe(400); + const json = await res.json(); + expect(json.error).toMatch(/playerAnswers/i); + }); + + it("returns 400 when solution is not an array of numbers", async () => { + const req = makeRequest({ + puzzleType: "sequence", + playerAnswers: [5], + solution: ["a", "b"], + hiddenIndices: [4], + sequenceType: "arithmetic", + difficulty: "easy", + durationSecs: 30, + }); + const res = await POST(req); + expect(res.status).toBe(400); + const json = await res.json(); + expect(json.error).toMatch(/solution/i); + }); + + it("returns { correct: false } when validateSequence returns false", async () => { + mockValidateSequence.mockReturnValue(false); + mockScoreSequence.mockReturnValue(0.5); + const req = makeRequest({ + puzzleType: "sequence", + playerAnswers: [99], + solution: [1, 2, 3, 4, 5], + hiddenIndices: [4], + sequenceType: "arithmetic", + difficulty: "easy", + durationSecs: 30, + }); + const res = await POST(req); + expect(res.status).toBe(200); + const json = await res.json(); + expect(json.correct).toBe(false); + }); + + it("calls scoreSequence for partial-credit quality calculation", async () => { + setupHappyPath(); + mockValidateSequence.mockReturnValue(true); + mockScoreSequence.mockReturnValue(0.8); + const req = makeRequest({ + puzzleType: "sequence", + playerAnswers: [5], + solution: [1, 2, 3, 4, 5], + hiddenIndices: [4], + sequenceType: "fibonacci", + difficulty: "medium", + durationSecs: 45, + }); + const res = await POST(req); + expect(res.status).toBe(200); + expect(mockScoreSequence).toHaveBeenCalledOnce(); + const json = await res.json(); + expect(json.correct).toBe(true); + }); +}); + +// --------------------------------------------------------------------------- +// Pattern +// --------------------------------------------------------------------------- + +describe("POST /api/logic/submit — pattern", () => { + const validCell = { shape: "circle", fill: "solid", size: "large", rotation: 0 }; + + it("returns 400 when selectedChoice is missing", async () => { + const req = makeRequest({ + puzzleType: "pattern", + answer: validCell, + activeAttributes: ["shape"], + difficulty: "easy", + durationSecs: 20, + }); + const res = await POST(req); + expect(res.status).toBe(400); + const json = await res.json(); + expect(json.error).toMatch(/selectedChoice/i); + }); + + it("returns 400 when answer is missing", async () => { + const req = makeRequest({ + puzzleType: "pattern", + selectedChoice: validCell, + // no answer + activeAttributes: ["shape"], + difficulty: "easy", + durationSecs: 20, + }); + const res = await POST(req); + expect(res.status).toBe(400); + const json = await res.json(); + expect(json.error).toMatch(/answer/i); + }); + + it("returns { correct: false } when validatePattern returns false", async () => { + mockValidatePattern.mockReturnValue(false); + mockScorePattern.mockReturnValue(0); + const req = makeRequest({ + puzzleType: "pattern", + selectedChoice: validCell, + answer: { ...validCell, shape: "triangle" }, + activeAttributes: ["shape"], + difficulty: "easy", + durationSecs: 20, + }); + const res = await POST(req); + expect(res.status).toBe(200); + const json = await res.json(); + expect(json.correct).toBe(false); + }); + + it("returns correct response on valid pattern submission", async () => { + setupHappyPath(); + mockValidatePattern.mockReturnValue(true); + mockScorePattern.mockReturnValue(1.0); + const req = makeRequest({ + puzzleType: "pattern", + selectedChoice: validCell, + answer: validCell, + activeAttributes: ["shape", "fill"], + difficulty: "medium", + durationSecs: 25, + }); + const res = await POST(req); + expect(res.status).toBe(200); + const json = await res.json(); + expect(json.correct).toBe(true); + expect(mockScorePattern).toHaveBeenCalledOnce(); + }); +}); + +// --------------------------------------------------------------------------- +// Word Scramble +// --------------------------------------------------------------------------- + +describe("POST /api/logic/submit — wordscramble", () => { + it("returns 400 when guess is empty string", async () => { + const req = makeRequest({ + puzzleType: "wordscramble", + guess: " ", + answer: "APPLE", + wordCategory: "food", + difficulty: "easy", + durationSecs: 15, + }); + const res = await POST(req); + expect(res.status).toBe(400); + const json = await res.json(); + expect(json.error).toMatch(/guess/i); + }); + + it("returns 400 when answer is empty string", async () => { + const req = makeRequest({ + puzzleType: "wordscramble", + guess: "APPLE", + answer: "", + wordCategory: "food", + difficulty: "easy", + durationSecs: 15, + }); + const res = await POST(req); + expect(res.status).toBe(400); + const json = await res.json(); + expect(json.error).toMatch(/answer/i); + }); + + it("returns { correct: false } when validateWordScramble returns false", async () => { + mockValidateWordScramble.mockReturnValue(false); + mockScoreWordScramble.mockReturnValue(0); + const req = makeRequest({ + puzzleType: "wordscramble", + guess: "WRONG", + answer: "APPLE", + wordCategory: "food", + difficulty: "easy", + durationSecs: 15, + }); + const res = await POST(req); + expect(res.status).toBe(200); + const json = await res.json(); + expect(json.correct).toBe(false); + }); + + it("calls validateWordScramble with guess and answer", async () => { + setupHappyPath(); + mockValidateWordScramble.mockReturnValue(true); + mockScoreWordScramble.mockReturnValue(1.0); + const req = makeRequest({ + puzzleType: "wordscramble", + guess: "APPLE", + answer: "APPLE", + wordCategory: "food", + difficulty: "hard", + durationSecs: 10, + }); + await POST(req); + expect(mockValidateWordScramble).toHaveBeenCalledWith("APPLE", "APPLE"); + }); +}); + +// --------------------------------------------------------------------------- +// Constraint Grid +// --------------------------------------------------------------------------- + +describe("POST /api/logic/submit — constraint", () => { + const CAGES = [{ id: "c1", cells: [{ row: 0, col: 0 }, { row: 0, col: 1 }], target: 5 }]; + + it("returns 400 when playerGrid is not 4×4", async () => { + const req = makeRequest({ + puzzleType: "constraint", + playerGrid: [[1, 2, 3]], // wrong shape + cages: CAGES, + difficulty: "medium", + durationSecs: 90, + }); + const res = await POST(req); + expect(res.status).toBe(400); + const json = await res.json(); + expect(json.error).toMatch(/playerGrid/i); + }); + + it("returns 400 when cages is not an array", async () => { + const req = makeRequest({ + puzzleType: "constraint", + playerGrid: makeGrid4(1), + cages: "not-an-array", + difficulty: "medium", + durationSecs: 90, + }); + const res = await POST(req); + expect(res.status).toBe(400); + const json = await res.json(); + expect(json.error).toMatch(/cages/i); + }); + + it("returns 400 when grid values are out of range (> 4)", async () => { + const invalidGrid = makeGrid4(5); // 5 is out of range for 4×4 + const req = makeRequest({ + puzzleType: "constraint", + playerGrid: invalidGrid, + cages: CAGES, + difficulty: "easy", + durationSecs: 60, + }); + const res = await POST(req); + expect(res.status).toBe(400); + const json = await res.json(); + expect(json.error).toMatch(/playerGrid/i); + }); + + it("returns { correct: false } when validateConstraintGrid returns false", async () => { + mockValidateConstraintGrid.mockReturnValue(false); + mockScoreConstraintGrid.mockReturnValue(0); + const req = makeRequest({ + puzzleType: "constraint", + playerGrid: makeGrid4(1), + cages: CAGES, + difficulty: "medium", + durationSecs: 90, + }); + const res = await POST(req); + expect(res.status).toBe(200); + const json = await res.json(); + expect(json.correct).toBe(false); + }); + + it("calls scoreConstraintGrid for partial-credit quality calculation", async () => { + setupHappyPath(); + mockValidateConstraintGrid.mockReturnValue(true); + mockScoreConstraintGrid.mockReturnValue(0.75); + const req = makeRequest({ + puzzleType: "constraint", + playerGrid: makeGrid4(1), + cages: CAGES, + difficulty: "hard", + durationSecs: 180, + }); + const res = await POST(req); + expect(res.status).toBe(200); + expect(mockScoreConstraintGrid).toHaveBeenCalledOnce(); + const json = await res.json(); + expect(json.correct).toBe(true); + }); +}); + +// --------------------------------------------------------------------------- +// Math Equation +// --------------------------------------------------------------------------- + +describe("POST /api/logic/submit — mathequation", () => { + const VALID_PUZZLE = { + equation: "? + 3 = 7", + answer: 4, + operationCount: 1, + difficulty: "easy" as const, + hint: "subtract 3 from 7", + }; + + it("returns 400 when puzzle object is missing", async () => { + const req = makeRequest({ + puzzleType: "mathequation", + playerAnswer: 4, + difficulty: "easy", + durationSecs: 10, + }); + const res = await POST(req); + expect(res.status).toBe(400); + const json = await res.json(); + expect(json.error).toMatch(/puzzle/i); + }); + + it("returns 400 when puzzle.answer is not a number", async () => { + const req = makeRequest({ + puzzleType: "mathequation", + puzzle: { ...VALID_PUZZLE, answer: "four" }, + playerAnswer: 4, + difficulty: "easy", + durationSecs: 10, + }); + const res = await POST(req); + expect(res.status).toBe(400); + const json = await res.json(); + expect(json.error).toMatch(/puzzle/i); + }); + + it("returns 400 when playerAnswer is not a number", async () => { + const req = makeRequest({ + puzzleType: "mathequation", + puzzle: VALID_PUZZLE, + playerAnswer: "four", + difficulty: "easy", + durationSecs: 10, + }); + const res = await POST(req); + expect(res.status).toBe(400); + const json = await res.json(); + expect(json.error).toMatch(/playerAnswer/i); + }); + + it("returns { correct: false } when validateMathEquation returns false", async () => { + mockValidateMathEquation.mockReturnValue(false); + const req = makeRequest({ + puzzleType: "mathequation", + puzzle: VALID_PUZZLE, + playerAnswer: 99, + difficulty: "easy", + durationSecs: 10, + }); + const res = await POST(req); + expect(res.status).toBe(200); + const json = await res.json(); + expect(json.correct).toBe(false); + }); + + it("calls validateMathEquation with puzzle and playerAnswer", async () => { + setupHappyPath(); + mockValidateMathEquation.mockReturnValue(true); + const req = makeRequest({ + puzzleType: "mathequation", + puzzle: VALID_PUZZLE, + playerAnswer: 4, + difficulty: "medium", + durationSecs: 15, + }); + await POST(req); + expect(mockValidateMathEquation).toHaveBeenCalledWith(VALID_PUZZLE, 4); + }); + + it("returns correct response on valid math equation submission", async () => { + setupHappyPath(); + mockValidateMathEquation.mockReturnValue(true); + const req = makeRequest({ + puzzleType: "mathequation", + puzzle: VALID_PUZZLE, + playerAnswer: 4, + difficulty: "hard", + durationSecs: 8, + }); + const res = await POST(req); + expect(res.status).toBe(200); + const json = await res.json(); + expect(json.correct).toBe(true); + expect(json.xp).toBeDefined(); + }); +}); + +// --------------------------------------------------------------------------- +// DB error paths +// --------------------------------------------------------------------------- + +describe("POST /api/logic/submit — DB error paths", () => { + it("returns 404 when user is not found", async () => { + mockValidateSudoku.mockReturnValue(true); + mockCalculateXpGain.mockReturnValue(DEFAULT_XP); + mockRollCriticalHit.mockReturnValue(false); + mockGetMultiplierPercent.mockResolvedValue(0); + mockCheckLevelUp.mockReturnValue(DEFAULT_LEVEL); + mockGetTitleForLevel.mockReturnValue("Novice"); + mockUserFindFirst.mockResolvedValue(null); + + const req = makeRequest({ + puzzleType: "sudoku", + difficulty: "easy", + durationSecs: 60, + playerGrid: makeGrid9(), + solution: makeGrid9(), + }); + const res = await POST(req); + expect(res.status).toBe(404); + const json = await res.json(); + expect(json.error).toMatch(/no user/i); + }); + + it("returns 500 when CategorySkill for logic is not found", async () => { + mockValidateSudoku.mockReturnValue(true); + mockCalculateXpGain.mockReturnValue(DEFAULT_XP); + mockRollCriticalHit.mockReturnValue(false); + mockGetMultiplierPercent.mockResolvedValue(0); + mockCheckLevelUp.mockReturnValue(DEFAULT_LEVEL); + mockGetTitleForLevel.mockReturnValue("Novice"); + mockUserFindFirst.mockResolvedValue({ + ...DEFAULT_USER, + categorySkills: [], // no logic skill + }); + + const req = makeRequest({ + puzzleType: "sudoku", + difficulty: "easy", + durationSecs: 60, + playerGrid: makeGrid9(), + solution: makeGrid9(), + }); + const res = await POST(req); + expect(res.status).toBe(500); + const json = await res.json(); + expect(json.error).toMatch(/CategorySkill/i); + }); +}); + +// --------------------------------------------------------------------------- +// XP and level-up behavior +// --------------------------------------------------------------------------- + +describe("POST /api/logic/submit — XP and level-up", () => { + it("includes multiplierPercent in xp response", async () => { + setupHappyPath(); + mockValidateSudoku.mockReturnValue(true); + mockGetMultiplierPercent.mockResolvedValue(25); + const req = makeRequest({ + puzzleType: "sudoku", + difficulty: "hard", + durationSecs: 300, + playerGrid: makeGrid9(), + solution: makeGrid9(), + }); + const res = await POST(req); + const json = await res.json(); + expect(json.xp.multiplierPercent).toBe(25); + }); + + it("sets levelUp=true when user gains a level", async () => { + setupHappyPath(); + mockValidateSudoku.mockReturnValue(true); + mockCheckLevelUp + .mockReturnValueOnce({ levelsGained: 1, newLevel: 6, remainingXp: 50, newXpToNextLevel: 600 }) // user level-up + .mockReturnValueOnce(DEFAULT_LEVEL); // category + const req = makeRequest({ + puzzleType: "sudoku", + difficulty: "hard", + durationSecs: 300, + playerGrid: makeGrid9(), + solution: makeGrid9(), + }); + const res = await POST(req); + const json = await res.json(); + expect(json.levelUp).toBe(true); + expect(json.newUserLevel).toBe(6); + }); + + it("sets categoryLevelUp=true and calls processSkillUnlocks on category level gain", async () => { + setupHappyPath(); + mockValidateSudoku.mockReturnValue(true); + mockCheckLevelUp + .mockReturnValueOnce(DEFAULT_LEVEL) // user + .mockReturnValueOnce({ levelsGained: 1, newLevel: 4, remainingXp: 20, newXpToNextLevel: 300 }); // category + mockProcessSkillUnlocks.mockResolvedValue({ + unlocked: ["Logic Boost I"], + streakFreezesGranted: 1, + }); + const req = makeRequest({ + puzzleType: "sudoku", + difficulty: "hard", + durationSecs: 300, + playerGrid: makeGrid9(), + solution: makeGrid9(), + }); + const res = await POST(req); + const json = await res.json(); + expect(json.categoryLevelUp).toBe(true); + expect(json.newCategoryLevel).toBe(4); + expect(json.unlocks).toContain("Logic Boost I"); + expect(json.streakFreezesGranted).toBe(1); + expect(mockProcessSkillUnlocks).toHaveBeenCalledOnce(); + }); + + it("does NOT call processSkillUnlocks when no category level gained", async () => { + setupHappyPath(); + mockValidateSudoku.mockReturnValue(true); + // both calls return no level gained + mockCheckLevelUp.mockReturnValue(DEFAULT_LEVEL); + const req = makeRequest({ + puzzleType: "sudoku", + difficulty: "easy", + durationSecs: 60, + playerGrid: makeGrid9(), + solution: makeGrid9(), + }); + await POST(req); + expect(mockProcessSkillUnlocks).not.toHaveBeenCalled(); + }); + + it("shows critical hit message when isCriticalHit is true", async () => { + setupHappyPath(); + mockValidateSudoku.mockReturnValue(true); + mockRollCriticalHit.mockReturnValue(true); + mockCalculateXpGain.mockReturnValue({ ...DEFAULT_XP, isCriticalHit: true }); + const req = makeRequest({ + puzzleType: "sudoku", + difficulty: "medium", + durationSecs: 120, + playerGrid: makeGrid9(), + solution: makeGrid9(), + }); + const res = await POST(req); + const json = await res.json(); + expect(json.isCriticalHit).toBe(true); + expect(json.message).toMatch(/critical hit/i); + }); + + it("calls getMultiplierPercent with prisma, userId=1, and category='logic'", async () => { + setupHappyPath(); + mockValidateSudoku.mockReturnValue(true); + const req = makeRequest({ + puzzleType: "sudoku", + difficulty: "easy", + durationSecs: 60, + playerGrid: makeGrid9(), + solution: makeGrid9(), + }); + await POST(req); + expect(mockGetMultiplierPercent).toHaveBeenCalledWith( + expect.anything(), + 1, + "logic", + ); + }); +}); + +// --------------------------------------------------------------------------- +// Daily log behavior +// --------------------------------------------------------------------------- + +describe("POST /api/logic/submit — DailyLog", () => { + it("creates a new DailyLog when none exists", async () => { + setupHappyPath(); + mockValidateSudoku.mockReturnValue(true); + mockDailyLogFindFirst.mockResolvedValue(null); + const req = makeRequest({ + puzzleType: "sudoku", + difficulty: "easy", + durationSecs: 60, + playerGrid: makeGrid9(), + solution: makeGrid9(), + }); + await POST(req); + expect(mockDailyLogCreate).toHaveBeenCalledOnce(); + expect(mockDailyLogUpdate).not.toHaveBeenCalled(); + }); + + it("updates existing DailyLog when one exists", async () => { + setupHappyPath(); + mockValidateSudoku.mockReturnValue(true); + mockDailyLogFindFirst.mockResolvedValue({ + id: 99, + xpEarned: 50, + activityCount: 2, + }); + const req = makeRequest({ + puzzleType: "sudoku", + difficulty: "easy", + durationSecs: 60, + playerGrid: makeGrid9(), + solution: makeGrid9(), + }); + await POST(req); + expect(mockDailyLogUpdate).toHaveBeenCalledOnce(); + expect(mockDailyLogCreate).not.toHaveBeenCalled(); + }); + + it("sets dailyGoalMet=true when earned XP meets the goal", async () => { + setupHappyPath(); + mockValidateSudoku.mockReturnValue(true); + mockCalculateXpGain.mockReturnValue({ ...DEFAULT_XP, totalXp: 200 }); + // user dailyGoalXp is 100, existing xpEarned = 0, totalXp gain = 200 → goal met + mockDailyLogFindFirst.mockResolvedValue(null); + const req = makeRequest({ + puzzleType: "sudoku", + difficulty: "hard", + durationSecs: 300, + playerGrid: makeGrid9(), + solution: makeGrid9(), + }); + const res = await POST(req); + const json = await res.json(); + expect(json.dailyGoalMet).toBe(true); + }); +}); + +// --------------------------------------------------------------------------- +// Title progression +// --------------------------------------------------------------------------- + +describe("POST /api/logic/submit — title progression", () => { + it("includes newTitle in response when title changes", async () => { + setupHappyPath(); + mockValidateSudoku.mockReturnValue(true); + mockGetTitleForLevel.mockReturnValue("Adept"); // different from user.title="Novice" + const req = makeRequest({ + puzzleType: "sudoku", + difficulty: "hard", + durationSecs: 300, + playerGrid: makeGrid9(), + solution: makeGrid9(), + }); + const res = await POST(req); + const json = await res.json(); + expect(json.newTitle).toBe("Adept"); + }); + + it("omits newTitle when title has not changed", async () => { + setupHappyPath(); + mockValidateSudoku.mockReturnValue(true); + mockGetTitleForLevel.mockReturnValue("Novice"); // same as user.title + const req = makeRequest({ + puzzleType: "sudoku", + difficulty: "easy", + durationSecs: 60, + playerGrid: makeGrid9(), + solution: makeGrid9(), + }); + const res = await POST(req); + const json = await res.json(); + expect(json.newTitle).toBeUndefined(); + }); +}); diff --git a/src/app/api/logic/submit/route.ts b/src/app/api/logic/submit/route.ts new file mode 100644 index 0000000000000000000000000000000000000000..b2295f3fe3c5c2f9e08ab00d15d54f4e434eaa28 --- /dev/null +++ b/src/app/api/logic/submit/route.ts @@ -0,0 +1,536 @@ +import { NextRequest, NextResponse } from "next/server"; +import { prisma } from "@/lib/db"; +import { validateSudoku, type SudokuGrid } from "@/lib/puzzles/sudoku"; +import { scoreSequence, validateSequence } from "@/lib/puzzles/sequences"; +import { validatePattern, scorePattern, type PatternCell } from "@/lib/puzzles/patterns"; +import { validateWordScramble, scoreWordScramble } from "@/lib/puzzles/wordscramble"; +import { + validateConstraintGrid, + scoreConstraintGrid, + type Cage, +} from "@/lib/puzzles/constraint"; +import { + validateMathEquation, + type MathEquationPuzzle, +} from "@/lib/puzzles/mathequation"; +import { calculateXpGain, rollCriticalHit } from "@/lib/xp"; +import { checkLevelUp } from "@/lib/progression"; +import { EXERCISE_XP } from "@/config/xp"; +import { processSkillUnlocks } from "@/lib/skill-unlock"; +import { getMultiplierPercent } from "@/lib/multiplier"; +import { getTitleForLevel } from "@/config/titles"; +import { withApiError } from "@/lib/api-error"; +import { getPersonalBest } from "@/lib/puzzles/personal-best"; +import { processEndOfDay } from "@/lib/streak"; + +interface SudokuSubmitBody { + puzzleType?: "sudoku"; + playerGrid: SudokuGrid; + solution: SudokuGrid; + durationSecs: number; + difficulty: "easy" | "medium" | "hard"; +} + +interface SequenceSubmitBody { + puzzleType: "sequence"; + playerAnswers: number[]; + solution: number[]; + hiddenIndices: number[]; + sequenceType: string; + durationSecs: number; + difficulty: "easy" | "medium" | "hard"; +} + +interface PatternSubmitBody { + puzzleType: "pattern"; + selectedChoice: PatternCell; + answer: PatternCell; + activeAttributes: string[]; + durationSecs: number; + difficulty: "easy" | "medium" | "hard"; +} + +interface WordScrambleSubmitBody { + puzzleType: "wordscramble"; + guess: string; + answer: string; + wordCategory: string; + durationSecs: number; + difficulty: "easy" | "medium" | "hard"; +} + +interface ConstraintSubmitBody { + puzzleType: "constraint"; + playerGrid: number[][]; + cages: Cage[]; + durationSecs: number; + difficulty: "easy" | "medium" | "hard"; +} + +interface MathEquationSubmitBody { + puzzleType: "mathequation"; + /** The puzzle object echoed back from the generate endpoint */ + puzzle: Pick; + /** The integer answer entered by the player */ + playerAnswer: number; + durationSecs: number; + difficulty: "easy" | "medium" | "hard"; +} + +type SubmitBody = SudokuSubmitBody | SequenceSubmitBody | PatternSubmitBody | WordScrambleSubmitBody | ConstraintSubmitBody | MathEquationSubmitBody; + +// --------------------------------------------------------------------------- +// Par times (seconds) per puzzle type and difficulty. +// Solving at or under par earns the full speed bonus; above par tapers to 0. +// --------------------------------------------------------------------------- + +export const PAR_TIMES: Record> = { + sudoku: { easy: 120, medium: 240, hard: 480 }, + sequence: { easy: 20, medium: 35, hard: 60 }, + pattern: { easy: 25, medium: 45, hard: 75 }, + wordscramble: { easy: 20, medium: 35, hard: 55 }, + constraint: { easy: 60, medium: 120, hard: 200 }, + mathequation: { easy: 15, medium: 30, hard: 55 }, +}; + +/** Maximum speed bonus added to the quality score (capped). */ +const MAX_SPEED_BONUS = 0.25; + +/** + * Calculate a speed bonus (0–MAX_SPEED_BONUS) based on how fast the puzzle + * was solved relative to the par time. + * + * - At or under par → full MAX_SPEED_BONUS + * - At 2× par → 0 bonus (linear interpolation) + * - Over 2× par → 0 bonus (clamped) + * - durationSecs ≤ 0 → treated as instant (full bonus) + * + * The bonus is deliberately modest (max +0.25) so it adds flavour without + * dominating the difficulty-based quality score. + */ +export function calcSpeedBonus(durationSecs: number, parSecs: number): number { + if (parSecs <= 0) return 0; + const clampedDuration = Math.max(0, durationSecs); + if (clampedDuration <= parSecs) return MAX_SPEED_BONUS; + // Linear decay from parSecs (full bonus) to 2×parSecs (zero bonus) + const decay = (clampedDuration - parSecs) / parSecs; + return Math.max(0, MAX_SPEED_BONUS * (1 - decay)); +} + +/** Map difficulty to a quality score influencing the XP bonus (0–1). */ +function difficultyQualityScore(difficulty: string): number { + switch (difficulty) { + case "easy": + return 0.3; + case "medium": + return 0.65; + case "hard": + return 1.0; + default: + return 0.5; + } +} + +/** + * Combined quality score: difficulty weight + speed bonus, clamped to [0, 1]. + */ +function combinedQualityScore( + puzzleType: string, + difficulty: string, + durationSecs: number, +): number { + const base = difficultyQualityScore(difficulty); + const parSecs = PAR_TIMES[puzzleType]?.[difficulty] ?? 0; + const speedBonus = calcSpeedBonus(durationSecs, parSecs); + return Math.min(1.0, base + speedBonus); +} + +/** Validate the shape of the submitted grids. */ +function isValidGrid(grid: unknown): grid is SudokuGrid { + if (!Array.isArray(grid) || grid.length !== 9) return false; + return grid.every( + (row) => + Array.isArray(row) && + row.length === 9 && + row.every((cell) => typeof cell === "number" && cell >= 0 && cell <= 9), + ); +} + +/** + * POST /api/logic/submit + * + * Validates a completed puzzle (Sudoku or sequence), awards XP, and persists the activity. + * Supports: + * - puzzleType="sudoku" (default): classic Sudoku validation + * - puzzleType="sequence": number sequence validation with partial credit + */ +export const POST = withApiError(async (request: NextRequest) => { + let body: SubmitBody; + + try { + body = await request.json(); + } catch { + return NextResponse.json({ error: "Invalid JSON body" }, { status: 400 }); + } + + const puzzleType = body.puzzleType ?? "sudoku"; + const { durationSecs, difficulty } = body; + + // --- Common validation --- + if (typeof durationSecs !== "number" || durationSecs < 0) { + return NextResponse.json( + { error: "durationSecs must be a non-negative number" }, + { status: 400 }, + ); + } + if (!["easy", "medium", "hard"].includes(difficulty)) { + return NextResponse.json( + { error: "difficulty must be easy, medium, or hard" }, + { status: 400 }, + ); + } + + // --- Puzzle-type-specific validation & scoring --- + let isCorrect: boolean; + let qualityScore: number; + let exerciseType: string; + let description: string; + let metadata: Record; + + if (puzzleType === "sequence") { + const seqBody = body as SequenceSubmitBody; + const { playerAnswers, solution, hiddenIndices, sequenceType } = seqBody; + + if (!Array.isArray(playerAnswers) || !playerAnswers.every((v) => typeof v === "number")) { + return NextResponse.json( + { error: "playerAnswers must be an array of numbers" }, + { status: 400 }, + ); + } + if (!Array.isArray(solution) || !solution.every((v) => typeof v === "number")) { + return NextResponse.json( + { error: "solution must be an array of numbers" }, + { status: 400 }, + ); + } + if (!Array.isArray(hiddenIndices) || !hiddenIndices.every((v) => typeof v === "number")) { + return NextResponse.json( + { error: "hiddenIndices must be an array of numbers" }, + { status: 400 }, + ); + } + + isCorrect = validateSequence(playerAnswers, solution, hiddenIndices); + // Use partial credit scoring for quality (even if not fully correct) + const partialScore = scoreSequence(playerAnswers, solution, hiddenIndices); + // Combine difficulty weighting + speed bonus with actual accuracy + qualityScore = partialScore * combinedQualityScore("sequence", difficulty, durationSecs); + exerciseType = "sequence"; + description = `Completed ${difficulty} ${sequenceType || "number"} sequence in ${Math.round(durationSecs)}s`; + metadata = { difficulty, sequenceType, partialScore, isCorrect }; + } else if (puzzleType === "pattern") { + const patternBody = body as PatternSubmitBody; + const { selectedChoice, answer, activeAttributes } = patternBody; + + if (!selectedChoice || typeof selectedChoice !== "object") { + return NextResponse.json( + { error: "selectedChoice must be a PatternCell object" }, + { status: 400 }, + ); + } + if (!answer || typeof answer !== "object") { + return NextResponse.json( + { error: "answer must be a PatternCell object" }, + { status: 400 }, + ); + } + + isCorrect = validatePattern(selectedChoice, answer); + qualityScore = scorePattern(selectedChoice, answer) * combinedQualityScore("pattern", difficulty, durationSecs); + exerciseType = "pattern"; + description = `Completed ${difficulty} pattern matrix (${(activeAttributes || []).join(", ")}) in ${Math.round(durationSecs)}s`; + metadata = { difficulty, activeAttributes, isCorrect }; + } else if (puzzleType === "wordscramble") { + const wsBody = body as WordScrambleSubmitBody; + const { guess, answer: wsAnswer, wordCategory } = wsBody; + + if (typeof guess !== "string" || guess.trim().length === 0) { + return NextResponse.json( + { error: "guess must be a non-empty string" }, + { status: 400 }, + ); + } + if (typeof wsAnswer !== "string" || wsAnswer.trim().length === 0) { + return NextResponse.json( + { error: "answer must be a non-empty string" }, + { status: 400 }, + ); + } + + isCorrect = validateWordScramble(guess, wsAnswer); + qualityScore = scoreWordScramble(guess, wsAnswer) * combinedQualityScore("wordscramble", difficulty, durationSecs); + exerciseType = "wordscramble"; + description = `Completed ${difficulty} word scramble (${wordCategory || "mixed"}) in ${Math.round(durationSecs)}s`; + metadata = { difficulty, wordCategory, isCorrect }; + } else if (puzzleType === "constraint") { + const constraintBody = body as ConstraintSubmitBody; + const { playerGrid, cages } = constraintBody; + + if ( + !Array.isArray(playerGrid) || + playerGrid.length !== 4 || + !playerGrid.every( + (row) => + Array.isArray(row) && + row.length === 4 && + row.every((v) => typeof v === "number" && v >= 0 && v <= 4), + ) + ) { + return NextResponse.json( + { error: "playerGrid must be a 4×4 array of integers 0–4" }, + { status: 400 }, + ); + } + if (!Array.isArray(cages)) { + return NextResponse.json( + { error: "cages must be an array" }, + { status: 400 }, + ); + } + + isCorrect = validateConstraintGrid(playerGrid, cages); + const partialScore = scoreConstraintGrid(playerGrid, cages); + qualityScore = partialScore * combinedQualityScore("constraint", difficulty, durationSecs); + exerciseType = "constraint"; + description = `Completed ${difficulty} constraint grid in ${Math.round(durationSecs)}s`; + metadata = { difficulty, partialScore, isCorrect }; + } else if (puzzleType === "mathequation") { + const mathBody = body as MathEquationSubmitBody; + const { puzzle: mathPuzzle, playerAnswer } = mathBody; + + if (!mathPuzzle || typeof mathPuzzle !== "object" || typeof mathPuzzle.answer !== "number") { + return NextResponse.json( + { error: "puzzle must be a MathEquationPuzzle object with a numeric answer" }, + { status: 400 }, + ); + } + if (typeof playerAnswer !== "number") { + return NextResponse.json( + { error: "playerAnswer must be a number" }, + { status: 400 }, + ); + } + + isCorrect = validateMathEquation(mathPuzzle as MathEquationPuzzle, playerAnswer); + qualityScore = isCorrect ? combinedQualityScore("mathequation", difficulty, durationSecs) : 0; + exerciseType = "mathequation"; + description = `Solved ${difficulty} math equation "${mathPuzzle.equation}" in ${Math.round(durationSecs)}s`; + metadata = { difficulty, equation: mathPuzzle.equation, playerAnswer, isCorrect }; + } else { + // Sudoku + const sudokuBody = body as SudokuSubmitBody; + const { playerGrid, solution } = sudokuBody; + + if (!isValidGrid(playerGrid)) { + return NextResponse.json( + { error: "playerGrid must be a 9×9 array of integers 0–9" }, + { status: 400 }, + ); + } + if (!isValidGrid(solution)) { + return NextResponse.json( + { error: "solution must be a 9×9 array of integers 0–9" }, + { status: 400 }, + ); + } + + isCorrect = validateSudoku(playerGrid, solution); + qualityScore = combinedQualityScore("sudoku", difficulty, durationSecs); + exerciseType = "sudoku"; + description = `Completed ${difficulty} Sudoku in ${Math.round(durationSecs)}s`; + metadata = { difficulty }; + } + + if (!isCorrect) { + return NextResponse.json( + { correct: false, message: "Puzzle not solved correctly." }, + { status: 200 }, + ); + } + + // --- Fetch user (always user id=1 for now) --- + const user = await prisma.user.findFirst({ + where: { id: 1 }, + include: { categorySkills: { where: { category: "logic" } } }, + }); + + if (!user) { + return NextResponse.json({ error: "No user found" }, { status: 404 }); + } + + const logicSkill = user.categorySkills[0]; + if (!logicSkill) { + return NextResponse.json( + { error: "Logic CategorySkill not found" }, + { status: 500 }, + ); + } + + // --- Personal best check (must run before inserting the new activity) --- + const pbResult = await getPersonalBest(1, exerciseType, difficulty, durationSecs); + + // --- Speed bonus (for response transparency) --- + const parSecs = PAR_TIMES[puzzleType]?.[difficulty] ?? 0; + const speedBonus = isCorrect ? calcSpeedBonus(durationSecs, parSecs) : 0; + + // --- XP calculation (with skill tree multiplier) --- + const { baseXp, maxQualityBonus } = EXERCISE_XP["logic"]; + const isCriticalHit = rollCriticalHit(); + const multiplierPercent = await getMultiplierPercent(prisma, 1, "logic"); + + const xpResult = calculateXpGain({ + baseXp, + qualityScore, + maxQualityBonus, + isCriticalHit, + multiplierPercent, + }); + + // --- Level-up checks (user + category) --- + const userLevelResult = checkLevelUp({ + currentXp: user.currentXp + xpResult.totalXp, + xpToNextLevel: user.xpToNextLevel, + level: user.level, + }); + + const categoryLevelResult = checkLevelUp({ + currentXp: logicSkill.currentXp + xpResult.totalXp, + xpToNextLevel: logicSkill.xpToNext, + level: logicSkill.level, + }); + + // --- Title progression --- + const newTitle = getTitleForLevel(userLevelResult.newLevel); + const titleChanged = newTitle !== user.title; + + // --- Streak processing (idempotent — no-op if already run today) --- + await processEndOfDay(user.id); + + // --- Daily log bookkeeping --- + const now = new Date(); + const todayStart = new Date( + Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate()), + ); + const tomorrowStart = new Date(todayStart.getTime() + 86_400_000); + + const existingLog = await prisma.dailyLog.findFirst({ + where: { + userId: 1, + date: { gte: todayStart, lt: tomorrowStart }, + }, + }); + + const newXpEarned = (existingLog?.xpEarned ?? 0) + xpResult.totalXp; + const newActivityCount = (existingLog?.activityCount ?? 0) + 1; + const goalMet = newXpEarned >= user.dailyGoalXp; + + // --- Persist all changes in a transaction --- + let unlockResult = { unlocked: [] as string[], streakFreezesGranted: 0 }; + await prisma.$transaction(async (tx) => { + // Record the activity + await tx.activity.create({ + data: { + userId: 1, + category: "logic", + exerciseType, + description, + baseXp: xpResult.baseXp, + qualityBonus: xpResult.qualityBonus, + isCriticalHit: xpResult.isCriticalHit, + totalXp: xpResult.totalXp, + score: qualityScore, + durationSecs: Math.round(durationSecs), + metadata: JSON.stringify(metadata), + }, + }); + + // Update user XP and level + await tx.user.update({ + where: { id: 1 }, + data: { + totalXp: user.totalXp + xpResult.totalXp, + currentXp: userLevelResult.remainingXp, + xpToNextLevel: userLevelResult.newXpToNextLevel, + level: userLevelResult.newLevel, + ...(titleChanged && { title: newTitle }), + }, + }); + + // Update category skill XP and level + await tx.categorySkill.update({ + where: { id: logicSkill.id }, + data: { + totalXp: logicSkill.totalXp + xpResult.totalXp, + currentXp: categoryLevelResult.remainingXp, + xpToNext: categoryLevelResult.newXpToNextLevel, + level: categoryLevelResult.newLevel, + }, + }); + + // Auto-unlock skill tree nodes if category leveled up + if (categoryLevelResult.levelsGained > 0) { + unlockResult = await processSkillUnlocks( + tx, 1, "logic", categoryLevelResult.newLevel, + ); + } + + // Upsert daily log + if (existingLog) { + await tx.dailyLog.update({ + where: { id: existingLog.id }, + data: { + xpEarned: newXpEarned, + activityCount: newActivityCount, + goalMet, + }, + }); + } else { + await tx.dailyLog.create({ + data: { + userId: 1, + date: todayStart, + xpEarned: newXpEarned, + activityCount: newActivityCount, + goalMet, + }, + }); + } + }); + + return NextResponse.json({ + correct: true, + xp: { ...xpResult, multiplierPercent }, + isCriticalHit: xpResult.isCriticalHit, + speedBonus: Math.round(speedBonus * 100) / 100, + parSecs: parSecs || null, + isPersonalBest: pbResult.isPersonalBest, + prevBestSecs: pbResult.prevBestSecs, + levelUp: userLevelResult.levelsGained > 0, + newUserLevel: userLevelResult.newLevel, + categoryLevelUp: categoryLevelResult.levelsGained > 0, + newCategoryLevel: categoryLevelResult.newLevel, + dailyGoalMet: goalMet, + categoryXp: { + currentXp: categoryLevelResult.remainingXp, + xpToNext: categoryLevelResult.newXpToNextLevel, + level: categoryLevelResult.newLevel, + levelUp: categoryLevelResult.levelsGained > 0, + }, + newTitle: titleChanged ? newTitle : undefined, + unlocks: unlockResult.unlocked, + streakFreezesGranted: unlockResult.streakFreezesGranted, + message: isCriticalHit + ? "Critical Hit! Puzzle solved!" + : "Puzzle solved correctly!", + }); +}); diff --git a/src/app/api/profile/__tests__/route.test.ts b/src/app/api/profile/__tests__/route.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..2df3c8bc5b8e1a036ed7dbd489cbb242d5a913ac --- /dev/null +++ b/src/app/api/profile/__tests__/route.test.ts @@ -0,0 +1,535 @@ +/** + * Tests for GET /api/profile + * + * Covers: + * - 404 when no user found + * - response shape: user, stats, categorySkills, skillTree, unlocks, chesscomStats, dailyActivity + * - user fields: all fields including xpToNextLevel (computed) + * - stats: totalExercises, totalTimeSecs, totalXpAllTime, exercisesByCat + * - exercisesByCat: aggregated per category + * - categorySkills: mapped correctly + * - skillTree: all nodes with unlocked flag + * - unlocked flag: true for nodes in user.unlocks, false otherwise + * - unlocks: maps nodeId, nodeName, unlockedAt + * - null durationSecs handled gracefully + * - empty activities and nodes + * - DB errors propagate as 500 + * - Chess.com stats: null when chesscomUsername is null + * - Chess.com stats: null when getPlayerStats returns null (unknown username) + * - Chess.com stats: populated with ratings when chesscomUsername is set and API succeeds + * - Chess.com stats: includes rapid, blitz, bullet, daily, best ratings, puzzle rush, tactics + * - Chess.com stats: fields are null when time class is absent from API response + * - getPlayerStats not called when chesscomUsername is null + * - dailyActivity: included in response (empty when no logs) + * - dailyActivity: maps date, xpEarned, activityCount, goalMet from daily logs + * - dailyActivity: queries last 90 days (gte filter) + */ + +import { describe, it, expect, vi, beforeEach } from "vitest"; +import { NextRequest } from "next/server"; + +// --------------------------------------------------------------------------- +// Mock prisma +// --------------------------------------------------------------------------- + +const mockUserFindFirst = vi.fn(); +const mockSkillTreeNodeFindMany = vi.fn(); +const mockActivityFindMany = vi.fn(); +const mockDailyLogFindMany = vi.fn(); + +vi.mock("@/lib/db", () => ({ + prisma: { + user: { findFirst: (...args: unknown[]) => mockUserFindFirst(...args) }, + skillTreeNode: { findMany: (...args: unknown[]) => mockSkillTreeNodeFindMany(...args) }, + activity: { findMany: (...args: unknown[]) => mockActivityFindMany(...args) }, + dailyLog: { findMany: (...args: unknown[]) => mockDailyLogFindMany(...args) }, + }, +})); + +// --------------------------------------------------------------------------- +// Mock Chess.com client +// --------------------------------------------------------------------------- + +const mockGetPlayerStats = vi.fn(); +const mockGetBestRating = vi.fn(); + +vi.mock("@/lib/chesscom", () => ({ + getPlayerStats: (...args: unknown[]) => mockGetPlayerStats(...args), + getBestRating: (...args: unknown[]) => mockGetBestRating(...args), +})); + +import { GET } from "../route"; + +// --------------------------------------------------------------------------- +// Fixtures +// --------------------------------------------------------------------------- + +const baseUser = { + id: 1, + name: "Player One", + level: 5, + totalXp: 1250, + currentXp: 250, + title: "Apprentice", + dailyGoalXp: 100, + streak: 3, + longestStreak: 10, + streakFreezes: 2, + lichessUsername: "player1", + chesscomUsername: null, + createdAt: new Date("2026-01-01T00:00:00Z"), + categorySkills: [ + { category: "CHESS", level: 2, totalXp: 300, currentXp: 50, xpToNext: 150 }, + { category: "FEYNMAN", level: 1, totalXp: 100, currentXp: 100, xpToNext: 100 }, + ], + unlocks: [ + { nodeId: 10, node: { name: "Chess Basics" }, unlockedAt: new Date("2026-02-01T00:00:00Z") }, + ], +}; + +const baseNodes = [ + { id: 10, category: "CHESS", name: "Chess Basics", description: "Beginner chess concepts", levelRequired: 1, parentNodeId: null, nodeType: "skill" }, + { id: 11, category: "CHESS", name: "Tactical Patterns", description: "Common tactics", levelRequired: 2, parentNodeId: 10, nodeType: "skill" }, + { id: 20, category: "FEYNMAN", name: "Feynman Foundations", description: "Core Feynman method", levelRequired: 1, parentNodeId: null, nodeType: "skill" }, +]; + +const baseActivities = [ + { category: "CHESS", durationSecs: 120, createdAt: new Date("2026-03-24T10:00:00Z"), totalXp: 40 }, + { category: "CHESS", durationSecs: 90, createdAt: new Date("2026-03-23T09:00:00Z"), totalXp: 30 }, + { category: "FEYNMAN", durationSecs: null, createdAt: new Date("2026-03-22T08:00:00Z"), totalXp: 50 }, +]; + +function makeGet(): NextRequest { + return new NextRequest("http://localhost/api/profile"); +} + +async function json(res: Response): Promise { + return res.json(); +} + +// --------------------------------------------------------------------------- +// Tests +// --------------------------------------------------------------------------- + +const baseDailyLogs = [ + { date: new Date("2026-03-24T00:00:00Z"), xpEarned: 120, activityCount: 3, goalMet: true }, + { date: new Date("2026-03-23T00:00:00Z"), xpEarned: 60, activityCount: 1, goalMet: false }, +]; + +describe("GET /api/profile", () => { + beforeEach(() => { + vi.clearAllMocks(); + mockSkillTreeNodeFindMany.mockResolvedValue(baseNodes); + mockActivityFindMany.mockResolvedValue(baseActivities); + mockDailyLogFindMany.mockResolvedValue(baseDailyLogs); + // Default: Chess.com not called (user has no chesscomUsername in baseUser) + mockGetPlayerStats.mockResolvedValue(null); + mockGetBestRating.mockReturnValue(null); + }); + + it("returns 404 when no user found", async () => { + mockUserFindFirst.mockResolvedValue(null); + const res = await GET(makeGet()); + expect(res.status).toBe(404); + }); + + it("returns 200 with full response shape", async () => { + mockUserFindFirst.mockResolvedValue(baseUser); + const res = await GET(makeGet()); + expect(res.status).toBe(200); + + const body = await json(res) as Record; + expect(body).toHaveProperty("user"); + expect(body).toHaveProperty("stats"); + expect(body).toHaveProperty("categorySkills"); + expect(body).toHaveProperty("skillTree"); + expect(body).toHaveProperty("unlocks"); + expect(body).toHaveProperty("dailyActivity"); + }); + + it("maps user fields correctly", async () => { + mockUserFindFirst.mockResolvedValue(baseUser); + const res = await GET(makeGet()); + const body = await json(res) as Record; + const user = body.user as Record; + + expect(user.id).toBe(1); + expect(user.name).toBe("Player One"); + expect(user.level).toBe(5); + expect(user.totalXp).toBe(1250); + expect(user.currentXp).toBe(250); + expect(user.title).toBe("Apprentice"); + expect(user.dailyGoalXp).toBe(100); + expect(user.streak).toBe(3); + expect(user.longestStreak).toBe(10); + expect(user.streakFreezes).toBe(2); + expect(user.lichessUsername).toBe("player1"); + expect(user.chesscomUsername).toBeNull(); + expect(user).toHaveProperty("createdAt"); + }); + + it("computes xpToNextLevel via xpForLevel(level + 1)", async () => { + mockUserFindFirst.mockResolvedValue(baseUser); + const res = await GET(makeGet()); + const body = await json(res) as Record; + const user = body.user as Record; + + expect(typeof user.xpToNextLevel).toBe("number"); + expect(user.xpToNextLevel as number).toBeGreaterThan(0); + }); + + it("computes stats.totalExercises", async () => { + mockUserFindFirst.mockResolvedValue(baseUser); + const res = await GET(makeGet()); + const body = await json(res) as Record; + const stats = body.stats as Record; + expect(stats.totalExercises).toBe(3); + }); + + it("computes stats.totalTimeSecs (null treated as 0)", async () => { + mockUserFindFirst.mockResolvedValue(baseUser); + const res = await GET(makeGet()); + const body = await json(res) as Record; + const stats = body.stats as Record; + // 120 + 90 + 0 (null) = 210 + expect(stats.totalTimeSecs).toBe(210); + }); + + it("computes stats.totalXpAllTime", async () => { + mockUserFindFirst.mockResolvedValue(baseUser); + const res = await GET(makeGet()); + const body = await json(res) as Record; + const stats = body.stats as Record; + // 40 + 30 + 50 = 120 + expect(stats.totalXpAllTime).toBe(120); + }); + + it("builds exercisesByCat per category", async () => { + mockUserFindFirst.mockResolvedValue(baseUser); + const res = await GET(makeGet()); + const body = await json(res) as Record; + const stats = body.stats as Record; + const byCat = stats.exercisesByCat as Record; + + expect(byCat.CHESS).toBe(2); + expect(byCat.FEYNMAN).toBe(1); + }); + + it("maps categorySkills correctly", async () => { + mockUserFindFirst.mockResolvedValue(baseUser); + const res = await GET(makeGet()); + const body = await json(res) as Record; + const skills = body.categorySkills as Array>; + + expect(skills).toHaveLength(2); + expect(skills[0]).toMatchObject({ + category: "CHESS", + level: 2, + totalXp: 300, + currentXp: 50, + xpToNext: 150, + }); + }); + + it("maps skill tree nodes with unlocked flag", async () => { + mockUserFindFirst.mockResolvedValue(baseUser); + const res = await GET(makeGet()); + const body = await json(res) as Record; + const skillTree = body.skillTree as Array>; + + expect(skillTree).toHaveLength(3); + + // Node 10 is in user.unlocks — should be unlocked: true + const node10 = skillTree.find((n) => n.id === 10); + expect(node10?.unlocked).toBe(true); + expect(node10?.name).toBe("Chess Basics"); + expect(node10?.category).toBe("CHESS"); + expect(node10?.levelRequired).toBe(1); + expect(node10?.parentNodeId).toBeNull(); + expect(node10?.nodeType).toBe("skill"); + + // Node 11 is not unlocked + const node11 = skillTree.find((n) => n.id === 11); + expect(node11?.unlocked).toBe(false); + + // Node 20 is not unlocked + const node20 = skillTree.find((n) => n.id === 20); + expect(node20?.unlocked).toBe(false); + }); + + it("maps unlocks with nodeId, nodeName, unlockedAt", async () => { + mockUserFindFirst.mockResolvedValue(baseUser); + const res = await GET(makeGet()); + const body = await json(res) as Record; + const unlocks = body.unlocks as Array>; + + expect(unlocks).toHaveLength(1); + expect(unlocks[0].nodeId).toBe(10); + expect(unlocks[0].nodeName).toBe("Chess Basics"); + expect(unlocks[0]).toHaveProperty("unlockedAt"); + }); + + it("handles empty activities gracefully", async () => { + mockUserFindFirst.mockResolvedValue(baseUser); + mockActivityFindMany.mockResolvedValue([]); + + const res = await GET(makeGet()); + const body = await json(res) as Record; + const stats = body.stats as Record; + + expect(stats.totalExercises).toBe(0); + expect(stats.totalTimeSecs).toBe(0); + expect(stats.totalXpAllTime).toBe(0); + expect(stats.exercisesByCat).toEqual({}); + }); + + it("handles empty skill tree nodes", async () => { + mockUserFindFirst.mockResolvedValue(baseUser); + mockSkillTreeNodeFindMany.mockResolvedValue([]); + + const res = await GET(makeGet()); + const body = await json(res) as Record; + expect(body.skillTree).toEqual([]); + }); + + it("handles user with no unlocks", async () => { + mockUserFindFirst.mockResolvedValue({ ...baseUser, unlocks: [] }); + + const res = await GET(makeGet()); + const body = await json(res) as Record; + const skillTree = body.skillTree as Array>; + + expect(body.unlocks).toEqual([]); + // All nodes should be unlocked: false + for (const node of skillTree) { + expect(node.unlocked).toBe(false); + } + }); + + it("queries skill tree nodes ordered by category then levelRequired", async () => { + mockUserFindFirst.mockResolvedValue(baseUser); + + await GET(makeGet()); + + expect(mockSkillTreeNodeFindMany).toHaveBeenCalledWith({ + orderBy: [{ category: "asc" }, { levelRequired: "asc" }], + }); + }); + + it("queries activities selecting minimal fields", async () => { + mockUserFindFirst.mockResolvedValue(baseUser); + + await GET(makeGet()); + + expect(mockActivityFindMany).toHaveBeenCalledWith( + expect.objectContaining({ + where: { userId: 1 }, + select: expect.objectContaining({ + category: true, + durationSecs: true, + totalXp: true, + }), + }), + ); + }); + + it("propagates DB errors as 500", async () => { + mockUserFindFirst.mockRejectedValue(new Error("DB down")); + const res = await GET(makeGet()); + expect(res.status).toBe(500); + }); + + // --------------------------------------------------------------------------- + // Chess.com stats + // --------------------------------------------------------------------------- + + it("returns chesscomStats: null when user has no chesscomUsername", async () => { + mockUserFindFirst.mockResolvedValue({ ...baseUser, chesscomUsername: null }); + const res = await GET(makeGet()); + const body = await json(res) as Record; + expect(body.chesscomStats).toBeNull(); + expect(mockGetPlayerStats).not.toHaveBeenCalled(); + }); + + it("does not call getPlayerStats when chesscomUsername is null", async () => { + mockUserFindFirst.mockResolvedValue({ ...baseUser, chesscomUsername: null }); + await GET(makeGet()); + expect(mockGetPlayerStats).not.toHaveBeenCalled(); + }); + + it("returns chesscomStats: null when getPlayerStats returns null (unknown user)", async () => { + mockUserFindFirst.mockResolvedValue({ ...baseUser, chesscomUsername: "hikaru" }); + mockGetPlayerStats.mockResolvedValue(null); + const res = await GET(makeGet()); + const body = await json(res) as Record; + expect(body.chesscomStats).toBeNull(); + }); + + it("calls getPlayerStats with the chesscomUsername", async () => { + mockUserFindFirst.mockResolvedValue({ ...baseUser, chesscomUsername: "hikaru" }); + mockGetPlayerStats.mockResolvedValue(null); + await GET(makeGet()); + expect(mockGetPlayerStats).toHaveBeenCalledWith("hikaru"); + }); + + it("returns populated chesscomStats when API succeeds", async () => { + mockUserFindFirst.mockResolvedValue({ ...baseUser, chesscomUsername: "hikaru" }); + mockGetBestRating.mockReturnValue(3200); + mockGetPlayerStats.mockResolvedValue({ + chess_rapid: { + last: { rating: 2900, date: 1700000000 }, + best: { rating: 3000, date: 1690000000 }, + record: { win: 100, loss: 20, draw: 10 }, + }, + chess_blitz: { + last: { rating: 3100, date: 1700000000 }, + best: { rating: 3200, date: 1690000000 }, + record: { win: 200, loss: 30, draw: 20 }, + }, + chess_bullet: { + last: { rating: 3150, date: 1700000000 }, + best: { rating: 3250, date: 1690000000 }, + record: { win: 150, loss: 25, draw: 15 }, + }, + chess_daily: { + last: { rating: 2800, date: 1700000000 }, + best: { rating: 2850, date: 1690000000 }, + record: { win: 50, loss: 5, draw: 2 }, + }, + tactics: { highest: { rating: 2950, date: 0 }, lowest: { rating: 1500, date: 0 } }, + puzzle_rush: { best: { total_attempts: 150, score: 87 } }, + }); + + const res = await GET(makeGet()); + const body = await json(res) as Record; + const stats = body.chesscomStats as Record; + + expect(stats).not.toBeNull(); + expect(stats.bestRating).toBe(3200); + expect(stats.rapid).toBe(2900); + expect(stats.blitz).toBe(3100); + expect(stats.bullet).toBe(3150); + expect(stats.daily).toBe(2800); + expect(stats.rapidBest).toBe(3000); + expect(stats.blitzBest).toBe(3200); + expect(stats.bulletBest).toBe(3250); + expect(stats.tacticsHighest).toBe(2950); + expect(stats.puzzleRushBest).toBe(87); + }); + + it("returns null for absent time classes", async () => { + mockUserFindFirst.mockResolvedValue({ ...baseUser, chesscomUsername: "newplayer" }); + mockGetBestRating.mockReturnValue(1500); + mockGetPlayerStats.mockResolvedValue({ + // Only rapid — no blitz, bullet, daily, tactics, puzzle_rush + chess_rapid: { + last: { rating: 1500, date: 1700000000 }, + best: { rating: 1600, date: 1690000000 }, + record: { win: 10, loss: 5, draw: 2 }, + }, + }); + + const res = await GET(makeGet()); + const body = await json(res) as Record; + const stats = body.chesscomStats as Record; + + expect(stats.rapid).toBe(1500); + expect(stats.rapidBest).toBe(1600); + expect(stats.blitz).toBeNull(); + expect(stats.blitzBest).toBeNull(); + expect(stats.bullet).toBeNull(); + expect(stats.bulletBest).toBeNull(); + expect(stats.daily).toBeNull(); + expect(stats.tacticsHighest).toBeNull(); + expect(stats.puzzleRushBest).toBeNull(); + }); + + it("includes chesscomStats in the response shape when username is set", async () => { + mockUserFindFirst.mockResolvedValue({ ...baseUser, chesscomUsername: "magnus" }); + mockGetBestRating.mockReturnValue(2800); + mockGetPlayerStats.mockResolvedValue({ + chess_rapid: { last: { rating: 2800, date: 0 }, best: { rating: 2850, date: 0 }, record: { win: 1, loss: 0, draw: 0 } }, + }); + + const res = await GET(makeGet()); + const body = await json(res) as Record; + // chesscomStats key should exist (not missing from response) + expect(Object.prototype.hasOwnProperty.call(body, "chesscomStats")).toBe(true); + }); + + // --------------------------------------------------------------------------- + // dailyActivity (streak calendar heatmap) + // --------------------------------------------------------------------------- + + it("dailyActivity is an array in response", async () => { + mockUserFindFirst.mockResolvedValue(baseUser); + const res = await GET(makeGet()); + const body = await json(res) as Record; + expect(Array.isArray(body.dailyActivity)).toBe(true); + }); + + it("dailyActivity is empty when no daily logs exist", async () => { + mockDailyLogFindMany.mockResolvedValue([]); + mockUserFindFirst.mockResolvedValue(baseUser); + const res = await GET(makeGet()); + const body = await json(res) as Record; + expect(body.dailyActivity).toEqual([]); + }); + + it("dailyActivity maps date, xpEarned, activityCount, goalMet", async () => { + mockUserFindFirst.mockResolvedValue(baseUser); + const res = await GET(makeGet()); + const body = await json(res) as Record; + const activity = body.dailyActivity as Array>; + + expect(activity).toHaveLength(2); + + const first = activity[0]; + expect(first).toHaveProperty("date"); + expect(first.xpEarned).toBe(120); + expect(first.activityCount).toBe(3); + expect(first.goalMet).toBe(true); + + const second = activity[1]; + expect(second.xpEarned).toBe(60); + expect(second.activityCount).toBe(1); + expect(second.goalMet).toBe(false); + }); + + it("dailyActivity queries with gte filter (last 90 days)", async () => { + mockUserFindFirst.mockResolvedValue(baseUser); + await GET(makeGet()); + + expect(mockDailyLogFindMany).toHaveBeenCalledOnce(); + const callArgs = mockDailyLogFindMany.mock.calls[0][0] as Record; + const where = callArgs.where as Record; + const dateFilter = (where.date as Record).gte as Date; + + // Should be ~89 days ago (within a day's tolerance) + const nowMs = Date.now(); + const diffDays = (nowMs - dateFilter.getTime()) / (1000 * 60 * 60 * 24); + expect(diffDays).toBeGreaterThan(88); + expect(diffDays).toBeLessThan(91); + }); + + it("dailyActivity query uses userId filter", async () => { + mockUserFindFirst.mockResolvedValue(baseUser); + await GET(makeGet()); + + const callArgs = mockDailyLogFindMany.mock.calls[0][0] as Record; + const where = callArgs.where as Record; + expect(where.userId).toBe(1); + }); + + it("dailyActivity query selects only needed fields", async () => { + mockUserFindFirst.mockResolvedValue(baseUser); + await GET(makeGet()); + + const callArgs = mockDailyLogFindMany.mock.calls[0][0] as Record; + const select = callArgs.select as Record; + expect(select).toHaveProperty("date"); + expect(select).toHaveProperty("xpEarned"); + expect(select).toHaveProperty("activityCount"); + expect(select).toHaveProperty("goalMet"); + }); +}); diff --git a/src/app/api/profile/route.ts b/src/app/api/profile/route.ts new file mode 100644 index 0000000000000000000000000000000000000000..8429a4396382c711548aa7e4bb3a48235754b4e7 --- /dev/null +++ b/src/app/api/profile/route.ts @@ -0,0 +1,152 @@ +import { NextResponse } from "next/server"; +import { prisma } from "@/lib/db"; +import { xpForLevel } from "@/config/xp"; +import { withApiError } from "@/lib/api-error"; +import { + getPlayerStats, + getBestRating, + type ChessComPlayerStats, +} from "@/lib/chesscom"; + +// --------------------------------------------------------------------------- +// Types +// --------------------------------------------------------------------------- + +export interface ChessComStatsResult { + bestRating: number | null; + rapid: number | null; + blitz: number | null; + bullet: number | null; + daily: number | null; + rapidBest: number | null; + blitzBest: number | null; + bulletBest: number | null; + puzzleRushBest: number | null; + tacticsHighest: number | null; +} + +export const GET = withApiError(async () => { + const user = await prisma.user.findFirst({ + where: { id: 1 }, + include: { + categorySkills: true, + unlocks: { include: { node: true } }, + }, + }); + + if (!user) { + return NextResponse.json({ error: "No user found", status: 404 }, { status: 404 }); + } + + // All skill tree nodes + const allNodes = await prisma.skillTreeNode.findMany({ + orderBy: [{ category: "asc" }, { levelRequired: "asc" }], + }); + + // Activity count and time totals + const activities = await prisma.activity.findMany({ + where: { userId: 1 }, + select: { category: true, durationSecs: true, createdAt: true, totalXp: true }, + }); + + const totalExercises = activities.length; + const totalTimeSecs = activities.reduce((s: number, a: { durationSecs: number | null }) => s + (a.durationSecs ?? 0), 0); + const totalXpAllTime = activities.reduce((s: number, a: { totalXp: number }) => s + a.totalXp, 0); + + // Per-category exercise counts + const exercisesByCat: Record = {}; + for (const a of activities) { + exercisesByCat[a.category] = (exercisesByCat[a.category] ?? 0) + 1; + } + + // Streak info + const longestStreak = user.longestStreak; + const currentStreak = user.streak; + + const unlockedNodeIds = new Set(user.unlocks.map((u: { nodeId: number }) => u.nodeId)); + + // Last 90 days of daily activity for streak calendar heatmap + const ninetyDaysAgo = new Date(); + ninetyDaysAgo.setUTCDate(ninetyDaysAgo.getUTCDate() - 89); + ninetyDaysAgo.setUTCHours(0, 0, 0, 0); + + const dailyLogs = await prisma.dailyLog.findMany({ + where: { userId: 1, date: { gte: ninetyDaysAgo } }, + orderBy: { date: "asc" }, + select: { date: true, xpEarned: true, activityCount: true, goalMet: true }, + }); + + // Chess.com ratings (optional — only fetched when username is set) + let chesscomStats: ChessComStatsResult | null = null; + if (user.chesscomUsername) { + const raw: ChessComPlayerStats | null = await getPlayerStats(user.chesscomUsername); + if (raw) { + chesscomStats = { + bestRating: getBestRating(raw), + rapid: raw.chess_rapid?.last?.rating ?? null, + blitz: raw.chess_blitz?.last?.rating ?? null, + bullet: raw.chess_bullet?.last?.rating ?? null, + daily: raw.chess_daily?.last?.rating ?? null, + rapidBest: raw.chess_rapid?.best?.rating ?? null, + blitzBest: raw.chess_blitz?.best?.rating ?? null, + bulletBest: raw.chess_bullet?.best?.rating ?? null, + puzzleRushBest: raw.puzzle_rush?.best?.score ?? null, + tacticsHighest: raw.tactics?.highest?.rating ?? null, + }; + } + } + + return NextResponse.json({ + user: { + id: user.id, + name: user.name, + level: user.level, + totalXp: user.totalXp, + currentXp: user.currentXp, + xpToNextLevel: xpForLevel(user.level + 1), + title: user.title, + dailyGoalXp: user.dailyGoalXp, + streak: currentStreak, + longestStreak, + streakFreezes: user.streakFreezes, + lichessUsername: user.lichessUsername, + chesscomUsername: user.chesscomUsername, + createdAt: user.createdAt, + }, + stats: { + totalExercises, + totalTimeSecs, + totalXpAllTime, + exercisesByCat, + }, + categorySkills: user.categorySkills.map((cs: { category: string; level: number; totalXp: number; currentXp: number; xpToNext: number }) => ({ + category: cs.category, + level: cs.level, + totalXp: cs.totalXp, + currentXp: cs.currentXp, + xpToNext: cs.xpToNext, + })), + skillTree: allNodes.map((n: { id: number; category: string; name: string; description: string; levelRequired: number; parentNodeId: number | null; nodeType: string }) => ({ + id: n.id, + category: n.category, + name: n.name, + description: n.description, + levelRequired: n.levelRequired, + parentNodeId: n.parentNodeId, + nodeType: n.nodeType, + unlocked: unlockedNodeIds.has(n.id), + })), + unlocks: user.unlocks.map((u: { nodeId: number; node: { name: string }; unlockedAt: Date }) => ({ + nodeId: u.nodeId, + nodeName: u.node.name, + unlockedAt: u.unlockedAt, + })), + chesscomStats, + dailyActivity: dailyLogs.map((l: { date: Date; xpEarned: number; activityCount: number; goalMet: boolean }) => ({ + date: l.date, + xpEarned: l.xpEarned, + activityCount: l.activityCount, + goalMet: l.goalMet, + })), + }); +}); diff --git a/src/app/api/quests/__tests__/routes.test.ts b/src/app/api/quests/__tests__/routes.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..cde494f282c9658a37ca82ccb6ecfa9516c0eb96 --- /dev/null +++ b/src/app/api/quests/__tests__/routes.test.ts @@ -0,0 +1,855 @@ +/** + * Tests for Quests API route handlers. + * + * Covers: + * GET /api/quests/generate + * - API key guard (503 when missing, no Claude call) + * - Claude integration: prompt includes domain + difficulty, haiku model + * - invalid JSON from Claude → 500 + * - malformed quest (missing title/lesson/exercises) → 500 + * - network error from Claude → 500 + * - valid domain and difficulty params are forwarded in prompt + * - invalid domain/difficulty params fall back to defaults + * - response shape: domain, difficulty, title, lesson, exercises + * + * POST /api/quests/submit + * - API key guard (503 when missing, no Claude call) + * - input validation: missing domain, title, exercises, answers → 400 + * - invalid JSON body → 400 + * - user not found → 404 + * - missing quests CategorySkill → 500 + * - multiple-choice grading: exact match (case-insensitive) → correct; wrong answer → incorrect + * - short-answer: Claude call for grading; Claude error falls back to incorrect + * - qualityScore = correctCount / totalExercises + * - XP: qualityBonus present for high scores; zero for all incorrect + * - XP: critical hit doubles totalXp; isCriticalHit in response + * - XP: multiplier bonus reflected in response + * - response shape: graded, correctCount, totalExercises, qualityScore, xp, levelUp, categoryXp, unlocks + * - DailyLog: created when none exists; updated when one exists + * - goalMet flag set when XP reaches dailyGoalXp + * - processSkillUnlocks called on category level-up; not called otherwise + */ + +import { describe, it, expect, vi, beforeEach } from "vitest"; +import { NextRequest } from "next/server"; + +// --------------------------------------------------------------------------- +// Mock Prisma +// --------------------------------------------------------------------------- + +const mockUserFindFirst = vi.fn(); +const mockDailyLogFindFirst = vi.fn(); +const mockTransaction = vi.fn(); + +vi.mock("@/lib/db", () => ({ + prisma: { + user: { findFirst: (...args: unknown[]) => mockUserFindFirst(...args) }, + dailyLog: { findFirst: (...args: unknown[]) => mockDailyLogFindFirst(...args) }, + $transaction: (...args: unknown[]) => mockTransaction(...args), + }, +})); + +// --------------------------------------------------------------------------- +// Mock Claude +// --------------------------------------------------------------------------- + +const mockClaudeCreate = vi.fn(); + +vi.mock("@/lib/claude", () => ({ + claude: { + messages: { create: (...args: unknown[]) => mockClaudeCreate(...args) }, + }, + parseClaudeJson: (text: string) => JSON.parse(text.trim().replace(/^```(?:json)?\s*/i, "").replace(/\s*```\s*$/, "").trim()), +})); + +// --------------------------------------------------------------------------- +// Mock rollCriticalHit (deterministic) +// --------------------------------------------------------------------------- + +const mockRollCriticalHit = vi.fn(() => false); + +vi.mock("@/lib/xp", async (importOriginal) => { + const actual = await importOriginal(); + return { + ...actual, + rollCriticalHit: () => mockRollCriticalHit(), + }; +}); + +// --------------------------------------------------------------------------- +// Mock getMultiplierPercent +// --------------------------------------------------------------------------- + +const mockGetMultiplierPercent = vi.fn(() => Promise.resolve(0)); + +vi.mock("@/lib/multiplier", () => ({ + getMultiplierPercent: (...args: unknown[]) => (mockGetMultiplierPercent as (...a: unknown[]) => unknown)(...args), +})); + +// --------------------------------------------------------------------------- +// Mock processSkillUnlocks +// --------------------------------------------------------------------------- + +const mockProcessSkillUnlocks = vi.fn((): Promise<{ unlocked: string[]; streakFreezesGranted: number }> => + Promise.resolve({ unlocked: [], streakFreezesGranted: 0 }), +); + +vi.mock("@/lib/skill-unlock", () => ({ + processSkillUnlocks: (...args: unknown[]) => (mockProcessSkillUnlocks as (...a: unknown[]) => unknown)(...args), +})); + +// --------------------------------------------------------------------------- +// Mock processEndOfDay (no-op — streak logic is tested separately) +// --------------------------------------------------------------------------- + +vi.mock("@/lib/streak", () => ({ + processEndOfDay: vi.fn(() => Promise.resolve({ + streak: 1, + freezeUsed: false, + streakBroken: false, + alreadyProcessed: false, + })), +})); + +// --------------------------------------------------------------------------- +// Fixtures +// --------------------------------------------------------------------------- + +function makeRequest( + method: "GET" | "POST", + url: string, + body?: unknown, +): NextRequest { + return new NextRequest(url, { + method, + body: body !== undefined ? JSON.stringify(body) : undefined, + headers: body !== undefined ? { "content-type": "application/json" } : {}, + }); +} + +function makeUser(overrides: Record = {}) { + return { + id: 1, + currentXp: 100, + totalXp: 500, + xpToNextLevel: 200, + level: 3, + title: "Apprentice", + dailyGoalXp: 100, + categorySkills: [ + { + id: 20, + category: "quests", + currentXp: 50, + totalXp: 200, + xpToNext: 150, + level: 2, + }, + ], + ...overrides, + }; +} + +/** Simulates prisma.$transaction by executing the callback with mock tx */ +function mockTxExec() { + mockTransaction.mockImplementation(async (cb: (tx: unknown) => unknown) => { + const tx = { + activity: { create: vi.fn() }, + user: { update: vi.fn() }, + categorySkill: { update: vi.fn() }, + dailyLog: { create: vi.fn(), update: vi.fn() }, + }; + return cb(tx); + }); +} + +const VALID_QUEST: { + domain: string; + difficulty: string; + title: string; + lesson: string; + exercises: Array<{ + id: number; + type: "multiple-choice" | "short-answer"; + question: string; + options?: string[]; + correctAnswer: string; + }>; +} = { + domain: "Science", + difficulty: "beginner", + title: "Photosynthesis Basics", + lesson: "Photosynthesis is the process by which plants convert sunlight into energy. It occurs in chloroplasts. The equation is CO2 + H2O + light → glucose + O2.", + exercises: [ + { + id: 1, + type: "multiple-choice", + question: "Where does photosynthesis occur?", + options: ["Mitochondria", "Chloroplasts", "Nucleus", "Ribosome"], + correctAnswer: "Chloroplasts", + }, + { + id: 2, + type: "multiple-choice", + question: "What gas is released during photosynthesis?", + options: ["CO2", "N2", "O2", "H2"], + correctAnswer: "O2", + }, + { + id: 3, + type: "multiple-choice", + question: "What is the main energy source for photosynthesis?", + options: ["Heat", "Sunlight", "Water", "Glucose"], + correctAnswer: "Sunlight", + }, + { + id: 4, + type: "short-answer", + question: "Explain what photosynthesis does for a plant.", + correctAnswer: "Photosynthesis converts sunlight into glucose (food) for the plant to use as energy.", + }, + ], +}; + +// --------------------------------------------------------------------------- +// GET /api/quests/generate +// --------------------------------------------------------------------------- + +describe("GET /api/quests/generate", () => { + async function callGenerate(params: Record = {}, apiKey = "test-key") { + const savedKey = process.env.ANTHROPIC_API_KEY; + if (apiKey) { + process.env.ANTHROPIC_API_KEY = apiKey; + } else { + delete process.env.ANTHROPIC_API_KEY; + } + const { GET } = await import("@/app/api/quests/generate/route"); + const qs = new URLSearchParams(params).toString(); + const url = `http://localhost/api/quests/generate${qs ? `?${qs}` : ""}`; + const req = makeRequest("GET", url); + const res = await GET(req); + process.env.ANTHROPIC_API_KEY = savedKey; + return res; + } + + beforeEach(() => { + vi.resetModules(); + mockClaudeCreate.mockReset(); + }); + + it("returns 503 when ANTHROPIC_API_KEY is missing", async () => { + const res = await callGenerate({}, ""); + expect(res.status).toBe(503); + expect(mockClaudeCreate).not.toHaveBeenCalled(); + }); + + it("uses claude-3-5-haiku model", async () => { + mockClaudeCreate.mockResolvedValueOnce({ + content: [{ type: "text", text: JSON.stringify(VALID_QUEST) }], + }); + await callGenerate({ domain: "Science", difficulty: "beginner" }); + expect(mockClaudeCreate).toHaveBeenCalledWith( + expect.objectContaining({ model: "claude-haiku-4-5-20251001" }), + ); + }); + + it("includes domain and difficulty in Claude prompt", async () => { + mockClaudeCreate.mockResolvedValueOnce({ + content: [{ type: "text", text: JSON.stringify(VALID_QUEST) }], + }); + await callGenerate({ domain: "Philosophy", difficulty: "advanced" }); + const prompt = mockClaudeCreate.mock.calls[0][0].messages[0].content as string; + expect(prompt).toContain("Philosophy"); + expect(prompt).toContain("advanced"); + }); + + it("returns 200 with correct shape on success", async () => { + mockClaudeCreate.mockResolvedValueOnce({ + content: [{ type: "text", text: JSON.stringify(VALID_QUEST) }], + }); + const res = await callGenerate({ domain: "Science", difficulty: "beginner" }); + expect(res.status).toBe(200); + const body = await res.json(); + expect(body.domain).toBe("Science"); + expect(body.difficulty).toBe("beginner"); + expect(body.title).toBeTruthy(); + expect(body.lesson).toBeTruthy(); + expect(Array.isArray(body.exercises)).toBe(true); + expect(body.exercises.length).toBeGreaterThan(0); + }); + + it("returns 500 when Claude returns invalid JSON", async () => { + mockClaudeCreate.mockResolvedValueOnce({ + content: [{ type: "text", text: "not valid json {{" }], + }); + const res = await callGenerate({}); + expect(res.status).toBe(500); + const body = await res.json(); + expect(body.error).toMatch(/Failed to generate/i); + }); + + it("returns 500 when Claude returns quest with missing title", async () => { + mockClaudeCreate.mockResolvedValueOnce({ + content: [{ type: "text", text: JSON.stringify({ ...VALID_QUEST, title: "" }) }], + }); + const res = await callGenerate({}); + expect(res.status).toBe(500); + const body = await res.json(); + expect(body.error).toMatch(/Malformed/i); + }); + + it("returns 500 when Claude returns quest with missing exercises array", async () => { + mockClaudeCreate.mockResolvedValueOnce({ + content: [{ type: "text", text: JSON.stringify({ ...VALID_QUEST, exercises: [] }) }], + }); + const res = await callGenerate({}); + expect(res.status).toBe(500); + }); + + it("returns 500 when Claude throws a network error", async () => { + mockClaudeCreate.mockRejectedValueOnce(new Error("Network timeout")); + const res = await callGenerate({}); + expect(res.status).toBe(500); + }); + + it("falls back to Science domain when an invalid domain is supplied", async () => { + mockClaudeCreate.mockResolvedValueOnce({ + content: [{ type: "text", text: JSON.stringify(VALID_QUEST) }], + }); + await callGenerate({ domain: "ZZZInvalidDomain" }); + const prompt = mockClaudeCreate.mock.calls[0][0].messages[0].content as string; + // Default is "Science" + expect(prompt).toContain("Science"); + }); + + it("falls back to beginner difficulty when an invalid difficulty is supplied", async () => { + mockClaudeCreate.mockResolvedValueOnce({ + content: [{ type: "text", text: JSON.stringify(VALID_QUEST) }], + }); + await callGenerate({ difficulty: "expert" }); + const prompt = mockClaudeCreate.mock.calls[0][0].messages[0].content as string; + expect(prompt).toContain("beginner"); + }); + + it.each([ + "Art & Architecture", + "Astronomy", + "Cooking & Food Science", + "Logic & Puzzles", + "Law & Justice", + "Environmental Science", + ])("accepts new domain: %s", async (newDomain) => { + mockClaudeCreate.mockResolvedValueOnce({ + content: [{ type: "text", text: JSON.stringify({ ...VALID_QUEST, domain: newDomain }) }], + }); + const res = await callGenerate({ domain: newDomain }); + expect(res.status).toBe(200); + const prompt = mockClaudeCreate.mock.calls[0][0].messages[0].content as string; + expect(prompt).toContain(newDomain); + }); +}); + +// --------------------------------------------------------------------------- +// POST /api/quests/submit +// --------------------------------------------------------------------------- + +describe("POST /api/quests/submit", () => { + async function callSubmit(body: unknown, apiKey = "test-key") { + const savedKey = process.env.ANTHROPIC_API_KEY; + if (apiKey) { + process.env.ANTHROPIC_API_KEY = apiKey; + } else { + delete process.env.ANTHROPIC_API_KEY; + } + const { POST } = await import("@/app/api/quests/submit/route"); + const req = makeRequest("POST", "http://localhost/api/quests/submit", body); + const res = await POST(req); + process.env.ANTHROPIC_API_KEY = savedKey; + return res; + } + + function makeSubmitBody( + overrides: Record = {}, + answers: Record = { 1: "Chloroplasts", 2: "O2", 3: "Sunlight", 4: "Plants use photosynthesis to make food from light" }, + ) { + return { + domain: VALID_QUEST.domain, + title: VALID_QUEST.title, + exercises: VALID_QUEST.exercises, + answers, + ...overrides, + }; + } + + beforeEach(() => { + vi.resetModules(); + mockClaudeCreate.mockReset(); + mockUserFindFirst.mockReset(); + mockDailyLogFindFirst.mockReset(); + mockTransaction.mockReset(); + mockRollCriticalHit.mockReturnValue(false); + mockGetMultiplierPercent.mockResolvedValue(0); + mockProcessSkillUnlocks.mockResolvedValue({ unlocked: [], streakFreezesGranted: 0 }); + }); + + // --- API key guard --- + + it("returns 503 when ANTHROPIC_API_KEY is missing", async () => { + const res = await callSubmit(makeSubmitBody(), ""); + expect(res.status).toBe(503); + expect(mockClaudeCreate).not.toHaveBeenCalled(); + }); + + // --- Input validation --- + + it("returns 400 for invalid JSON body", async () => { + process.env.ANTHROPIC_API_KEY = "test-key"; + const { POST } = await import("@/app/api/quests/submit/route"); + const req = new NextRequest("http://localhost/api/quests/submit", { + method: "POST", + body: "not-json", + headers: { "content-type": "application/json" }, + }); + const res = await POST(req); + expect(res.status).toBe(400); + }); + + it("returns 400 when domain is missing", async () => { + const res = await callSubmit({ title: "T", exercises: [], answers: {} }); + expect(res.status).toBe(400); + }); + + it("returns 400 when title is missing", async () => { + const res = await callSubmit({ domain: "Science", exercises: [], answers: {} }); + expect(res.status).toBe(400); + }); + + it("returns 400 when exercises is missing", async () => { + const res = await callSubmit({ domain: "Science", title: "T", answers: {} }); + expect(res.status).toBe(400); + }); + + it("returns 400 when answers is missing", async () => { + const res = await callSubmit({ domain: "Science", title: "T", exercises: [] }); + expect(res.status).toBe(400); + }); + + // --- DB errors --- + + it("returns 404 when user is not found", async () => { + // short-answer calls Claude for grading, so stub it + mockClaudeCreate.mockResolvedValue({ + content: [{ type: "text", text: JSON.stringify({ correct: true, feedback: "Good." }) }], + }); + mockUserFindFirst.mockResolvedValue(null); + const res = await callSubmit(makeSubmitBody()); + expect(res.status).toBe(404); + }); + + it("returns 500 when quests CategorySkill is missing", async () => { + mockClaudeCreate.mockResolvedValue({ + content: [{ type: "text", text: JSON.stringify({ correct: true, feedback: "Good." }) }], + }); + mockUserFindFirst.mockResolvedValue(makeUser({ categorySkills: [] })); + const res = await callSubmit(makeSubmitBody()); + expect(res.status).toBe(500); + }); + + // --- Grading: multiple-choice --- + + it("marks MC answer correct on exact case-insensitive match", async () => { + // Only MC exercises, no short-answer + const mcOnlyExercises = VALID_QUEST.exercises.slice(0, 3); + mockUserFindFirst.mockResolvedValue(makeUser()); + mockDailyLogFindFirst.mockResolvedValue(null); + mockTxExec(); + + const res = await callSubmit({ + domain: VALID_QUEST.domain, + title: VALID_QUEST.title, + exercises: mcOnlyExercises, + answers: { 1: "chloroplasts", 2: "o2", 3: "sunlight" }, // lowercase + }); + expect(res.status).toBe(200); + const body = await res.json(); + expect(body.correctCount).toBe(3); + expect(body.graded).toHaveLength(3); + body.graded.forEach((g: { correct: boolean }) => expect(g.correct).toBe(true)); + }); + + it("marks MC answer incorrect on wrong answer", async () => { + const mcOnlyExercises = VALID_QUEST.exercises.slice(0, 1); + mockUserFindFirst.mockResolvedValue(makeUser()); + mockDailyLogFindFirst.mockResolvedValue(null); + mockTxExec(); + + const res = await callSubmit({ + domain: VALID_QUEST.domain, + title: VALID_QUEST.title, + exercises: mcOnlyExercises, + answers: { 1: "Mitochondria" }, // wrong + }); + expect(res.status).toBe(200); + const body = await res.json(); + expect(body.correctCount).toBe(0); + expect(body.graded[0].correct).toBe(false); + expect(body.graded[0].feedback).toMatch(/Chloroplasts/i); + }); + + // --- Grading: short-answer --- + + it("calls Claude to grade short-answer exercises", async () => { + const saExercises = [VALID_QUEST.exercises[3]]; // only short-answer + mockClaudeCreate.mockResolvedValueOnce({ + content: [{ type: "text", text: JSON.stringify({ correct: true, feedback: "Great answer." }) }], + }); + mockUserFindFirst.mockResolvedValue(makeUser()); + mockDailyLogFindFirst.mockResolvedValue(null); + mockTxExec(); + + const res = await callSubmit({ + domain: VALID_QUEST.domain, + title: VALID_QUEST.title, + exercises: saExercises, + answers: { 4: "Plants convert sunlight into glucose using photosynthesis." }, + }); + expect(res.status).toBe(200); + expect(mockClaudeCreate).toHaveBeenCalledTimes(1); + const body = await res.json(); + expect(body.graded[0].correct).toBe(true); + expect(body.graded[0].feedback).toBe("Great answer."); + }); + + it("falls back to incorrect when short-answer Claude grading throws", async () => { + const saExercises = [VALID_QUEST.exercises[3]]; + mockClaudeCreate.mockRejectedValueOnce(new Error("Claude down")); + mockUserFindFirst.mockResolvedValue(makeUser()); + mockDailyLogFindFirst.mockResolvedValue(null); + mockTxExec(); + + const res = await callSubmit({ + domain: VALID_QUEST.domain, + title: VALID_QUEST.title, + exercises: saExercises, + answers: { 4: "Some answer." }, + }); + expect(res.status).toBe(200); + const body = await res.json(); + expect(body.graded[0].correct).toBe(false); + expect(body.graded[0].feedback).toMatch(/Could not grade/i); + }); + + // --- Quality score --- + + it("qualityScore = correctCount / totalExercises", async () => { + const mcOnlyExercises = VALID_QUEST.exercises.slice(0, 4); // 3 MC + 1 SA (all MC here) + const allMc = mcOnlyExercises.filter((e) => e.type === "multiple-choice"); + mockUserFindFirst.mockResolvedValue(makeUser()); + mockDailyLogFindFirst.mockResolvedValue(null); + mockTxExec(); + + const res = await callSubmit({ + domain: VALID_QUEST.domain, + title: VALID_QUEST.title, + exercises: allMc, + answers: { 1: "Chloroplasts", 2: "N2", 3: "Sunlight" }, // 2 of 3 correct + }); + expect(res.status).toBe(200); + const body = await res.json(); + expect(body.correctCount).toBe(2); + expect(body.totalExercises).toBe(3); + expect(body.qualityScore).toBeCloseTo(2 / 3, 5); + }); + + // --- Response shape --- + + it("returns 200 with complete response shape", async () => { + mockClaudeCreate.mockResolvedValue({ + content: [{ type: "text", text: JSON.stringify({ correct: true, feedback: "Good." }) }], + }); + mockUserFindFirst.mockResolvedValue(makeUser()); + mockDailyLogFindFirst.mockResolvedValue(null); + mockTxExec(); + + const res = await callSubmit(makeSubmitBody()); + expect(res.status).toBe(200); + const body = await res.json(); + expect(Array.isArray(body.graded)).toBe(true); + expect(typeof body.correctCount).toBe("number"); + expect(typeof body.totalExercises).toBe("number"); + expect(typeof body.qualityScore).toBe("number"); + expect(body.xp).toBeDefined(); + expect(body.xp.baseXp).toBeGreaterThan(0); + expect(body.xp.totalXp).toBeGreaterThan(0); + expect(typeof body.levelUp).toBe("boolean"); + expect(body.categoryXp).toBeDefined(); + expect(Array.isArray(body.unlocks)).toBe(true); + }); + + // --- XP --- + + it("qualityBonus is 0 when all answers are wrong", async () => { + const mcOnly = VALID_QUEST.exercises.slice(0, 3); + mockUserFindFirst.mockResolvedValue(makeUser()); + mockDailyLogFindFirst.mockResolvedValue(null); + mockTxExec(); + + const res = await callSubmit({ + domain: VALID_QUEST.domain, + title: VALID_QUEST.title, + exercises: mcOnly, + answers: { 1: "Wrong", 2: "Wrong", 3: "Wrong" }, + }); + const body = await res.json(); + expect(body.xp.qualityBonus).toBe(0); + }); + + it("critical hit flag doubles totalXp", async () => { + mockClaudeCreate.mockResolvedValue({ + content: [{ type: "text", text: JSON.stringify({ correct: true, feedback: "Good." }) }], + }); + const allMc = VALID_QUEST.exercises.slice(0, 3); + + mockRollCriticalHit.mockReturnValueOnce(true); + mockUserFindFirst.mockResolvedValue(makeUser()); + mockDailyLogFindFirst.mockResolvedValue(null); + mockTxExec(); + const resCrit = await callSubmit({ + domain: VALID_QUEST.domain, + title: VALID_QUEST.title, + exercises: allMc, + answers: { 1: "Chloroplasts", 2: "O2", 3: "Sunlight" }, + }); + const bodyCrit = await resCrit.json(); + + mockRollCriticalHit.mockReturnValueOnce(false); + mockUserFindFirst.mockResolvedValue(makeUser()); + mockDailyLogFindFirst.mockResolvedValue(null); + mockTxExec(); + const resNorm = await callSubmit({ + domain: VALID_QUEST.domain, + title: VALID_QUEST.title, + exercises: allMc, + answers: { 1: "Chloroplasts", 2: "O2", 3: "Sunlight" }, + }); + const bodyNorm = await resNorm.json(); + + expect(bodyCrit.xp.totalXp).toBeGreaterThan(bodyNorm.xp.totalXp); + expect(bodyCrit.xp.isCriticalHit).toBe(true); + }); + + it("multiplier bonus is reflected in xp response", async () => { + mockGetMultiplierPercent.mockResolvedValueOnce(25); + mockClaudeCreate.mockResolvedValue({ + content: [{ type: "text", text: JSON.stringify({ correct: true, feedback: "G." }) }], + }); + mockUserFindFirst.mockResolvedValue(makeUser()); + mockDailyLogFindFirst.mockResolvedValue(null); + mockTxExec(); + + const res = await callSubmit(makeSubmitBody()); + const body = await res.json(); + expect(body.xp.multiplierPercent).toBe(25); + expect(body.xp.multiplierBonus).toBeGreaterThan(0); + }); + + // --- DailyLog --- + + it("creates a new DailyLog when none exists", async () => { + mockClaudeCreate.mockResolvedValue({ + content: [{ type: "text", text: JSON.stringify({ correct: true, feedback: "Good." }) }], + }); + mockUserFindFirst.mockResolvedValue(makeUser()); + mockDailyLogFindFirst.mockResolvedValue(null); + + let created = false; + mockTransaction.mockImplementation(async (cb: (tx: unknown) => unknown) => { + const tx = { + activity: { create: vi.fn() }, + user: { update: vi.fn() }, + categorySkill: { update: vi.fn() }, + dailyLog: { + create: vi.fn(() => { created = true; }), + update: vi.fn(), + }, + }; + return cb(tx); + }); + + await callSubmit(makeSubmitBody()); + expect(created).toBe(true); + }); + + it("updates existing DailyLog when one exists", async () => { + mockClaudeCreate.mockResolvedValue({ + content: [{ type: "text", text: JSON.stringify({ correct: true, feedback: "G." }) }], + }); + mockUserFindFirst.mockResolvedValue(makeUser()); + mockDailyLogFindFirst.mockResolvedValue({ id: 77, xpEarned: 40, activityCount: 1, goalMet: false }); + + let updated = false; + mockTransaction.mockImplementation(async (cb: (tx: unknown) => unknown) => { + const tx = { + activity: { create: vi.fn() }, + user: { update: vi.fn() }, + categorySkill: { update: vi.fn() }, + dailyLog: { + create: vi.fn(), + update: vi.fn(() => { updated = true; }), + }, + }; + return cb(tx); + }); + + await callSubmit(makeSubmitBody()); + expect(updated).toBe(true); + }); + + it("sets goalMet when cumulative XP reaches dailyGoalXp", async () => { + mockClaudeCreate.mockResolvedValue({ + content: [{ type: "text", text: JSON.stringify({ correct: true, feedback: "G." }) }], + }); + mockUserFindFirst.mockResolvedValue(makeUser({ dailyGoalXp: 50 })); + mockDailyLogFindFirst.mockResolvedValue({ id: 5, xpEarned: 45, activityCount: 1, goalMet: false }); + + let capturedGoalMet: boolean | undefined; + mockTransaction.mockImplementation(async (cb: (tx: unknown) => unknown) => { + const tx = { + activity: { create: vi.fn() }, + user: { update: vi.fn() }, + categorySkill: { update: vi.fn() }, + dailyLog: { + create: vi.fn(), + update: vi.fn(({ data }: { data: { goalMet: boolean } }) => { + capturedGoalMet = data.goalMet; + }), + }, + }; + return cb(tx); + }); + + await callSubmit(makeSubmitBody()); + expect(capturedGoalMet).toBe(true); + }); + + // --- Skill unlocks --- + + it("calls processSkillUnlocks when quests category levels up", async () => { + mockClaudeCreate.mockResolvedValue({ + content: [{ type: "text", text: JSON.stringify({ correct: true, feedback: "G." }) }], + }); + const user = makeUser(); + user.categorySkills[0].currentXp = 9999; + user.categorySkills[0].xpToNext = 1; + mockUserFindFirst.mockResolvedValue(user); + mockDailyLogFindFirst.mockResolvedValue(null); + + mockTransaction.mockImplementation(async (cb: (tx: unknown) => unknown) => { + const tx = { + activity: { create: vi.fn() }, + user: { update: vi.fn() }, + categorySkill: { update: vi.fn() }, + dailyLog: { create: vi.fn(), update: vi.fn() }, + }; + mockProcessSkillUnlocks.mockImplementationOnce(() => + Promise.resolve({ unlocked: ["Quest Master"], streakFreezesGranted: 0 }), + ); + return cb(tx); + }); + + const res = await callSubmit(makeSubmitBody()); + expect(res.status).toBe(200); + const body = await res.json(); + expect(Array.isArray(body.unlocks)).toBe(true); + }); + + it("does not call processSkillUnlocks when no category level-up", async () => { + mockClaudeCreate.mockResolvedValue({ + content: [{ type: "text", text: JSON.stringify({ correct: true, feedback: "G." }) }], + }); + const user = makeUser(); + user.categorySkills[0].currentXp = 0; + user.categorySkills[0].xpToNext = 99999; + mockUserFindFirst.mockResolvedValue(user); + mockDailyLogFindFirst.mockResolvedValue(null); + mockProcessSkillUnlocks.mockClear(); + mockTxExec(); + + await callSubmit(makeSubmitBody()); + expect(mockProcessSkillUnlocks).not.toHaveBeenCalled(); + }); + + it("returns empty unlocks and streakFreezesGranted=0 when no level-up", async () => { + mockClaudeCreate.mockResolvedValue({ + content: [{ type: "text", text: JSON.stringify({ correct: true, feedback: "G." }) }], + }); + mockUserFindFirst.mockResolvedValue(makeUser()); + mockDailyLogFindFirst.mockResolvedValue(null); + mockTxExec(); + + const res = await callSubmit(makeSubmitBody()); + const body = await res.json(); + expect(body.unlocks).toEqual([]); + expect(body.streakFreezesGranted).toBe(0); + }); + + // --- durationSecs --- + + describe("durationSecs", () => { + function captureActivityCreate() { + let captured: Record | null = null; + mockTransaction.mockImplementation(async (cb: (tx: unknown) => unknown) => { + const tx = { + activity: { + create: vi.fn((args: { data: Record }) => { + captured = args.data; + }), + }, + user: { update: vi.fn() }, + categorySkill: { update: vi.fn() }, + dailyLog: { create: vi.fn(), update: vi.fn() }, + }; + return cb(tx); + }); + return () => captured; + } + + beforeEach(() => { + mockClaudeCreate.mockResolvedValue({ + content: [{ type: "text", text: JSON.stringify({ correct: true, feedback: "G." }) }], + }); + mockUserFindFirst.mockResolvedValue(makeUser()); + mockDailyLogFindFirst.mockResolvedValue(null); + }); + + it("persists durationSecs when provided", async () => { + const getCapture = captureActivityCreate(); + await callSubmit(makeSubmitBody({ durationSecs: 120 })); + expect(getCapture()?.durationSecs).toBe(120); + }); + + it("rounds durationSecs to the nearest integer", async () => { + const getCapture = captureActivityCreate(); + await callSubmit(makeSubmitBody({ durationSecs: 73.9 })); + expect(getCapture()?.durationSecs).toBe(74); + }); + + it("stores null when durationSecs is omitted", async () => { + const getCapture = captureActivityCreate(); + await callSubmit(makeSubmitBody()); + expect(getCapture()?.durationSecs).toBeNull(); + }); + + it("stores null when durationSecs is negative", async () => { + const getCapture = captureActivityCreate(); + await callSubmit(makeSubmitBody({ durationSecs: -10 })); + expect(getCapture()?.durationSecs).toBeNull(); + }); + + it("persists durationSecs of 0", async () => { + const getCapture = captureActivityCreate(); + await callSubmit(makeSubmitBody({ durationSecs: 0 })); + expect(getCapture()?.durationSecs).toBe(0); + }); + }); +}); diff --git a/src/app/api/quests/generate/route.ts b/src/app/api/quests/generate/route.ts new file mode 100644 index 0000000000000000000000000000000000000000..9be3dd54db9143fdcbe4d111b370229d5d4e1224 --- /dev/null +++ b/src/app/api/quests/generate/route.ts @@ -0,0 +1,155 @@ +import { NextRequest, NextResponse } from "next/server"; +import { claude, parseClaudeJson } from "@/lib/claude"; +import { withApiError } from "@/lib/api-error"; + +export interface QuestExercise { + id: number; + type: "multiple-choice" | "short-answer"; + question: string; + options?: string[]; // for multiple-choice + correctAnswer: string; // for MC: exact match; for SA: model answer +} + +export interface QuestLesson { + domain: string; + difficulty: string; + title: string; + lesson: string; + exercises: QuestExercise[]; +} + +const DOMAINS = [ + "Language", + "Music Theory", + "Mental Math", + "Science", + "Geography", + "History", + "Philosophy", + "Economics", + "Art & Architecture", + "Astronomy", + "Cooking & Food Science", + "Logic & Puzzles", + "Law & Justice", + "Environmental Science", +] as const; + +export type QuestDomain = (typeof DOMAINS)[number]; + +const DIFFICULTIES = ["beginner", "intermediate", "advanced"] as const; + +function normalizeParam( + value: string | null, + allowed: T, + fallback: T[number], +): T[number] { + if (value && (allowed as readonly string[]).includes(value)) { + return value as T[number]; + } + return fallback; +} + +export const GET = withApiError(async (request: NextRequest) => { + if (!process.env.ANTHROPIC_API_KEY) { + return NextResponse.json( + { error: "ANTHROPIC_API_KEY is not configured" }, + { status: 503 }, + ); + } + + const { searchParams } = new URL(request.url); + const rawDomain = searchParams.get("domain"); + const rawDifficulty = searchParams.get("difficulty"); + + const domain = normalizeParam(rawDomain, DOMAINS, "Science"); + const difficulty = normalizeParam(rawDifficulty, DIFFICULTIES, "beginner"); + + let quest: QuestLesson; + try { + const message = await claude.messages.create({ + model: "claude-haiku-4-5-20251001", + max_tokens: 2048, + messages: [ + { + role: "user", + content: `You are a master educator creating a ${difficulty} micro-lesson on a specific topic within the domain "${domain}". + +Pick an interesting, specific subtopic within "${domain}" that can be explained in 3-4 concise paragraphs. + +Create a micro-lesson with: +1. A clear, specific title +2. A lesson body: 3 short paragraphs totaling 150-250 words. Teach a concrete concept, fact, or skill — not vague generalities. +3. Exactly 4 exercises: 3 multiple-choice (each with exactly 4 options, one correct) and 1 short-answer (open-ended, testing application of the lesson). + +For multiple-choice: the correctAnswer must exactly match one of the 4 options strings. +For short-answer: the correctAnswer should be a 1-2 sentence model answer used for grading. + +Respond ONLY with valid JSON (no markdown, no code fences): +{ + "domain": "${domain}", + "difficulty": "${difficulty}", + "title": "...", + "lesson": "...", + "exercises": [ + { + "id": 1, + "type": "multiple-choice", + "question": "...", + "options": ["A", "B", "C", "D"], + "correctAnswer": "A" + }, + { + "id": 2, + "type": "multiple-choice", + "question": "...", + "options": ["A", "B", "C", "D"], + "correctAnswer": "B" + }, + { + "id": 3, + "type": "multiple-choice", + "question": "...", + "options": ["A", "B", "C", "D"], + "correctAnswer": "C" + }, + { + "id": 4, + "type": "short-answer", + "question": "...", + "correctAnswer": "Model answer..." + } + ] +}`, + }, + ], + }); + + const text = + message.content[0].type === "text" ? message.content[0].text : ""; + quest = parseClaudeJson(text) as QuestLesson; + } catch (err) { + return NextResponse.json( + { + error: "Failed to generate quest", + details: err instanceof Error ? err.message : String(err), + }, + { status: 500 }, + ); + } + + // Validate minimal shape + if ( + !quest.title || + !quest.lesson || + !Array.isArray(quest.exercises) || + quest.exercises.length === 0 + ) { + return NextResponse.json( + { error: "Malformed quest response from Claude" }, + { status: 500 }, + ); + } + + return NextResponse.json(quest); +}); diff --git a/src/app/api/quests/submit/route.ts b/src/app/api/quests/submit/route.ts new file mode 100644 index 0000000000000000000000000000000000000000..3165cede46e1a0b5232a288cc373f780026c591a --- /dev/null +++ b/src/app/api/quests/submit/route.ts @@ -0,0 +1,296 @@ +import { NextRequest, NextResponse } from "next/server"; +import { claude, parseClaudeJson } from "@/lib/claude"; +import { prisma } from "@/lib/db"; +// import { Prisma } from "@prisma/client"; +import { calculateXpGain, rollCriticalHit } from "@/lib/xp"; +import { checkLevelUp } from "@/lib/progression"; +import { EXERCISE_XP } from "@/config/xp"; +import type { QuestExercise } from "../generate/route"; +import { processSkillUnlocks } from "@/lib/skill-unlock"; +import { getMultiplierPercent } from "@/lib/multiplier"; +import { getTitleForLevel } from "@/config/titles"; +import { withApiError } from "@/lib/api-error"; +import { processEndOfDay } from "@/lib/streak"; + +interface SubmitBody { + domain: string; + title: string; + exercises: QuestExercise[]; + answers: Record; // exerciseId → user answer + durationSecs?: number; + userId?: number; +} + +interface GradedExercise { + id: number; + correct: boolean; + feedback: string; +} + +async function gradeShortAnswer( + question: string, + modelAnswer: string, + userAnswer: string, +): Promise<{ correct: boolean; feedback: string }> { + try { + const message = await claude.messages.create({ + model: "claude-haiku-4-5-20251001", + max_tokens: 256, + messages: [ + { + role: "user", + content: `Grade this short-answer response. + +Question: ${question} +Model Answer: ${modelAnswer} +Student Answer: ${userAnswer} + +Is the student's answer substantially correct? Respond ONLY with valid JSON (no markdown): +{ "correct": true/false, "feedback": "One sentence of specific feedback." }`, + }, + ], + }); + + const text = + message.content[0].type === "text" ? message.content[0].text : ""; + const result = parseClaudeJson(text) as { correct: boolean; feedback: string }; + return result; + } catch { + // Fallback: mark as incorrect if grading fails + return { + correct: false, + feedback: "Could not grade your answer automatically.", + }; + } +} + +export const POST = withApiError(async (request: NextRequest) => { + if (!process.env.ANTHROPIC_API_KEY) { + return NextResponse.json( + { error: "ANTHROPIC_API_KEY is not configured" }, + { status: 503 }, + ); + } + + let body: SubmitBody; + try { + body = await request.json(); + } catch { + return NextResponse.json({ error: "Invalid JSON body" }, { status: 400 }); + } + + const { domain, title, exercises, answers, durationSecs } = body; + + if (!domain || !title || !Array.isArray(exercises) || !answers) { + return NextResponse.json( + { error: "domain, title, exercises, and answers are required" }, + { status: 400 }, + ); + } + + // Grade each exercise + const graded: GradedExercise[] = []; + + for (const exercise of exercises) { + const userAnswer = answers[exercise.id] ?? ""; + + if (exercise.type === "multiple-choice") { + const correct = + userAnswer.trim().toLowerCase() === + exercise.correctAnswer.trim().toLowerCase(); + graded.push({ + id: exercise.id, + correct, + feedback: correct + ? "Correct!" + : `Correct answer: ${exercise.correctAnswer}`, + }); + } else { + // short-answer — use Claude + const result = await gradeShortAnswer( + exercise.question, + exercise.correctAnswer, + userAnswer, + ); + graded.push({ id: exercise.id, ...result }); + } + } + + const correctCount = graded.filter((g) => g.correct).length; + const qualityScore = correctCount / exercises.length; + + // Fetch user + const userId = body.userId ?? 1; + const user = await prisma.user.findFirst({ + where: { id: userId }, + include: { categorySkills: { where: { category: "quests" } } }, + }); + + if (!user) { + return NextResponse.json({ error: "No user found" }, { status: 404 }); + } + + const questSkill = user.categorySkills[0]; + if (!questSkill) { + return NextResponse.json( + { error: "Quests CategorySkill not found" }, + { status: 500 }, + ); + } + + // XP calculation (with skill tree multiplier) + const { baseXp, maxQualityBonus } = EXERCISE_XP["quests"]; + const isCriticalHit = rollCriticalHit(); + const multiplierPercent = await getMultiplierPercent(prisma, userId, "quests"); + + const xpResult = calculateXpGain({ + baseXp, + qualityScore, + maxQualityBonus, + isCriticalHit, + multiplierPercent, + }); + + // Level-up checks + const userLevelResult = checkLevelUp({ + currentXp: user.currentXp + xpResult.totalXp, + xpToNextLevel: user.xpToNextLevel, + level: user.level, + }); + + const categoryLevelResult = checkLevelUp({ + currentXp: questSkill.currentXp + xpResult.totalXp, + xpToNextLevel: questSkill.xpToNext, + level: questSkill.level, + }); + + // --- Title progression --- + const newTitle = getTitleForLevel(userLevelResult.newLevel); + const titleChanged = newTitle !== user.title; + + // --- Streak processing (idempotent — no-op if already run today) --- + await processEndOfDay(userId); + + // Daily log bookkeeping + const now = new Date(); + const todayStart = new Date( + Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate()), + ); + const tomorrowStart = new Date(todayStart.getTime() + 86_400_000); + + const existingLog = await prisma.dailyLog.findFirst({ + where: { + userId, + date: { gte: todayStart, lt: tomorrowStart }, + }, + }); + + const newXpEarned = (existingLog?.xpEarned ?? 0) + xpResult.totalXp; + const newActivityCount = (existingLog?.activityCount ?? 0) + 1; + const goalMet = newXpEarned >= user.dailyGoalXp; + + // Sanitise optional duration + const safeDuration = + typeof durationSecs === "number" && durationSecs >= 0 + ? Math.round(durationSecs) + : null; + + // Persist in a transaction + let unlockResult = { unlocked: [] as string[], streakFreezesGranted: 0 }; + await prisma.$transaction(async (tx) => { + await tx.activity.create({ + data: { + userId, + category: "quests", + exerciseType: "micro-lesson", + description: `Skill Quest: ${title} (${domain})`, + baseXp: xpResult.baseXp, + qualityBonus: xpResult.qualityBonus, + isCriticalHit: xpResult.isCriticalHit, + totalXp: xpResult.totalXp, + score: qualityScore, + durationSecs: safeDuration, + metadata: JSON.stringify({ + domain, + title, + correctCount, + totalExercises: exercises.length, + }), + }, + }); + + await tx.user.update({ + where: { id: userId }, + data: { + totalXp: user.totalXp + xpResult.totalXp, + currentXp: userLevelResult.remainingXp, + xpToNextLevel: userLevelResult.newXpToNextLevel, + level: userLevelResult.newLevel, + ...(titleChanged && { title: newTitle }), + }, + }); + + await tx.categorySkill.update({ + where: { id: questSkill.id }, + data: { + totalXp: questSkill.totalXp + xpResult.totalXp, + currentXp: categoryLevelResult.remainingXp, + xpToNext: categoryLevelResult.newXpToNextLevel, + level: categoryLevelResult.newLevel, + }, + }); + + // Auto-unlock skill tree nodes if category leveled up + if (categoryLevelResult.levelsGained > 0) { + unlockResult = await processSkillUnlocks( + tx, userId, "quests", categoryLevelResult.newLevel, + ); + } + + if (existingLog) { + await tx.dailyLog.update({ + where: { id: existingLog.id }, + data: { + xpEarned: newXpEarned, + activityCount: newActivityCount, + goalMet, + }, + }); + } else { + await tx.dailyLog.create({ + data: { + userId, + date: todayStart, + xpEarned: newXpEarned, + activityCount: newActivityCount, + goalMet, + }, + }); + } + }); + + return NextResponse.json({ + graded, + correctCount, + totalExercises: exercises.length, + qualityScore, + xp: { + baseXp: xpResult.baseXp, + qualityBonus: xpResult.qualityBonus, + multiplierBonus: xpResult.multiplierBonus, + multiplierPercent, + totalXp: xpResult.totalXp, + isCriticalHit: xpResult.isCriticalHit, + }, + levelUp: userLevelResult.levelsGained > 0, + categoryXp: { + currentXp: categoryLevelResult.remainingXp, + xpToNext: categoryLevelResult.newXpToNextLevel, + level: categoryLevelResult.newLevel, + levelUp: categoryLevelResult.levelsGained > 0, + }, + newTitle: titleChanged ? newTitle : undefined, + unlocks: unlockResult.unlocked, + streakFreezesGranted: unlockResult.streakFreezesGranted, + }); +}); diff --git a/src/app/api/reading/__tests__/routes.test.ts b/src/app/api/reading/__tests__/routes.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..bba6b1880865da88dbc701388e2247efbe7cfe9b --- /dev/null +++ b/src/app/api/reading/__tests__/routes.test.ts @@ -0,0 +1,1148 @@ +/** + * Tests for Reading API route handlers. + * + * Covers: + * GET /api/reading/content + * - list mode: returns article metadata (no body field) + * - slug mode: returns specific article; 404 on unknown slug + * - random mode: returns some article; respects difficulty filter + * + * POST /api/reading/fetch + * - invalid JSON body → 400 + * - missing url and text → 400 + * - invalid URL format → 400 + * - non-http/https protocol → 400 + * - URL fetch: delegates to fetchAndExtract, returns { article, source: "url" } + * - URL fetch error: propagates error message as 422 + * - text paste: delegates to createFromText, returns { article, source: "text" } + * - text paste error: propagates error message as 422 + * + * POST /api/reading/questions + * - API key guard (503 when missing, no Claude call) + * - invalid JSON body → 400 + * - missing slug and content → 400 + * - invalid slug → 404 + * - valid content object accepted alongside slug + * - Claude called with article title and body in prompt + * - haiku model used + * - returns { questions } array on success + * - invalid JSON from Claude → 500 + * - network error from Claude → 500 + * + * POST /api/reading/score + * - API key guard (503 when missing, no Claude call) + * - invalid JSON body → 400 + * - missing answers/questions → 400 + * - invalid slug → 404 + * - missing content object → 400 + * - user not found → 404 + * - missing reading CategorySkill → 500 + * - Claude integration: prompt includes article title + QA pairs + * - haiku model used + * - invalid JSON from Claude → 500 + * - network error from Claude → 500 + * - response shape: scores, overallFeedback, avgScore, xp, levelUp, categoryXp, unlocks + * - XP: quality score derived from avgScore/10; qualityBonus for high scores + * - XP: critical hit doubles totalXp + * - XP: multiplier bonus reflected in response + * - custom content: sets isCustomContent path (exerciseType "comprehension-custom") + * - DailyLog: created when no existing log; updated when log exists + * - goalMet flag when XP reaches dailyGoalXp + * - processSkillUnlocks called on category level-up; not called otherwise + */ + +import { describe, it, expect, vi, beforeEach } from "vitest"; +import { NextRequest } from "next/server"; + +// --------------------------------------------------------------------------- +// Mock Prisma +// --------------------------------------------------------------------------- + +const mockUserFindFirst = vi.fn(); +const mockDailyLogFindFirst = vi.fn(); +const mockTransaction = vi.fn(); + +vi.mock("@/lib/db", () => ({ + prisma: { + user: { findFirst: (...args: unknown[]) => mockUserFindFirst(...args) }, + dailyLog: { findFirst: (...args: unknown[]) => mockDailyLogFindFirst(...args) }, + $transaction: (...args: unknown[]) => mockTransaction(...args), + }, +})); + +// --------------------------------------------------------------------------- +// Mock Claude +// --------------------------------------------------------------------------- + +const mockClaudeCreate = vi.fn(); + +vi.mock("@/lib/claude", () => ({ + claude: { + messages: { create: (...args: unknown[]) => mockClaudeCreate(...args) }, + }, + parseClaudeJson: (text: string) => JSON.parse(text.trim().replace(/^```(?:json)?\s*/i, "").replace(/\s*```\s*$/, "").trim()), +})); + +// --------------------------------------------------------------------------- +// Mock rollCriticalHit (deterministic) +// --------------------------------------------------------------------------- + +const mockRollCriticalHit = vi.fn(() => false); + +vi.mock("@/lib/xp", async (importOriginal) => { + const actual = await importOriginal(); + return { + ...actual, + rollCriticalHit: () => mockRollCriticalHit(), + }; +}); + +// --------------------------------------------------------------------------- +// Mock getMultiplierPercent +// --------------------------------------------------------------------------- + +const mockGetMultiplierPercent = vi.fn(() => Promise.resolve(0)); + +vi.mock("@/lib/multiplier", () => ({ + getMultiplierPercent: (...args: unknown[]) => (mockGetMultiplierPercent as (...a: unknown[]) => unknown)(...args), +})); + +// --------------------------------------------------------------------------- +// Mock processSkillUnlocks +// --------------------------------------------------------------------------- + +const mockProcessSkillUnlocks = vi.fn((): Promise<{ unlocked: string[]; streakFreezesGranted: number }> => + Promise.resolve({ unlocked: [], streakFreezesGranted: 0 }), +); + +vi.mock("@/lib/skill-unlock", () => ({ + processSkillUnlocks: (...args: unknown[]) => (mockProcessSkillUnlocks as (...a: unknown[]) => unknown)(...args), +})); + +// --------------------------------------------------------------------------- +// Mock processEndOfDay (no-op — streak logic is tested separately) +// --------------------------------------------------------------------------- + +vi.mock("@/lib/streak", () => ({ + processEndOfDay: vi.fn(() => Promise.resolve({ + streak: 1, + freezeUsed: false, + streakBroken: false, + alreadyProcessed: false, + })), +})); + +// --------------------------------------------------------------------------- +// Mock extract library (for /api/reading/fetch) +// --------------------------------------------------------------------------- + +const mockFetchAndExtract = vi.fn(); +const mockCreateFromText = vi.fn(); + +vi.mock("@/lib/reading/extract", () => ({ + fetchAndExtract: (...args: unknown[]) => mockFetchAndExtract(...args), + createFromText: (...args: unknown[]) => mockCreateFromText(...args), +})); + +// --------------------------------------------------------------------------- +// Helpers +// --------------------------------------------------------------------------- + +function makeRequest(method: "GET" | "POST", url: string, body?: unknown): NextRequest { + return new NextRequest(url, { + method, + body: body !== undefined ? JSON.stringify(body) : undefined, + headers: body !== undefined ? { "content-type": "application/json" } : {}, + }); +} + +function makeUser(overrides: Record = {}) { + return { + id: 1, + currentXp: 50, + xpToNextLevel: 100, + level: 1, + totalXp: 50, + dailyGoalXp: 100, + title: "Smooth Brain", + categorySkills: [ + { + id: 10, + category: "reading", + level: 1, + currentXp: 20, + xpToNext: 100, + totalXp: 20, + }, + ], + ...overrides, + }; +} + +function makeClaudeScoreResponse(avgScore = 7) { + return { + scores: [ + { questionId: 1, score: avgScore, feedback: "Good recall." }, + { questionId: 2, score: avgScore, feedback: "Solid inference." }, + { questionId: 3, score: avgScore, feedback: "Decent inference." }, + { questionId: 4, score: avgScore, feedback: "Good critical thinking." }, + ], + overallFeedback: "Strong comprehension overall.", + }; +} + +function makeClaudeMsg(text: string) { + return { content: [{ type: "text", text }] }; +} + +const SAMPLE_QUESTIONS = [ + { id: 1, type: "recall" as const, question: "What did the article state?" }, + { id: 2, type: "inference" as const, question: "What can we infer?" }, + { id: 3, type: "inference" as const, question: "What follows from this?" }, + { id: 4, type: "critical" as const, question: "Evaluate the argument." }, +]; + +const SAMPLE_ANSWERS = [ + { questionId: 1, answer: "The article stated X." }, + { questionId: 2, answer: "We can infer Y." }, + { questionId: 3, answer: "Z follows." }, + { questionId: 4, answer: "The argument is sound because W." }, +]; + +// --------------------------------------------------------------------------- +// GET /api/reading/content +// --------------------------------------------------------------------------- + +describe("GET /api/reading/content", () => { + it("list mode: returns metadata without body field", async () => { + const { GET } = await import("@/app/api/reading/content/route"); + const req = makeRequest("GET", "http://localhost/api/reading/content?list=1"); + const res = await GET(req); + const data = await res.json(); + expect(res.status).toBe(200); + expect(Array.isArray(data.articles)).toBe(true); + expect(data.articles.length).toBeGreaterThan(0); + // No body field in list mode + for (const a of data.articles) { + expect(a).not.toHaveProperty("body"); + expect(a).toHaveProperty("slug"); + expect(a).toHaveProperty("title"); + expect(a).toHaveProperty("difficulty"); + } + }); + + it("slug mode: returns specific article", async () => { + const { GET } = await import("@/app/api/reading/content/route"); + const req = makeRequest("GET", "http://localhost/api/reading/content?slug=fermi-estimation"); + const res = await GET(req); + const data = await res.json(); + expect(res.status).toBe(200); + expect(data.article.slug).toBe("fermi-estimation"); + expect(data.article).toHaveProperty("body"); + expect(data.article.body.length).toBeGreaterThan(0); + }); + + it("slug mode: 404 on unknown slug", async () => { + const { GET } = await import("@/app/api/reading/content/route"); + const req = makeRequest("GET", "http://localhost/api/reading/content?slug=does-not-exist"); + const res = await GET(req); + const data = await res.json(); + expect(res.status).toBe(404); + expect(data).toHaveProperty("error"); + }); + + it("random mode: returns some article", async () => { + const { GET } = await import("@/app/api/reading/content/route"); + const req = makeRequest("GET", "http://localhost/api/reading/content"); + const res = await GET(req); + const data = await res.json(); + expect(res.status).toBe(200); + expect(data.article).toHaveProperty("slug"); + expect(data.article).toHaveProperty("body"); + }); + + it("random mode with difficulty: returns article of that difficulty (or any if none match)", async () => { + const { GET } = await import("@/app/api/reading/content/route"); + const req = makeRequest( + "GET", + "http://localhost/api/reading/content?difficulty=beginner", + ); + const res = await GET(req); + const data = await res.json(); + expect(res.status).toBe(200); + // Should return an article + expect(data.article).toHaveProperty("slug"); + }); +}); + +// --------------------------------------------------------------------------- +// POST /api/reading/fetch +// --------------------------------------------------------------------------- + +describe("POST /api/reading/fetch", () => { + beforeEach(() => { + vi.clearAllMocks(); + }); + + it("invalid JSON body → 400", async () => { + const { POST } = await import("@/app/api/reading/fetch/route"); + const req = new NextRequest("http://localhost/api/reading/fetch", { + method: "POST", + body: "not-json", + headers: { "content-type": "application/json" }, + }); + const res = await POST(req); + expect(res.status).toBe(400); + const data = await res.json(); + expect(data).toHaveProperty("error"); + }); + + it("missing url and text → 400", async () => { + const { POST } = await import("@/app/api/reading/fetch/route"); + const req = makeRequest("POST", "http://localhost/api/reading/fetch", {}); + const res = await POST(req); + expect(res.status).toBe(400); + const data = await res.json(); + expect(data.error).toMatch(/url.*text|text.*url/i); + }); + + it("invalid URL format → 400", async () => { + const { POST } = await import("@/app/api/reading/fetch/route"); + const req = makeRequest("POST", "http://localhost/api/reading/fetch", { + url: "not-a-valid-url", + }); + const res = await POST(req); + expect(res.status).toBe(400); + const data = await res.json(); + expect(data.error).toMatch(/invalid url/i); + }); + + it("non-http protocol → 400", async () => { + const { POST } = await import("@/app/api/reading/fetch/route"); + const req = makeRequest("POST", "http://localhost/api/reading/fetch", { + url: "ftp://example.com/file", + }); + const res = await POST(req); + expect(res.status).toBe(400); + const data = await res.json(); + expect(data.error).toMatch(/http/i); + }); + + it("URL fetch success: calls fetchAndExtract and returns article with source=url", async () => { + mockFetchAndExtract.mockResolvedValueOnce({ + title: "Test Article", + body: "Test content here.", + domain: "example.com", + wordCount: 3, + estimatedMinutes: 1, + sourceUrl: "https://example.com/article", + }); + + const { POST } = await import("@/app/api/reading/fetch/route"); + const req = makeRequest("POST", "http://localhost/api/reading/fetch", { + url: "https://example.com/article", + }); + const res = await POST(req); + const data = await res.json(); + expect(res.status).toBe(200); + expect(data.source).toBe("url"); + expect(data.article.title).toBe("Test Article"); + expect(mockFetchAndExtract).toHaveBeenCalledWith("https://example.com/article"); + }); + + it("URL fetch error: returns 422 with error message", async () => { + mockFetchAndExtract.mockRejectedValueOnce(new Error("Page not found")); + + const { POST } = await import("@/app/api/reading/fetch/route"); + const req = makeRequest("POST", "http://localhost/api/reading/fetch", { + url: "https://example.com/missing", + }); + const res = await POST(req); + const data = await res.json(); + expect(res.status).toBe(422); + expect(data.error).toContain("Page not found"); + }); + + it("text paste success: calls createFromText and returns article with source=text", async () => { + mockCreateFromText.mockReturnValueOnce({ + title: "My Pasted Text", + body: "This is the pasted content.", + domain: "custom", + wordCount: 5, + estimatedMinutes: 1, + sourceUrl: "", + }); + + const { POST } = await import("@/app/api/reading/fetch/route"); + const req = makeRequest("POST", "http://localhost/api/reading/fetch", { + text: "This is the pasted content.", + title: "My Pasted Text", + }); + const res = await POST(req); + const data = await res.json(); + expect(res.status).toBe(200); + expect(data.source).toBe("text"); + expect(data.article.title).toBe("My Pasted Text"); + expect(mockCreateFromText).toHaveBeenCalledWith( + "This is the pasted content.", + "My Pasted Text", + ); + }); + + it("text paste error: returns 422 with error message", async () => { + mockCreateFromText.mockImplementationOnce(() => { + throw new Error("Text too short"); + }); + + const { POST } = await import("@/app/api/reading/fetch/route"); + const req = makeRequest("POST", "http://localhost/api/reading/fetch", { + text: "x", + }); + const res = await POST(req); + const data = await res.json(); + expect(res.status).toBe(422); + expect(data.error).toContain("Text too short"); + }); +}); + +// --------------------------------------------------------------------------- +// POST /api/reading/questions +// --------------------------------------------------------------------------- + +describe("POST /api/reading/questions", () => { + beforeEach(() => { + vi.clearAllMocks(); + process.env.ANTHROPIC_API_KEY = "test-key"; + }); + + it("503 when API key missing, no Claude call", async () => { + delete process.env.ANTHROPIC_API_KEY; + const { POST } = await import("@/app/api/reading/questions/route"); + const req = makeRequest("POST", "http://localhost/api/reading/questions", { + slug: "fermi-estimation", + }); + const res = await POST(req); + expect(res.status).toBe(503); + expect(mockClaudeCreate).not.toHaveBeenCalled(); + }); + + it("503 when API key is empty string, no Claude call", async () => { + process.env.ANTHROPIC_API_KEY = ""; + const { POST } = await import("@/app/api/reading/questions/route"); + const req = makeRequest("POST", "http://localhost/api/reading/questions", { + slug: "fermi-estimation", + }); + const res = await POST(req); + expect(res.status).toBe(503); + expect(mockClaudeCreate).not.toHaveBeenCalled(); + }); + + it("invalid JSON body → 400", async () => { + const { POST } = await import("@/app/api/reading/questions/route"); + const req = new NextRequest("http://localhost/api/reading/questions", { + method: "POST", + body: "{bad json", + headers: { "content-type": "application/json" }, + }); + const res = await POST(req); + expect(res.status).toBe(400); + }); + + it("missing slug and content → 400", async () => { + const { POST } = await import("@/app/api/reading/questions/route"); + const req = makeRequest("POST", "http://localhost/api/reading/questions", {}); + const res = await POST(req); + expect(res.status).toBe(400); + const data = await res.json(); + expect(data.error).toMatch(/slug.*content|content.*slug/i); + }); + + it("unknown slug → 404", async () => { + const { POST } = await import("@/app/api/reading/questions/route"); + const req = makeRequest("POST", "http://localhost/api/reading/questions", { + slug: "nonexistent-slug", + }); + const res = await POST(req); + expect(res.status).toBe(404); + }); + + it("slug success: Claude called with article title in prompt", async () => { + const questions = [ + { id: 1, type: "recall", question: "What is the main idea?" }, + { id: 2, type: "inference", question: "What can we infer?" }, + { id: 3, type: "inference", question: "What follows?" }, + { id: 4, type: "critical", question: "Evaluate the argument." }, + ]; + mockClaudeCreate.mockResolvedValueOnce( + makeClaudeMsg(JSON.stringify(questions)), + ); + + const { POST } = await import("@/app/api/reading/questions/route"); + const req = makeRequest("POST", "http://localhost/api/reading/questions", { + slug: "fermi-estimation", + }); + const res = await POST(req); + expect(res.status).toBe(200); + const data = await res.json(); + expect(Array.isArray(data.questions)).toBe(true); + expect(data.questions.length).toBe(4); + + const promptText = mockClaudeCreate.mock.calls[0][0].messages[0].content as string; + expect(promptText).toContain("Fermi Estimation"); + }); + + it("custom content object: Claude called with custom title in prompt", async () => { + const questions = [ + { id: 1, type: "recall", question: "What was said?" }, + { id: 2, type: "inference", question: "What can be inferred?" }, + { id: 3, type: "inference", question: "What follows?" }, + { id: 4, type: "critical", question: "Evaluate the logic." }, + ]; + mockClaudeCreate.mockResolvedValueOnce( + makeClaudeMsg(JSON.stringify(questions)), + ); + + const { POST } = await import("@/app/api/reading/questions/route"); + const req = makeRequest("POST", "http://localhost/api/reading/questions", { + content: { + title: "My Custom Article", + body: "This is the custom body text for reading comprehension.", + }, + }); + const res = await POST(req); + expect(res.status).toBe(200); + const promptText = mockClaudeCreate.mock.calls[0][0].messages[0].content as string; + expect(promptText).toContain("My Custom Article"); + }); + + it("uses claude-3-5-haiku model", async () => { + const questions = [ + { id: 1, type: "recall", question: "Q1?" }, + { id: 2, type: "inference", question: "Q2?" }, + { id: 3, type: "inference", question: "Q3?" }, + { id: 4, type: "critical", question: "Q4?" }, + ]; + mockClaudeCreate.mockResolvedValueOnce( + makeClaudeMsg(JSON.stringify(questions)), + ); + + const { POST } = await import("@/app/api/reading/questions/route"); + const req = makeRequest("POST", "http://localhost/api/reading/questions", { + slug: "fermi-estimation", + }); + await POST(req); + + const callArgs = mockClaudeCreate.mock.calls[0][0]; + expect(callArgs.model).toContain("haiku"); + }); + + it("invalid JSON from Claude → 500", async () => { + mockClaudeCreate.mockResolvedValueOnce( + makeClaudeMsg("this is not valid json {{{{"), + ); + + const { POST } = await import("@/app/api/reading/questions/route"); + const req = makeRequest("POST", "http://localhost/api/reading/questions", { + slug: "fermi-estimation", + }); + const res = await POST(req); + expect(res.status).toBe(500); + }); + + it("network error from Claude → 500", async () => { + mockClaudeCreate.mockRejectedValueOnce(new Error("Connection refused")); + + const { POST } = await import("@/app/api/reading/questions/route"); + const req = makeRequest("POST", "http://localhost/api/reading/questions", { + slug: "fermi-estimation", + }); + const res = await POST(req); + expect(res.status).toBe(500); + }); +}); + +// --------------------------------------------------------------------------- +// POST /api/reading/score +// --------------------------------------------------------------------------- + +describe("POST /api/reading/score", () => { + beforeEach(() => { + vi.resetAllMocks(); // reset implementations too, not just call counts + process.env.ANTHROPIC_API_KEY = "test-key"; + mockRollCriticalHit.mockReturnValue(false); + mockGetMultiplierPercent.mockResolvedValue(0); + mockProcessSkillUnlocks.mockResolvedValue({ unlocked: [], streakFreezesGranted: 0 }); + mockTransaction.mockImplementation(async (fn: (tx: unknown) => Promise) => { + const tx = { + activity: { create: vi.fn().mockResolvedValue({}) }, + user: { update: vi.fn().mockResolvedValue({}) }, + categorySkill: { update: vi.fn().mockResolvedValue({}) }, + dailyLog: { + update: vi.fn().mockResolvedValue({}), + create: vi.fn().mockResolvedValue({}), + }, + }; + return fn(tx); + }); + mockDailyLogFindFirst.mockResolvedValue(null); + }); + + it("503 when API key missing, no Claude call", async () => { + delete process.env.ANTHROPIC_API_KEY; + const { POST } = await import("@/app/api/reading/score/route"); + const req = makeRequest("POST", "http://localhost/api/reading/score", { + slug: "fermi-estimation", + answers: SAMPLE_ANSWERS, + questions: SAMPLE_QUESTIONS, + durationSecs: 300, + }); + const res = await POST(req); + expect(res.status).toBe(503); + expect(mockClaudeCreate).not.toHaveBeenCalled(); + }); + + it("503 when API key is empty string", async () => { + process.env.ANTHROPIC_API_KEY = ""; + const { POST } = await import("@/app/api/reading/score/route"); + const req = makeRequest("POST", "http://localhost/api/reading/score", { + slug: "fermi-estimation", + answers: SAMPLE_ANSWERS, + questions: SAMPLE_QUESTIONS, + durationSecs: 300, + }); + const res = await POST(req); + expect(res.status).toBe(503); + }); + + it("invalid JSON body → 400", async () => { + const { POST } = await import("@/app/api/reading/score/route"); + const req = new NextRequest("http://localhost/api/reading/score", { + method: "POST", + body: "{bad json", + headers: { "content-type": "application/json" }, + }); + const res = await POST(req); + expect(res.status).toBe(400); + }); + + it("missing answers → 400", async () => { + const { POST } = await import("@/app/api/reading/score/route"); + const req = makeRequest("POST", "http://localhost/api/reading/score", { + slug: "fermi-estimation", + questions: SAMPLE_QUESTIONS, + durationSecs: 300, + }); + const res = await POST(req); + expect(res.status).toBe(400); + }); + + it("missing questions → 400", async () => { + const { POST } = await import("@/app/api/reading/score/route"); + const req = makeRequest("POST", "http://localhost/api/reading/score", { + slug: "fermi-estimation", + answers: SAMPLE_ANSWERS, + durationSecs: 300, + }); + const res = await POST(req); + expect(res.status).toBe(400); + }); + + it("empty answers array → 400", async () => { + const { POST } = await import("@/app/api/reading/score/route"); + const req = makeRequest("POST", "http://localhost/api/reading/score", { + slug: "fermi-estimation", + answers: [], + questions: SAMPLE_QUESTIONS, + durationSecs: 300, + }); + const res = await POST(req); + expect(res.status).toBe(400); + }); + + it("unknown slug → 404", async () => { + const { POST } = await import("@/app/api/reading/score/route"); + const req = makeRequest("POST", "http://localhost/api/reading/score", { + slug: "nonexistent-article", + answers: SAMPLE_ANSWERS, + questions: SAMPLE_QUESTIONS, + durationSecs: 300, + }); + const res = await POST(req); + expect(res.status).toBe(404); + }); + + it("missing content and slug → 400", async () => { + const { POST } = await import("@/app/api/reading/score/route"); + const req = makeRequest("POST", "http://localhost/api/reading/score", { + answers: SAMPLE_ANSWERS, + questions: SAMPLE_QUESTIONS, + durationSecs: 300, + }); + const res = await POST(req); + expect(res.status).toBe(400); + }); + + it("user not found → 404", async () => { + mockUserFindFirst.mockResolvedValueOnce(null); + mockClaudeCreate.mockResolvedValueOnce( + makeClaudeMsg(JSON.stringify(makeClaudeScoreResponse(7))), + ); + + const { POST } = await import("@/app/api/reading/score/route"); + const req = makeRequest("POST", "http://localhost/api/reading/score", { + slug: "fermi-estimation", + answers: SAMPLE_ANSWERS, + questions: SAMPLE_QUESTIONS, + durationSecs: 300, + }); + const res = await POST(req); + expect(res.status).toBe(404); + }); + + it("missing reading CategorySkill → 500", async () => { + mockUserFindFirst.mockResolvedValueOnce({ + ...makeUser(), + categorySkills: [], // no reading skill + }); + mockClaudeCreate.mockResolvedValueOnce( + makeClaudeMsg(JSON.stringify(makeClaudeScoreResponse(7))), + ); + + const { POST } = await import("@/app/api/reading/score/route"); + const req = makeRequest("POST", "http://localhost/api/reading/score", { + slug: "fermi-estimation", + answers: SAMPLE_ANSWERS, + questions: SAMPLE_QUESTIONS, + durationSecs: 300, + }); + const res = await POST(req); + expect(res.status).toBe(500); + }); + + it("success: response shape is correct", async () => { + mockUserFindFirst.mockResolvedValueOnce(makeUser()); + mockClaudeCreate.mockResolvedValueOnce( + makeClaudeMsg(JSON.stringify(makeClaudeScoreResponse(8))), + ); + + const { POST } = await import("@/app/api/reading/score/route"); + const req = makeRequest("POST", "http://localhost/api/reading/score", { + slug: "fermi-estimation", + answers: SAMPLE_ANSWERS, + questions: SAMPLE_QUESTIONS, + durationSecs: 300, + }); + const res = await POST(req); + expect(res.status).toBe(200); + const data = await res.json(); + expect(data).toHaveProperty("scores"); + expect(data).toHaveProperty("overallFeedback"); + expect(data).toHaveProperty("avgScore"); + expect(data).toHaveProperty("xp"); + expect(data.xp).toHaveProperty("baseXp"); + expect(data.xp).toHaveProperty("totalXp"); + expect(data.xp).toHaveProperty("qualityBonus"); + expect(data.xp).toHaveProperty("isCriticalHit"); + expect(data).toHaveProperty("levelUp"); + expect(data).toHaveProperty("categoryXp"); + expect(data.categoryXp).toHaveProperty("level"); + expect(data.categoryXp).toHaveProperty("levelUp"); + expect(data).toHaveProperty("unlocks"); + }); + + it("Claude prompt includes article title and Q&A pairs", async () => { + mockUserFindFirst.mockResolvedValueOnce(makeUser()); + mockClaudeCreate.mockResolvedValueOnce( + makeClaudeMsg(JSON.stringify(makeClaudeScoreResponse(5))), + ); + + const { POST } = await import("@/app/api/reading/score/route"); + const req = makeRequest("POST", "http://localhost/api/reading/score", { + slug: "fermi-estimation", + answers: SAMPLE_ANSWERS, + questions: SAMPLE_QUESTIONS, + durationSecs: 300, + }); + await POST(req); + + const promptText = mockClaudeCreate.mock.calls[0][0].messages[0].content as string; + expect(promptText).toContain("Fermi Estimation"); + expect(promptText).toContain("What did the article state?"); + expect(promptText).toContain("The article stated X."); + }); + + it("uses claude-3-5-haiku model", async () => { + mockUserFindFirst.mockResolvedValueOnce(makeUser()); + mockClaudeCreate.mockResolvedValueOnce( + makeClaudeMsg(JSON.stringify(makeClaudeScoreResponse(5))), + ); + + const { POST } = await import("@/app/api/reading/score/route"); + const req = makeRequest("POST", "http://localhost/api/reading/score", { + slug: "fermi-estimation", + answers: SAMPLE_ANSWERS, + questions: SAMPLE_QUESTIONS, + durationSecs: 300, + }); + await POST(req); + const callArgs = mockClaudeCreate.mock.calls[0][0]; + expect(callArgs.model).toContain("haiku"); + }); + + it("invalid JSON from Claude → 500", async () => { + mockUserFindFirst.mockResolvedValueOnce(makeUser()); + mockClaudeCreate.mockResolvedValueOnce(makeClaudeMsg("{ corrupt json ]")); + + const { POST } = await import("@/app/api/reading/score/route"); + const req = makeRequest("POST", "http://localhost/api/reading/score", { + slug: "fermi-estimation", + answers: SAMPLE_ANSWERS, + questions: SAMPLE_QUESTIONS, + durationSecs: 300, + }); + const res = await POST(req); + expect(res.status).toBe(500); + }); + + it("network error from Claude → 500", async () => { + mockUserFindFirst.mockResolvedValueOnce(makeUser()); + mockClaudeCreate.mockRejectedValueOnce(new Error("Network unreachable")); + + const { POST } = await import("@/app/api/reading/score/route"); + const req = makeRequest("POST", "http://localhost/api/reading/score", { + slug: "fermi-estimation", + answers: SAMPLE_ANSWERS, + questions: SAMPLE_QUESTIONS, + durationSecs: 300, + }); + const res = await POST(req); + expect(res.status).toBe(500); + }); + + it("XP: quality bonus is non-zero for high scores", async () => { + mockUserFindFirst.mockResolvedValueOnce(makeUser()); + // All scores of 10/10 → qualityScore=1.0 → max quality bonus + mockClaudeCreate.mockResolvedValueOnce( + makeClaudeMsg(JSON.stringify(makeClaudeScoreResponse(10))), + ); + + const { POST } = await import("@/app/api/reading/score/route"); + const req = makeRequest("POST", "http://localhost/api/reading/score", { + slug: "fermi-estimation", + answers: SAMPLE_ANSWERS, + questions: SAMPLE_QUESTIONS, + durationSecs: 300, + }); + const res = await POST(req); + const data = await res.json(); + expect(data.xp.qualityBonus).toBeGreaterThan(0); + expect(data.xp.totalXp).toBeGreaterThan(data.xp.baseXp); + }); + + it("XP: zero quality bonus for score of 0", async () => { + mockUserFindFirst.mockResolvedValueOnce(makeUser()); + mockClaudeCreate.mockResolvedValueOnce( + makeClaudeMsg(JSON.stringify(makeClaudeScoreResponse(0))), + ); + + const { POST } = await import("@/app/api/reading/score/route"); + const req = makeRequest("POST", "http://localhost/api/reading/score", { + slug: "fermi-estimation", + answers: SAMPLE_ANSWERS, + questions: SAMPLE_QUESTIONS, + durationSecs: 300, + }); + const res = await POST(req); + const data = await res.json(); + expect(data.xp.qualityBonus).toBe(0); + expect(data.xp.totalXp).toBe(data.xp.baseXp); + }); + + it("XP: critical hit doubles totalXp", async () => { + mockRollCriticalHit.mockReturnValue(true); + mockUserFindFirst.mockResolvedValueOnce(makeUser()); + mockClaudeCreate.mockResolvedValueOnce( + makeClaudeMsg(JSON.stringify(makeClaudeScoreResponse(0))), + ); + + const { POST } = await import("@/app/api/reading/score/route"); + const req = makeRequest("POST", "http://localhost/api/reading/score", { + slug: "fermi-estimation", + answers: SAMPLE_ANSWERS, + questions: SAMPLE_QUESTIONS, + durationSecs: 300, + }); + const res = await POST(req); + const data = await res.json(); + expect(data.xp.isCriticalHit).toBe(true); + expect(data.xp.totalXp).toBe(data.xp.baseXp * 2); + }); + + it("XP: multiplier bonus reflected in response", async () => { + mockGetMultiplierPercent.mockResolvedValue(10); + mockUserFindFirst.mockResolvedValueOnce(makeUser()); + mockClaudeCreate.mockResolvedValueOnce( + makeClaudeMsg(JSON.stringify(makeClaudeScoreResponse(0))), + ); + + const { POST } = await import("@/app/api/reading/score/route"); + const req = makeRequest("POST", "http://localhost/api/reading/score", { + slug: "fermi-estimation", + answers: SAMPLE_ANSWERS, + questions: SAMPLE_QUESTIONS, + durationSecs: 300, + }); + const res = await POST(req); + const data = await res.json(); + expect(data.xp.multiplierPercent).toBe(10); + expect(data.xp.multiplierBonus).toBeGreaterThan(0); + expect(data.xp.totalXp).toBeGreaterThan(data.xp.baseXp); + }); + + it("custom content: accepted and exerciseType is comprehension-custom in activity", async () => { + mockUserFindFirst.mockResolvedValueOnce(makeUser()); + mockClaudeCreate.mockResolvedValueOnce( + makeClaudeMsg(JSON.stringify(makeClaudeScoreResponse(7))), + ); + + let capturedExerciseType = ""; + mockTransaction.mockImplementationOnce( + async (fn: (tx: unknown) => Promise) => { + const tx = { + activity: { + create: vi.fn().mockImplementation((args: { data: { exerciseType: string } }) => { + capturedExerciseType = args.data.exerciseType; + return {}; + }), + }, + user: { update: vi.fn().mockResolvedValue({}) }, + categorySkill: { update: vi.fn().mockResolvedValue({}) }, + dailyLog: { + update: vi.fn().mockResolvedValue({}), + create: vi.fn().mockResolvedValue({}), + }, + }; + return fn(tx); + }, + ); + + const { POST } = await import("@/app/api/reading/score/route"); + const req = makeRequest("POST", "http://localhost/api/reading/score", { + content: { + title: "Custom Read", + body: "Custom body text for this article.", + sourceUrl: "https://example.com/custom", + }, + answers: SAMPLE_ANSWERS, + questions: SAMPLE_QUESTIONS, + durationSecs: 300, + }); + const res = await POST(req); + expect(res.status).toBe(200); + expect(capturedExerciseType).toBe("comprehension-custom"); + }); + + it("DailyLog created when no existing log", async () => { + mockUserFindFirst.mockResolvedValueOnce(makeUser()); + mockDailyLogFindFirst.mockResolvedValue(null); + mockClaudeCreate.mockResolvedValueOnce( + makeClaudeMsg(JSON.stringify(makeClaudeScoreResponse(5))), + ); + + let dailyLogCreated = false; + let dailyLogUpdated = false; + mockTransaction.mockImplementationOnce( + async (fn: (tx: unknown) => Promise) => { + const tx = { + activity: { create: vi.fn().mockResolvedValue({}) }, + user: { update: vi.fn().mockResolvedValue({}) }, + categorySkill: { update: vi.fn().mockResolvedValue({}) }, + dailyLog: { + update: vi.fn().mockImplementation(() => { dailyLogUpdated = true; return {}; }), + create: vi.fn().mockImplementation(() => { dailyLogCreated = true; return {}; }), + }, + }; + return fn(tx); + }, + ); + + const { POST } = await import("@/app/api/reading/score/route"); + const req = makeRequest("POST", "http://localhost/api/reading/score", { + slug: "fermi-estimation", + answers: SAMPLE_ANSWERS, + questions: SAMPLE_QUESTIONS, + durationSecs: 300, + }); + await POST(req); + expect(dailyLogCreated).toBe(true); + expect(dailyLogUpdated).toBe(false); + }); + + it("DailyLog updated when log exists", async () => { + mockUserFindFirst.mockResolvedValueOnce(makeUser()); + mockDailyLogFindFirst.mockResolvedValue({ + id: 99, + xpEarned: 40, + activityCount: 1, + }); + mockClaudeCreate.mockResolvedValueOnce( + makeClaudeMsg(JSON.stringify(makeClaudeScoreResponse(5))), + ); + + let dailyLogCreated = false; + let dailyLogUpdated = false; + mockTransaction.mockImplementationOnce( + async (fn: (tx: unknown) => Promise) => { + const tx = { + activity: { create: vi.fn().mockResolvedValue({}) }, + user: { update: vi.fn().mockResolvedValue({}) }, + categorySkill: { update: vi.fn().mockResolvedValue({}) }, + dailyLog: { + update: vi.fn().mockImplementation(() => { dailyLogUpdated = true; return {}; }), + create: vi.fn().mockImplementation(() => { dailyLogCreated = true; return {}; }), + }, + }; + return fn(tx); + }, + ); + + const { POST } = await import("@/app/api/reading/score/route"); + const req = makeRequest("POST", "http://localhost/api/reading/score", { + slug: "fermi-estimation", + answers: SAMPLE_ANSWERS, + questions: SAMPLE_QUESTIONS, + durationSecs: 300, + }); + await POST(req); + expect(dailyLogUpdated).toBe(true); + expect(dailyLogCreated).toBe(false); + }); + + it("goalMet is true when XP meets dailyGoalXp", async () => { + // User has dailyGoalXp=30, xpEarned so far=0, baseXp for reading=30 + // A perfect score (30+30=60 XP) should easily meet the goal of 30 + const user = makeUser({ dailyGoalXp: 30 }); + mockUserFindFirst.mockResolvedValue(user); + mockDailyLogFindFirst.mockResolvedValue(null); + mockClaudeCreate.mockResolvedValueOnce( + makeClaudeMsg(JSON.stringify(makeClaudeScoreResponse(10))), // perfect score + ); + + let capturedGoalMet = false; + // Use mockImplementationOnce so this custom tx doesn't bleed into later tests + mockTransaction.mockImplementationOnce( + async (fn: (tx: unknown) => Promise) => { + const tx = { + activity: { create: vi.fn().mockResolvedValue({}) }, + user: { update: vi.fn().mockResolvedValue({}) }, + categorySkill: { update: vi.fn().mockResolvedValue({}) }, + dailyLog: { + update: vi.fn().mockResolvedValue({}), + create: vi.fn().mockImplementation((args: { data: { goalMet: boolean } }) => { + capturedGoalMet = args.data.goalMet; + return {}; + }), + }, + }; + mockProcessSkillUnlocks.mockResolvedValueOnce({ unlocked: [], streakFreezesGranted: 0 }); + return fn(tx); + }, + ); + + const { POST } = await import("@/app/api/reading/score/route"); + const req = makeRequest("POST", "http://localhost/api/reading/score", { + slug: "fermi-estimation", + answers: SAMPLE_ANSWERS, + questions: SAMPLE_QUESTIONS, + durationSecs: 300, + }); + const res = await POST(req); + expect(res.status).toBe(200); + expect(capturedGoalMet).toBe(true); + }); + + it("processSkillUnlocks called on category level-up", async () => { + // Force a category level-up: currentXp=9999 well exceeds xpToNext=1 + const user = makeUser(); + user.categorySkills[0].currentXp = 9999; + user.categorySkills[0].xpToNext = 1; + mockUserFindFirst.mockResolvedValue(user); + mockDailyLogFindFirst.mockResolvedValue(null); + mockClaudeCreate.mockResolvedValueOnce( + makeClaudeMsg(JSON.stringify(makeClaudeScoreResponse(5))), + ); + + let processSkillUnlocksCalled = false; + // Use mockImplementationOnce so this override doesn't bleed into later tests + mockTransaction.mockImplementationOnce(async (fn: (tx: unknown) => Promise) => { + const tx = { + activity: { create: vi.fn().mockResolvedValue({}) }, + user: { update: vi.fn().mockResolvedValue({}) }, + categorySkill: { update: vi.fn().mockResolvedValue({}) }, + dailyLog: { create: vi.fn().mockResolvedValue({}), update: vi.fn().mockResolvedValue({}) }, + }; + mockProcessSkillUnlocks.mockImplementationOnce(() => { + processSkillUnlocksCalled = true; + return Promise.resolve({ unlocked: [], streakFreezesGranted: 0 }); + }); + return fn(tx); + }); + + const { POST } = await import("@/app/api/reading/score/route"); + const req = makeRequest("POST", "http://localhost/api/reading/score", { + slug: "fermi-estimation", + answers: SAMPLE_ANSWERS, + questions: SAMPLE_QUESTIONS, + durationSecs: 300, + }); + const res = await POST(req); + expect(res.status).toBe(200); + expect(processSkillUnlocksCalled).toBe(true); + }); + + it("processSkillUnlocks not called when no category level-up", async () => { + // Category XP won't reach next level + const user = makeUser(); + user.categorySkills[0].currentXp = 0; + user.categorySkills[0].xpToNext = 1000; + mockUserFindFirst.mockResolvedValueOnce(user); + mockClaudeCreate.mockResolvedValueOnce( + makeClaudeMsg(JSON.stringify(makeClaudeScoreResponse(0))), // minimal XP + ); + + const { POST } = await import("@/app/api/reading/score/route"); + const req = makeRequest("POST", "http://localhost/api/reading/score", { + slug: "fermi-estimation", + answers: SAMPLE_ANSWERS, + questions: SAMPLE_QUESTIONS, + durationSecs: 300, + }); + await POST(req); + expect(mockProcessSkillUnlocks).not.toHaveBeenCalled(); + }); + + it("unlocks populated in response when skill unlocks occur", async () => { + mockProcessSkillUnlocks.mockResolvedValue({ + unlocked: ["Deep Diver", "Focus Boost"], + streakFreezesGranted: 0, + }); + const user = makeUser(); + user.categorySkills[0].currentXp = 99; + user.categorySkills[0].xpToNext = 100; + mockUserFindFirst.mockResolvedValueOnce(user); + mockClaudeCreate.mockResolvedValueOnce( + makeClaudeMsg(JSON.stringify(makeClaudeScoreResponse(10))), + ); + + const { POST } = await import("@/app/api/reading/score/route"); + const req = makeRequest("POST", "http://localhost/api/reading/score", { + slug: "fermi-estimation", + answers: SAMPLE_ANSWERS, + questions: SAMPLE_QUESTIONS, + durationSecs: 300, + }); + const res = await POST(req); + const data = await res.json(); + expect(data.unlocks).toEqual(["Deep Diver", "Focus Boost"]); + }); +}); diff --git a/src/app/api/reading/content/route.ts b/src/app/api/reading/content/route.ts new file mode 100644 index 0000000000000000000000000000000000000000..e07f89e52e3b191552540d4729e87ef6538c6a03 --- /dev/null +++ b/src/app/api/reading/content/route.ts @@ -0,0 +1,43 @@ +import { NextRequest, NextResponse } from "next/server"; +import { + ARTICLES, + getArticleBySlug, + getRandomArticle, + type ArticleDifficulty, +} from "@/lib/reading/articles"; +import { withApiError } from "@/lib/api-error"; + +/** + * GET /api/reading/content + * + * Query params: + * slug – return a specific article + * difficulty – filter random pick by difficulty (beginner | intermediate | advanced) + * list – if "1", return article metadata (no body) + */ +export const GET = withApiError(async (request: NextRequest) => { + const { searchParams } = new URL(request.url); + const slug = searchParams.get("slug"); + const difficulty = searchParams.get("difficulty") as ArticleDifficulty | null; + const list = searchParams.get("list"); + + // List mode: return metadata only + if (list === "1") { + // eslint-disable-next-line @typescript-eslint/no-unused-vars + const articles = ARTICLES.map(({ body: _body, ...meta }) => meta); + return NextResponse.json({ articles }); + } + + // Specific slug + if (slug) { + const article = getArticleBySlug(slug); + if (!article) { + return NextResponse.json({ error: "Article not found", status: 404 }, { status: 404 }); + } + return NextResponse.json({ article }); + } + + // Random article (optionally filtered by difficulty) + const article = getRandomArticle(difficulty ?? undefined); + return NextResponse.json({ article }); +}); diff --git a/src/app/api/reading/fetch/route.ts b/src/app/api/reading/fetch/route.ts new file mode 100644 index 0000000000000000000000000000000000000000..adf3b21692e57b5cc95dbe6f9e5ac709dee00d54 --- /dev/null +++ b/src/app/api/reading/fetch/route.ts @@ -0,0 +1,72 @@ +import { NextRequest, NextResponse } from "next/server"; +import { fetchAndExtract, createFromText } from "@/lib/reading/extract"; +import { withApiError } from "@/lib/api-error"; + +/** + * POST /api/reading/fetch + * + * Body: { url: string } | { text: string, title?: string } + * + * Fetches a URL and extracts readable content, or accepts pasted text. + * Returns an article-compatible object for the Reader component. + */ +export const POST = withApiError(async (request: NextRequest) => { + let body: { url?: string; text?: string; title?: string }; + try { + body = await request.json(); + } catch { + return NextResponse.json({ error: "Invalid JSON body" }, { status: 400 }); + } + + const { url, text, title } = body; + + // URL fetch mode + if (url && typeof url === "string") { + // Basic URL validation + let parsedUrl: URL; + try { + parsedUrl = new URL(url); + } catch { + return NextResponse.json({ error: "Invalid URL format" }, { status: 400 }); + } + + if (!["http:", "https:"].includes(parsedUrl.protocol)) { + return NextResponse.json( + { error: "Only HTTP and HTTPS URLs are supported" }, + { status: 400 }, + ); + } + + try { + const article = await fetchAndExtract(url); + return NextResponse.json({ article, source: "url" }); + } catch (err) { + return NextResponse.json( + { + error: err instanceof Error ? err.message : "Failed to fetch URL", + }, + { status: 422 }, + ); + } + } + + // Paste text mode + if (text && typeof text === "string") { + try { + const article = createFromText(text, title); + return NextResponse.json({ article, source: "text" }); + } catch (err) { + return NextResponse.json( + { + error: err instanceof Error ? err.message : "Invalid text input", + }, + { status: 422 }, + ); + } + } + + return NextResponse.json( + { error: "Provide either a 'url' or 'text' field" }, + { status: 400 }, + ); +}); diff --git a/src/app/api/reading/questions/route.ts b/src/app/api/reading/questions/route.ts new file mode 100644 index 0000000000000000000000000000000000000000..2b5453d6af45ef4ec79d8f9f3a2e0e61066a6934 --- /dev/null +++ b/src/app/api/reading/questions/route.ts @@ -0,0 +1,107 @@ +import { NextRequest, NextResponse } from "next/server"; +import { claude, parseClaudeJson } from "@/lib/claude"; +import { getArticleBySlug } from "@/lib/reading/articles"; +import { withApiError } from "@/lib/api-error"; + +export interface ComprehensionQuestion { + id: number; + type: "recall" | "inference" | "critical"; + question: string; +} + +/** + * POST /api/reading/questions + * + * Body: { slug: string } | { content: { title: string; body: string } } + * + * Calls Claude to generate 4 comprehension questions (recall, inference, critical) + * based on article content. Accepts either a seeded article slug or custom content. + */ +export const POST = withApiError(async (request: NextRequest) => { + if (!process.env.ANTHROPIC_API_KEY) { + return NextResponse.json( + { error: "ANTHROPIC_API_KEY is not configured" }, + { status: 503 }, + ); + } + + let body: { slug?: string; content?: { title: string; body: string } }; + try { + body = await request.json(); + } catch { + return NextResponse.json({ error: "Invalid JSON body" }, { status: 400 }); + } + + const { slug, content } = body; + + // Resolve article content — seeded slug or custom content + let articleTitle: string; + let articleBody: string; + + if (slug && typeof slug === "string") { + const article = getArticleBySlug(slug); + if (!article) { + return NextResponse.json({ error: "Article not found" }, { status: 404 }); + } + articleTitle = article.title; + articleBody = article.body; + } else if ( + content && + typeof content.title === "string" && + typeof content.body === "string" + ) { + articleTitle = content.title; + articleBody = content.body; + } else { + return NextResponse.json( + { error: "Provide either a 'slug' or 'content' object with title and body" }, + { status: 400 }, + ); + } + + let questions: ComprehensionQuestion[]; + try { + const message = await claude.messages.create({ + model: "claude-haiku-4-5-20251001", + max_tokens: 1024, + messages: [ + { + role: "user", + content: `You are generating comprehension questions for a reading exercise. The reader has just finished reading the article below and must now answer questions from memory. + +Generate exactly 4 questions: +- 1 recall question (tests direct memory of stated facts) +- 2 inference questions (tests understanding of implied meaning or logical connections) +- 1 critical thinking question (tests ability to evaluate, challenge, or extend the argument) + +Respond ONLY in valid JSON (no markdown, no code fences): +[ + { "id": 1, "type": "recall", "question": "..." }, + { "id": 2, "type": "inference", "question": "..." }, + { "id": 3, "type": "inference", "question": "..." }, + { "id": 4, "type": "critical", "question": "..." } +] + +Article title: "${articleTitle}" + +Article: +${articleBody}`, + }, + ], + }); + + const text = + message.content[0].type === "text" ? message.content[0].text : "[]"; + questions = parseClaudeJson(text) as ComprehensionQuestion[]; + } catch (err) { + return NextResponse.json( + { + error: "Failed to generate questions", + details: err instanceof Error ? err.message : String(err), + }, + { status: 500 }, + ); + } + + return NextResponse.json({ questions }); +}); diff --git a/src/app/api/reading/score/route.ts b/src/app/api/reading/score/route.ts new file mode 100644 index 0000000000000000000000000000000000000000..0e28275d2ea74a176854ec26693c19e1771587ec --- /dev/null +++ b/src/app/api/reading/score/route.ts @@ -0,0 +1,305 @@ +import { NextRequest, NextResponse } from "next/server"; +import { claude, parseClaudeJson } from "@/lib/claude"; +import { prisma } from "@/lib/db"; +// import { Prisma } from "@prisma/client"; +import { calculateXpGain, rollCriticalHit } from "@/lib/xp"; +import { checkLevelUp } from "@/lib/progression"; +import { EXERCISE_XP } from "@/config/xp"; +import { getArticleBySlug } from "@/lib/reading/articles"; +import type { ComprehensionQuestion } from "@/app/api/reading/questions/route"; +import { processSkillUnlocks } from "@/lib/skill-unlock"; +import { getMultiplierPercent } from "@/lib/multiplier"; +import { getTitleForLevel } from "@/config/titles"; +import { withApiError } from "@/lib/api-error"; +import { processEndOfDay } from "@/lib/streak"; + +interface ScoreBody { + slug?: string; + content?: { title: string; body: string; sourceUrl?: string }; + answers: { questionId: number; answer: string }[]; + questions: ComprehensionQuestion[]; + durationSecs: number; + userId?: number; +} + +interface QuestionScore { + questionId: number; + score: number; // 0-10 + feedback: string; +} + +interface ClaudeScoreResponse { + scores: QuestionScore[]; + overallFeedback: string; +} + +/** + * POST /api/reading/score + * + * Scores comprehension answers via Claude, calculates XP, persists to DB. + */ +export const POST = withApiError(async (request: NextRequest) => { + if (!process.env.ANTHROPIC_API_KEY) { + return NextResponse.json( + { error: "ANTHROPIC_API_KEY is not configured" }, + { status: 503 }, + ); + } + + let body: ScoreBody; + try { + body = await request.json(); + } catch { + return NextResponse.json({ error: "Invalid JSON body" }, { status: 400 }); + } + + const { slug, content, answers, questions, durationSecs } = body; + + if (!answers || !questions || answers.length === 0) { + return NextResponse.json( + { error: "answers and questions are required" }, + { status: 400 }, + ); + } + + // Resolve article content — seeded slug or custom content + let articleTitle: string; + let isCustomContent = false; + let sourceUrl = ""; + + if (slug && typeof slug === "string") { + const article = getArticleBySlug(slug); + if (!article) { + return NextResponse.json({ error: "Article not found" }, { status: 404 }); + } + articleTitle = article.title; + } else if ( + content && + typeof content.title === "string" && + typeof content.body === "string" + ) { + articleTitle = content.title; + isCustomContent = true; + sourceUrl = content.sourceUrl ?? ""; + } else { + return NextResponse.json( + { error: "Provide either a 'slug' or 'content' object" }, + { status: 400 }, + ); + } + + // Build Q&A pairs for Claude + const qaPairs = questions.map((q) => { + const a = answers.find((ans) => ans.questionId === q.id); + return { question: q.question, type: q.type, answer: a?.answer ?? "" }; + }); + + let scored: ClaudeScoreResponse; + try { + const message = await claude.messages.create({ + model: "claude-haiku-4-5-20251001", + max_tokens: 2048, + messages: [ + { + role: "user", + content: `You are scoring comprehension answers for a reading exercise. The reader answered from memory after reading the article — they no longer had access to the text. + +Score each answer 0-10 based on accuracy, depth, and relevance to the question. Be fair but rigorous — a vague or partially correct answer should score 4-6, not 8-10. + +Respond ONLY in valid JSON (no markdown, no code fences): +{ + "scores": [ + { "questionId": 1, "score": N, "feedback": "..." }, + ... + ], + "overallFeedback": "..." +} + +Article: "${articleTitle}" + +Questions and answers: +${qaPairs.map((qa, i) => `Q${i + 1} [${qa.type}]: ${qa.question}\nAnswer: ${qa.answer}`).join("\n\n")}`, + }, + ], + }); + + const text = + message.content[0].type === "text" ? message.content[0].text : "{}"; + scored = parseClaudeJson(text) as ClaudeScoreResponse; + } catch (err) { + return NextResponse.json( + { + error: "Failed to score answers", + details: err instanceof Error ? err.message : String(err), + }, + { status: 500 }, + ); + } + + // Quality score: average of all question scores / 10 + const avgScore = + scored.scores.reduce((sum, s) => sum + s.score, 0) / scored.scores.length; + const qualityScore = avgScore / 10; + + // --- Fetch user --- + const userId = body.userId ?? 1; + const user = await prisma.user.findFirst({ + where: { id: userId }, + include: { categorySkills: { where: { category: "reading" } } }, + }); + + if (!user) { + return NextResponse.json({ error: "No user found" }, { status: 404 }); + } + + const readingSkill = user.categorySkills[0]; + if (!readingSkill) { + return NextResponse.json( + { error: "Reading CategorySkill not found" }, + { status: 500 }, + ); + } + + // --- XP calculation (with skill tree multiplier) --- + const { baseXp, maxQualityBonus } = EXERCISE_XP["reading"]; + const isCriticalHit = rollCriticalHit(); + const multiplierPercent = await getMultiplierPercent(prisma, userId, "reading"); + + const xpResult = calculateXpGain({ + baseXp, + qualityScore, + maxQualityBonus, + isCriticalHit, + multiplierPercent, + }); + + // Level-up checks + const userLevelResult = checkLevelUp({ + currentXp: user.currentXp + xpResult.totalXp, + xpToNextLevel: user.xpToNextLevel, + level: user.level, + }); + + const categoryLevelResult = checkLevelUp({ + currentXp: readingSkill.currentXp + xpResult.totalXp, + xpToNextLevel: readingSkill.xpToNext, + level: readingSkill.level, + }); + + // --- Title progression --- + const newTitle = getTitleForLevel(userLevelResult.newLevel); + const titleChanged = newTitle !== user.title; + + // --- Streak processing (idempotent — no-op if already run today) --- + await processEndOfDay(userId); + + // Daily log bookkeeping + const now = new Date(); + const todayStart = new Date( + Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate()), + ); + const tomorrowStart = new Date(todayStart.getTime() + 86_400_000); + + const existingLog = await prisma.dailyLog.findFirst({ + where: { userId, date: { gte: todayStart, lt: tomorrowStart } }, + }); + + const newXpEarned = (existingLog?.xpEarned ?? 0) + xpResult.totalXp; + const newActivityCount = (existingLog?.activityCount ?? 0) + 1; + const goalMet = newXpEarned >= user.dailyGoalXp; + + let unlockResult = { unlocked: [] as string[], streakFreezesGranted: 0 }; + await prisma.$transaction(async (tx) => { + await tx.activity.create({ + data: { + userId, + category: "reading", + exerciseType: isCustomContent ? "comprehension-custom" : "comprehension", + description: `Read & comprehended: ${articleTitle}`, + baseXp: xpResult.baseXp, + qualityBonus: xpResult.qualityBonus, + isCriticalHit: xpResult.isCriticalHit, + totalXp: xpResult.totalXp, + score: qualityScore, + durationSecs, + metadata: JSON.stringify({ + ...(slug ? { slug } : {}), + articleTitle, + avgScore, + questionCount: questions.length, + ...(isCustomContent && { custom: true }), + ...(sourceUrl && { sourceUrl }), + }), + }, + }); + + await tx.user.update({ + where: { id: userId }, + data: { + totalXp: user.totalXp + xpResult.totalXp, + currentXp: userLevelResult.remainingXp, + xpToNextLevel: userLevelResult.newXpToNextLevel, + level: userLevelResult.newLevel, + ...(titleChanged && { title: newTitle }), + }, + }); + + await tx.categorySkill.update({ + where: { id: readingSkill.id }, + data: { + totalXp: readingSkill.totalXp + xpResult.totalXp, + currentXp: categoryLevelResult.remainingXp, + xpToNext: categoryLevelResult.newXpToNextLevel, + level: categoryLevelResult.newLevel, + }, + }); + + // Auto-unlock skill tree nodes if category leveled up + if (categoryLevelResult.levelsGained > 0) { + unlockResult = await processSkillUnlocks( + tx, userId, "reading", categoryLevelResult.newLevel, + ); + } + + if (existingLog) { + await tx.dailyLog.update({ + where: { id: existingLog.id }, + data: { xpEarned: newXpEarned, activityCount: newActivityCount, goalMet }, + }); + } else { + await tx.dailyLog.create({ + data: { + userId, + date: todayStart, + xpEarned: newXpEarned, + activityCount: newActivityCount, + goalMet, + }, + }); + } + }); + + return NextResponse.json({ + scores: scored.scores, + overallFeedback: scored.overallFeedback, + avgScore, + xp: { + baseXp: xpResult.baseXp, + totalXp: xpResult.totalXp, + qualityBonus: xpResult.qualityBonus, + multiplierBonus: xpResult.multiplierBonus, + multiplierPercent, + isCriticalHit: xpResult.isCriticalHit, + }, + levelUp: userLevelResult.levelsGained > 0, + categoryXp: { + currentXp: categoryLevelResult.remainingXp, + xpToNext: categoryLevelResult.newXpToNextLevel, + level: categoryLevelResult.newLevel, + levelUp: categoryLevelResult.levelsGained > 0, + }, + newTitle: titleChanged ? newTitle : undefined, + unlocks: unlockResult.unlocked, + streakFreezesGranted: unlockResult.streakFreezesGranted, + }); +}); diff --git a/src/app/api/settings/__tests__/route.test.ts b/src/app/api/settings/__tests__/route.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..0a70783fec7cf2edd682d94713ba2df8e40c7a1e --- /dev/null +++ b/src/app/api/settings/__tests__/route.test.ts @@ -0,0 +1,270 @@ +/** + * Tests for GET /api/settings and PATCH /api/settings + * + * GET: + * - 404 when no user found + * - returns name, dailyGoalXp, lichessUsername, chesscomUsername + * - null username fields coerced to empty string + * + * PATCH: + * - 400 for invalid JSON body + * - 400 for empty updates (no valid fields) + * - name: valid update, empty string rejected, >50 chars rejected, trimmed + * - dailyGoalXp: valid values accepted, invalid value rejected + * - lichessUsername: updates and clears (empty string → null) + * - chesscomUsername: updates and clears (empty string → null) + * - combined update of multiple fields + * - response shape matches GET response shape + * - DB errors propagate as 500 + */ + +import { describe, it, expect, vi, beforeEach } from "vitest"; +import { NextRequest } from "next/server"; + +// --------------------------------------------------------------------------- +// Mock prisma +// --------------------------------------------------------------------------- + +const mockUserFindFirst = vi.fn(); +const mockUserUpdate = vi.fn(); + +vi.mock("@/lib/db", () => ({ + prisma: { + user: { + findFirst: (...args: unknown[]) => mockUserFindFirst(...args), + update: (...args: unknown[]) => mockUserUpdate(...args), + }, + }, +})); + +import { GET, PATCH } from "../route"; + +// --------------------------------------------------------------------------- +// Fixtures +// --------------------------------------------------------------------------- + +const baseUser = { + id: 1, + name: "Player One", + dailyGoalXp: 100, + lichessUsername: "magnus", + chesscomUsername: "hikaru", +}; + +function makeGet(): NextRequest { + return new NextRequest("http://localhost/api/settings"); +} + +function makePatch(body?: Record): NextRequest { + return new NextRequest("http://localhost/api/settings", { + method: "PATCH", + body: body !== undefined ? JSON.stringify(body) : undefined, + headers: { "Content-Type": "application/json" }, + }); +} + +async function json(res: Response): Promise { + return res.json(); +} + +// --------------------------------------------------------------------------- +// Tests — GET +// --------------------------------------------------------------------------- + +describe("GET /api/settings", () => { + beforeEach(() => { + vi.clearAllMocks(); + }); + + it("returns 404 when no user found", async () => { + mockUserFindFirst.mockResolvedValue(null); + const res = await GET(makeGet()); + expect(res.status).toBe(404); + }); + + it("returns settings fields", async () => { + mockUserFindFirst.mockResolvedValue(baseUser); + const res = await GET(makeGet()); + expect(res.status).toBe(200); + + const body = await json(res) as Record; + expect(body.name).toBe("Player One"); + expect(body.dailyGoalXp).toBe(100); + expect(body.lichessUsername).toBe("magnus"); + expect(body.chesscomUsername).toBe("hikaru"); + }); + + it("coerces null lichessUsername to empty string", async () => { + mockUserFindFirst.mockResolvedValue({ ...baseUser, lichessUsername: null }); + const res = await GET(makeGet()); + const body = await json(res) as Record; + expect(body.lichessUsername).toBe(""); + }); + + it("coerces null chesscomUsername to empty string", async () => { + mockUserFindFirst.mockResolvedValue({ ...baseUser, chesscomUsername: null }); + const res = await GET(makeGet()); + const body = await json(res) as Record; + expect(body.chesscomUsername).toBe(""); + }); + + it("propagates DB errors as 500", async () => { + mockUserFindFirst.mockRejectedValue(new Error("DB error")); + const res = await GET(makeGet()); + expect(res.status).toBe(500); + }); +}); + +// --------------------------------------------------------------------------- +// Tests — PATCH +// --------------------------------------------------------------------------- + +describe("PATCH /api/settings", () => { + beforeEach(() => { + vi.clearAllMocks(); + mockUserUpdate.mockResolvedValue(baseUser); + }); + + it("returns 400 for invalid JSON body", async () => { + const req = new NextRequest("http://localhost/api/settings", { + method: "PATCH", + body: "not-json{{{", + headers: { "Content-Type": "application/json" }, + }); + const res = await PATCH(req); + expect(res.status).toBe(400); + }); + + it("returns 400 when no valid fields provided", async () => { + const res = await PATCH(makePatch({ unknown_field: "x" })); + expect(res.status).toBe(400); + const body = await json(res) as Record; + expect(body.error).toMatch(/no valid fields/i); + }); + + it("updates name successfully", async () => { + mockUserUpdate.mockResolvedValue({ ...baseUser, name: "New Name" }); + const res = await PATCH(makePatch({ name: "New Name" })); + expect(res.status).toBe(200); + + expect(mockUserUpdate).toHaveBeenCalledWith( + expect.objectContaining({ + data: expect.objectContaining({ name: "New Name" }), + }), + ); + }); + + it("trims name whitespace", async () => { + mockUserUpdate.mockResolvedValue({ ...baseUser, name: "Trimmed" }); + await PATCH(makePatch({ name: " Trimmed " })); + expect(mockUserUpdate).toHaveBeenCalledWith( + expect.objectContaining({ + data: expect.objectContaining({ name: "Trimmed" }), + }), + ); + }); + + it("rejects empty name", async () => { + const res = await PATCH(makePatch({ name: "" })); + expect(res.status).toBe(400); + const body = await json(res) as Record; + expect(body.error).toMatch(/name must be/i); + }); + + it("rejects name longer than 50 characters", async () => { + const res = await PATCH(makePatch({ name: "a".repeat(51) })); + expect(res.status).toBe(400); + const body = await json(res) as Record; + expect(body.error).toMatch(/name must be/i); + }); + + it("accepts a name of exactly 50 characters", async () => { + mockUserUpdate.mockResolvedValue({ ...baseUser, name: "a".repeat(50) }); + const res = await PATCH(makePatch({ name: "a".repeat(50) })); + expect(res.status).toBe(200); + }); + + it("updates dailyGoalXp with valid value", async () => { + for (const valid of [50, 100, 150, 200, 300]) { + mockUserUpdate.mockResolvedValue({ ...baseUser, dailyGoalXp: valid }); + const res = await PATCH(makePatch({ dailyGoalXp: valid })); + expect(res.status).toBe(200); + } + }); + + it("rejects invalid dailyGoalXp value", async () => { + const res = await PATCH(makePatch({ dailyGoalXp: 75 })); + expect(res.status).toBe(400); + const body = await json(res) as Record; + expect(body.error).toMatch(/dailyGoalXp/i); + }); + + it("updates lichessUsername", async () => { + mockUserUpdate.mockResolvedValue({ ...baseUser, lichessUsername: "leelaAI" }); + const res = await PATCH(makePatch({ lichessUsername: "leelaAI" })); + expect(res.status).toBe(200); + expect(mockUserUpdate).toHaveBeenCalledWith( + expect.objectContaining({ + data: expect.objectContaining({ lichessUsername: "leelaAI" }), + }), + ); + }); + + it("clears lichessUsername when empty string provided", async () => { + mockUserUpdate.mockResolvedValue({ ...baseUser, lichessUsername: null }); + await PATCH(makePatch({ lichessUsername: "" })); + expect(mockUserUpdate).toHaveBeenCalledWith( + expect.objectContaining({ + data: expect.objectContaining({ lichessUsername: null }), + }), + ); + }); + + it("updates chesscomUsername", async () => { + mockUserUpdate.mockResolvedValue({ ...baseUser, chesscomUsername: "nakamura" }); + const res = await PATCH(makePatch({ chesscomUsername: "nakamura" })); + expect(res.status).toBe(200); + }); + + it("clears chesscomUsername when empty string provided", async () => { + mockUserUpdate.mockResolvedValue({ ...baseUser, chesscomUsername: null }); + await PATCH(makePatch({ chesscomUsername: "" })); + expect(mockUserUpdate).toHaveBeenCalledWith( + expect.objectContaining({ + data: expect.objectContaining({ chesscomUsername: null }), + }), + ); + }); + + it("allows combined update of multiple fields", async () => { + mockUserUpdate.mockResolvedValue({ ...baseUser, name: "Updated", dailyGoalXp: 150 }); + const res = await PATCH(makePatch({ name: "Updated", dailyGoalXp: 150 })); + expect(res.status).toBe(200); + expect(mockUserUpdate).toHaveBeenCalledWith( + expect.objectContaining({ + data: expect.objectContaining({ name: "Updated", dailyGoalXp: 150 }), + }), + ); + }); + + it("response shape matches GET response shape", async () => { + const updatedUser = { ...baseUser, name: "New", lichessUsername: null, chesscomUsername: null }; + mockUserUpdate.mockResolvedValue(updatedUser); + const res = await PATCH(makePatch({ name: "New" })); + const body = await json(res) as Record; + + expect(body).toHaveProperty("name"); + expect(body).toHaveProperty("dailyGoalXp"); + expect(body).toHaveProperty("lichessUsername"); + expect(body).toHaveProperty("chesscomUsername"); + // null coercion + expect(body.lichessUsername).toBe(""); + expect(body.chesscomUsername).toBe(""); + }); + + it("propagates DB errors as 500", async () => { + mockUserUpdate.mockRejectedValue(new Error("DB constraint failed")); + const res = await PATCH(makePatch({ name: "ValidName" })); + expect(res.status).toBe(500); + }); +}); diff --git a/src/app/api/settings/route.ts b/src/app/api/settings/route.ts new file mode 100644 index 0000000000000000000000000000000000000000..46432d18ffeed3a23f6ca464c6a95f7418feaf60 --- /dev/null +++ b/src/app/api/settings/route.ts @@ -0,0 +1,91 @@ +import { NextRequest, NextResponse } from "next/server"; +import { prisma } from "@/lib/db"; +import { withApiError } from "@/lib/api-error"; + +// GET /api/settings — return current user settings +export const GET = withApiError(async () => { + const user = await prisma.user.findFirst({ where: { id: 1 } }); + if (!user) { + return NextResponse.json({ error: "No user found" }, { status: 404 }); + } + + return NextResponse.json({ + name: user.name, + dailyGoalXp: user.dailyGoalXp, + lichessUsername: user.lichessUsername ?? "", + chesscomUsername: user.chesscomUsername ?? "", + }); +}); + +// PATCH /api/settings — update user settings +export const PATCH = withApiError(async (req: NextRequest) => { + let body: unknown; + try { + body = await req.json(); + } catch { + return NextResponse.json({ error: "Invalid JSON" }, { status: 400 }); + } + + const { + name, + dailyGoalXp, + lichessUsername, + chesscomUsername, + } = body as { + name?: string; + dailyGoalXp?: number; + lichessUsername?: string; + chesscomUsername?: string; + }; + + // Validate + const updates: Record = {}; + + if (name !== undefined) { + const trimmed = String(name).trim(); + if (trimmed.length === 0 || trimmed.length > 50) { + return NextResponse.json( + { error: "Name must be 1–50 characters" }, + { status: 400 }, + ); + } + updates.name = trimmed; + } + + if (dailyGoalXp !== undefined) { + const valid = [50, 100, 150, 200, 300]; + if (!valid.includes(Number(dailyGoalXp))) { + return NextResponse.json( + { error: `dailyGoalXp must be one of ${valid.join(", ")}` }, + { status: 400 }, + ); + } + updates.dailyGoalXp = Number(dailyGoalXp); + } + + if (lichessUsername !== undefined) { + const trimmed = String(lichessUsername).trim(); + updates.lichessUsername = trimmed.length > 0 ? trimmed : null; + } + + if (chesscomUsername !== undefined) { + const trimmed = String(chesscomUsername).trim(); + updates.chesscomUsername = trimmed.length > 0 ? trimmed : null; + } + + if (Object.keys(updates).length === 0) { + return NextResponse.json({ error: "No valid fields to update" }, { status: 400 }); + } + + const user = await prisma.user.update({ + where: { id: 1 }, + data: updates, + }); + + return NextResponse.json({ + name: user.name, + dailyGoalXp: user.dailyGoalXp, + lichessUsername: user.lichessUsername ?? "", + chesscomUsername: user.chesscomUsername ?? "", + }); +}); diff --git a/src/app/api/stats/__tests__/achievements.test.ts b/src/app/api/stats/__tests__/achievements.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..4e578cfa9af89b8b977b21c8ed088d94b8b8c438 --- /dev/null +++ b/src/app/api/stats/__tests__/achievements.test.ts @@ -0,0 +1,515 @@ +/** + * Tests for GET /api/stats/achievements + * + * Covers: + * - 404 when no user found + * - 500 on DB error (propagated via withApiError) + * - response shape: achievements array + summary object + * - achievements: each item has required fields (id, name, description, tier, icon, earned, earnedAt, progress) + * - achievements: no duplicate IDs + * - achievements: all tiers are valid strings + * - achievements: earned=true items have earnedAt ISO string, unearned have earnedAt=null + * - achievements: progress in [0, 100] + * - summary: total matches achievements.length + * - summary: earned matches sum of earned items + * - summary: byTier counts sum to earned count + * - summary: contains bronze/silver/gold/platinum keys + * - DB query validation: user/categorySkills/activities/dailyLogs/unlocks all queried for userId=1 + * - earned achievements reflect actual DB data (level milestone earned when user.level >= threshold) + * - unearned achievements reflect actual DB data (level milestone not earned when level too low) + * - activities passed to computeAchievements (critical hit milestone) + * - dailyLogs passed to computeAchievements (goal-met milestone) + * - unlocks passed to computeAchievements (unlock milestone) + */ + +import { describe, it, expect, vi, beforeEach } from "vitest"; +import { NextRequest } from "next/server"; + +// --------------------------------------------------------------------------- +// Mock prisma +// --------------------------------------------------------------------------- + +const mockUserFindFirst = vi.fn(); +const mockCategorySkillFindMany = vi.fn(); +const mockActivityFindMany = vi.fn(); +const mockDailyLogFindMany = vi.fn(); +const mockUnlockFindMany = vi.fn(); + +vi.mock("@/lib/db", () => ({ + prisma: { + user: { findFirst: (...args: unknown[]) => mockUserFindFirst(...args) }, + categorySkill: { findMany: (...args: unknown[]) => mockCategorySkillFindMany(...args) }, + activity: { findMany: (...args: unknown[]) => mockActivityFindMany(...args) }, + dailyLog: { findMany: (...args: unknown[]) => mockDailyLogFindMany(...args) }, + unlock: { findMany: (...args: unknown[]) => mockUnlockFindMany(...args) }, + }, +})); + +import { GET } from "../achievements/route"; + +// --------------------------------------------------------------------------- +// Fixtures +// --------------------------------------------------------------------------- + +const baseUser = { + level: 1, + totalXp: 0, + streak: 0, + longestStreak: 0, + createdAt: new Date("2026-01-01T00:00:00Z"), +}; + +function makeRequest(): NextRequest { + return new NextRequest("http://localhost/api/stats/achievements"); +} + +function makeActivity(overrides: Partial<{ + category: string; + exerciseType: string; + isCriticalHit: boolean; + score: number | null; + durationSecs: number | null; + createdAt: Date; + metadata: string | null; +}> = {}) { + return { + category: "logic", + exerciseType: "sudoku", + isCriticalHit: false, + score: 0.8, + durationSecs: 120, + createdAt: new Date("2026-03-01T10:00:00Z"), + metadata: null, + ...overrides, + }; +} + +function makeLog(overrides: Partial<{ + date: Date; + goalMet: boolean; + activityCount: number; +}> = {}) { + return { + date: new Date("2026-03-01T00:00:00Z"), + goalMet: false, + activityCount: 1, + ...overrides, + }; +} + +function makeUnlock(overrides: Partial<{ unlockedAt: Date }> = {}) { + return { + unlockedAt: new Date("2026-03-01T00:00:00Z"), + ...overrides, + }; +} + +// --------------------------------------------------------------------------- +// beforeEach: reset mocks and set default happy-path returns +// --------------------------------------------------------------------------- + +beforeEach(() => { + vi.clearAllMocks(); + mockUserFindFirst.mockResolvedValue(baseUser); + mockCategorySkillFindMany.mockResolvedValue([]); + mockActivityFindMany.mockResolvedValue([]); + mockDailyLogFindMany.mockResolvedValue([]); + mockUnlockFindMany.mockResolvedValue([]); +}); + +// --------------------------------------------------------------------------- +// 404 / error paths +// --------------------------------------------------------------------------- + +describe("GET /api/stats/achievements — error paths", () => { + it("returns 404 when no user found", async () => { + mockUserFindFirst.mockResolvedValue(null); + const res = await GET(makeRequest()); + expect(res.status).toBe(404); + const body = await res.json() as Record; + expect(body.error).toBeDefined(); + }); + + it("propagates DB errors as 500", async () => { + mockUserFindFirst.mockRejectedValue(new Error("DB connection failed")); + const res = await GET(makeRequest()); + expect(res.status).toBe(500); + }); + + it("propagates parallel query errors as 500", async () => { + mockActivityFindMany.mockRejectedValue(new Error("activity query failed")); + const res = await GET(makeRequest()); + expect(res.status).toBe(500); + }); +}); + +// --------------------------------------------------------------------------- +// Response shape +// --------------------------------------------------------------------------- + +describe("GET /api/stats/achievements — response shape", () => { + it("returns 200 with achievements array and summary object", async () => { + const res = await GET(makeRequest()); + expect(res.status).toBe(200); + const body = await res.json() as Record; + expect(Array.isArray(body.achievements)).toBe(true); + expect(typeof body.summary).toBe("object"); + expect(body.summary).not.toBeNull(); + }); + + it("achievements array is non-empty", async () => { + const res = await GET(makeRequest()); + const body = await res.json() as { achievements: unknown[] }; + expect(body.achievements.length).toBeGreaterThan(0); + }); + + it("each achievement has required fields", async () => { + const res = await GET(makeRequest()); + const body = await res.json() as { + achievements: Array>; + }; + for (const a of body.achievements) { + expect(typeof a.id).toBe("string"); + expect(typeof a.name).toBe("string"); + expect(typeof a.description).toBe("string"); + expect(typeof a.tier).toBe("string"); + expect(typeof a.icon).toBe("string"); + expect(typeof a.earned).toBe("boolean"); + expect(typeof a.progress).toBe("number"); + // earnedAt is string | null + expect(a.earnedAt === null || typeof a.earnedAt === "string").toBe(true); + } + }); + + it("achievement IDs are unique", async () => { + const res = await GET(makeRequest()); + const body = await res.json() as { achievements: Array<{ id: string }> }; + const ids = body.achievements.map((a) => a.id); + const uniqueIds = new Set(ids); + expect(uniqueIds.size).toBe(ids.length); + }); + + it("achievement tiers are valid values", async () => { + const validTiers = new Set(["bronze", "silver", "gold", "platinum"]); + const res = await GET(makeRequest()); + const body = await res.json() as { achievements: Array<{ tier: string }> }; + for (const a of body.achievements) { + expect(validTiers.has(a.tier)).toBe(true); + } + }); + + it("progress values are in [0, 100]", async () => { + const res = await GET(makeRequest()); + const body = await res.json() as { achievements: Array<{ progress: number }> }; + for (const a of body.achievements) { + expect(a.progress).toBeGreaterThanOrEqual(0); + expect(a.progress).toBeLessThanOrEqual(100); + } + }); + + it("earned achievements have earnedAt as ISO string", async () => { + const res = await GET(makeRequest()); + const body = await res.json() as { + achievements: Array<{ earned: boolean; earnedAt: string | null }>; + }; + const earned = body.achievements.filter((a) => a.earned); + // With base user (level 1, 0 XP, 0 activities) the "first solve" type + // milestones won't be earned, but if any are, earnedAt must be a string. + for (const a of earned) { + expect(typeof a.earnedAt).toBe("string"); + } + }); + + it("unearned achievements have earnedAt=null", async () => { + const res = await GET(makeRequest()); + const body = await res.json() as { + achievements: Array<{ earned: boolean; earnedAt: string | null }>; + }; + const unearned = body.achievements.filter((a) => !a.earned); + expect(unearned.length).toBeGreaterThan(0); // with level 1 / 0 XP, most are unearned + for (const a of unearned) { + expect(a.earnedAt).toBeNull(); + } + }); + + it("earned progress is capped at 100", async () => { + const res = await GET(makeRequest()); + const body = await res.json() as { + achievements: Array<{ earned: boolean; progress: number }>; + }; + const earned = body.achievements.filter((a) => a.earned); + for (const a of earned) { + expect(a.progress).toBe(100); + } + }); +}); + +// --------------------------------------------------------------------------- +// Summary shape +// --------------------------------------------------------------------------- + +describe("GET /api/stats/achievements — summary", () => { + it("summary.total equals achievements.length", async () => { + const res = await GET(makeRequest()); + const body = await res.json() as { + achievements: unknown[]; + summary: { total: number }; + }; + expect(body.summary.total).toBe(body.achievements.length); + }); + + it("summary.earned equals count of earned achievements", async () => { + const res = await GET(makeRequest()); + const body = await res.json() as { + achievements: Array<{ earned: boolean }>; + summary: { earned: number }; + }; + const earnedCount = body.achievements.filter((a) => a.earned).length; + expect(body.summary.earned).toBe(earnedCount); + }); + + it("summary.byTier has bronze/silver/gold/platinum keys with total and earned", async () => { + const res = await GET(makeRequest()); + const body = await res.json() as { + summary: { byTier: Record }; + }; + for (const tier of ["bronze", "silver", "gold", "platinum"]) { + expect(typeof body.summary.byTier[tier].total).toBe("number"); + expect(typeof body.summary.byTier[tier].earned).toBe("number"); + } + }); + + it("byTier earned counts sum to summary.earned", async () => { + const res = await GET(makeRequest()); + const body = await res.json() as { + summary: { + earned: number; + byTier: Record; + }; + }; + const tierEarnedSum = + body.summary.byTier.bronze.earned + + body.summary.byTier.silver.earned + + body.summary.byTier.gold.earned + + body.summary.byTier.platinum.earned; + expect(tierEarnedSum).toBe(body.summary.earned); + }); + + it("byTier total counts sum to summary.total", async () => { + const res = await GET(makeRequest()); + const body = await res.json() as { + summary: { + total: number; + byTier: Record; + }; + }; + const tierTotalSum = + body.summary.byTier.bronze.total + + body.summary.byTier.silver.total + + body.summary.byTier.gold.total + + body.summary.byTier.platinum.total; + expect(tierTotalSum).toBe(body.summary.total); + }); + + it("summary.earned is 0 for a brand-new user with no data", async () => { + const res = await GET(makeRequest()); + const body = await res.json() as { summary: { earned: number } }; + // Brand-new user: level 1, 0 XP, no activities — expect 0 earned + expect(body.summary.earned).toBe(0); + }); +}); + +// --------------------------------------------------------------------------- +// DB query validation +// --------------------------------------------------------------------------- + +describe("GET /api/stats/achievements — DB queries", () => { + it("queries user with userId=1", async () => { + await GET(makeRequest()); + expect(mockUserFindFirst).toHaveBeenCalledWith( + expect.objectContaining({ where: { id: 1 } }) + ); + }); + + it("queries categorySkills with userId=1", async () => { + await GET(makeRequest()); + expect(mockCategorySkillFindMany).toHaveBeenCalledWith( + expect.objectContaining({ where: { userId: 1 } }) + ); + }); + + it("queries activities with userId=1", async () => { + await GET(makeRequest()); + expect(mockActivityFindMany).toHaveBeenCalledWith( + expect.objectContaining({ where: { userId: 1 } }) + ); + }); + + it("queries dailyLogs with userId=1", async () => { + await GET(makeRequest()); + expect(mockDailyLogFindMany).toHaveBeenCalledWith( + expect.objectContaining({ where: { userId: 1 } }) + ); + }); + + it("queries unlocks with userId=1", async () => { + await GET(makeRequest()); + expect(mockUnlockFindMany).toHaveBeenCalledWith( + expect.objectContaining({ where: { userId: 1 } }) + ); + }); + + it("selects required user fields", async () => { + await GET(makeRequest()); + expect(mockUserFindFirst).toHaveBeenCalledWith( + expect.objectContaining({ + select: expect.objectContaining({ + level: true, + totalXp: true, + streak: true, + longestStreak: true, + createdAt: true, + }), + }) + ); + }); + + it("orders activities by createdAt asc", async () => { + await GET(makeRequest()); + expect(mockActivityFindMany).toHaveBeenCalledWith( + expect.objectContaining({ + orderBy: { createdAt: "asc" }, + }) + ); + }); + + it("orders unlocks by unlockedAt asc", async () => { + await GET(makeRequest()); + expect(mockUnlockFindMany).toHaveBeenCalledWith( + expect.objectContaining({ + orderBy: { unlockedAt: "asc" }, + }) + ); + }); +}); + +// --------------------------------------------------------------------------- +// Data-driven: achievements earned / unearned based on DB content +// --------------------------------------------------------------------------- + +describe("GET /api/stats/achievements — earned based on DB data", () => { + it("level-5 bronze achievement earned when user.level >= 5", async () => { + mockUserFindFirst.mockResolvedValue({ ...baseUser, level: 5, totalXp: 800 }); + const res = await GET(makeRequest()); + const body = await res.json() as { achievements: Array<{ id: string; earned: boolean; progress: number }> }; + const level5 = body.achievements.find((a) => a.id === "level-5"); + expect(level5).toBeDefined(); + expect(level5!.earned).toBe(true); + expect(level5!.progress).toBe(100); + }); + + it("level-5 bronze achievement not earned when user.level < 5", async () => { + mockUserFindFirst.mockResolvedValue({ ...baseUser, level: 3, totalXp: 200 }); + const res = await GET(makeRequest()); + const body = await res.json() as { achievements: Array<{ id: string; earned: boolean; progress: number }> }; + const level5 = body.achievements.find((a) => a.id === "level-5"); + expect(level5).toBeDefined(); + expect(level5!.earned).toBe(false); + expect(level5!.progress).toBeLessThan(100); + }); + + it("xp-1000 bronze achievement earned when totalXp >= 1000", async () => { + mockUserFindFirst.mockResolvedValue({ ...baseUser, level: 5, totalXp: 1000 }); + const res = await GET(makeRequest()); + const body = await res.json() as { achievements: Array<{ id: string; earned: boolean }> }; + const xp1k = body.achievements.find((a) => a.id === "xp-1000"); + expect(xp1k).toBeDefined(); + expect(xp1k!.earned).toBe(true); + }); + + it("streak-7 silver achievement earned when longestStreak >= 7", async () => { + mockUserFindFirst.mockResolvedValue({ ...baseUser, longestStreak: 7 }); + const res = await GET(makeRequest()); + const body = await res.json() as { achievements: Array<{ id: string; earned: boolean }> }; + const s7 = body.achievements.find((a) => a.id === "streak-7"); + expect(s7).toBeDefined(); + expect(s7!.earned).toBe(true); + }); + + it("critical hit achievement earned when isCriticalHit activities exist", async () => { + mockActivityFindMany.mockResolvedValue([ + makeActivity({ isCriticalHit: true }), + ]); + const res = await GET(makeRequest()); + const body = await res.json() as { achievements: Array<{ id: string; earned: boolean }> }; + const crit1 = body.achievements.find((a) => a.id === "crit-1"); + expect(crit1).toBeDefined(); + expect(crit1!.earned).toBe(true); + }); + + it("goals-7 achievement earned when 7+ dailyLogs have goalMet=true", async () => { + const logs = Array.from({ length: 7 }, (_, i) => + makeLog({ + date: new Date(`2026-03-${String(i + 1).padStart(2, "0")}T00:00:00Z`), + goalMet: true, + }) + ); + mockDailyLogFindMany.mockResolvedValue(logs); + const res = await GET(makeRequest()); + const body = await res.json() as { achievements: Array<{ id: string; earned: boolean }> }; + const goal7 = body.achievements.find((a) => a.id === "goals-7"); + expect(goal7).toBeDefined(); + expect(goal7!.earned).toBe(true); + }); + + it("unlock-1 achievement earned when at least 1 unlock exists", async () => { + mockUnlockFindMany.mockResolvedValue([makeUnlock()]); + const res = await GET(makeRequest()); + const body = await res.json() as { achievements: Array<{ id: string; earned: boolean }> }; + const u1 = body.achievements.find((a) => a.id === "unlock-1"); + expect(u1).toBeDefined(); + expect(u1!.earned).toBe(true); + }); + + it("summary.earned increases when user data crosses thresholds", async () => { + // First call: brand-new user + const res1 = await GET(makeRequest()); + const body1 = await res1.json() as { summary: { earned: number } }; + const earnedBefore = body1.summary.earned; + + // Second call: user with level 5 + mockUserFindFirst.mockResolvedValue({ ...baseUser, level: 5, totalXp: 1000 }); + const res2 = await GET(makeRequest()); + const body2 = await res2.json() as { summary: { earned: number } }; + + expect(body2.summary.earned).toBeGreaterThan(earnedBefore); + }); +}); + +// --------------------------------------------------------------------------- +// categorySkills passed through (mastery achievements) +// --------------------------------------------------------------------------- + +describe("GET /api/stats/achievements — categorySkills data", () => { + it("chess mastery-5 achievement earned when chess level >= 5", async () => { + mockCategorySkillFindMany.mockResolvedValue([ + { category: "chess", level: 5, totalXp: 500 }, + ]); + const res = await GET(makeRequest()); + const body = await res.json() as { achievements: Array<{ id: string; earned: boolean }> }; + const chessL5 = body.achievements.find((a) => a.id === "chess-level-5"); + expect(chessL5).toBeDefined(); + expect(chessL5!.earned).toBe(true); + }); + + it("chess mastery-5 not earned when chess level < 5", async () => { + mockCategorySkillFindMany.mockResolvedValue([ + { category: "chess", level: 2, totalXp: 100 }, + ]); + const res = await GET(makeRequest()); + const body = await res.json() as { achievements: Array<{ id: string; earned: boolean }> }; + const chessL5 = body.achievements.find((a) => a.id === "chess-level-5"); + expect(chessL5).toBeDefined(); + expect(chessL5!.earned).toBe(false); + }); +}); diff --git a/src/app/api/stats/__tests__/best-scores.test.ts b/src/app/api/stats/__tests__/best-scores.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..60c9752b8ba837e0fd97adde19f6cabf28278cb2 --- /dev/null +++ b/src/app/api/stats/__tests__/best-scores.test.ts @@ -0,0 +1,336 @@ +/** + * Tests for GET /api/stats/best-scores + * + * Covers: + * - empty byExerciseType and byCategory when no activities exist + * - response shape: { byExerciseType, byCategory } + * - byExerciseType: each entry has required fields + * - byCategory: each entry has required fields + * - only activities with non-null score contribute to best scores + * - best score is the highest quality score across all attempts for a type + * - attemptCount includes unscored activities + * - scoredCount only counts activities with non-null score + * - achievedAt matches the ISO timestamp of the highest-scored activity + * - byCategory bestScore is the highest across all exercise types in category + * - byCategory avgScore is average of all scored activities (2 dp rounding) + * - DB query fetches all activities for userId=1, ordered by createdAt asc + * - DB query selects only the needed fields (category, exerciseType, score, totalXp, createdAt) + * - 500 on DB error (propagated via withApiError) + * - all 6 canonical categories are present in byCategory even when no data + * - byExerciseType entries are ordered by category display order + * - activities with null score contribute to attemptCount but not scoredCount or bestScore + */ + +import { describe, it, expect, vi, beforeEach } from "vitest"; +import { NextRequest } from "next/server"; + +// --------------------------------------------------------------------------- +// Mock prisma +// --------------------------------------------------------------------------- + +const mockActivityFindMany = vi.fn(); + +vi.mock("@/lib/db", () => ({ + prisma: { + activity: { findMany: (...args: unknown[]) => mockActivityFindMany(...args) }, + }, +})); + +import { GET } from "../best-scores/route"; + +// --------------------------------------------------------------------------- +// Helpers +// --------------------------------------------------------------------------- + +function makeRequest() { + return new NextRequest("http://localhost/api/stats/best-scores"); +} + +function makeActivity(overrides: { + category: string; + exerciseType: string; + score: number | null; + totalXp?: number; + createdAt?: Date; +}) { + return { + category: overrides.category, + exerciseType: overrides.exerciseType, + score: overrides.score, + totalXp: overrides.totalXp ?? 50, + createdAt: overrides.createdAt ?? new Date("2026-01-15T10:00:00Z"), + }; +} + +async function json(res: Response) { + return res.json() as Promise>; +} + +beforeEach(() => { + mockActivityFindMany.mockResolvedValue([]); +}); + +// --------------------------------------------------------------------------- +// Empty / no-data cases +// --------------------------------------------------------------------------- + +describe("GET /api/stats/best-scores — empty data", () => { + it("returns 200 with empty byExerciseType when no activities", async () => { + mockActivityFindMany.mockResolvedValue([]); + const res = await GET(makeRequest()); + expect(res.status).toBe(200); + const body = await json(res); + expect(Array.isArray(body.byExerciseType)).toBe(true); + expect((body.byExerciseType as unknown[]).length).toBe(0); + }); + + it("all 6 canonical categories are present in byCategory even with no data", async () => { + mockActivityFindMany.mockResolvedValue([]); + const res = await GET(makeRequest()); + const body = await json(res); + const cats = (body.byCategory as Array<{ category: string }>).map((c) => c.category); + expect(cats).toContain("chess"); + expect(cats).toContain("reading"); + expect(cats).toContain("feynman"); + expect(cats).toContain("logic"); + expect(cats).toContain("critical-thinking"); + expect(cats).toContain("quests"); + expect(cats.length).toBe(7); + }); + + it("byCategory entries have zero/null stats when no activities", async () => { + mockActivityFindMany.mockResolvedValue([]); + const res = await GET(makeRequest()); + const body = await json(res); + const chess = (body.byCategory as Array<{ category: string; attemptCount: number; avgScore: number; bestScore: number }>) + .find((c) => c.category === "chess"); + expect(chess).toBeDefined(); + expect(chess!.attemptCount).toBe(0); + expect(chess!.avgScore).toBe(0); + expect(chess!.bestScore).toBe(0); + }); +}); + +// --------------------------------------------------------------------------- +// Response shape +// --------------------------------------------------------------------------- + +describe("GET /api/stats/best-scores — response shape", () => { + it("has byExerciseType and byCategory top-level keys", async () => { + mockActivityFindMany.mockResolvedValue([]); + const res = await GET(makeRequest()); + const body = await json(res); + expect(body).toHaveProperty("byExerciseType"); + expect(body).toHaveProperty("byCategory"); + }); + + it("byExerciseType entry has all required fields", async () => { + mockActivityFindMany.mockResolvedValue([ + makeActivity({ category: "chess", exerciseType: "puzzle", score: 0.8 }), + ]); + const res = await GET(makeRequest()); + const body = await json(res); + const entry = (body.byExerciseType as unknown[])[0] as Record; + expect(entry).toHaveProperty("category"); + expect(entry).toHaveProperty("categoryLabel"); + expect(entry).toHaveProperty("exerciseType"); + expect(entry).toHaveProperty("exerciseLabel"); + expect(entry).toHaveProperty("bestScore"); + expect(entry).toHaveProperty("attemptCount"); + expect(entry).toHaveProperty("scoredCount"); + expect(entry).toHaveProperty("achievedAt"); + }); + + it("byCategory entry has all required fields", async () => { + mockActivityFindMany.mockResolvedValue([ + makeActivity({ category: "chess", exerciseType: "puzzle", score: 0.8 }), + ]); + const res = await GET(makeRequest()); + const body = await json(res); + const chessEntry = (body.byCategory as Array>) + .find((c) => c.category === "chess"); + expect(chessEntry).toHaveProperty("category"); + expect(chessEntry).toHaveProperty("categoryLabel"); + expect(chessEntry).toHaveProperty("bestScore"); + expect(chessEntry).toHaveProperty("attemptCount"); + expect(chessEntry).toHaveProperty("avgScore"); + }); +}); + +// --------------------------------------------------------------------------- +// Score computation +// --------------------------------------------------------------------------- + +describe("GET /api/stats/best-scores — score computation", () => { + it("best score is the highest score across multiple attempts", async () => { + mockActivityFindMany.mockResolvedValue([ + makeActivity({ category: "chess", exerciseType: "puzzle", score: 0.5, createdAt: new Date("2026-01-01T10:00:00Z") }), + makeActivity({ category: "chess", exerciseType: "puzzle", score: 0.9, createdAt: new Date("2026-01-02T10:00:00Z") }), + makeActivity({ category: "chess", exerciseType: "puzzle", score: 0.7, createdAt: new Date("2026-01-03T10:00:00Z") }), + ]); + const res = await GET(makeRequest()); + const body = await json(res); + const entry = (body.byExerciseType as Array<{ exerciseType: string; bestScore: number }>) + .find((e) => e.exerciseType === "puzzle"); + expect(entry).toBeDefined(); + expect(entry!.bestScore).toBe(0.9); + }); + + it("achievedAt corresponds to the highest-scored activity", async () => { + const highScoreDate = new Date("2026-02-15T14:30:00Z"); + mockActivityFindMany.mockResolvedValue([ + makeActivity({ category: "chess", exerciseType: "puzzle", score: 0.5, createdAt: new Date("2026-01-01T10:00:00Z") }), + makeActivity({ category: "chess", exerciseType: "puzzle", score: 0.9, createdAt: highScoreDate }), + makeActivity({ category: "chess", exerciseType: "puzzle", score: 0.7, createdAt: new Date("2026-03-01T10:00:00Z") }), + ]); + const res = await GET(makeRequest()); + const body = await json(res); + const entry = (body.byExerciseType as Array<{ exerciseType: string; achievedAt: string }>) + .find((e) => e.exerciseType === "puzzle"); + expect(entry!.achievedAt).toBe(highScoreDate.toISOString()); + }); + + it("null-score activities contribute to attemptCount but not scoredCount or bestScore", async () => { + mockActivityFindMany.mockResolvedValue([ + makeActivity({ category: "feynman", exerciseType: "explain", score: null }), + makeActivity({ category: "feynman", exerciseType: "explain", score: null }), + makeActivity({ category: "feynman", exerciseType: "explain", score: 0.75 }), + ]); + const res = await GET(makeRequest()); + const body = await json(res); + const entry = (body.byExerciseType as Array<{ exerciseType: string; attemptCount: number; scoredCount: number; bestScore: number }>) + .find((e) => e.exerciseType === "explain"); + expect(entry).toBeDefined(); + expect(entry!.attemptCount).toBe(3); + expect(entry!.scoredCount).toBe(1); + expect(entry!.bestScore).toBe(0.75); + }); + + it("byCategory bestScore is the highest across all exercise types in category", async () => { + mockActivityFindMany.mockResolvedValue([ + makeActivity({ category: "critical-thinking", exerciseType: "flaw-finder", score: 0.6 }), + makeActivity({ category: "critical-thinking", exerciseType: "steelman", score: 0.95 }), + makeActivity({ category: "critical-thinking", exerciseType: "devils-advocate", score: 0.8 }), + ]); + const res = await GET(makeRequest()); + const body = await json(res); + const catEntry = (body.byCategory as Array<{ category: string; bestScore: number }>) + .find((c) => c.category === "critical-thinking"); + expect(catEntry).toBeDefined(); + expect(catEntry!.bestScore).toBe(0.95); + }); + + it("byCategory avgScore is average of all scored activities (2 dp)", async () => { + mockActivityFindMany.mockResolvedValue([ + makeActivity({ category: "reading", exerciseType: "comprehension", score: 0.8 }), + makeActivity({ category: "reading", exerciseType: "comprehension", score: 0.6 }), + makeActivity({ category: "reading", exerciseType: "comprehension", score: null }), + ]); + const res = await GET(makeRequest()); + const body = await json(res); + const catEntry = (body.byCategory as Array<{ category: string; avgScore: number }>) + .find((c) => c.category === "reading"); + // (0.8 + 0.6) / 2 = 0.7 + expect(catEntry!.avgScore).toBe(0.7); + }); + + it("byCategory avgScore excludes null-score activities from denominator", async () => { + mockActivityFindMany.mockResolvedValue([ + makeActivity({ category: "quests", exerciseType: "lesson", score: 1.0 }), + makeActivity({ category: "quests", exerciseType: "lesson", score: null }), + makeActivity({ category: "quests", exerciseType: "lesson", score: null }), + ]); + const res = await GET(makeRequest()); + const body = await json(res); + const catEntry = (body.byCategory as Array<{ category: string; avgScore: number }>) + .find((c) => c.category === "quests"); + // Only 1 scored: avg = 1.0 / 1 = 1.0 + expect(catEntry!.avgScore).toBe(1.0); + }); + + it("multiple categories are independent", async () => { + mockActivityFindMany.mockResolvedValue([ + makeActivity({ category: "chess", exerciseType: "puzzle", score: 0.7 }), + makeActivity({ category: "feynman", exerciseType: "explain", score: 0.9 }), + ]); + const res = await GET(makeRequest()); + const body = await json(res); + const chessCat = (body.byCategory as Array<{ category: string; bestScore: number }>) + .find((c) => c.category === "chess"); + const feynmanCat = (body.byCategory as Array<{ category: string; bestScore: number }>) + .find((c) => c.category === "feynman"); + expect(chessCat!.bestScore).toBe(0.7); + expect(feynmanCat!.bestScore).toBe(0.9); + }); + + it("attemptCount includes all activities for the category+exerciseType", async () => { + mockActivityFindMany.mockResolvedValue([ + makeActivity({ category: "logic", exerciseType: "sudoku", score: 1.0 }), + makeActivity({ category: "logic", exerciseType: "sudoku", score: 0.0 }), + makeActivity({ category: "logic", exerciseType: "sudoku", score: null }), + ]); + const res = await GET(makeRequest()); + const body = await json(res); + const entry = (body.byExerciseType as Array<{ exerciseType: string; attemptCount: number }>) + .find((e) => e.exerciseType === "sudoku"); + expect(entry!.attemptCount).toBe(3); + }); +}); + +// --------------------------------------------------------------------------- +// DB query validation +// --------------------------------------------------------------------------- + +describe("GET /api/stats/best-scores — DB query", () => { + it("queries activities for userId=1", async () => { + await GET(makeRequest()); + expect(mockActivityFindMany).toHaveBeenCalledWith( + expect.objectContaining({ + where: { userId: 1 }, + }) + ); + }); + + it("orders activities by createdAt ascending", async () => { + await GET(makeRequest()); + expect(mockActivityFindMany).toHaveBeenCalledWith( + expect.objectContaining({ + orderBy: { createdAt: "asc" }, + }) + ); + }); + + it("selects only the required fields", async () => { + await GET(makeRequest()); + expect(mockActivityFindMany).toHaveBeenCalledWith( + expect.objectContaining({ + select: expect.objectContaining({ + category: true, + exerciseType: true, + score: true, + totalXp: true, + createdAt: true, + }), + }) + ); + }); +}); + +// --------------------------------------------------------------------------- +// Error handling +// --------------------------------------------------------------------------- + +describe("GET /api/stats/best-scores — error handling", () => { + it("returns 500 on DB error", async () => { + mockActivityFindMany.mockRejectedValue(new Error("DB connection lost")); + const res = await GET(makeRequest()); + expect(res.status).toBe(500); + }); + + it("includes error message in 500 response", async () => { + mockActivityFindMany.mockRejectedValue(new Error("query failed")); + const res = await GET(makeRequest()); + const body = await json(res); + expect(typeof body.error).toBe("string"); + }); +}); diff --git a/src/app/api/stats/__tests__/personal-bests.test.ts b/src/app/api/stats/__tests__/personal-bests.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..90f1410524d051e9455acba8c6136d7240177792 --- /dev/null +++ b/src/app/api/stats/__tests__/personal-bests.test.ts @@ -0,0 +1,371 @@ +/** + * Tests for GET /api/stats/personal-bests + * + * Covers: + * - empty records when no activities exist + * - empty records when all activities have null durationSecs + * - empty records when all activities have score ≤ 0 + * - correctly identifies personal best (fastest correct solve per type+difficulty) + * - accumulates solveCount across multiple correct solves + * - ignores activities with null durationSecs + * - ignores activities with score = 0 (wrong answers) + * - ignores activities with score = null + * - difficulty extracted from description: "easy", "medium", "hard" + * - activities with no recognisable difficulty are skipped + * - response is ordered: exercise type order, then easy → medium → hard + * - all 6 logic exercise types appear when data exists for each + * - achievedAt is the ISO timestamp of the fastest solve + * - response shape: { records: [...] } + * - DB errors propagate as 500 + */ + +import { describe, it, expect, vi, beforeEach } from "vitest"; +import { NextRequest } from "next/server"; + +// --------------------------------------------------------------------------- +// Mock prisma +// --------------------------------------------------------------------------- + +const mockActivityFindMany = vi.fn(); + +vi.mock("@/lib/db", () => ({ + prisma: { + activity: { findMany: (...args: unknown[]) => mockActivityFindMany(...args) }, + }, +})); + +import { GET } from "../personal-bests/route"; + +// --------------------------------------------------------------------------- +// Helpers +// --------------------------------------------------------------------------- + +function makeRequest() { + return new NextRequest("http://localhost/api/stats/personal-bests"); +} + +function makeActivity(overrides: { + exerciseType: string; + description: string; + durationSecs: number | null; + score: number | null; + createdAt?: Date; +}) { + return { + exerciseType: overrides.exerciseType, + description: overrides.description, + durationSecs: overrides.durationSecs, + score: overrides.score, + createdAt: overrides.createdAt ?? new Date("2026-01-15T10:00:00Z"), + }; +} + +async function json(res: Response) { + return res.json() as Promise>; +} + +beforeEach(() => { + mockActivityFindMany.mockResolvedValue([]); +}); + +// --------------------------------------------------------------------------- +// Empty / no-data cases +// --------------------------------------------------------------------------- + +describe("GET /api/stats/personal-bests — empty data", () => { + it("returns empty records array when no activities exist", async () => { + mockActivityFindMany.mockResolvedValue([]); + const res = await GET(makeRequest()); + expect(res.status).toBe(200); + const body = await json(res); + expect(body.records).toEqual([]); + }); + + it("returns empty records when prisma returns no activities (DB filters applied)", async () => { + // The DB query filters durationSecs NOT NULL and score > 0. + // When those filters exclude everything, prisma returns []. + mockActivityFindMany.mockResolvedValue([]); + const res = await GET(makeRequest()); + const body = await json(res); + expect(body.records).toEqual([]); + }); + + it("skips activities with no recognisable difficulty in description", async () => { + mockActivityFindMany.mockResolvedValue([ + makeActivity({ exerciseType: "sudoku", description: "Completed Sudoku in 60s", durationSecs: 60, score: 1 }), + ]); + const res = await GET(makeRequest()); + const body = await json(res); + expect(body.records).toEqual([]); + }); +}); + +// --------------------------------------------------------------------------- +// Correct extraction +// --------------------------------------------------------------------------- + +describe("GET /api/stats/personal-bests — PB extraction", () => { + it("returns one record for a single correct solve", async () => { + mockActivityFindMany.mockResolvedValue([ + makeActivity({ exerciseType: "sudoku", description: "Completed easy Sudoku in 120s", durationSecs: 120, score: 1 }), + ]); + const res = await GET(makeRequest()); + const body = await json(res); + const records = body.records as Array>; + expect(records).toHaveLength(1); + const r = records[0]; + expect(r.exerciseType).toBe("sudoku"); + expect(r.difficulty).toBe("easy"); + expect(r.bestSecs).toBe(120); + expect(r.solveCount).toBe(1); + }); + + it("picks the fastest solve as bestSecs (activities pre-ordered by durationSecs asc)", async () => { + // Simulate prisma returning in ascending order (fastest first) + mockActivityFindMany.mockResolvedValue([ + makeActivity({ exerciseType: "sudoku", description: "Completed easy Sudoku in 90s", durationSecs: 90, score: 1, createdAt: new Date("2026-01-20T10:00:00Z") }), + makeActivity({ exerciseType: "sudoku", description: "Completed easy Sudoku in 120s", durationSecs: 120, score: 1 }), + makeActivity({ exerciseType: "sudoku", description: "Completed easy Sudoku in 240s", durationSecs: 240, score: 1 }), + ]); + const res = await GET(makeRequest()); + const body = await json(res); + const records = body.records as Array>; + expect(records).toHaveLength(1); + expect(records[0].bestSecs).toBe(90); + }); + + it("accumulates solveCount across multiple correct solves for same type+difficulty", async () => { + mockActivityFindMany.mockResolvedValue([ + makeActivity({ exerciseType: "sudoku", description: "Completed easy Sudoku in 90s", durationSecs: 90, score: 1 }), + makeActivity({ exerciseType: "sudoku", description: "Completed easy Sudoku in 120s", durationSecs: 120, score: 1 }), + makeActivity({ exerciseType: "sudoku", description: "Completed easy Sudoku in 150s", durationSecs: 150, score: 1 }), + ]); + const res = await GET(makeRequest()); + const body = await json(res); + const records = body.records as Array>; + expect(records[0].solveCount).toBe(3); + }); + + it("keeps separate records for different difficulties of the same exercise type", async () => { + mockActivityFindMany.mockResolvedValue([ + makeActivity({ exerciseType: "sudoku", description: "Completed easy Sudoku in 90s", durationSecs: 90, score: 1 }), + makeActivity({ exerciseType: "sudoku", description: "Completed medium Sudoku in 200s", durationSecs: 200, score: 1 }), + makeActivity({ exerciseType: "sudoku", description: "Completed hard Sudoku in 450s", durationSecs: 450, score: 1 }), + ]); + const res = await GET(makeRequest()); + const body = await json(res); + const records = body.records as Array>; + expect(records).toHaveLength(3); + expect(records.map((r) => r.difficulty)).toEqual(["easy", "medium", "hard"]); + expect(records.map((r) => r.bestSecs)).toEqual([90, 200, 450]); + }); + + it("keeps separate records for different exercise types", async () => { + mockActivityFindMany.mockResolvedValue([ + makeActivity({ exerciseType: "sudoku", description: "Completed easy Sudoku in 90s", durationSecs: 90, score: 1 }), + makeActivity({ exerciseType: "sequence", description: "Completed easy number sequence in 25s", durationSecs: 25, score: 1 }), + ]); + const res = await GET(makeRequest()); + const body = await json(res); + const records = body.records as Array>; + expect(records).toHaveLength(2); + const types = records.map((r) => r.exerciseType); + expect(types).toContain("sudoku"); + expect(types).toContain("sequence"); + }); +}); + +// --------------------------------------------------------------------------- +// Difficulty extraction from description +// --------------------------------------------------------------------------- + +describe("GET /api/stats/personal-bests — difficulty extraction", () => { + it('extracts "easy" from description', async () => { + mockActivityFindMany.mockResolvedValue([ + makeActivity({ exerciseType: "mathequation", description: "Solved easy math equation in 20s", durationSecs: 20, score: 1 }), + ]); + const res = await GET(makeRequest()); + const records = ((await json(res)).records) as Array>; + expect(records[0].difficulty).toBe("easy"); + }); + + it('extracts "medium" from description', async () => { + mockActivityFindMany.mockResolvedValue([ + makeActivity({ exerciseType: "pattern", description: "Completed medium pattern matrix in 40s", durationSecs: 40, score: 1 }), + ]); + const res = await GET(makeRequest()); + const records = ((await json(res)).records) as Array>; + expect(records[0].difficulty).toBe("medium"); + }); + + it('extracts "hard" from description', async () => { + mockActivityFindMany.mockResolvedValue([ + makeActivity({ exerciseType: "constraint", description: "Completed hard constraint grid in 180s", durationSecs: 180, score: 1 }), + ]); + const res = await GET(makeRequest()); + const records = ((await json(res)).records) as Array>; + expect(records[0].difficulty).toBe("hard"); + }); + + it("is case-insensitive for difficulty matching", async () => { + mockActivityFindMany.mockResolvedValue([ + makeActivity({ exerciseType: "wordscramble", description: "Completed EASY word scramble in 18s", durationSecs: 18, score: 1 }), + ]); + const res = await GET(makeRequest()); + const records = ((await json(res)).records) as Array>; + expect(records[0].difficulty).toBe("easy"); + }); +}); + +// --------------------------------------------------------------------------- +// exerciseLabel +// --------------------------------------------------------------------------- + +describe("GET /api/stats/personal-bests — exerciseLabel", () => { + const labelCases: Array<[string, string]> = [ + ["sudoku", "Sudoku"], + ["sequence", "Number Sequence"], + ["pattern", "Pattern Matrix"], + ["wordscramble", "Word Scramble"], + ["constraint", "Constraint Grid"], + ["mathequation", "Math Equation"], + ]; + + for (const [type, expectedLabel] of labelCases) { + it(`returns correct exerciseLabel for ${type}`, async () => { + mockActivityFindMany.mockResolvedValue([ + makeActivity({ exerciseType: type, description: `Completed easy ${type} in 60s`, durationSecs: 60, score: 1 }), + ]); + const res = await GET(makeRequest()); + const records = ((await json(res)).records) as Array>; + expect(records[0].exerciseLabel).toBe(expectedLabel); + }); + } +}); + +// --------------------------------------------------------------------------- +// Ordering +// --------------------------------------------------------------------------- + +describe("GET /api/stats/personal-bests — ordering", () => { + it("orders exercise types in canonical order (sudoku, sequence, pattern, wordscramble, constraint, mathequation)", async () => { + mockActivityFindMany.mockResolvedValue([ + makeActivity({ exerciseType: "mathequation", description: "Solved easy math equation in 20s", durationSecs: 20, score: 1 }), + makeActivity({ exerciseType: "pattern", description: "Completed easy pattern matrix in 30s", durationSecs: 30, score: 1 }), + makeActivity({ exerciseType: "sudoku", description: "Completed easy Sudoku in 90s", durationSecs: 90, score: 1 }), + makeActivity({ exerciseType: "sequence", description: "Completed easy number sequence in 25s", durationSecs: 25, score: 1 }), + ]); + const res = await GET(makeRequest()); + const records = ((await json(res)).records) as Array>; + const types = records.map((r) => r.exerciseType); + expect(types).toEqual(["sudoku", "sequence", "pattern", "mathequation"]); + }); + + it("orders difficulties easy → medium → hard within each exercise type", async () => { + mockActivityFindMany.mockResolvedValue([ + makeActivity({ exerciseType: "sudoku", description: "Completed hard Sudoku in 450s", durationSecs: 450, score: 1 }), + makeActivity({ exerciseType: "sudoku", description: "Completed easy Sudoku in 90s", durationSecs: 90, score: 1 }), + makeActivity({ exerciseType: "sudoku", description: "Completed medium Sudoku in 200s", durationSecs: 200, score: 1 }), + ]); + const res = await GET(makeRequest()); + const records = ((await json(res)).records) as Array>; + expect(records.map((r) => r.difficulty)).toEqual(["easy", "medium", "hard"]); + }); +}); + +// --------------------------------------------------------------------------- +// achievedAt +// --------------------------------------------------------------------------- + +describe("GET /api/stats/personal-bests — achievedAt", () => { + it("achievedAt is an ISO string", async () => { + const date = new Date("2026-03-15T14:30:00Z"); + mockActivityFindMany.mockResolvedValue([ + makeActivity({ exerciseType: "sudoku", description: "Completed easy Sudoku in 90s", durationSecs: 90, score: 1, createdAt: date }), + ]); + const res = await GET(makeRequest()); + const records = ((await json(res)).records) as Array>; + expect(records[0].achievedAt).toBe(date.toISOString()); + }); + + it("achievedAt corresponds to the fastest (first) solve entry", async () => { + const fastDate = new Date("2026-03-20T10:00:00Z"); + const slowDate = new Date("2026-03-10T10:00:00Z"); + mockActivityFindMany.mockResolvedValue([ + // Ordered by durationSecs asc — fastest first + makeActivity({ exerciseType: "sudoku", description: "Completed easy Sudoku in 90s", durationSecs: 90, score: 1, createdAt: fastDate }), + makeActivity({ exerciseType: "sudoku", description: "Completed easy Sudoku in 150s", durationSecs: 150, score: 1, createdAt: slowDate }), + ]); + const res = await GET(makeRequest()); + const records = ((await json(res)).records) as Array>; + expect(records[0].achievedAt).toBe(fastDate.toISOString()); + }); +}); + +// --------------------------------------------------------------------------- +// DB query validation +// --------------------------------------------------------------------------- + +describe("GET /api/stats/personal-bests — DB query", () => { + it("queries only logic puzzle exercise types", async () => { + mockActivityFindMany.mockResolvedValue([]); + await GET(makeRequest()); + expect(mockActivityFindMany).toHaveBeenCalledWith( + expect.objectContaining({ + where: expect.objectContaining({ + exerciseType: expect.objectContaining({ + in: expect.arrayContaining(["sudoku", "sequence", "pattern", "wordscramble", "constraint", "mathequation"]), + }), + }), + }) + ); + }); + + it("filters to userId=1", async () => { + mockActivityFindMany.mockResolvedValue([]); + await GET(makeRequest()); + expect(mockActivityFindMany).toHaveBeenCalledWith( + expect.objectContaining({ + where: expect.objectContaining({ userId: 1 }), + }) + ); + }); + + it("filters durationSecs not null", async () => { + mockActivityFindMany.mockResolvedValue([]); + await GET(makeRequest()); + const callArg = mockActivityFindMany.mock.calls[0][0] as Record; + const where = callArg.where as Record; + expect(where.durationSecs).toEqual({ not: null }); + }); + + it("filters score > 0", async () => { + mockActivityFindMany.mockResolvedValue([]); + await GET(makeRequest()); + const callArg = mockActivityFindMany.mock.calls[0][0] as Record; + const where = callArg.where as Record; + expect(where.score).toEqual({ gt: 0 }); + }); + + it("orders by durationSecs ascending", async () => { + mockActivityFindMany.mockResolvedValue([]); + await GET(makeRequest()); + expect(mockActivityFindMany).toHaveBeenCalledWith( + expect.objectContaining({ + orderBy: { durationSecs: "asc" }, + }) + ); + }); +}); + +// --------------------------------------------------------------------------- +// Error handling +// --------------------------------------------------------------------------- + +describe("GET /api/stats/personal-bests — error handling", () => { + it("propagates DB errors as 500", async () => { + mockActivityFindMany.mockRejectedValue(new Error("DB connection lost")); + const res = await GET(makeRequest()); + expect(res.status).toBe(500); + }); +}); diff --git a/src/app/api/stats/__tests__/route.test.ts b/src/app/api/stats/__tests__/route.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..97675ada311e061dbd00f52c36791ff3104d772b --- /dev/null +++ b/src/app/api/stats/__tests__/route.test.ts @@ -0,0 +1,875 @@ +/** + * Tests for GET /api/stats + * + * Covers: + * - 404 when no user found + * - response shape: windowDays, dailyXp, categoryBreakdown, recentActivities, summary + * - dailyXp: maps dailyLogs to { date, xpEarned, activityCount, goalMet } + * - categoryBreakdown: accumulates totalXp, count, avgScore, totalDuration per category + * - avgScore: averaged correctly over SCORED activities only (null scores excluded from denominator) + * - recentActivities: limited to first 25, maps all fields + * - summary: totalExercises, totalXpEarned, criticalHits, criticalHitRate, goalDaysMet + * - summary: correctSolves and correctSolveRate (score > 0 out of scored exercises) + * - summary: streak and level from user + * - empty data cases + * - DB errors propagate as 500 + * - ?days param: windowDays 7/30/90 (default 30), invalid values fall back to 30 + * - ?days param: DB gte boundary verified for 7-day and 90-day windows + */ + +import { describe, it, expect, vi, beforeEach } from "vitest"; +import { NextRequest } from "next/server"; + +// --------------------------------------------------------------------------- +// Mock prisma +// --------------------------------------------------------------------------- + +const mockUserFindFirst = vi.fn(); +const mockDailyLogFindMany = vi.fn(); +const mockActivityFindMany = vi.fn(); + +vi.mock("@/lib/db", () => ({ + prisma: { + user: { findFirst: (...args: unknown[]) => mockUserFindFirst(...args) }, + dailyLog: { findMany: (...args: unknown[]) => mockDailyLogFindMany(...args) }, + activity: { findMany: (...args: unknown[]) => mockActivityFindMany(...args) }, + }, +})); + +import { GET } from "../route"; + +// --------------------------------------------------------------------------- +// Fixtures +// --------------------------------------------------------------------------- + +const baseUser = { + id: 1, + name: "Player One", + level: 5, + streak: 3, + longestStreak: 10, + categorySkills: [], +}; + +function makeActivity(overrides: Partial<{ + id: number; category: string; exerciseType: string; description: string; + baseXp: number; qualityBonus: number; isCriticalHit: boolean; totalXp: number; + score: number | null; durationSecs: number | null; createdAt: Date; +}> = {}) { + return { + id: 1, + category: "CHESS", + exerciseType: "chess-puzzle", + description: "Solved a puzzle", + baseXp: 30, + qualityBonus: 10, + isCriticalHit: false, + totalXp: 40, + score: 0.8, + durationSecs: 120, + createdAt: new Date("2026-03-24T10:00:00Z"), + ...overrides, + }; +} + +function makeDailyLog(overrides: Partial<{ + date: Date; xpEarned: number; activityCount: number; goalMet: boolean; +}> = {}) { + return { + date: new Date("2026-03-24T00:00:00Z"), + xpEarned: 80, + activityCount: 3, + goalMet: false, + ...overrides, + }; +} + +function makeGet(params?: Record): NextRequest { + const url = new URL("http://localhost/api/stats"); + if (params) { + for (const [k, v] of Object.entries(params)) { + url.searchParams.set(k, v); + } + } + return new NextRequest(url.toString()); +} + +async function json(res: Response): Promise { + return res.json(); +} + +// --------------------------------------------------------------------------- +// Tests +// --------------------------------------------------------------------------- + +describe("GET /api/stats", () => { + beforeEach(() => { + vi.clearAllMocks(); + mockDailyLogFindMany.mockResolvedValue([]); + mockActivityFindMany.mockResolvedValue([]); + }); + + it("returns 404 when no user found", async () => { + mockUserFindFirst.mockResolvedValue(null); + const res = await GET(makeGet()); + expect(res.status).toBe(404); + }); + + it("returns 200 with full response shape", async () => { + mockUserFindFirst.mockResolvedValue(baseUser); + + const res = await GET(makeGet()); + expect(res.status).toBe(200); + + const body = await json(res) as Record; + expect(body).toHaveProperty("windowDays"); + expect(body).toHaveProperty("dailyXp"); + expect(body).toHaveProperty("categoryBreakdown"); + expect(body).toHaveProperty("recentActivities"); + expect(body).toHaveProperty("summary"); + }); + + it("maps dailyXp from logs", async () => { + mockUserFindFirst.mockResolvedValue(baseUser); + mockDailyLogFindMany.mockResolvedValue([ + makeDailyLog({ xpEarned: 100, activityCount: 4, goalMet: true }), + makeDailyLog({ date: new Date("2026-03-23T00:00:00Z"), xpEarned: 50, activityCount: 2, goalMet: false }), + ]); + + const res = await GET(makeGet()); + const body = await json(res) as Record; + const dailyXp = body.dailyXp as Array>; + + expect(dailyXp).toHaveLength(2); + expect(dailyXp[0]).toMatchObject({ xpEarned: 100, activityCount: 4, goalMet: true }); + expect(dailyXp[1]).toMatchObject({ xpEarned: 50, activityCount: 2, goalMet: false }); + expect(dailyXp[0]).toHaveProperty("date"); + }); + + it("builds categoryBreakdown accumulating XP and count", async () => { + mockUserFindFirst.mockResolvedValue(baseUser); + mockActivityFindMany.mockResolvedValue([ + makeActivity({ id: 1, category: "CHESS", totalXp: 40, score: 0.8, durationSecs: 120 }), + makeActivity({ id: 2, category: "CHESS", totalXp: 30, score: 0.6, durationSecs: 90 }), + makeActivity({ id: 3, category: "FEYNMAN", totalXp: 50, score: 1.0, durationSecs: 300 }), + ]); + + const res = await GET(makeGet()); + const body = await json(res) as Record; + const breakdown = body.categoryBreakdown as Record>; + + expect(breakdown.CHESS.totalXp).toBe(70); + expect(breakdown.CHESS.count).toBe(2); + expect(breakdown.CHESS.totalDuration).toBe(210); + expect(breakdown.FEYNMAN.totalXp).toBe(50); + expect(breakdown.FEYNMAN.count).toBe(1); + }); + + it("computes avgScore as mean of non-null scores", async () => { + mockUserFindFirst.mockResolvedValue(baseUser); + mockActivityFindMany.mockResolvedValue([ + makeActivity({ id: 1, category: "CHESS", score: 0.8 }), + makeActivity({ id: 2, category: "CHESS", score: 0.6 }), + ]); + + const res = await GET(makeGet()); + const body = await json(res) as Record; + const breakdown = body.categoryBreakdown as Record>; + + // (0.8 + 0.6) / 2 = 0.7, rounded to 2dp + expect(breakdown.CHESS.avgScore).toBe(0.7); + }); + + it("ignores null scores in avgScore denominator — divides by scored count only", async () => { + mockUserFindFirst.mockResolvedValue(baseUser); + mockActivityFindMany.mockResolvedValue([ + makeActivity({ id: 1, category: "CHESS", score: 0.8 }), + makeActivity({ id: 2, category: "CHESS", score: null }), + ]); + + const res = await GET(makeGet()); + const body = await json(res) as Record; + const breakdown = body.categoryBreakdown as Record>; + + // 1 scored activity with score=0.8 → avgScore = 0.8/1 = 0.8 (not 0.8/2 = 0.4) + expect(breakdown.CHESS.avgScore).toBe(0.8); + }); + + it("returns avgScore 0 when no scored activities in a category", async () => { + mockUserFindFirst.mockResolvedValue(baseUser); + mockActivityFindMany.mockResolvedValue([ + makeActivity({ id: 1, category: "CHESS", score: null }), + makeActivity({ id: 2, category: "CHESS", score: null }), + ]); + + const res = await GET(makeGet()); + const body = await json(res) as Record; + const breakdown = body.categoryBreakdown as Record>; + + expect(breakdown.CHESS.avgScore).toBe(0); + }); + + it("limits recentActivities to 25", async () => { + mockUserFindFirst.mockResolvedValue(baseUser); + const activities = Array.from({ length: 30 }, (_, i) => + makeActivity({ id: i + 1 }) + ); + mockActivityFindMany.mockResolvedValue(activities); + + const res = await GET(makeGet()); + const body = await json(res) as Record; + const recent = body.recentActivities as unknown[]; + expect(recent).toHaveLength(25); + }); + + it("maps all recentActivity fields", async () => { + mockUserFindFirst.mockResolvedValue(baseUser); + mockActivityFindMany.mockResolvedValue([ + makeActivity({ id: 42, category: "FEYNMAN", exerciseType: "explain", description: "Black holes", baseXp: 30, qualityBonus: 10, isCriticalHit: true, totalXp: 80, score: 0.9, durationSecs: 180 }), + ]); + + const res = await GET(makeGet()); + const body = await json(res) as Record; + const recent = body.recentActivities as Array>; + + expect(recent[0]).toMatchObject({ + id: 42, + category: "FEYNMAN", + exerciseType: "explain", + description: "Black holes", + baseXp: 30, + qualityBonus: 10, + isCriticalHit: true, + totalXp: 80, + score: 0.9, + durationSecs: 180, + }); + expect(recent[0]).toHaveProperty("createdAt"); + }); + + it("counts totalExercises in summary", async () => { + mockUserFindFirst.mockResolvedValue(baseUser); + mockActivityFindMany.mockResolvedValue([ + makeActivity({ id: 1 }), + makeActivity({ id: 2 }), + makeActivity({ id: 3 }), + ]); + + const res = await GET(makeGet()); + const body = await json(res) as Record; + const summary = body.summary as Record; + expect(summary.totalExercises).toBe(3); + }); + + it("sums totalXpEarned in summary", async () => { + mockUserFindFirst.mockResolvedValue(baseUser); + mockActivityFindMany.mockResolvedValue([ + makeActivity({ id: 1, totalXp: 40 }), + makeActivity({ id: 2, totalXp: 60 }), + ]); + + const res = await GET(makeGet()); + const body = await json(res) as Record; + const summary = body.summary as Record; + expect(summary.totalXpEarned).toBe(100); + }); + + it("counts criticalHits in summary", async () => { + mockUserFindFirst.mockResolvedValue(baseUser); + mockActivityFindMany.mockResolvedValue([ + makeActivity({ id: 1, isCriticalHit: true }), + makeActivity({ id: 2, isCriticalHit: false }), + makeActivity({ id: 3, isCriticalHit: true }), + ]); + + const res = await GET(makeGet()); + const body = await json(res) as Record; + const summary = body.summary as Record; + expect(summary.criticalHits).toBe(2); + }); + + it("computes criticalHitRate as percentage", async () => { + mockUserFindFirst.mockResolvedValue(baseUser); + mockActivityFindMany.mockResolvedValue([ + makeActivity({ id: 1, isCriticalHit: true }), + makeActivity({ id: 2, isCriticalHit: false }), + makeActivity({ id: 3, isCriticalHit: false }), + makeActivity({ id: 4, isCriticalHit: false }), + ]); + + const res = await GET(makeGet()); + const body = await json(res) as Record; + const summary = body.summary as Record; + // 1/4 = 25.0 + expect(summary.criticalHitRate).toBe(25); + }); + + it("returns criticalHitRate 0 when no activities", async () => { + mockUserFindFirst.mockResolvedValue(baseUser); + mockActivityFindMany.mockResolvedValue([]); + + const res = await GET(makeGet()); + const body = await json(res) as Record; + const summary = body.summary as Record; + expect(summary.criticalHitRate).toBe(0); + }); + + // ── Correct Solve Rate ──────────────────────────────────────────────────── + + it("counts correctSolves as activities with score > 0", async () => { + mockUserFindFirst.mockResolvedValue(baseUser); + mockActivityFindMany.mockResolvedValue([ + makeActivity({ id: 1, score: 0.8 }), + makeActivity({ id: 2, score: 0.0 }), // zero score = incorrect + makeActivity({ id: 3, score: 1.0 }), + makeActivity({ id: 4, score: null }), // no score = unscored + ]); + + const res = await GET(makeGet()); + const body = await json(res) as Record; + const summary = body.summary as Record; + // Only id=1 (0.8) and id=3 (1.0) are correct solves + expect(summary.correctSolves).toBe(2); + }); + + it("computes correctSolveRate as percentage of scored exercises", async () => { + mockUserFindFirst.mockResolvedValue(baseUser); + mockActivityFindMany.mockResolvedValue([ + makeActivity({ id: 1, score: 1.0 }), // correct + makeActivity({ id: 2, score: 0.8 }), // correct + makeActivity({ id: 3, score: 0.0 }), // incorrect + makeActivity({ id: 4, score: null }), // unscored — excluded from denominator + ]); + + const res = await GET(makeGet()); + const body = await json(res) as Record; + const summary = body.summary as Record; + // 2 correct out of 3 scored = 66.7% + expect(summary.correctSolveRate).toBe(66.7); + }); + + it("returns correctSolveRate 100 when all scored exercises correct", async () => { + mockUserFindFirst.mockResolvedValue(baseUser); + mockActivityFindMany.mockResolvedValue([ + makeActivity({ id: 1, score: 0.9 }), + makeActivity({ id: 2, score: 1.0 }), + ]); + + const res = await GET(makeGet()); + const body = await json(res) as Record; + const summary = body.summary as Record; + expect(summary.correctSolveRate).toBe(100); + }); + + it("returns correctSolveRate 0 when no scored activities", async () => { + mockUserFindFirst.mockResolvedValue(baseUser); + mockActivityFindMany.mockResolvedValue([ + makeActivity({ id: 1, score: null }), + makeActivity({ id: 2, score: null }), + ]); + + const res = await GET(makeGet()); + const body = await json(res) as Record; + const summary = body.summary as Record; + expect(summary.correctSolveRate).toBe(0); + expect(summary.correctSolves).toBe(0); + }); + + it("returns correctSolveRate 0 when no activities at all", async () => { + mockUserFindFirst.mockResolvedValue(baseUser); + mockActivityFindMany.mockResolvedValue([]); + + const res = await GET(makeGet()); + const body = await json(res) as Record; + const summary = body.summary as Record; + expect(summary.correctSolveRate).toBe(0); + }); + + it("summary includes correctSolves and correctSolveRate fields", async () => { + mockUserFindFirst.mockResolvedValue(baseUser); + mockActivityFindMany.mockResolvedValue([makeActivity({ id: 1, score: 0.7 })]); + + const res = await GET(makeGet()); + const body = await json(res) as Record; + const summary = body.summary as Record; + expect(summary).toHaveProperty("correctSolves"); + expect(summary).toHaveProperty("correctSolveRate"); + }); + + it("counts goalDaysMet from daily logs", async () => { + mockUserFindFirst.mockResolvedValue(baseUser); + mockDailyLogFindMany.mockResolvedValue([ + makeDailyLog({ goalMet: true }), + makeDailyLog({ goalMet: false }), + makeDailyLog({ goalMet: true }), + ]); + + const res = await GET(makeGet()); + const body = await json(res) as Record; + const summary = body.summary as Record; + expect(summary.goalDaysMet).toBe(2); + }); + + it("includes streak and longestStreak from user", async () => { + mockUserFindFirst.mockResolvedValue({ ...baseUser, streak: 7, longestStreak: 14 }); + + const res = await GET(makeGet()); + const body = await json(res) as Record; + const summary = body.summary as Record; + expect(summary.currentStreak).toBe(7); + expect(summary.longestStreak).toBe(14); + }); + + it("includes user level in summary", async () => { + mockUserFindFirst.mockResolvedValue({ ...baseUser, level: 8 }); + + const res = await GET(makeGet()); + const body = await json(res) as Record; + const summary = body.summary as Record; + expect(summary.level).toBe(8); + }); + + it("handles null durationSecs gracefully", async () => { + mockUserFindFirst.mockResolvedValue(baseUser); + mockActivityFindMany.mockResolvedValue([ + makeActivity({ id: 1, durationSecs: null }), + makeActivity({ id: 2, durationSecs: 60 }), + ]); + + const res = await GET(makeGet()); + const body = await json(res) as Record; + const summary = body.summary as Record; + expect(summary.totalDuration).toBe(60); + }); + + it("returns empty collections when no activity", async () => { + mockUserFindFirst.mockResolvedValue(baseUser); + mockActivityFindMany.mockResolvedValue([]); + mockDailyLogFindMany.mockResolvedValue([]); + + const res = await GET(makeGet()); + const body = await json(res) as Record; + expect(body.dailyXp).toEqual([]); + expect(body.categoryBreakdown).toEqual({}); + expect(body.recentActivities).toEqual([]); + }); + + it("queries daily logs from last 30 days ordered asc", async () => { + mockUserFindFirst.mockResolvedValue(baseUser); + + await GET(makeGet()); + + const call = mockDailyLogFindMany.mock.calls[0][0]; + expect(call).toMatchObject({ + where: { userId: 1, date: { gte: expect.any(Date) } }, + orderBy: { date: "asc" }, + }); + // gte is UTC midnight ~30 days ago; tolerance ±24h for midnight truncation + const gteDate: Date = call.where.date.gte; + const nowMs = Date.now(); + const diffMs = nowMs - gteDate.getTime(); + const thirtyDaysMs = 30 * 24 * 60 * 60 * 1000; + const oneDayMs = 24 * 60 * 60 * 1000; + expect(diffMs).toBeGreaterThanOrEqual(thirtyDaysMs - oneDayMs); + expect(diffMs).toBeLessThanOrEqual(thirtyDaysMs + oneDayMs); + }); + + it("propagates DB errors as 500", async () => { + mockUserFindFirst.mockRejectedValue(new Error("DB down")); + const res = await GET(makeGet()); + expect(res.status).toBe(500); + }); +}); + +// --------------------------------------------------------------------------- +// ?days query parameter +// --------------------------------------------------------------------------- + +describe("GET /api/stats — ?days query param", () => { + beforeEach(() => { + vi.clearAllMocks(); + mockUserFindFirst.mockResolvedValue(baseUser); + mockDailyLogFindMany.mockResolvedValue([]); + mockActivityFindMany.mockResolvedValue([]); + }); + + it("defaults to windowDays=30 when ?days is omitted", async () => { + const res = await GET(makeGet()); + const body = await json(res) as Record; + expect(body.windowDays).toBe(30); + }); + + it("returns windowDays=7 when ?days=7", async () => { + const res = await GET(makeGet({ days: "7" })); + const body = await json(res) as Record; + expect(body.windowDays).toBe(7); + }); + + it("returns windowDays=30 when ?days=30", async () => { + const res = await GET(makeGet({ days: "30" })); + const body = await json(res) as Record; + expect(body.windowDays).toBe(30); + }); + + it("returns windowDays=90 when ?days=90", async () => { + const res = await GET(makeGet({ days: "90" })); + const body = await json(res) as Record; + expect(body.windowDays).toBe(90); + }); + + it("falls back to windowDays=30 for invalid ?days value (e.g. 14)", async () => { + const res = await GET(makeGet({ days: "14" })); + const body = await json(res) as Record; + expect(body.windowDays).toBe(30); + }); + + it("falls back to windowDays=30 for non-numeric ?days", async () => { + const res = await GET(makeGet({ days: "week" })); + const body = await json(res) as Record; + expect(body.windowDays).toBe(30); + }); + + it("queries daily logs with gte set to UTC midnight ~7 days ago when ?days=7", async () => { + await GET(makeGet({ days: "7" })); + + const call = mockDailyLogFindMany.mock.calls[0][0]; + const gteDate: Date = call.where.date.gte; + // The route zeroes time to UTC midnight; gte is at midnight of (today - 7 days). + // Tolerance: ±24h accounts for the midnight truncation at any time of day. + expect(gteDate).toBeInstanceOf(Date); + const nowMs = Date.now(); + const diffMs = nowMs - gteDate.getTime(); + const sevenDaysMs = 7 * 24 * 60 * 60 * 1000; + const oneDayMs = 24 * 60 * 60 * 1000; + expect(diffMs).toBeGreaterThanOrEqual(sevenDaysMs - oneDayMs); + expect(diffMs).toBeLessThanOrEqual(sevenDaysMs + oneDayMs); + }); + + it("queries daily logs with gte set to UTC midnight ~90 days ago when ?days=90", async () => { + await GET(makeGet({ days: "90" })); + + const call = mockDailyLogFindMany.mock.calls[0][0]; + const gteDate: Date = call.where.date.gte; + expect(gteDate).toBeInstanceOf(Date); + const nowMs = Date.now(); + const diffMs = nowMs - gteDate.getTime(); + const ninetyDaysMs = 90 * 24 * 60 * 60 * 1000; + const oneDayMs = 24 * 60 * 60 * 1000; + expect(diffMs).toBeGreaterThanOrEqual(ninetyDaysMs - oneDayMs); + expect(diffMs).toBeLessThanOrEqual(ninetyDaysMs + oneDayMs); + }); + + it("response includes windowDays alongside dailyXp, summary, etc.", async () => { + const res = await GET(makeGet({ days: "7" })); + const body = await json(res) as Record; + expect(body).toHaveProperty("windowDays", 7); + expect(body).toHaveProperty("dailyXp"); + expect(body).toHaveProperty("summary"); + expect(body).toHaveProperty("categoryBreakdown"); + expect(body).toHaveProperty("recentActivities"); + }); +}); + +// --------------------------------------------------------------------------- +// Activity pagination (?activityOffset / ?activityLimit) +// --------------------------------------------------------------------------- + +describe("GET /api/stats — activity pagination", () => { + // Build a pool of 60 activities with sequential IDs + const POOL = Array.from({ length: 60 }, (_, i) => + makeActivity({ id: i + 1, totalXp: 10 + i, createdAt: new Date(Date.now() - i * 1000) }), + ); + + beforeEach(() => { + vi.clearAllMocks(); + mockUserFindFirst.mockResolvedValue(baseUser); + mockDailyLogFindMany.mockResolvedValue([]); + mockActivityFindMany.mockResolvedValue(POOL); + }); + + it("returns activityTotal equal to all activities in the pool", async () => { + const res = await GET(makeGet()); + const body = await json(res) as Record; + expect(body.activityTotal).toBe(60); + }); + + it("returns first 25 activities by default (no offset/limit params)", async () => { + const res = await GET(makeGet()); + const body = await json(res) as Record; + const activities = body.recentActivities as Array>; + expect(activities).toHaveLength(25); + expect(activities[0].id).toBe(1); // most recent (index 0 in pool) + expect(activities[24].id).toBe(25); + }); + + it("respects activityOffset — skips the first N activities", async () => { + const res = await GET(makeGet({ activityOffset: "25" })); + const body = await json(res) as Record; + const activities = body.recentActivities as Array>; + expect(activities).toHaveLength(25); + expect(activities[0].id).toBe(26); + expect(activities[24].id).toBe(50); + }); + + it("respects activityLimit — returns fewer activities than default", async () => { + const res = await GET(makeGet({ activityLimit: "10" })); + const body = await json(res) as Record; + const activities = body.recentActivities as Array>; + expect(activities).toHaveLength(10); + }); + + it("respects both activityOffset and activityLimit together", async () => { + const res = await GET(makeGet({ activityOffset: "10", activityLimit: "5" })); + const body = await json(res) as Record; + const activities = body.recentActivities as Array>; + expect(activities).toHaveLength(5); + expect(activities[0].id).toBe(11); + expect(activities[4].id).toBe(15); + }); + + it("caps activityLimit at MAX (50)", async () => { + const res = await GET(makeGet({ activityLimit: "9999" })); + const body = await json(res) as Record; + const activities = body.recentActivities as Array>; + expect(activities).toHaveLength(50); // pool has 60, but cap is 50 + }); + + it("returns fewer than limit when near end of pool", async () => { + const res = await GET(makeGet({ activityOffset: "55", activityLimit: "25" })); + const body = await json(res) as Record; + const activities = body.recentActivities as Array>; + expect(activities).toHaveLength(5); // only 5 left (55..59) + }); + + it("returns empty array when offset equals pool size", async () => { + const res = await GET(makeGet({ activityOffset: "60" })); + const body = await json(res) as Record; + const activities = body.recentActivities as Array>; + expect(activities).toHaveLength(0); + }); + + it("returns empty array when offset exceeds pool size", async () => { + const res = await GET(makeGet({ activityOffset: "100" })); + const body = await json(res) as Record; + const activities = body.recentActivities as Array>; + expect(activities).toHaveLength(0); + }); + + it("treats invalid activityOffset as 0", async () => { + const res = await GET(makeGet({ activityOffset: "abc" })); + const body = await json(res) as Record; + const activities = body.recentActivities as Array>; + expect(activities).toHaveLength(25); + expect((activities[0] as Record).id).toBe(1); + }); + + it("treats invalid activityLimit as default (25)", async () => { + const res = await GET(makeGet({ activityLimit: "banana" })); + const body = await json(res) as Record; + const activities = body.recentActivities as Array>; + expect(activities).toHaveLength(25); + }); + + it("treats negative activityOffset as 0", async () => { + const res = await GET(makeGet({ activityOffset: "-10" })); + const body = await json(res) as Record; + const activities = body.recentActivities as Array>; + expect(activities[0].id).toBe(1); + }); + + it("activityTotal is stable regardless of pagination params", async () => { + const [r1, r2] = await Promise.all([ + GET(makeGet({ activityOffset: "0", activityLimit: "10" })), + GET(makeGet({ activityOffset: "50", activityLimit: "10" })), + ]); + const b1 = await json(r1) as Record; + const b2 = await json(r2) as Record; + expect(b1.activityTotal).toBe(60); + expect(b2.activityTotal).toBe(60); + }); + + it("response always contains activityTotal field", async () => { + const res = await GET(makeGet()); + const body = await json(res) as Record; + expect(body).toHaveProperty("activityTotal"); + expect(typeof body.activityTotal).toBe("number"); + }); +}); + +// --------------------------------------------------------------------------- +// ?activityCategory filter +// --------------------------------------------------------------------------- + +describe("GET /api/stats — ?activityCategory filter", () => { + const CHESS_ACTIVITY = makeActivity({ + id: 1, + category: "chess", + exerciseType: "chess-puzzle", + totalXp: 40, + }); + const READING_ACTIVITY = makeActivity({ + id: 2, + category: "reading", + exerciseType: "comprehension", + totalXp: 50, + }); + const FEYNMAN_ACTIVITY = makeActivity({ + id: 3, + category: "feynman", + exerciseType: "explain", + totalXp: 60, + }); + + const MIXED_POOL = [CHESS_ACTIVITY, READING_ACTIVITY, FEYNMAN_ACTIVITY]; + + beforeEach(() => { + vi.clearAllMocks(); + mockUserFindFirst.mockResolvedValue(baseUser); + mockDailyLogFindMany.mockResolvedValue([]); + mockActivityFindMany.mockResolvedValue(MIXED_POOL); + }); + + it("returns only chess activities when activityCategory=chess", async () => { + const res = await GET(makeGet({ activityCategory: "chess" })); + const body = await json(res) as Record; + const activities = body.recentActivities as Array>; + expect(activities).toHaveLength(1); + expect(activities[0].id).toBe(1); + expect(activities[0].category).toBe("chess"); + }); + + it("returns only reading activities when activityCategory=reading", async () => { + const res = await GET(makeGet({ activityCategory: "reading" })); + const body = await json(res) as Record; + const activities = body.recentActivities as Array>; + expect(activities).toHaveLength(1); + expect(activities[0].category).toBe("reading"); + }); + + it("returns all activities when activityCategory=all", async () => { + const res = await GET(makeGet({ activityCategory: "all" })); + const body = await json(res) as Record; + const activities = body.recentActivities as Array>; + expect(activities).toHaveLength(3); + }); + + it("returns all activities when ?activityCategory is omitted", async () => { + const res = await GET(makeGet()); + const body = await json(res) as Record; + const activities = body.recentActivities as Array>; + expect(activities).toHaveLength(3); + }); + + it("treats an invalid category value as 'all' (returns all activities)", async () => { + const res = await GET(makeGet({ activityCategory: "basketweaving" })); + const body = await json(res) as Record; + const activities = body.recentActivities as Array>; + expect(activities).toHaveLength(3); + }); + + it("activityTotal reflects the filtered count, not the full pool", async () => { + const res = await GET(makeGet({ activityCategory: "chess" })); + const body = await json(res) as Record; + expect(body.activityTotal).toBe(1); + }); + + it("activityTotal is full pool size when no filter", async () => { + const res = await GET(makeGet()); + const body = await json(res) as Record; + expect(body.activityTotal).toBe(3); + }); + + it("activityCategory field in response is the active category when filtered", async () => { + const res = await GET(makeGet({ activityCategory: "feynman" })); + const body = await json(res) as Record; + expect(body.activityCategory).toBe("feynman"); + }); + + it("activityCategory field in response is null when no filter", async () => { + const res = await GET(makeGet()); + const body = await json(res) as Record; + expect(body.activityCategory).toBeNull(); + }); + + it("activityCategory field in response is null when activityCategory=all", async () => { + const res = await GET(makeGet({ activityCategory: "all" })); + const body = await json(res) as Record; + expect(body.activityCategory).toBeNull(); + }); + + it("activityCategory field in response is null for invalid category", async () => { + const res = await GET(makeGet({ activityCategory: "invalid" })); + const body = await json(res) as Record; + expect(body.activityCategory).toBeNull(); + }); + + it("category breakdown is not affected by activityCategory filter (uses full pool)", async () => { + const res = await GET(makeGet({ activityCategory: "chess" })); + const body = await json(res) as Record; + const breakdown = body.categoryBreakdown as Record>; + // All 3 categories still appear in breakdown + expect(breakdown).toHaveProperty("chess"); + expect(breakdown).toHaveProperty("reading"); + expect(breakdown).toHaveProperty("feynman"); + }); + + it("summary stats are not affected by activityCategory filter (uses full pool)", async () => { + const res = await GET(makeGet({ activityCategory: "chess" })); + const body = await json(res) as Record; + const summary = body.summary as Record; + // All 3 activities counted in summary despite chess-only filter + expect(summary.totalExercises).toBe(3); + }); + + it("category filter is case-insensitive (DB category stored as lowercase)", async () => { + // Activity has category "chess" (lowercase), param is "chess" — should match + const res = await GET(makeGet({ activityCategory: "chess" })); + const body = await json(res) as Record; + const activities = body.recentActivities as Array>; + expect(activities).toHaveLength(1); + }); + + it("filter works with hyphenated category (critical-thinking)", async () => { + const ctActivity = makeActivity({ + id: 10, + category: "critical-thinking", + exerciseType: "flaw-finder", + totalXp: 70, + }); + mockActivityFindMany.mockResolvedValue([...MIXED_POOL, ctActivity]); + + const res = await GET(makeGet({ activityCategory: "critical-thinking" })); + const body = await json(res) as Record; + const activities = body.recentActivities as Array>; + expect(activities).toHaveLength(1); + expect(activities[0].id).toBe(10); + }); + + it("returns empty activities (not 404) when filter matches no activities", async () => { + const res = await GET(makeGet({ activityCategory: "quests" })); + expect(res.status).toBe(200); + const body = await json(res) as Record; + const activities = body.recentActivities as Array>; + expect(activities).toHaveLength(0); + expect(body.activityTotal).toBe(0); + }); + + it("pagination still works within a filtered set", async () => { + // Build 5 chess activities + 2 reading + const pool = [ + ...Array.from({ length: 5 }, (_, i) => + makeActivity({ id: i + 1, category: "chess", totalXp: 10 }), + ), + makeActivity({ id: 10, category: "reading", totalXp: 10 }), + makeActivity({ id: 11, category: "reading", totalXp: 10 }), + ]; + mockActivityFindMany.mockResolvedValue(pool); + + const res = await GET(makeGet({ activityCategory: "chess", activityOffset: "2", activityLimit: "2" })); + const body = await json(res) as Record; + const activities = body.recentActivities as Array>; + expect(activities).toHaveLength(2); + expect(activities[0].id).toBe(3); // 3rd chess activity (0-indexed: [2]) + expect(body.activityTotal).toBe(5); // only chess total + }); +}); diff --git a/src/app/api/stats/achievements/route.ts b/src/app/api/stats/achievements/route.ts new file mode 100644 index 0000000000000000000000000000000000000000..5161ce5de20400d356ee6a7e77b5cad493795728 --- /dev/null +++ b/src/app/api/stats/achievements/route.ts @@ -0,0 +1,71 @@ +import { NextResponse } from "next/server"; +import { prisma } from "@/lib/db"; +import { withApiError } from "@/lib/api-error"; +import { computeAchievements, achievementSummary } from "@/lib/achievements"; + +/** + * GET /api/stats/achievements + * + * Returns the full achievement list with earned/progress status for user 1, + * plus a summary breakdown by tier. + */ +export const GET = withApiError(async () => { + const user = await prisma.user.findFirst({ + where: { id: 1 }, + select: { + level: true, + totalXp: true, + streak: true, + longestStreak: true, + createdAt: true, + }, + }); + + if (!user) { + return NextResponse.json( + { error: "No user found", status: 404 }, + { status: 404 } + ); + } + + const [categorySkills, activities, dailyLogs, unlocks] = await Promise.all([ + prisma.categorySkill.findMany({ + where: { userId: 1 }, + select: { category: true, level: true, totalXp: true }, + }), + prisma.activity.findMany({ + where: { userId: 1 }, + select: { + category: true, + exerciseType: true, + isCriticalHit: true, + score: true, + durationSecs: true, + createdAt: true, + metadata: true, + }, + orderBy: { createdAt: "asc" }, + }), + prisma.dailyLog.findMany({ + where: { userId: 1 }, + select: { date: true, goalMet: true, activityCount: true }, + }), + prisma.unlock.findMany({ + where: { userId: 1 }, + select: { unlockedAt: true }, + orderBy: { unlockedAt: "asc" }, + }), + ]); + + const achievements = computeAchievements({ + user, + categorySkills, + activities, + dailyLogs, + unlocks, + }); + + const summary = achievementSummary(achievements); + + return NextResponse.json({ achievements, summary }); +}); diff --git a/src/app/api/stats/best-scores/__tests__/route.test.ts b/src/app/api/stats/best-scores/__tests__/route.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..59345cc3fcae248b558514e4a7c609e92b44441d --- /dev/null +++ b/src/app/api/stats/best-scores/__tests__/route.test.ts @@ -0,0 +1,227 @@ +import { describe, it, expect, vi, beforeEach } from "vitest"; +import { NextRequest } from "next/server"; + +// --------------------------------------------------------------------------- +// DB mock +// --------------------------------------------------------------------------- + +const mockActivityFindMany = vi.fn(); + +vi.mock("@/lib/db", () => ({ + prisma: { + activity: { findMany: mockActivityFindMany }, + }, +})); + +// --------------------------------------------------------------------------- +// Import route under test AFTER mocking +// --------------------------------------------------------------------------- + +const { GET } = await import("../route"); + +// --------------------------------------------------------------------------- +// Helpers +// --------------------------------------------------------------------------- + +function makeActivity( + category: string, + exerciseType: string, + score: number | null, + createdAt = new Date("2026-03-10T10:00:00Z"), +) { + return { category, exerciseType, score, totalXp: 50, createdAt }; +} + +function makeRequest() { + return new NextRequest("http://localhost/api/stats/best-scores"); +} + +async function callGET() { + const res = await GET(makeRequest()); + return { res, body: await res.json() }; +} + +// --------------------------------------------------------------------------- +// Tests +// --------------------------------------------------------------------------- + +describe("GET /api/stats/best-scores — DB query", () => { + beforeEach(() => { + mockActivityFindMany.mockResolvedValue([]); + }); + + it("queries activities for userId=1", async () => { + await callGET(); + expect(mockActivityFindMany).toHaveBeenCalledWith( + expect.objectContaining({ + where: { userId: 1 }, + }), + ); + }); + + it("selects only needed fields", async () => { + await callGET(); + const call = mockActivityFindMany.mock.calls[0][0]; + expect(call.select).toMatchObject({ + category: true, + exerciseType: true, + score: true, + totalXp: true, + createdAt: true, + }); + }); + + it("orders by createdAt ascending", async () => { + await callGET(); + const call = mockActivityFindMany.mock.calls[0][0]; + expect(call.orderBy).toEqual({ createdAt: "asc" }); + }); + + it("does NOT filter by score in the DB query (includes unscored)", async () => { + await callGET(); + const call = mockActivityFindMany.mock.calls[0][0]; + expect(call.where?.score).toBeUndefined(); + }); +}); + +describe("GET /api/stats/best-scores — response shape", () => { + beforeEach(() => { + mockActivityFindMany.mockResolvedValue([]); + }); + + it("returns 200", async () => { + const { res } = await callGET(); + expect(res.status).toBe(200); + }); + + it("response has byExerciseType and byCategory keys", async () => { + const { body } = await callGET(); + expect(body).toHaveProperty("byExerciseType"); + expect(body).toHaveProperty("byCategory"); + expect(Array.isArray(body.byExerciseType)).toBe(true); + expect(Array.isArray(body.byCategory)).toBe(true); + }); + + it("byCategory always has 7 entries (one per category)", async () => { + const { body } = await callGET(); + expect(body.byCategory).toHaveLength(7); + }); + + it("byExerciseType is empty when no activities", async () => { + const { body } = await callGET(); + expect(body.byExerciseType).toHaveLength(0); + }); +}); + +describe("GET /api/stats/best-scores — with activity data", () => { + it("returns best score for a chess puzzle", async () => { + mockActivityFindMany.mockResolvedValue([ + makeActivity("chess", "puzzle", 0.8, new Date("2026-03-01T10:00:00Z")), + makeActivity("chess", "puzzle", 0.95, new Date("2026-03-02T10:00:00Z")), + ]); + const { body } = await callGET(); + const entry = body.byExerciseType.find( + (e: { category: string; exerciseType: string }) => + e.category === "chess" && e.exerciseType === "puzzle", + ); + expect(entry).toBeDefined(); + expect(entry.bestScore).toBe(0.95); + expect(entry.achievedAt).toBe("2026-03-02T10:00:00.000Z"); + }); + + it("includes all three critical thinking exercise types", async () => { + mockActivityFindMany.mockResolvedValue([ + makeActivity("critical-thinking", "flaw-finder", 0.7), + makeActivity("critical-thinking", "steelman", 0.8), + makeActivity("critical-thinking", "devils-advocate", 0.6), + ]); + const { body } = await callGET(); + const ctEntries = body.byExerciseType.filter( + (e: { category: string }) => e.category === "critical-thinking", + ); + expect(ctEntries).toHaveLength(3); + const types = ctEntries.map((e: { exerciseType: string }) => e.exerciseType).sort(); + expect(types).toEqual(["devils-advocate", "flaw-finder", "steelman"]); + }); + + it("byCategory reflects best score across all exercise types", async () => { + mockActivityFindMany.mockResolvedValue([ + makeActivity("critical-thinking", "flaw-finder", 0.5), + makeActivity("critical-thinking", "steelman", 0.95), + ]); + const { body } = await callGET(); + const ctCat = body.byCategory.find( + (c: { category: string }) => c.category === "critical-thinking", + ); + expect(ctCat.bestScore).toBe(0.95); + }); + + it("unscored activities increment attemptCount but not scoredCount", async () => { + mockActivityFindMany.mockResolvedValue([ + makeActivity("feynman", "explain", 0.7), + makeActivity("feynman", "explain", null), + makeActivity("feynman", "explain", null), + ]); + const { body } = await callGET(); + const entry = body.byExerciseType.find( + (e: { category: string; exerciseType: string }) => + e.category === "feynman" && e.exerciseType === "explain", + ); + expect(entry.attemptCount).toBe(3); + expect(entry.scoredCount).toBe(1); + }); + + it("all-unscored activities produce empty byExerciseType", async () => { + mockActivityFindMany.mockResolvedValue([ + makeActivity("chess", "puzzle", null), + makeActivity("chess", "puzzle", null), + ]); + const { body } = await callGET(); + expect(body.byExerciseType).toHaveLength(0); + }); + + it("byCategory attemptCount reflects all attempts including unscored", async () => { + mockActivityFindMany.mockResolvedValue([ + makeActivity("reading", "comprehension", 0.7), + makeActivity("reading", "comprehension", null), + ]); + const { body } = await callGET(); + const readingCat = body.byCategory.find( + (c: { category: string }) => c.category === "reading", + ); + expect(readingCat.attemptCount).toBe(2); + }); + + it("avgScore is correctly computed across multiple scored activities", async () => { + mockActivityFindMany.mockResolvedValue([ + makeActivity("quests", "quest", 0.6), + makeActivity("quests", "quest", 0.8), + makeActivity("quests", "quest", 1.0), + ]); + const { body } = await callGET(); + const questCat = body.byCategory.find( + (c: { category: string }) => c.category === "quests", + ); + // (0.6 + 0.8 + 1.0) / 3 = 0.8 + expect(questCat.avgScore).toBe(0.8); + }); + + it("bestScore in byCategory entry uses 4dp precision", async () => { + mockActivityFindMany.mockResolvedValue([ + makeActivity("logic", "sudoku", 2 / 3), + ]); + const { body } = await callGET(); + const entry = body.byExerciseType.find( + (e: { category: string }) => e.category === "logic", + ); + expect(entry.bestScore).toBe(0.6667); + }); +}); + +describe("GET /api/stats/best-scores — error handling", () => { + it("returns 500 when DB throws", async () => { + mockActivityFindMany.mockRejectedValue(new Error("DB connection lost")); + const { res } = await callGET(); + expect(res.status).toBe(500); + }); +}); diff --git a/src/app/api/stats/best-scores/route.ts b/src/app/api/stats/best-scores/route.ts new file mode 100644 index 0000000000000000000000000000000000000000..18e9dc8ecad9b978d7a91cdb5305a56555ac0a3b --- /dev/null +++ b/src/app/api/stats/best-scores/route.ts @@ -0,0 +1,59 @@ +/** + * GET /api/stats/best-scores + * + * Returns all-time best quality scores per category and exercise type. + * + * Unlike /api/stats/personal-bests (which tracks Logic Puzzle *speed*), + * this endpoint tracks *quality scores* (0–1) across all 6 exercise + * categories — useful for Feynman, Deep Reading, Critical Thinking, Chess, + * and Skill Quests where quality is the primary performance signal. + * + * Response shape: + * { + * byExerciseType: Array<{ + * category: Category; + * categoryLabel: string; + * exerciseType: string; + * exerciseLabel: string; + * bestScore: number; // 0–1, rounded to 4 dp + * attemptCount: number; // total attempts (including unscored) + * scoredCount: number; // attempts with a non-null score + * achievedAt: string; // ISO timestamp of the best-score activity + * }>; + * byCategory: Array<{ + * category: Category; + * categoryLabel: string; + * bestScore: number; // highest bestScore across all types + * attemptCount: number; + * avgScore: number; // average across all scored activities, 2 dp + * }>; + * } + */ + +import { NextResponse } from "next/server"; +import { prisma } from "@/lib/db"; +import { withApiError } from "@/lib/api-error"; +import { + computeBestScores, + type ActivityForScores, +} from "@/lib/stats/best-scores"; + +export const GET = withApiError(async () => { + // Fetch all activities that have been scored — no time-window filter since + // personal bests are all-time records by definition. + const activities = await prisma.activity.findMany({ + where: { userId: 1 }, + select: { + category: true, + exerciseType: true, + score: true, + totalXp: true, + createdAt: true, + }, + orderBy: { createdAt: "asc" }, // chronological so first-seen is first in array + }); + + const result = computeBestScores(activities as ActivityForScores[]); + + return NextResponse.json(result); +}); diff --git a/src/app/api/stats/personal-bests/route.ts b/src/app/api/stats/personal-bests/route.ts new file mode 100644 index 0000000000000000000000000000000000000000..894e8b52598e1ba05a77824a707bf49781071ee9 --- /dev/null +++ b/src/app/api/stats/personal-bests/route.ts @@ -0,0 +1,134 @@ +import { NextResponse } from "next/server"; +import { prisma } from "@/lib/db"; +import { withApiError } from "@/lib/api-error"; + +/** + * GET /api/stats/personal-bests + * + * Returns all-time personal best solve times for Logic Puzzle categories, + * grouped by exerciseType and difficulty. + * + * Only counts correct solves (score > 0) with a recorded durationSecs. + * + * Response shape: + * { + * records: Array<{ + * exerciseType: string; + * difficulty: "easy" | "medium" | "hard"; + * bestSecs: number; + * solveCount: number; // total correct solves for this type+difficulty + * achievedAt: string; // ISO timestamp of the fastest solve + * }>; + * } + */ + +const LOGIC_EXERCISE_TYPES = [ + "sudoku", + "sequence", + "pattern", + "wordscramble", + "constraint", + "mathequation", +] as const; + +const DIFFICULTIES = ["easy", "medium", "hard"] as const; + +const EXERCISE_LABELS: Record = { + sudoku: "Sudoku", + sequence: "Number Sequence", + pattern: "Pattern Matrix", + wordscramble: "Word Scramble", + constraint: "Constraint Grid", + mathequation: "Math Equation", +}; + +export type PersonalBestRecord = { + exerciseType: string; + exerciseLabel: string; + difficulty: "easy" | "medium" | "hard"; + bestSecs: number; + solveCount: number; + achievedAt: string; +}; + +export type PersonalBestsResponse = { + records: PersonalBestRecord[]; +}; + +export const GET = withApiError(async () => { + // Fetch all correct logic puzzle activities with a duration in one query, + // then process in-memory. Total row count is bounded (6 types × 3 diff × N + // solves) so this is fine for a single-user app. + const activities = await prisma.activity.findMany({ + where: { + userId: 1, + exerciseType: { in: [...LOGIC_EXERCISE_TYPES] }, + durationSecs: { not: null }, + score: { gt: 0 }, + }, + select: { + exerciseType: true, + description: true, + durationSecs: true, + createdAt: true, + }, + orderBy: { durationSecs: "asc" }, + }); + + // Group by exerciseType + difficulty. + // Difficulty is embedded in the activity description as the word + // "easy", "medium", or "hard" — consistent with how submit route sets it. + const bestMap = new Map< + string, // key: `${exerciseType}:${difficulty}` + { bestSecs: number; solveCount: number; achievedAt: Date } + >(); + + for (const act of activities) { + // Determine difficulty from description + let difficulty: "easy" | "medium" | "hard" | null = null; + const desc = act.description.toLowerCase(); + if (desc.includes("easy")) difficulty = "easy"; + else if (desc.includes("medium")) difficulty = "medium"; + else if (desc.includes("hard")) difficulty = "hard"; + + if (!difficulty) continue; + + const key = `${act.exerciseType}:${difficulty}`; + const existing = bestMap.get(key); + + if (!existing) { + // First entry — activities are ordered by durationSecs asc, so this + // is guaranteed to be the fastest for this key. + bestMap.set(key, { + bestSecs: act.durationSecs!, + solveCount: 1, + achievedAt: act.createdAt, + }); + } else { + // Accumulate solve count; bestSecs is already the minimum (first entry). + existing.solveCount += 1; + } + } + + // Build ordered response: exercise types in display order, then easy→medium→hard. + const records: PersonalBestRecord[] = []; + + for (const exerciseType of LOGIC_EXERCISE_TYPES) { + for (const difficulty of DIFFICULTIES) { + const key = `${exerciseType}:${difficulty}`; + const entry = bestMap.get(key); + if (!entry) continue; + + records.push({ + exerciseType, + exerciseLabel: EXERCISE_LABELS[exerciseType] ?? exerciseType, + difficulty, + bestSecs: entry.bestSecs, + solveCount: entry.solveCount, + achievedAt: entry.achievedAt.toISOString(), + }); + } + } + + return NextResponse.json({ records } satisfies PersonalBestsResponse); +}); diff --git a/src/app/api/stats/route.ts b/src/app/api/stats/route.ts new file mode 100644 index 0000000000000000000000000000000000000000..c921502b221506551b0a62aaa1672dbf5104289c --- /dev/null +++ b/src/app/api/stats/route.ts @@ -0,0 +1,225 @@ +import { NextRequest, NextResponse } from "next/server"; +import { prisma } from "@/lib/db"; +import { withApiError } from "@/lib/api-error"; + +/** Valid time windows for the XP chart (in days). */ +const VALID_WINDOWS = [7, 30, 90] as const; +type ChartWindow = (typeof VALID_WINDOWS)[number]; + +function parseWindowDays(raw: string | null): ChartWindow { + const n = parseInt(raw ?? "", 10); + return (VALID_WINDOWS as readonly number[]).includes(n) + ? (n as ChartWindow) + : 30; +} + +/** Maximum number of activities returned per page. */ +const MAX_ACTIVITY_LIMIT = 50; +/** Default number of activities returned per page. */ +const DEFAULT_ACTIVITY_LIMIT = 25; + +/** Valid category values for filtering. */ +const VALID_CATEGORIES = new Set([ + "chess", + "reading", + "feynman", + "logic", + "critical-thinking", + "quests", +]); + +function parseActivityPagination( + rawOffset: string | null, + rawLimit: string | null, +): { offset: number; limit: number } { + const offset = Math.max(0, parseInt(rawOffset ?? "0", 10) || 0); + const parsed = parseInt(rawLimit ?? String(DEFAULT_ACTIVITY_LIMIT), 10); + const limit = Number.isFinite(parsed) && parsed > 0 + ? Math.min(parsed, MAX_ACTIVITY_LIMIT) + : DEFAULT_ACTIVITY_LIMIT; + return { offset, limit }; +} + +/** + * Parse the ?activityCategory query param. + * Returns the category string if valid, or null for "all" / invalid values. + */ +function parseActivityCategory(raw: string | null): string | null { + if (!raw || raw === "all") return null; + return VALID_CATEGORIES.has(raw) ? raw : null; +} + +/** + * GET /api/stats + * + * Returns aggregated stats for the Stats page: + * - dailyXp: XP earned per day (configurable window: 7, 30, or 90 days; default 30) + * - windowDays: the resolved time window used for dailyXp + * - categoryBreakdown: total XP and exercise count per category + * - recentActivities: paginated activity slice (default first 25) + * - activityTotal: total number of activities across all time (for pagination) + * - summary: overall totals + * + * Query params: + * ?days=7|30|90 — chart time window (default: 30; invalid values fall back to 30) + * ?activityOffset=N — skip N activities (default: 0) + * ?activityLimit=N — return up to N activities (default: 25; max: 50) + * ?activityCategory= — filter activity log to one category (default: all) + * valid values: chess, reading, feynman, logic, critical-thinking, quests + * "all" or missing/invalid values → no filter applied + */ +export const GET = withApiError(async (request: NextRequest) => { + const { searchParams } = new URL(request.url); + const windowDays = parseWindowDays(searchParams.get("days")); + const { offset: activityOffset, limit: activityLimit } = + parseActivityPagination( + searchParams.get("activityOffset"), + searchParams.get("activityLimit"), + ); + const activityCategory = parseActivityCategory(searchParams.get("activityCategory")); + + const user = await prisma.user.findFirst({ + where: { id: 1 }, + include: { categorySkills: true }, + }); + + if (!user) { + return NextResponse.json({ error: "No user found", status: 404 }, { status: 404 }); + } + + // Daily logs for the selected window + const windowStart = new Date(); + windowStart.setUTCDate(windowStart.getUTCDate() - windowDays); + windowStart.setUTCHours(0, 0, 0, 0); + + const dailyLogs = await prisma.dailyLog.findMany({ + where: { + userId: 1, + date: { gte: windowStart }, + }, + orderBy: { date: "asc" }, + }); + + // All activities for category breakdown and summary stats + const allActivities = await prisma.activity.findMany({ + where: { userId: 1 }, + orderBy: { createdAt: "desc" }, + }); + + // Category breakdown + const categoryBreakdown: Record< + string, + { totalXp: number; count: number; avgScore: number; totalDuration: number } + > = {}; + // Track scored-activity counts separately to compute accurate averages + const categoryScoreCount: Record = {}; + + for (const a of allActivities) { + if (!categoryBreakdown[a.category]) { + categoryBreakdown[a.category] = { + totalXp: 0, + count: 0, + avgScore: 0, + totalDuration: 0, + }; + categoryScoreCount[a.category] = 0; + } + const cat = categoryBreakdown[a.category]; + cat.totalXp += a.totalXp; + cat.count += 1; + if (a.score !== null) { + cat.avgScore += a.score; + categoryScoreCount[a.category] += 1; + } + if (a.durationSecs !== null) cat.totalDuration += a.durationSecs; + } + + // Compute averages — divide by number of scored activities, not total count + for (const [category, cat] of Object.entries(categoryBreakdown)) { + const scoredCount = categoryScoreCount[category] ?? 0; + if (scoredCount > 0) { + cat.avgScore = Math.round((cat.avgScore / scoredCount) * 100) / 100; + } else { + cat.avgScore = 0; + } + } + + // Filtered activity pool for the log (category breakdown and summary use full allActivities) + const filteredActivities = activityCategory + ? allActivities.filter( + (a) => a.category.toLowerCase() === activityCategory, + ) + : allActivities; + + // Paginated activity slice (from filtered pool) + const activityTotal = filteredActivities.length; + const recentActivities = filteredActivities + .slice(activityOffset, activityOffset + activityLimit) + .map((a) => ({ + id: a.id, + category: a.category, + exerciseType: a.exerciseType, + description: a.description, + baseXp: a.baseXp, + qualityBonus: a.qualityBonus, + isCriticalHit: a.isCriticalHit, + totalXp: a.totalXp, + score: a.score, + durationSecs: a.durationSecs, + createdAt: a.createdAt, + })); + + // Summary stats + const totalExercises = allActivities.length; + const totalXpEarned = allActivities.reduce((sum, a) => sum + a.totalXp, 0); + const totalDuration = allActivities.reduce( + (sum, a) => sum + (a.durationSecs ?? 0), + 0 + ); + const criticalHits = allActivities.filter((a) => a.isCriticalHit).length; + const goalDaysMet = dailyLogs.filter((l) => l.goalMet).length; + + // Correct solves: activities with a non-null score > 0 + const correctSolves = allActivities.filter( + (a) => a.score !== null && a.score > 0, + ).length; + // Scored exercises: activities that have any score (null excluded) + const scoredExercises = allActivities.filter((a) => a.score !== null).length; + const correctSolveRate = + scoredExercises > 0 + ? Math.round((correctSolves / scoredExercises) * 1000) / 10 + : 0; + + return NextResponse.json({ + windowDays, + /** The active activity category filter. null means "all categories". */ + activityCategory: activityCategory ?? null, + dailyXp: dailyLogs.map( + (l: { date: Date; xpEarned: number; activityCount: number; goalMet: boolean }) => ({ + date: l.date, + xpEarned: l.xpEarned, + activityCount: l.activityCount, + goalMet: l.goalMet, + }) + ), + categoryBreakdown, + recentActivities, + activityTotal, + summary: { + totalExercises, + totalXpEarned, + totalDuration, + criticalHits, + criticalHitRate: + totalExercises > 0 + ? Math.round((criticalHits / totalExercises) * 1000) / 10 + : 0, + correctSolves, + correctSolveRate, + goalDaysMet, + currentStreak: user.streak, + longestStreak: user.longestStreak, + level: user.level, + }, + }); +}); diff --git a/src/app/chess/error.tsx b/src/app/chess/error.tsx new file mode 100644 index 0000000000000000000000000000000000000000..1ed1702d7fa5f6106ca9a503493ae540ee92842a --- /dev/null +++ b/src/app/chess/error.tsx @@ -0,0 +1,20 @@ +"use client"; + +import { ExerciseError } from "@/components/shared/exercise-error"; + +export default function ChessError({ + error, + reset, +}: { + error: Error & { digest?: string }; + reset: () => void; +}) { + return ( + + ); +} diff --git a/src/app/chess/page.tsx b/src/app/chess/page.tsx new file mode 100644 index 0000000000000000000000000000000000000000..8bb3cd22473c261842e0e1be15eff90f6a2daf4d --- /dev/null +++ b/src/app/chess/page.tsx @@ -0,0 +1,1056 @@ +"use client"; + +import { useState, useCallback, useEffect, useRef } from "react"; +import { motion, AnimatePresence } from "framer-motion"; +import { + Loader2, + Trophy, + Zap, + RotateCcw, + CalendarDays, + Shuffle, + Swords, + ExternalLink, + CheckCircle2, + MinusCircle, + XCircle, +} from "lucide-react"; +import { Button } from "@/components/ui/button"; +import { PuzzleBoard } from "@/components/chess/puzzle-board"; +import { XpResults } from "@/components/shared/xp-results"; +import { LevelUpOverlay } from "@/components/shared/level-up"; +import { SkillUnlockToast } from "@/components/shared/skill-unlock-toast"; +import { + apiClient, + ApiClientError, + type ChessGameResult, +} from "@/lib/api-client"; + +// --------------------------------------------------------------------------- +// Constants +// --------------------------------------------------------------------------- + +const CHESS_COLOR = "#f59e0b"; // amber-400 + +const STOCKFISH_LEVELS = [ + { level: 1, label: "Level 1", sublabel: "Beginner" }, + { level: 2, label: "Level 2", sublabel: "Casual" }, + { level: 3, label: "Level 3", sublabel: "Amateur" }, + { level: 4, label: "Level 4", sublabel: "Club" }, + { level: 5, label: "Level 5", sublabel: "Advanced" }, + { level: 6, label: "Level 6", sublabel: "Expert" }, + { level: 7, label: "Level 7", sublabel: "Master" }, + { level: 8, label: "Level 8", sublabel: "Maximum" }, +] as const; + +// --------------------------------------------------------------------------- +// Types +// --------------------------------------------------------------------------- + +interface PuzzlePayload { + id: string; + fen: string; + pgn: string; + solution: string[]; + rating: number; + themes: string[]; + plays: number; + gameUrl: string; +} + +interface SubmitResult { + solved: boolean; + qualityScore: number; + xp: { + totalXp: number; + baseXp: number; + qualityBonus: number; + isCriticalHit: boolean; + multiplierBonus?: number; + multiplierPercent?: number; + }; + levelUp: boolean; + newLevel: number; + categoryXp: { currentXp: number; xpToNext: number; level: number; levelUp: boolean }; + newTitle?: string; + unlocks?: string[]; + streakFreezesGranted?: number; +} + +interface GameResultData { + result: ChessGameResult; + level: number; + qualityScore: number; + xp: { + totalXp: number; + baseXp: number; + qualityBonus: number; + isCriticalHit: boolean; + multiplierBonus?: number; + multiplierPercent?: number; + }; + levelUp: boolean; + newLevel: number; + categoryXp: { currentXp: number; xpToNext: number; level: number; levelUp: boolean }; + newTitle?: string; + unlocks?: string[]; + streakFreezesGranted?: number; +} + +type UIState = + | "idle" + | "loading" + | "playing" + | "submitting" + | "results" + | "bot-select" + | "bot-launching" + | "bot-playing" + | "bot-submitting" + | "bot-results"; + +// --------------------------------------------------------------------------- +// Helpers +// --------------------------------------------------------------------------- + +function difficultyFromRating(rating: number): string { + if (rating < 1200) return "Beginner"; + if (rating < 1500) return "Intermediate"; + if (rating < 1800) return "Advanced"; + if (rating < 2100) return "Expert"; + return "Master"; +} + +const RESULT_ICONS: Record = { + win: , + draw: , + loss: , +}; + +const RESULT_LABELS: Record = { + win: "Victory! 🎉", + draw: "Draw — well fought", + loss: "Defeat — keep going", +}; + +// --------------------------------------------------------------------------- +// Page Component +// --------------------------------------------------------------------------- + +export default function ChessPage() { + const [uiState, setUiState] = useState("idle"); + const [puzzle, setPuzzle] = useState(null); + const [result, setResult] = useState(null); + const [error, setError] = useState(null); + const [isDaily, setIsDaily] = useState(false); + const [showLevelUp, setShowLevelUp] = useState(false); + + // Timing ref — set when puzzle board becomes active, used on submit + const puzzleStartRef = useRef(null); + + // Bot-game state + const [botLevel, setBotLevel] = useState(4); + const [botGameId, setBotGameId] = useState(null); + const [botGameUrl, setBotGameUrl] = useState(null); + const [botGameResult, setBotGameResult] = useState(null); + const [botSubmitting, setBotSubmitting] = useState(false); + + const [difficultyHint, setDifficultyHint] = useState(null); + + useEffect(() => { + apiClient.getCoachDifficulty() + .then((data) => { + const rec = data.recommendations?.chess; + if (rec?.boost !== undefined && rec.difficulty) setDifficultyHint(rec.difficulty); + }) + .catch(() => {}); + }, []); + + // --------------------------------------------------------------------------- + // Puzzle flow + // --------------------------------------------------------------------------- + + const fetchPuzzle = useCallback(async (daily: boolean) => { + setUiState("loading"); + setError(null); + setIsDaily(daily); + try { + const data = await apiClient.getChessPuzzle({ daily }); + setPuzzle(data as unknown as PuzzlePayload); + setResult(null); + puzzleStartRef.current = Date.now(); + setUiState("playing"); + } catch (err) { + setError( + err instanceof ApiClientError + ? ((err.body as { error?: string })?.error ?? `HTTP ${err.status}`) + : err instanceof Error + ? err.message + : "Failed to load puzzle", + ); + setUiState("idle"); + } + }, []); + + const doSubmit = useCallback( + async (solved: boolean, extraMoves: number) => { + if (!puzzle) return; + setUiState("submitting"); + const totalMoves = puzzle.solution.length + extraMoves; + const durationSecs = + puzzleStartRef.current !== null + ? Math.round((Date.now() - puzzleStartRef.current) / 1000) + : undefined; + try { + const data = await apiClient.submitChessPuzzle({ + puzzleId: puzzle.id, + puzzleRating: puzzle.rating, + solved, + movesPlayed: totalMoves, + solutionLen: puzzle.solution.length, + durationSecs, + }); + setResult(data as unknown as SubmitResult); + setShowLevelUp((data as unknown as SubmitResult).categoryXp?.levelUp ?? false); + setUiState("results"); + } catch (err) { + setError( + err instanceof ApiClientError + ? ((err.body as { error?: string })?.error ?? `HTTP ${err.status}`) + : err instanceof Error + ? err.message + : "Failed to submit result", + ); + setResult(null); + setUiState("results"); + } + }, + [puzzle], + ); + + const handleSolved = useCallback((extraMoves: number) => doSubmit(true, extraMoves), [doSubmit]); + const handleGiveUp = useCallback(() => doSubmit(false, 0), [doSubmit]); + + // --------------------------------------------------------------------------- + // Bot flow + // --------------------------------------------------------------------------- + + const launchBotGame = useCallback(async () => { + setUiState("bot-launching"); + setError(null); + try { + const data = await apiClient.createStockfishChallenge({ level: botLevel }); + setBotGameId(data.gameId); + setBotGameUrl(data.gameUrl); + setUiState("bot-playing"); + // Open game on Lichess + window.open(data.gameUrl, "_blank", "noopener,noreferrer"); + } catch (err) { + setError( + err instanceof ApiClientError + ? ((err.body as { error?: string })?.error ?? `HTTP ${err.status}`) + : err instanceof Error + ? err.message + : "Failed to create Stockfish challenge", + ); + setUiState("bot-select"); + } + }, [botLevel]); + + const submitBotResult = useCallback(async (gameResult: ChessGameResult) => { + if (!botGameId) return; + setBotSubmitting(true); + setUiState("bot-submitting"); + try { + const data = await apiClient.submitChessGameResult({ + gameId: botGameId, + level: botLevel, + result: gameResult, + }); + setBotGameResult(data as unknown as GameResultData); + setShowLevelUp((data as unknown as GameResultData).categoryXp?.levelUp ?? false); + setBotSubmitting(false); + setUiState("bot-results"); + } catch (err) { + setError( + err instanceof ApiClientError + ? ((err.body as { error?: string })?.error ?? `HTTP ${err.status}`) + : err instanceof Error + ? err.message + : "Failed to record game result", + ); + setBotGameResult(null); + setBotSubmitting(false); + setUiState("bot-results"); + } + }, [botGameId, botLevel]); + + const resetToIdle = useCallback(() => { + setPuzzle(null); + setResult(null); + setBotGameId(null); + setBotGameUrl(null); + setBotGameResult(null); + setBotSubmitting(false); + setError(null); + setShowLevelUp(false); + setUiState("idle"); + }, []); + + // --------------------------------------------------------------------------- + // Render + // --------------------------------------------------------------------------- + + return ( +
+ {/* Header */} +
+

+ Chess +

+

+ Sharpen your mind with Lichess puzzles or challenge Stockfish. +

+ {difficultyHint && ( +

+ 📊 Recommended: {difficultyHint.charAt(0).toUpperCase() + difficultyHint.slice(1)} +

+ )} +
+ + + + {/* ----------------------------------------------------------------- */} + {/* IDLE — mode picker */} + {/* ----------------------------------------------------------------- */} + {uiState === "idle" && ( + + {error && ( + + {error} + + )} + + {/* Puzzles card */} +
+
+
+ ♟ +
+
+

+ Tactical Puzzles +

+

+ Find the best move sequence • 20–40 XP +

+
+
+
+ + +
+
+ + {/* Bot game card */} +
+
+
+ +
+
+

+ Play vs Stockfish +

+

+ Challenge the bot on Lichess • 30–60 XP +

+
+
+ +
+
+ )} + + {/* ----------------------------------------------------------------- */} + {/* PUZZLE LOADING */} + {/* ----------------------------------------------------------------- */} + {uiState === "loading" && ( + + +

+ {isDaily ? "Fetching today's daily puzzle…" : "Fetching a random puzzle…"} +

+
+ )} + + {/* ----------------------------------------------------------------- */} + {/* PUZZLE PLAYING / SUBMITTING */} + {/* ----------------------------------------------------------------- */} + {(uiState === "playing" || uiState === "submitting") && puzzle && ( + +
+
+ ♟ +
+

+ {isDaily ? "Daily Puzzle" : "Tactical Puzzle"} +

+

+ {difficultyFromRating(puzzle.rating)} · ID: {puzzle.id} +

+
+
+ +
+ +
+ +
+ + {uiState === "submitting" && ( +
+
+ + Calculating XP… +
+
+ )} + +

+ Puzzle sourced from{" "} + + Lichess + +

+
+ )} + + {/* ----------------------------------------------------------------- */} + {/* PUZZLE RESULTS */} + {/* ----------------------------------------------------------------- */} + {uiState === "results" && puzzle && ( + +
+ + + + +
+

+ {result?.xp.isCriticalHit + ? "⚡ CRITICAL HIT!" + : result?.solved + ? "Puzzle Solved!" + : "Puzzle Abandoned"} +

+

+ {difficultyFromRating(puzzle.rating)} · Rating {puzzle.rating} +

+
+ + {result?.levelUp && ( + + Level Up! → Lv.{result.newLevel} + + )} + + {puzzle.themes.length > 0 && ( +
+ Themes: + {puzzle.themes.slice(0, 4).map((t) => ( + + {t} + + ))} +
+ )} + + {error && !result && ( +

XP not saved: {error}

+ )} +
+ + {result && ( + fetchPuzzle(false)} + nextLabel="New Puzzle" + > +
+ + +
+
+ )} + + {result?.unlocks && result.unlocks.length > 0 && ( + + )} + + setShowLevelUp(false)} + /> +
+ )} + + {/* ----------------------------------------------------------------- */} + {/* BOT SELECT — level picker */} + {/* ----------------------------------------------------------------- */} + {uiState === "bot-select" && ( + +
+
+

+ Choose Difficulty +

+

+ Stockfish Level 1–8 · Played on Lichess +

+
+ +
+ + {error && ( +

+ {error} +

+ )} + + {/* Level grid */} +
+ {STOCKFISH_LEVELS.map(({ level, sublabel }) => { + const selected = botLevel === level; + return ( + + ); + })} +
+ + {/* XP preview */} +
+
+
+ 30 +
+
base XP
+
+
+
+ +30 +
+
quality bonus
+
+
+
+ 2× +
+
critical hit
+
+
+ + +
+ )} + + {/* ----------------------------------------------------------------- */} + {/* BOT LAUNCHING */} + {/* ----------------------------------------------------------------- */} + {uiState === "bot-launching" && ( + + +

+ Creating Stockfish challenge on Lichess… +

+
+ )} + + {/* ----------------------------------------------------------------- */} + {/* BOT PLAYING — waiting for user to finish game on Lichess */} + {/* ----------------------------------------------------------------- */} + {uiState === "bot-playing" && ( + +
+ +
+ +
+

+ Game in Progress +

+

+ Your Stockfish Level {botLevel} game has opened on Lichess. + Play the game, then come back and report your result to earn XP. +

+
+ + {botGameUrl && ( + + + Open game on Lichess + + )} + + {/* Result reporting */} +
+

+ How did it go? +

+
+ + + +
+ +
+
+ )} + + {/* ----------------------------------------------------------------- */} + {/* BOT SUBMITTING */} + {/* ----------------------------------------------------------------- */} + {uiState === "bot-submitting" && ( + + +

+ Calculating XP… +

+
+ )} + + {/* ----------------------------------------------------------------- */} + {/* BOT RESULTS */} + {/* ----------------------------------------------------------------- */} + {uiState === "bot-results" && ( + +
+ + {botGameResult?.result + ? RESULT_ICONS[botGameResult.result] + : } + + +
+

+ {botGameResult?.xp?.isCriticalHit + ? "⚡ CRITICAL HIT!" + : botGameResult?.result + ? RESULT_LABELS[botGameResult.result] + : "Game Complete"} +

+

+ Stockfish Level {botGameResult?.level ?? botLevel} +

+
+ + {botGameResult?.levelUp && ( + + Level Up! → Lv.{botGameResult.newLevel} + + )} + + {error && !botGameResult && ( +

XP not saved: {error}

+ )} +
+ + {botGameResult && ( + setUiState("bot-select")} + nextLabel="Play Again" + > + + + )} + + {botGameResult?.unlocks && botGameResult.unlocks.length > 0 && ( + + )} + + setShowLevelUp(false)} + /> +
+ )} + +
+
+ ); +} diff --git a/src/app/coach/page.tsx b/src/app/coach/page.tsx new file mode 100644 index 0000000000000000000000000000000000000000..3396b0e64652035ababd9086c78900cc8d826a1b --- /dev/null +++ b/src/app/coach/page.tsx @@ -0,0 +1,1175 @@ +"use client"; + +import { useState, useEffect, useCallback } from "react"; +import { useRouter } from "next/navigation"; +import { motion, AnimatePresence } from "framer-motion"; +import { + Brain, + TrendingUp, + TrendingDown, + Minus, + Sparkles, + ArrowRight, + RefreshCw, + Zap, + Target, + Trophy, + AlertCircle, + ChevronDown, + ChevronUp, + FileBarChart, + CheckCircle, + Focus, +} from "lucide-react"; +import { + CATEGORY_LABELS, + CATEGORY_COLORS, + type Category, +} from "@/config/xp"; +import type { PerformanceSummary, CategoryPerformance, Trend } from "@/lib/performance"; +import type { DifficultyRecommendations } from "@/lib/difficulty"; +import type { CoachFeedback } from "@/lib/coach-feedback"; +import type { WeeklyReport } from "@/lib/weekly-report"; +import { apiClient, ApiClientError, type CoachWeeklyReportResponse } from "@/lib/api-client"; + +// ─── Types ──────────────────────────────────────────────────────────────────── + +interface WeeklyReportResponse extends WeeklyReport { + cached: boolean; +} + +interface WeeklyReportGateData { + activeDaysThisWeek: number; + requiredDays: number; +} + +interface CoachData { + performance: PerformanceSummary; + difficulty: DifficultyRecommendations; + feedback: CoachFeedback & { cached: boolean }; + weeklyReport: WeeklyReportResponse | null; + weeklyReportGate: WeeklyReportGateData | null; +} + +// ─── Route mapping ──────────────────────────────────────────────────────────── + +const CATEGORY_ROUTES: Record = { + chess: "/chess", + reading: "/reading", + feynman: "/feynman", + logic: "/logic", + "critical-thinking": "/critical-thinking", + quests: "/quests", + coding: "/coding", +}; + +// ─── Helpers ────────────────────────────────────────────────────────────────── + +function TrendIcon({ trend }: { trend: Trend }) { + switch (trend) { + case "improving": + return ; + case "declining": + return ; + case "stable": + return ; + case "new": + return ; + } +} + +function trendLabel(trend: Trend): string { + switch (trend) { + case "improving": + return "Improving"; + case "declining": + return "Declining"; + case "stable": + return "Stable"; + case "new": + return "New"; + } +} + +function difficultyColor(d: string): string { + switch (d) { + case "easy": + return "#10b981"; + case "medium": + return "#f59e0b"; + case "hard": + return "#f43f5e"; + default: + return "var(--text-secondary)"; + } +} + +// ─── Skeleton loader ────────────────────────────────────────────────────────── + +function SkeletonCard({ className = "" }: { className?: string }) { + return ( +
+
+
+
+
+
+
+
+ ); +} + +// ─── Sub-components ─────────────────────────────────────────────────────────── + +function CoachSaysCard({ + feedback, + encouragement, + cached, + onRefresh, + refreshing, +}: { + feedback: string; + encouragement: string; + cached: boolean; + onRefresh: () => void; + refreshing: boolean; +}) { + return ( + + {/* Accent gradient */} +
+ +
+
+
+ 🧠 +
+

+ Coach Says +

+
+ + +
+ +

+ {feedback} +

+ +
+ +

+ {encouragement} +

+
+ + {cached && ( +
+ Cached response · click refresh for new feedback +
+ )} + + ); +} + +function RecommendedNextCard({ + category, + difficulty, +}: { + category: Category; + difficulty: string; +}) { + const router = useRouter(); + const label = CATEGORY_LABELS[category] ?? category; + const color = CATEGORY_COLORS[category] ?? "#6366f1"; + const route = CATEGORY_ROUTES[category] ?? "/"; + + return ( + router.push(route)} + role="button" + tabIndex={0} + onKeyDown={(e) => { + if (e.key === "Enter" || e.key === " ") router.push(route); + }} + > + {/* Accent bar */} +
+ +
+ +

+ Recommended Next +

+
+ +
+
+
+ {label} +
+
+ + {difficulty} + +
+
+ +
+ +
+
+ + ); +} + +function StrengthsCard({ + categories, +}: { + categories: CategoryPerformance[]; +}) { + const strengths = categories + .filter((c) => c.attempts >= 3 && c.successRate >= 60) + .sort((a, b) => b.successRate - a.successRate) + .slice(0, 3); + + return ( + +
+ +

+ Your Strengths +

+
+ + {strengths.length === 0 ? ( +

+ Complete 3+ exercises in a category to see your strengths. +

+ ) : ( +
+ {strengths.map((cat) => { + const color = + CATEGORY_COLORS[cat.category] ?? "#6366f1"; + return ( +
+
+
+
+ + {cat.label} + +
+ + + {cat.successRate}% + +
+
+ {/* Progress bar */} +
+
+
+
+
+ ); + })} +
+ )} + + ); +} + +function FocusAreasCard({ + categories, + recommendations, +}: { + categories: CategoryPerformance[]; + recommendations: DifficultyRecommendations; +}) { + // Focus areas: categories with low success rate or declining trend, or unexplored ones + const focusAreas = categories + .filter( + (c) => + (c.attempts >= 3 && c.successRate < 60) || + (c.attempts >= 3 && c.trend === "declining"), + ) + .sort((a, b) => a.successRate - b.successRate) + .slice(0, 3); + + const unexplored = categories.filter((c) => c.attempts === 0); + + return ( + +
+ +

+ Focus Areas +

+
+ + {focusAreas.length === 0 && unexplored.length === 0 ? ( +

+ No weak spots detected — you're well-rounded! +

+ ) : ( +
+ {focusAreas.map((cat) => { + const color = CATEGORY_COLORS[cat.category] ?? "#6366f1"; + const rec = recommendations.recommendations[cat.category]; + return ( +
+
+
+
+
+ + {cat.label} + +
+ + + {cat.successRate}% + +
+
+ {rec && ( +
+ Next focus: {rec.nextSkill} +
+ )} +
+
+
+ ); + })} + + {unexplored.length > 0 && ( +
+ Unexplored:{" "} + {unexplored.map((c) => c.label).join(", ")} +
+ )} +
+ )} + + ); +} + +function PerformanceOverviewCard({ + performance, +}: { + performance: PerformanceSummary; +}) { + return ( + +
+ +

+ Performance Overview +

+
+ +
+ {[ + { + label: "Overall Score", + value: `${performance.overallScore}%`, + icon: "📊", + }, + { + label: "Streak", + value: `${performance.streakDays} day${performance.streakDays !== 1 ? "s" : ""}`, + icon: "🔥", + sub: `best: ${performance.longestStreak}`, + }, + { + label: "Exercises", + value: performance.totalExercises.toLocaleString(), + icon: "📚", + }, + { + label: "Active Days", + value: performance.activeDays.toLocaleString(), + icon: "📅", + }, + ].map(({ label, value, icon, sub }) => ( +
+
{icon}
+
+ {value} +
+
+ {label} +
+ {sub && ( +
+ {sub} +
+ )} +
+ ))} +
+ + {/* Category trend grid */} +
+
+ Category Trends +
+ {performance.categories + .filter((c) => c.attempts > 0) + .map((cat) => { + const color = CATEGORY_COLORS[cat.category] ?? "#6366f1"; + return ( +
+
+ + {cat.label} + +
+ + + {trendLabel(cat.trend)} + +
+ + Lv {cat.level} + +
+ ); + })} +
+ + ); +} + +// ─── Weekly Report ───────────────────────────────────────────────────────────── + +function WeeklyReportCard({ + report, + gate, +}: { + report: WeeklyReportResponse | null; + gate: WeeklyReportGateData | null; +}) { + const [expanded, setExpanded] = useState(false); + + // Not enough data — show progress toward the 3-day requirement + if (!report) { + const activeDays = gate?.activeDaysThisWeek ?? 0; + const requiredDays = gate?.requiredDays ?? 3; + const progressPct = Math.round((activeDays / requiredDays) * 100); + + return ( + +
+ +

+ Weekly Report +

+
+

+ Complete exercises on at least {requiredDays} different days this week to unlock + your weekly brain health report. +

+ {/* Progress bar toward the 3-day requirement */} +
+
+ This week's active days + 0 ? "var(--text-secondary)" : "var(--text-muted)", + }} + > + {activeDays} / {requiredDays} + +
+
+ = requiredDays ? "#10b981" : "#06b6d4" }} + initial={{ width: 0 }} + animate={{ width: `${progressPct}%` }} + transition={{ duration: 0.6, ease: "easeOut", delay: 0.4 }} + /> +
+ {activeDays > 0 && ( +

+ {requiredDays - activeDays} more day{requiredDays - activeDays === 1 ? "" : "s"} to go +

+ )} +
+
+ ); + } + + const { weekOverWeek } = report; + const xpUp = weekOverWeek.xpChange >= 0; + + return ( + + {/* Accent gradient */} +
+ + {/* Header — clickable to expand/collapse */} + + + {/* Summary — always visible */} +

+ {report.report} +

+ + {/* Week-over-week stat pills — always visible */} +
+
+ {xpUp ? : } + {weekOverWeek.xpChangePercent >= 0 ? "+" : ""} + {weekOverWeek.xpChangePercent}% XP +
+
+ {weekOverWeek.currentWeekExercises} exercises +
+
+ {weekOverWeek.currentWeekActiveDays} active days +
+
+ + {/* Expandable details */} + + {expanded && ( + +
+ {/* Highlights */} +
+
+ + + Highlights + +
+
    + {report.highlights.map((h, i) => ( +
  • + + {h} +
  • + ))} +
+
+ + {/* Areas to Focus */} +
+
+ + + Focus Next Week + +
+
    + {report.areasToFocus.map((a, i) => ( +
  • + + {a} +
  • + ))} +
+
+ + {/* Week-over-week detail grid */} +
+ {[ + { + label: "This Week", + xp: weekOverWeek.currentWeekXp, + exercises: weekOverWeek.currentWeekExercises, + days: weekOverWeek.currentWeekActiveDays, + }, + { + label: "Last Week", + xp: weekOverWeek.previousWeekXp, + exercises: weekOverWeek.previousWeekExercises, + days: weekOverWeek.previousWeekActiveDays, + }, + { + label: "Change", + xp: weekOverWeek.xpChange, + exercises: + weekOverWeek.currentWeekExercises - + weekOverWeek.previousWeekExercises, + days: + weekOverWeek.currentWeekActiveDays - + weekOverWeek.previousWeekActiveDays, + }, + ].map(({ label, xp, exercises, days }) => ( +
+
+ {label} +
+
+ {label === "Change" && xp >= 0 ? "+" : ""} + {xp.toLocaleString()} XP +
+
+ {label === "Change" && exercises >= 0 ? "+" : ""} + {exercises} exercises +
+
+ {label === "Change" && days >= 0 ? "+" : ""} + {days} days +
+
+ ))} +
+ +
+ Generated{" "} + {new Date(report.generatedAt).toLocaleDateString(undefined, { + weekday: "short", + month: "short", + day: "numeric", + hour: "numeric", + minute: "2-digit", + })} +
+
+
+ )} +
+ + ); +} + +// ─── Main Page ──────────────────────────────────────────────────────────────── + +export default function CoachPage() { + const [data, setData] = useState(null); + const [loading, setLoading] = useState(true); + const [refreshing, setRefreshing] = useState(false); + const [error, setError] = useState(null); + + const loadAll = useCallback(async () => { + setError(null); + try { + const [performance, difficulty, feedbackResult, reportResult] = await Promise.allSettled([ + apiClient.getCoachPerformance(), + apiClient.getCoachDifficulty(), + apiClient.getCoachFeedback(), + apiClient.getWeeklyReport(), + ]); + + if (performance.status === "rejected") { + throw new Error( + performance.reason instanceof ApiClientError + ? `Performance API failed (${performance.reason.status})` + : "Performance API failed", + ); + } + if (difficulty.status === "rejected") { + throw new Error( + difficulty.reason instanceof ApiClientError + ? `Difficulty API failed (${difficulty.reason.status})` + : "Difficulty API failed", + ); + } + + let feedback: CoachFeedback & { cached: boolean }; + if (feedbackResult.status === "fulfilled") { + feedback = feedbackResult.value as CoachFeedback & { cached: boolean }; + } else { + // Feedback may fail if no API key — use fallback + feedback = { + feedback: + "I can't generate personalized feedback right now (API key not configured). Try some exercises and check back later!", + recommendedExercise: { category: "logic" as Category, difficulty: "medium" }, + encouragement: "Every exercise counts — get started and I'll be here when you come back.", + cached: false, + }; + } + + // Weekly report: may be unavailable if not enough data + let weeklyReport: WeeklyReportResponse | null = null; + let weeklyReportGate: WeeklyReportGateData | null = null; + if (reportResult.status === "fulfilled") { + const reportData = reportResult.value as CoachWeeklyReportResponse; + // Route returns { hasReport: false, ... } when not enough activity + if ("hasReport" in reportData && reportData.hasReport === false) { + weeklyReportGate = { + activeDaysThisWeek: reportData.activeDaysThisWeek, + requiredDays: reportData.requiredDays, + }; + } else { + weeklyReport = reportData as WeeklyReportResponse; + } + } + + setData({ + performance: performance.value as PerformanceSummary, + difficulty: difficulty.value as unknown as DifficultyRecommendations, + feedback, + weeklyReport, + weeklyReportGate, + }); + } catch (e) { + setError(e instanceof Error ? e.message : "Failed to load coach data"); + } + }, []); + + const refreshFeedback = useCallback(async () => { + if (!data) return; + setRefreshing(true); + try { + const feedback = await apiClient.getCoachFeedback({ override: true }); + setData((prev) => (prev ? { ...prev, feedback: feedback as CoachFeedback & { cached: boolean } } : prev)); + } catch { + // silently fail, keep existing feedback + } finally { + setRefreshing(false); + } + }, [data]); + + useEffect(() => { + setLoading(true); + loadAll().finally(() => setLoading(false)); + }, [loadAll]); + + // Loading state + if (loading) { + return ( +
+
+ +
+

+ Active Coach +

+

+ Analyzing your performance… +

+
+
+ +
+ + +
+ +
+ ); + } + + // Error state + if (error || !data) { + return ( +
+
+ +

Coach Unavailable

+

+ {error ?? "No data available"} +

+ +
+
+ ); + } + + const { performance, difficulty, feedback, weeklyReport, weeklyReportGate } = data; + + return ( +
+ {/* Header */} + +
+ 🧠 +
+
+

+ Active Coach +

+

+ Personalized guidance based on your training data. +

+
+
+ + {/* Coach Says — full width */} + + + {/* Recommended Next — full width */} + + + {/* Strengths + Focus Areas — side by side on desktop */} +
+ + +
+ + {/* Performance Overview — full width */} + + + {/* Weekly Report — expandable */} + +
+ ); +} diff --git a/src/app/coding/page.tsx b/src/app/coding/page.tsx new file mode 100644 index 0000000000000000000000000000000000000000..cd495dbb92d6a52447d273c5bba966805ff8e222 --- /dev/null +++ b/src/app/coding/page.tsx @@ -0,0 +1,254 @@ +"use client"; + +import { useState } from "react"; +import { useRouter } from "next/navigation"; +import { motion } from "framer-motion"; +import { + Code2, + Bug, + ScanSearch, + Building2, + Loader2, + ArrowRight, +} from "lucide-react"; +import { + Select, + SelectContent, + SelectItem, + SelectTrigger, + SelectValue, +} from "@/components/ui/select"; +import { Button } from "@/components/ui/button"; +import { + apiClient, + type CodingProblemType, + type CodingDifficulty, + type CodingLanguage, +} from "@/lib/api-client"; + +const CODING_COLOR = "var(--color-coding)"; + +const PROBLEM_TYPES: { + id: CodingProblemType; + label: string; + blurb: string; + icon: React.ReactNode; +}[] = [ + { + id: "code-creation", + label: "Code Creation", + blurb: "Write a function from scratch to pass a hidden test suite.", + icon: , + }, + { + id: "debugging", + label: "Complex Debugging", + blurb: "Find and fix the bug so all tests go green.", + icon: , + }, + { + id: "code-review", + label: "Code Review (AI output)", + blurb: "Review AI-generated code and identify its issues — there may be none.", + icon: , + }, + { + id: "architecture", + label: "Architecture Discussion", + blurb: "Reason about a system design question, graded against a rubric.", + icon: , + }, +]; + +const DIFFICULTY_LABELS: Record = { + easy: "Easy", + medium: "Medium", + hard: "Hard", +}; + +const LANGUAGES: { id: CodingLanguage; label: string }[] = [ + { id: "javascript", label: "JavaScript" }, + { id: "typescript", label: "TypeScript" }, + { id: "python", label: "Python" }, + { id: "go", label: "Go" }, +]; + +export default function CodingPage() { + const router = useRouter(); + const [type, setType] = useState("code-creation"); + const [difficulty, setDifficulty] = useState("easy"); + const [language, setLanguage] = useState("javascript"); + const [loading, setLoading] = useState(false); + const [error, setError] = useState(null); + + const isExecutable = type === "code-creation" || type === "debugging"; + const langExecutes = language === "javascript" || language === "typescript"; + + async function handleGenerate() { + setLoading(true); + setError(null); + try { + const res = await apiClient.generateCodingProblem({ type, difficulty, language }); + // Hand the generated problem to the problem page via sessionStorage. + sessionStorage.setItem("coding:problem", JSON.stringify(res)); + router.push("/coding/problem"); + } catch (e) { + setError( + e instanceof Error ? e.message : "Failed to generate a problem set. Please try again.", + ); + setLoading(false); + } + } + + return ( +
+
+
+ +
+
+

+ Coding Training +

+

+ Keep your engineering fundamentals sharp — write, debug, review, and design. +

+
+
+ + + {/* Problem type */} +
+ +
+ {PROBLEM_TYPES.map((t) => { + const active = type === t.id; + return ( + + ); + })} +
+
+ + {/* Difficulty + language */} +
+
+ + +
+ +
+ + +
+
+ + {isExecutable && !langExecutes && ( +

+ Live sandbox execution supports JavaScript & TypeScript. For {LANGUAGES.find((l) => l.id === language)?.label}, + you'll still get a problem but auto-grading requires an executable language. +

+ )} + + {error && ( +

+ {error} +

+ )} + + +
+
+ ); +} diff --git a/src/app/coding/problem/page.tsx b/src/app/coding/problem/page.tsx new file mode 100644 index 0000000000000000000000000000000000000000..c9a26c106cf6a5dfa89ef4b5580b840b00f876b1 --- /dev/null +++ b/src/app/coding/problem/page.tsx @@ -0,0 +1,444 @@ +"use client"; + +import { useEffect, useMemo, useRef, useState } from "react"; +import Link from "next/link"; +import { useRouter } from "next/navigation"; +import { motion } from "framer-motion"; +import { + Play, + Send, + Loader2, + CheckCircle2, + XCircle, + RotateCcw, + ArrowLeft, +} from "lucide-react"; +import { Button } from "@/components/ui/button"; +import { CodeBlock } from "@/components/coding/code-block"; +import { XpResults } from "@/components/shared/xp-results"; +import { LevelUpOverlay } from "@/components/shared/level-up"; +import { + apiClient, + type CodingGenerateResponse, + type CodingRunResponse, + type CodingSubmitCodeResponse, + type CodingSubmitWrittenResponse, + type CodingLanguage, +} from "@/lib/api-client"; + +const CODING_COLOR = "var(--color-coding)"; + +const TYPE_LABELS: Record = { + "code-creation": "Code Creation", + debugging: "Debugging", + "code-review": "Code Review", + architecture: "Architecture", +}; + +function Badge({ children }: { children: React.ReactNode }) { + return ( + + {children} + + ); +} + +export default function CodingProblemPage() { + const router = useRouter(); + const [data, setData] = useState(null); + const [missing, setMissing] = useState(false); + + const [code, setCode] = useState(""); + const [answer, setAnswer] = useState(""); + + const [running, setRunning] = useState(false); + const [runResult, setRunResult] = useState(null); + const [submittingCode, setSubmittingCode] = useState(false); + const [codeResult, setCodeResult] = useState(null); + const [submittingWritten, setSubmittingWritten] = useState(false); + const [writtenResult, setWrittenResult] = useState(null); + const [showLevelUp, setShowLevelUp] = useState(false); + const [error, setError] = useState(null); + + const startRef = useRef(0); + + useEffect(() => { + const raw = typeof window !== "undefined" ? sessionStorage.getItem("coding:problem") : null; + if (!raw) { + setMissing(true); + return; + } + try { + const parsed = JSON.parse(raw) as CodingGenerateResponse; + setData(parsed); + const p = parsed.problem; + setCode(p.buggyCode ?? p.starterCode ?? ""); + startRef.current = Date.now(); + } catch { + setMissing(true); + } + }, []); + + const problem = data?.problem; + const language = (problem?.language ?? "javascript") as CodingLanguage; + const isExecutable = + problem?.type === "code-creation" || problem?.type === "debugging"; + const isWritten = + problem?.type === "code-review" || problem?.type === "architecture"; + + const elapsed = () => Math.max(0, Math.round((Date.now() - startRef.current) / 1000)); + + async function handleRun() { + if (!data) return; + setRunning(true); + setError(null); + try { + const res = await apiClient.runCode(data.instanceId, code); + setRunResult(res); + } catch (e) { + setError(e instanceof Error ? e.message : "Run failed."); + } finally { + setRunning(false); + } + } + + async function handleSubmitCode() { + if (!data) return; + setSubmittingCode(true); + setError(null); + try { + const res = await apiClient.submitCode(data.instanceId, code, elapsed()); + setCodeResult(res); + if (res.awarded && res.categoryXp?.levelUp) setShowLevelUp(true); + } catch (e) { + setError(e instanceof Error ? e.message : "Submit failed."); + } finally { + setSubmittingCode(false); + } + } + + async function handleSubmitWritten() { + if (!data) return; + setSubmittingWritten(true); + setError(null); + try { + const res = await apiClient.submitWrittenAnswer(data.instanceId, answer, elapsed()); + setWrittenResult(res); + if (res.awarded && res.categoryXp?.levelUp) setShowLevelUp(true); + } catch (e) { + setError(e instanceof Error ? e.message : "Submit failed."); + } finally { + setSubmittingWritten(false); + } + } + + const runSummary = useMemo(() => { + if (!runResult) return null; + if (runResult.compileError) return { ok: false, text: runResult.compileError }; + return { + ok: runResult.allPassed, + text: `${runResult.passed}/${runResult.total} example tests passed`, + }; + }, [runResult]); + + if (missing) { + return ( +
+

+ No problem loaded. Generate one to get started. +

+ + + +
+ ); + } + + if (!problem) { + return ( +
+ +
+ ); + } + + return ( +
+ {/* Header */} +
+ + Back + +
+ {TYPE_LABELS[problem.type] ?? problem.type} + {problem.difficulty} + {problem.language} +
+
+ +
+

+ {problem.title} +

+

+ {problem.prompt} +

+
+ + {/* Code under review (read-only) */} + {problem.type === "code-review" && problem.code && ( + + )} + + {/* Example tests for executable problems */} + {isExecutable && problem.tests && problem.tests.length > 0 && ( +
+ Example tests:{" "} + {problem.tests.map((t, i) => ( + + {problem.entryFunction}({JSON.stringify(t.input).slice(1, -1)}) → {JSON.stringify(t.expected)} + {i < problem.tests!.length - 1 ? " · " : ""} + + ))} +
+ )} + + {/* Executable: editor + run + submit */} + {isExecutable && ( +
+ +